Slow first Time in ASP.NET applications

19. March 2013 12:19 by Mrojas in ASP.NET  //  Tags: , , , , , ,   //   Comments (0)

Well, this is a recurrent topic with ASP.NET:Why is the first page load always so slowjQuery152032498610322363675_1363786231988?

I don't think there is a definite answer but I can think on some explanations:

  • ASP.NET applications by nature exhibit some degree of delay upon initial access to the site. This can be due to JIT compilation, caching, etc. 
  • Note that it is also a common effect on some sharepoint sites. 
  • Some people on StackExchange attribute this slowness to: " The IIS application pool is shut down after 30 minutes of inactivity. After that, when you make a request IIS basically has to start the website up again, which leads to the behavior you are describing. You can change the idle time of your website in iis though to avoid it." 
Workarounds
 
 
There are some workarounds for this situation:
 
For some years there has been a warmup script that you can use on pre-vs2010 apps:
 

ASP.NET Site Warm up on GitHub

 
And there is  even an IIS addin for that, the following blog provides some references about this addin:
 

ASP .NET Pre heating and the App Warmup Addin for IIS

 
These problem is so common that now in VS 2010 there is even an auto-start feature that you can use:

Auto Start Feature in ASP.NET 4

 
 I hope this links help and I'll add more explanations as I find them. Please feel free to comment.

Share session state between ASP classic and ASP.NET or missing ASP classic and ASP.NET

31. January 2013 19:10 by Mrojas in ASP.NET, ASP  //  Tags: , , , , , , , ,   //   Comments (0)

Today my good friend Jafet asked me: "What do you think about sharing ASP classic and ASP.NET state?". And I told him that there were some projects for helping in this task.

I will mention some of them here.

The first one is NSession. This project provides an implementation that allows you to use the ASP.NET state server in ASP classic. You do not have to change your ASP classic code.

"You need to instantiate one of the COM objects in your ASP classic page before it accesses session state, either:

set oSession = Server.CreateObject("NSession.Session")

or

set oSession = Server.CreateObject("NSession.ReadOnlySession")


If you instantiate NSession.Session, the session state in the session store will be transferred to the ASP Classic session dictionary, and an exclusive lock will be placed in the session store. You do not need to change your existing code that accesses the ASP Classic session object. When NSession.Session goes out of scope, it will save the ASP Classic session dictionary back to the session store and release the exclusive lock.
If you have done with the session state, you can release the lock early with

set oSession = Nothing


If you instantiate NSession.ReadOnlySession, the session state in the session store will be transferred to the ASP Classic session dictionary but no locks will be placed."

The second option is SessionService. This project provides a mechanism for sharing the state between ASP classic and ASP.NET by serializing state data to an SQL Server.  The project page provides detailed information on how to setup IIS, how it is used in both platforms.

 

And the third option is a very interesting one called ASPClassicCompiler. This is a great great project. It provides a mechanism for compiling the ASP classic to .NET. This project is now opensource and we need to thank Li Chen for it.

 

Great ideas can be implemented thanks to this source. For example Brian Ellis suggested using the VBScript engine to replace the  MSScript.OCX. Another great one is an implementation of an View Engine that can be used with MVC and which support ASP Classic.

I really like the ASPClassic project and will be posting some interesting examples soon (as soon as I finish watching some Dr. Who episodes and the last Fringe season :) ) 

HTML5 lets you deploy your applications everywhere

Some VB6 and Windows Forms applications are still great but probably you need them to reach a bigger audience. 

There are now amazing devices with internet access, but all of then different in hardware and software combinations. 

HTML and in particular HTML5 five technologies provide an unifying set of technologies that are supported by the main industry vendors. HTML5 browsers are available on tables, cell phones, linux/mac/windows PCs. 

Mobilize.NET tools automate this complicated process. See http://mobilize.net/html5/

Silverlight as a mechanism for simplification of application deployment

 

I think Silverlight is a great technology that can be use to create great applications, or as a migration target from Visual Basic 6, Powerbuilder or Windows Forms apps which can take advantage of a very simplified deployment approach.

And use  Artinsoft/ Mobilize automated solutions (see http://www.artinsoft.com/visual-basic-6-or-csharp-to-the-web.aspx ) 

Deployment is as simple as just publish your SL application on your intranet and your clients just need to press F5 to have the latest SL version. 


Silverlight provides a good balance between ease of development and platform features(XAML and .NET and Visual Studio). 

Silverlight can run cross-platform. (On Windows and Mac using the official Microsoft implementation and on Linux using Moonlight. 

 

 

Support For Silverlight 4

 

 

Support For Silverlight 5

  

Also Silverlight is a good intermediate point if you plan to modernize your application even further to Windows 8 but not just yet. You will find several resources for porting your Silverlight app to Windows 8 like http://msdn.microsoft.com/en-us/library/windows/apps/xaml/br229571.aspx.  

 

 

 

NOTE: Moonlight provides support for 32 and 64 bit Linux. It supports Silverlight 2.0, and some features of silverlight 3 and 4, but is not currently an active project.  

 

Using ClickOnce deployment over the web to simplify Windows Form Application deployment

 

Artinsoft\Mobilize.Net helps legacy application to be modernized using the Windows Forms technology. Doing this upgrade revitalizes your application code and allows you to take advantage of the new platforms features like ClickOnce deployment. 

What is ClickOnce deployment?   

 
"ClickOnce is a deployment technology that enables you to create self-updating Windows-based applications that can be installed and run with minimal user interaction. Visual Studio provides full support for publishing and updating applications deployed with ClickOnce technology if you have developed your projects with Visual Basic and Visual C#.

ClickOnce deployment overcomes three major issues in deployment: 

  •          Difficulties in updating applications. With Microsoft Windows Installer deployment, whenever an application is updated, the user can install an update, an msp file, and apply it to the installed product; with ClickOnce deployment, you can provide updates automatically. Only those parts of the application that have changed are downloaded, and then the full, updated application is reinstalled from a new side-by-side folder. 

  •          Impact to the user's computer. With Windows Installer deployment, applications often rely on shared components, with the potential for versioning conflicts; with ClickOnce deployment, each application is self-contained and cannot interfere with other applications. 

  •          Security permissions. Windows Installer deployment requires administrative permissions and allows only limited user installation; ClickOnce deployment enables non-administrative users to install and grants only those Code Access Security permissions necessary for the application. 

In the past, these issues sometimes caused developers to decide to create Web applications instead of Windows-based applications, sacrificing a rich user interface for ease of installation. By using applications deployed using ClickOnce, you can have the best of both technologies."


Click Once Deployment Strategies 

 

There are 3 deployment strategies: 

  • Install from Web or a Network Share 
  • Install from a CD 
  • Start from the Web or Network share 


Quick Overview 


 

For a quick overview of how to use the ClickOnce deployment take a look at Shahar Gvirtz's post http://weblogs.asp.net/shahar/archive/2008/01/29/how-to-use-clickonce-to-deploy-your-applications.aspx

 

Profiling and Couldn't open metabase error when profiling for ASP .NET in IIS

27. November 2012 10:25 by Mrojas in ASP.NET, IIS, Profiling  //  Tags:   //   Comments (0)

I was trying to profile an ASP.NET application that was hosted on my local IIS.

But everytime I started the profiler I got a message like:

"Could not start IIS"

"Couldn't open metabase ..." "account has reduced privileges..." bla bla.

I could not understand why? My account is in the administrator group and yes,

Visual Studio was running as Administrator

Solution:

1. Run cmd as Administrator

2. c:\windows\microsoft.net\framework\v4.0.30319

3. aspnet_regiis 

4. aspnet_regiis -ga Domain\User

 

And then log off and log in

Problem uploading large files in ASP.NET

12. October 2012 10:35 by Mrojas in ASP.NET, C#, Cloud, General, HTML5, SQL Server, VB6 Migration  //  Tags: , , , ,   //   Comments (0)

If you try to upload large files you might get an exception like

HttpException: Maximum request lenght exceeded.

This problem occurs because the default value for the maxRequestLength parameter in the section 

of the machine.config or Web.config file is 4096 (4M).

So any file with a size bigger will fail.

However I think that the max size that you can write here is 2G 2097151

Some info can be found here: http://support.microsoft.com/default.aspx?scid=kb;EN-US;295626

 

So to change that for 512mb use something like:

 

<configuration>

    <system.web>

        <httpRuntime maxRequestLength="524288" /> 

    </system.web>

</configuration>

Binding problem when Sending JSON object to MVC3

25. May 2012 16:59 by Mrojas in ASP.NET, HTML5, JSON, Razor, Visual Studio  //  Tags: , , ,   //   Comments (0)

After a frustrating couple of hours trying to determine WHY WHY my object did not bind with MVC3 I finally found why.

The story began like this.

I have a very simple method in a controller. Something like this:

 

public class Form1Controller : Controller
    {
        //
        // GET: /Form1/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DoButton1(Person zzz)
        { 
            System.Diagnostics.Debug.WriteLine(zzz.Name);
            return Json(data: "Good Test");
        }
   
       

    }
 
And I called that code with a jquery Statement like:
var person= JSON.stringify({ Name: "Mauricio", LastName: "Rojas" });              $.ajax({                                    
                    url: "/Form1/DoButton1/",
                    type: "POST",
                    dataType: "json",
                    data: person,
                    success: function () {
                        alert("OK");
                    },
   
                });
 
But!!! (maybe you already saw the obvious mistake) no matter what I sent, the Person object was not bind.
The action method got called but I was not able to see the sent values. I used Chrome developer tools and the network that show the
values I had modified.
SO WHYYYYY!!!!
I tried to debug the MVC code, but VS studio could not load the pdb, something I get that I still not sure why.
So how could I intercept what was happening? Simple with a ModelBinder.
A ModelBinder is class that is used to bind your request to a model object.
So I went to the Global.asax file and register my binder, and set some breakpoints.
//Code in Global.asax to register a Person Binder
    protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            ModelBinders.Binders.Add(typeof(Person), new PersonBinder());
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

    public class PersonBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var contentType = controllerContext.HttpContext.Request.ContentType;
            if (!contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                return (null);

            string bodyText;

            using (var stream = controllerContext.HttpContext.Request.InputStream)
            {
                stream.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(stream))
                    bodyText = reader.ReadToEnd();
            }

            if (string.IsNullOrEmpty(bodyText)) return (null);

            var xx = new JavaScriptSerializer().Deserialize<Person>(bodyText);

            return xx;
        }
    }
 
And voila!! the content type I was getting was something like:application/x-www-form-urlencoded
 
So I just added the content type parameter to my javascript code:
$.ajax({                                    
                    url: "/Form1/DoButton1/",
                    type: "POST",
                    dataType: "json",
                    data: viewModelStr,
                    success: function () {
                        alert("inside");
                    }//,
                    contentType: 'application/json; charset=utf-8' 
                });
 

Binding problem when Sending JSON object to MVC3

25. May 2012 16:59 by Mrojas in ASP.NET, Razor, Visual Studio  //  Tags: , , ,   //   Comments (0)

After a frustrating couple of hours trying to determine WHY WHY my object did not bind with MVC3 I finally found why.

The story began like this.

I have a very simple method in a controller. Something like this:

 

public class Form1Controller : Controller
    {
        //
        // GET: /Form1/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DoButton1(Person zzz)
        { 
            System.Diagnostics.Debug.WriteLine(zzz.Name);
            return Json(data: "Good Test");
        }
   
       

    }
 
And I called that code with a jquery Statement like:
var person= JSON.stringify({ Name: "Mauricio", LastName: "Rojas" });              $.ajax({                                    
                    url: "/Form1/DoButton1/",
                    type: "POST",
                    dataType: "json",
                    data: person,
                    success: function () {
                        alert("OK");
                    },
   
                });
 
But!!! (maybe you already saw the obvious mistake) no matter what I sent, the Person object was not bind.
The action method got called but I was not able to see the sent values. I used Chrome developer tools and the network that show the
values I had modified.
SO WHYYYYY!!!!
I tried to debug the MVC code, but VS studio could not load the pdb, something I get that I still not sure why.
So how could I intercept what was happening? Simple with a ModelBinder.
A ModelBinder is class that is used to bind your request to a model object.
So I went to the Global.asax file and register my binder, and set some breakpoints.
//Code in Global.asax to register a Person Binder
    protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            ModelBinders.Binders.Add(typeof(Person), new PersonBinder());
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

    public class PersonBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var contentType = controllerContext.HttpContext.Request.ContentType;
            if (!contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                return (null);

            string bodyText;

            using (var stream = controllerContext.HttpContext.Request.InputStream)
            {
                stream.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(stream))
                    bodyText = reader.ReadToEnd();
            }

            if (string.IsNullOrEmpty(bodyText)) return (null);

            var xx = new JavaScriptSerializer().Deserialize<Person>(bodyText);

            return xx;
        }
    }
 
And voila!! the content type I was getting was something like:application/x-www-form-urlencoded
 
So I just added the content type parameter to my javascript code:
$.ajax({                                    
                    url: "/Form1/DoButton1/",
                    type: "POST",
                    dataType: "json",
                    data: viewModelStr,
                    success: function () {
                        alert("inside");
                    }//,
                    contentType: 'application/json; charset=utf-8' 
                });
 

Output unescaped string in Razor

24. May 2012 00:03 by Mrojas in ASP.NET, HTML5, Javascript, JSON, Razor  //  Tags: , , , , ,   //   Comments (0)


 
While doing some experiments with Razor, and trying to generate some simple JSON objects in my ASP.NET MVC views
I had to deal with problems because my json string got a lot of weird &quot; and other strange escape character.
That in general is very good but I needed my string just as is.

The current workaround that I have found for doing that is:
 
var objectInStr = @(new HtmlString(Json.Encode(Model or your object)));