Entity Framework – AutoDetectChangesEnabled

From MSDN

When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is handled by the Detect Changes algorithm. Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

But some times we need to turn off this feature. for example, I need to upload a excel file it contains a bulk data. At this time AutoDetectChangesEnabled is true then it take a lot time for insert all rows. I can do the data validations at db side.

Just check the difference of AutoDetectChangesEnabled ON and OFF while inserting a bulk data.

Normal way:

namespace TestAutoDetectChangesEnabled
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Time Test - AutoDetectChangesEnabled";
            string[] names = { "Arun", "Raj", "Musthaan", "Majeed", "Muzafir",
                                 "Hari", "Dharma", "Kannan", "Imran", "Santo",
                                 "Rahmath", "Jayesh" };
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var db = new AppContext();
            foreach (var i in Enumerable.Range(1, 20000))
            {
                var student = new Student()
                {
                    Name = names[(new Random().Next(0, 10))],
                    ContactNo = "9870002735",
                    RegNo = i.ToString().PadLeft(7, '0')
                };
                db.Students.Add(student);
                Console.Clear();
                Console.WriteLine("{0} records added", i);
            }
            db.SaveChanges();
            sw.Stop();
            Console.WriteLine("Taked time - {0}", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }

    public class AppContext : DbContext
    {
        public AppContext()
            : base("AppConnection")
        {

        }
        public DbSet<Student> Students { get; set; }
    }
    public class Student
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string RegNo { get; set; }
        public string ContactNo { get; set; }

    }
}

AutoDetectChangesEnabled-before

After disable AutoDetectChanges

 class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Time Test - AutoDetectChangesEnabled";
            string[] names = { "Arun", "Raj", "Musthaan", "Majeed", "Muzafir",
                                 "Hari", "Dharma", "Kannan", "Imran", "Santo",
                                 "Rahmath", "Jayesh" };
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var db = new AppContext();
            try
            {
                db.Configuration.AutoDetectChangesEnabled = false;

                foreach (var i in Enumerable.Range(1, 20000))
                {
                    var student = new Student()
                    {
                        Name = names[(new Random().Next(0, 10))],
                        ContactNo = "9870002735",
                        RegNo = i.ToString().PadLeft(7, '0')
                    };
                    db.Students.Add(student);
                    Console.Clear();
                    Console.WriteLine("{0} records added", i);
                }
                db.SaveChanges();
            }
            finally
            {
                db.Configuration.AutoDetectChangesEnabled = true;
            }
            sw.Stop();
            Console.WriteLine("Taked time - {0}", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }

AutoDetectChangesEnabled-after

See the difference, it almost 10x faster. But use it with care. Don’t forget to re-enable detection of changes after the loop — used a try/finally to ensure it is always re-enabled even if code in the loop throws an exception.

See System.Data.Entity.Validation.DbEntityValidationException Details

Today i got an error on saving data to db using EF.

An exception of type ‘System.Data.Entity.Validation.DbEntityValidationException’ occurred in EntityFramework.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

System.Data.Entity.Validation.DbEntityValidationException

but I can’t find out what are the failed validations.

System.Data.Entity.Validation.DbEntityValidationException2

No more details in quick watch. I stucked a little. At this time i find out the use of $exception.That is a special debugger variable. You cannot access it via code.

https://msdn.microsoft.com/en-us/library/ms164891.aspx

https://blogs.msdn.microsoft.com/shaykatc/2004/02/20/vs-2003-tip-3-view-exception-information-with-exception/

look  $exception in quickwatch.

System.Data.Entity.Validation.DbEntityValidationException3

 

The JSON request was too large to be deserialized.

I am working on a list and it has a bulk update through api. I am tested with upto 30 records and its working fine on my dev system. whilie update to QA they added a lot of records to update at that time I got an error The JSON request was too large to be deserialized

JSON request was too large
Problem is I am sending data as JSON as MVC’s default maximum Json deserializer members count is 1000. So I changed it in web.config.

<appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

Set Access-Control-Allow-Origin in Web API

If you access your web api methods from another domain using JQuery Ajax or GetJSON method then there you may see an error like
XMLHttpRequest cannot load (url). No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘(url)’ is therefore not allowed access.

You can just install CORS with package manager

Install-Package Microsoft.AspNet.WebApi.Cors

Follow this link http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Or create a own simple attribute like

  • Add a new class AllowCrossSiteJsonAttribute
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Response != null)
                    actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    
                base.OnActionExecuted(actionExecutedContext);
            }
        }
    
  • For whole API Controller
    [AllowCrossSiteJson]
    public class UserAPIController : ApiController
    {
            // GET api/userapi
            public HttpResponseMessage Get()
            {
                  return uservar;
            }
    }
    
  • For a specific API Call
    public class UserAPIController : ApiController
    {
             // GET api/userapi
             [AllowCrossSiteJson]
             public HttpResponseMessage Get()
             {
                   return uservar;
             }
    }
    

that’s it.

String Formating in c# 6

Formatting the string values are very common during development. We generally use String.Format() method, that replaces each format item in a specified string with the text equivalent values from the objects. While this is a common, sometimes this is confusing and produce error. Because, we need to specific the place holder for each item and […]

Rate this:

Learn ASP.NET MVC 5 in 2 days

Questpond has launched a full step by step course on ASP.NET MVC. This course from Shivprasad Koirala will help you to learn MVC (Model view controller) step by step in 2 days ( i.e in 16 hours) right from basics to a professional level. This is a Sponsored post and in this post, the first video will show you how to display a simple Hello world in ASP.NET MVC. Also, check out the complete syllabus for details. Shivprasad Koirala has published a video course on Questpond, which will step-by-step guide you to learn MVC 5 in just 2 days
(yes, you heard the word correct… just 2 days i.e. 16 hours only). Below is the complete syllabus of the course “Learn MVC 5 in 2 days”:Lab 01 : – Simple Hello world (20 minutes) Lab 02 : – Explain MVC Routing (10 minutes) Lab 03 : – Explain ViewData, ViewBag, TempData & Session Variables (20 minutes) Lab 04 : – Explain Model and Strongly typed views (20 minutes) Lab 05 : – Explain Model Binders (10 minutes) Lab 06 : – Why MVC and MVC vs Webforms? (30 minutes) Lab 07 : – Explain TempData, Peek and…(Read more)

ControlAdapter for ASP SiteMapPath

Today i faced a small issue related Breadcrumb. I’m using asp:SiteMapPath to show Breadcrumb. It works fine. But look and feel is little boring and i want it convert to bootstrap style. I tried to customize the design with diffrent templates properties, but always it shows surround a tag and bootstrap not working.
after some googling i found a solution ; add a Control Adaper for this.

Now it working fine and looks good.

First add a class for this ControlAdapter SiteMapPathControlAdapter.

 public class SiteMapPathControlAdapter : WebControlAdapter
    {
 public virtual string LinkCssClass
        { get; set; }
        protected override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.WriteLine();
            writer.WriteBeginTag("div");

            writer.WriteAttribute("class", ((System.Web.UI.WebControls.SiteMapPath)(Control)).CssClass);
            writer.Write(HtmlTextWriter.TagRightChar);
        }
        protected override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.WriteEndTag("div");
            writer.WriteLine();
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Indent++;
            SiteMapPath item = (SiteMapPath)Control;
            SiteMapProvider Provider = ((System.Web.UI.WebControls.SiteMapPath)(Control)).Provider;
            SiteMapNodeCollection collection = new SiteMapNodeCollection();
            SiteMapNode node = Provider.CurrentNode;
            if (node != null)
            {

                collection.Add(node);
                while (node != Provider.CurrentNode.RootNode)
                {
                    node = node.ParentNode;
                    collection.Add(node);
                }

            }
            BuildItems(collection, true, writer);
            writer.Indent--;
            writer.WriteLine();
        }
        private void BuildItems(SiteMapNodeCollection items, bool isRoot, HtmlTextWriter writer)
        {
            if (items.Count > 0)
            {
                writer.WriteLine();

                writer.Indent++;
                for (int i = items.Count - 1; i > -1; i--)
                {
                    BuildItem(items[i], writer);
                }
                writer.Indent--;
                writer.WriteLine();
            }
        }
        private void BuildItem(SiteMapNode item, HtmlTextWriter writer)
        {
            if ((item != null) && (writer != null))
            {
                if (item.Url.Length > 0)
                {
                    writer.WriteLine();
                    writer.WriteBeginTag("a");
                    writer.WriteAttribute("href", Page.ResolveUrl(item.Url));
                    string linkCSS = (Control.Attributes["LinkCssClass"] ?? "").ToString();
                    writer.WriteAttribute("class", linkCSS);
                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Write(item.Title);
                    writer.WriteEndTag("a");
                    writer.WriteLine();

                }
            }
        }
   }

Second add a browser file to link this adapter :

<browsers>
  <browser refID="Default">
    <controlAdapters>
       <adapter controlType="System.Web.UI.WebControls.SiteMapPath" adapterType="CSharpSampleWebApps.SiteMapPathControlAdapter" />
    </controlAdapters>
  </browser>
</browsers>

and my aspx page

<div>
        <asp:SiteMapPath runat="server" ID="SiteMapPath1" CssClass="btn-group btn-breadcrumb"
            LinkCssClass="btn btn-success">
        </asp:SiteMapPath>
    </div>

Now rendering HTML like :

    <div>
        
<div class="btn-group btn-breadcrumb">

		<a href="/default.aspx" class="btn btn-success">Home</a>

		<a href="/Services.aspx" class="btn btn-success">Services</a>

		<a href="/Training.aspx" class="btn btn-success">Training</a>


</div>

    </div>

Request URL in ASP.Net

Suppose i am request a page http://localhost:57089/test/WebForm1.aspx?id=10 then what are the request property values in server side ? Many of the cases we need part of a request URL. Maybe Some times Port No or File Path or Exact file Name etc.

I just write the values in server side Request Property.

// Accessing http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write( Request.RawUrl);
// /test/WebForm1.aspx?id=10
Response.Write( Request.Url.ToString());
// http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write(Request.Url.AbsolutePath);
// /test/WebForm1.aspx
Response.Write(Request.Url.AbsoluteUri);
// http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write("
" + Request.Url.Authority);
// localhost:57089
Response.Write(Request.Url.DnsSafeHost);
// localhost
Response.Write( Request.Url.Host);
// localhost
Response.Write(Request.Url.LocalPath);
// /test/WebForm1.aspx
Response.Write( Request.Url.OriginalString);
// http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write( Request.Url.PathAndQuery);
// /test/WebForm1.aspx?id=10
Response.Write(Request.Url.Port.ToString());
// 57089
Response.Write(Request.Url.Query);
// ?id=10
Response.Write( Request.Url.Scheme);
// http
foreach (var Segment in Request.Url.Segments)
{
Response.Write("
" + Segment );
}
// [0] /
// [1] test/
// [2] WebForm1.aspx
Response.Write("
" + Request.QueryString);
// id=10
Response.Write( Request.PhysicalPath);
// C:\Users\user\documents\visual studio 2010\Projects\WebApplication3\WebApplication3\test\WebForm1.aspx
Response.Write( Request.PhysicalApplicationPath);
// C:\Users\user\documents\visual studio 2010\Projects\WebApplication3\WebApplication3\
Response.Write(Request.Path);
// /test/WebForm1.aspx
Response.Write(Request.ApplicationPath);
// /

 Response.Write("<br/>" + System.IO.Path.GetFileName(Request.Url.LocalPath));
//   WebForm1.aspx
Musthaan
Musthaan

object into an XML string

Microsoft added the ability to create a static method in a static class that behaves like it’s a member of the class that it is called on. This has some interesting ramifications including that you can call an extension method off of a null reference

So let’s say you want to create an extension method that makes it easy to turn any object into an XML string. We could write:

public static class ObjectExtensions
    {
         public static string ToXml(this object input, bool shouldPrettyPrint)
        {
             if (input == null) throw new ArgumentNullException("input");
    
            var xs = new XmlSerializer(input.GetType());
           
         using (var memoryStream = new MemoryStream())
          using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))
          {
              xs.Serialize(xmlTextWriter, input);
               return Encoding.UTF8.GetString(memoryStream.ToArray());
           }
       }
    }

Now, we can easily write:

 // can convert primatives to xml
     string intXml = 5.ToXml();
     
     // can convert complex types to xml
    string objXml = product.ToXml();
     
    // can even call as static method if you choose:
    objXml = ObjectExtensions.ToXml(products);