Category: HowTo

short tutorials

Asp.NET MVC, Jquery and Razor – Cascading dropdown, retrieving partial views, Json send objects, handling errors

There are many blogs and other posts on using jQuery with MVC. You can find individual posts on:

·         How to send objects to an action method via JavaScript.

·         How to retrieve partial views.

·         How to handle errors.

asp.net mvc jquery razor cascading demo

I have written a sample showing how to do all of these together. The sample is written in  MVC 3 using Razor views

The sample demonstrates:

  1. Cascading dropdown ( see the button Populate from action and Cascading drop down)
  2. Populating a table from a Partial View(see the button Add New Employee(jquery call action and render)
  3. How to handle  error from action ( press Save 2 )
  4. How to send id parameters (long) from javascript to action ( press Delete 1 or Delete 2)
  5. How to send objects(Employee) from javascript to action ( press Save 1 or Save 2)

Without further ado, this is the project . Enjoy!

Jquery MVC Razor demo full

PS: If you seems that the code is too hard, here is a more detailed explanation :http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/

MVC Zip Result

Sometimes you need to send to the user more than 1 file – or, maybe, the file is too large
The simplest way is : made a zip file that contains the others.

What do you need
1. SharpzipLib from http://www.icsharpcode.net/opensource/sharpziplib/ ( or download via NuGet in VS)
2. obtain the file(s) that you want as a string or as a byte[] – let’s say you have a byte[] to store in a str variable
3. make in your action something like that:

 var fcr = new ZipResult("Export.xls", str);
            fcr.AddFile("readme.txt","this zip file contains ..");
            return fcr;

4. copy the following code in your asp.net mvc projects:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Text;

namespace utilsResult
{
    public class ZipResult : FileResult
    {

        
        private Dictionary<string, byte[]> content = new Dictionary<string, byte[]>();
        public string FileNameZip;
        public ZipResult(string FileName, byte[] Contents)
            : base("application/octet-stream")
        {
            this.FileDownloadName = Path.GetFileNameWithoutExtension(FileName) + ".zip";
            AddFile(FileName, Contents);
        }
        public void AddFile(string FileName,  byte[] Contents)
        {
            content.Add(FileName, Contents);
        }
        public void AddFile(string FileName,string Contents, Encoding e = null)
        {
            if (e == null)
                e = ASCIIEncoding.ASCII;

            content.Add(FileName, e.GetBytes(Contents));
        }

        protected override void WriteFile(HttpResponseBase response)
        {

            using (ZipOutputStream zos = new ZipOutputStream(response.OutputStream))
            {
                zos.SetLevel(3);
                zos.UseZip64=UseZip64.Off;

                foreach (var item in content)
                {
                    ZipEntry ze = new ZipEntry(item.Key);
                    ze.DateTime = DateTime.Now;                    
                    zos.PutNextEntry(ze);
                    int count=item.Value.Length;
                    zos.Write(item.Value, 0, count);
                   
                    
                }                
            }
        }
    }
}

5. future improvements:
Zip the file(s) in a dll project to made fully testable!

ASP.NET MVC make users–roles fast

please left click on “Microsoft SQL Server Management Studio (push button)”
clip_image001
please create a database in “Microsoft SQL Server Management Studio”
clip_image002
please left click on “C:\Windows\system32\cmd.exe (push button)” and enter the following command : aspnet_regsql.exe -E -S .\SQLExpress -d proprii -A rm
clip_image003
please left click on “ListPanel (list)” in “Microsoft SQL Server Management Studio”
clip_image004
please left click on “Tables (outline item)” in “Microsoft SQL Server Management Studio”
clip_image005
please keyboard input in “Microsoft SQL Server Management Studio” [F5]
clip_image006
please right click on “aspnet_Applications (list item)” in “Microsoft SQL Server Management Studio”
clip_image007
please left click on “Select Top 1000 Rows (menu item)”
clip_image008
please left click in “Microsoft SQL Server Management Studio”
clip_image009
please left click on “aspnet_Users (list item)” in “Microsoft SQL Server Management Studio”
clip_image010
please right click on “aspnet_Users (list item)” in “Microsoft SQL Server Management Studio”
clip_image011
please left click on “Select Top 1000 Rows (menu item)”
clip_image012
please left click on “RdcDAL – Microsoft Visual Web Developer 2010 Express (Administrator) (push button)”
clip_image013
please edit web.config in your MVC application and change the connection string to point to your database
clip_image014
please scroll down until membership and change application name from / to /applicationName
clip_image015
please run your application and left click on “Log On (editable text)” in “Home Page – Windows Internet Explorer”
clip_image016
please left click on “User name (editable text)” in “Log On – Windows Internet Explorer”
clip_image017
please left click on “Register (editable text)” in “Log On – Windows Internet Explorer”
clip_image018
please left click on “User name (editable text)” in “Register – Windows Internet Explorer”
clip_image019
please input your details (I have put mine : ignatandrei)
clip_image020
please see that I am registered to the site
clip_image021
please verify to the database – left click on “Microsoft SQL Server Management Studio (push button)”
clip_image022
please left click in “Microsoft SQL Server Management Studio”
clip_image023
please press [F5] in “Microsoft SQL Server Management Studio”
clip_image024
please see the results – application name
clip_image025
please left click on “Execute (push button)” in “Microsoft SQL Server Management Studio” for the query that lists users.
clip_image026

Optimizing EF4 and EDMGen2

Just reading (from Adrian Florea links ) how the EF4 could be optimized : http://www.codeproject.com/KB/database/PerfEntityFramework.aspx

First modification is to “Pre-generated Your View”. For this you must have .ssdl, .csdl, and .msl files – so you change the “Metadata Artifact Processing property to: Copy to Output Directory.”. Then you process the .ssdl, .csdl, and .msl with edmgen in order to can have the  views.

Until here , all ok.

But, in the next advice, is to keep “Metadata Artifact Processing property to: Embed in Output Assembly.”

One solution is to put “Metadata Artifact Processing property to: Copy to Output Directory.” , compile, put again “Metadata Artifact Processing property to: Embed in Output Assembly.” and compile again. But , if you change the edmx (add fields or tables ) you must redo the operation  – so you will have more things to do(if you remember)

A solution is to build them on the pre-build step .But how to generate the .ssdl, .csdl, and .msl files  ?

Edmgen2 , http://code.msdn.microsoft.com/EdmGen2 , to the rescue. Download, put into a lib folder under your solution folder and put a pre-build like this :

$(SolutionDir)lib\edmgen2\edmgen2 /FromEdmx $(ProjectDir)prod.edmx”

“%windir%\Microsoft.NET\Framework\v4.0.30319\EdmGen.exe” /mode:ViewGeneration /language:CSharp /nologo “/inssdl:prod.ssdl” “/incsdl:prod.csdl”   “/inmsl:prod.msl” “/outviews:$(ProjectDir)prod.Views.cs”

What you must change on your project?

1. IF you are on 64 bit, change Framework to Framework64

2. change the prod with your edmx name.

What is the performance?

Tested by loading a table with 301 rows by doing the steps :

1. open connection, load all table in objects(POCO), closing connection

2. open connection , find object with PK = 1, closing connection

3. open connection ,  loading 1 tables with 2 related (include ) , closing connection

The results are in milliseconds:

Without pre-compiled views

LoadTable LoadID LoadMultiple Total Time
579 800 172 1551
563 755 171 1489
559 754 169 1482
568 762 240 1570

With pre-compiled views:

LoadTable LoadID LoadMultiple Total Time
606 807 183 1596
509 706 177 1392
852 137 192 1181
530 733 221 1484
523 722 183 1428

The average / min / max results:

average max min
without 1523 1570 1482
with 1413.25 1596 1181

In the next picture the smaller the duration(milliseconds), is the better :

image

Conclusions:

1.  For the average and min the difference is 7%, respectively 20%. Please remember we are using only 3 queries.

For the max, it is vey curious : the with is more than without. The penalty is 1%, I think that is a measuring error ? – or maybe not. However , the penalty is small comparing with others.

2. Very curious, find after ID, with a table with 301 rows, took longer than loading the whole table.However, did not take into accound finding in the list the object( it is in memory also)

3. It may worth to add the pre-build step shown before to pre-compile views.

Links :

http://www.codeproject.com/KB/database/PerfEntityFramework.aspx

http://msdn.microsoft.com/en-us/library/bb896240.aspx

Error intercepting in MVC when saving data

I have seen many times in MVC the following code , when doing a post and saving data :

try
{
        //code to save to database
}
catch
{
         ModelState.AddRuleViolations(TheModel.GetRuleViolations());
}

Why is not good ?
I will do a simple example : if some error occurs on the database level ( such as simple unique index on a name column ) or even some error occurs whenestablishing the database connection – you will never see what’s happening. And you will have no chance to repair the problem
A slighty better code is :

try
{
     ModelState.AddRuleViolations(TheModel.GetRuleViolations());
     if(ModelState.Count == 0)// no error in the model
     {
     //code to save to database
     }
}
catch(Exception ex)
{
      ModelState.AddModelError("", ex.Message);
}

Please see also how to do logging to the exception at
http://msprogrammer.serviciipeweb.ro/2010/04/19/logging-and-instrumentation/

Five common mistakes for ASP.NET (MVC) accesing resources : css, js, images, ajax

To have once for all the link to show to people, because too much makes the same error again and again.

(From here – you can use ResolveUrl or Url.Content – it’s the same for me. I use ResolveUrl because I used first …)

Case 1 The image does not display

Please check you have the following :

<img src='<%= ResolveUrl("~/Content/images/YOURIMAGE.jpg" )%>'  alt="image" style="border:0" />

Case 2 The css does not show

Please check you have the following :

<%= string.Format("<link href='{0}' type='text/css' rel='stylesheet' />", ResolveUrl("~/Content/your.css")) %>

or

<style type="text/css">
@import '<%= ResolveUrl("~/Content/your.css") %>';

</style>

Case 3 The js does not execute (undefined error)

Please check you have the following :

<script type="text/javascript" src='<%= ResolveUrl("~/Scripts/yourjs.js")%>'></script>

Case 4 The js does execute in aspx page, but did not execute under js file

Please check you DO NOT have the following

<%

in the js file. The js file is not interpreted by the same engine as aspx, so can not interpret asp.net tags. Instead , add a parameter to your function : the path.

Simple example : Let’s say in aspx you have :

<script type=”text/javascript”>

function Generate(){

window.open(‘<% Url.Action(“About”)%>’);
}

</script>

and you call Generate();

When you put in .js file, please put this :

function Generate(url){

window.open(url);
}

and call like this :

Generate('<% Url.Action(“About”)%>');

Case 5 The ajax request gives you a 404 error.

Please ensure that you have

<%= ResolveUrl("~/path”)%>

and not

/path

Bonus 1: T4MVC , http://mvccontrib.codeplex.com/releases

Bonus 2: Edit the project file and put <MvcBuildViews>true</MvcBuildViews>

( short url: http://bit.ly/asp5Mistakes)

Generating history trigger with EF , edmx and TT files

I have wrote in an older post ( http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/ ) how to generate history code for tables . The easy solution was to create a tt file that track for the ObjectContext the SaveChanges for each table that has a “history” in name. the limitation is that , when you raise an sql command such as “update table ” you must load from database a lot of rows for this….

Now I want to show the same thing, but generating triggers in database for that ! I start also from edmx file and with a template stealed from http://forums.asp.net/p/1599616/4083198.aspx ( to have type of fields in the database ) and another stealed and modified from StackOverflow(to generate trigger for after insert , update, delete) I manage to have a solution to generate sql tables and trigger code.

When is that good ?At the beginning stages of a project when the table structure changes by adding a new parameter.

Sample code generated for table Notes(ID, TextNote, PersonID)

print 'Create table Notes_History ';
Create Table Notes_History(
		ID_Notes_History BIGINT IDENTITY NOT NULL
		,History_Action varchar(50)
		,History_From varchar(100) default HOST_NAME()
		,History_User varchar(50) default SYSTEM_USER
		,History_Date varchar(50) default  getdate()
	   ,Id  int   NOT NULL
	   ,Textnote  nvarchar (255)  NULL
	   ,PersonId  int   NULL
	)
print 'end Create table Notes_History ';
GO
print 'create trigger for Notes'
GO
CREATE TRIGGER dbo.TR_IUP_Notes
   ON  Notes
   AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;
	DECLARE @Ins int

DECLARE @Del int

SELECT @Ins = Count(*) FROM inserted

SELECT @Del = Count(*) FROM deleted
if(@Ins  + @Del = 0)
	return;

declare @operation varchar(50)
	set @operation ='update';
	if(@ins < @del)
		set @operation ='delete';
	if(@ins > @del)
		set @operation ='insert';

	if(@ins <= @del)
	begin
		INSERT INTO Notes_History(History_Action ,Id,Textnote,PersonId)
			select @operation ,Id,Textnote,PersonId from deleted
	end
    else
	begin
    INSERT INTO Notes_History(History_Action ,Id,Textnote,PersonId)
			select @operation ,Id,Textnote,PersonId from inserted
	end
END

The drawback of the code : the user that executes is not always the logged sql server user…
Anyway, what you have to do to use this automatically generated history/audit for tables ?

download historysql and modify

string inputFile = @”Model1.edmx”;

from historysql.tt to your edmx name. Then take the generated code and execute in sql server.

Logparser quick and dirty

Sometimes you must find information in text files. Many,many text files, like IIS logs or other custom non-regular formats.

I have a bot from http://www.imified.com/ – and I log the messages with log4net in text files, with another messages.

An entry looks like that :

System.ArgumentException: ;channel=private;botkey=<guid>;userkey=<guid>;user=name@yhaoo.com;network=Yahoo;msg=hello;step=1;value0=hello;to=asdasd

And there are multiple log files that I want to parse and find the email adresses to collect feedback from those persons that use my bot.

LogParser to the rescue! Download from http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en and use this command line

LOGPARSER “Select Text into a.csv from current* where Text like ‘%@%'” -i:TEXTLINE

Explanation of command :

Select Text into a.csv from current* where Text like ‘%@%’ –means find in files that begin with current(current*) all text that contains emails ( ‘%@%’) and put in file a.csv  the results.

-i:TEXTLINE – means the format is text

What can be more simple ?

(Ok, for finding the user name I had to resort to excel, to remove duplicates … )

More I think it is fast enough : for parsing 114 files with 58.8 MB (PC with a 2GB RAM + 7200 RPM ) the results are :

Statistics:
———–
Elements processed: 487176
Elements output:    1044
Execution time:     7.69 seconds

Also logparser can be used for more than text files :

http://support.microsoft.com/kb/910447

http://www.stevebunting.org/udpd4n6/forensics/logparser.htm

More, it can be as a COM DLL in every .NET project, making it a usefull tool . See

http://www.codeproject.com/KB/recipes/SimpleLogParse.aspx

Next time I will show the using Powershell in combination with LogParser.

First Install of tools for programmer

My primary tools are Visual Studio ( and the Express suite) , Sql Server ( and SQL Server Management Studio )( and the Express suite) and Office (Excel, Word)

Those are the modification that I do every time … I wish there were enabled by default :

For VS2010

Go to=> Tools, Options , Html, Formatting ,Check “ Insert attribute value quotes when typing”

image

This saves me a lot of time , when I put : input type=”text” , the “  are inserted automatically.

For SSMS

Go to=> Tools, Options , Designers , uncheck “Prevent saving changes that require table re-creation”

image

As a developer, I do modify tables … and this wont let me the first time …

For Excel, Word

Alt+F11 (Visual Basic Editor), Tools, Options, Editor Tab, uncheck “Auto syntax check”, check “require variable declaration”

image

“require variable declaration”  :This saves you a lot of time debugging or writing “Option Explicit” .

“Auto syntax check “ : I do not want a message box each time I do an error. The error is seen in red … no need for a Msgbox.

How about you, dear reader ? Do you have programs that require after installation modifying of options ?

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.