dimanche 10 mai 2015

Using [Authorize] on the GET and POST methods with same name

Maybe the answer to the following is simple, but I have hard time finding the answer:

When I have a GET method in a controller that is secured with the [Authorize] attribute, and a POST method (defined with [HttpPost]), will the same restrictions apply to it as well? Both methods have the same name, but differ in parameters.

Example code:

 [Authorize(Roles = "Administrator")]
 public ActionResult Delete()
 {
     return View();
 }

 [HttpPost]
 public ActionResult Delete(int id)
 {            
     /* the method's logic omitted */
     return RedirectToAction("Index");
 }

Using AddRange with Distinct() is not working with Enum in MVC5 C#

I am trying to filter one of my enum fields from my model. Here's the definition of my enum:

public enum ProjectDifficulty
{
    Medium,
    High,
    [Display(Name = "Very High")]
    VeryHigh,
    Complex
}

But I cannot get the results; I see this error:

Cannot convert from 'System.Linq.IQueryable<Finder.Models.ProjectDifficulty>' to 'System.Collections.Generic.IEnumerable<string>'

My controller contains this code:

var ProjectDifficultyLst = new List<string>();

var ProjectDifficultyQry = from b in db.Projects
                           orderby b.ProjectDifficulty
                           select b.ProjectDifficulty;

ProjectDifficultyLst.AddRange(ProjectDifficultyQry.Distinct());

ViewBag.projectDifficulty = new SelectList(ProjectDifficultyLst);

if (!String.IsNullOrEmpty(projectDifficulty))
{
    SearchQry = SearchQry.Where(l => l.ProjectDifficulty == projectDifficulty);
}

Update MVC from 4.0 to 5.2 - Could not install package

Im trying to update my project from MVC 4.0 to 5.2. But As soon I do that I get an error message:

Install-Package : Could not install package 'Microsoft.AspNet.Razor 3.2.3'. You are trying to install this packag e into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly referen ces or content files that are compatible with that framework. For more information, contact the package author. At line:1 char:1 + Install-Package Microsoft.AspNet.Mvc -Version 5.2.3 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

How can I Sovle this issue? And What does this mean?

Fully center a div inside a div with bootstrap and Visual Studio's shared layout

I am using Bootstrap and Visual Studio to make a portal webpage. I want a div centered on the page (with a background color). Then I want a div inside that div, again fully centered (this will be the login form).

Right now I'm using the grid system with 3 columns to get the middle of the page (horizontal centered). But the thing is that the first div isn't centered either.

Can someone explain me how to center a div horizontal and vertical, and then another div inside there fully centered.

I am using VS's shared layout, so where exactly do I need to put the Renderbody? In the first div or second div?

Thanks in advance.

Code I am currently using:

HTML of the shared layout:

<html xmlns="http://ift.tt/lH0Osb" style="height: 100%;">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>@ViewBag.Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../Content/themes/bootstrap.css">
    <link rel="stylesheet" href="../../Content/themes/stylesheet.css">
    <script src="http://ift.tt/1qRgvOJ"></script>
    <script src="http://ift.tt/1Cqnml8"></script>
</head>

<body style="height: 100%; background:#000;">
    @RenderBody()
</body>
</html>

The view file:

<div class="vertical-center" style="height:100%; background-color:aliceblue; background-position:center;background-repeat:no-repeat;">
    <div class="row">
        <div class="col-sm-4"></div>
        <div class="col-sm-4" style="background-color:lavenderblush;">
            @using (Html.BeginForm("Login", "Account"))
            {
                <span style="color:red">@ViewBag.Message</span>
                <fieldset class="vertical-center">
                    <ol>
                        <li>
                            @Html.TextBoxFor(m => m.Nickname)
                        </li>
                        <li>
                            @Html.PasswordFor(m => m.Password)
                        </li>
                    </ol>
                    <input type="submit" value="Log in" />
                </fieldset>
            }
        </div>
        <div class="col-sm-4"></div>
    </div>
</div>

And then the customized stylesheet.css:

.vertical-center {
  min-height: 100%;
  min-height: 100vh;
  display: flexbox;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
}

Linq in controller MVC

In my application I am using Entity Framework.I need to show all available rooms at the moment. I have two tables room and reservation . They are connected many to many from table RoomReservation.

public class Room
    {
public int Id { get; set; }
public double CostNight { get; set; }
public virtual ICollection<Reservation> Reservation { get; set; }
}

public class Reservation
    {
public int Id { get; set; }
public string DateOfEntry { get; set; }
public int NumberOfNights { get; set; }
public virtual ICollection<Room> Room { get; set; }
}

I tried to write:

public IEnumerable<Room> GetRooms(int title, DateTime? datepicker)
        {
            return context.Room.Where(x => x.Booking.Count == 0 ||
            x.Booking.All(b => b.DateOfEntry > datepicker || (b.DateOfEntry < DbFunctions.AddDays(datepicker, b.NumberOfNights))))
            .Where(x=>x.Categoryid == title);
        }

datepicker - date selected by the Client. title - category room(this i need too). DateOfEntry - date of arrival in the Room. But it does not work.

Also, if for example the client chose 2015-05-10 and book for 5 days, and the database is already have booked this number 2015-05-12 , need display a message..how to do it?Thanks!

the model in view could not bind to the action in the controller in ASP.NET MVC4

I have defined the custom name about the input tag in Index view of Account. The name is iptloginPassWord and iptloginPassWord. However, in the controller the model will be null whenever the submit button is clicked.

I have attached the code below. Is this a model binding issue? Could you guys help to determine what is wrong here?

View:

<div class="rl-modal-body">
    <div class="login-model-body-wrap">
        @using (Html.BeginForm("Logon", "Account", FormMethod.Post, new { id = "loginForm" }))
        {
            <div class="rlf-model-group">
                <div class="ipt-container">
                    <div class="ipt-config ipt-UserName"></div>
                    @*h5提供了required属性,Name的N必须为大写*@
                    @*<input id="iptloginUserName" type="text" name="iptloginUserName" value="" placeholder="请输入用户名" class="ipt ipt-login" required="required" />*@
                    @Html.TextBoxFor(model => model.UserName, new { @id = "iptloginUserName", @Name = "iptloginUserName", @placeholder = "请输入用户名", @class = "ipt ipt-login", @required = "required" })
                </div>
                <p class="rl-p"></p>
            </div>
            <div class="rlf-model-group">
                <div class="ipt-container">
                    <div class="ipt-config ipt-Password"></div>
                    @*<input id="iptloginPassWord" type="password" name="iptloginPassWord" value="" placeholder="请输入密码" class="ipt ipt-login ipt-passwordforJS" required="required" />*@
                    @Html.PasswordFor(model => model.Password, new { @id = "iptloginPassWord", @Name = "iptloginPassWord", @placeholder = "请输入密码", @class = "ipt ipt-login ipt-passwordforJS", @required = "required" })
                </div>
                <p class="rl-p"></p>
            </div>
            <div class="rlf-model-group">
                <label for="AutoLogin">
                    <input id="AutoLogin" type="checkbox" checked="checked" />自动登录
                </label>
            </div>
            <div class="rlf-model-group">
                <p class="rl-p"></p>
                <input id="iptloginsubmit" type="submit" name="Button" value="登录" class="btn-red btn-full" />
            </div>
        }
    </div>
</div>


Controller:
public class AccountController : Controller
{
    //
    // GET: /Account/

    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }

    [AllowAnonymous]
    [HttpPost]
    public ActionResult Logon(User model)
    {
        string username = model.UserName;//this will get null 
        string password = model.Password;//this will also get null
        return View(model);
    }
}

How to programaticaly enable/disable control in razor view [closed]

I need to enable/disable certain controls in the view depending on a condition. I try to use the answer in this link here but it did not work in my case. Currently I'm using the (pseudo) code as show below, which works, but it is insane to use it, since there are many entries like that. I need a solution like the one in here

@{ if (Model.ChargeCost == true)
 {
   @Html.TextBoxFor(m => m.Cost, new { @id="myId", @class = "form-control" })
 }
  else
 {
   @Html.TextBoxFor(m => m.Cost, new { @id = "myId", @class = "form-control", disabled = "disabled" })
}

UPDATE: I APOLOGIZE FOR THE MISUNDERSTANDING BUT THE CODE THAT I HAVE AS AN EXAMPLE WORKS PERFECTLY. WHAT I NEED IS SOMEONE WHO ACTUALLY HAS A DEEPER UNDERSTANDING OF MVC5 AND C# THAT CAN OPTIMIZE THIS TERRIBLE CODE, SINCE I HAVE MANY MORE CONDITIONS LIKE THIS ONE IN THE VIEW..

ASP.NET MVC5 EF6 Relation with ApplicationUser

[ForeignKey("Creator")]
public string CreatorID {get;set;}
public virtual ApplicationUser Creator {get;set;}

While update-database, errors appeared. Said there's no Key column for ApplicationUser, I've got information about modelBuilder, but I don't want to change anything inside the project and database, which project using Asp.net default authentication template and database column with AspNet prefix. Is there any ways to get there Thanks

Show live summation in Html Textbox helper

I'm trying to make a website using asp.net mvc 4 and jQuery 1.9.1 where user can get the summation automatically whenever typing to other textbox. But for some reason whenever I type to other textboxes I don't get any result in my Total textbox. Here are my codes,

<script>
    $(document).ready(function () {
        $('.toSum').each(function () {
            $(this).keyup(function () {
                var total = 0;
                $('.toSum').each(function () {
                    if (this.value.length != 0) {
                        total += parseInt(this.value);
                    }
                });
                $('#txtTotal').html(total);
            });
        });
    });
</script>
<div class="tab-pane" id="AddFl" style="padding-top: 10px; padding-left: 10px;">
            @using (Html.BeginForm("SumManager", "Home"))
            {
                @Html.ValidationSummary(true)
                <div class="editor-label">
                    <strong>Set Basic</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.basic, new { @class="toSum" })
                    @Html.ValidationMessageFor(a => a.Flats.basic)
                </div>
                <div class="editor-label">
                    <strong>Set Bill</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.bill, new { @class="toSum" })
                    @Html.ValidationMessageFor(a => a.Flats.bill)
                </div>
                <div class="editor-label">
                    <strong>Set Miscellaneous</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.misc, new { @class="toSum" })
                    @Html.ValidationMessageFor(a => a.Flats.misc)
                </div>
                <div class="editor-label">
                    <strong>Total</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.total, new { id="txtTotal"})
                    @Html.ValidationMessageFor(a => a.Flats.total)
                </div>                    
                <p><input type="submit" class="btn btn-info" value="Add" /></p>
            }
        </div>

Am I doing something wrong in my code? How can I get the summation result instantly whenever user types on other textboxes? Need this help badly. Tnx.

MVC 4 bundleconfig.cs files not including in layout.cshtml

BundleConfig.cs

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {

        bundles.Add(new StyleBundle("~/resources/css").Include("~/resources/css/reset.css", 
            "~/resources/css/style.css", "~/resources/css/invalid.css"));

        bundles.Add(new ScriptBundle("~/resources/scripts").Include("~/resources/scripts/jquery-1.3.2.min.js",

            "~/resources/scripts/simpla.jquery.configuration.js", "~/resources/scripts/facebox.js",
            "~/resources/scripts/jquery.wysiwyg.js"));
    }
}

Layout.cshtml

 @Styles.Render("~/resources/css")
 @Scripts.Render("~/resources/scripts")

What it renders in html

 <link href="/resources/css" rel="stylesheet"/>
<script src="/resources/scripts"></script>

Not including css and js file paths in html ??

Get DropDownListFor selected value in multiple model

I create multiple model

public class MultipleModel
{
    public Photo Photo { get; set; }
    public Room Room { get; set; }
}

for two different models:

public class Room
    {
        public int Id { get; set; }
        public string NumberRoom { get; set; }
        public virtual ICollection<Photo> Photo { get; set; }
    }
public class Photo
    {
        public int Id { get; set; }
        public string PhotoName { get; set; }
        public int Roomid { get; set; }
        public virtual Room Room { get; set; }
    }

On click Submit in my view i want upload image to the folder with the name from DropDownListFor selected item ( for example /images/2/, where 2=id from DropDownListFor) and add to database. How i can correctly send selected item from DropDownListFor using Html.BeginForm? My view:

@using Hotel.BusinessObject
@model MultipleModel
@using (Html.BeginForm("AddRoomImg", "Admin",
        FormMethod.Post, new { enctype = "multipart/form-data", id = Model.Room.Id}))
{
    <div>@Html.DropDownListFor(m=> m.Room.Id, ViewBag.roomlist as SelectList, "Select Room")</div>

    <input type="file" name="img" />
    <input type="submit" value="upload" />
}

And my controller, where Room.Id in formCollection is always=0 and int? id not works and return NULL

        public ActionResult AddRoomImg()
        {
            ViewBag.roomlist = new SelectList(db.Room, "Id", "NumberRoom");
            return View();
        }
        [HttpPost]
        public ActionResult AddRoomImg(FormCollection formCollection, int? id)
        {
            foreach (string item in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                if (file.ContentLength == 0)
                    continue;
                if (file.ContentLength > 0)
                {
                    ImageUpload imageUpload = new ImageUpload { Width = 600 };

                    ImageResult imageResult = imageUpload.RenameUploadFile(file);
                    if (imageResult.Success)
                    {
                        //TODO: write the filename to the db 
                    }
                    else
                    {
                        ViewBag.Error = imageResult.ErrorMessage;
                    }
                }
            }

Bind Images Only After Page Completely Load Like Flipcart

i need to bind all images only after page completely load, like flipcart asynchronous image binding . please any one help me how to use in MVC 4

Passing an enum as an annotation parameter and getting list of itens

I created a custom attribute, that will be used to define that the property is used in a DropDownList. So the code of attribute is this:

public class DropDownList : Attribute
    {

        public Type EnumType { get; set; }

        public DropDownList(Type type)
        {
            this.EnumType = type;

        }

    }

I can't pass the enum as paramater, i only could do this passing the type of enum, like this:

class TestViewModel{

[DropDownList(typeof(MyEnums.EnumTest)]
prop int MyProp {get; set;}

}

I have a HTML extension, that needs to work like this:

public HtmlString AddSelectFor<TValue>(Expression<Func<TModel, TValue>> expression){

       var memberExpression = expression.Body as MemberExpression;
       var attribute = memberExpression.Member.GetCustomAttributes(typeof(MyProj.Attributes.DropDownList), false).FirstOrDefault() as MyProj.Attributes.DropDownList;

       // HERE i need to get the list of enum itens
       var itens = Enum.GetValues(attribute.EnumType);

       return HtmlHelper.DropDownListFor(expression, list);
}

The problem is, i don't have the enum, i have only the type, because it needs to be generic. So i can't do the cast to create the list used on "HtmlHelper.DropDownListFor".

How can i do that? Thanks

How to set scroll position in MVC 4 when new page is loaded

In my MVC 4 Webapp one of the views is listing house objects, and to the right of every object the user has the possibility to change language. Let's say you are on the middle of the page Reading about an object and decides you want to change language. Then a new page is loaded which looks exactly the same, but with text now in the other language. The problem is that the new page starts from the beginning (of course since it's a new page), and I want the newly loaded page to have the same scroll position as the previous one.

To get a better understanding you can visit the site at http://www.lomahovi.com and then click on Accomodations. There you will see a link for every object where you can switch between English and Russian.

So if a client is looking at an object in English, and decides that he/she wants to switch to Russian I don't want the page to start at the beginning but instead it should be on the same object/position as it was in English, so that the client doesn't have to scroll down the page to find the object again.

Any help is appreciated. Thanks,

Peter

Simple Route to an action in another controller

i have an MVC .Net C# project. have Plan Action under Home Controller. but i dont want to access this page as http://....../Home/Plans but i want to access it as http://....../Plans but i dont want to create Plans Controller. so i dont want to do a redirectToAction.

i am trying to use the Route Annonation as the following:

[Route("plans/")]
public ActionResult Plans()

[Route("plans/{actions}")]
public ActionResult Plans()

[Route("plans/index")]
public ActionResult Plans()

but none of the above worked for me. can you guys help me in this.

Populate DropDownList using AJAX MVC 4

I have a view in place that contains 2 @DropDownListFor's Helpers:

    @using (Html.BeginForm("CreateOneWayTrip", "Trips"))
    {
        @Html.ValidationSummary(false);
        <fieldset>
            <legend>Enter Your Trip Details</legend>

            <label>Start Point</label>
            @Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces, new { @Id = "province_dll", @class = "form-control" })
            @Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities, new { @Id = "city_dll", @class = "form-control" })

            <p style="float: none; text-align: center;">
                <button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
                    <i class="fa fa-check"></i>
                </button>

                <button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
                    <i class="fa fa-times"></i>
                </button>
            </p>
        </fieldset>
    }

Here is the temporary model I use to Capture data:

 public class CaptureCreateTrip
 {
    [Required]
    [Display(Name = "Trip ID")]
    public string TripID { get; set; }

    [Required]
    public string StartPointProvince { get; set; }

    [Required]
    public string StartPointCity { get; set; }
}

One of the DropsDownList's are populated when the page is created and the second will be populated based on the option that the user chooses in the first DropDownList. To achieve this, i am using ajax. The javascript to I use looks like this:

$("#province_dll").change(function () {
        $.ajax({
            url: 'getCities/Trips',
            type: 'post',
            data: {
                provinceId: $("#province_dll").val()
            }
        }).done(function (response) {
            $("cities_dll").html(response);
        });
    });

Here is the Controller the AJAX calls:

  [HttpPost]
  public ActionResult getCicites(int provinceId)
  {
      var lstCities = new SelectList(new[] { "City1", "City2", "City3" });

      return Content(String.Join("", lstCities));
  }

Up until this point everything works - When I choose a value in my Province DropDown the javascript event fires and the Controller action does return the select list values to the Cities DropDown, the problem however is that the data(of the formatof the data) that the Action returns is incorrect. I Tested this by creating a Paragraph element and updating it's text with the return value of the ajax call, which is : "System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.Select‌​‌​ListItem"

*Note: I am new to ajax and in the process of learning Jquery and AJAX.

ASP.NET MVC: Unauthenticated User Always Redirected to Login page

I've been trying to fix this for a week now, I tried everything that crossed my mind. I am creating web app using asp.net mvc 4 template. Problem is that I am always redirected to login page before I can't access any route without log in first. Not even register new user, which is absurd. I'm using simple membership and default Account controller and I even tried removing [Authorize] attribute from Account controller, but even then I'm redirected to login page. My Account controller looks like this:

[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
...
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

My web config is:

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
   </authentication>

In chrome when I click on Register link, I get this error enter image description here

center image in thumbnail

This is what I have (the images inside an anchor):
enter image description here
And I want that low res images will be centered like this: (edited with paint)
enter image description here

This is the razor view:

<div>
<div class="row">
    @foreach (var item in Model)
    {
        <div class="col-md-3 ">
            <div class="thumbnail centerThumb" style="height:345px; width:280px;margin-bottom:15px">
                <div style="height:125px; ">
                    <a href="@Url.Action("Details", "Items", new { id = item.ItemID})">
                        <img src="~/Content/thumbnails/@item.Img" alt="thmbnail" width="255" class="img-rounded centerThumb">
                    </a>
                </div>
                <div class="caption">
                    <h3>@Html.DisplayFor(modelItem => item.Name)</h3>
                    <p style="height:95px">@Html.DisplayFor(modelItem => item.Description)</p>
                    <p style="position:fixed">
                        <a href="#" class="btn btn-primary" role="button">Add to Cart</a>
                    </p>
                    <p style="margin-left:50%"> @Html.DisplayFor(modelItem => item.Price) </p>
                </div>
            </div>
        </div>
    }
</div>

AngularJs (client side) with ASP.NET MVC 5 (server side)

I would like to learn AngularJs. I'm familar with ASP.NET MVC. I'm going to write some web app and I want to use AngularJs in client side and ASP.NET MVC 5 in server side.

I project solution:

  • Project Web - client side ( AngularJs)
  • Core (DAL, repositories, business layer) (C#)
  • Test

Is is good architecture ? What do you think about it ?

MVC with Quartz Service - Not working

I have successfully implemented Quartz as embedded and service. Everything works fine except one. MVC with embedded Quartz works fine but not with service.

I placed MVC project's dll into Quartz folder as instructed and run MVC project and through MVC project i accessed Quartz service and assign job. Quartz successfully puts entry into database(I have used AdoJobStorage) but still job is not triggered by Quartz service.

I have checked things like is service running and beside if i have console application it works fine.

Ajax BeginForm target = _self still loads page when finished

I have an Ajax.BeginForm which is used to update some fields. However, after this call finishes, I just want the screen to stay as it is, but it keeps redirecting to the link defined in the BeginForm address.

I've added target = "_self" to no avail, it still keeps moving pages when the function completes.

Is there any way to stop this from happening? (maybe It's a missing javascript file or something?)

My HTML looks like this:

using (Ajax.BeginForm("Update", "Extraction", null, 
    new AjaxOptions { HttpMethod = "POST", OnSuccess = "saveSuccessful", 
    OnFailure = "saveFailed" }, new { target = "_self" }))

And the controller looks like this:

[HttpPost]
public void Update(Model model)
{
    // do work here
}

I've tried putting a debugger on the saveSuccessful javascript function and can see that this doesn't even get hit as the page already has moved to the page defined on BeginForm.

NHibernate session Is not getting Closed

I have an MVC application with the following libraries installed.

  • Autofac
  • Nhibernate

I had a bug where the session is not getting closed after the request is done. I am having multiple sessions in the SQL database, however none of them are getting closed.

public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder) {
    var config = SessionFactory.ConofigCoreDb();
    var factory = SessionFactory.BuildCloudSQLSessionFactory(config);
    builder.RegisterInstance(config).As<Configuration>().SingleInstance();
    builder.RegisterInstance(factory).As<ISessionFactory>().SingleInstance();
    var session = builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).As<ISession>().InstancePerLifetimeScope();
    //sql services
    builder.RegisterType<ConsumerManager>().As<IConsumerManager>();
    builder.RegisterType<DefaultLogger>().As<ILogger>();
    builder.RegisterType<SettingsService>().As<ISettingService>();
    // and so on...
}

The problem that am having is, with each call to any of the services the sql session is being generated and I can call the database however it is not getting disposed properlym, although the BaseRepository class has a disposable method which flushs the sessions and properly closes them.

How to get autofac to properly close the session safely?

i18n in asp.net using resources and entity framework

I've been trying to store my strings in a database using resource files to fetch them. I've been following the guide from http://ift.tt/1GQqBUL The example works fine enough when i use his sql code based on ADO.net to fetch the strings from the database. But i want to use Entity Framework to fetch the strings from the database, because my translation table is quite different. Could anyone show me an example of how to use Entity Framework in the resource project(assembly?), because i can't seem to get it to work. I cant import any of my models or contexts from my main project with "using", and it tells me i have duplicate models when i copy them to the resources project/assembly

Third-party (NPoco) package in ASP5 MVC6 says DNX Core 5 - Not Available

I'm Trying to port WebAPI2 to MVC6 but I've run in to the following obstacle everywhere.

Hovering over the missing reference gives me a dialog box saying:

DNX 4.5.1 - Available
DNX Core 5 - Not Available

I guess i needs to be available in both frameworks but how.
When i look under references its there under both DNX versions.

Is it because of incompatibility with ASP5 and the package needs a newer version or something?

The dependencies i have are:

"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta4",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta4",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta4",
"NPoco": "2.8.99-beta"
},

Best way to add MVC to a Web.api-project

I have an existing web.api-project that I need to add a mvc5 controller/view to.

I tried to add this by hand by adding bits and pieces of folders, references and config-stuff here and there in the project. Clearly i was not successful because when I try to view my cshtml-files the server just returns server errors. Now I want to start over in structured manner.

So, with a pure web.api-project at hand, how can I add mvc-support?

MVC 4 Rating System

sorry that I'm quite new to MVC4. Im building an mvc4 rating system.

First, i was created a view to input the rating question field and store the info into rating db as below:

Rating Question Input
==============================
Question : [ What Fruit You Like? ] 
Sub Question : Apple ; Orange ; Grapes
Number of Radio Button : [3]
Rating Header : Hate ; Like ; Very Like

My Ratingdb field:

public class RatingInput
    {
        public int Id { get; set; }
        public int QuestionId { get; set; }
        public string Question { get; set; }
        public string Subquestion { get; set; }
        public int NumberRadioButton { get; set; }
        public string ratingheader { get; set; }
    }

How was the data look like in db :

Question             | Subquestion         | NumberRadioButton | ratingheader
What Fruit you Like? | Apple;Orange;Grapes |         3         | Hate;Like;Very Like

How do i generate the seperate line in table for the question and radio button? The illustrate output as below:

1. What Fruit You Like ?

                  Hate     Like      Very Like
Apple             []        []          []
Orange            []        []          []
Grapes            []        []          []

My Rating Output page code sample :

 @foreach (var item in Model)
    {
        <tr>

            <td>
                @Html.DisplayFor(modelItem => item.Question)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.SubQuestion) *Need Help
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.NumberRadioButton) *Need Help
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ratingheader) *Need Help
            </td>

        </tr>
    }

How to pass/map Date object from JavaScript to DateTime object in C# MVC controller action through ajax post?

I am posting a JavaScript date object from the client side and receiving it in the C# controller action. In the C# controller action the object is mapped to a C# DateTime object.

But the DateTime object is not getting the exact value from javascript date object.

Its showing DateTime's min value, i.e.

01-01-0001 12:00:00 AM

  • Here is my client side breakpoint screen-shot:

enter image description here

  • Here is my C# controller action screen-shot:

enter image description here

Here is my ViewModel class:

public class CompanyLaraHistoryViewModel
{
    public int HistoryId { get; set; }
    public int CompanyId { get; set; }
    [Display(Name = "Company Name")]
    public string CompanyName { get; set; }
    [Display(Name = "LARA")]
    public byte LaraId { get; set; }
    public LARA Lara { get; set; }
    [Display(Name = "Changed Date")]
    public DateTime ChangedDate { get; set; }
    public int ChangedById { get; set; }
    [Display(Name = "Comments")]
    public string Comments { get; set; }
    public bool IsDeleted { get; set; }
}

What can be the possible reason for this? Is it that js date objects cannot be mapped to c# datetime objects?

Can anyone give me a solution?

Is it good to call Thread.Sleep during polling Google Big Query results in ASP.NET? Alternatives?

I am using ASP.NET MVC 5 which gets data from Google Big Query. Due to the way Google Big Query is designed, I need to poll for results if job is not finished. Here is my code,

       var qr = new QueryRequest
        {
            Query = string.Format(myQuery, param1, param2)
        };// all params are mine
        var jobs = _bigqueryService.Jobs;
        var response = await jobs.Query(qr, _settings.GoogleCloudServiceProjectId).ExecuteAsync();
        var jobId = response.JobReference.JobId;
        var isCompleted = response.JobComplete == true;
        IList<TableRow> rows = response.Rows;
        while (!isCompleted)
        {
            var r = await jobs.GetQueryResults(_settings.GoogleCloudServiceProjectId, jobId).ExecuteAsync();
            isCompleted = r.JobComplete == true;
            if (!isCompleted)
            {
                Thread.Sleep(100);
            }
            else
            {
                rows = r.Rows;
            }
        }

Looking at this code can someone tell me whether its good to call Thread.Sleep inside this context or I should continuously burn CPU cycles.

Bundling javascript/css

I am working with jQuery libraries in an ASP.Net MVC project.

The following code snippet is from "BundleConfig.cs"

public class BundleConfig
{
    // For more information on Bundling, visit http://ift.tt/1jkQbIb
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                    "~/Scripts/jquery-ui-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

        // Use the development version of Modernizr to develop with and learn from. Then, when you're
        // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/jqgrid").Include(
            "~/Scripts/jquery.jqGrid.min.js", 
            "~/Scripts/grid.locale-en.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

        bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                    "~/Content/themes/base/jquery.ui.core.css",
                    "~/Content/themes/base/jquery.ui.resizable.css",
                    "~/Content/themes/base/jquery.ui.selectable.css",
                    "~/Content/themes/base/jquery.ui.accordion.css",
                    "~/Content/themes/base/jquery.ui.autocomplete.css",
                    "~/Content/themes/base/jquery.ui.button.css",
                    "~/Content/themes/base/jquery.ui.dialog.css",
                    "~/Content/themes/base/jquery.ui.slider.css",
                    "~/Content/themes/base/jquery.ui.tabs.css",
                    "~/Content/themes/base/jquery.ui.datepicker.css",
                    "~/Content/themes/base/jquery.ui.progressbar.css",
                    "~/Content/themes/base/jquery.ui.theme.css",
                    "~/Content/ui.jqgrid.css"));
    }
}

This is the HTML code from my Layout file where I have @Stlyes.Render. As per my understanding, it is supposed to include all the javascript libraries and css that I have bundled in my code above. However, when I view the page source, it only includes a few libraries (as shown in the screenshot below).

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqgrid")

</head>

enter image description here

Not sure why it is not including all the javascript and css files even after specifying those into the BundleConfig.cs file.

Please help!

Localize enum property in asp.net mvc

I have enum property

public enum MyType
{
    House = 0, 
    Apartment = 1
}

now I want to localize this enum using localized resx strings, so I add

public enum MyType
{
    [LocalizedName("House", typeof(LocalizedUIStrings))]
     House = 0, 
    [LocalizedName("Apartment ", typeof(LocalizedUIStrings))]
     Apartment = 1
 }

and localizedname helper class

public class LocalizedNameAttribute : Attribute
{
    private readonly Type _resourceType;
    private readonly string _resourceKey;

    public LocalizedNameAttribute(string resourceKey, Type resourceType)
    {
       _resourceType = resourceType;
       _resourceKey = resourceKey;
       DisplayName = (string)_resourceType
           .GetProperty(_resourceKey, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
          .GetValue(null, null);
    }
    public string DisplayName { get; private set; }
}

in the view I'm trying to use this localized property like this

@Html.DisplayFor(modelItem => item.MyType)

It still returns non localized string, no errors (either on compile or runtime). What I'm doing wrong here?

Saving data many-to-many relationship

My question is: I have two tables room and reservation . They are connected many to many from table RoomReservation.

public class Room
    {
public int Id { get; set; }
public double CostNight { get; set; }
public virtual ICollection<Reservation> Reservation { get; set; }
}

public class Reservation
    {
public int Id { get; set; }
public string DateOfEntry { get; set; }
public int NumberOfNights { get; set; }
public virtual ICollection<Room> Room { get; set; }
}

On My DbContext I configurated this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Entity<Reservation>().HasMany(c => c.Room)
                .WithMany(s => s.Reservation)
                .Map(t => t.MapLeftKey("RoomId")
                    .MapRightKey("ReservationId")
                    .ToTable("RoomReservation"));
        }

After button pressing I save data into database:

public ActionResult Reservation(int number, string date, int roomid)
        {
                var reserv = new Reservation
            {
                NumberOfNights = number,
                DateOfEntry = date
            };
                    db.Reservation.Add(reserv);
                    db.SaveChanges();
}

How can I save data into table RoomReservation?

C# Request.InputStream result my code no response? what is wrong

using (FileStream outputStream = new FileStream (path, FileMode.Create)) 
{
    Stream inputStream = Request.InputStream;
    const int bufferSize = 4096;
    int len;
    byte[] buffer = new byte[bufferSize];
    while ( (len = inputStream.Read(buffer, 0, bufferSize)) > 0)
        {
             outputStream.Write(buffer, 0, len);
        }  
}

My program is running with ASP.Net MVC 5

This is my code, my question is:

when i debug this code, i add a breakpoint in the line "Stream inputStream = Request.InputStream;"

but nothing shows, no error, just cannot run to the next line, it is really weird, i don't know how why, can somebody help me?

How to send a very large array (20 millions numbers) to the client browser?

I have a very large array (20 million numbers, output of a sql query) in my MVC application and I need to send it to the client browser (it will be visualized on a map using webGL and the user is supposed to play with the data locally). What is the best approach to send the data? This is my current code (called using ajax), but when array size goes above 3 millions I receive outofmemory exception. It seems the serialization (stringbuilder?) fails.

List<double> results = DomainModel.GetPoints();
JsonResult result = Json(results, JsonRequestBehavior.AllowGet);
result.MaxJsonLength = Int32.MaxValue;
return result;

I do not have much experience with web programming/javascript/MVC. I have been researching for the past 24 hours but did not get anywhere, so I need a hint/sample code to continue my research.

Roles based authorization in MVC4

I am new to MVC and want to understand the authentication mechanism in MVC

I have these tables in SQL, Users table, Roles table and UserRoles table which maps user id column to role id column. Now as soon as I add an attribute Authorize(Roles = "Customer") I want the access to be given only to the users having customer priviliges. Now what is is that I have to do to create a link between these two. I am looking for a step by step explanation or a link which points me to do this exactly, as I found a number of articles googling out on this and was unable to find the matching one.

Thanks in advance.

ASP.NET MVC - DisplayFormat returns currency based on computer setting

I am using the following line in my model to format value in currency.

However, i found an issue - it returns currency symbol based on computer setting. e.g. in my case it returns $ but person having UK setting returns pound sign

DisplayFormat(DataFormatString = "{0:C0}")

is there any workaround for this? please advise.

Jquery datatable searching, sorting is nt working

I am trying to create a table and apply sorting & searching for that fields. Finally, I found that using jquery datatable it is easy to create a table and apply sorting, search functionality to that. I have tried like this.

 <script>
   $(document).ready(function() {
            $('#example').dataTable( {
                  "dom": '<"top"i>rt<"bottom"flp><"clear">'
            } );
    } );
</script>

<p>
    @Html.ActionLink("Create New", "Create")
</p>


<table id="example" class="display" cellspacing="0" width="100%">

    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MobileNo)
            </th>
            <th>Options</th>
        </tr>
    </thead>
    @foreach (var item in Model)
{
    <tbody>
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MobileNo)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    </tbody>
}

</table>

But searching , pagination & sorting is not working. When I use normal html code it is working fine. But when I get data from database it is not working.

Can we develop VNext projects using Apache Tomcat or Wildfly

I don't know whether this question should be posted over here but I am too keen to know the answer. Can we develop VNext/.net projects using Apache Tomcat or Wildfly. I heard .net projects can be hosted on Tomcat but can we use a non IIS servers for development using visual studio? No offence, with a great respect to IIS and Microsoft. Thank you!

Piranha CMS Manager Login Session

I would like to know how to check if the user is currently logged in the Manager Area. How could I check this? Thanks.

I want to create something like:

    If(Session["Manager"] != null)
       bool IsManagerIn = true;

Access more scope Google Authentication with ASP.NET Identity at runtime

I have a MVC5 project that using ASP.NET Identity and external login with Google.

At first, i just need user to login by his Google account. Later when using some function in system, i may need permission to access his YouTube account. At that time, i will need to expand the scope (not only login). User will be re-direct to a google page and allow more scope for my app.

I have read this topic. But it looks like i have to clarify all scope when application start.

So is there anyway i can expand scope of Google Authentication with ASP.net Identity when it demand?

samedi 9 mai 2015

Crypto.VerifyHashedPassword throws exception

I have hashed the user password using Crypto.HashPassword('nakedPassword'); and saved this value in my db.

During signup:

public Status Signup(Customer user) 
{
    //change password to password hash & create a verification codetry 
    try 
    {
        int pkid;
        user.PASSWORD = Crypto.HashPassword(user.PASSWORD);
        user.VER_CODE = Guid.NewGuid().ToString();
        Mapper.CreateMap <Customer,user>();
        var mappedcustomer = Mapper.Map<Customer,user>(user);
        string result = _userRepository.Signup(mappedcustomer);
        Status status = new Status();
        if (result == "MOB_EXISTS") 
        {
            status.setError("Mobile number already exists");
        } 
        else if (result == "EMAIL_EXISTS") 
        {
            status.setError("Email already exists");
        }
    } catch (Exception e) {}
}

Later during login when i retrieve using:

Status status = new Status();
try
{
    string hashedPass = _userRepository.GetHashedPassByEmail(email);
    if (Crypto.VerifyHashedPassword(hashedPass, password)) //<-- THIS LINE THROWS THE EXCEPTION
    {
        //authenticated
        status.setSuccess("Login successful !");
    }
    else
    {
        status.setError("Invalid Credentials. Please try again.");
    }

}
catch (Exception e)
{
    status.setError("Error during login. Please check the credentials and try again.");
}

The pointed line throws the exception

System.FormatException

Invalid length for a Base-64 char array or string.

Stacktrace:

at System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
at System.Convert.FromBase64String(String s) at System.Web.Helpers.Crypto.VerifyHashedPassword(String hashedPassword, String password) at Tmmmt.Business.UserProvider.login(String email, String password) in c:\Users\MacBook\Source\Repos\tmmmt.com\Tmmmt.Business\UserProvider.cs:line 802

Note: This does not happen all the time but happens on certain signups only. See Crypto.VerifyHashedPassword

EDIT:

When i looked into my code for signup i saw a hash getting generated but it is truncated when writing to db.

For example..

Actual Hash: ANFRzzPtJ6H/hmsxmbPpkUgIDcmxoaWDV6Ej8Xes8+PupKnsKq3EI/cUTHCRZm9t+g==

Hash in Db: ANFRzzPtJ6H/hmsxmbPpkUgIDcmxoaWDV6Ej8Xes8+PupKnsKq

The password field in the db is varchar(8000) and i am putting it through the following way..

public virtual ObjectResult<string> sp_signupweb(string name, string email, string passHash, string code, Nullable<long> mob, Nullable<int> utc, string verifycode, ObjectParameter result) 

{

    ...//some code//

     var passHashParameter = passHash != null ?
                    new ObjectParameter("passHash", passHash) :
                    new ObjectParameter("passHash", typeof(string));

    //.... some more code
                return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<string>("sp_signupweb", nameParameter, emailParameter, passHashParameter, codeParameter, mobParameter, utcParameter, verifycodeParameter, result);

}

Can someone please explain the truncation and help me solve it.

C# MVC: displaying list items with ajax

I'm trying to display list items with AJAX. First, when you go into the page, you will see the first item of the list. After clicking "Next", then AJAX will refresh its div with the next item in the list.

Controller

public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView(_attractionList.ElementAt(1)); // next element in the list
            }

            return View(_attractionList.First());
        }

View

@model EasyTripNow.Models.Attraction

@{
    ViewBag.Title = "Index";
}

    @Html.Partial("_Attraction", Model)

    @using (Ajax.BeginForm(
        new AjaxOptions()
        {
            HttpMethod = "get",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "newAttraction"
        }))
    {
        <input type="submit" value="Next"/>
    }

Attraction Partial view:

<div id="newAttraction">
    <h4>Attraction</h4>
    @Html.EditorForModel(Model)
    <p>
        @Html.ActionLink("Edit", "Edit", new {id = Model.ID}) |
        @Html.ActionLink("Back to List", "Index")
    </p>
</div>

Can't think of a good way to do it.

Any suggestions?

ASP.NET MVC 6 (vNext) not properly linking to files

I'm trying to run the ASP.NET 5 MVC 6 sample "HelloMVC" project, with a custom CSS file.

I place my .css files in the wwwroot folder, let's say in a styles folder.

I then link to it in my _Layout.cshtml with

<link rel="stylesheet" href="~/styles/mystyle.css" />

However, the style doesn't get rendered.

If I go to the URL of the expected file in my browser (let's say I'm running on port 12345, so I go to http://localhost:12345/styles/mystyle.css, I'm greeted with a cheeky page (pure HTML) with a lightbulb and a smiley face that says "Your ASP.NET 5 application has been successfully started".

In fact, if I go to any URL for the running app, I'm greeted with the same page. i.e. going to http://localhost:12345/thisfiledoesntexist.jpg will return the same page.

Is this ASP.NET 5's current 404 page? Why aren't my styles getting rendered? I would think this would be a very simple thing.

Looking at this question it seems that what I'm doing would be the proper way. In fact, Visual Studio even has intellisense for the css files that I've added when typing out the href.

ASP.NET MVC 5 and Visual Studio 2015RC CS0234 errors

There are similar Qs on SO but I could find none relating to my specifics

The ASP.NET MVC out of the box template (ie file new project etc) build and run ok but in the editor I have red squigglies all over the place with 17 CS0234 errors each reporting:

"the name xxxx does not exist in the current context"

Where xxxx is ViewBag, Scripts, RenderSection etc.

Observe same issue with opening existing projects from vs2013 in 2015.

I have tried deleting and reinstalling MVC (Microsoft.AspNet.Mvc) manually using nuget to no avail.

os: windows 8.1 pro

Maybe a known bug? Hope someone can throw some light on this.

Web Config (extract):

<dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>

Packages (extract):

<packages>

  <package id="Microsoft.AspNet.Identity.Core" version="2.2.0" targetFramework="net452" userInstalled="true" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.0" targetFramework="net452" userInstalled="true" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.2.0" targetFramework="net452" userInstalled="true" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net452" userInstalled="true" />
  <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net452" userInstalled="true" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net452" userInstalled="true" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net452" userInstalled="true" />

</packages>

EDIT

thought I had fixed this (see below orig fix 1 below) but the c# code completion/intellisense was broken.

Decided to reinstall vs2015 and this has reverted to the original issue at the top of this question and the C# code completion / intellisense is not working.

fix 1 squigglies + cs0234 errors disappeared but no c# intellisense/code completion

  1. went to programs and features to modify the current vs settings to remove just the web tools
  2. almost immediately aborted the above - the installer aborted with no changes except maybe setting a restore point. Thought it was prudent to go back into vs and uninstall web essentials extension first!
  3. in vs uninstalled web essentials
  4. on restarting vs had an error relating to chutzpah extension ( error details below) which I uninstalled
  5. Opened vs again to check it still worked - newed up an asp.net mvc 5 project (so at this stage no changes have been made to the vs installed components) and everything was working no more errors in the editor all squigglies gone!
  6. reloaded above extensions and everything still works

error details (from %APPDATA%\Microsoft\VisualStudio\10.0\ActivityLog.xml)

<entry>
    <record>389</record>
    <time>2015/05/06 19:45:05.396</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [ChutzpahVS2012Package]</description>
    <guid>{A523D775-1341-4F21-A950-8C716E5628C9}</guid>
  </entry>
  <entry>
    <record>390</record>
    <time>2015/05/06 19:45:05.396</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>SetSite failed for package [ChutzpahVS2012Package]</description>
    <guid>{A523D775-1341-4F21-A950-8C716E5628C9}</guid>
    <hr>80070002</hr>
    <errorinfo>Could not load file or assembly 'Microsoft.VisualStudio.TestPlatform.ObjectModel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.</errorinfo>
  </entry>

ASP.NET 5 Custom roles for Windows Authentication

I'm building an intranet type site with ASP.NET 5 that uses Windows Authentication. I have the authentication working, but I don't want everyone on the domain to have access to the intranet site. I can't use domain roles so I've set up my own custom roles in my SQL Server. I have a table that maps the domain username to roles. I want to restrict access to the intranet site to only users that have a role defined in my SQL Server role table. How would I set up custom roles for Windows Authentication in ASP.NET 5? Thanks!

Deploy to Azure issue: Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0...manifest not match issue

I'm developing an MVC site and it works fine locally, but when I deploy to my Azure site, I am getting this error:

Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I should be deploying all of those assemblies. Since its hosted in Azure, I have limited control over the box, but I thought they would have this assembly on there as well so I'm not sure why this is causing an issue. Any ideas?

More details:

Server Error in '/' Application.

Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.

WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[FileLoadException: Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] marylandgives.mvc.MvcApplication.Application_Start() +0

[HttpException (0x80004005): Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9916673 System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118 System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172 System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336 System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9930568 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.36215

Remove css and scripts from PartialView

I want to implement an Star Rating code. For that I am using a PartialView called as:

@{ Html.RenderAction("Rate"); }

The purpose is to show and handle the star rating code separately from the current page. Thus, I dont really need to use the css or other javascripts that are being rendered in the parent .cshtml.

I am removing the layout as follow:

@{ Layout = null; }

From the controller:

public ActionResult Rate() {
return PartialView(); }

But I noticed that the parent css and javascript are messing up with the star rating thus I don't really want to use them. How to protect the partial view?

use mymodel with defaut identity model error

I created a project with the model identity model by default. And I have also created a personal model in another file class whose name is "monmodele". Everything worked fine until now . but now I get an error that I do not understand and I do not know what I changed that it does not work anymore. In the login default view created when creating the project it is now asking me to pass him my model instead of defaut model. help please

controller get method

//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindAsync(model.Email, model.Password);
        if (user != null)
        {
            await SignInAsync(user, model.RememberMe);
            return RedirectToLocal(returnUrl);
        }
        else
        {
            ModelState.AddModelError("", "Invalid username or password.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

the message error when I try to arrive to login view :

The model item passed into the dictionary is of type 'CreationLogicielSitePhoto.Models.LoginViewModel', but this dictionary requires a model item of type 'CreationLogicielSitePhoto.Models.Monmodele'.

model : file accountviewmodel.cs

namespace CreationLogicielSitePhoto.Models
{
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }

    public class ExternalLoginListViewModel
    {
        public string Action { get; set; }
        public string ReturnUrl { get; set; }
    }

    public class ManageUserViewModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class LoginViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class ResetPasswordViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        public string Code { get; set; }
    }

    public class ForgotPasswordViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }
}

the view login and the declaration's model where is the mistake :

@using CreationLogicielSitePhoto.Models
@model LoginViewModel


@{
    ViewBag.Title = "Log in";
}

<h2>@ViewBag.Title.</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>Use a local account to log in.</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @Value = "d.fernandes.amorim@hotmail.fr" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @Value = "10Carail-" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Log in" class="btn btn-default" />
                    </div>
                </div>
                <p>
                    @Html.ActionLink("Register as a new user", "Register")
                </p>
                @* Enable this once you have account confirmation enabled for password reset functionality
                <p>
                    @Html.ActionLink("Forgot your password?", "ForgotPassword")
                </p>*@
            }
        </section>
    </div>
    <div class="col-md-4">
        <section id="socialLoginForm">
            @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { Action = "ExternalLogin", ReturnUrl = ViewBag.ReturnUrl })
        </section>
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

and my personal model :

namespace CreationLogicielSitePhoto.Models
{
    using Microsoft.AspNet.Identity;

    //Classe du modèle
    public class Monmodele
    {
        public TCommande Tcommande { get; set; }
        public List<TCommande> Tcommandes { get; set; }
        public TRetouche Tretouche { get; set; }
        public List<TRetouche> Tretouches { get; set; }
        public TTypeRetouche Ttyperetouche { get; set; }
        public List<TTypeRetouche> Ttyperetouches { get; set; }
        public TRetoucheFormat Tretoucheformat { get; set; }
        public ICollection<TRetoucheFormat> Tretouchesformats { get; set; }
        public TFormat Tformat { get; set; }
        public List<TFormat> Tformats { get; set; }

        //Methode qui indique si une commande est en cours
        public bool ExistCommande()
        {
            using (var db = new ApplicationDbContext())
            {
                string iduser = System.Web.HttpContext.Current.User.Identity.GetUserId().ToString();
                var commande = (from a in db.TCommandes
                                where a.Userid == iduser | a.Commandevalide == false
                                select a).FirstOrDefault();
                if (commande != null)
                {
                    return true;
                }
                return false;
            }
        }
    }

    [Table("TRetoucheFormat")]
    public class TRetoucheFormat
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int IdRetoucheFormat { get; set; }
        public int IdRetouche { get; set; }
        public int IdFormat { get; set; }
        public int IdCommande { get; set; }
        public int Quantite { get; set; }
    }
}

he ask me to pass monmodele but in the view, is the loginviewmodel asked.

tks

To Test Camera, Microphone and Speaker through a .Net web application

I have built a .NET web application for video chat through OpenTok APIs, and want to give an option to the users to test their settings for camera, speaker and microphone after they log into my application, similar to as we have in Skype, go-to-meeting etc., except for Skype is a windows app and Go to Meeting comes in as a plugin with outlook. Is there a way to check if the below three are installed properly/ enabled on a computer/ laptop through some client side scripts (may be Java Script or something similar) on my web application:

  1. Camera
  2. Microphone
  3. Speaker

Many Thanks!!

ASP.NET Identity 2 Separation of Email and UserName and using Email to login

By default, ASP.NET Identity has the UserName and Email fields as being the email the user inputs. I've already changed it so that my system takes in a separate username and email for the user.

My problem is that now I cannot login to the system because of the checks Identity does against both the UserName and Email.

I was wondering if there was a way to keep these two fields separate and unique, while being able to just check against the Email field in order to login to the system?

I noticed that public virtual Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout); checks the userName, but changing this to the email does nothing and I am still unable to login.

I've also looked at these other questions:

ASP.Net UserName to Email

Allowing both email and username for authentication

for possible solutions and found nothing really allowed me to do what I want.

Is there anything else I could possibly attempt in order to have separate usernames and emails, while still being able to login with the email field?

MVC Helper @Html.LabelFor not showing up?

Am I missing a reference or something?

I have a reference to System.Web.Mvc 4.0x

But whenever I try this

 @Html.LabelFor(x=>Model.yadda, new {id="_lblYadda"});

I get nothing I can't even get it to compile. I only have a reference to

 @Html.Label("Yadda", "Yadda yadda");

I spent like 5 minutes looking, I know it's simple so.. help please!

WebConfig namespaces are:

 <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>

ASP.NET MVC: What's the best way to validate the expiry/legitimate of querysting

We have a payment successful page where we read the query string ?paid=yes.

If paid=yes then we show the payment sucessfull message etc. Otherwise payment failed.

What's the best way to:

  1. Validate ?paid=yes query string is valid? In other words, how can we stop people from manually manipulating query string ?

  2. Set query string expiry time or set attempt (max 1)?

Thanks.

ASP MVC 5 Empty Model List after Post

I've been around this for a couple of time and I would love if possible for a couple of "fresh" pair of eyes to look at this.

In my app I have a form where I use a model with some primitive types and two lists. Also I'm using a Kendo grid.

My problem is that when the user does Submit, the model arrives ok but one of the two lists returns with 0 elements...! (never null)

The list that arrives ok is the one I'm creating in the Kendo Grid.

The list that returns empty is List ProductItemlist, that is generated in the partial view (also tried not using the partial view).

The thing is, on the controller if I do:

string test = Request.Form["ProductItemlist[0].ProductItemId"],

I get the values I want, so the problem I think must be in the mapping.

Nevertheless I'm failing in discovering it....

What's happenning...? Thanks in advance for any help!

My Model:

public class PurchaseRegistrationProductEditVM
    {
public int ClientId { get; set; }

    public int ProductId { get; set; }

    public int EnterpriseId { get; set; }

    public int HeadquarterId { get; set; }

    public string Name { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime? EndDate { get; set; }

    public int StatusId { get; set; }

    public int? RUC { get; set; }

    public string RUCName { get; set; }

    public string RUCAddress { get; set; }

    public List<PurchaseRegistrationProductItemEditVM> ProductItemlist { get; set; }

    public List<ClientProductPurchaseRegistryComissionEditVM> ComissionList { get; set; }

}

Model PurchaseRegistrationProductItemEditVM:

public class PurchaseRegistrationProductItemEditVM{

 public int ProductItemId { get; set; }

    public string ProductItemName { get; set; }

    public int ProductItemTypeId { get; set; }

    public string ProductItemTypeName { get; set; }

    public DateTime? StartCourseDate { get; set; }

    public DateTime? EndCourseDate { get; set; }

    public decimal Amount { get; set; }

    public int ExpiryDays { get; set; }

    public string Size { get; set; }

    public int DiscountTypeId { get; set; }

    public string DiscountTypeName { get; set; }

    public decimal? Discount { get; set; }

    public int? MonthlyPaymentDueDay { get; set; }

    public decimal? MonthlyPaymentDuePenalty { get; set; }

    public DateTime MatriculationStartDate { get; set; }

    public string MatriculationObservation { get; set; }

}

Model: ClientProductPurchaseRegistryComissionEditVM

public class ClientProductPurchaseRegistryComissionEditVM
    {
    public int Id { get; set; }

    public int ClientProductPurchaseRegistryId { get; set; }

    public string EmployeeName { get; set; }

    public int EmployeeId { get; set; }

    public string Observations { get; set; }
}

My View:

@model PurchaseRegistrationProductEditVM

@{
Layout = "~/Areas/Backoffice/Views/Shared/_Layout.cshtml";
}


        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
            @Html.HiddenFor(model => model.ClientId)
            @Html.HiddenFor(model => model.EndDate)
            @Html.HiddenFor(model => model.EnterpriseId)
            @Html.HiddenFor(model => model.HeadquarterId)
            @Html.HiddenFor(model => model.Name)
            @Html.HiddenFor(model => model.ProductId)
            @Html.HiddenFor(model => model.ProductItemlist)
            @Html.HiddenFor(model => model.StartDate)
            @Html.HiddenFor(model => model.StatusId)


                                @Html.Partial("_PartialViewProductItem")

                                <div class="form_sep">
                                        @Html.Label(Resources.Client_Pending_Payment_Label_Comission)
                                    @(Html.Kendo().ComboBox()
                                        .Name("EmployeeComissionComboBox")
                                        .Placeholder(Resources.Employee_ComboBox)
                                        .DataTextField("Text")
                                        .DataValueField("Value")
                                        .Filter(FilterType.Contains)

                                        .DataSource(source =>
                                        {
                                            source.Read(read =>
                                            {
                                                read.Action("GetEmployeesComboBox", "Client", new { EnterpriseId = @Model.EnterpriseId });
                                            })
                                            .ServerFiltering(true);

                                        })
                                    )
                                </div>
                                <div class="form_sep">
                                    @Html.Label(Resources.Client_Purchase_Registry_Comission_Field_Observations)
                                    @Html.TextBox("PurchaseComissionObservations", "", new { maxlength = 50, size = 10, @class = "form-control" })


                                </div>
                                <div class="form_sep">

                                    @(Html.Kendo().Button()
                                    .Name("EmployeeComissionAddButton")
                                    .HtmlAttributes(new { type = "button", @class = "k-primary" })
                                    .Content(Resources.Client_SelectedPayments_Button_Add_Employee_Comission)
                                    .Events(ev => ev.Click("onClickAddEmployeeComission"))
                                    )
                                </div>

                                <div class="form_sep">
                                    @Html.Label(Resources.Client_Purchase_Registry_Grid_Added_Employees)
                                    @(Html.Kendo().Grid<ClientProductPurchaseRegistryComissionEditVM>()
                                        .Name("PurchaseCommissionGrid")
                                        .HtmlAttributes(new { style = "height:150px;" })
                                        .Columns(columns =>
                                        {
                                            columns.Bound(o => o.EmployeeName).Filterable(f => f.Cell(c => c.ShowOperators(false))).ClientTemplate("#= EmployeeName #<input type='hidden' name='ComissionList[#= indexPurchaseComissionGrid(data)#].EmployeeName' value='#= EmployeeName #' />");
                                            columns.Bound(o => o.EmployeeId).Hidden().Filterable(f => f.Cell(c => c.ShowOperators(false))).ClientTemplate("#= EmployeeId #<input type='hidden' name='ComissionList[#= indexPurchaseComissionGrid(data)#].EmployeeId' value='#= EmployeeId #' />");
                                            columns.Bound(o => o.Observations).Filterable(f => f.Cell(c => c.ShowOperators(false))).ClientTemplate("#= Observations #<input type='hidden' name='ComissionList[#= indexPurchaseComissionGrid(data)#].Observations' value='#= Observations #' />");
                                            columns.Command(command =>
                                            {
                                                command.Custom("Remove").Text(Resources.Site_Link_Remove).Click("onDeleteEmployeeComission");
                                            });
                                        })
                                        .DataSource(dataSource => dataSource
                                        .Ajax()
                                        .PageSize(5)
                                        )
                                        .Pageable()
                                        .Sortable()
                                        .Scrollable())
                                </div>

                                <div class="form_sep">
                                    @Html.LabelFor(model => model.RUC)
                                    @Html.TextBoxFor(model => model.RUC, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.RUC)
                                </div>

                                <div class="form_sep">
                                    @Html.LabelFor(model => model.RUCName)
                                    @Html.TextBoxFor(model => model.RUCName, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.RUCName)
                                </div>

                                <div class="form_sep">
                                    @Html.LabelFor(model => model.RUCAddress)
                                    @Html.TextBoxFor(model => model.RUCAddress, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.RUCAddress)

                        <input id="btnSubmit" type="submit" value="@Resources.FO_Client_Link_Buy_Product" class="btn btn-default" />
                        @Html.ActionLink(Resources.Site_Link_Back, "PurchaseProduct/" + @Model.ClientId, "Client", new { Area = "Frontoffice" }, new { @class = "btn btn-default" })

        }

Partial View:

@model PurchaseRegistrationProductEditVM

 @for (int i = 0; i < Model.ProductItemlist.Count; i++)
{
@Html.HiddenFor(model => model.ProductItemlist[i].Amount)
@Html.HiddenFor(model => model.ProductItemlist[i].Discount)
@Html.HiddenFor(model => model.ProductItemlist[i].DiscountTypeId)
@Html.HiddenFor(model => model.ProductItemlist[i].DiscountTypeName)
@Html.HiddenFor(model => model.ProductItemlist[i].EndCourseDate)
@Html.HiddenFor(model => model.ProductItemlist[i].ExpiryDays)
@Html.HiddenFor(model => model.ProductItemlist[i].MonthlyPaymentDueDay)
@Html.HiddenFor(model => model.ProductItemlist[i].MonthlyPaymentDuePenalty)
@Html.HiddenFor(model => model.ProductItemlist[i].ProductItemId)
@Html.HiddenFor(model => model.ProductItemlist[i].ProductItemName)
@Html.HiddenFor(model => model.ProductItemlist[i].ProductItemTypeId)
@Html.HiddenFor(model => model.ProductItemlist[i].ProductItemTypeName)
@Html.HiddenFor(model => model.ProductItemlist[i].Size)
@Html.HiddenFor(model => model.ProductItemlist[i].StartCourseDate)

if (Model.ProductItemlist[i].ProductItemTypeId == 1)
{
    DateTime date = DateTime.Now;
    if (date < Model.ProductItemlist[i].StartCourseDate.Value)
    {
        date = Model.ProductItemlist[i].StartCourseDate.Value;
    }

    //Case Course

    <div class="form_sep">
        <b>@Resources.Site_Link_Course&nbsp;@Html.LabelFor(model => model.ProductItemlist[i].ProductItemName)</b>
    </div>
    <div class="form_sep">
        @Html.LabelFor(model => model.ProductItemlist[i].MatriculationStartDate)
        @(Html.Kendo().DatePickerFor(model => model.ProductItemlist[i].MatriculationStartDate)
                                                .Animation(true)
                                                .Culture("pt-PT")
                                                .Format("dd-MM-yyyy")
                                                .Value(date)
                                                .Min(Model.ProductItemlist[i].StartCourseDate.Value)
                                                .Max(Model.ProductItemlist[i].EndCourseDate.Value)
        )
        @Html.ValidationMessageFor(model => model.ProductItemlist[i].MatriculationStartDate)
    </div>

    //Observations
    <div class="form_sep">
        @Html.LabelFor(model => model.ProductItemlist[i].MatriculationObservation)
        @Html.TextBoxFor(model => model.ProductItemlist[i].MatriculationObservation, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ProductItemlist[i].MatriculationObservation)
    </div>
}

}

My Controller:

[HttpPost]
    public ActionResult PurchaseProductRegistration(PurchaseRegistrationProductEditVM model)
    {
        Log.Instance.Info(string.Format(LogConst.CONTROLLER, "Client", "ProcessPayments", "Get"));

        string test = Request.Form["ProductItemlist[0].ProductItemId"];

                return RedirectToAction("Details/" + model.ClientId, "Client");

}

How to use partial views from different models in ASP.NET MVC 5?

Hi I am trying to code a simple blog with using ASP.NET MVC 5 Framework. I have done CRUD operations of Posts. I mean I can add new articles and manage them. When I wanted to add comments to articles, I stuck. Comments will be added to Details pages of articles. So I should add Create comment page to Details page.

I used Code First model and I have two models. Articles and Comments. I decided to use partial views to enter comments. But result is an error:

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Article but this dictionary requires a model item of type 'Blog.Models.Comment'. Comments can not be added. I created 2 PartialViews, one of them is _CreateComments PartialView and other one is _Index PartialView

Details View:

@model Blog.Models.Article

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

 <div>
<h4>Article</h4>
<hr />
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.Title)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Title)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Author)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Author)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Date)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Date)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.ArticleContent)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.ArticleContent)
    </dd>

</dl>
 </div>
 <div class="jumbotron">
  @Html.Partial("~/Views/Comments/_CreateComments.cshtml", new Blog.Models.Comment())
  @Html.Partial("~/Views/Comments/_Index.cshtml", new List<Blog.Models.Comment> { new Blog.Models.Comment() })
   </div>

_CreateComment PartialView

  @model Blog.Models.Comment
   @using (Html.BeginForm("Create")) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Comment</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CommentContent, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CommentContent, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CommentContent, "", new { @class = "text-danger" })
        </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>
</div>
 }

<div>
@Html.ActionLink("Back to List", "Index")
</div>

_Index PartialView @model IEnumerable

 <table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Date)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.CommentContent)
    </th>
    <th></th>
</tr>

 @foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Date)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.CommentContent)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.CommentId }) |
        @Html.ActionLink("Details", "Details", new { id=item.CommentId }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.CommentId })
    </td>
</tr>
 }

 </table>

Generate formatted friendly URL from RouteData

I'm trying to programmatically map a query string to an SEO friendly route URL I've created within my RouteConfig.cs file but appear to be having difficultly.

My route configuration looks like this:

routes.MapRoute(
    name: "ReviewPost",
    url: "{year}/{month}/{filename}/",
    defaults: new {controller = "ReviewPost", action = "Detail"},
    namespaces: new[] {"ApplicationName.Website.Controllers"},
    constraints: new {year = @"\d{4}", month = @"\d{2}"}
);

And I'm able to retrieve the correct RouteData object like so:

string url = "~/ReviewPost/Detail/?year=2015&month=05&filename=review-title";
RouteData routeData = RouteDataUtils.RouteByUrl(myUrl);

However I'm having difficulty figuring out how to generate the friendly URL that should look like the one specified in my configuration (/2015/05/review-title/).

Is the RouteData object able to create an instance of the formatted URL above, or do I have to format it myself? Or does the MVC framework have a class for correctly formatting the URL string using the RouteData object?

Any help would be appreciated.

I want to generate this textbox with a model's I.d when i'm creating and also making the textbox uneditable

This is my model

    [Key]
    public int ConsultId { get; set; }

`

This is my View `

    @Html.LabelFor(model => model.ConsultId, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.IdFor(m=>m.ConsultId)

        @Html.ValidationMessageFor(model => model.ConsultId, "", new { @class = "text-danger" })

What I want to do is,i want the textbox for the ConsultId to be autogenerated

downgrade jquery version on specific view only

let's say that I'm using jquery version 1.10 inside _Layout.cshtml and on specific pages to downgrade to 1.7.2.

How can I do this without changing Layout on this specific views? Is this even possible ? :)

custom identity user and extending profile MVC

I am trying to extend the identity user data in separate table but its not populating.

  public class MyUserInfo
  {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

  }

  public class AppUser : IdentityUser<Int32, AppUserLogin, AppUserRole, AppUserClaim>
  {

    public MyUserInfo MyUserInfo { get; set; }
 }

//Fetching the user data

var userStore = new UserStore<AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>(db);
var userManager = new UserManager<AppUser, int>(userStore);

var user = userManager.FindById(1);
**user.MyUserInfo** showing the null. But in db, we have the respective user data.

I saw many post where without customization seems working but for me I modified id stored as integer and changed the table name.

ASP.Net Create Two Models With One Controller

I'm just trying To create one controller that will work with two models. Comment Model:

 public class Comment
 {
    public int ID { get; set; } // property
    public int PostID { get; set; }
    public String Title { get; set; }
    public String Name { get; set; }
    public Uri Url { get; set; }
    public String Text { get; set; }
    public Post Post { get; set; }
}

public class CommentDBContext : DbContext 
{
    public DbSet<Comment> Comments { get; set; }

    public System.Data.Entity.DbSet<BlogShauli.Models.Post> Posts { get; set; }

}

Post Model:

  public class Post
  {
    public int ID { get; set; } // property
    public String Title { get; set; }
    public String Author { get; set; }
    public String AuthorSite { get; set; }
    public DateTime ReleaseDate { get; set; }
    public String Text { get; set; }
 }

public class PostDBContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
}

And now I want to create a Single Controller that will work with both models. I read that the way to do it is to use ViewModel Pattern so i created one more model class named "BlogViewModel.cs", with the following code:

public class MotorcycleViewModel
 {
     public Comment CommentPointer { get; set; }
     public Post PostPointer { get; set; }
 }

But from here i didn't understand what do. i'm trying to create a new Controller using Entity framework but i don't know what to select in the "Data context class". can someone would explain me how to make the connection between Both models and the Controller? Thanks!

The cast to value type 'System.Int32' failed because the materialized value is null

I have a Issue that I don't know what it is, there is my Home Controller:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Biblioteca.Models;
using CrystalDecisions.CrystalReports.Engine;

namespace Biblioteca.Controllers
{
public class HomeController : Controller
{
    private BibliotecaDatabase db = new BibliotecaDatabase();

    public ActionResult Index()
    {
        var totalesviewmodel = new TotalesViewModel();
        totalesviewmodel.MontoCopias = db.AlumnosList.Sum(o => o.Copias);
        totalesviewmodel.MontoImpresiones = db.AlumnosList.Sum(o => o.Impresiones);
        totalesviewmodel.DineroDeposito = db.AlumnosList.Sum(o => o.Deposito);
        totalesviewmodel.DineroSap = db.AlumnosList.Sum(o => o.Sap);
// there is my issue
        totalesviewmodel.MontoCopiasMaestro = db.MaestrosList.Sum(o  => o.Copias );
        totalesviewmodel.MontoImpresionesMaestro = db.MaestrosList.Sum(o => o.Impresiones);
        return View(totalesviewmodel);
    }

    public ActionResult Reports()
    {
        List<Alumno> allDatos = new List<Alumno>();
        using (BibliotecaEntities dc = new BibliotecaEntities())
        {
            allDatos = dc.Alumnos.ToList();


        }
        return View(allDatos);
    }

    public ActionResult ExportReport()
    {
        List<Alumno> allDatos = new List<Alumno>();
        using (BibliotecaEntities dc = new BibliotecaEntities())
        {
            allDatos = dc.Alumnos.ToList();



            ReportDocument rd = new ReportDocument();
            rd.Load(Path.Combine(Server.MapPath("~/Reports"), "rpt_datos.rpt"));
            rd.SetDataSource(allDatos);

            Response.Buffer = false;
            Response.ClearContent();
            Response.ClearHeaders();

            try
            {
                Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                stream.Seek(0, SeekOrigin.Begin);
                return File(stream, "application/pdf", "Reporte.pdf");
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }

    public ActionResult Contact ()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

So, I don't know why I have this issue on:

totalesviewmodel.MontoCopiasMaestro = db.MaestrosList.Sum(o  => o.Copias );

before install crystal reports I don't have this issue, can any one help me?

What am I doing wrong?