Thursday, October 31, 2013

Creating an Easy Data Access Layer using Entity Framework

Data Access Layers

The purpose of a Data Access Layer is to simplify access to data stored in a persistent storage separate from your application.

In the past, creating a functional and easy-to-use Data Access Layer (DAL) in your application could be a tedious and long-winded process. Following this tutorial, you will learn how to easily generate a DAL from a database with minimal effort. You will learn how to automatically generate classes that map your database entities, their relationships, and even the stored procedures to .NET objects and methods. You’ll also discover how to update your DAL when the database has been changed. Finally, you’ll learn how to extend your automatically created classes to really customise your DAL.

Pre-Requisites

The following are required for this tutorial:
• SQL Server
• SQL Server Management Studio
• Some flavour of Microsoft Visual Studio
• The Entity Framework DLL (I use http://www.microsoft...s.aspx?id=8363)

The Database

Creating the Instance

I’m going to start by creating a SQL Server database for our application. It’s possible to use many database types, but that is beyond the scope of this tutorial. Note that if you’re using Visual Studio Express you might need to create a class library using Visual Web Developer to connect to anything other than SQLCE databases (including SQL Server). We’re going to start really simple by creating a database that just tracks Users, Products and Orders.

Firstly, from SQL Server Management Studio, click the “Connect” drop-down and select “Database Engine”. You can also use “File” -> “Connect Object Explorer” and use the drop-down to select “Database Engine”. You’ll see the “Connect to Server” dialog as in the screenshot below.


Spoiler
Posted Image


Use this to connect to your SQL Server instance as usual. You should then be able to view your available databases in the Object Explorer as in the below screenshot. I haven’t got any at the moment, but that’s about to change.

Spoiler
Posted Image


Right-click on the “Databases” folder and click “New Database”, after which the “New Database” dialog should then appear as below.

Spoiler


Set your database name. I’m going to call mine “EntityTutorial”. Now click OK, and the database will be created. You should be able to see it sitting in your Object Explorer.

Creating the Tables

To start with, our application database is going to be very simple. We’re going to have 3 tables; “Users”, “Products”, and “Orders”. Expand your database, and right-click the “Tables” folder. Next, select “New Table” and you will then be able to design your table. Using the “Properties” window, name the table “Users”. We need to also add the columns “UserID” (an “int” type that does not allow nulls), “UserName” (nvarchar(5), not nullable), “FirstName” and “LastName” (nvarchar(5), nullable), and “EmailAddress”(nvarchar(MAX), not nullable). Before we finalise this table, we need to make the UserID field start from 1 and auto-increment itself. That means the IDs for this table will be assigned on creation, and we don’t need to worry about them. Click on the “UserID” column, and you will see the “Column Properties” section of the window has its details. In the “Identity Specification” section, set “(Is Identity)” to “Yes”, and ensure the fields “Identity Increment” and “Identity Seed” fill with a 1. Save and close this table design.

Do the same to create two more tables. “Products” will need columns for “ProductID” (int, not nullable, identity), “ProductName” (nvarchar(100), not null), “Description” (nvarchar(MAX), null), “Price”(float, not null), “AddedBy” (int, not null), and “AddedOn”(datetime, not null). The “Orders” table needs columns “OrderID” (int, not null, identity), “Product” (int, not null), “OrderedBy” (int, not null), “OrderedOn” (datetime, not null), and “Quantity” (int, not null).

Spoiler


All three tables should now be showing in object explorer, as in the screenshot above. However, if you examine them, you’ll notice there are no Primary Keys on any table. We want the ID field (first column) from each table to be the Primary Key, so we need to add them. Right-click a column on the “Users” table, select “Modify” and you’re taken back to the designer. Then, right-click the column selector to the left of the “UserID” column and select “Set Primary Key”; there should now be a yellow key next to it. Do the same for the “Products” and “Orders” tables, setting the “ProductID” and “OrderID” columns as Primary Keys.

You might have been sharp enough to pick up on the fact that we’ve created some columns that will connect to another column in another table. We’ll set these as Foreign Keys now. Right-click the “Keys” folder for the “Products” table, and select “New Foreign Key…” You’ll see a “Foreign Key Relationships” dialog like the screenshot below.

Spoiler


Click the ellipsis (“…”) button and you’ll see a “Tables and Columns” dialog. Change the “Primary key table” to “Users”, set the left column to “UserID” and the right to “AddedBy”. That means that when a Product gets added, it will need to reference the UserID of the user who added it. Click “OK”, then “Close”.

Spoiler


Do the same linking the “Product” field on the “Orders” table to the “ProductID” field on the “Products” table, and the “OrderedBy” field on the “Orders” table to the “UserID” field on the “Users” table. You will have to add a second relationship in the “Tables and Columns” dialog or you will overwrite your previous relationship. Our database is complete, for now.

The Data Access Layer

Connecting to the Database

So, we have a simple database for our application. Now, we need an application for our simple database. Using Visual Studio, let’s create a new Console project named “EntityTutorial”. The first thing I’m going to do is add another project to this solution: a Class Library called “DataAccessLayer”. I’m also going to delete the “Class1” file generated with that library.

First, we need an EDMX: this is a file that defines the mapping to the database. These are really easy to generate in Visual Studio. Right-click your “DataAccessLayer” project and select “Add”, then “New Item…” An “Add New Item” dialog will appear. Select “ADO.NET Entity Data Model” and name it “TutorialModel.edmx”.

Spoiler
Posted Image


When you click “Add”, you’ll be taken to the “Entity Data Model Wizard”. First, select “Generate From Database” and click “Next”. Then, you’ll need to create a new connection to your database: Select “New Connection”, ensure your Data Source is “Microsoft SQL Server (SqlClient)” and select the “Server name” and “Database name” fields. Note as per my previous warning, if using Visual Studio Express you may have to use Visual Web Developer Express to create this connection.

Spoiler


Click “Test Connection”, and hopefully it will succeed. Click “OK” and in the previous part of the Wizard, you’ll see a new connection string, as well as a checkbox asking if you want to save the connection string. Make sure you have, so you can substitute a different database location further down the line. Click “Next, and the Wizard will retrieve information from your database. Select all the Tables and click “Finish”.

Spoiler


Once the EDMX has been created, you’ll see it looks similar to the database we made, including the relationships (as indicated by the dotted lines). Great! We have a connection from our application to the database.

Generate the Entity Classes

Next, we want to generate the classes we will use in our application that will be modelled on our database. We will also generate a “DbContext” class that will give us read/write access to the database so we can get and manipulate these objects from storage, as well as save any state changes.

To begin with, you’ll need to get the “Entity Framework 4.x [or 5.x] DbContext Generator” component from the Online Gallery in Extension Manager. Then, right-click your EDMX and select “Add Code Generation item…” Select “EF [ver] DbContext Generator” and set the name as “TutorialModel.tt” and click “Add”.

Seconds later, this should have finished. You’ll have two new items in the Solution Explorer: “TutorialModel.Context.tt” and “TutorialModel.tt”. If you expand the “TutorialModel.Context.tt” you should also see “TutorialModel.Context.cs”.

Below the “TutorialModel.tt” you have “Order.cs”, “Product.cs”, “TutorialModel.cs” and “User.cs”.

Open the User.cs class; you’ll see it has properties to match each database field, and an ICollection to represent the relationships. Also check out the “TutorialModel.Context.cs” class; this inherits from DbContext, giving us access to the underlying database. However, this project will need to reference Entity Framework; add a reference to the project and navigate to where the DLL is saved on your machine.

A quick note: NEVER make changes to these classes. They’re generated automatically, and can be overwritten when regenerated. Later, we’ll learn how to extend these classes.

Using the Classes

Creating a New User

At some point we’re going to need to use what we’ve made here, so let’s add a reference in our EntityTutorial console application to our DataAccessLayer project. You’ll also need to add a reference to Entity Framework. Now, in the Program.cs class file, add a method with the following signature:
1private static bool AddUser(string userName, string firstName, string lastName, string emailAddress)

This helper method will allow us to easily create a user and save it in the database. It will also return true if the save was successful.
We need to create a context. The good news is, the DbContext class implements the IDisposable interface, so we can wrap it in a using statement, like so:
1using (var dbContext = new EntityTutorialEntities())

That forces the context to be disposed of implicitly when out of scope. Within curly braces, we then need to create an object of type User (I’m going to use an object initializer to save effort):
1var user = new User
2                    {
3                        UserName = userName,
4                        FirstName = firstName,
5                        LastName = lastName,
6                        EmailAddress = emailAddress
7                    };

Now we need to add this User object to the database context’s Users collection.
1dbContext.Users.Add(user);

The database context class has methods we can invoke as well as the collections of objects representing the tables. The SaveChanges() method will, unsurprisingly, save changes to the database, and its return value is the number of changes saved.
1var changesSaved = dbContext.SaveChanges();

Finally, we will return true if the changesSaved variable has a value of greater than or equal to 1.
1return changesSaved >= 1;

The whole method looks like this:
Spoiler

Let’s test that works. Add this line to the Main method in your console app’s Program.cs:
1var addedUser = AddUser("MrShoes", "Mister", "Shoes", "mrshoes@shoefits.com");

Hopefully, you understand what that line does: it creates a user with the user name “MrShoes”, first name “Mister”, last name “Shoes”, email address “mrshoes@shoefits.com”, and the variable addedUser holds a Boolean value indicating whether the changes were saved or not. We probably want to output something to the screen.
1Console.WriteLine(addedUser ? "A user was added." : "No user could be added.");
2Console.ReadKey();

Run the console application and let’s see the result.

Spoiler


Oh no! An unhandled exception! The message for this exception is: "No connection string named 'EntityTutorialEntities' could be found in the application config file." Yes, we do have an app.config with that information in the class library; we just need to copy the file into the console project. You can easily do that in VS by right-clicking the App.config file and selecting “Copy”, then right-click the console project and select “Paste”. Run it again and you should see:

Spoiler


Seems like it’s been successful. Let’s check the Users table in the database.

Spoiler


You’ll see a new entry in this table matching what we added in code; even better, the row has a UserID property that was automatically generated.

Getting a User from the Database

Obviously, we need to be able to read from the database as well as writing to it. We use the same DbContext object to access the database entities, which will automatically be mapped to the classes we’ve created.

If you wanted to get all the Users, for example, you’d use:
1var allUsers = dbContext.Users;

The variable allUsers would then be of type DbSet and, in our current state, will include one single User object. If you wanted to get the users with an ID greater than 7, you’d use:
1var usersAfterSeven = dbContext.Users.Where(u => u.UserID > 7);

In this case, the “usersAfterSeven” variable would be of type IQueryable and in our example hold no entries (since our only user has an ID of 1). The .Where() extension method is very useful when using Entity Framework, but can be fairly intimidating if you’re not familiar with using a lambda as a predicate. It’s beyond the scope of this tutorial, but I’m sure you’ll quickly pick up how to use them.
1var firstUser = dbContext.Users.FirstOrDefault();

The above line will return a single User object, the first in the database, or null if there are no Users stored. What’s useful is that you can also supply a lambda expression as an argument to the .FirstOrDefault extension method. For example, if you want to get a User by its UserName property, you’d use:
1return dbContext.Users.FirstOrDefault(u => u.UserName == 1);

That will return our User from the database. Let’s create another method in our console app to help us get Users by UserName.
Spoiler

Now let’s try this out. Change your Main method to match:
Spoiler

Run that, and you should get this output:

Spoiler



Creating a New Product

We’re going to create a method that will help us easily add Products to the database. This method will also take an object of type User as a parameter. Create a method with the following signature:
1private static bool AddProduct(string productName, string description, double price, User addedBy)

We need to create the database context as before.
1using (var dbContext = new EntityTutorialEntities())

Now, within curly braces, we use an object initializer to create a Product object.
1var product = new Product
2{
3ProductName = productName,
4Description = description,
5Price = price,
6AddedOn = DateTime.Now,
7AddedBy = addedBy.UserID
8};

You notice that for the AddedBy property, we’re accessing the UserID of the User object we’ve passed as a parameter. This will ensure we are creating the correct relationship between entities. We’re also using DateTime.Now to store as the AddedOn date. As before, we need to add the Product to the context’s Products collection.
1dbContext.Products.Add(product);

The method should look like this, after we’ve finished it off the same way we did AddUser:
Spoiler

Change your Main method like so:
Spoiler

Run this, then check your database.

Spoiler


We now have a new Product, it has been assigned its own ProductID, and the AddedBy matches the User’s UserID field.

Getting a Product from the Database

Returning the Products is done the same as with Users. Four our purposes, we’ll use a helper method:
Spoiler

You might also want a method that lets you easily get the Products that were created by a User. Because the relationship exists in the database, Entity Framework will allow us to access them simply as a property of a User object.
Spoiler

Creating a New Order

By now, you won’t be surprised to hear that we’re going to make a helper method just like our others to create Orders.
Spoiler

We’ll add an order from our Main method.
Spoiler

Run this and check your Orders table in the database.

Spoiler


You can see it has been added, and the ProductID and OrderedBy field match the User and Product we created earlier.

Dealing with Changes

Often, especially when developing a new product, the database might change. Whether it’s new tables, new columns, or stored procedures, if you wish to use them in your application you’ll need to update the mapping in your EDMX. Fortunately, that’s just as easy as it was to generate the EDMX in the first place.

Adding a New Column

In SQL Server Management Studio, right-click your Users table and select “Design”. Add a new column “LastActive” of type datetime, and allow nulls. Close and save this table.

Spoiler


The column now exists in the table, but not our Entities nor our mapping. Return to the EDMX in Visual Studio, right-click and select “Update Model from Database…” You’ll then be shown the Update Wizard.

Spoiler


Click “Finish” and it will refresh the current tables. After a while, you’ll see the “LastActive” field has been added to your EDMX. Check your User.cs file and… oh, it hasn’t changed. Not yet, at least. Save your EDMX and check again.
Spoiler

OK, we now have the LastActive property. It’s important to remember that the code generation tool won’t be re-run until the EDMX is saved.

Adding a New Table

Sometimes an entirely new table has been added to the database, and you’ll need to start using it in your application. This is just as easy as adding a column.
To start with, in SQL Server Management Studio, we’ll create a new table called “News”, with the columns ItemID(int, not null, identity), Date(datetime, not null), Heading (varchar(200), not null), Body (text, not null), and AddedBy(int, not null). Set ItemID as the Primary Key, and create a relationship linking AddedBy to the UserID field in the Users table.

We’ll need to map this in our EDMX. Go back to Visual Studio, right-click the EDMX and select “Update Model from Database…” This time, you’ll be able to select the “News” table to add, so do that and select “Finish”.

Spoiler


The “News” table has now been mapped to entities, and the relationship has been created. Save, and you should now have a News.cs class file.
Spoiler

You should also see a new collection named “News” in the User class.
Spoiler

Adding a Stored Procedure

Sometimes, the database will have stored procedures that you’ll need to call. This is also possible using the mapping of Entity Framework, and it makes calling a stored procedure as simple as invoking a method.

In SQL Server Management Studio, navigate to “Programmability” -> “Stored Procedures” in your database. Right-click and select “New Stored Procedure”. Replace the template text with the following:
Spoiler

Run this and the procedure will be created. You will be able to see it in the Stored Procedures folder. Now, let’s add it to our mapping. Again, go to Visual Studio, right-click your EDMX and select “Update Model from Database…” Now you will be able to select the “DeleteUser” stored procedure; do so, then click “Finish”.

This time, you won’t see anything visually added to your model. That makes sense, since we’ve only added a stored procedure and not an object. We need to use “Function Import” to add this to our context class. Go to the “Model Browser” window in VS (if you can’t view it, right-click on the EDMX and select “Model Browser”) and, there in the Stored Procedures folder you should see our “DeleteUser” procedure. Right-click it and select “Add Function Import”.

Spoiler


The “Add Function Import window will now appear. We don’t need to change anything here, we’re not returning anything and we don’t need to change the name. Click “OK”, then save your EDMX. The EntityTutorialEntities class should now look like this:
Spoiler

Ok, we can see that all the Entities we’ve created are collected here, and we now have a DeleteUser method. How do we call it?
1dbContext.DeleteUser("MrShoes");

Extending the Classes

I mentioned earlier that you should never change the automatically generated classes. That’s because any update will rerun the code generator, and will therefore overwrite any changes you make. However, the people who made the code generator knew you might need to extend the classes, and so they made them partial classes.

To extend the classes, then, you only need to create a new class with the same name in the same namespace, and also make it partial. That way, you can access all the properties and methods of the generated classes and create your own.

Create a new UserExtend.cs file in your DataAccessLayer project, so we can extend the User entity. Add the keyword to the class definition, and rename it “User” from “UserExtend”.

Let’s give it a property that returns the number of Orders placed by the User.
1public int NumberOfOrders { get { return Orders.Count; } }

Now you see we can access the Orders collection from this extended class, even though it is defined in a separate file. They are the same class defined in multiple files.

Maybe you want to use this class as an IIdentity so your application can keep track of which user is logged in. Change the class signature:
1public partial class User : IIdentity

Remembering to add the statement:
1using System.Security.Principal;

And implement the interface members:
1public string Name{ get { return UserName; } }
2public string AuthenticationType { get { return "Standard"; } }
3public bool IsAuthenticated { get { return true; } }

Now our generated class implements a useful interface!

Summary

By now you’ll see just how easy it can be to automatically generate a DAL from a database with automatically generated code. Obviously, it’s possible to create much more complex data layers than the one shown, but this should server as a good reference for a starting point.

Monday, April 29, 2013

[Sample Of Apr 26th] Interactive Windows Service

[Sample Of Apr 26th] Interactive Windows Service:

Homepage image
RSS Feed
Sample Download : http://code.msdn.microsoft.com/CSCreateProcessAsUserFromSe-b682134e
The sample demonstrates how to create/launch a process interactively in the session of the logged-on user from a service application written in C#.Net..
image
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

[Sample Of Apr 25th] Complex Type Objects demo in EF

[Sample Of Apr 25th] Complex Type Objects demo in EF:

Homepage image
RSS Feed
Sample Download : http://code.msdn.microsoft.com/CSEFComplexType-d058a5a3
 The code sample illustrates how to work with the Complex Type which is new in Entity Framework 4.0.  It shows how to add Complex Type  properties to entities, how to map Complex Type properties to table columns, and how to map a Function Import to a Complex Type.
image
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

[Sample Of Apr 24th]Customize ASP.NET TreeView node as RadioButton

[Sample Of Apr 24th]Customize ASP.NET TreeView node as RadioButton:

Homepage image
RSS Feed
Sample Download : http://code.msdn.microsoft.com/VBASPNETRadioButtonTreeView-8a1b8fe9
The project shows how to simulate a RadioButton Group within the TreeView control to make the user can only select one item from a note tree in ASP.NET.
image
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

[Sample Of Apr 23rd] Invokes ADO.NET Data Services in .NET

[Sample Of Apr 23rd] Invokes ADO.NET Data Services in .NET:

Homepage image
RSS Feed
Sample Download :
CS Version: http://code.msdn.microsoft.com/CSADONETDataServiceClient-aaeafce9
VB Version: http://code.msdn.microsoft.com/VBADONETDataServiceClient-ff0849a9
The code sample shows how to invoke the ADO.NET Data Services from a .NET application.
image
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

[Sample Of Apr 22nd] Client templating with jQuery and JSON

[Sample Of Apr 22nd] Client templating with jQuery and JSON:

Homepage image
RSS Feed
Sample Download :  http://code.msdn.microsoft.com/Client-templating-with-0c85db68
This project illustrates how to display a tabular data to users based on some inputs in ASP.NET application. We will see how this can be addressed with JQuery and JSON to build a tabular data display in web page. Here we use JQuery plug-in JTemplate to make it easy.
imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

ASP.NET Interview Questions: - Show Post Cache substitution?

ASP.NET Interview Questions: - Show Post Cache substitution?:
This is one of the asked ASP.Net Interview Questions during the Interview by the Interviewer.
Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.
Post-cache substitution can be achieved by two means:

Figure: - “Writesubstitution” in action
You can see we have a static function here “GetDateToString()”. We pass the response substitution callback to the “WriteSubstitution” method. So now, when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page has not been cached yet (for example, it's being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it’s content is never cached.
Ok the above example was by using “WriteSubstitution” now lets try to see how we can do by using “<>” control. You can get the “<>” control from the editor toolbox.
Figure: - Substitution Control
Figure: - Substitution in Action
Below is a sample code that shows how substitution control works. We have ASPX code at the right hand side and class code at the behind code at the left hand side. We need to provide the method name in the “methodname” attribute of the substitution control.
View following video on Web.config transformation in ASP .Net: -

Learn more on ASP.NET interview questions
Regards,
From more on author’s blog related to ASP.NET interview questions click and visit.

SQL Server Interview Question and answers:- Triggers, Instead of triggers, after triggers, inserted and deleted tables?

SQL Server Interview Question and answers:- Triggers, Instead of triggers, after triggers, inserted and deleted tables?:
Triggers are special kind of stored procedure which have logic's.These logics can be executed after or before data modification happens on a table.There are two types of triggers “Instead of triggers" and "After triggers".

Instead of triggers logic executes prior to data modification while after trigger logic executes after data modification.




In what scenarios will you use instead of trigger and after trigger?

You will use "INSTEAD trigger" to take alternative actions before the update happens.

Some of the uses of instead of trigger's are:-
•Reject updates which are not valid.
•Take some alternative action if any error occurs.
•To implement cascading deletes.For instance you want to delete a customer record.But in order to delete the customer record you also have to delete address records. So you can create a instead of trigger which will first delete the address table before executing delete on customer table.

While "AFTER trigger" is useful when you want to execute trigger logic after the data has been updated.

Some uses of after triggers are:-

•For recording Audit trail where you want new and old values to be inserted in to audit table.
•Updating values after the update has happened.For instance in a sales table if number of products and per product is inserted, you can create an after trigger which will calculate the total sales amount using these two values.

What are inserted and deleted tables?

During triggers we sometimes need old and new values.Insert and deleted tables are temporary tables created by SQL server itself which have new and old values.Inserted tables have one record for newly added data and deleted table has one record of the old version of the data.

So for instance let's say we add a new record called as "Shiv". The inserted table will have "Shiv" and deleted table will have nulls because the record did not exist.Now let’s say some user updates "Shiv" to "Raju".Then inserted table will have "Raju" and deleted tables will have "Shiv".

Also watch my most asked SQL Server interview question video on:- What is the difference between clustered and non-clustered indexes?

Taken from the best selling SQL Server interview question book,you can see more about the book by clicking on  SQL Server interview questions book.

What is BI Semantic model (BISM) in SQL Server 2012?

What is BI Semantic model (BISM) in SQL Server 2012?:
Some days back I was installing SQL Server 2012 enterprise service pack 1. During installation when I was running through the setup, it gave me two options (multi-dimensional and tabular) of  how I want to install SQL Server analysis service. Below is the image captured while doing installation.


At the first glance these options are clearly meant to specify how we want the model design for our analysis service.

No the first option i.e. "MultiDimensional" was pretty clear as I have been using them right from SQL server 2005 till today i.e. (Star schema or Snow flake).

After some googling and hunting I came to know about the second option. Let me through some light on the same and then we will conclude what is BISM.

Now over all we have two kinds of database systems, one is OLTP system where the database design thought process is in terms of tables and normalization rules ( 1 normal form , second normal form and third normal form database design ) are followed.

The second kinds of systems are OLAP system's where we mostly design in terms of fact tables and dimension tables. Cube which is a multi-dimensinal view of data is created properly if you design your database as OLAP system.

Sin simple words we need to create a DB with OLAP design to ensure that proper cubes structure is created.

Now some times I will say many times it's really not feasible to create different structure and then create cubes from them. It would be great if SSAS gives us some options where we can do analysis straight from normalized simple tables

For instance take simple end users who use "Power Pivot". It's very difficult for them to make understand OLAP models like dimension and fact tamles. But yes they do understand tables with rows and columns. If you see microsoft excel the format is in terms of table which have rows and columns and these end users are comfortable with a tabular structure.

Below is a simple image of how simple end users visulize data in excel i.e. tabular - rows and columns.


That's where exactly the second option i.e. the "tabular" mode comes in to picture.

So if we put in simple words BISM (Business intelligence semantic model) is a model which tries to serve simple user / programmers who are comfortable with tabular structure and also maintains professional OLAP  models for corporate.

So BISM is a unifying name for both Multi-dimension and tabular models. So if you are personal BI person who loves ADHOC analysis, you can use power pivot or SSAS tabular IDE to do analysis. And if you are person who is working on a corporate project then Multi-dimension model is more scalable and worth looking in to.

Just alast quick note this is also a favorite SQL Server interview question which is making round now a days when SQL Server 2012 topic is discussed.

With all due respect to my publisher Ihave taken the above answer from my book SQL Server interview questions and answers.

You can also see my blog which has some important for SQL Server interview questions on Colaesce.

You can also see my video on Can views be updated (SQL Server interview questions)?



 



















   

C# interview questions and answers: - What is the difference between “==” and .Equals()?

C# interview questions and answers: - What is the difference between “==” and .Equals()?:

When we create any object there are two parts to the object one is the content and the other is reference to that content.

So for example if you create an object as shown in below code:-
  1. “.NET interview questions” is the content.
  2. “o” is the reference to that content.



 “==” compares if the object references are same while “.Equals()” compares if the contents are same.

So if you run the below code both “==” and “.Equals()” returns true because content as well as references are same.


object o = ".NET Interview questions";
object o1 = o;

Console.WriteLine(o == o1);
Console.WriteLine(o.Equals(o1));
Console.ReadLine();

True
True

Now consider the below code where we have same content but they point towards different instances. So if you run the below code both “==”   will return false and “.Equals()”  will return true.


object o = ".NET Interview questions";
object o1 = new string(".NET Interview questions".ToCharArray());

Console.WriteLine(o == o1);
Console.WriteLine(o.Equals(o1));
Console.ReadLine();

False
True

When you are using string data type it always does content comparison. In other words you either use “.Equals()” or “==” it always do content comparison.

Enjoy this awesome youtube play list which covers 12 important .Net and c# interview question videos

You can also refer our blog which has more than 1000 .NET and c# interview questions with answer

Also see the following c# interview question video on Difference between == VS .Equals():-

Codeproject.tv :- Learn SharePoint Step by Step Videos

Codeproject.tv :- Learn SharePoint Step by Step Videos:
Codeproject.com is like a family to me. So when they announced codeproject.tv which is a extension arm ( I hope I am not wrong) of codeproject.com for videos , I was overexcited.

So here are my three videos on Sharepoint 2010. These three videos will help you to get to speed with sharepoint.

Note :- I have a typical Indian accent  and English is my second language. So if my accent hurts your ears , sorry for it.

In the first video I have explained basics like Sharepoint and Sharepoint foundation. This video is a warm-up video where I have talked about benefits of sharepoint and what are the pre-requisites for installing sharepoint.




In the second video I have wasted no time and I started creating a small portal using sharepoint. While creating this portal we will also go through different sharepoint concepts like Webapplications,Site collection,Site , pages and List. While creating the portal we will take help of custom fields and content types to collect end user data.




This third video is an extension of second video. The second video was almost 25 minutes so I broken down the videos in two parts.




This is my first experiment with codeproject.tv and I wish Chris and Sean the best for their new venture.



Visual Studio 2012 Update 2 is here

Visual Studio 2012 Update 2 is here:
We’re excited to announce that today, Visual Studio 2012 Update 2 (VS2012.2) is now available for download.
For an overview of the five areas of investments in VS2012.2 that we made across agile planning, quality enablement, Windows Store development, line-of-business development, and the general developer experience, please visit Soma’s blog. In particular, you can find an outline of the new functionality and issues we’ve fixed in Visual Studio 2012 Update 2 and comprehensive details on the respective blogs below:
If you encounter a bug or an issue, please report it through the Visual Studio, LightSwitch, and Blend Connect sites. As always, we want to hear your suggestions or feature ideas/improvements so please tell us on UserVoice or vote on other user’s suggestions.
Thanks,
The Visual Studio Team

A convention-based data template selector for Windows 8 XAML Store apps

A convention-based data template selector for Windows 8 XAML Store apps:
This article describes how you can use naming conventions to hook a XAML Data Template to a ViewModel or a Model in a Windows 8 Store app. The last couple of years, convention-based coding became more and more popular in the .NET world. The MVC framework was one of the first managed environments where the constituents of an application (in this case Models, Views, and Controllers) were automatically linked to each other based on their name, instead of letting a developer create references and interfaces. The latest version of the Managed Extensibility Framework –a.k.a. MEF- also comes with a convention-based programming model: the RegistrationBuilder and PartBuilder classes provide an alternative for MEF attributes: they let you specify the rules to infer Parts, Imports, and Exports from the names of your classes and properties. Also in the XAML world, convention-based coding is not new. Most of the popular MVVM frameworks rely heavily on naming conventions to link components together. Caliburn.micro has several classes to lookup the View for a ViewModel (and vice-versa) and to generate data bindings solely based on class and property names: ViewLocator, ViewModelLocator, and ViewModelBinder.
This article presents a way to link a XAML DataTemplate in a View to its corresponding Model or ViewModel data context  class. Here are some screenshots of the attached sample project: it shows a FlipView control (with an associated FlipViewIndicator) that has a different type of Model for each item, so each page should look differently:



In ye olde XAML platforms, you could specify the default data template for a class with the DataType property. In Windows 8 Store app XAML, that property is not supported anymore. So when you want an ItemsControl to display a list of objects of different types, you have to use a DataTemplateSelector. I already explained the mechanisms in this blog post.
The following class defines a data template selector that looks up a data template in the app’s resources, based on the name of the data context class. It just adds “Template” to the name of the data context class, so if you want to display an instance of “Person”, you just have to provide a data template with as x:Key “PersonTemplate”:
/// <summary>
/// Convention-based DataTemplate Selector.
/// </summary>
public sealed class DynamicDataTemplateSelector : DataTemplateSelector
{
    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        DataTemplate result = null;
        string typeName = item.GetType().Name;

        try
        {
            result = App.Current.Resources[typeName + "Template"] as DataTemplate;
        }
        catch (Exception)
        {
            Debug.Assert(false, string.Format("No data template found to display '{0}' instances.", typeName));
        }

        return result;
    }
}

The try-catch block is necessary because the resource manager throws an exception when a resource is not found.
Here’s how to apply the selector in an ItemsControl. It is declared as a resource:
<Page.Resources>
    <templates:DynamicDataTemplateSelector x:Key="DynamicDataTemplateSelector" />
</Page.Resources>
And then applied to the FlipView:
<FlipView x:Name="TheFlipView"
            ItemsSource="{Binding Models}"
            ItemTemplateSelector="{StaticResource DynamicDataTemplateSelector}" />
Here are some of the data templates from the resource dictionary:
<!-- Biography -->
<DataTemplate x:Key="BiographyTemplate">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Name}"
                    Foreground="Yellow"
                    FontSize="28"
                    HorizontalAlignment="Center"
                    Margin="0 48 0 0" />
        <TextBlock Text="{Binding  Description}"
                    Grid.Row="1"
                    FontSize="20"
                    TextWrapping="Wrap"
                    Margin="0 48 0 0" />
    </Grid>
</DataTemplate>

<!-- Powers And Abilities -->
<DataTemplate x:Key="PowersAndAbilitiesTemplate">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Name}"
                    Foreground="Yellow"
                    FontSize="28"
                    HorizontalAlignment="Center"
                    Margin="0 48 0 0" />
        <ItemsControl ItemsSource="{Binding Powers}"
                        Grid.Row="1"
                        Margin="0 48 0 0"
                        HorizontalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock FontSize="20">
                        <Run Text="● " />
                        <Run Text="{Binding}" />
                    </TextBlock>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <TextBlock Text="Weaknesses"
                    Grid.Row="2"
                    Foreground="Yellow"
                    FontSize="28"
                    HorizontalAlignment="Center"
                    Margin="0 48 0 0" />
        <ItemsControl ItemsSource="{Binding Weaknesses}"
                        Grid.Row="3"
                        Margin="0 48 0 0"
                        HorizontalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock FontSize="20">
                        <Run Text="● " />
                        <Run Text="{Binding}" />
                    </TextBlock>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</DataTemplate>
When a data template is not found in the resources, the selector returns a Null value. The data binding engine then applies a default template, with the fully qualified type name in a text box. Here’s how this looks like:

During debugging, the Assert statement writes an exception to the output window when the template is not found, like this:

That’s all there is. Actually, the title of this article was longer than its source code. Here is the sample app: U2UConsult.Win8.DataTemplating.zip (692.39 kb)
Enjoy!
Diederik

Monday, January 21, 2013

[Sample Of Jan 17th] Image Verification Code for Logging in ASP.NET

[Sample Of Jan 17th] Image Verification Code for Logging in ASP.NET:

Homepage image
RSS Feed
Sample Download:
CS Version: http://code.msdn.microsoft.com/CSASPNETVerificationImage-81902fa4 
VB Version: http://code.msdn.microsoft.com/VBASPNETVerificationImage-3873cacc
This sample will demo you how to create an image verification code in ASP.NET. Sometimes we may need the verification code in order to prevent malicious actions. Such as: auto registration by "Automatic-Teller Registration Machine" or the malicious password cracking. We provide a program to acquire a specified number of characters or symbols, and add some interferences with the line, and then output a picture and save the value in session. The user input content according to the display contents of the picture, and then to compare the input with the value in SESSION.  According to the results of the comparison, we will determine the follow-up operations.


image
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

Could not find a part of the path ... bin\roslyn\csc.exe

I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added a...