Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, August 22, 2018

Running IISExpress from the command line or Powershell

You don't need to open up Visual Studio just to run another project. You can run IISExpress via the command line instead.

Here is the same example, once for the command prompt and again for Powershell. The name of the site can be found in the applicationhost.config file. You'll see a <site> tag and the name attribute is the siteName. This is also the name that shows up in the system tray when you launch the site in Visual Studio itself.

You can use the system tray IIS Express icon to quit instances started using Powershell or command prompt. You can also type a the letter Q at the command prompt that gets spawned.

Command Prompt

"C:\Program Files (x86)\IIS Express\iisexpress.exe" /config:"C:\dev\MyMvcApp\.vs\config\applicationhost.config" /site:"MyMvcApp"

You'll need to tweak this to match your paths, etc.

Powershell


$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path

function Start-IisExpress($config, $siteName) {
    Start-Process -FilePath 'C:\Program Files (x86)\IIS Express\iisexpress.exe' -ArgumentList "/config:$config /site:$siteName"
}


Start-IisExpress -config "$scriptDir\.vs\config\applicationhost.config" -siteName: "MyMvcApp"

NOTE: This assumes that you have put this in a Powershell (.ps1) file and placed it next to your solution and more importantly that the .vs directory is in the same directory as the .ps1 file. If not, you'll need to adjust the path or hard code the full path.

Saturday, May 20, 2017

Securing your ASP.NET MVC website Checklist

First, let me start by saying this is not a comprehensive list, but it is a good start.

Add headers for all requests

Add this to your web.config
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
<remove name="X-AspNet-Version" />
<remove name="X-AspNetMvc-Version" />
<remove name="X-Powered-By" />
<remove name="Server" />
        <add name="X-XSS-Protection" value="1; mode=block"/>
        <add name="X-Content-Type-Options" value="nosniff"/>
        <add name="Strict-Transport-Security" value="max-age=31536000"/>
<add name="X-Frame-Options" value="DENY" />
<add name="Referrer-Policy" value="no-referrer" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

This does a good job of explaining what some of the header options are

Require Strong Passwords

Go to your AccountController and find the code that creates the PasswordValidator and change it to something like this. Length is the most important thing to consider from a cryptographic complexity. 

NOTE: 12 is the minimum required, but 16 is better to make it sufficiently time consuming to hack.

manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 12,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true
            };

Remove ASP.NET Technology Headers


In Global.asax add the following to the Application_Start() event.

MvcHandler.DisableMvcResponseHeader = true;

You will also need to add the following to the web.config

<system.web>
<httpRuntime targetFramework="4.5.2" enableVersionHeader="false" />
</system.web>


Remove Server Info from headers

Add the following to Global.asax.cs

protected void Application_PreSendRequestHeaders()
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Response.Headers.Remove("Server");
            }
        }


Also read through security issues that require reviewing your code and maybe some knowledge of how your application is written.

Restrict origin of anything loaded

To be extra safe look at adding creating a white list of what stylesheets, scripts, etc can be loaded. This will take some digging on your site, but is probably worth the effort.


There is a nuget package that does some of this. This looks to be a better choice as it is per controller, etc and explains how to use it.


X-Frame-Options

MVC5 will add in the X-Frame-Option by default. If you want to remove it and make it DENY you will need to add the following line to your Application_Start() method in the Global.asax.cs.

System.Web.Helpers.AntiForgeryConfig.SuppressXFrameOptionsHeader = true;



Thursday, May 18, 2017

OWASP Top 10 Security for ASP.NET tips you may not know about

Below are my notes on what I thought was important out of the OWASP Top 10 Web Application Security Risks for ASP.NET

SQL Injection

Havij for testing for SQL Injection on a web url

Encoding output

Use the appropriate encoding (escaping character or character sequences) for the context you are using the input.

Use AntiXssEncoder.HtmlEncode() to HTML encode input when using web forms. (Available in NuGet or .NET 4.5). For example, use this before rendering user input what to the screen. <%: %> Syntax will automatically encode it.

ASP.NET MVC Razor automatically encodes for HTML unless you tell it not to. For example, on Model/ViewModel add the [AllowHtml] attribute to the property you want to allow.

Use Microsoft.Security.Application.Encoder.JavaScriptEncode() to encode input for JavaScript. For example taking input and assigning to a JavaScript variable.


You can turn off request validation at the site level (web.config) or the page level. See here for more details.

Hiding Payload

Url encoding can be used by hackers to get around XSS detectors and make the payload unclear to the average user. Another approach is to use a url shortener like tinyurl.com.

Session Persistence

Don't use the url for any sensitive information since they are in web logs, browser history, etc. A session id is definitely sensitive information that can allow someone else to be you while that session is still active. Cookies are a much safer place to pass and persist session ids. The only downside is cookies need to be enabled, but most people have cookies enabled. Cookies is the default behaviour for ASP.NET. Be sure to never send cookie with secret in it over an insecure connection.

Session Timeouts

In the case of a sliding forms timeout it is nice in that it can be extended forever by hitting the url and thus give a large window were someone can use a hijacked session.This is great for valid users and hackers love it too. So, turn off sliding timeout if you can to increase security.

The alternate is to set a fixed session timeout, but the problem is users will lose their session at the end of the timeout no matter what they are doing. There is no perfect solution for all cases. Set according to your needs to strike a balance between security and convenience for users. Do change default values to meet specific needs.

Indirect Reference Map

Indirect references can be used to conceal internal keys, but they are NEVER a substitute for access controls. Each internal id is replaced with a temporary indirect reference (that is stored on the server in the session for example and never exposed to the browser / user). This temporary indirect reference is cryptographically random and has no pattern for guessing. Once the session ends this mapping should expire. The map should be user specific so that it can't be used by any other user. This greatly reduces the ability for an attack by limiting who can use it and limiting the length of time it is valid and making it not guessable based on a pattern. 

Thought on GUIDs. A GUID is not a map. It is unique and does not have a pattern. They should be viewed as obfuscation of the key. They are not user specific and proper Access Control is a MUST if GUIDs are used. They do have the advantage they they cannot be enumerated easily and close to being Globally Unique. A better choice would be to use System.Security.Cryptography.RNGCryptoGraphicProvider.GetBytes() then HttpServerUtility.UrlTokenEncode() and a map instead of a GUID.

Access Control

Just because the url is not visible in the browser's url bar don't assume that a hacker can't look at the source of the page for urls to hack. The best defense is to add code on the controller action that checks the direct and indirect referenced keys belong to the user that is sending them. For example, if the user was passing the id of the record to be displayed, the controller action that displays the record should check that that user has access to that record.

Cross Site Request Forgery

Put simply it is a way to trick the browser to making valid request from an evil site by exploiting the fact that cookies are sent for all requests from that domain. The evil site make a request that is identical in form to the request that the original site would have done, but with malicious payload. It could for example, take advantage of an authentication cookie that was not secured property. 

ASP.NET MVC has a mechanism that adds randomness via a CSRF token.  This token is known to the legitimate page where the form is as a hidden field and the to the browser via a cookie. When the request is sent to the server both the hidden value and the cookie are sent and the server compares them and they must match. The trick is the hacker won't know what the value to put in the form so the attack will fail. This is actually very effective protection.

To implement this, you need to do two things. Add the attriubute called ValidateAntiForgeryToken to the controller action. Also, add @AntiForgeryToken() to you view just inside the BeginForm() brackets. 

Once you implement this, you will see a __RequestVerificationToken in the Request body when the request is made. There is also a matching cookie called __RequestVerificationToken. When the CRSF attack is executed the authentication cookie and the __ReuestVerificationToken cookies are sent with the attack request, but ASP.NET MVC returns a 500 error because there is no (or invalid) form field called __RequestVerificationToken in the request. The hacker doesn't have direct access to the cookies, but they are sent automatically by the browser. Thus the hacker has no way of know the CSRF token value. Attack has been stopped.

NOTE: There is also an Authorize attribute that is often the first line of defense, not as useful for CSRF attack since often authenticated users are the ones tricked into making the attacks.

NOTE: Checking the Referrer site can be helpful, but doesn't protect from CSRF.

Trace.axd

It contains such as cookies such as authToken, CSRF token, etc potentially connection string, versions of software, etc. Luckily the url is disabled by default. This can be enabled in MVC and Web Forms. Use a config transformation to remove the trace node on the Release configuration in case it is ever enabled in the web.config file.

Encrypt Connection String in web.config

It is good to have multiple layers of security. In case a hacker is able to access your web.config you want to limit what he can see. The connection string is quite important and should be encrypted.

To do so, run a command prompt as Administrator and execute:
aspnet-regiis -site "name of site in IIS" -app "app name or /" -pe "connectionStrings"

This uses the encryption key on the server and is server specific. So, it must be executed on that server.

The remaining risk is that someone can go to the server and run a the command to decrypt the string, so limit who can access the server.

Enable Retail Mode

Retail Mode prevents leaking of exception data on YSOD even when configuration is wrong for ALL applications on server. To do so, add the following deployment tag to the machine.config. This forces the same behavior as enabling customErrors. It is a safety net for all applications. 

<system.web>
      <deployment retail="true"/>

Password Rules

Make it harder for hackers by requiring longer passwords, not allowing words in the dictionary or variations of them, and require special characters, mixed case, numbers.

Storage of Passwords

If a hacker can get the username and salt and the hashed value and the operation used by the system to do the hashing then they can brute force attach and recover over 65% of the passwords (on average). To do this they simply call the hashing operation with a password from their list of likely passwords using the salt that they gained access to. Now they compare the hashes. If they are the same then they know the password that was originally used by the user. They now have everything needed to login as that user.

Membership Provider Default Implementation use near useless because we have both the hash and salt. Also SHA1 is too fast of an algorithm which means it can be cracked faster.

Be careful if someone has used your password on the internet and that hash has been compromised then a simple google search for that hash can show what the original password was. If a long salt was used then rainbow tables become useless. Salts make it harder to crash a hash, but it is just a matter of time and with Modern GPUs computing 7.5 billion hashes per second (in 2012) it is literally just a matter of time.

Check out Kerckhoffs' principle if you are wondering if your security is good. Basically it says, if you are not willing to give the design of how your security works and are thus relying on this lack of knowledge as part of the security then your security is not good enough. You must assume the attacker will learn how the security works soon enough.

Cryptography-Hashing

Faster algorithms are not good ironically. We actually want the hashing algorithm to take as long as we can stand. This is balanced with the processing required to login or register for example and how long it will take to hack. SHA1 is probably not sufficient anymore. One way around this is to apply the algorithm say 1000 times, but again that probably isn't enough. BCrypt allows us to directly control how many times we apply the algorithm.

No algorithm is fool proof especially when lists of password and hashes and salts are cataloged. It is all about making it too difficult / time consuming / financially unjustified, etc to do it. Even the most complex algorithms can be circumvented by cataloging the input and outputs.

Cyptography- Encryption

Encryption is less desirable than hashing because if the key is obtained then all the encrypted values can be decrypted and the original values are available. With Hashing it is a one way process and the original value cannot be obtained using the algorithm (must hack as noted earlier). 

The trick with encryption is that you must manage the safety of the key. DPAPI uses the machine key on the server the code is running on to do the encryption and decryption (symmetric algorithm) so the application does not have to.

Password Hacking tools

hashcat - advanced password recovery - brute force for comparing hashes and common hashing algorithms
RainbowCrack - Use rainbow tables to get a pregenerated list of hashes meeting different rules for password.

Restricting Urls in MVC

Don't use web.config location tag permission restrictions because it is based on url, not page. In MVC more than one route can point to the same page, but only the urls used to access them is protected in the location tag in web.config. This means if you have two routes you have to have to location tags in the web.config. This could lead to very buggy and inconsistent access. It worked well in Web Forms because the page is the url.

For MVC you want to protect the Controller and actions of the controller. The way to do that is the Authorize attribute. Just using it requires authenticated users. If you want to restrict to a role you can comma separate list them as a parameter to the Authorize attribute.

Don't forget to protect resources like JavaScript, reports, ajax calls, reports, API's, pdfs, etc. Really anything that is not in the browsers url bar, but does show up in the network traffic.

Side note: Never send sensitive data in the url because they can be in web server logs, error logs, history, etc.

Just because a url can't be guessed doesn't make it secure. Urls get leaked through many different routes such that they don't have to be guessed.

Insufficient Transport Layer Protection

If TLS (Transport Layer Security) is not properly done it opens up the opportunity for a MiTM (Man in the Middle) attack. This can be done by physically tap an ethernet cable, intercept traffic at the ISP level, monitor unprotected traffic at a wifi hotspot, or create a rogue wireless access point. 

With MiTM the attacker can see all http (not https though this is debatable) traffic from the victim. This would include any cookies that are not secured with HTTPS. All cookies that have sensitive information (arguably all do) should only be allowed to be sent via HTTPS (and the cookie not sent if http is used). 

To do this in ASP.NET WebForms you need to set the cookie with Secure to Yes by changing the web.config by adding a <httpCookies requireSSL="true" />. It can also be overridden per request using Response.Cookies.Add(). When you do this if you hit a page that uses HTTP the cookie will not be sent. If this is the authentication cookie it will ask you to log in again (won't be able to) if you access a http link from and https page because the auth cookie is not sent for the http page.

You can also require HTTPS per controller action by adding a RequireHttps. This will make sure the url cannot be access to HTTP. It is best to direct them to the HTTPS version instead of relying on a redirect from http to https. 

As a best practice and to avoid a browser warning that the entire site should use http instead a mixed of http and https. This can show up when the site requires https, but a script tag references http:// as the source. A clean way around this is to use protocol relative url. To do this set source="//hostname/somelib.js". Basically just remove the http: or https: from the url. It will then assume the protocol of the page (i.e. https). Be sure the url you are access supports both http and https.

As a side note, when using a load balancer the request comes to the load balancer  as HTTPS, but by the time it gets to the web server itself it is no longer HTTPS (it is HTTP). In this case, the load balancer typically adds HTTP X-forwarded-proto header headers instead of built in secure cookie attribute. This will require custom implementation.

HSTS is HTTP strict transport security and tells the browser to never make a http request to the site. The header Strict-Transport-Security does this. It has its limitations and patchy in browsers, but is still a good line of defense. it does require the certificate to be trusted.

HSTS can be implemented in an ASP.NET MVC application by adding the following to your web.config

<system.webServer>
       <httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=31536000"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Do NOT show a login form over HTTP (use HTTPS), even if the post is to HTTPS. The reason is that a MiTM attack could inject code on the page to do something like get form values (username and password) and send them off to another location in parallel to the normal submission.

Do NOT load HTTPS login forms inside an iframe on a HTTP page because the parent page is vulnerable and could be manipulated to load a different login form into the iframe. A better choice would be to show the actual login in a full screen window so users can see url and the secure icon in the browser.

Do NOT put username and passwords in urls because they are often in web server logs in plain text, etc.

Unvalidated Redirects and Forwards = bad reputation

They are useful to attackers because the unvalidated redirects abuse the trust the victim has in the site they trust.

Imagine you have a site and you want to track when a user clicks on a link so you have a redirect action on your controller that takes a target url that the user is to be redirected to. Another is how ASP.NET takes the user to the login page when they try to access a page that they don't have access to. In this case, the target url is an internal url or atleast is expected to be. 

The problem comes when a hacker manages to change the target url (when it is not validated) in the redirect link. From the users perspective the site they are on is one they likely trust or looks legitimate, but when the hacker gets to change the target url they can take them where ever they want. The user is harmed in this scenario and the site with this link is also. 

Now imagine the user receives a spam email and the link is something like http://1.usa.gov/OYCBM7. It could be via email, social media, compromised legitimate sites, etc. This could come from a url shortner site to make it difficult to tell where it is coming from. It also has a .gov so people will likely trust it. The long version of the url could be something like http://trustedsite.com/redirect?url=http://evilsite.com/malware. It could also have the query string encoded to obfuscate it.This also gets by blacklist detectors.

If you don't validate redirects and forwards on your site you are a potential target hackers to use your site for their evil ways. To protect your site, you need to validate the querystring before you redirect to the target site. The best way to do this is have a white list of acceptable urls. The white list could be a regex, string literal, int, list, etc. This would be in the action on the controller, etc where the redirect is done. 

There are scenario where you can't use a white list. In this case, you can check the referrer (UrlReferrer) in the request to determine if the user came from our site or some other site. In particular, the UrlReferrer will be null when request came from a non-browser request such as email client, twitter client, pasting into url bar in browser, etc. We can also check if the request is from our site (Request.UrlReferrer.Host != Request.Url.Host).

This is not 100% risk free. For example, Referrer header value can be faked / changed to be whatever and circumvent checks. This is not what happens when a victim follows a link though.

Security Related Sites

nakedsecurity
hak5
Troy Hunt

Friday, March 11, 2016

Search and Replace in a MS Word document

I reviewed options for editing MS Word files in DOCX format and decided that the free and one that has the greatest chance of existing in 10 years is just using the Open XML Word Processing SDK (see my review for details).

For complex stuff maybe a different choice would make sense. However, my requirements are simple much like a mail merge:

  1. Taking an existing MS Word file (DOCX format) as input. (Use it as a template)
  2. Search the MS Word file for some placeholders / tags and replace with real data, but don't save any changes to the original file since it is my template.
  3. Be able to write changes to a new file or stream file to browser for download
As it turns out this can be done in very few lines of code and for FREE. Below is my solution.

// Sample command line application
static void Main(string[] args)
{
    string filename = "Test.docx";
    var oldNewValues = new Dictionary<string, string>();
    oldNewValues.Add("pear", "banana");
    oldNewValues.Add("love", "like");
    byte[] returnedBytes = SearchAndReplace(filename, oldNewValues);
    File.WriteAllBytes("Changed" + filename, returnedBytes);

}


// Does a search and replace in the content (body) of a MS Word DOCX file using only the DocumentFormat.OpenXml.Packaging namespace.
// Reference: http://justgeeks.blogspot.co.uk/2016/03/how-to-do-search-and-replace-in.html
public static byte[] SearchAndReplace(string filename, Dictionary<string, string> oldNewValues)
{
    // make a copy of the Word document and put it in memory.
    // The code below operates on this in memory copy, not the file itself.
    // When the OpenXml SDK Auto saves the changes (that is why we don't call save explicitly)
    // the in memory copy is updated, not the original file.
    byte[] byteArray = File.ReadAllBytes(filename);
    using (MemoryStream copyOfWordFile = new MemoryStream())
    {
        copyOfWordFile.Write(byteArray, 0, (int)byteArray.Length);

        // Open the Word document for editing
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(copyOfWordFile, true))
        {

            // Get the Main Document Part. It is really just XML.
            // NOTE: There are other parts in the Word document that we are not changing
            string bodyAsXml = null;
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                bodyAsXml = sr.ReadToEnd();
            }

            foreach (var keyValue in oldNewValues)
            {
                string oldValueRegex = keyValue.Key;
                string newValue = keyValue.Value;

                // Do the search and replace. Here we are implementing the logic using REGEX replace.
                Regex regexText = new Regex(oldValueRegex);
                bodyAsXml = regexText.Replace(bodyAsXml, newValue);
            }

            // After making the changes to the string we need to write the updated XML string back to
            // the Word doc (remember it is in memory, not the original file itself)
            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(bodyAsXml);
            }
        }

        // Convert the in memory stream to a byte array (binary data)
        // NOTE: These bytes can be written to a physical file or streamed back to the browser for download, etc.
        byte[] bytesOfEntireWordFile = copyOfWordFile.ToArray();

        return bytesOfEntireWordFile;
    }
}



After calling the SearchAndReplace method you have the bytes that make up the MS Word file. It is up to you what you want to do with it. You can save it a file or stream it to the browser when a user clicks a link to download a file.

To write the file to another file (leaving the original unchanged), use the following line:

File.WriteAllBytes(newFilename, returnedBytes);


To stream the bytes back to a browser via a Action method in a ASP.NET MVC controller, use the following:

return File(returnedBytes, "application/msword", "Filename to download as here.docx");


NOTE: Original code inspired by this MSDN example and additional a post or other page I can't remember (sorry).

Thursday, December 3, 2015

Passing additional view data to a Edit to make sharing a EditorTemplate on an Edit and Create view.


Imagine you have a Editor in Shared\EditorTemplates\Person.cs for an object (Person in this example) and two views for an Order entity that is showing edit fields for Order obeject and the Person object. The two EditorTemplates are Person\Edit.cshtml and Person\Create.cshtml. To use the Person EditorTemplate in the Order Edit AND Create view we need to make sure we always pass a value for the Person.OrderID. If we don't do this, the problem is that when we use the editor in the context of the Order\Create.cshtml View the Model is null and validation for the hidden field will have a value of null. When it is on Order\Edit.cshtml the model will not be null and we will have a value for model (a Person object) and thus have the value Model.OrderID. It is really the Create that requires this work around, but we want to be able to use the EditorTemplate even when it is on a Create view. Below is the code needed

Code located in the Order\Edit.cshtml View
model in this context is the Order object
NOTE: We ARE passing MyOrderID value here since we do need the editor to know and keep the value.

@Html.EditorFor(model => model.Person, new { MyOrderID = Model.OrderID })

NOTE: When we set MyOrderID, it is scoped to the EditorTemplate that we are passing the value to. However, if we put the value in the ViewBag or ViewData directly (at the top or Order\Edit.cshtml for example) then it is available to all Views and EditorTemplates in this context.

Code located in the Order\Create.cshtml View
model in this context is the Order object
NOTE: we are not passing the MyOrderID value here since we just need any value (-1 was arbitrarily chosen to be safe) and will be assigned by the Entity Framework when it is saved to the database. Most importantly it will pass the validation and the model will be valid until then.

@Html.EditorFor(model => model.Person)
Code in the partial view ( in EditorTemplates folder makes it a template) for the Person object.
model in this context is the Person object
NOTE: If no value is passed using ViewBag.MyOrderID then we use -1, otherwise we use the passed value (usually from the Order\Edit.cshtml View)

@Html.HiddenFor(model => model.OrderID, new { Value = ViewBag.MyOrderID ?? -1 })


You can also use a strongly-typed ViewModel and pass all data to it instead of using the ViewBag.

Wednesday, December 2, 2015

Configure Code First migrations to use Singular Table Names

If you are using Code First Migration with Entity Framework you will probably have noticed that the table names it generates are all plural. Personally, I dislike this because all the contstraints including foreign keys are very confusing to read when they are plurarlized. Before you do an update-database for the first time be sure to override a method (OnModelCreating()) on your class (typicaly ApplicaionDbContext) that inherits from IdentityDbContext. The default class is called ApplicationDbContext.



public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

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

        public DbSet People{ get; set; }
      

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // make the table names singular instead of plural
            //when code-first generates the table names

            modelBuilder.Conventions.Remove();
            base.OnModelCreating(modelBuilder);
        }


    }


Thursday, November 26, 2015

Resetting migrations when using Code First Migrations in MVC

  1. Delete all the migrations folder in your project except Configuration.cs
  2. Move Configuration.cs to some place safe and remove from the migrations folder
  3. Delete the records in the __MigrationHistory table in your database
  4. Then run the following command in the Package Manager Console:
    >Enable-Migrations -EnableAutomaticMigrations -Force
    NOTE: This will recreate your Configuration.cs
  5. Replace the new Configuration.cs with the Configuration.cs that we moved to a safe place earlier
  6. Then run the following command in the Package Manager Console:
    >Add-Migration Reset
    NOTE: The name is not important
  7. This will create a file in the migrations folder.
  8. Open the new migration file and comment out all the code in the Up() method such that the body of the method is just commented out code.
  9. Save and Build the project
  10. Then run the following command in the Package Manager Console:
    >Update-Database
  11. Uncomment the Up() method.
  12. Save and Build the project.



Good Articles on MVC and .NET

Getting Started

Implementing Basic CRUD Functionality with the Entity Framework in ASP.NET MVC Application - Good step by step tutorial for MVC 5 (not MVC 6). It also shows how to use TryUpdateModel to specify what can be bound to each object. This is a bit cleaner and more object specific, but does require a bit of code.

Binding 

ASP.NET MVC - The Features and Foibles of ASP.NET MVC Model Binding - a great post that gives an in-depth explanation of  how the binder works and how it can be extended.

Prefixing Input Elements Of Partial Views With ASP.NET MVC - Explains how to make a partial view generate html with references that the Binder can understand properly. Also shows a generic method for passing the prefix to the Partial View. It doesn't say it, but creating Edit Templates and EditorFor() instead of Partial Views will also solve this problem.

Model Binding To A List - Explains how to set the Name html form property so that the binder will create the collection.

Mass Assignment / Over-posting

6 Ways To Avoid Mass Assignment in ASP.NET MVC - If you use the Include or Exclude parameters with the Bind attribute it doesn't seem so say it anywhere, but the names of the fields are the same as what show up in Request.Form. So, things like Person.Address.Name, Person.Address.ID, and Person.Address would all need to be added to the Include parameter in order for fields bound to related objects to be allowed through the Include() list and be added to the Request.Form colletion.

Sharing Create / Edit Screens

 ASP.NET MVC - using the same form to both create and edit - forum on how this could be implemented

View Model

How to Use ViewModel with ASP.NET MVC - shows how to implement the repository pattern, how to organize your project, and how to use a View Model.

Videos

Building Applications in ASP.NET MVC 4  - very in depth video on how to build MVC applications. Most of it still applies to MVC 6. It has details on certain topics that are not covered in the MVC 5 version of the video.

Building Applications in ASP.NET MVC 5 - very good video and in depth video on how to build MVC applications.

Best Practices

Best Practices for ASP.NET MVC  - this is a bit old, from 2010, but still has some good advise.
 

Dependency Injection

Dependency Injection and Unit Of Work using Castle Windsor and NHibernate - good example of how to use DI and UOW in MVC application. It shows NHibernate, but it can be used for Entity Framework. It also shows how to use in the context of the different layers of an application.

Castle Windsor Tutorial 1 - I highly recommend reviewing this tutorial. It shows how to create a Castle Windsor container application. It is complex enough to see how a whole application can be done with only calling the container 3 times. It also found it useful to modify the code such that it does NOT use IoC (i.e. not using Castle Windsor). This involves instantiating objects by hand. Then a line at a time, I removed the code I added to hardcode the creation of an object and added the appropriate line in the Installer for that object. Run the application between changes to see how the container actually instantiates the objects automatically once they are registered (in the installer).

Castle Windsor Tutorial 2 - In the case where you do need to create your own instances of an object and still use IoC, you should use TypedFactoryFacility.

Krzysztof Koźmic on software - talks about IoC concepts in depth.

What's New

Top 10 Changes in ASP.NET 5 and MVC 6

Entity Framework

Configuring Relationships with the Fluent API i.e. configuring Cascade delete and one-to-one relationships.

Unit Testing

Testing Entity Framework with a MOQ - step by step instructions on how to test the EF6+ using MOQ. I am using the latest EF6 and did NOT have to change the class the inherits from DbContext such that the DbSets are virtual because they are already that way in the T4 templates.Also, if you need to access the .Set method of the DbContext then you will need to tell the mock what it should be returning using something like: mockContext.Setup(m => m.Set()).Returns(mockSet.Object); See here for more details.

Attributes for MSTesting - includes samples of attributes for setup and cleanup methods that apply to tests, classes, assemblies, etc depending on the scope you need. A class can be created that has assembly specific setup and cleanup and doesn't need to have any tests actually in the class itself. Teh class does need to be marked as TestClass() though.

Unit Testing Good Patterns #3 - Know Your Moq Argument Matchers - this is an excellent read to understand how to use the It and Verify classes.

Keeping up

Code Magazine

Entity Framework Team Blog

Wednesday, November 25, 2015

Using CDN (Content Delivery Networks) with ASP.NET MVC

CDN (Content Delivery Networks) can be a great way to speed up your ASP.NET MVC application for the following reasons:
  • Files are downloaded from the best geographical location
  • CDN networks are trusted and built for high availability and high usage
  • The browser can download files from several servers at the same time.
  • CDN networks can use caching to further improve performance
With ASP.NET MVC  we can specify a CDN to use AND also a fallback url in the event that the CDN is not available for some reason.

In BundleConfig.cs you can specify a CDN (Content Delivery Networks) url and a fallback url (on web app) if the CDN fails for some reason. The failure is determined on the browser side by checking a javascript expression specified by CdnFallbackExpression.

Here is an example of what can be done for the ~/bundles/query that is set by default on a new project.

            // use CDN if it is available.
            // NOTE: Won't show on local machine unless turn debugging off in web.config
            bundles.UseCdn = true;

            var bundle = new ScriptBundle("~/bundles/jquery",
                @"//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js");
            bundle.CdnFallbackExpression = "window.jquery";
            bundle.Include("~/Scripts/jquery-{version}.js");
            bundles.Add(bundle);

 
Be sure to set the bundles.UseCdn = true. Also, if you are running your project under debug (set in the web.config) then you won't get the bunding, minimizing, optimizations, etc, but you would in production. To force these in development, set debugging to false in the web.config.

Here is a list of CdnFallbackExpression values for common CDNs.

## Library ##      ## Expression ##
jQuery             window.jQuery  
jQuery.UI          window.jQuery.ui  
Modernizr          window.Modernizr  
Bootstrap          $.fn.modal  
jquery.transit     $.transit  
jquery.validate    $.validator  
json2              JSON.stringify  
webfont            WebFont  
jquery.blockUI     $.unblockUI()  
respond            window.respond  
moment             window.moment 
dataTables         $.fn.dataTable

NOTE: List copied from here and the augmented.
Great post on CDN

How to change the default Name of a TextBox when using MVC, Razor

We want this format so that each Name on the form is unique. Sometimes we need to change what the value of Name is on the HTML form.

Here is the simple example using @Html.TextBoxFor() to change it from the default of "StartTime" to "MyStartTime":

@Html.TextBoxFor(modelItem => item.StartTime, new { Name = "MyStartTime"})

Below is an example of how to set the Name of the StartTime TextBox when looping through a collection of complex objects such as an Appointment
In the html, the INPUT will have a names like:
Appointments[0].StartTime
Appointments[1].StartTime

The example below formats the Name html property to the format that the MVC binder understands and will automatically create the Appointment objects and bind to them.To better understand how the binding in MVC works, check out this article.

This is possible because @Html.EditorFor takes a parameter for the Name, but @Html.HiddenFor.

If you want to use @Html.TextBoxFor instead, it doesn't have this option, but we can use the htmlAttributes parameter. In this case, Name is CASE SENSITIVE. Using name will not work right.

 @{
        var @i = 0;
    }
    @foreach (var item in Model)
    {
                @Html.EditorFor(modelItem => item.StartTime, "TextBox", "Appointments[" + @i + "].StartTime", null)
                @Html.TextBoxFor(modelItem => item.StartTime, new { Name = "Appointments[" + @i + "].StartTime"})

                 i++;
    }


NOTE: You can also use a for loop instead of the foreach.
NOTE: This technique should also work for the other Html helpers, but I have not tested it.

Monday, November 23, 2015

Get a list of ApplicationUsers (Users) in MVC 6

If you need a list of all the user in your MVC 6 application.

The following will work from any controller.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
...
 var users = Request.GetOwinContext().GetUserManager().Users;

The generated controllers have a line like this:

private ApplicationDbContext db = new ApplicationDbContext();

After the above initialization takes place, you can also get a list of users by simply doing:

db.Users

Notice, I am NOT using db.ApplicationUsers which you may have been tempted to add to the ApplicationDbContext class using the following:

public DbSet ApplicationUsers { get; set; }

The problem as noted here is that that IdentityDbContext already has the following defined.

public virtual IDbSet Users { get; set; }

So, by adding the ApplicationUsers line above you have added two properties that map to the ApplicationUsers. Here is the error you will get if you have done this:

Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'MyApp.Models.ApplicationUser'.


Thursday, January 10, 2013

Introduction to Razor in MVC

Razor is a view engine that is used in MVC 3 and later. Files use the file extension .cshtml.

One of the nice things is that it is unit testable with standard Visual Studio unit tests.

A cleaner and more elegant view engine than the default view engine.

You can use multiple view engines in the same project, including ones that third-parties have created.

Syntax

It is simpler to use than the Web forms engine syntax used by the default MVC view engine.

Default way: <%: Html.ActionLink(“Register”, “Register”) %>

Razor way: @Html.ActionLink(“Register”, “Register”)

You’ll notice there is no closing code block needed and the opening code block is just the @ sign which is easier to type. It will still automatically encode the string as well.

Code Block

if you are using Html.BeginForm or other blocks of code you can do something like this. No need for the old <% %> tags

@Html.BeginForm() {
… <some html here>…
}

Comments

You can do a server side comment with

@”
Comment here
”@

Layouts

Razor uses Layouts instead of Master Pages. They are just like other Razor files except it uses @RenderBody() to designate where content should be. Each view has a Layout property that you can set to the layout file. Alternatively, you can define the default by creating a file that is has a special name_ViewStart.cshtml. That way you don’t need to specify the layout property on each view. You can also put the file in subfolders in the View folder to have only the views in that subfolder be affected.

Friday, December 21, 2012

MVC and Routing Basics

Routing is located in the System.Web.Routing namespace

Can be used in MVC and also ASP.NET web forms apps.

Routing is used to map incoming URLS to action methods in a controller and optionally pass arguments to the action methods.

Generates outgoing urls (links in pages; generally used for navigation).

check out www.useit.com for guidelines on url best practices.

Routing is similar to URL Rewriting (been around for a long time in ASP.NET web forms). URL rewriting is geared towards pages and doesn’t really apply to MVC. Now you should almost always use Routing, but in MVC it is hard not to use routing.

 

Defining a route

  • URL Pattern
  • Default values
  • Constraints
  • Arbitrary properties

Look in the Global.asax.cs file under the RegisterRoute() method. In the RegisterRoute method you will use the MapRoute() method to specify any of the 4 items listed above. There are many overloads for this method.

routes.MapRoute(
“Default”, // route name
”{controller}/{action}/{id}”, // url pattern
new { controller = "Home”, action = “Index”, id = “”} // parameter defaults
);

The order or the MapRoute method is very important. They are processed from top to bottom. so put routes from more specific to more general.

URL Pattern

Default URL pattern: {controller}/{action}/{id}

Consists of segments. Each segment has URL parameters or placeholders and are shown as {…} and some static text.

The RouteValueDictionary holds the values that the parameters take based on the current url. For example if the url is http://localhost/Dog/Edit/3 then when the route is matched the RouteValueDictionary will contain keys and values as shown below.

controller = Dog
action = Edit
id = 3

You don’t have to use / to separate the placeholders. You can use just about anything, but it should be something that is not the data

Some other examples of url patterns:

“Brent/{controller}-{action}-{id}” –> Brent/Dog-Edit-3

“Brent/{controller}-{action}/{id}” –> Brent/Dog-Edit/3

 

Default Values

Works much like optional parameters in methods. If the parameter is not specified routing looks to see if there is a default value for that parameter (placeholder). They are passed to the routes.MapRoute() method.

http://localhost - default values for controller and action

http://localhost/Dog/List - default values for id

 

Constraint

What will happen if your url is http://localhost/Dog/Edit/3? In this example, let’s assume that the id is an int and 3 will be assigned to it. This matches the routing pattern fine, but what would http://localhost/Dog/Edit/Jewel do? It would try to assign Jewel to an int and that would not work and would result in the YSOD. To make it so the pattern is not matched we can introduce a constraint to only match numbers. Constraints can use regular expressions to control accepted values.

We could change the route to something like this using an overloaded Map method.

routes.MapRoute(
“Default”, // route name
”{controller}/{action}/{id}”, // url pattern
new { controller = "Home”, action = “Index”} // parameter defaults – notice no id default
new { id = @”\d{1,6} }

);

routes.MapRoute(
“Default”, // route name
”{controller}/{action}”, // url pattern
new { controller = "Home”, action = “Index”} // parameter defaults,
);

The first route is to accomplish what we were looking for. Unfortunately, it doesn’t allow for things like http://localhost and http://localhost/Dog/List. So, we had to add the second route to allow those routes.

Handling an Arbitrary Number of Parameters

Can use a catch-all parameter that:

  • match URLS with arbitrary number of parameters
  • Ignores slashes
  • Captures everything after what matches the url pattern to the end of the url
  • Excludes the query string parameters (doesn’t capture)
  • MUST be the last parameter in the url
  • Can only have one in url pattern

To do this, just a * to the beginning of the parameter name.

routes.MapRoute(
“CatchAll”, // route name
”Catch/All/Params/{*randomParams}”, // url pattern
new { controller = "Dog”, action = “CatchAll” } // parameter defaults
);

There needs to be a method in the Dog controller called CatchAll. It would look something like this

public ActionResult CatchAll(string randomParams) {… }

A matching url might look like this: http://localhost/Catch/All/Params/and/more/stuff/goes/here.

In this example, “and/more/stuff/goes/here” would be passed to the CatchAll method.

It is up to you to do something with the string. In most cases you will parse it and do something interesting with the values in the url.

 

Blocking Routes

You may want to block users from particular urls. To do that you would typically put a new route as shown below as one of the first routes in your routes collection so that it matches first.

routes.IgnoreRoute(“{resource.axd/{*pathInfo}”)

or

routes.Add(new Route(“{resource}.axd/{*pathInfo}”, new StopRouteHandler()));

Both of these do the same thing.

 

Generating URLS

You could hardcode urls in your MVC application, but is difficult to maintain and messy. Luckily MVC makes it easy when you use the routes to automatically generate urls. To access this automatic generation you would typically use HtmlHelper.ActionLink and HtmlHelper.RouteLink helper methods.

ActionLink – the url is based on the combination of the controller and action name, and any other parameters

RouteLink – relies on the route definitions and parameters

Works just like incoming routes regard order, so Routing will match the first one it finds which is based on the order you add it to the collection of routes.

 

Named Routes

If you want to force a particular route to be used. This works because the route name is basically a key into the list of routes in the route collection. This affects both the automatically generated urls (see ActionLink and RouteLink) and incoming urls. This would be useful if you want to use a route that is farther down the list of routes and thus would not usually be matched. Some people say that you should not use named routes, but the choice is yours.

Monday, December 10, 2012

Intro to MVC

URLS have the default format: /domain/controller/method/ID

Controller

They are generally light, or that should be the goal. (I need to verify this comment)

Class must end in Controller suffix and implement IController interface. However, we usually inherit from the Controller class since it inherits from IController and provides more common code we need. It cannot be abstract and cannot use generic parameters.

index() is the name of the Action Method for the default method that will be called.

Unless a method says otherwise, it looks in the Views folder. It then looks for a folder named the same as the class (minus the suffix Controller). Then it looks for the page with the name that matches the method name.

Action Methods can be overloaded, but also have attributes that determine how it is used.

Requirements to be an Action method:

  • Public (and not static)
  • Must be defined on System.Object or Controller
  • Cannot be a special method
  • Cannot have a NonAction attribute.


Security Warning: Anybody on the internet can invoke any public Method in your controller unless decorated as NonAction. However, you would usually only include methods that should be invoked based on a url.

Use the [ActionName("MyNewActionNameHere")] attribute on the Action method to change how it is used in the url. This changes what is matched for routing the request.

HttpGet, HttpPost, HttpPut, HttpDelete attributes to affect what overloaded method is called based on how it is being called. The verb is based on the verb in the current request.

use HandleUnknownAction() method to change what happens when a bad url is passed (i.e. 404 error). We could redirect to error page for example.

Controllers should be simple. Logic should be in the model. A controller's job is to translate user's actions to the model, then provide a response.

It is not uncommon to directly reference the Model (including the Entity Framework) here using Linq. If you do, it is best to instantiate the Entity Framework model in the action method rather than creating it at the controller level.

Action Filters

Implemented as attributes that can be used on Action Methods in the controller or the controller itself. Can use more than one, and specify order.
AsyncTimeout, NoAsyncTimeout, Authorize, ChildActionOnly, HandleError, OutputCache, RequiresHttps, ValidateAntiforgeryToken, ValidateInput

View

use Html.RenderPartial() to render a user control

<%: ... %> will automatically html encode (if not already) what is being rendered. This is a better choice than <% ... %>

Should be as simple as possible. No calculations, etc. Logic and calculations should be in the Model.

Give the View the raw data, let it format it the way the user should see it.

Can use open source view engines such as: Spark, Nvelocity, Brail, Nhaml

Generally will want to put files, etc in the Content directory.

Use ContentResult object as a return type in the Action to send a file to the browser.

Use ViewData object for use with strongly-typed model and Dictionary (name/value pairs). Allows code nuggets (<% %>)
Code Nuggets: <% %>

<%= %> not recommended anymore, use <%: %> due to data not being encoded.

<%: %> always use instead of = nuggest since it will do same thing, but safely encode content.

HTML Helper Methods help with writing tedious common html. They are really just shortcuts to generate HTML. Examples: Html.Label(), Html.LabelFor(), Html.TextBox(), Html.TextBoxFor(), Html.BeginForm(), Html.ValidationSummary(), Html.ValidateMessageFor(), Html.ActionLink(), Html.RenderPartial(), Html.TextArea(), Html.Hidden(), Html.RouteLink(), Html.Action()

Partial Views (implemented as user Controls). They allow you to reuse html and view code. They can be handy for Create and Edit views that share nearly all the html. Generally they should be in the Views/Shared if they will be used by multiple controllers. If they will be used by one controller, but multiple views then put it in the Views/<Controller Folder>. use the Html.RenderPartial() to include the partial view on the part of the page you want it to display. Shares data with parent model by default, but this can be changed to use a different model by passing different model via Html.RenderPartial(). Partial views can be nested.

Use RenderAction() to call controller action methods from a view and display the result of that action method. useful to show data that is not part of the model of the view. Similar to using a RenderPartial(), but instead of inserting a partial view, you can insert virtually anything because most anything you return from an Action method. Beware of using this too often because the calls between controller and views becomes difficult to maintain. Only use it when needed.

HtmlHelper - AntiForgeryToken(), Encode(), EnableClientValidation(), AttributeEncode(), HttpMethodOverride(). 3 classes of helpers: 1. Untyped or regular helper methods, 2. Strongly typed helper methods, 3. templated helper methods. Lots of overloads. Searches for fields in the following order: ModelState, ViewData, and view model. Can put @ before a custom attribute that is passed to a helper. You can also use a Dictionary.
The Html.Label() helper method will use the Display() attribute from the Model to determine what text to display.

There are some high level helpers for Grids and Charts. For those, check out, WebGrid() with getHtml() and Chart with AddTitle(), AddSeries(). These are used with Razor.

Can supply a default value via an extra parameter on helper methods.

Most common Templated Helper Methods

  • Display, DisplayFor, DisplayForModel
  • Edit, EditorFor, EditorForModel

Models

Most any kind of technology or conventions can be used here. This would include things like Entity Framework, etc.
Encapsulates data and business rules, logic, validation, calculations, etc. This is where all the heavy lifting is done.
Use directly in conrollers and views
It is NOT required to add the suffix Model to the classes, but it does generally make it easier to follow in code.