What’s the difference between the Entity Framework and LINQ to SQL?
| LINQ TO SQL | ENTITY FRAMEWORK | |
|---|---|---|
| Complexity | Less complex | More complex |
| Model | Domain model | Conceptual data model |
| DB Server | SQL Server | Variety of database products |
| Development Time | Rapid application development | More time required but has mode features |
| Mapping Type | Class to single table | Class to multiple tables |
| Inheritance | Difficult to apply | Simple to apply |
| File Types | DBML files | EDMX, CDSL, MSL, SSDL files |
| Complex Type Support | No | Yes |
| Query Capability | LINQ to SQL through DataContext | LINQ to Entities, ESQL, Object Services, Entity Client |
| Performance | Slow for first query | Slow for first query but overall better than LINQ to SQL |
| Future Enhancements | No | Yes |
| Generate DB from Model | No | Yes |
- Complexity With more features comes more complexity, which is why LINQ to SQL,
which has fewer features, is considered easier to use than the Entity Framework, which
has more features. - Model LINQ to SQL provides a one-to-one mapping of tables to classes. If you have
Customers, Orders, and LineItems tables, you will have a Customer, Order, and LineItem
class to match up with rows of each table. The Entity Framework enables you to have a
Customer class whose data maps to several tables. This means the company name can
be in one table, but the address can be in a different table, and the phone number can
be in another table, and so on. - DB Server LINQ to SQL supports only Microsoft SQL Server 2000 and later, but even
SQL Server 2000 support has some limitations. The Entity Framework has support for
IBM DB2, Sybase SqlAnywhere, Oracle, SQL Azure, and many others. - Development Time LINQ to SQL is simple to learn and implement for rapid application
development, but LINQ to SQL has limitations that can cause problems in complex
applications. The Entity Framework has more capabilities, which can take longer to
learn and implement, but these features will minimize problems when creating complex
applications. - Mapping Type With LINQ to SQL, each table maps to a single class. If your database
has a join table, you must represent this as a class. Also, complex types cannot be easily
represented without creating a separate table. For example, if a customer has an
address and the Customers table has the address components in the table, you can’t
represent the address as a separate type. To represent the address as a separate type,
you must extract the address to its own table. With the Entity Framework, a class can
map to multiple tables. Regarding the address scenario, the address can be a type
even if it’s contained within the Customers table. - Inheritence LINQ to SQL supports Table per Class Hierarchy (TPH), whereas the Entity
Framework supports TPH and Table per Type (TPT). The Entity Framework also provides
limited support for Table per Concrete Class (TPC). - File Type LINQ to SQL uses a Database Markup Language (DBML extension) file that
contains XML mappings of entities to tables. The Entity Framework uses four files. The
first file is the Entity Data Model (EDMX extension), which the Entity Data Model designer
uses. At compile time, the other three files are created from the EDMX file. The
first of the three files is a Conceptual Schema Definition Language (CSDL extension)
file that contains XML definition of the conceptual model. The second file is the Store
Schema Definition Language (SSDL) file that contains XML definition of the storage
model. The third file is the Mapping Specification Language (MSL extension) file that
contains the mappings between the conceptual and storage models. - Complex Type Support A complex type is a nonscalar property of an entity type that
does not have a key property. For example, a customer has a phone number, but you
want the phone number to be defined as having a country code, an area code, a city
code, a number, and an extension. LINQ to SQL doesn’t support the creation of complex
types, but the Entity Framework does. - Query Capability You can query the database by using LINQ to SQL through the
DataContext object. With the Entity Framework, you can query the database by using
LINQ to Entities through the ObjectContext object. The Entity Framework also provides
ESQL, which is a SQL-like query language that is good for defining a query as part of
the model definition. The Entity Framework also contains the ObjectQuery class, used
with Object Services for dynamically constructing queries at run time. Last, the Entity
Framework contains the EntityClient provider, which runs queries against the conceptual
model. - Performance Both LINQ to SQL and the Entity Framework are slow when running the
first query, but, after that, you should find that both provide acceptable performance,
although the Entity Framework provides slightly better performance. - Future Enhancements Microsoft intended to obsolete LINQ to SQL after the Entity
Framework release, but LINQ to SQL was popular due to its simplicity, so Microsoft
responded to user feedback. You can expect that LINQ to SQL will not receive future
enhancements, however. - Generate Database from Model LINQ to SQL has no capability of generating the
database from the model. The Entity Framework supports two types of development,
Database First and Code First. With Database First development, the database already
exists, so there is no need to generate the database from the model. With Code First
development, you create your model, and, from the model, you can generate your
database.
Difference between NUnit and Visual Studio 2010 Unit Testing
| NUnit | VS2010 | |
|---|---|---|
| DLL | NUnit.Framework | Microsoft.VisualStudio.TestTools.UnitTesting |
| Annotation | [TestFixture] | [TestClass] |
| Annotation | [Test] | [TestMethod] |
| Annotation | [Setup] | [TestInitialize] |
| Annotation | [TestFixtureSetUp] | [ClassInitialize] |
| Annotation | [TearDown] | [TestCleanup] |
| Annotation | [TestFixtureTearDown] | [ClassCleanup] |
| Method | Assert.Ignore | Assert.Inconclusive |
Display data from excel file in webpage using ASP.Net
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// You can call YourPageName.aspx?cache=clear
// to clear "XlsDataCache" cache.
string qs = Request.QueryString["cache"];
if (qs != null)
{
if (qs == "clear")
Cache.Remove("XlsDataCache");
}
BindData();
}
}
protected void BindData()
{
string folderPath = "Your folder path here";
string fileName = "Your file name here";
if (Cache["XlsDataCache"] == null)
{
string command = @"SELECT * FROM [Sheet1$]";
gridviewSample.DataSource =
GetXls(Server.MapPath(folderPath), fileName + ".xls", command);
gridviewSample.DataBind();
Cache.Insert("XlsDataCache", GetXls(Server.MapPath(folderPath),
fileName + ".xls", command), null, DateTime.Now.AddMinutes(60), TimeSpan.Zero);
}
else
{
gridviewSample.DataSource = (DataView)Cache["XlsDataCache"];
gridviewSample.DataBind();
}
}
protected object GetXls(string folderPath, string fileName, string command)
{
string connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;
Data Source={0};Extended Properties=Excel 8.0", folderPath + "" + fileName);
using (OleDbConnection oledbConn = new OleDbConnection(connString))
{
try
{
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand(command, oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Fill the DataSet from the data extracted from
// the worksheet.
DataSet ds = new DataSet();
oleda.Fill(ds, "XlsDataSet");
// Bind the data to the GridView
return ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
throw ex;
}
finally
{
oledbConn.Close();
}
}
}
What should a developer know before building a public web site?
Ref from here
The idea here is that most of us should already know most of what is on this list. But there just might be one or two items you haven’t really looked into before, don’t fully understand, or maybe never even heard of.
Interface and User Experience
- Be aware that browsers implement standards inconsistently and make sure your site works reasonably well across all major browsers. At a minimum test against a recent Gecko engine (Firefox), a Webkit engine (Safari, Chrome, and some mobile browsers), your supported IE browsers (take advantage of the Application Compatibility VPC Images), and Opera. Also consider how browsers render your site in different operating systems.
- Consider how people might use the site other than from the major browsers: cell phones, screen readers and search engines, for example. — Some accessibility info: WAI and Section508, Mobile development: MobiForge.
- Staging: How to deploy updates without affecting your users. Ed Lucas’s answer has some comments on this.
- Don’t display unfriendly errors directly to the user.
- Don’t put users’ email addresses in plain text as they will get spammed to death.
- Add the attribute
rel="nofollow"to user-generated links to avoid spam. - Build well-considered limits into your site – This also belongs under Security.
- Learn how to do progressive enhancement.
- Redirect after a POST if that POST was successful, to prevent a refresh from submitting again.
- Don’t forget to take accessibility into account. It’s always a good idea and in certain circumstances it’s a legal requirement. WAI-ARIA is a good resource in this area.
Security
- It’s a lot to digest but the OWASP development guide covers Web Site security from top to bottom.
- Know about SQL injection and how to prevent it.
- Never trust user input (cookies are user input too!).
- Hash passwords using salt to prevent rainbow attacks. Use a slow hashing algorithm, such as bcrypt (time tested) or scrypt (even stronger, but newer) (1, 2), for storing passwords. (How To Safely Store A Password)
- Don’t try to come up with your own fancy authentication system: it’s such an easy thing to get wrong in subtle and untestable ways and you wouldn’t even know it until after you’re hacked.
- Know the rules for processing credit cards. (See this question as well)
- Use SSL/HTTPS for login and any pages where sensitive data is entered (like credit card info).
- How to resist session hijacking.
- Avoid cross site scripting (XSS).
- Avoid cross site request forgeries (XSRF).
- Keep your system(s) up to date with the latest patches.
- Make sure your database connection information is secured.
- Keep yourself informed about the latest attack techniques and vulnerabilities affecting your platform.
- Read The Google Browser Security Handbook.
- Read The Web Application Hacker’s Handbook.
Performance
- Implement caching if necessary, understand and use HTTP caching properly as well as HTML5 Manifest.
- Optimize images – don’t use a 20 KB image for a repeating background.
- Learn how to gzip/deflate content (deflate is better).
- Combine/concatenate multiple stylesheets or multiple script files to reduce number of browser connections and improve gzip ability to compress duplications between files.
- Take a look at the Yahoo Exceptional Performance site, lots of great guidelines including improving front-end performance and their YSlow tool. Google page speed is another tool for performance profiling. Both require Firebug to be installed.
- Use CSS Image Sprites for small related images like toolbars (see the “minimize HTTP requests” point)
- Busy web sites should consider splitting components across domains. Specifically…
- Static content (i.e. images, CSS, JavaScript, and generally content that doesn’t need access to cookies) should go in a separate domain that does not use cookies, because all cookies for a domain and its subdomains are sent with every request to the domain and its subdomains. One good option here is to use a Content Delivery Network (CDN).
- Minimize the total number of HTTP requests required for a browser to render the page.
- Utilize Google Closure Compiler for JavaScript and other minification tools.
- Make sure there’s a
favicon.icofile in the root of the site, i.e./favicon.ico. Browsers will automatically request it, even if the icon isn’t mentioned in the HTML at all. If you don’t have a/favicon.ico, this will result in a lot of 404s, draining your server’s bandwidth.
SEO (Search Engine Optimization)
- Use “search engine friendly” URLs, i.e. use
example.com/pages/45-article-titleinstead ofexample.com/index.php?page=45 - When using # for dynamic content change the # to #! and then on the server $_REQUEST["_escaped_fragment_"] is what googlebot uses instead of #!. In other words, ./#!page=1 becomes ./?_escaped_fragments_=page=1. Also, for users that may be using FF.b4 or Chromium,
history.pushState({"foo":"bar"}, "About", "./?page=1");Is a great command. So even though the address bar has changed the page does not reload. This allows you to use ? instead of #! to keep dynamic content and also tell the server when you email the link that we are after this page, and the AJAX does not need to make another extra request. - Don’t use links that say “click here”. You’re wasting an SEO opportunity and it makes things harder for people with screen readers.
- Have an XML sitemap, preferably in the default location
/sitemap.xml. - Use
<link rel="canonical" ... />when you have multiple URLs that point to the same content, this issue can also be addressed from Google Webmaster Tools. - Use Google Webmaster Tools and Yahoo Site Explorer.
- Install Google Analytics right at the start (or an open source analysis tool like Piwik).
- Know how robots.txt and search engine spiders work.
- Redirect requests (using
301 Moved Permanently) asking forwww.example.comtoexample.com(or the other way round) to prevent splitting the google ranking between both sites. - Know that there can be badly-behaved spiders out there.
- If you have non-text content look into Google’s sitemap extensions for video etc. There is some good information about this in Tim Farley’s answer.
Technology
- Understand HTTP and things like GET, POST, sessions, cookies, and what it means to be “stateless”.
- Write your XHTML/HTML and CSS according to the W3C specifications and make sure they validate. The goal here is to avoid browser quirks modes and as a bonus make it much easier to work with non-standard browsers like screen readers and mobile devices.
- Understand how JavaScript is processed in the browser.
- Understand how JavaScript, style sheets, and other resources used by your page are loaded and consider their impact on perceived performance. It may be appropriate in some cases to move scripts to the bottom of your pages.
- Understand how the JavaScript sandbox works, especially if you intend to use iframes.
- Be aware that JavaScript can and will be disabled, and that AJAX is therefore an extension, not a baseline. Even if most normal users leave it on now, remember that NoScript is becoming more popular, mobile devices may not work as expected, and Google won’t run most of your JavaScript when indexing the site.
- Learn the difference between 301 and 302 redirects (this is also an SEO issue).
- Learn as much as you possibly can about your deployment platform.
- Consider using a Reset Style Sheet.
- Consider JavaScript frameworks (such as jQuery, MooTools, Prototype, or YUI 3), which will hide a lot of the browser differences when using JavaScript for DOM manipulation.
Bug fixing
- Understand you’ll spend 20% of your time coding and 80% of it maintaining, so code accordingly.
- Set up a good error reporting solution.
- Have a system for people to contact you with suggestions and criticisms.
- Document how the application works for future support staff and people performing maintenance.
- Make frequent backups! (And make sure those backups are functional) Ed Lucas’s answer has some advice. Have a restore strategy, not just a backup strategy.
- Use a version control system to store your files, such as Subversion or Git.
- Don’t forget to do your Acceptance Testing. Frameworks like Selenium can help.
- Make sure you have sufficient logging in place using frameworks such as log4j, log4n or log4r. If something goes wrong on your live site, you’ll need a way of finding out what.
- When logging make sure you’re capture both handled exceptions, and unhandled exceptions. Report/analyse the log output, as it’ll show you where the key issues are in your site.
Versioning with the Override and New Keywords
Ref from here
The C# language is designed so that versioning between base and derived classes in different libraries can evolve and maintain backwards compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is completely supported by C# and does not lead to unexpected behavior. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that simply hides a similarly named inherited method.
C# allows derived classes to contain methods with the same name as base class methods.
- The base class method must be defined virtual.
- If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.
- If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
- If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method rather than the base class method.
- The base class method can be called from within the derived class using the base keyword.
- The override, virtual, and new keywords can also be applied to properties, indexers, and events.
By default, C# methods are not virtual — if a method is declared as virtual, any class inheriting the method can implement its own version. To make a method virtual, the virtual modifier is used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. For more information, see Compiler Warning CS0108.
To demonstrate this in practice, assume for a moment that Company A has created a class entitled GraphicsClass, which your program uses. GraphicsClass looks like this:
Your company uses this class, and you use it to derive your own class, adding a new method:
Your application is used without problems, until Company A releases a new version of GraphicsClass, which looks like this:
class GraphicsClass { public virtual void DrawLine() { } public virtual void DrawPoint() { } public virtual void DrawRectangle() { } }
The new version of GraphicsClass now contains a method entitled DrawRectangle. Initially, nothing happens. The new version is still binary compatible with the old — any software you have deployed will continue to work, even if the new class is installed on those computer systems. Any existing calls to the method DrawRectangle will continue to reference your version, in your derived class.
However, once you recompile your application using the new version of GraphicsClass, you will receive a warning from the compiler. For more information, see Compiler Warning CS0108.
This warning informs you that you need to consider how you want your DrawRectangle method to behave in your application.
If you want your method to override the new base class method, use the override keyword, like th
The override keyword makes sure that any objects derived from YourDerivedGraphicsClass will use the derived class version of DrawRectangle. Objects derived from YourDerivedGraphicsClass can still access the base class version of DrawRectangle using the base keyword, like this:
If you do not want your method to override the new base class method, the following considerations apply.To avoid confusion between the two methods, you can rename your method. This can be time-consuming and error-prone, and simply not practical in some situations. However, if your project is relatively small, you can use Visual Studio’s Refactoring options to rename the method. For more information, see Refactoring Classes and Types.
Alternatively, you can prevent the warning by using the keyword new in your derived class definition, like this:
Using the new keyword tells the compiler that your definition hides the definition contained in the base class. This is the default behavior.
Override and Method Selection
When a method is named on a class, the C# compiler selects the best method to call if more than one method is compatible with the call, such as when there are two methods with the same name, and parameters that are compatible with the parameter passed. The following methods would be compatible:
public class Derived : Base { public override void DoWork(int param) { } public void DoWork(double param) { } }
When DoWork is called on an instance of Derived, the C# compiler will first try to make the call compatible with the versions of DoWork declared originally on Derived. Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters. For example:
Because the variable val can be converted to a double implicitly, the C# compiler calls DoWork(double) instead of DoWork(int). There are two ways to avoid this. First, avoid declaring new methods with the same name as virtual methods. Second, you can instruct the C# compiler to call the virtual method by making it search the base class method list by casting the instance of Derived to Base. Because the method is virtual, the implementation of DoWork(int) on Derived will be called. For example:
Read data from CSV, and remove quotesm commas from numbers
public static void ReadCSV(string folderPath, string fileName)
{
using (StreamReader readFile = new StreamReader(folderPath + "\\" + fileName))
{
string line;
while ((line = readFile.ReadLine()) != null)
{
//Remove quotes, commas from numbers
string pattern = "\"([0-9.,]+)\"";
MatchEvaluator eval = delegate(Match match)
{
return match.Groups[1].Value.Replace(",", "");
};
line = new Regex(pattern).Replace(line, eval);
string[] strResult = line.Split(',');
for (int i = 0; i < strResult.Length; i++)
{
//Continue...
}
}
}
}
Use SharpZip Library to upload Zipped CSV files, and save each extracted CSV into datbase.
protected void UploadButton_Click(object sender, EventArgs e)
{
if (this.IsValid)
{
if (FileUpload1.HasFile)
{
// get the name of the file to upload.
string fileName = FileUpload1.FileName;
string zipExtension = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
if (zipExtension == "zip")
{
string zippedFilesFolder = ConfigSettings.ZippedFilesFolder + fileName;
// save zipped file on to folder.
FileUpload1.SaveAs(zippedFilesFolder);
string[] results = ProcessUploadedZip(fileName); // get list of file names.
for (int i = 0; i 0)
{
streamWriter.Write(data, 0, size);
}
else
{break;
}
}
names.Add(fileName); // Return a list of CSV file name.
AddIntoDatabse(fileName, data,(int)theEntry.Size); // Store each csv in database.
}
}
}
return (string[])names.ToArray(typeof(string));
}
private void AddIntoDatabse(string fileName, byte[] fileData, int fileSize)
{
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=ZippedUpload;Integrated Security=SSPI");
try
{
conn.Open();
string insertString = string.Format("insert into UploadedCSVFile (FileName, FileData, FileSize) values ({0}, {1}, {2})", DateTime.Now.ToString("yyyyMMdd") + "-" + DateTime.Now.ToString("HH:mm") + "-" + fileName, fileData, fileSize);
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Convert String to ByteArray
public static byte[] ConvertStringToByteArray(string stringToConvert)
{
return (new UnicodeEncoding()).GetBytes(stringToConvert);
}
public static string ConvertByteArrayToString(byte [] byteArray)
{
return (new UnicodeEncoding()).GetString(byteArray);
}
public static string ConvertByteArrayToString(byte[] byteArray, Encoding enc)
{
return enc.GetString(byteArray);
}
public static byte[] ConvertStringToByteArray(string stringToConvert, Encoding enc)
{
return enc.GetBytes(stringToConvert);
}