EF 4.1 – 4.2 “Code First” Perfomance Tip

Posted on October 28, 2011

EF always track entity and changes, but sometime if you need add/remove bulk records you may want temporary disable this tracking.

Example

db.Configuration.AutoDetectChangesEnabled = false;
foreach (var item in list)
{
db.Table.Add(item);
}
db.SaveChanges;
db.Configuration.AutoDetectChangesEnabled = true;

Share

MVC3 + EF CodeFirst + Facebook Authentication (Oauth) Part 1

Posted on September 13, 2011

MVC3 + EF CodeFirst +
Facebook Authentication (Oauth) Part 1

Lets mix
all together in one project

First step
create new MVC3 project

Create new MVC3 project

Next step -
selecting project type , creating test project (if you needed)

Download packages

I prefer
new Razor View Engine with HTML5 semantic markup.

For next
step I will use Nuget to install some
package to project

List of
package

1) http://nuget.org/List/Packages/EntityFramework/4.1.10715.0

2) http://nuget.org/List/Packages/jQuery/1.6.3

3) http://nuget.org/List/Packages/Facebook/5.2.1.0

4) http://nuget.org/List/Packages/FacebookWeb/5.2.1.0

5) http://nuget.org/List/Packages/FacebookWebMvc/5.2.1.0

 

Installing codefirstmembership

Now we need to install codefirstmembership

Go to http://codefirstmembership.codeplex.com/releases/61794/download/212575
and download latest version.

Copy
this source code (Code and Data directories) to your MVC3 application

Delete
default connection string from Web.Config

Replace
Web.Config values for default Membership, Profile and Role with this:

<membership defaultProvider=”CodeFirstMembershipProvider”>

<providers>

<clear />

<add name=”CodeFirstMembershipProvider” type=”CodeFirstMembershipDemo.CodeFirstMembershipProvider” connectionStringName=”CodeFirstContext” applicationName=”/” />

</providers>

</membership>

 

<profile enabled=”false”>

<providers>

<clear />

</providers>

</profile>

 

<roleManager enabled=”true” defaultProvider=”CodeFirstRoleProvider”>

<providers>

<clear />

<add name=”CodeFirstRoleProvider” type=”CodeFirstMembershipDemo.CodeFirstRoleProvider” connectionStringName=”CodeFirstContext” applicationName=”/” />

<add applicationName=”/” name=”AspNetWindowsTokenRoleProvider” type=”System.Web.Security.WindowsTokenRoleProvider” />

</providers>

</roleManager>

Add this to your Global.asax page in the Application_Start

protected
void Application_Start()

{

 

 

Database.DefaultConnectionFactory
= new SqlCeConnectionFactory(“System.Data.SqlServerCe.4.0″);

Database.SetInitializer(new CodeFirstContextInit());

//’Used to
preinitialize database, remove on production

var
Context = new CodeFirstContext();

Context.Users.FirstOrDefault();

}

*
Open AccountController
and replace LogOn and LogOff methods with this:

[HttpPost()]

public ActionResult LogOn(LogOnModel model, string returnUrl)

{

if
(ModelState.IsValid)

{

if
(CodeFirstSecurity.Login(model.UserName, model.Password, model.RememberMe))

{

if
(!string.IsNullOrEmpty(returnUrl) &&
Url.IsLocalUrl(returnUrl))

{

return Redirect(returnUrl);

}

else

{

return RedirectToAction(“Index”,
“Home”);

}

}

else

{

ModelState.AddModelError(“”, “The
user name or password provided is incorrect.”);

}

}

// If we
got this far, something failed, redisplay form

return
View(model);

}

public ActionResult LogOff()

{

CodeFirstSecurity.Logout();

return
RedirectToAction(“Index”, “Home”);

}

Try logging in with: Username: “Demo
Password: “Demo” or with Email: “demo@demo.com
(password is case-sensitive)

Some additional fix

1)
Replace
CodeFirstMembershipDemoSharp with solution name

2)
Remove
using System.Data.Entity.Database; from CodeFirstContextInit.cs

3)
Add using
System.Data.Entity;

Facebook

Now we move to Facebook

1.
Create
your application on Facebook. You can do so here: http://www.facebook.com/developers/createapp.php

Description: image

2.
We
have to set a few settings on our newly created Facebook Application. First,
lets set the Site Url in the Web Site tab. Set the site url to http://localhost:3434/.
After you have entered the information click save changes.

Description: image

3.
After
you save the changes you will be take to the app info page. Leave this open as
we will need some of the settings later.

4.
We
also need to set our application so that it runs on the same port every time.
So lets set our app to run on port 3434 (same as we already configured in the
Facebook Application settings). I am using IIS Express with Visual Studio 2010
SP1. I would highly recommend using IIS Express yourself rather than Visual
Studio Development server because there are some issues and difficulties. See
below how to set the port in IIS Express.

Description: image

5.
We
now need to edit a few of our web config settings. So open your web.config file
and find the section called facebookSettings. It will most likely be at the
very bottom of you config file.

<facebookSettings appId=”{app id}” appSecret=”{app secret}” />

6.
From
the Facebook Application info page you had open on step 3 find your App ID and
App Secret. Set these settings in your web.config file as shown.

<facebookSettings appId=”134035780002122″ appSecret=”a7adde41a7fd6228b656db70e0ba9d7c” />

To be continue (Extending Code first user, Autorisation Action etc)

Share

mysql .net connector error

Posted on August 05, 2011

Recently i use .net sql connctor for mysql ver 6.4.3   …

I describe some bugs i was faced  with

1) Input string was not in correct format

show up wen you rty make a connecton to server 

Promblem wit user locale (ru-ru for example)

Fix : change locale to  EN-US . But someone need to fix the source (im lazy to do this)

the same here http://bugs.mysql.com/bug.php?id=61797  this bug  

Like an option internets sugest downgrade to  6,3,7

http://dev.mysql.com/downloads/connector/net/6.3.html#downloads

After downgrading we get a “new” bug with incorrect SQL generation in EF

 

are you still using MySQL ?   

 PS

*1) Fixed in 6.2.6, 6.3.8 and 6.4.4+. 

Share

How to generate C# Class from XSD schema

Posted on June 30, 2011

 

 

Lets take our XSD schema file (from previous post)

We need a little console tool called: “XML Schema Definition Tool” (Xsd.exe).
in my case location was “C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin”
or
You may load link from start menu called “Visual Studio x64 Win64 Command Prompt 2010″ and all needed enviroments variable will be loaded for you. Left only type “xsd params”
We need only few console parameters for generation

/o —Specifies the directory for output files. This argument can appear only once. The default is the current directory
/c — Generates classes that correspond to the specified schema. To read XML data into the object, use the System.XML.Serialization.XMLSerializer.Deserializer method.
/f — Generate fields instead of properties.

type “xsd schema.xsd /c” and result is

 

This is all now we can add Station list to our app as resource/ In next post i show you how to load xml from an embeded resource

//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.431
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
///
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class StationList {
///
[System.Xml.Serialization.XmlElementAttribute("Station")]
public StationListStation[] Station;
}
///
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class StationListStation {
///
public string name;
///
[System.Xml.Serialization.XmlElementAttribute(DataType="anyURI")]
public string url;
///
public string freq;
}



let’s make a few coding style improvements

using System.Xml.Serialization;
using System.Collections.Generic;
///
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute]
[System.Diagnostics.DebuggerStepThroughAttribute]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
[XmlRootAttribute(Namespace = "", IsNullable = false, DataType = "StationList")]
public partial class StationList
{
///
[XmlElementAttribute("Station", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public List Stations { get; set; }
}
///
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute]
[System.Diagnostics.DebuggerStepThroughAttribute]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true, TypeName = "StationListStation")]
public partial class Station
{
///
[XmlElementAttribute(ElementName = "name",Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Name { get; set; }
///
[XmlElementAttribute(ElementName = "url", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, DataType = "anyURI")]
public string Url { get; set; }
///
[XmlElementAttribute(ElementName = "freq", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Freq { get; set; }
}

 

This all . we successfully add Station List class to app

In next post i show you how load resource from file.

Share