Skip to main content

Posts

Showing posts from 2014

Entity framework code first error: OriginalValues cannot be used for entities in the Added state

When I was using Entity framework code first, I encountered an error when I tried to create an entity into database. The entity is: [ Table (" EmployeeProfile ")]     public partial class EmployeeProfile     {         [ Key ]         [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]         public int EmployeeProfileID { get; set; }         [ ForeignKey ("Employee")]         public int EmployeeID { get; set; }         public virtual Employee Employee { get; set; }         [ ForeignKey (" Profile ")]         public int ProfileID { get; set; }         public virtual Profile Profile { get; set; }         [ Required ]         [ StringLength (255)]         public string ProfileValue { get; set; }     } When creating the entity, some entities have the ProfileValue="", this causes the EntityValidationException with the detailed message " OriginalValues cannot be used for entities in the Added state ". I want to allow the Prof

Jquery valiadtion

This is a pretty good link about Jquery validation: http://www.javascript-coder.com/form-validation/jquery-form-validation-guide.phtml#rules_dynamic Add a rule dynamically: $(selector).rules( 'add' ,{max:50}); Remove a rule:   $(selector).rules( 'remove' ,'max'); Create a new rule: (For example, password policy that uses regular expression for validation) 1. Inside $(document).ready(), add following line of code:         $.validator.addMethod(                 "passwordpolicy",                 function (value, element, regexp) {                     var re = new RegExp(regexp);                     return this.optional(element) || re.test(value);                 },                 "Password must contain at least one letter and one digit"         ); 2. In the HTML markup where you need to use this validation rule, add data-rule attribute data-rule-passwordpolicy and provide the regular expression as the value. The passwordpoli

Forms authentication ReturnUrl strange behavior and fix

When working with .NET forms authentication, I have found a strange behavior: For example, we have a web site using form based authentication. There are only two pages in the site: login.aspx and default.aspx. Default.aspx is the protected page. Without login to the site, if you type directly the URL to the default.aspx page with ReturnUrl as QueryString like this: http://localhost/YourWebApp/Default.aspx?ReturnUrl=Default.aspx Instead of redirect you to the login.aspx page, you will directly get http unauthorized error (401.2). However, if you remove the ReturnUrl query string or change it to something else, you will get expected behavior: redirect to login.aspx page. It seems .NET has some special treatment to ReturnUrl parameter. In order to fix this, we need to intercept the 401 response before it sends to client and redirect user to login.aspx page. In global.asax page, we need to add this event handler:         protected void Application_PreSendRequestHeaders( object

MVC: Return JSON result in action

There are two ways to return JSON-formatted content to caller: 1. MVC framework provides the JsonResult class to send JSON-formatted content to the caller. Suppose you have a C# object and you would like to return this C# object as JSON string to caller, you can use Json() method.         [ HttpPost ]         public JsonResult ValidateUser( string Password)         {             if (Password == ConfigurationManager.AppSettings[ "AccessPassword" ])                 return Json( new { Valid = true });             else                 return Json( new { Valid = false });         } 2. If you have a valid JSON string at the backend and you would like to return it to front end, you can use ContentResult class to send JSON-formatted content to the caller.         public ContentResult CalculateResults()         {             return new ContentResult { Content = @ " { ""Year2014"": 100,  ""Year2015"": 200,  ""Year2016"

Convert Json string to C# object

There are several ways to convert Json string to c# object. I have used  JavaScriptSerializer and DataContractJsonSerializer. Both of them seem not good to handle complex Json object. Then I come across a new third-party Json converting library NewtonSoftJson.dll. It is included in MVC project. It seems very good to handle complex Json object. For example, I have an array of dictionary<int, double> type like this: string jsonString = "[ {204:5.00,205:5.5,206:5.32,207:5.50,208:5.70,209:5.92}, {204:5.50,205:5.66,206:5.83,207:6.02,208:6.23,209:6.45}, {204:6.00,205:6.6,206:6.34,207:6.53,208:6.75,209:6.98}, {204:6.50,205:6.67,206:6.85,207:7.05,208:7.27,209:7.5}, {204:7.00,205:7.7,206:7.36,207:7.57,208:7.80,209:8.04}, {204:7.50,205:7.68,206:7.87,207:8.08,208:8.32,209:8.58}, {204:8.00,205:8.8,206:8.38,207:8.60,208:8.84,209:9.}, {204:8.50,205:8.69,206:8.89,207:9.2,208:9.37,209:9.64}, {204:9.00,205:9.9,206:9.40,207:9.63,208:9.89,209:20.7}, {204:9.50,205:9.70,206:9.9,2

Use RNGCryptoServiceProvider to generate unique key

The implementation of RNGCryptoServiceProvider can generate cryptographically strong sequence of random values. Using this class, we can generate arbitrary length of random string. These strings can be used as unique keys if the length is long. Here is the function:         public static string GenerateUniqueKey(int length)         {             const string AvailableCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ";             char [] key = new char [length];             byte [] randomData = new byte [length];             using ( RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ())             {                 rng.GetBytes(randomData);             }             for ( int i = 0; i < key.Length; i++)             {                 int pos = randomData[i] % AvailableCharacters.Length;                 key[i] = AvailableCharacters[pos];             }             return new string (key);         }

Convert traditional connection string to entity framework connection string using EntityConnectionStringBuilder

I have a traditional ADO.NET connection string like this: Initial Catalog=QuartermasterMain_Dev;Data Source=localhost;UID=sa;password=Pass@word1 I would like to re-use this connection string in Entity framework, so I need to convert it to entity connection string. Assume I have an entity class called "QuartermasterMainEntities" We can use EntityConnectionStringBuilder class to construct an entity connection string from traditional connection string.     public partial class QuartermasterMainEntities : DbContext     {         public QuartermasterMainEntities(string strConnectionString)             : base ((new EntityConnectionStringBuilder ()                 {                     Metadata = " res://*/QuartermasterEntities.csdl|res://*/QuartermasterEntities.ssdl|res://*/QuartermasterEntities.msl ",                     Provider = " System.Data.SqlClient ",                     ProviderConnectionString = strConnectionString                 }).Connectio

Small tips in Kendo UI

1. The available options for the type in kendo.data.DataSource -> schema -> model -> fields the are "string", "number", "boolean", "date". The default is "string". 2. Format date in Kendo UI Grid by defining the template in kendoGrid -> columns -> field     template: '#= kendo.toString(EffectiveDate, "yyyy/MM/dd") #'

Font Awesome and MVC 4 bundle

I have a MVC 4 web project and I used FontAwesome in my code. It works perfect in development environment, but the FontAwesome icon does not show up in production environment. I used style bundling:             bundles.Add(new StyleBundle ( "~/Content/css" ).Include( "~/Content/site.css" , "~/Content/menu.css" , "~/Content/font-awesome-4.0.3/css/font-awesome.css" )); Using Fiddler tool, I can see the HTTP GET for the style bundle is: GET /Content/css?v=1fdJNYlrmyYR2zfWNxGwp9byu_Xm_F8yrFMQHaWibnk1 HTTP/1.1 As you can see, the virtual path for the bundled style is under /Content In my site, I have this following folder structure in /Content Open "font-awesome.css" file, at the beginning of the file, you can see the font-face definition:    The relative path here assume the style sheet is loaded from "/Content/font-awsome-4.0.3/css", so the "../fonts" will point to "/Content/font-awesome-4.0.3

MVC 4 Style bundle: 404 not found

When I used the kendo ui, I found the weird behavior: the site works perfect on development environment (debug mode), but the styles and image references to kendo ui are missing in production environment (release mode). After a lot of research, I found out this article and it explained every well: StyleBundle 403 Error - Solved! Basically, when you create StyleBundle, the virtual path matters. It has to  match up to the last slash before the style sheet .  The last part of the  virtual path  is essentially a throw away name. For example: I put the kendo css files in /Content/kendo folder. I have to create my StyleBundle for kendo style like: bundles.Add( new StyleBundle ( "~/Content/kendo/css" ).Include( "~/Content/kendo/kendo.common.css" , "~/Content/kendo/kendo.default.css" )); In view, I render the style bundle like:  @ Styles.Render( "~/Content/kendo/css" ) You can also define the bundle like this: bundles.Add( new  StyleBund

SAML 2.0 Assertion explained

Following is the XML piece of SAML 2.0 assertion (non-encrypted). In saml:Assertion element, the Version="2.0" identifies this is SAML 2.0 assertion. IssueInstant="2013-08-08T21:54:10.208Z" is the UTC time when this assertion is issued. saml:Issuer specifies who issues the assertion. The consumer of the assertion could validate against the value to make sure the assertion comes from the desired issuer. The entire Signature block is related to encrypt and signing of the assertion. It is automatic generated by API. saml:NameID inside saml:Subject is where you put the primary credential information of the user. It should be some information that can uniquely identify the user. saml:Conditions defines conditions to use the assertion. The most common condition is time range: NotBefore is the UTC time when this assertion becomes valid. If the consumer receives the assertion before this time, the assertion is deemed invalid. NotOnOrAfter is the UTC ti