vendredi 31 juillet 2015

New Line Character in mvc3 model In errormesaage

I'm using MVC 3 web application and i have give error message with
tag but br tag not working in mvc 3 if i used mvc4 then its working fine below are the code whioch i used.

MODEL :

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

CSHTML :

 <div class="editor-field">
  @Html.PasswordFor(m => m.Password)
  @Html.ValidationMessageFor(m => m.Password)
 </div>

Please help me.

jeudi 30 juillet 2015

What is Dbexception unhandled by user code in Asp.Net Mvc while i am trying to insert values on form?

I have created a form for the submission of values but the error strikes during the post method of that method at db.savechanges() but can't find what's wrong.

dry code from sql to view

I have seven locations and 14 statuses. I've hard-coded a lot of things and I want to make it DRY. I made everything into an int array. I tried to do some studying on enumerator but I wasn't sure on how exactly it'd fit.

At the moment, I need to show every location to count how many units with each status.

"SELECT
SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) AS A
,SUM(CASE WHEN status = 'B' THEN 1 ELSE 0 END) AS B
,SUM(CASE WHEN status = 'C' THEN 1 ELSE 0 END) AS C
,SUM(CASE WHEN status = 'D' THEN 1 ELSE 0 END) AS D
,SUM(CASE WHEN status = 'E' THEN 1 ELSE 0 END) AS E
,SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) AS F
,SUM(CASE WHEN status = 'G' THEN 1 ELSE 0 END) AS G...
FROM TABLE WHERE location1 = @location"
//..
                    int[] result = new int[15];
                    //..
                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    foreach (DataRow dRow in ds.Tables[0].Rows)
                    {
                        result[0] = (int)dRow["A"];
                        result[1] = (int)dRow["B"];
                        result[2] = (int)dRow["C"];
                        result[3] = (int)dRow["D"];
                        result[4] = (int)dRow["E"];
                        //..
                    }
                    return result;

My Controller

    private IEquipmentDapper dapper = new EquipmentDapper();

    public ActionResult Index()
    {
        int[] AllLocationStatuses = dapper.CountAllStatuses();

        ViewBag.TotalA = AllLocationStatuses[0];
        ViewBag.TotalB = AllLocationStatuses[1];
        ViewBag.TotalC = AllLocationStatuses[2];
        ViewBag.TotalD = AllLocationStatuses[3];
        ViewBag.TotalE = AllLocationStatuses[4];
        //..
        int[] Location1Statuses = dapper.CountStatusesByLocation();

        ViewBag.Location1A = Location1Statuses[0];
        ViewBag.Location1B = Location1Statuses[1];
        ViewBag.Location1C = Location1Statuses[2];
        //..

And my view

    <td>Total</td>
    <td><span class="A"></span>@ViewBag.A A</td>
    <td><span class="B"></span>@ViewBag.B B</td>
    <td><span class="C"></span>@ViewBag.C C</td>
    <td><span class="D"></span>@ViewBag.D D</td>

Publishing ASP.NET MVC to Azure -- works locally but not on Azure

I've been investigating this thing for hours but couldn't understand what's the problem causing this behavior.

I have built a simple ASP.NET MVC app to upload and delete photos from a predefined container on the Azure Storage Server. It works perfectly when I run the application on my machine, locally. Also, it works perfectly when I run this on my machine but the Data service is located on Azure.

But, when Publishing the application to Azure, surfing to this website runs to this uninformative error:

Server Error in '/' Application.

Runtime Error

Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".

<!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's configuration tag to point to a custom error page URL.

<!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>

This doesn't tell me anything, also - nothing like this happens when running on my machine with Visual Studio.

If you have any idea what's going on here I'd really appreciate your help, thanks.

Encountered Validation Error in double? datatype in MVC3 C#

Hi guys I am new to Mvc 3 and previously while debugging my Project, I encountered an error in the field of Miles , and a very unusual error appeared that says The field Miles must be a number. upon entering .2 and 135. whereas it will be automatic that the value before and after the decimal point is zero, it is preventing me from saving the values and now I'm here searching for solutions.

I hope someone can help me with this.

This is my code snippet:

<div>
   <div class="label">
      @Html.LabelFor(m => m.Miles) @Html.ValidationMessageFor(m => m.Miles)
   </div>
   <div class="field">
      @Html.TextBoxFor(m => m.Miles)
    </div>
</div>

and here is my datatype in my Model:

public Nullable MILES { get; set; }

mercredi 29 juillet 2015

Does Execuing an application on server reflect on clients machine in asp.net

Suppose I execute an .exe say paint in Server and the client machine doesn't have paint installed (imagine) , will the paint.exe executed from server show on the client machine ? I know its not possible . Need confirmation. Thanks

How do you hide a filename in the url with ASP.NET MVC?

I have a file called "index.html" that I don't want to convert to a View in my project. When I browse to this file, I see:

"http://ift.tt/OLCuVP"

in the browser's address window, but I would instead just like to see:

"mydomain.com"

How can I accomplish this in an ASP.NET MVC project?

Sagepay server (iframe) integration not hitting MVC controller

I have a mvc controller set up to handle the notification request from sagepay, however sagepay does not seem to post to it.

If I create an .aspx page it can post to that fine.

Has anybody got sagepay working with extensionless urls i.e. does sagepay require a file extension or is there something wrong with my controller?

Loop through XML nodes and update each nodes with value from database

I have a XML file like this: I'm creating event node for the number of records i have in the database.

<event_list>
<event>
 <servername></servername>
</event>
<event>
<servername></servername>
</event>
<event>
<servername></servername>
</event>
<event>
<title></title>
</event>
</event_list>

I will get value of servers from database. I'm not able to pass each server name to corresponding node. Instead i'm ending up updating all fur nodes with same server name with following function:

public static XmlDocument OpenXmlFile(string fileLocation,     List<ServiceObjects> Sqldata)
{

 eventlist_location = @"C:\Temp\List.xml";

 XMLFileManagement FM = new XMLFileManagement();

FM.CreateXML(eventlist_location);

XmlDocument template = new XmlDocument();

template.Load(fileLocation);

XmlDocument Neweventlist = new XmlDocument();

for (int i = 0; i < Sqldata.Count; i++)

{

 XmlNamespaceManager namespaces = new     XmlNamespaceManager(template.NameTable);

namespaces.AddNamespace("n", "http://www.hp.com/2009");

XmlNode node = template.SelectSingleNode(".//n:event", namespaces);

Neweventlist.Load(eventlist_location);

     Neweventlist.DocumentElement.AppendChild(Neweventlist.ImportNode(template.DocumentElement, true));

 XmlNamespaceManager nsmgr = new XmlNamespaceManager(Neweventlist.NameTable);

namespaces.AddNamespace("abc", "http://ift.tt/1MxC40E");

 foreach (XmlNode Xnode in Neweventlist.SelectNodes(".//*", namespaces))

{

if (Xnode.Name == "servername")

Xnode.InnerText = Sqldata.FirstOrDefault().ServerName.ToString();



}
Neweventlist.Save(eventlist_location);

}

return Neweventlist;

}

Web API 2 - Controller - Custom AuthorizeAttribute

I need to add Security to my Web API calls. As I will need custom validation, I decided to create a custom AuthorizeAttribute (I will need to be able to check the current principal).

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CliCWebAuthorize : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK);

        using (var mgr = AuthenticationManager.CreateNew())
        {
            if (!mgr.IsAllowedAccess(actionContext.RequestContext.Principal))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }

        var isAuthorized = actionContext.Response.StatusCode == HttpStatusCode.OK;

        return isAuthorized;
    }        
}

I have a Controller action defined like this:

[HttpGet]
[CliCWebAuthorize]
public IHttpActionResult TestPrdAccess()
{
    return Ok(true);
}

If I access the associated url, the debugger breaks at the custom attribute code (and goes through the code without error), but regardless of true or false, it doesn't go into the Controller method. Nor do I see anything on the browser.

Any help?

not able to send message via whatsapp API using asp.net mvc3

when i'm trying to send a message using c# with whatsApp API ,

it shows login Failed. The error is not-authorized. Please help me. Thanks in advance.

code:

  WhatsApp wa = new WhatsApp(from, "mypassword", "Rajat", false, false);

        wa.OnConnectSuccess += () =>
            {
                TempData["connect"] = "Connected to whatsapp";

                wa.OnLoginSuccess += (PhoneNumber, data) =>
                    {
                        wa.SendMessage(to, msg);
                        TempData["sent"] = "Message Sent";
                    };
                wa.OnLoginFailed += (data) =>
                    {
                        TempData["fail"] = data;
                    };
                wa.Login();
            };

        wa.OnConnectFailed += (ex) =>
            {
                TempData["failure"] = "Connection Failed";
            };

        wa.Connect();

        return View();

html dropdown option background color issue in chrome Browser

I have web based application in MVC4 which having a drop down with 302 records. On drop down item selection I have set color like Gray. But that Gray color will spread in whole Drop down including option tag too.

Here, is my css class

select
{
    width: 100px;
    background-color: #717171;
    color: #fff;
}
.toolbar select > option
{
    background-color: #fff;
    color: #000;
}

.toolbarDropdownSelected
{
    background-color: #8B5052 !important;
}

Till, 300 records everything is look good in Chrome browser but if records are exceed than 300 then Gray color spread in whole Dropdown including options in case of Chrome Browser.

In Firefox browser everything is look good if records are exceed than 300.

I have attached screenshot. Please have a look. Please help.enter image description here

Sub Domain implementation In MVC 5 Application

We are developing a MVC 5 application. Suppose the main site is like www.sport.com

Now we want to create 3 sub domain like cricket.sport.com, football.sport.com and hockey.sport.com

Most of the functionality will be same for this 3 sub-sites.

We have implemented 2 approaches :

Approach 1: Create 3 area for each cricket/football/hockey. But this will create code redundancy. So whenever request comes from URL we check and forward request to specific area.

Approach 2 : Create Single Controller - Check URL SubDomain and redirect depending upon each request and display specific view. In this approach, each time we need to check request sub domain and forward to same.

What is best possible way to implement sub domain in MVC application?

We want to deploy this site on Windows Azure.

mardi 28 juillet 2015

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,

Example, Before removing and replacing the Url:

http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15

And After Removing and replacing the url , it goes like this:

http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615

This is my Code Snippet:

var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
                    var regex = /(\&|&)actionMe=reload&Id=/;
                    var location = window.location.href;
                    if (regex.test(location)) {
                        window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
                    }

                }

Thanks for Answering guys:)

Implement Remember me and copy paste url in MVC3

The requirement is implement "Remember Me" and "Copy Paste url on browser" functionality using MVC3.

  1. I am using Active Directory (LDAP) for authenticate user, on success create Cookies and store a value.
  2. On NEXT visit check for cookies values not null and return to requested url or else return to Login Page.

I am able to authenticate logged in user using Active Directory.

Need help to implement "Remember Me" and "Copy Paste url on browser" functionality using MVC3.

lundi 27 juillet 2015

Cannot perform run time binding on a null reference in layout file on action link

Sir i have this error "Cannot perform run time binding on a null reference" in the following line of code in master layout file

  • @Html.ActionLink("Edit Profile", "Edit_Profile", new { id = Model.lwr_id })
  • @Html.ActionLink("Profile", "Lwr_Details", new { id = Model.lwr_id })
  • @Html.ActionLink("Add New Record", "AddNewRecord", new { id = Model.lwr_id })
  • @Html.ActionLink("Account Setting", "Setting")
  • @Html.ActionLink("SignOut", "signOut")
  • this file is private layout file which is accessible after login by lawyer ...i tried to solve it but i cont understand it what is the problem.

Can you use @model like @ViewBag?

So I have a question about model in ASP.NET MVC. I know I can use a ViewBag like this: <h1> @ViewBag.Question </h1> and it would display the text in @ViewBag.Question. Can I use @model in the same way? I have tried using it in the same context, <h1> @Model.Question </h1> but the view throws an error. How can I display the text of a model property inside an html element?

Two different actions on same view in mvc3 with razor

I have created one application with mvc3 (Razor) named studentApp. i have one page that is index page. I want to add two actions on the same page.

Action 1: Insert new student.
Action 2: Search the student.

So how should i maintain the two different actions on same view.

dimanche 26 juillet 2015

Related posts using tags and titles

I am trying to make my own CMS in ASP.net MVC5. So, I have over 100 topics in my DB table so far, and each topic have 5 tags. Now I want to show related posts on each topic post page (like wordpress YARPP plugin).

I just need a little direction on how I should achieve this. Looking forward to the suggestions. Thanks

samedi 25 juillet 2015

Why auto break occurs in VS2010 while running MVC3 application on closing browser and this too long message on VS?

I debugged asp.net mvc 3 application and when just closing the browser only the visual studio breaks the application and displays the message as shown below: 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.exe', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\WebDev.WebHost40\v4.0_10.0.0.0__b03f5f7f11d50a3a\WebDev.WebHost40.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Caching\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.Caching.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Build.Utilities.v4.0\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Utilities.v4.0.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.JScript\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.JScript.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Users\Ashok Bhattarai\AppData\Local\Temp\Temporary ASP.NET Files\root\76d02aef\df738d0d\assembly\dl3\39455804\a6533f86_5bc7d001\EntityFramework.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Users\Ashok Bhattarai\AppData\Local\Temp\Temporary ASP.NET Files\root\76d02aef\df738d0d\assembly\dl3\1aaafdda\3032de87_5bc7d001\MVC3Demo.dll', Symbols loaded. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Loader\v4.0_1.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Loader.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Deployment\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Deployment.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Abstractions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Abstractions.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Helpers\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.Helpers.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Routing\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Routing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Mvc\v4.0_3.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml\v4.0_4.0.0.0__b77a5c561934e089\System.Xaml.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Runtime\v4.0_2.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Runtime.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Web.Infrastructure\v4.0_1.0.0.0__31bf3856ad364e35\Microsoft.Web.Infrastructure.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Tracing\v4.0_2.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Tracing.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.RegularExpressions\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.RegularExpressions.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.Wrapper.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.Services.Design\v4.0_4.0.0.0__b77a5c561934e089\System.Data.Services.Design.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Users\Ashok Bhattarai\AppData\Local\Temp\Temporary ASP.NET Files\root\76d02aef\df738d0d\App_global.asax.6hu2wdf7.dll', Symbols loaded. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DataVisualization\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DataVisualization.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Security\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Security.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Internals.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml.Hosting\v4.0_4.0.0.0__31bf3856ad364e35\System.Xaml.Hosting.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transactions.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\Microsoft.VisualBasic.Activities.Compiler\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualBasic.Activities.Compiler.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.DurableInstancing\v4.0_4.0.0.0__31bf3856ad364e35\System.Runtime.DurableInstancing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.SqlXml\v4.0_4.0.0.0__b77a5c561934e089\System.Data.SqlXml.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Net.Http\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Net.Http.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Razor\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.Razor.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Build.Framework\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Framework.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Workflow.ComponentModel\v4.0_4.0.0.0__31bf3856ad364e35\System.Workflow.ComponentModel.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Workflow.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Workflow.Activities.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Workflow.Runtime\v4.0_4.0.0.0__31bf3856ad364e35\System.Workflow.Runtime.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.Entity\v4.0_4.0.0.0__b77a5c561934e089\System.Data.Entity.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Mobile\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Deployment\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Deployment.dll' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'Anonymously Hosted DynamicMethods Assembly' 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Dynamic\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Dynamic.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Users\Ashok Bhattarai\AppData\Local\Temp\Temporary ASP.NET Files\root\76d02aef\df738d0d\App_Web_ey0gz5jp.dll', Symbols loaded. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Users\Ashok Bhattarai\AppData\Local\Temp\Temporary ASP.NET Files\root\76d02aef\df738d0d\App_Web_ygwvhpoi.dll', Symbols loaded. 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\Users\Ashok Bhattarai\AppData\Local\Temp\Temporary ASP.NET Files\root\76d02aef\df738d0d\App_Web_k13bbru2.dll', Symbols loaded. The thread 0x950 has exited with code 0 (0x0). The program '[4464] iexplore.exe: Script program' has exited with code 0 (0x0). The program '[4940] WebDev.WebServer40.EXE: Managed (v4.0.30319)' has exited with code 0 (0x0). The program '[4940] WebDev.WebServer40.EXE: Program Trace' has exited with code 0 (0x0).

Can i install visual studio 2010 & 2013 in the same computer?

I am currently doing MVC 3 project which VS2013 doesnot support, so I am installing VS2010 and for my learning purpose I need VS2013 to install to run MVC5. Any right guide for installation, will MSSQL Server 2012 works for both IDE. So any suggestions?

vendredi 24 juillet 2015

MVC Controller Param using list of objects. Odd behaviour

So I was wondering if I'm missing something here or if MVC just can do this. Say I have this class:

public class Stuff
{
    public string Thing1 { get; set; }
    public string Thing2 { get; set; }
    public string Thing3 { get; set; }
}

And this is used in my controller like so:

private ActionResult Something(List<Stuff> stuff)...

Now how come when I execute this link:
.../#Tester/Something?Thing1=hello&Thing2=world&Thing3=WachuUpTo
The url params don't bind to the controllers List of items. But if I reconfigure my class to look like this:

public class Stuff
{
    public List<string> Thing1 { get; set; }
    public List<string> Thing2 { get; set; }
    public List<string> Thing3 { get; set; }
}

Then make the controller param a single object:

private ActionResult Something(Stuff stuff)...

It works. Thing1, Thing2, Thing3 each have one element in the list with the correct values in each. Now why does this way work but the other doesn't?
I'd much prefer this first way because it's simpler since I don't have to worry about adding logic to make sure the number of elements in each sublist are the same. Working with MVC 3 btw. Also I'm trying to do this using url params if possible.

passing Json Array to MVC Controller Action returning Null

passing Json Array to MVC Controller Action returning Null .

**controler*** 
public class TestData
{
    public string name1  { get; set; }
    public string value1 { get; set; }   
}

public JsonResult MyMethod(List<TestData> testVal)
    {
 //testval object having name1 and value1 null values
  }

view page

      $.getJSON("/viewFolderName/MyMethod",
         {
             testVal: [{ name1: "veea", value1: "0" }]

         },
         function (data) {
         //result
         });

passing Json Array to MVC Controller Action returning Null

Ajax.BeginForm not creating a form tag inside the dom

In my MVC project I'm using an ajax form to dynamically update some search results based on a modified search term.

When rendering the Ajax.BeginForm() Method, it doesn't render a <form> tag on the page (in the DOM)

everything is set up fine, Jquery, Unobtrusive and AJAX are all referenced and I have working Ajax.BeginForm instances elsewhere

@using (Ajax.BeginForm("FilterSearch","Attachment", new AjaxOptions()
    {
        OnComplete = "updateSearchResults",
        HttpMethod = "POST"
    },new{}))
    {
        @Html.HiddenFor(model => model.AccountId)
        @Html.HiddenFor(model => model.ContactId)
        @Html.HiddenFor(model => model.OpportunityId)


        @Html.TextBoxFor(model => model.SearchTerm, new { placeholder = "Search Term", @class = "header-search-box" })
        <input type="submit" class="header-search-input" />
    }

is just rendering inside the DOM as

<input id="AccountId" name="AccountId" type="hidden" value="">
<input id="ContactId" name="ContactId" type="hidden" value="">
<input id="OpportunityId" name="OpportunityId" type="hidden" value="O6UJ9A001TB1">
<input class="header-search-box" id="SearchTerm" name="SearchTerm" placeholder="Search Term" type="text" value="">
<input type="submit" class="header-search-input">

Avoid postback on OnClick event of View

I have two views as below :

Index.cshtml

    <p>
       @Html.ActionLink("Create New", "Create", "Owner ", new { id = "lnkCreate" })
    </p>

 @section JavaScript {
        <script type="text/javascript" src="@Url.Content("/Scripts/Owner.js")"></script>

    }

Create.cshtml

 <div>
            @Html.ActionLink("Back", "Index", "Owner", new { id = "lnkBack" })
        </div>

@section JavaScript {
    <script type="text/javascript" src="@Url.Content("/Scripts/Owner.js")"></script>

}

Script >> Owner.js

$(document).ready(function () {


   $('#lnkBack').click(function (e) {                  // not working
        alert('hello')
        e.preventDefault();
        $.ajax({
            url: '/Owner/Index',
            dataType: "html",
            success: function (data) {
                //$('#divContent').hide();
                //$('#divGrid').html(data);
            }
        });

    });

    $('#lnkCreate').click(function (e) {                 //working fine

        e.preventDefault();
        $.ajax({
            url: '/Owner/Create',
            dataType: "html",
            success: function (data) {
               // $('#divGrid').hide();
               // $('#divContent').html(data);
            }
        });

    });

});

What I want to accomplish that whenever i click on "Create New" link it is working as coded without any postback. But when i click on "Back" link of the different view under same controller it is doing postback and not going to click event as in written in script code.

jeudi 23 juillet 2015

MVC Form Submission returns null if Editortemplates Item deleted from view

I am using Editortemplates to show a list of items associated with a form and i allow user to remove row if not wanted But when uiser submits the form after removing any row on POST action i am getting collection as null and if the user did'nt do any deletions of items the i get the complete collection at POST action with modified values . Here is the code i tried with Models Controller and View

//Models
public class Student
{
    public string StudName { get; set; }
    public int StudId { get; set; }
    public List<Assignment> Assignments { get; set; }
}
public class Assignment 
{
    public int Id{get;set;}
    public string Name{get;set;}
    public int Amount{get;set;}
    public string Remarks{get;set;}
}

//Controller Actions    
public ActionResult Assign(int Id)
{
    Student model = new Student { StudId = Id, StudName = "Name +" + Id };
    List<Assignment> _assignments = new List<Assignment>();
    for(int j=0;j<3;j++)
    {

        Assignment itm = new Assignment { Id = j, Name = "Assign " + j, Remarks = "Remarks " + j, Amount = j * 33 };
        _assignments.Add(itm);
    }
    model.Assignments = _assignments;
    return View(model);
}
[HttpPost]
public ActionResult Assign(int Id,Student model)
{
    return Content("rxvd "+model.Assignments.Count);
    //count is correct if not removing anything from Assign page 
    //If i remove any items from assign page then count is null
}
//Assign View
@model OpenXMLMvc3.Controllers.Student
@{
    ViewBag.Title = "Assign";
}
<h2>Assign</h2>
<script type="text/javascript">
$(function () {
//call from Editor template
    $("a.deleteRow").live("click", function () {
        $(this).parents("tr.editorRow:first").remove();
        return false;
    });
});
</script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
        <div class="col-md-6">
        <div class="editor-label">
            @Html.LabelFor(model => model.StudName)
            @Html.EditorFor(model => model.StudName)
            @Html.ValidationMessageFor(model => model.StudName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.StudId)
            @Html.EditorFor(model => model.StudId)
            @Html.ValidationMessageFor(model => model.StudId)
        </div>
        </div>
       <div class="col-md-6">
        <table  id="container">
            @for (int j = 0; j < Model.Assignments.Count; j++)
            {
            //using editor template to list the assignments 
                 @Html.EditorFor(model => Model.Assignments[j])
            } 
    @*This will [using foreach instead of for ] result a NULL at form submission even without editing or removing any rows 
        @foreach (OpenXMLMvc3.Controllers.Assignment assign in Model.Assignments)
        {
                @Html.EditorFor(model => assign)
        }*@
        </table>
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
}
//Editor template view
@model OpenXMLMvc3.Controllers.Assignment

<tr class="editorRow">
<td>
  @Html.HiddenFor(model => Model.Id, new {@class="iHidden" })
  sa
</td>
<td>
    @Html.EditorFor(model => Model.Name)
</td>
<td>
     @Html.EditorFor(model => Model.Amount)
</td>
    <td>
      @Html.EditorFor(model => Model.Remarks)
    </td>
    <td>
   <a href="#" class="deleteRow">delete</a>
   </td>
 </tr>  

So how can i allow user to remove item from Collection via EditorTemplates in MVC3

How to get the values from Html.ListBox in asp.net MVC

I had this before

<div class="form-group">
    @Html.Label("Empresa", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
       @Html.DropDownList("Empresa", 
         new SelectList(empresas, "Id", "Nombre"), 
         new { @class = "form-control" })
     </div>
</div>

and on my controller I could get the values: (check the request.form line)

      public async Task<ActionResult> Create(
        [Bind(
            Include =
                "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department"
            )] Microsoft.Azure.ActiveDirectory.GraphClient.User user)
    {
        ActiveDirectoryClient client = null;
        try
        {
            client = AuthenticationHelper.GetActiveDirectoryClient();
        }
        catch (Exception e)
        {
            if (Request.QueryString["reauth"] == "True")
            {
                //
                // Send an OpenID Connect sign-in request to get a new set of tokens.
                // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                //
                HttpContext.GetOwinContext()
                    .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }

            //
            // The user needs to re-authorize.  Show them a message to that effect.
            //
            ViewBag.ErrorMessage = "AuthorizationRequired";
            return View();
        }

        try
        {
            var usuario = user.UserPrincipalName;
            user.UserPrincipalName = usuario+SettingsHelper.Domain;
            user.MailNickname = usuario;
            user.AccountEnabled = true;
            await client.Users.AddUserAsync(user);

            string extPropLookupName = string.Format("extension_{0}_{1}", SettingsHelper.ClientId.Replace("-", ""), "Compania");

            //TO BE FINISHED
            user.SetExtendedProperty(extPropLookupName, Request.Form["Empresa"].ToString());
            await user.UpdateAsync();
            //Task.WaitAll();

            // Save the extended property value to Azure AD.
            user.GetContext().SaveChanges();
            return RedirectToAction("Index");
        }
        catch (Exception exception)
        {
            ModelState.AddModelError("", exception.Message);
            return View();
        }
    }

However I changed DropDownList with ListBox because I need it to be multipleselect, and now I dont see it in the Request.Form collection

How can I get the values selected?

HtmlHelper on type parameter of generic view-model

I'm trying to create an HtmlHelper method on a strongly-typed view, where the view-model is a generic. But there's a complication. I want to simplify my syntax so I can specify a member expression of a property on my view-model. Consider the following.

public interface ViewModel<T>
{
    T Model { get; set; }
}

public class DocViewModel : ViewModel<Document> 
{
    public IEnumerable<string> Options { get; set; }
    public Document Model { get; set; }
}

public class Document
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Now, I can easily create a helper that references the view-model itself, and use it like so:

@model DocViewModel
<div>
    @Html.DoSomething(vm => vm.Options);
    @Html.DoSomethingElse(vm => vm.Model.Name);
    @Html.DoSomethingYetAgain(vm => vm.Model.Value);
</div>

But I'd like to be able to pass simply an expression on the Model, like so:

@model DocViewModel
<div>
    @Html.DoSomething(vm => vm.Options);
    @Html.DoSomethingElse(vm => vm.Name);
    @Html.DoSomethingYetAgain(vm => vm.Value);
</div>

Now, I can write the helper in such a way that I can do this if I explicitly reference the type parameters in my calls:

@model DocViewModel
<div>
     @Html.DoSomething<Document>(vm => vm.Name);
</div>

But that sort of defeats the purpose of what I'm going after. It seems like I should be able to write an HtmlHelper that can exploit the fact that the view is strongly-typed on DocViewModel, which itself is a KoViewModel, and that @Html() returns

HtmlHelper<DocViewModel> //HtmlHelper<KoViewModel<Document>>

so that the type-param that Document represents is known implicitly, and so that I can write

public static string DoSomethingElse<TModel, TProperty>(this HtmlHelper<KoViewModel<TModel>> helper, Expression<Func<TModel, TProperty>> expression) 
{
    return "Whatever";
}

but that conversion can't be done. So is there any way I can do this? Or am I just going to have to live with the ugly syntax?

MVC3 dll mismatch 500- internal server error

Please help! I had deployed a MVC3 application to our Dev server and it was working fine with system.web.Mvc version=3.0.0.0. Next, I deployed a higher version of MVC3 System.Web.Mvc, Version=3.0.0.1 and got that to work as well with 1) bindingredirect tag 2) using the 3.0.0.1 version dll in bin and bin_deployableAssemblies folder I accidentally deleted the deployed folder of the whole application, and now I cannot get anything to work, new or old version. All I see is 500-internal server error. I even tried to get past this error by using settings to see detailed message but nothing works. Please help! I have attached a snippet of my web.config file.

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://ift.tt/18KuGN2
  -->
<configuration>
  <configSections>
    <section name="BatchItemsFieldCounts" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    <section name="BatchFileColumnNames" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    <section name="BatchFileSheetNamesByBatchTypeFromDb" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
    </sectionGroup>
  </configSections>
  <BatchItemsFieldCounts>
    <add key="LEPBatch" value="15"/>
    <add key="LEPPaymentBatch" value="31"/>
  </BatchItemsFieldCounts>
  <BatchFileColumnNames>
        <add key="LEPBatch" value="BatchItemId,RecordType,MCOContractNumber,PBPNumber,PlanSegmentNumber,HICNumber,Surname,FirstInitial,Gender,DOB,EligibilityEffectiveDate,EligibilityTermDate,NoOfMonthsInPeriod,NoOfUncoveredMonths,LEPAmount"/>
    <add key="LEPPaymentBatch" value="BatchItemId,BusinessUnit,OperatingUnit,Product,BankAccount,State,MbrId,MbrLName,MbrFName,HICN,PaymentType,ItemNumber,CheckNumber2,TotalAmount2,TransactionNumber,Status,Note,TotalAmount,BatchDate,LockBatchId,LockboxId,Amount,CheckPayorNameUnkn,CheckSN,Site,Account2,AddressLine1,Account,CheckDate,CheckPayorName,CustomerNumber,InvoiceAmount,InvoiceNumber,InvoiceTotal,Sequence,TransactionType,NumberOfItems"/>
  </BatchFileColumnNames>
  <BatchFileSheetNamesByBatchTypeFromDb>
    <add key="InsertPayment" value="[Combined$]"/>
  </BatchFileSheetNamesByBatchTypeFromDb>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="autoFormsAuthentication" value="false"/>
    <add key="CopayBillingProductId" value="1"/>
    
    <add key="enableSimpleMembership" value="false"/>
    <add key="sqlCommandTimeout" value="1200"/>
    <add key="LogFilePath" value="D:\inetpub\wwwroot\LEPBilling\Uploads"/>
    <add key="UploadsFolder" value="\\agpcorp\files\VA1\Private\ITS-TechServices\AMS\CorpSvcs\Finance\NY\NY Reconciliation\LEPBilling\DEV"/>
    <add key="ReportsUrl" value="http://vadrsf01/Reports/Pages/Folder.aspx?ItemPath=%2fDevelopment%2fManaged%2fFinance%2fPrivate%2fLEP+Billing"/>
    <add key="InvoiceUrl"
      value="http://vadrsf01/ReportServer/Pages/ReportViewer.aspx?%2fDevelopment%2fManaged%2fFinance%2fPrivate%2fLEP+Billing%2fRep_InvoiceDetails"/>
  </appSettings>
  <connectionStrings>
    <add name="LEPBillingEF" providerName="System.Data.SqlClient"
      connectionString="Server=XXX;Database=XXX;user id=xxx;password=xxx;connect timeout=600;"/>
    <add name="MemberLookup" providerName="System.Data.SqlClient"
      connectionString="Server=xxx;Database=xxx;user id=xxx;password=xxx;connect timeout=600;"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <authentication mode="Windows"/>
    <authorization>
      <allow users="?"/>
    </authorization>
    <pages>
      <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.Routing"/>
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
    <customErrors mode="Off"/>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
    </httpModules>
  </system.web>
  <system.webServer>
    <httpErrors errorMode="Detailed"/>
    <asp scriptErrorSentToBrowser="true"/>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="UrlRoutingModule"/>
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler"/>
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler"/>
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler"/>
    </modules>
    <security>
      <authentication/>
    </security>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,      Version=2.0.0.0, Culture=neutral,      PublicKeyToken=b03f5f7f11d50a3a"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.1" newVersion="3.0.0.1"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System" publicKeyToken="b77a5c561934e089" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Core" publicKeyToken="b77a5c561934e089" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Data" publicKeyToken="b77a5c561934e089" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Xml" publicKeyToken="b77a5c561934e089" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Configuration" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Drawing" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Services" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <elmah>
    <!--
    See http://ift.tt/1oeE5D2 for 
    more information on remote access and securing ELMAH.
  -->
    <security allowRemoteAccess="true"/>
  </elmah>
  <location path="elmah.axd" >
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
      </httpHandlers>
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode"/>
      </handlers>
    </system.webServer>
  </location>
</configuration>

MVC Null Reference on Model

I'm trying to implement a partial view but I'm having troubles with the model. I'm getting the following error:

System.NullReferenceException: object reference not set to an instance of an object

The HTML code where the error is detected is the following:

@model IEnumerable<BUGTRACKER.Models.Revisiones>


<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Version)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Descripción)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Fecha)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Version)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Descripción)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Fecha)
        </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>
}

I really don't know what's going on here, any idea?

Duck Typing for Razor views

I have a data session model which contains many different types of applicants. All of these have FirstName and LastName properties which I would like to display in a razor view.

var applicant = model.Lead ??
                model.Drivers.FirstOrDefault() ??
                model.Loans.FirstOrDefault() ?? 
                model.Renewals.FirstOrDefault();

At first glance, I would use inheritance, except that these are classes in an EF database, not sure how to setup a parent class.

Is there a clean way to do this or am I stuck with something like this?

dynamic applicant = new ExpandoObject();

if (model.Lead != null) {
   applicant.FirstName = model.Lead.FirstName;
   applicant.LastName = model.Lead.LastName;
} else if ( model.Drivers.Any() ) {
   var first = model.Drivers.FirstOrDefault();
   applicant.FirstName = first.FirstName;
   applicant.LastName = first.LastName;
} else if ...

mercredi 22 juillet 2015

How to disable disabled account to use applicaton

ASP .NET MVC3 application uses login controller from MVC3 application template below.

User enters user name and password and click "remember me" checkbox. Authorization cookie is stored in browser and credentials are no more asked on subsequent accesses.

User can disabled by setting disavled column in accounts database. If such user tries to log on membership provider returns error and login failed.

However if user is already logged in, membership provider is not called. Disabled user can continue to use application. How to fix this so that disabled user cannot use application ?

LogOn controller is basically from Visual Studio MVC3 sample application template:

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (string.IsNullOrWhiteSpace(model.UserName) || string.IsNullOrWhiteSpace(model.Password))
        {
            ModelState.AddModelError("", "User or password not filled");
            return View(model);
        }
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            FormsService.SignIn(model.UserName, model.RememberMe);
            if (!String.IsNullOrEmpty(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Logon error");
        }
        return View(model);
    }

I create and assign values to a list of strings in my controller. I want to assign the list of values to a JavaScript variable. How can I do this?

Controller:

List<string> fruits = new List<string>();
list.Add('Apple');
list.Add('Banana');
list.Add('Kiwi');
ViewBag.FruitList = fruits;

View:

var fruitList = '@ViewBag.FruitList';

When I run the program fruitList comes back as System.Collections.Generic.List 1[System.String]

Templates can be used only with field access, on razor view

I am trying to bind a KeyValuePair VALUE in a asp.net mvc view, however I get this error above.

How can I fix this?

@using Microsoft.Azure.ActiveDirectory.GraphClient
@using xx.Utils
@model IEnumerable<User>


@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}
<h2>Usuarios</h2>

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>Lista de Usuarios</h5>
                    <div class="ibox-tools">
                        @Html.ActionLink("Create New", "Create", null, new { @class = "btn btn-primary btn-xs" })
                    </div>
                </div>
                <div class="ibox-content">

                    <table id="directoryObjects" class="table table-bordered table-striped">
                        <tr>
                            <th>
                                UserPrincipalName
                            </th>
                            <th>
                                DisplayName
                            </th>
                            <th>
                                JobTitle
                            </th>
                            <th>
                                ObjectId
                            </th>
                            <th />
                        </tr>
                        @foreach (var item in Model)
                        {
                            var user = item as User;
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => user.UserPrincipalName)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => user.DisplayName)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => user.JobTitle)
                            </td>
                            <td>
                                @{ 
                                    string extPropLookupName = string.Format("extension_{0}_{1}", SettingsHelper.ClientId.Replace("-", ""), "Compania");
                                }
                                @Html.DisplayFor(modelItem => user.GetExtendedProperties().Where(prop => prop.Key == extPropLookupName).FirstOrDefault());
                            </td>
                            <td>
                                @Html.ActionLink("Edit", "Edit", new { objectId = item.ObjectId }) <br />
                                @Html.ActionLink("Details", "Details", new { objectId = item.ObjectId }) <br />
                                @Html.ActionLink("Delete", "Delete", new { objectId = item.ObjectId })  <br />
                                @Html.ActionLink("GroupMembership", "GetGroups", new { objectId = item.ObjectId }) <br />
                                @Html.ActionLink("DirectReports", "GetDirectReports", new { objectId = item.ObjectId }) <br />
                            </td>
                        </tr>
    }
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>

null entry for parameter 'captchaValid'

I have an old site over MVC 3 wich was working fine, but our server crashed last week, now i've recovered it but reCaptcha in the forms started giving problems it didn't have before.

On my local machine it works fine but on production server, where everything is set in the same way, it yells System.ArgumentException: The parameters dictionary contains a null entry for parameter 'captchaValid' of non-nullable type 'System.Boolean'

I believe everything should be ok

[web.config]

<appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="ReCaptchaPrivateKey" value="MyPrivateKey" />
    <add key="ReCaptchaPublicKey" value="MyPublicKey" />
</appSettings>
(...)
<namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="Recaptcha"/>
</namespaces>

[reCaptcha on View]

<script type="text/javascript">
    var RecaptchaOptions = {
        theme: 'custom',
        custom_theme_widget: 'recaptcha_widget'
    };
</script>

<div id="recaptcha_widget" style="display:none">

    <div style="float:left;">
        <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect please try again</div>

        <span class="recaptcha_only_if_image"><label for="recaptcha_response_field">Insira as palavras que vê na imagem</label></span>
        <span class="recaptcha_only_if_audio">Enter<label for="recaptcha_response_field">Insira os números que ouve</label></span>

        <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />
    </div>

    <div style="float:right;">
        <div style="float: left;">
            <div id="recaptcha_image"></div>
        </div>
        <div style="float: left; margin-left: 30xp;">
            <div><a href="javascript:Recaptcha.reload()" class="recaptcha-btn"><i class="icon-refresh"></i></a></div>
            <div class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type('audio')" class="recaptcha-btn"><i class="icon-volume-up"></i></a></div>
            <div class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type('image')" class="recaptcha-btn"><i class="icon-font"></i></a></div>
            <div><a href="javascript:Recaptcha.showhelp()" class="recaptcha-btn"><i class="icon-question-sign"></i></a></div> 
        </div>
        <div class="clear"></div>
    </div>

</div>

<script type="text/javascript" src="http://ift.tt/1HJpC9Y"></script>
<noscript>
    <iframe src="http://ift.tt/1HJpCa0" height="300" width="500" frameborder="0"></iframe><br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>

[in the controller]

[HttpPost]
[Recaptcha.RecaptchaControlMvc.CaptchaValidator]
public JsonResult Enviar(RegisterModel model, bool captchaValid, string captchaErrorMessage)
{
    (...)
}

I belive that Recaptcha.RecaptchaControlMvc.CaptchaValidator should be the one responsible for generating values for captchaValid but this is not working outside my development machine.

Does anybody have any idea why does this is happening?

How to bind a dictionary value to a column in asp.net mvc

I am using Active Directory Authentication Library to get a list of users in my active directory. The view is bound to the User class in this library.

@using Microsoft.Azure.ActiveDirectory.GraphClient
@model IEnumerable<User>


@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}
<h2>Usuarios</h2>

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>Lista de Usuarios</h5>
                    <div class="ibox-tools">
                        @Html.ActionLink("Create New", "Create", null, new { @class = "btn btn-primary btn-xs" })
                    </div>
                </div>
                <div class="ibox-content">

                    <table id="directoryObjects" class="table table-bordered table-striped">
                        <tr>
                            <th>
                                UserPrincipalName
                            </th>
                            <th>
                                DisplayName
                            </th>
                            <th>
                                JobTitle
                            </th>
                            <th>
                                ObjectId
                            </th>
                            <th />
                        </tr>
                        @foreach (var item in Model)
    {
        var user = item as User;
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => user.UserPrincipalName)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => user.DisplayName)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => user.JobTitle)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => user.ObjectId)
                            </td>
                            <td>
                                @Html.ActionLink("Edit", "Edit", new { objectId = item.ObjectId }) <br />
                                @Html.ActionLink("Details", "Details", new { objectId = item.ObjectId }) <br />
                                @Html.ActionLink("Delete", "Delete", new { objectId = item.ObjectId })  <br />
                                @Html.ActionLink("GroupMembership", "GetGroups", new { objectId = item.ObjectId }) <br />
                                @Html.ActionLink("DirectReports", "GetDirectReports", new { objectId = item.ObjectId }) <br />
                            </td>
                        </tr>
    }
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>

However in Active Directory you can create custom properties, those properties are called Schema Extensions: FYI ONLY http://ift.tt/1Ebo4pS

In my list of users some users have custom properties some others dont.

In my view I want to create a column to show the value of that custom property if it exists.

I know how to get the value server side, but I dont know how to bind it on the HTML

This is the index action in the users controller

 public async Task<ActionResult> Index()
    {
        var userList = new List<Microsoft.Azure.ActiveDirectory.GraphClient.User>();
        try
        {
            ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
            IPagedCollection<IUser> pagedCollection = await client.Users.ExecuteAsync();
            if (pagedCollection != null)
            {
                do
                {
                    List<IUser> usersList = pagedCollection.CurrentPage.ToList();
                    foreach (IUser user in usersList)
                    {
                        var usuarioAD = (Microsoft.Azure.ActiveDirectory.GraphClient.User)user;
                        var extendedProperties = usuarioAD.GetExtendedProperties();

                        foreach (var property in extendedProperties)
                        {
                            if (property.Key.Contains("Compania"))
                            {
                                string value = property.Value.ToString();
                            }
                        }

                        userList.Add((Microsoft.Azure.ActiveDirectory.GraphClient.User)user);
                    }
                    pagedCollection = await pagedCollection.GetNextPageAsync();
                } while (pagedCollection != null);
            }
        }
        catch (Exception e)
        {
            if (Request.QueryString["reauth"] == "True")
            {
                //
                // Send an OpenID Connect sign-in request to get a new set of tokens.
                // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                //
                HttpContext.GetOwinContext()
                    .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }

            //
            // The user needs to re-authorize.  Show them a message to that effect.
            //
            ViewBag.ErrorMessage = "AuthorizationRequired";
            return View(userList);
        }
        return View(userList);
    }

How can I bind the value? or maybe I can write a complex expression on the razor view without writing anything on the controller to get that value?

How to pass a hidden variable value to href onclick function

I have a hidden variable which stores an ID. In another view i have href tag from which I am calling a function with with I need to send this ID as a paramater.

my hidden variable:

<input type="hidden" id="CID" value="@Model.CID">

< a href="#!" onclick="openDlg('@item.Name', 'here i want that hidden variable value'") >/<a>

Please help

Ajax call in different web application

I've 2 web applications. I want to make an ajax call from one web application(say Application1) to another web application(say Application2).

I'm doing it like this

  var ajax_url = "http://localhost:50224/common/IsUserOnline";
    $.ajax({
        url: ajax_url,
        dataType: "json",
        type: "POST",
        data: { customerId: '@Model.UserId' },
        success: function (response) {
            var data = response.Data;
            if (data.isUserOnline == false) {
                $("#IsUserActive").val('false');
            }
            else {
                $("#IsUserActive").val('true');
            }
        }
    });
    if ($("#IsUserActive").val() == "false") {
        window.location.href = '@Url.Action("SessionExpired", "Home")';
    }

However i get the following error. No 'Access-Control-Allow-Origin' header is present on the requested resource. Is there a way i can make a hit to Application2 and get the data?

mardi 21 juillet 2015

VS Debug Site is showing not available after stop debugging

We are currently developing a MVC 4 web application. Recently I may have changed some configuration in the "root/" web.config and "View/" web.config, since then every time I have to start debugging to access the website. I was able to just do build and visit my site.

I have tried to fix my config files but after hours of struggle I came to ask the question. I am not quite sure it is because of the changes in web.config

My VS is 2013.

Online users list in nopcommerce 2.40

How can i find out list of all logged in users in nopcommerce 2.40, I'm maintaining a flag in database which tells me that user is signed in or not. Everytime when user login value of flag is set to 1 and on logout value is set to 0. But there are two cases which are not being covered in the above scenario

  1. When user after login closes the browser (the value of flag is still 1 in database but the user has left the site).
  2. When site is open and no action is performed on site for more than 20 minutes(the value of flag is still 1 in database but the user is not active on the site)

.

Any ideas about how to overcome the problems and get list of all online users which are active?

Displaying JSON on HTML returned from Web Api Controller

I have created the Web Api project with MVC.I want to display the JSON result in HTML page. How should i do that? URL:

http://localhost:58379/api/ccpayment/GetEligibility?userid=3830&type=json

and the data i am getting is in the following format

{"DailyAllowance":10000.00,"AmountUsedForTheDay":0.00,"CDF":3.0000,"UserEligibleForCC":"EligibleButBanned"}

lundi 20 juillet 2015

Display only Unique rows in a column C# (razor)

Here is my requirement:

Mytable:

Sno Name Phonenumber Interests

1 Ram 9500677543 SQL 2 Ram 1234567890 SQL 3 Ed 0987654343 C# 4 Ed 1357986420 C#

I need to get this table displayed in razor view like below:

Sno Name Phonenumber Interests

1 Ram 9500677543 SQL 2 1234567890
3 Ed 0987654343 C# 4 1357986420

I'm not getting any idea. Anyone Please help me!

dimanche 19 juillet 2015

How to get popup window in MVC using Javascript or jquery?

<script type="text/javascript">
    $('#btnpopup2').click(function () {

        jQuery.noConflict();
        $('#SearchPopupWindow1').load("/Service/ServiceList",
                function (response, status, xhr) {
                    $('#SearchPopupWindow1').dialog('open');
               });
   });

Umbraco unpublish Event not working for the current node

I am developing Umbraco 7 MVC application and my requirement is to add Item inside Umbraco. Item name should be unique. For that used the below code but I am getting the error "Oops: this document is published but is not in the cache (internal error)"

      protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication,
            ApplicationContext applicationContext)
        {
            ContentService.Publishing += ContentService_Publishing;
        }


        private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
        {
            try
            {
               if(newsItemExists)
               {
                  e.Cancel = true;
               }
            }
            catch (Exception ex)
            {
                e.Cancel = true;
                Logger.Error(ex.ToString());
            }
        }

Then I tried adding code to unpublish but its not working i.e the node is getting published. Below is my code

private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
        {
            try
            {
               int itemId=1234; //CurrentPublishedNodeId
               if(newsItemExists)
               {
                  IContent content = ContentService.GetById(itemId);
                  ContentService.UnPublish(content);
                  library.UpdateDocumentCache(item.Id);
               }
            }
            catch (Exception ex)
            {
                e.Cancel = true;
                Logger.Error(ex.ToString());
            }
        }

But with the above code, if you give the CurrentPublishedNodeId=2345 //someOthernodeId its unpublished correctly.

Can you please help me on this issue.

jeudi 16 juillet 2015

MapRoute not working as expected

Considering the mapped routes below, when the user goes to /Home, why would the second route be hitting instead of the first? My assumption was that going to /Home would result in the first route being hit, but for some reason the second one is being used.

Why is this?

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
          "Home page behind eRaider",
          "Home",
          new { controller = "Home", action = "HomeSecure", id = "" }
        );

        routes.MapRoute(
          "Default",                                              
          "{controller}/{action}/{id}",                           
          new { controller = "Home", action = "Index", id = "" } 
        );
    }

edit: just to be clear, I want /Home to go to the HomeSecure action in the Home controller.

edit2:

        public ActionResult Index()
        {
            return View();
        }

        [AuthorizeHasAccess]
        public ActionResult HomeSecure()
        {
            return View();
        }

mercredi 15 juillet 2015

Alert not executing when redirected from other page

I have the following code in the body tag of a view in MVC. The problem is that the alert message is displayed on first time loading of the page but it isn't executing when the control is coming through redirect.

Also, I have used the break point to see that the code is executing but it doesn't execute the alert line.

@{

    <script type="text/javascript">
    @if (TempData["notice"] != null)
    {
        @:alert(TempData["notice"]);
    }
    else 
    {
        @:alert("No notice");          
    }
    </script>
}

mardi 14 juillet 2015

How get on controller values of strings(splits-email of ajax-jquery)?

Image easy error is:http://ift.tt/1fHJzVH

{

$('#dialog-form').dialog({
            modal: true,
            autoOpen: false,
            width: 500,
            buttons: {
                "تایید": function (e) {
                    var ccTo = $('#ccTo').val();
                    var email = $('#email').val();
                    var reason = $('#reason').val();
                    $.ajax({
                    url:'@Url.Action("EmailInfo", "Admins")',
                    type: "POST",
                    dataType: "text",

                data: ({ ccTo: ccTo, email: email, reason: reason }),
                success: function (result) {
                    if (data != null && data.success) {
                        alert(result);




}

Can we use ModeState.IsValid in view(.cshtml page) in mvc?

I am trying to show/hide a div on the basis of "ModelState.IsValid" in my view (.cshtml page) in mvc. Is it possible to use ModelState.IsValid in .cshtml? Please send me some link or any idea? Or should I use the other kind of logic like ViewBag?

ajax call is never post back to the server

I am trying to make an ajax call back to the server to save the new data into the database: here is my code:

$.ajax({
    type: 'POST',
    url: '@Url.Action("SaveNewApplication")',
    contentType: 'application/json; charset=utf-8',
    data: {
        appName: newAppName,
        appDesc: newAppDesc,
        expire: newDaysToExpire,
        displayNote: newDspNote,
        adminRole: newAdminRole,
        defualtRole: newDefaultRole,
        active: newIsActive
    },
    dataType: '',
    success: function () {
        alert("new data has been saved");
    },
    error: function () {
        alert("Error happened whiles saving the new application data");
    }
});

I set a break point at the "SaveNewApplication" function but the break point is never hit! here is the "SaveNewApplication" function:

    [HttpPost]
    [OutputCache(Duration = 0)]
    public void SaveNewApplication(string appName, string appDesc, int expire, string displayNote, string adminRole,
       string defualtRole, bool active)
    {

    }

the success function in the ajax call is never executed

MVC3 model is null if Datatable filtering is applied

I'm using the jQuery Datatable (http://ift.tt/1gQlUua) for styling, sorting and filtering of list of data.

My razor is like [ which list a set of items and allow user to edit name and aim to save all changes to Db on single GO]

@using (Html.BeginForm()) {
    <div>
        <fieldset>
            <legend>Modify items</legend>
            <p>
                <input type="submit" value="Save" />
            </p>
        <table cellpadding="0" cellspacing="0" border="0" class="" id="SelectEmpTable"> 
            <thead>
                <tr>
                    <th>Old Name</th>
                    <th>New Name</th>
                </tr>
            </thead>
            <tbody>
            @for (int i = 0; i < @Model.Count();  i++)
            {
            <tr>
                <td class="editor-label">
                    @Html.DisplayForm(m => m[i].Name)                       
                    @Html.HiddenFor(m => m[i].Id)
                </td>
                <td>
                     @Html.TextBoxFor(m => m[i].Name) //allow user to edit
                </td>
            </tr>
            }
            </tbody>
        </table>
        </fieldset>
    </div>
}

and then use the jQuery plugin for the rest...

$(document).ready(function() { 
     $('#SelectEmpTable').dataTable(); 
} );

When posting back without filtering the table (on the client side) my model is populated.

    [HttpPost]
    public ActionResult SubmissionForm(IList<CompanyModel> model)
    {
        //model is not null and has all list of values
    }

However when filtering the table, and then submit form , the model is then null, in the above code.

How can i make sure both filtering is possible and get data in model while submitting form

Data Annotation Validation for a Group of Fields in Model

I am new to MVC 3 Data Annotations and I just want to ask that if its possible to add Validation on a Group of Fields in Model and Display the validation if none of it has Value?

this is the set of fields in my Data model

 public class ContactModel
    {
        public Nullable<int> Id { get; set; }


        [Display(Name = "Contact Firstname")]
        [Required(ErrorMessage = "Required!")]
        public string ContactFirstname { get; set; }

        [Display(Name = "Contact Lastname")]
        [Required(ErrorMessage = "Required!")]
        public string ContactLastname { get; set; }

        [Display(Name = "Contact Middlename")]
        public string ContactMiddlename { get; set; }

            [Display(Name = "Phone")]
            [Required(ErrorMessage = "Required!")]
            public string ContactPhone { get; set; }

            [Display(Name = "Mobile ")]
            [Required(ErrorMessage = "Required!")]
            public string ContactMobile { get; set; }

            [Display(Name = "Email")]
            [Required(ErrorMessage = "Required!")]
            public string ContactEmail { get; set; }

        [Display(Name = "Job Title")]
        [StringLength(50, ErrorMessage = "Max character reached!")]
        public string ContactJobTitle { get; set; }

    }

And I want to add validation if one from Phone,Mobile or Email doesn't have value

Thanks

Manual Parsing of JSON Data from MVC3 Request

My Ajax Sends Json as

{"deleteids":"8","dtldels":[]}

I have a class where i am trying to decipher the values from request object in to the class properties as follow

 get {
        var x = HttpContext.Current.Request.QueryString["deleteids"]; // null here
        var y = HttpContext.Current.Request.Form["deleteids"]; // null here
        return  HttpUtility.UrlDecode(HttpContext.Current.Request["deleteids"]); // null here
  }

Both x, y and the return all return null. Why is that ? And how do i get the values correctly into my property.

Thanks.

lundi 13 juillet 2015

MySql Connector Locaweb host

Boa noite, estou utilizando MVC 3, EntityFrameWork 4 e banco de dados MySql... hospedei minha aplicação na LOCAWEB.. até ai tudo certinho, mas infelizmente não consigo fazer a mesma conectar ao banco de dados! e por incrível que pareça, rodando a aplicação na minha máquina local e conectando ao banco hospedado na LOCAWEB... funciona perfeitamente! alguém que já teve esta experiência teria uma sugestão do que fazer?

Obrigado

Transferring Data from MVC controller on to a Web API controller method

I have a MVC view/controller for a page. A partial view inside uses web api to make external service calls.

Using session, I could not access value stored in a MVC controller in WebAPI controller method. Is it not possible? or Am i missing something?

If not, how do I transfer data across?

Trying to Upgrade froM MVC3 to MVC4, all ok bar one component which is still referencing 3.0.0.0

I have upgraded my MVC3 application using the Nuget UpgradeFromMvc3ToMvc4 which has worked fine, except for one component. I did uninstall the V3 of this "MvcSiteMapProvider" component before upgrading, and then installed "MvcSiteMap Core V4" after the MVC4 upgrade.

Ther error I get is:

Error   41  Assembly 'MvcSiteMapProvider, Version=4.6.18.0,  
Culture=neutral, PublicKeyToken=1923abe4657913cc' uses 'System.Web.Mvc, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which 
has a higher version than referenced assembly 'System.Web.Mvc, 
Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'  
d:\..\MvcSiteMapProvider.MVC4.Core.4.6.18\lib\net45   
\MvcSiteMapProvider.dll 

There is no reference to 3.0.0.0 in my solution. I have done a "find" in "all files". So am confused.

Any help appreciated. Thanks.

Loading a page using URL passed as argument to the controller and adding own javascript code to the loaded page

I need to build a functionality like seen here. Here, they take a url as input from the user and open that URL on the browser but also add their own javascript code to it. From the response received on opening a link like this
I can see that they are using some python package pywb but not sure if this particular one is used for rendering the functionality I am looking for. How can I do a similar URL opening and code injecting in ASP.NET? Is there any package for this?

Inner List in mvc Model is not getting updated

Employee class

Public Class Employee
Public Property ID As Integer
Public Property Name As String
Public Phonenumbers As IList(Of PhoneNumber)
Public Sub New()
    Phonenumbers = New List(Of PhoneNumber)
    Phonenumbers.Add(New PhoneNumber)
    Phonenumbers.Add(New PhoneNumber)
End Sub
End Class

PhoneNumber Class

Public Class PhoneNumber
Public PhoneNumber As Integer
Public Sub New()
    Me.PhoneNumber = 123
End Sub
End Class

Create.vbhtml.

@ModelType Employee
@Code
   ViewData("Title") = "Create"
End Code

<h2>Create</h2>

@Using (Html.BeginForm())

@Html.EditorForModel()
End Using

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

@Section Scripts 
@Scripts.Render("~/bundles/jqueryval")
End Section

I have used EditorTemplates(folder) where template for Employee and Phone are saved those are

Employee.cshtml(in editor Templates)

@Modeltype Employee
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.AntiForgeryToken()
@Html.ValidationSummary(True, "", New With {.class = "text-danger"})
@Html.HiddenFor(Function(x) x.ID)

<div class="form-group">
    @Html.LabelFor(Function(model) model.Name, htmlAttributes:=New With {.class = "control-label col-md-2"})
    <div class="col-md-10">
        @Html.TextBoxFor(Function(model) model.Name, New With {.htmlAttributes = New With {.class = "form-control"}})
        @Html.ValidationMessageFor(Function(model) model.Name, "", New With {.class = "text-danger"})
    </div>
</div>
<div class="form-group">
    @Html.Label("phones", htmlAttributes:=New With {.class = "control-label col-md-2"})
    <div id="PhoneNumbers" class="col-md-10">
        @Html.EditorFor(Function(x) x.Phonenumbers)
    </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>

PhoneNumber.vbhtml(in Editors Template)

@modeltype PhoneNumber
@Code
ViewData("Title") = "Phone"
End Code

<div class="container">
<div class="row">
    @Html.Label("phone", htmlAttributes:=New With {.class = "control-label col-md-2"})
    <div class="col-md-10 PhoneNumber">
        @Html.TextBoxFor(Function(model) model.PhoneNumber)
    </div>
</div>
</div>

now whenever I am posting data and receive post the class object employee always comes with old data. no data for phone list in class employee gets updated!!!

Employee Controller

Imports System.Web.Mvc

Namespace Controllers
Public Class EmpController
    Inherits Controller
    ' GET: Emp/Create
    Function Create() As ActionResult
        Dim employee = New Employee()
        Return View(employee)
    End Function
    ' POST: Emp/Create
    <HttpPost()>
    Function Create(ByVal emp As Employee) As ActionResult
        Try
            ' TODO: Add insert logic here
            Return RedirectToAction("Index")
        Catch
            Return View()
        End Try
    End Function
 End class
End Namespace

above is my controller in which, at the post time I am not getting any updated data for emp, although I get name property correctly but for inner list(of phonenumbers) I get always value default(123) which was given.

Compilation error: CS0246 in an ASP.net MVC3 project

I'm trying to follow this tutorial word for word. MVC Music Store I'm already on part 9 however, when I try to press the button "Checkout" it shows this error message:

Error

  1. Compiler Error Message: CS0246: The type or namespace name 'Mvc3ToolsUpdateWeb_Default' could not be found.
  2. public class _Page_Views_Account_LogOn_cshtml : System.Web.Mvc.WebViewPage

I was thinking that, maybe I had added or deleted something, like a "usings" reference line, if that helps. So what I did was:

  1. I tried to clean, build, rebuild the project and the solution.
  2. Deleted temporary log files - restarted the computer.
  3. I researched on the internet for similar errors such as this, but I didn't see anything. I also checked the comments on the tutorial however I didn't see any errors similar to mine.

The links I searched were:
My google search
Stackoverflow search

Kindly enlighten me on what to do. Thank youuuu!