Spring integration program is working nicely, I want to add the ability to shutdown the app via a simple servlet request (will extend this ability with more functionality later).

I have followed this example (http://spring.io/blog/2011/01/04/green-beans-getting-started-with-spring-mvc/) and added the changes to my working integration copy, run the main app via intelliJ however my browser gives 'unable to connect', indeed the controller does not even get called.

netstat -ano | findstr 8080 returns nothing so I guess it's not connecting.

I'm a newbie to Spring and have looked but can't find what I am missing.

Any suggestions?
Thanks

Env: Spring 4, intelliJ, Windows 7, Java 8, integration working well with activeMQ simple send/receive.

I have a WebApi method with these attributes:

[HttpPost]
[Route(...)]
public void MyMethod(byte[] content)...

I have tried this, which causes an exception:

string ct = Request.Headers.GetValues("Account-Number").FirstOrDefault();

The exception is:
Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects

I therefore tried this.

string accountNumber = Request.Content.Headers.GetValues("Account-Number").First();

The value doesn't appear to exist. If I check the POST raw values using fiddler, I can see that the value is in fact being passed through.

Thanks

I am getting the following error;

This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.
For more information, see http://go.microsoft.com/fwlink/?LinkID=317567.

I have created a website using MVC4 and I updated the framework to 4.5.1.

Everything works perfectly in development phase. I have enabled the migration with entity framework code first and created a migration "Init".

I have simple membership. When I drop my local database and launch the application, I have all tables perfectly created.

Local database

However, when I deploy (FTP) on the production server, I only have a subset of tables.

Production database

This is what is done in Global.asax.cs after I tried this

internal void Application_Start()
        {
            MvcHandler.DisableMvcResponseHeader = true;
            Database.SetInitializer(
                new MigrateDatabaseToLatestVersion<GlobalDbContext, Migrations.Configuration>("DefaultConnection"));
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            using (var context = new GlobalDbContext())
            {
                if (!context.Database.Exists())
                {
                    // Register the SimpleMembership database without Entity Framework migration schema
                    //((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    context.Database.Create();
                }
                ////context.Database.Initialize(true);
                //context.Database.Delete();
                //context.Database.Create();

            }
            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "Username", autoCreateTables: true);
        }

Apparently, It's context.Database.Create(); that behaves differently in production.

I already have deployed a full MVC4 application and a full MVC5 application. But it is the first time I deploy a MVC4 application updated to .net 4.5.1 (I don't know if that helps).

Any idea?

I've a little known problem with PayPal integration. I am using REST API with ASP.NET MVC. Everything is right but I would like to disable (or hide) the shipping address.

I read everywhere that it isn't possible with REST API. Really ?!! Is there another way to do that ? If I pass "null" as ShippingAddress, the user can set his shipping address (not the good solution for my app).

Thank you all in advance!

I want to see all the errors of the ModelState in the Quick of visual studio without writing any codes like :

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        DoSomethingWith(error);
    }

i'm looking for somethink

ModelSate.Errors

Thanks.

I have installed WebDeploy on my IIS server to allow publishing of sites via TFS. On configuring web deploy for a particular site, which user account should I use?

Within the IIS tutorial, we are told to use a non-administrator Windows user, but the ASP.NET tutorial seems to show a generic user. By default, Web Deploy selects the server administrator, which surely can't be good:

Web deploy user

Should we create a new account and specify that username and password within TFS? Some blogs suggest doing this and setting the password to never expire. If so, which permissions need setting on which directories for our new user?

I see there is also a WDeployAdmin user which has been created during install. Is this relevant?

Having a difficult time with this one...

Everything worked 100% with XLS (I'm using NPOI on my ASP.NET app):

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

private MemoryStream ms = new MemoryStream();
private IWorkbook workbook;
private ISheet worksheet;
private byte[] buffer;

using (FileStream file = new FileStream(@"C:\template.xls", FileMode.Open, FileAccess.Read))
{
    workbook = new HSSFWorkbook(file);
}

worksheet = workbook.GetSheetAt(0);
worksheet.GetRow(11).GetCell(11).SetCellValue("hello"); // etc etc etc

workbook.Write(ms);
buffer = ms.ToArray();

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "application/vnd.ms-excel");
response.AddHeader("Content-Disposition", String.Format("attachment; filename=template.xls; size={0}", buffer.Length.ToString()));
response.BinaryWrite(buffer);
response.End();

Requirements have changed and the new Excel template uses features from XLSX, so it's now template.xlsx. I've been using NPOI 2.0 all along, and I've seen that it supports XLSX (using XSSF instead of HSSF). I changed the code like this (only showing the differences here - everything else is the same):

using NPOI.XSSF.UserModel;

using (FileStream file = new FileStream(@"C:\template.xlsx", FileMode.Open, FileAccess.Read))
{
    workbook = new XSSFWorkbook(file);
}

response.AddHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.AddHeader("Content-Disposition", String.Format("attachment; filename=template.xlsx; size={0}", buffer.Length.ToString()));

The exception gets thrown at the line workbook.Write(ms);:

System.NotImplementedException: The method or operation is not implemented.
   at NPOI.XSSF.UserModel.XSSFChartSheet.Write(Stream out1)
   at NPOI.XSSF.UserModel.XSSFSheet.Commit()
   at NPOI.POIXMLDocumentPart.OnSave(List`1 alreadySaved)
   at NPOI.POIXMLDocumentPart.OnSave(List`1 alreadySaved)
   at NPOI.POIXMLDocument.Write(Stream stream)

What could I be doing incorrectly?

edit: I've tried NPOI 2.1.1 Beta - same issue

I am building an intranet application using ASP.NET MVC 4 with Windows authentication. In the global.asax file, I have implemented this method:

protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs args)

In this method, I create a new ClaimsIdentity and set args.User to it, just like the example on MSDN. Later on in the application, in one of the Controllers, I need to get some data from the database. Since I already had an API action that does this, I call that API (synchronously) from my Controller.

The API gets the claims for the current user using the ApiController.User property. Here though, the claims are not the ones I set in global.asax. In fact, they are the claims that were in place on the user before this request.

The strange thing (to me) is that the next time I make a call to the application, the new claims are in place. So in my case, I change the claims that later on decide which buttons should be visible to a user, but only after the user makes another request to the application, these buttons are updated.

How can I make sure that the claims that I set in global.asax immediately take effect?

Extra info:

I don't set the claims on every request. When this method executes, I check a number of things to see if the user is still valid: cookie, user isn't anonymous, and user is still "valid". The latter is decided by cache - I keep a list of users that are still valid and if someone updates their permissions through a user interface, they become invalidated and will receive new claims in their next request.

I've attached a debugger and I see my code getting executed, the principal gets all the claims I want it to have while still in this method. When I reach a controller action, ApiController.User has the claims it had on the request before this one. When I make another request, the authentication method is skipped (because the user name is now in the cache), and in the controller the ApiController.User has the correct claims.

I have some Jauery function that goes like this

// Check if the userAgent contains "msie"
$(function(){
    if (navigator.userAgent.match(/Trident\/7\./)) {
       alert('IE');
    }
    else {
       alert('Not IE');
    }
});

What i need now is to add different js files to page when diferrent browser, combine Razor C# template engine something like this

// Check if the userAgent contains "msie"
$(function(){
   if (navigator.userAgent.match(/Trident\/7\./)) { 
      <script type="text/javascript" src="@Url.Content("~/timeline.js")"></script> 
   }
   else {
        @using (Script.Foot())
        { 
            <script type="text/javascript" src="@Url.Content("~/jquery.isotope.min.js")"></script> 
            <script type="text/javascript" src="@Url.Content("~/jquery.dpSocialTimeline.min.js")"></script> 
            <script type="text/javascript" src="@Url.Content("~/jquery.dpSocialTimeline.values.js")"></script> 
        }
   }    
});

Is it possible to combine razor C# and javascript, like this example i have show?

UPDATE Tried something like this, does not work :(

@using (Script.Foot())
{ 
<script>
// Check if the userAgent contains "msie"
$(function(){
    if (navigator.userAgent.match(/Trident\/7\./)) { 
        alert('This is IE');
        }
    else {   
        document.write('<script src="@Url.Content("~/jquery.isotope.min.js")"><\/script>');
        document.write('<script src="@Url.Content("~/jquery.dpSocialTimeline.min.js")"><\/script>');
        document.write('<script src="@Url.Content("~/Tjquery.dpSocialTimeline.values.js")"><\/script>');
}
});
</script>
}

I use MVC 5 razor and I'm new to this.

I want to only display the projects that the user created. In my table project there is a FK to User as User_id.

I've used the ApplicationUser model that is auto rendered at the start from a new project in MVC.

In my project controller:

private UserManager<ApplicationUser> manager;

public ProjectController()
{
    manager = new UserManager<ApplicationUser>(
        new UserStore<ApplicationUser>(db));
}

// GET: /Project/
[Authorize]
public ActionResult Index()
{
    var currentUser = manager.FindById(User.Identity.GetUserId());
    var proj = from p in db.Projects
               where p.User == currentUser
               select p;
    return View(db.Projects.ToList(proj));
}

The error.

Unable to create a constant value of type 'herexamen800.Models.ApplicationUser'. Only primitive types or enumeration types are supported in this context.

I am setting up a solution in umbraco using MVC seriously for the first time. I have managed to render a form using BeginUmbracoForm, and submit data, which works wonders.

My issue is, I want to implement a reset button, but since my data is in Session, I have to reset server side.

View:

@using (Html.BeginUmbracoForm<Site1.Controllers.SearchCriteriaSurfaceController>("Search"))
{
    @*Form here*@
    @Html.ActionLink("Reset criterias", "Reset", "SearchCriteriaSurface", new {}, null)
    <input class="btn btn-primary" type="submit" value="Search now" />
}

Controller:

public class SearchCriteriaSurfaceController : SurfaceController
    {
        [HttpPost]
        public ActionResult Search(SearchParams model)
        {
            SearchParams.Params = model;
            ViewBag.HasSought = true;
            return CurrentUmbracoPage();
        }

        [HttpPost]
        public ActionResult Reset()
        {
            SearchParams.ResetParams();
            return CurrentUmbracoPage();
        }
    }

On click, I then get redirected to /umbraco/Surface/SearchCriteriaSurface/Reset which is a resource that cannot be found.

Any idea how I go about reloading the page after hitting the reset button?

Thanks for your time.

I'm displaying a drop-down using bootstrap. The problem is the the style isn't being applied to the drop-down.

When I view the Source code it shows...

<div class="form-group">
    <label class="control-label col-md-2" for="State">State</label>
    <div class="col-md-10">
        <select htmlAttributes="{ class = form-control }" id="State" name="State"><option 
    value="CT">CT</option>

Why is the class form-control not being added to the select tag?

<div class="form-group">
    @Html.LabelFor(m => m.State, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.State, db.StateDiscountRates.Select(c => new SelectListItem { Value = c.State, Text = c.State }).ToList().OrderBy(c => c.Text)
                    .GroupBy(test => test.Text)
                          .Select(group => group.First()), new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
    </div>
</div>

Hey I use mvc 5 razor and I'm new to this.

I want to get the project id wat I put in the url e.g. /bug/create/4 (The number 4 stands for the id of the project.)

and save it in the bug table

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="BugID,Title,Description,AssigneeID,Priority,Status,Projects_ProjectID")] Bug bug, int id)
        {
            var currentUser = manager.FindById(User.Identity.GetUserId()); 
            // is empty in DB
            ViewBag.getIdFromUrlIsHere =id; 

            if (ModelState.IsValid)
            {
                bug.User = currentUser;

                // I get an error here
                bug.Projects = id;


                db.Bugs.Add(bug);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.AssigneeID = new SelectList(db.Users, "Id", "UserName", bug.AssigneeID);
            return View(bug);
        }

Can anyone help me?

The error I get is cannot converto to int if I change the int id in my parameter to string I get the same error

MY BUG TABLE

CREATE TABLE [dbo].[Bugs] (
[BugID]              INT            IDENTITY (1, 1) NOT NULL,
[Title]              NVARCHAR (50)  NOT NULL,
[Description]        NVARCHAR (MAX) NOT NULL,
[AssigneeID]         NVARCHAR (128) NULL,
[Priority]           NVARCHAR (MAX) NOT NULL,
[Status]             NVARCHAR (MAX) NOT NULL,
[ApplicationUser_Id] NVARCHAR (128) NULL,
[Projects_ProjectID] INT            NULL,
[User_Id]            NVARCHAR (128) NULL,
CONSTRAINT [PK_dbo.Bugs] PRIMARY KEY CLUSTERED ([BugID] ASC),
CONSTRAINT [FK_dbo.Bugs_dbo.AspNetUsers_ApplicationUser_Id] FOREIGN KEY ([ApplicationUser_Id]) REFERENCES [dbo].[AspNetUsers] ([Id]),
CONSTRAINT [FK_dbo.Bugs_dbo.Projects_Projects_ProjectID] FOREIGN KEY ([Projects_ProjectID]) REFERENCES [dbo].[Projects] ([ProjectID]),
CONSTRAINT [FK_dbo.Bugs_dbo.AspNetUsers_AssigneeID] FOREIGN KEY ([AssigneeID]) REFERENCES [dbo].[AspNetUsers] ([Id]),
CONSTRAINT [FK_dbo.Bugs_dbo.AspNetUsers_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[AspNetUsers] ([Id])

);

GO CREATE NONCLUSTERED INDEX [IX_ApplicationUser_Id] ON [dbo].[Bugs]([ApplicationUser_Id] ASC);

GO CREATE NONCLUSTERED INDEX [IX_Projects_ProjectID] ON [dbo].[Bugs]([Projects_ProjectID] ASC);

GO CREATE NONCLUSTERED INDEX [IX_AssigneeID] ON [dbo].[Bugs]([AssigneeID] ASC);

GO CREATE NONCLUSTERED INDEX [IX_User_Id] ON [dbo].[Bugs]([User_Id] ASC);

Currently I am working on an asp.net mvc 4 web application, and on the index views I have wrote the sorting & paging code manually , which gives me the ability to control how the paging and sorting works. so in my case if I have 10,000 records and the paging size is 50 then only the 50 records will be retrieved from the database, so my current approach can be considered extensible. But currently I am looking to use web grids because it can save me time and efforts. But I need to know if there are any web grids that have the following main features:-

  1. Provide Ajax-base sort, filter and paging

  2. All the sort, filter and paging need to be done on the database level.

  3. The ability for the users to change the number of records displayed, such as show me 100 records, 200 records , etc

  4. The ability to easily change the look and feel of the web grid.

So can anyone advice on available web grids that have the above 4 main features?

Thanks

hi i have two dropdowns.

  1. MasterModule(country)
  2. Submodule(state)

My expectation is to First select Master category(country) than select(state)..

Currently it is showing all states when i selec any of country.

I have following razor code

<div class="editor-label">
                @Html.LabelFor(model => model.MasterID, "Department")
            </div>
            <div class="editor-field">
                @Html.DropDownList("MasterID", String.Empty)
                @Html.ValidationMessageFor(model => model.MasterID)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.SubId, "Employee")
            </div>
            <div class="editor-field">
                @Html.DropDownList("SubId", String.Empty)
                @Html.ValidationMessageFor(model => model.SubId)
            </div>

any help how to acheive this?

Above code is simply binding the dropdown values to both , i want submodules dropdown shows only states of selected country. and always shows values only when i select the country

We are using MVC5 to build a responsive website. A developer who has joined the team has pointed out that we are adding markup to our cshtml pages to support the responsive design. He thought that really we should just be adding css classes to our elements and then letting the style sheet take care of the layout.

Currently we are adding to the cshtml class sections of code around controls like.

 <div class="row">
      <div class="form-group col-md-6">
            @Html.LabelFor(model => model.TypeId)
            @Html.EditorFor(model => model.TypeId)
            @Html.PeritoValidationMessageFor(model => model.TypeId)
      </div>
 </div>

I suppose my question is - If I want a responsive design do I need to add the divs or is there some way I can apply css classes to my controls instead?

We are going to stick with Bootstrap for the responsive design and would not change the current approach unless it was relatively straight forward to do.

Thanks

Jake

I have a view which allows editing of multiple address items concurrently. Binding of the text box works fine however the drop down list does not recognize the selected value.

My ViewModels are:

public class AddressesViewModel
{
    public List<AddressViewModel> Addresses { get; set; }
}

public class AddressViewModel
{
    public string Street { get; set; }
    public string StateSelected { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }

    public AddressViewModel()
    {
        this.States = new List<SelectListItem> { 
            new SelectListItem(),
            new SelectListItem { Text = "New Jersey", Value = "NJ"}, 
            new SelectListItem { Text = "New York", Value = "NY"}, 
            new SelectListItem { Text = "Pennsylvania", Value = "PA" },
            new SelectListItem { Text = "Rhode Island", Value = "RI" }
        };
    }
}

my controller action is:

public ActionResult Index()
{
    var addressesViewModel = new AddressesViewModel();
    addressesViewModel.Addresses = new List<AddressViewModel>() { 
        new AddressViewModel{
            Street = "some road", 
            StateSelected = "PA"
        },
        new AddressViewModel{
            Street = "some other road", 
            StateSelected = "NJ"
        }
   };

   return View(addressesViewModel);
}

and my view is:

@model HelloWorld.Models.AddressesViewModel


@for (int i = 0; i < Model.Addresses.Count(); i++)
{
    <div class="editor-label">
        @Html.LabelFor(modelItem => Model.Addresses[i].Street)
    </div>
    <div class="editor-field">
        @Html.EditorFor(modelItem => Model.Addresses[i].Street)
    </div>

    <div class="editor-label">
        @Html.LabelFor(modelItem => Model.Addresses[i].StateSelected)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(modelItem => Model.Addresses[i].StateSelected, Model.Addresses[i].States)
    </div>
}

I tested the view using a single item (bound to AddressViewModel) and it worked fine.

we have a solution converted to ASP MVC, which is growing bigger and bigger.

The problem now is: The startup of the application takes around 15+ seconds, because the application needs to pre-cache a lot of stuff from a database.

Now, in ASP MVC the problem is, every time we change something in a controller, the whole app is shut down and restartet, all the stuff in global.asax is executed again (as if the app comes from a "cold start"

Imagine: You write a simple if-condition, by accident you put in the wrong parameters -> you have to correct the if-condition. --> the WHOLE app is restartet.

So, we have to wait 15+ seconds every time we change even small things.

In old ASP.NET, you placed most of the code in .aspx-files which were just re-interpreted, but the whole app wasn't shut down etc.

Is there a work around for this? Like -lets call it- "interpreted controllers" instead of compiled controllers?

This ASP MVC behaviours makes it really annoying, the current workaround is to put as much stuff as possible into the views, which is bad practice - but hey, it helps us since we don't have to wait 15+ seconds until the controller is recompiled and the app restarted.

Any idea?

Regards

I have a table with a column with a check constraint:

[Gender] NCHAR (1) NULL 
CONSTRAINT [CHK_Employee_Gender] 
CHECK ([Gender]='F' OR [Gender]='M')

i.e. valid values are null, 'F', or 'M'.

I'm using entity framework database first to generate a model over this.

I've then got the standard scaffold generated CRUD forms over that model.

This has created a standard text field for this value (as expected; I'd be very (pleasantly) surprised if EF could infer to use a dropdown from the check constraints). i.e.

@Html.EditorFor(
    model => model.Gender
    , new { htmlAttributes = new { @class = "form-control" } }
)

I've amended this to:

@Html.DropDownListFor(
    model => model.Gender
    , new List<SelectListItem>
    {
        new SelectListItem{ Text = "Unspecified", Value = null }
        ,new SelectListItem{ Text = "Female", Value = "F" }
        ,new SelectListItem{ Text = "Male", Value = "M" }
    }
    , new { htmlAttributes = new { @class = "form-control" } }
)

Is there a recommended way to amend the code to provide a drop down for this field (the above fields a bit hacky/breaks the MVC separation of duties), or would the simple approach above be sufficient?

net mvc

If created my clas project, projectUser and user

I want to create a projectUser by selecting the id from project and the id from user both in a dropdownList

My projectUser controller

 // GET: /ProjectUser/Create
    public ActionResult Create()
    {
        ViewBag.UserID = new SelectList(db.Users, "Id", "UserName");
        ViewBag.ProjectID = new SelectList(db.Projects, "Id", "ProjectID");
        return View();
    }

    // POST: /ProjectUser/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="ProjectUserID")] ProjectUser projectuser)
    {
        if (ModelState.IsValid)
        {
            db.ProjectUsers.Add(projectuser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.UserID = new SelectList(db.Users, "Id", "UserName", projectuser.User.Id);
        ViewBag.ProjectID = new SelectList(db.Projects, "Id", "ProjectID", projectuser.Projects.ProjectID);
        return View(projectuser);
    }

My view

<div class="form-horizontal">
    <h4>ProjectUser</h4>
    <hr />
    @Html.ValidationSummary(true)
    <div class="form-group">
        @Html.LabelFor(model => model.Projects, "Kies project", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ProjectID", String.Empty)
            @Html.ValidationMessageFor(model => model.Projects)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.User, "Kies user", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Id", String.Empty)
            @Html.ValidationMessageFor(model => model.User)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>

my projectUser class

 public class ProjectUser
    {

        public int ProjectUserID { get; set; }
        public virtual ApplicationUser User { get; set; }
        public virtual Project Projects { get; set; }
    }