Tuesday, July 15, 2014

Dictionary requires a model item of type System.Collections.Generic.IEnumerable in MVC 3

MVC

I encountered an error while implementation of return multiple models to single view.

Kindly visit an article for reference.

Return Multiple Models in single View in MVC3

An error was occurring on routine basis.Initially I found challenge to find the root cause of this.

Later I understood an error and change my approach to overcome on this.

In this blog I am sharing the way to resolve this error.

Whenever I run my application and paste the following URL in browser http://localhost:60346/Home/rsvpform , it prompts me an error:

The model item passed into the dictionary is of type 'MVCSample.Models.ParentModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MVCSample.Models.ParentModel]'.

The reason behind the View “(.cshtml) expects the IEnumerable model type. “as I’ve set below for sample app.

clip_image001

Now figure out the reason for occurrence of an error, it generates an error when we are returning only of base type model class object as an example below:

clip_image002

So point of interest is whenever you return a model type object it must be sync with view model type.

If I uncomment the above three lines as depict also in below image it will run as expected, because of this is we are returing viewModelList object as Enumerable type .

clip_image003

More Summarized words are, Model declaration in View and the model being return from Controller class must be sync with each other.

clip_image005

 

To know more about MVC kindly go through with the links given below:

· Smart Working With Custom Value Providers in ASP.Net MVC

· Invoke Action With Model Binders in MVC

· Extension Helpers Method in MVC

· Custom Button With TagBuilder Using MVC Razor Engine

· Precompiled Razor View Using RazorGenerator MVC and PreCompiledViewEngine in MVC 4

· RETURN MULTIPLE MODELS IN SINGLE VIEW IN MVC3

· CALL CONTROLLER ACTION METHOD FROM JQUERY USING AJAX

· EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ

· MEANING OF SCAFFOLDING IN MVC

· REMOVE AMBIGUTY OF CONTROLLER NAMES IN MVC APPLICATION

· CUSTOM BUTTON WITH TAGBUILDER TECHNIQUE USING MVC RAZOR ENGINE

· CONVERSION HELPERS IN MVC RAZOR: VALIDATING POSTED DATA

Thanks

Enjoy Coding and Stay Happy Smile

Local and Global Temporary tables in SqlServer 2008

Local and Global Temporary tables in SqlServer 2008

In this article I am sharing my thoughts on Temporary tables in SQL Server 2008.

Description: Temporary tables are quite similar to permanent tables in database; permanent tables get created in the specific database and persist till the database exists. Whilst Temporary tables get created into the tempdb and automatically deleted they are no longer in use. Like shown below:

 

clip_image001

Types of Temporary tables:

· Local temporary tables

· Global temporary tables

Local temporary tables: Local temp tables are similar to permanent tables in SQL server, it accepts single hash value ‘#’ value as prefix at time of its creation .Syntax:- (CREATE TABLE #t) are visible only to the connection that creates it, and are deleted when the connection is closed

I’ve created a local temp table with the following syntax:

create table #Android

( ID int NOT Null ,Name nvarchar(50) ,CompanyName nvarchar (50))

And inserted few values into this table.

insert into #Android values (1,'Galaxy S2','Samsung')

insert into #Android values (1,'Galaxy S3','Samsung')

insert into #Android values (1,'IPhone5','IPhone');

insert into #Android values (1,'Blackberry Z10','Blackberry');

select * from #Android

clip_image002

There are few characteristics of local temporary tables:

1. It starts with single hash value ‘#” as prefix of table name.

2. Local temporary table is only for connection in which it has created.

3. Each Local temporary table has a random value at end of table name as depict in below image:

clip_image004

4. Local temporary table gets automatically dropped when existing connection is closed, or user can explicitly drop with the following command “drop table #Android”.

5. If the temporary table is created into the stored procedure, it gets automatically dropped on the completion of the stored procedure execution.

6. You can create local temporary table with the same name but in different connection, and it stores with same name along with different random values.

clip_image006

clip_image008

Global temporary tables: Global temp tables are also similar to local temporary table tables in SQL server, Excepts two ## value as prefix at time of its creation .Syntax:- (CREATE TABLE ##tablename) are visible all connection of SQLServer, and only destroyed when the last connection referencing the table is closed (in which we have created the Global Temp table).

create table ##MobileDetails

( ID int NOT Null ,MobileName nvarchar(50) ,CompanyName nvarchar (50))

insert into ##MobileDetails values (1,'Galaxy S2','Samsung')

insert into ##MobileDetails values (1,'Nokia Lumia','Nokia')

insert into ##MobileDetails values (1,'IPhone5','IPhone');

insert into ##MobileDetails values (1,'Blackberry Z10','Blackberry');

After executing the above command you will see the following structure into the object explorere as depict below in image:

clip_image009

Run the following line into sqlserver query window and see the output:

select * from ##MobileDetails

clip_image010

There are few characteristics of global temporary tables:

1. It starts with single hash value ‘##” as prefix of table name and its name is always unique. There is no random number append to name.

clip_image012

2. Global temporary tables are visible all connection of SQLServer.

3. Global temporary tables are only destroyed when the last connection referencing the table is closed (in which we have created the Global Temp table).

4. You can access the Global temporary tables from all connection of SQLServer till the referencing connection is open.

Hope you like this demonstration:

 

To know more about MVC kindly go through with the links given below:

· Smart Working With Custom Value Providers in ASP.Net MVC

· Invoke Action With Model Binders in MVC

· Extension Helpers Method in MVC

· Custom Button With TagBuilder Using MVC Razor Engine

· Precompiled Razor View Using RazorGenerator MVC and PreCompiledViewEngine in MVC 4

· RETURN MULTIPLE MODELS IN SINGLE VIEW IN MVC3

· CALL CONTROLLER ACTION METHOD FROM JQUERY USING AJAX

· EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ

· MEANING OF SCAFFOLDING IN MVC

· REMOVE AMBIGUTY OF CONTROLLER NAMES IN MVC APPLICATION

· CUSTOM BUTTON WITH TAGBUILDER TECHNIQUE USING MVC RAZOR ENGINE

· CONVERSION HELPERS IN MVC RAZOR: VALIDATING POSTED DATA

Thanks

Keep coding and Smile Smile

Friday, July 11, 2014

Mapping of LINQ to SQL Object and Relational Object(Sql Server Object)
  ormapper
The following table shows the relationship between the LINQ to SQL object model and the corresponding relational model.
The LINQ to SQL object model provides the fundamental elements for working with and managing
relational objects. It is via this model that a relational model is mapped to and expressed in the
developer’s programming language.
In the LINQ to SQL object model, database commands are not issued against the database directly. As a
developer, you simply change values and execute methods within the confines of the object model. LINQ
to SQL then translates those changes or methods into the appropriate SQL commands and funnels them
through to the database to be executed.
Typical and more described details are showing below in table to map both objects.
Relational Object LINQ to SQL Object
Database Data Context
Table Entity class
Column Class member
Foreign-key relationship
Association

Hope this little excerpt help to .Net freaks.
To know more about MVC kindly go through with the links given below:
· Smart Working With Custom Value Providers in ASP.Net MVC
· Invoke Action With Model Binders in MVC
· Extension Helpers Method in MVC
· Custom Button With TagBuilder Using MVC Razor Engine
· Precompiled Razor View Using RazorGenerator MVC and PreCompiledViewEngine in MVC 4
· RETURN MULTIPLE MODELS IN SINGLE VIEW IN MVC3
· CALL CONTROLLER ACTION METHOD FROM JQUERY USING AJAX
· EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ
· MEANING OF SCAFFOLDING IN MVC
· REMOVE AMBIGUTY OF CONTROLLER NAMES IN MVC APPLICATION
· CUSTOM BUTTON WITH TAGBUILDER TECHNIQUE USING MVC RAZOR ENGINE
· CONVERSION HELPERS IN MVC RAZOR: VALIDATING POSTED DATA
Thanks
Stay Happy and Stay Coding Smile

























Error-Messages

Hi Folks

Today i encountered an error during update records using EntityFramework 5.Fortunately we found a quick fix.

This is an error we encountered:

Unable to update the EntitySet Table because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation

In this quick post you are going learn the way to overcome the titled error.

Fix for an issue as shown below:

Simple solution to this error is to create database tables with primary keys.

Simple to fix.

 

To know more about MVC kindly go through with the links given below:

 

 

Thanks

Sachin Kalia 

Tuesday, July 8, 2014

Practical Usage of TempData and ViewData and Differences in MVC 3

 

viewdata-viewbag and tempdata

In ASP.NET MVC 3 and MVC4, we have the objects ViewData and TempData to pass data from a controller to a view. I’ll use a sample application to show how these properties works.

TempData

First I’ll explain TempData that is driven from a TempDataDictionary. I’ll show you the functionality with an example.
The end result is that any data stored in TempData will be around for the life of the current request and the next request only, or until the item is removed.

  • TempData is a dictionary object derived from the TempDataDictionary class.
  • TempData is used to pass data from the current request to a subsequent request, in other words in the case of redirection.
  • The life of a TempData is very short and it retains its value for a short period of time.
  • It requires typecasting for complex data type as I’ve used in my example:
  • @foreach (var item in(List<MVCSample.Models.EmpRegistration>)TempData["EmployeeRegistration"])
  • You can retain its value using the Keep method for subsequent requests.

To show the practical usage of View Data, I provide the following sample application:
Step 1:

View Data

If you notice from the image above, it has the keys count =1 and has the value EmployeeRegistration.
Step 2:

After redirecting to the View from the controller, we can use the TempData value at the View page like this.
Note: Kindly check that the value is always null and make it a best practice to use that in code to reduce the occurrences of errors.

TempData
Step 3:

Now we’ll determine whether the tempData value persists at the next level.
I’ll hit the other action method to verify this. In our case I call the details action method:

TempData value
See the result is as depicted in the image below:

TempData using Breakpoint


It’s magic. But this magic happens because of the statement in code TempData.Keep("EmployeeRegistration");
TempData.Keep () has two overloaded method and I’ve used one of them.
Note: We can understand TempData as the Session we used in ASP.NET.


Usage of TempData
Usage 1: If you want to keep TempData values even after reading them then call Keep().Then those values will be kept for next request also.
TempData.Keep("EmployeeRegistration");
Usage 2: If you want to remove TempData values then call Remove (). Then those values will be removed from the current and next request.
TempData.Remove("EmployeeRegistration");
Conclusion

We should use TempData for a subsequent request only to pass Controller data to a View and later also.


ViewData
ViewData that is driven from a ViewDataDictionary. I’ll show you the functionality with an example.There is a little snippet about ViewData as shown below:

  • ViewData is a dictionary object derived from the ViewDataDictionary class.
  • After redirecting its value becomes null.
  • ViewData is used to pass data from the controller to the corresponding view.
  • Its value persists for a single request. For example one redirection from the Controller to the View. After redirecting to the View it looses its value and become null.
  • It requires typecasting for a complex data type.
  • @foreach (var item in (List<MVCSample.Models.EmpRegistration>)ViewData["EmployeeRegistration"])

To show the practical usage of View Data, I provide the following sample application:


Step 1:
ViewData using Breakpoint

If you notice from the image above, it has the keys count =1 and has the value EmployeeRegistration.

Step 2: After redirecting to the View from the controller, we can use a ViewData value at the View page like this.
Note: Kindly check that the value is always null and make it a best practice to use that in code to reduce the occurrences of errors.
Check ViewData null value
Step 3:

Now we’ll determine whether or not the ViewData value is persisted at the next level.
I’ll hit the other action method to verify this. In our case I call the details action method:


ViewData value


See the result is as depicted in the image below:


View Data with breakpoint


It doesn’t retain its ViewData value and has count=0.

To know more about MVC kindly go through with the links given below:


Conclusion

We should use ViewData for a current request only to pass Controller data to the View.

 

Kindly let me know if having any query.

Chees .Net

Sachin Kalia Smile

Generate LINQ, SQL queries with LINQPad

Generate LINQ, SQL queries with LINQPad
 
images

Excerpts from msdn about LINQ:
Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
In this article I am sharing how can we generate a LINQ query with a very facilitative tool LINQPad.
The most important fact about LINQPad is, it provides you lot of functionality to play around with tables within a LINQPad editor.
So let’s see how beneficial this is for .Net freaks.
A very initial look of LINQPad shown below:
clip_image002
If you notice there is an option to create a connection with the desired database. I will use Northwind database for my demonstration purpose, here are few sequential steps to make connection establish.
Click in Add connection a window will appear.
clip_image004
Choose “Default (LINQ to SQL) and click on Next button. A New window will appear, fill the required details to get connect with the desired database. As I’ve chosen default provider, (local) server, SQL Authentication option and passed the desired credentials.
clip_image005
Click on Test button and a dialog box will appear with “Connection Successful” message as depicted below:
clip_image006
Click on ok button and see the below image.
clip_image008
To move ahead after the successful connection, now turn is to run some query and see the benefits of this.
Before to run query into a LINQPad editor please have a look on the toolbar section and mouse over on each at least one(toolbar name is very easy to understand).
clip_image010
As you can see into just above window connection is still pointing to none, though connection has been made already, but the open editor is not pointing to any already made connection. Click on connection dropdown and select as your desired as mine is Northwind.
clip_image012
You can also write your query in many modes which .Net supports, See the below image.
clip_image014
I will run inner join query here using Orders and OrderDetails tables of Northwind database.
At very first time I will choose language as SQL and run the following SQL query with green button.
select od.Quantity ,o.OrderID from dbo.Orders as o inner join dbo.OrderDetails as od
on o.OrderID = od.OrderID
Output:
clip_image016
Now I run the following LINQ query into LINQPad editor and choose the Language option as C# Statement(s).
var Result = from o in Orders join od in OrderDetails on o.OrderID equals od.OrderID
select new { od.Quantity,o.OrderID};
I run the above query but nothing comes as result. The reason behind this is we have to use an extension method Dump() to print the result which is built in method of LINQPad.
Let’s run the above query again with Dump method.
var Result = from o in Orders join od in OrderDetails on o.OrderID equals od.OrderID
select new { od.Quantity,o.OrderID};
Result.Dump();
See the output:
clip_image018
There are also some inbuilt extension methods, Right click on any table and see the answer as below showing image.
clip_image020
You can download LINQPad form here http://www.linqpad.net/.
 
You can also have a look on MVC related article here:
Smart Working With Custom Value Providers in ASP.Net MVC
EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ
Invoke Action With Model Binders in MVC
Extension Helpers Method in MVC
Custom Button With TagBuilder Using MVC Razor Engine
CALL CONTROLLER ACTION METHOD FROM JQUERY USING AJAX
EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ
MEANING OF SCAFFOLDING IN MVC
REMOVE AMBIGUTY OF CONTROLLER NAMES IN MVC APPLICATION
Precompiled Razor View Using RazorGenerator MVC and PreCompiledViewEngine in MVC 4
So far so good.
Hoe you enjoyed this demonstration.
Keep coding and Be Happy Smile


























































AutoCreate SimpleMembership tables in ASP.NET MVC4

AutoCreate SimpleMembership tables in ASP.NET MVC4

This article describes about to SimpleMembership of WebMatrix.Authenication and authorization are very needed part of web application. SimpleMembership, introduced with WebMatrix, tries to address these issues by offering a flexible model for authenticating the users.

In this article I will explain how to integrate with existing database and issues confronted during development.

 

image

clip_image001

You can also have a look on MVC related article here:

Smart Working With Custom Value Providers in ASP.Net MVC

EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ

Invoke Action With Model Binders in MVC

Extension Helpers Method in MVC

Custom Button With TagBuilder Using MVC Razor Engine

CALL CONTROLLER ACTION METHOD FROM JQUERY USING AJAX

EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ

MEANING OF SCAFFOLDING IN MVC

REMOVE AMBIGUTY OF CONTROLLER NAMES IN MVC APPLICATION

Precompiled Razor View Using RazorGenerator MVC and PreCompiledViewEngine in MVC 4

Step1: I have created an internet application though I have already built in database in SqlServer 2008.

clip_image003

Step2: Select internet application from project template as shown in below image:

clip_image005

This is the default structure of application as shown in below image:

clip_image007

Step3: I have an existing database where I want to integrate SimpleMemberShip as shown in depicted below image:

clip_image008

I’ve created a table Users with few columns in an existing database. Columns such as ID and UserName are important for us which I will be talking about down the level in this article.

Step4: There are 4 files where i will be concentrating more during this article as shown in depicted image below:

clip_image010

Step5: Open you web.config and put this connection string in the connectionString tag as shown in depicted image below:

clip_image012

and configure these lines just behind the Authentication mode tag to enable SimpleMembershipProvider and roleManager as shown in below image:

clip_image014

Step6: Now open AccountModel.cs and change the RegisterModel as per our need, I added a new property Email into model to meet my requirement as shown below in image:

clip_image016

Step7: Open AccountController class and you will see that it has already decorated with an Annotation InitializeSimpleMembership .This class executes first to AccountController and responsible for Database creration if it doesn’t exist and also creates simple membership tables by connecting to database .Kindly see an image depicted below;

clip_image018

Step8: We are done with all configuration setup, now run an application and click on register button on the right top as shown in below image:

clip_image020

As soon as you click on register button it initialize InitializeSimpleMembership class and performs the steps to create SimpleMembership .Kindly see an image below:

clip_image021

Step9: Fill the required details and register the user as shown in image below:

clip_image023

Step10: All the information related to employee has been stored in database in two tables as well as user “dotnet” logged in user in web site. Kindly see an image shown below:

clip_image025

In next article I will tell you about some error which I encountered during this development.

Hope you learned SimpleMemberShip.

 

Note: Friends I am not able to upload sample application which I have created due to it exceeds the limit of 10 MB .This application is built up in VS 2012.So please keep in touch base with me on Sachin.kalia15@gmail.com or drop your message on Dotnetpiper.com.

 

clip_image027

Hope you enjoyed and it may help you down the line.

Keep coding and Smile Smile