I'm trying to rewrite an old mvc1 application as a vNext app in vs2014. Application authenticates against the company's active directory. Here's a bit of a background to help clarify where my confusion is coming from.

I wrote one app in mvc4 which authenticates the following way: 1. Vs template had account login post action with isValid method 2. I wrote my membership provider and registered it through web.config 3. When I run application isValid is now calling my override that does authentication

Now I'm in vNext and here's what I see 1. Same account and login method except there's some signinmanager and user manager passed into it. I'm yet to see where it's coming from exactly. I suspect it's through startup.cs 2. I see that isValid is replaced with something like Passwordsigninasync which I think I need to override to login the user.

Here's my question how do I make Passwordsigninasync authenticate to our AD? I can go solo and ignore the framework to make it work but I'm sure there's an easy way to do it and I'm just missing some understanding of how plumbing works in vNext. Appreciate any help in the right direction.

I have this property in my model :

[DisplayName("Birth Date")]
public Nullable<System.DateTime> dtnasc { get; set; }

use on view the htmlhelper

 @Html.LabelFor(_ => _.dtnasc)

and receive this error : Nullable object must have a value.

When value of property dtnasc is null, how can we get DisplayName Metadata?

I have an ASP.NET MVC website and a subdirectory "/dir/" under it which is also configured as an ASP.NET application.

I want the http://website/dir/ URL to route to a parent controller if some condition is met, or simply ignore it and "pass over" to the subdir-application if not. How do I do this?

PS. I cannot use RouteExistingFiles = true because both apps have some aspx/ashx/html files that need to work.

I am new to C#. In php setting session and get session data in model class I use something like this

class Users_model extends CI_Model
{   
    function auth(){
        //get session value of username
        $code=$this->session->userdata('code');
        //set session data 
        $this->session->set_userdata(array('auser'=>$resultAPI->GAResult->AGC));
    }
}

How would I achieve the same in my UsersModel.cs class in C# using razor MVC structure since I require the session data in the model to use in a query?

I need to get fresh specific hastag tweets in c# or c# asp.net or mvc

I have a Razor view in which I want to render the result of another action. So what I tried doing is this

@Html.Action("Index", "Home", new { area = "Portal" })

However this doesn't seem to render anything on the page. But when I check which URL is rendered by the Url.Action with the same parameters it's giving me the proper URL.

@Url.Action("Index", "Home", new { area = "Portal" }) // this shows /Portal/Blog/Index
@Html.Action("Index", "Home", new { area = "Portal" }) // this doesn't show anything

And if I go in my browser to /Portal/Blog/Index I can see content I'm trying to load just fine. I've even tried removing all of the code from HomeController so the action is simply

public ActionResult Index()
{
    // also tried returning this.PartialView() but it makes no difference
    return this.View();
}

and the Index.cshtml is just

@{
    Layout = null;
}
<div>test</div>

I have a problem with setting default route in my Asp.net MVC project. My global.asax doesn't have Routes.MapRoute, it just has the code bellow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace razor
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

I am trying to render the FirstName entered by the user as a label in the View. I have tried...

@Html.DisplayFor(c => c.FirstName)
@Html.LabelFor(c => c.FirstName)
@Html.DisplayNameFor(c => c.FirstName)

What is the best way? Seems simple, I am obviously missing something? Using the second one, I am getting the variable name, not the value.

Controller Code:

namespace TestProject.Controllers
{
    public class ContactsController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            Contact contact = new Contact();

            return View(contact);
        }
    }
}

View Code:

@model TestProject.Models.Contact

@{
    ViewBag.Title = "ContactSuccess";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2>Contact Has Been Successfully Added</h2>
<div class="imgContainer">
<img src="~/Content/Images/checkmark" />
</div>

@model.FirstName

Model Code:

namespace TestProject.Models
{
    public class Contact 
    {
        [Required]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        [StringLength(20, MinimumLength = 2, ErrorMessage = "Enter A Valid First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Enter A Valid Last Name")]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        [StringLength(20, MinimumLength = 2)]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Enter A Valid Home Phone Number including area code")]
        [DataType(DataType.PhoneNumber)]
        public string PhoneHome { get; set; }

        [Required(ErrorMessage = "Enter A Valid Cell Phone Number")]
        [DataType(DataType.PhoneNumber)]
        public string PhoneCell { get; set; }

        [Required(ErrorMessage = "Enter A Valid Email Address")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [Required(ErrorMessage = "Enter A Valid Street Address")]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        [StringLength(120, MinimumLength = 4)]
        public string Address { get; set; }

        [Required(ErrorMessage = "Enter A Valid City Name")]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        [StringLength(30, MinimumLength = 2)]
        public string City { get; set; }

        [Required(ErrorMessage = "Enter A Valid State Abbreviation")]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        [StringLength(20, MinimumLength = 2)]
        public string State { get; set; }

        [Required(ErrorMessage = "Enter A Valid 5 Digit Zip Code")]
        [DataType(DataType.PostalCode)]
        public string ZipCode { get; set; }
    }
}

I am using ODataLib 6.6.0 and Microsoft.AspNet.OData 5.2.1 Nuget packages.

I have the following code which creates a custom serializer to add a custom annotation to a paged OData feed. The code compiles and is called correctly, all the way through the point of adding the custom instance annotation.

namespace WebApiTest.App_Start
{
    using Microsoft.OData.Core;
    using System.Collections.Generic;
    using System.Web.Http;
    using System.Web.OData.Formatter;
    using System.Web.OData.Formatter.Deserialization;
    using System.Web.OData.Formatter.Serialization;
    using WebApiTest.Controllers;

    public class FormatterConfiguration
    {
        public static void Register(HttpConfiguration config)
        {
            var formatters = ODataMediaTypeFormatters.Create(
                new CustomODataSerializerProvider(),
                new DefaultODataDeserializerProvider());
            config.Formatters.InsertRange(0, formatters);
        }
    }

    public class CustomODataSerializerProvider : DefaultODataSerializerProvider
    {
        private readonly CustomODataFeedSerializer _feedSerializer;

        public CustomODataSerializerProvider()
        {
            _feedSerializer = new CustomODataFeedSerializer(this);
        }

        public override ODataEdmTypeSerializer GetEdmTypeSerializer(Microsoft.OData.Edm.IEdmTypeReference edmType)
        {
            var serializer = base.GetEdmTypeSerializer(edmType);
            var feedSerializer = serializer as ODataFeedSerializer;
            if (feedSerializer != null)
            {
                return _feedSerializer;
            }
            return serializer;
        }
    }

    public class CustomODataFeedSerializer : ODataFeedSerializer
    {
        public CustomODataFeedSerializer(ODataSerializerProvider serializerProvider)
            : base(serializerProvider)
        {
        }

        public override Microsoft.OData.Core.ODataFeed CreateODataFeed(System.Collections.IEnumerable feedInstance, Microsoft.OData.Edm.IEdmCollectionTypeReference feedType, ODataSerializerContext writeContext)
        {
            ODataFeed feed = base.CreateODataFeed(feedInstance, feedType, writeContext);
            var result = feedInstance as IPageResultCustom;
            if (result != null)
            {
                var value = new ODataComplexValue();
                var properties = new List<ODataProperty>();
                properties.Add(new ODataProperty() { Name = "CustomProperty", Value = result.CustomProperty });
                value.Properties = properties;
                feed.InstanceAnnotations.Add(new ODataInstanceAnnotation("org.CustomComplexValue", value));
            }
            return feed;
        }
    }
}

I issue a request to a feed including the HTTP headers Prefer: odata.include-annotations="*" and Content-Type=application/json in the request. Yet, I get no annotations in the response.

Tracing through the OData framework code, the internal property Func<string,bool> Microsoft.OData.Core.MessageWriterSettings.ShouldInludeAnnotations is never set when creating the ODataMessageWriters and therefore, the ODataJsonLightValueSerializer.ShouldSkipAnnotation(string name) method call always returns true.

It seems like a bug in the framework. Am I missing something in my configuration or request?

Edit Aug 7, 2014

The issue appears to be related to the bug https://aspnetwebstack.codeplex.com/workitem/1880.

A workaround was suggested that involved creating a custom ODataMediaTypeFormatter. However, ODataMediaTypeFormatters.Create is not generic and recreating it involves too many dependencies that are internally scoped. This workaround is a daunting task at a minimum. It appears that the realistic limit of extensibility on ODataMediaTypeFormatter is confined to implementing custom serializers and/or deserializers.

I have created a web api in asp.net mvc5. And now through the separate mvc application in same platform i want to register an account and login through it. How will i be able to register as well as login through my mvc application? The api provides the token in json after passing these values in localhost:35237/Token through post method

grant_type=password
Username=Chandan
Password=chandan123

and in return i get the json value with access-token, token_type, expires_in, userName, .issued, .expires.

{
access_token: "tR4lyDuXiohwmywmqyACV2DOG188M5vPKVBVyq9ffQjOwuSuzYolV8BK554FcUIu8v0O1h08rL_hZO91x-1Y8N6r4GbqSrqnfQzdOhPbXKCDVzt9z9ro2mDXwOzg0-AkcVlE4AAblHmUNExPQjNLmtiEtK0TYPW_RK6Bjf5QNTy4NTT22fKZJAbFnLojsZnWh1ptLDtTVan-XSQH7uEbW6HLceEuiJSAtFfqTFlkiT6eYA7IuGswmHoxeOQ2ED9Aw_Q7fdY23cylFJDxsC5ZLK7kkweVyTYEqagLl0Q3xSSsE2n2HY17YSy0l3dIX4RLJ9axy28a8LS6rJs33Aag9bTVs2V8C55xwqbPU49r8Ro5Hnq3C5mbeoqikv9mj41FBHRG1H9a-tAZ24bP0L95CsCUlUDSFuHRaaouN4JN3Jo"
token_type: "bearer"
expires_in: 2591999
userName: "Chandan"
.issued: "Sun, 17 Aug 2014 21:26:19 GMT"
.expires: "Tue, 16 Sep 2014 21:26:19 GMT"
}

Detailed information will be more helpful. Thank You in advance.

I am new to using the Grid.MVC feature. After looking at some of the examples i really like the grid and I was wondering how i could implement a solution similar to the example on the documentation page. I have the grid created and am trying to add the details to the right of the grid as shown but I not sure how to implement it. Here is the exmaple I am trying to accomplish with MVC and Razor. http://gridmvc.azurewebsites.net/

Here is what I have in my view:

@using GridMvc.Html
@using GridMvc.Sorting
@model IEnumerable<EmployeeManagement.Models.EmployeeMaster>

@{
    ViewBag.Title = "Index";
}
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="@Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" />
    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" />
    <script src="@Url.Content("~/Scripts/jquery-1.9.0.min.js")"></script>
    <script src="@Url.Content("~/Scripts/gridmvc.min.js")"></script>
    <title>Index</title>
    <script>
        pageGrids.employeeGrid.onRowSelect(function (e) {
            $.post("/Manage/GetEmployee?id=" + e.row.EmployeeNumber, function (data) {
                if (data.Status <= 0) {
                    alert(data.Message);
                    return;
                }
                $("#employee-content").html(data.Content);
            });
        });

    </script>
</head>



<div id="grid" style="float: left">
    @Html.Grid(Model).Columns(columns =>
{

    columns.Add(o => o.LastName)
            .Titled("Last Name")
            .SetWidth(10);

    columns.Add(o => o.FirstName)
            .Titled("First Name")
            .SortInitialDirection(GridSortDirection.Descending)
            .SetWidth(20);

    columns.Add(o => o.Initials)
            .Titled("Initials").SetWidth(20);

    columns.Add(o => o.Branch)
            .Titled("Branch").SetWidth(20);

    columns.Add(o => o.StatusFlag)
        .Titled("Status").SetWidth(20);

    columns.Add(o => o.EmployeeNumber)
            .Titled("Employee NO")
            .SetWidth(10);

    columns.Add()
        .Encoded(false)
        .Sanitized(false)
        .SetWidth(30)
        .RenderValueAs(d =>
            @<b>
                @Html.ActionLink("Edit", "Edit")
            </b>);
}).SetRowCssClasses(item => (bool)item.StatusFlag ? "success" : "danger").Sortable().Filterable().WithMultipleFilters().Named("employeeGrid")

</div>
<div id="details" style="float:left">
    <h2>Details</h2>
    <div id="employee-content">
        Click on an employee to get their detailed record.
    </div>

</div>

Here is GetEmployee Method looks like:

    [HttpPost]
    public EmployeeMaster GetEmployee(int id)
    {
        var e = EmployeeDb.EmployeeMasters.FirstOrDefault(x => x.EmployeeNumber == id);
        return e;
    }

I am using Entity Framework 6.1 in asp.net webform project. When I try to add new object into projects, I am getting Ambiguous match found exception. I am using database first approach. I do not any manipulation in created models. I have read some questions about that problem. General cause is same named properties and navigation in class. I did not found any same named property.

Can you tell me what i missed?

Thank you

Code:

projects m_NewProject = new projects();
decimal m_CompanyRef = MemberHelperC.getUser().CompanyRef;
DateTime m_EndDate = GeneralHelperC.getCompanyDateTime().AddDays(5);
DateTime m_StartDate = GeneralHelperC.getCompanyDateTime();
customers m_Customer = myEntity.customers.Where(xXx => xXx.CompanyRef == m_CompanyRef).FirstOrDefault();
m_NewProject.ProjectLeadRef = MemberHelperC.getUserID();
m_NewProject.ProjectName = m_ProjectName;
m_NewProject.ProjectStatus = Convert.ToByte(1);
m_NewProject.SourceLangRef = Convert.ToDecimal(comboSourceLang.SelectedValue);
m_NewProject.TargetLangRef = Convert.ToDecimal(comboTargetLang.SelectedValue);
m_NewProject.DomainRef = Convert.ToDecimal(1);
m_NewProject.ProjectYear = GeneralHelperC.getCompanyDateTime()/*DateTime.Now*/.Year;
m_NewProject.EndDate = m_EndDate;
m_NewProject.StartDate = m_StartDate;
m_NewProject.TaskStepNameRef = m_TaskStepNameID;
m_NewProject.CustomerRef = Convert.ToDecimal(m_Customer.RID);
Random m_Random = new Random();
m_NewProject.ProjectUniqueID = m_Random.Next(0, 99999999);
m_NewProject.ProjectTBX = m_Dictionary.RID;
myEntity.projects.Add(m_NewProject);//exception occur this method
myEntity.SaveChanges();

Object Class:

public partial class projects
{
    public projects()
    {
        this.projectnotes = new HashSet<projectnotes>();
        this.projectpriceoffers = new HashSet<projectpriceoffers>();
        this.projectreferencedoc = new HashSet<projectreferencedoc>();
        this.projects1 = new HashSet<projects>();
        this.taskstepexceptions = new HashSet<taskstepexceptions>();
        this.tbxrelation = new HashSet<tbxrelation>();
        this.tmproject = new HashSet<tmproject>();
        this.tmrelation = new HashSet<tmrelation>();
        this.wizardprojecttasks = new HashSet<wizardprojecttasks>();
        this.works = new HashSet<works>();
    }

    public decimal RID { get; set; }
    public string ProjectName { get; set; }
    public decimal ProjectStatus { get; set; }
    public decimal ProjectLeadRef { get; set; }
    public System.DateTime EndDate { get; set; }
    public System.DateTime StartDate { get; set; }
    public int ProjectYear { get; set; }
    public int ProjectUniqueID { get; set; }
    public Nullable<decimal> ParentProjectRef { get; set; }
    public Nullable<decimal> TMXHeaderRef { get; set; }
    public decimal SourceLangRef { get; set; }
    public decimal TargetLangRef { get; set; }
    public decimal DomainRef { get; set; }
    public decimal TaskStepNameRef { get; set; }
    public Nullable<decimal> ProjectTBX { get; set; }
    public Nullable<decimal> CustomerRef { get; set; }

    public virtual customers customers { get; set; }
    public virtual domainname domainname { get; set; }
    public virtual language language { get; set; }
    public virtual language language1 { get; set; }
    public virtual ICollection<projectnotes> projectnotes { get; set; }
    public virtual ICollection<projectpriceoffers> projectpriceoffers { get; set; }
    public virtual ICollection<projectreferencedoc> projectreferencedoc { get; set; }
    public virtual ICollection<projects> projects1 { get; set; }
    public virtual projects projects2 { get; set; }
    public virtual projectstatus projectstatus1 { get; set; }
    public virtual tasknames tasknames { get; set; }
    public virtual tbxdictionary tbxdictionary { get; set; }
    public virtual tmxheaderinterface tmxheaderinterface { get; set; }
    public virtual users users { get; set; }
    public virtual ICollection<taskstepexceptions> taskstepexceptions { get; set; }
    public virtual ICollection<tbxrelation> tbxrelation { get; set; }
    public virtual ICollection<tmproject> tmproject { get; set; }
    public virtual ICollection<tmrelation> tmrelation { get; set; }
    public virtual ICollection<wizardprojecttasks> wizardprojecttasks { get; set; }
    public virtual ICollection<works> works { get; set; }
}
}

I use the MachineKey.Protect() method to encrypt the id passed as a query string in my asp.net MVC application.

Here's the code I use to encrypt/decrypt:

public static string Encrypt(this string expression)
{
    if (string.IsNullOrEmpty(expression))
        return string.Empty;

    byte[] stream = Encoding.Unicode.GetBytes(expression);
    byte[] encodedValue = MachineKey.Protect(stream);            
    return HttpServerUtility.UrlTokenEncode(encodedValue);            
}

public static string Decrypt(this string expression)
{
    if (string.IsNullOrEmpty(expression))
        return string.Empty;

    byte[] stream = HttpServerUtility.UrlTokenDecode(expression);
    byte[] decodedValue = MachineKey.Unprotect(stream);
    return Encoding.Unicode.GetString(decodedValue);
}

And, here is the MachineKey element in my web.config file:

<system.web>
    .
    .
    .
    <machineKey validationKey="xxx" decryptionKey="xxx" validation="SHA1" decryption="AES" />
</system.web>

The problem is the encrypted id is not persistent. Every time I call the method, I get a new encrypted expression. How do I make it persistent?

I have a website hosted on a Windows Server 2008, using IIS 7.5.

Problem:

Around three times a day, my website is goes down. When I try to open or browse it, I get a 404 Not Found.

Temporary Fix:

I've found that I can make it work if I edit my web.config file and upload it to server again with FTP.

<compilation debug="false" targetFramework="4.0" />

It works if I toggle the value of the debug attribute of the compilation element. This brings the site back online again for five to six hours.

I'm not sure whether this is an issue with the code, the server, or the client.

Has anyone experienced any similar behavior? Is there a more permanent solution than having to change that attribute every few hours?

I am using this: http://www.codeproject.com/Articles/638674/Full-calendar-A-complete-web-diary-system-for-jQue

to add a calender to my website (asp.net mvc)

I'm new to mvc and I have this view:

@{
    ViewBag.Title = "MenuPlanner";
}

@section scripts{
@Scripts.Render(@Url.Content("~/bundles/jqueryui"))
@Scripts.Render(@Url.Content("~/bundles/jquery"))
    <script type="text/javascript">
        $(document).ready(function () {

            var sourceFullView = { url: '/Home/GetDiaryEvents/' };
            var sourceSummaryView = { url: '/Home/GetDiarySummary/' };
            var CalLoading = true;

            $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                defaultView: 'agendaDay',
                editable: true,
                allDaySlot: false,
                selectable: true,
                slotMinutes: 15,
                events: '/Home/GetDiaryEvents/',
                eventClick: function (calEvent, jsEvent, view) {
                    alert('You clicked on event id: ' + calEvent.id
                        + "\nSpecial ID: " + calEvent.someKey
                        + "\nAnd the title is: " + calEvent.title);

                },

                eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc) {
                    if (confirm("Confirm move?")) {
                        UpdateEvent(event.id, event.start);
                    }
                    else {
                        revertFunc();
                    }
                },

                eventResize: function (event, dayDelta, minuteDelta, revertFunc) {

                    if (confirm("Confirm change appointment length?")) {
                        UpdateEvent(event.id, event.start, event.end);
                    }
                    else {
                        revertFunc();
                    }
                },



                dayClick: function (date, allDay, jsEvent, view) {
                    $('#eventTitle').val("");
                    $('#eventDate').val($.fullCalendar.formatDate(date, 'dd/MM/yyyy'));
                    $('#eventTime').val($.fullCalendar.formatDate(date, 'HH:mm'));
                    ShowEventPopup(date);
                },

                viewRender: function (view, element) {

                    if (!CalLoading) {
                        if (view.name == 'month') {
                            $('#calendar').fullCalendar('removeEventSource', sourceFullView);
                            $('#calendar').fullCalendar('removeEvents');
                            $('#calendar').fullCalendar('addEventSource', sourceSummaryView);
                        }
                        else {
                            $('#calendar').fullCalendar('removeEventSource', sourceSummaryView);
                            $('#calendar').fullCalendar('removeEvents');
                            $('#calendar').fullCalendar('addEventSource', sourceFullView);
                        }
                    }
                }

            });

            CalLoading = false;


        });

        $('#btnInit').click(function () {
            $.ajax({
                type: 'POST',
                url: "/Home/Init",
                success: function (response) {
                    if (response == 'True') {
                        $('#calendar').fullCalendar('refetchEvents');
                        alert('Database populated! ');
                    }
                    else {
                        alert('Error, could not populate database!');
                    }
                }
            });
        });

        $('#btnPopupCancel').click(function () {
            ClearPopupFormValues();
            $('#popupEventForm').hide();
        });

        $('#btnPopupSave').click(function () {

            $('#popupEventForm').hide();

            var dataRow = {
                'Title': $('#eventTitle').val(),
                'NewEventDate': $('#eventDate').val(),
                'NewEventTime': $('#eventTime').val(),
                'NewEventDuration': $('#eventDuration').val()
            }

            ClearPopupFormValues();

            $.ajax({
                type: 'POST',
                url: "/Home/SaveEvent",
                data: dataRow,
                success: function (response) {
                    if (response == 'True') {
                        $('#calendar').fullCalendar('refetchEvents');
                        alert('New event saved!');
                    }
                    else {
                        alert('Error, could not save event!');
                    }
                }
            });
        });

        function ShowEventPopup(date) {
            ClearPopupFormValues();
            $('#popupEventForm').show();
            $('#eventTitle').focus();
        }

        function ClearPopupFormValues() {
            $('#eventID').val("");
            $('#eventTitle').val("");
            $('#eventDateTime').val("");
            $('#eventDuration').val("");
        }

        function UpdateEvent(EventID, EventStart, EventEnd) {

            var dataRow = {
                'ID': EventID,
                'NewEventStart': EventStart,
                'NewEventEnd': EventEnd
            }

            $.ajax({
                type: 'POST',
                url: "/Home/UpdateEvent",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(dataRow)
            });
        }

</script>


}


<div class="container">

    <div>
        <a href="#" id="btnInit" class="btn btn-secondary">Initialise database!</a>
    </div>

    <div id='calendar' style="width:65%"></div>

</div>


<div id="popupEventForm" class="modal hide" style="display: none;">
    <div class="modal-header"><h3>Add new event</h3></div>
    <div class="modal-body">
        <form id="EventForm" class="well">
            <input type="hidden" id="eventID">
            <label>Event title</label>
            <input type="text" id="eventTitle" placeholder="Title here"><br />
            <label>Scheduled date</label>
            <input type="text" id="eventDate"><br />
            <label>Scheduled time</label>
            <input type="text" id="eventTime"><br />
            <label>Appointment length (minutes)</label>
            <input type="text" id="eventDuration" placeholder="15"><br />
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" id="btnPopupCancel" data-dismiss="modal" class="btn">Cancel</button>
        <button type="button" id="btnPopupSave" data-dismiss="modal" class="btn btn-primary">Save event</button>
    </div>
</div>

Problem is that I am getting an error:

Uncaught TypeError: undefined is not a function

at this line:

 $('#calendar').fullCalendar({

and I have no idea why.

Any ideas please?

I know this issue has arisen many times on Stack Overflow. I've looked at them, but believe this to be unique:

  • I'm not using .Single() or .SingleOrDefault() in any LINQ expressions
  • I checked my models for duplicates, like "Id" and "ID", there are none
  • This happens onload of any Kendo UI MVC grids, on any table, on any page in my website that has such a grid, and we have several different pages, each with their own grids

Just some history, we just changed some foreign keys to Guids from IDs (ints) in order to point them at different tables in the database than they are currently in the code. Models were updated, accordingly. We also added a view for the Kendo grid to be pointed at, and this was changed in the view. But even grids that have nothing to do with the original or new SQL view/C# models seem to have been affected. Now, during this phase:

public OurDatabase(bool enableLazyLoading=true)
    : base("name=OurDBContext")
{
    Database.SetInitializer<OurDatabase>(null);
    ((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = enableLazyLoading;
    ((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = enableLazyLoading;
}

It keeps giving the error "Sequence contains more than one matching element". It will highlight on that middle line with that error.

Can something changing in the database cause this? Code that once worked, and hasn't been changed since that time, now does not, and this is very confusing.

I have 2 different layouts in my project that based on the view that is called, I will tell the view which layout to use. I'm having an issue where my first layout is rendered (my landing page), I render a certain set of scripts/styles. Once I want to render my 2nd layout, the browser is holding on to all the styles/scripts from my previous layout. Is there anyway to decouple those scripts/styles when changing layouts?

I have a web application being developped on Windows 8.1, .net 4.5.1, IIS 8.5 (under Integrated AppPool), Visual Studio 2013 Over the default template that includes asp.net Identity, Owin, etc. and locally works fine.

then I Uploaded it to a windows server 2008 & IIS 7.5 (Integrated Pipeline) Host and I get:

This operation requires IIS integrated pipeline mode.

Exception Details: System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.

Stack Trace:

[PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.]
System.Web.HttpResponse.get_Headers() +9687046
System.Web.HttpResponseWrapper.get_Headers() +9
Microsoft.Owin.Host.SystemWeb.OwinCallContext.CreateEnvironment() +309
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.GetInitialEnvironment(HttpApplication application) +246
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.PrepareInitialContext(HttpApplication application) +15
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(Object sender, EventArgs e, AsyncCallback cb, Object extradata) +265
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +285
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I have searched a lot and unable to find anything except for directing the reader to change the pipeline from classic mode to integrated mode that which I already did with no luck..

What can I do to fix the problem? Does "Microsoft.Owin.Host.SystemWeb" not like IIS 7.5, or server 2008 or me :) ?

I'd like to upload images from an uri postet to an asp.net mvc5 controller to azure blob storage. I already got it working with HttpPostedFileBase, like this. Can I somehow get the memory stream from an image uri?

HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
var imgFile = System.Drawing.Image.FromStream(hpf.InputStream, true, true);
CloudBlockBlob blob = coversContainer.GetBlockBlobReference("img.jpg");
MemoryStream stream = new MemoryStream();
imgFile.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
blob.UploadFromStream(stream);

  • How can I get the id of the currently logged in user in MVC 5? I tried the StackOverflow suggestions, but they seem to be not for MVC 5.
  • Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a User should have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?

I'm using "Individual User Accounts" from the MVC template.

Tried these:

'Membership.GetUser()' is null.

I run the Web Application HomeController.Index() action is run. Then I go to Person.Index()(it is at the bottom of this post) via browser then and only then Migrations.Configuration.Seed() is invoked. But I want it to happen at the application start.

Configuration:

namespace WebApplication2.Migrations {
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext> {
        public Configuration() {
            AutomaticMigrationsEnabled = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {

            System.Diagnostics.Debug.WriteLine("Seed started");
            //  System.Data.Entity.DropCreateDatabaseAlways<ApplicationDbContext> s = new DropCreateDatabaseAlways<ApplicationDbContext>();
            // s.InitializeDatabase(context);
            if (!context.Persons.Any()) {
                var persons = new List<Person> { 
             new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
             new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
            };

                persons.ForEach(person => context.Persons.AddOrUpdate(person));
                context.SaveChanges();
            }

            if (!context.Meetings.Any()) {
                var meetings = new List<Meeting>{
                new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
            };


                meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
                context.SaveChanges();
            }
            if (!context.Statuses.Any()) {
                var statuses = new List<Status> {
                new Status{Name = "OK"},
                new Status {Name = "NOT_OK"}
            };



                statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
                context.SaveChanges();

            }
            //Users Seeding

            if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("USER SEED");
                try {
                    var store = new UserStore<ApplicationUser>(context);
                    var manager = new UserManager<ApplicationUser>(store);
                    //why user is not created
                    var user1 = new ApplicationUser { UserName = "admin", Email = "informatyka4444@wp.pl" };
                    var user2 = new ApplicationUser { UserName = "emp", Email = "informatyka4444@wp.pl" };
                    manager.Create(user1, "admin");
                    manager.Create(user2, "emp");

                    context.SaveChanges();
                } catch (Exception e) { System.Diagnostics.Debug.WriteLine("THERE WAS AN EXCEPTION"); }
            }


        }
    }
}

IdentityModels.cs

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace WebApplication2.Models {
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false) {
            System.Diagnostics.Debug.WriteLine("CONSTRCTOR");
          // Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
        }



        public DbSet<Person> Persons { get; set; }
        public DbSet<Meeting> Meetings { get; set; }
        public DbSet<Status> Statuses { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public static ApplicationDbContext Create() {
            return new ApplicationDbContext();
        }
    }
}

Global.asax:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Migrations;
using WebApplication2.Models;


namespace WebApplication2 {
    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            System.Diagnostics.Debug.WriteLine("Application_Start");
            Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

}

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20140711041006.mdf;Initial Catalog=aspnet-WebApplication2-20140711041006;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <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.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
   <!-- <contexts>
     <context type="WebApplication2.Models.ApplicationDbContext, WebApplication2">
        <databaseInitializer type="WebApplication2.Migrations.Configuration, WebApplication2" />
      </context>
    </contexts>-->
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

The Person controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers {
    public class PersonController : Controller {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Person
        public ActionResult Index() {
            return View(db.Persons.ToList());
        }

        // GET: Person/Details/5
        public ActionResult Details(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (person == null) {
                return HttpNotFound();
            }
            return View(person);
        }

        // GET: Person/Create
        public ActionResult Create() {
            return View();
        }

        // POST: Person/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FirstName,LastName,CellNumber,SecondaryPhoneNumber,Address,BirthDate,Pesel,Notes")] Person person) {
            if (ModelState.IsValid) {
                db.Persons.Add(person);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(person);
        }

        // GET: Person/Edit/5
        public ActionResult Edit(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (person == null) {
                return HttpNotFound();
            }
            //Moj kod
            //Album album = db.Albums.Find(id);
            //ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
            //ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
            ViewBag.StatusId = new SelectList(db.Statuses, "Id", "Name", person.StatusId);



            //Moj kod
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,CellNumber,SecondaryPhoneNumber,Address,BirthDate,Pesel,Notes,StatusId")] Person person) {
            if (ModelState.IsValid) {
                db.Entry(person).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(person);
        }

        // GET: Person/Delete/5
        public ActionResult Delete(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (person == null) {
                return HttpNotFound();
            }
            return View(person);
        }

        // POST: Person/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id) {
            Person person = db.Persons.Find(id);
            db.Persons.Remove(person);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing) {
            if (disposing) {
                db.Dispose();
            }
            base.Dispose(disposing);
        }


        public string formatPhoneNumber(string number) {
            Regex rgx = new Regex("[^0-9]");
            return rgx.Replace(number, "");
        }

        public ActionResult Call(int id, string number) {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            string formattedNumber = "tel:+48" + formatPhoneNumber(number);
            System.Diagnostics.Debug.WriteLine("NUMBER " + formattedNumber);
            proc.StartInfo.FileName = formattedNumber;
            proc.Start();
            Person person = db.Persons.Find(id);
            return RedirectToAction("Edit", new Person { Id = id });
        }
    }
}