Saturday, July 21, 2012

MVC ~ Transferring data from one page to another

Lot of times we would need to pass data from one page to another. The data could be a simple data or it can also be a complex data. In case of simple data, we can transfer using query string parameter and this does the job but when the size of the data is really big or if it is a complex type, then we need a different mechanism.

 

With MVC, we get the dictionary object to store the values at one end and retrieve it at the other end. These values are actually stored in session and lasts until the session terminates. Here is how we can make use of it:

 

//store the data to temp data dictionary. Data can be of any type

TempData[“myUniqueKey”] = value;

……

……

//retrieve the data from temp data dictionary.

if (TempData.ContainsKey(“myUniqueKey”))

myComplexData = TempData[“myUniqueKey”] as MyComplexData;

 

Happy Programming!!!

Sunday, July 15, 2012

Resolving HTTP Connection Timeout with Android applications

Response time of any application greatly matters especially those dealing with network operations. Sometimes the response from the server is reasonable but at times servers get busy and takes much time in responding. In such situation, we generally set timeout (in the range of 20-30 seconds) for method execution and handle the operation accordingly. This range of timeout is fair for web application but coming to mobile devices the response time has to be much quicker in the range of 3-5 seconds.

We define the connection timeout as follows:

HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);

Here in the above snippet the connection timeout is set to 3000 milliseconds or 3 seconds. But executing the operation, we will notice that the execution does not return after 3 seconds though set rather it waits for a long time. In order to resolve this issue, along with setting the connection timeout, we also need to set the socket timeout as follows:

HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);

Now executing the operation, we will notice that the execution of code block returns in 3 seconds.

Hope this solves your problem…
Happy programming !!!

Thursday, July 12, 2012

Eclipse build error: The project was not built since its build path is incomplete. Cannot find the class file for xxxxx. Fix the build path then try building this project

We are creating a project in Eclipse studio, building the project and it executes. Everything goes fine and smooth. Next time we open the Eclipse studio and see red cross mark error beside our imports on basic java class references. To be more specific, we get the following issue:

The project was not built since its build path is incomplete. Cannot find the class file for xxxxx. Fix the build path then try building this project

Here xxxxx can be any of the java class file. We wonder why we get this and that it didn’t happen when we worked on the project just before Lunch!!! Annoying huh.. Ok so what is the problem and how to get rid of this ASAP? Well…the problem is with the reference of java library in our project. Sometimes Eclipse loses the reference path and require us to help it out. And how do we do that…here are the steps:

1.       Right click on the project from the Project Explorer and select “Properties”. Alternatively we can also select “Properties” from the Project menu.
2.       From the Properties dialog, select “Java Build Path” from the left side view.
3.       Clicking the “Libraries” tab we can see the libraries referenced in the project and will also see that something is wrong with JRE library referenced in the project as shown below:


4.       Next we select this library and remove it. Then we click the “Add Library…” button on the right and then select the “JRE System Library” and then click the “Next” button as shown below:


5.       By default, we will see that “Workspace default JRE” is selected as shown below. We can leave this as is and then click the “Finish” button


Now that we have the JRE library referenced to the project, we should see the error go away. But sometimes not. In this case, we do the regular clean-up of the project as follows:

1.       Project Menu -> Clean

2.       Right click on the project from “Project Explorer” and “Refresh”

3.       Right click on the project from “Project Explorer” and under "Android Tools" click “Fix Project Properties”

4.       May be even restart Eclipse if the above 3 steps doesn’t work and then repeat the 3 steps after restarting

Finally we see the error go away. Whew….
Hope this helps reduce your headache and…

Happy Programming!!!


Tuesday, July 10, 2012

Resolving ~ uncaught exception: [CKEDITOR.editor] The instance "myCKEditor" already exists.

Having added the CKEditor successfully to our web application, we see that it loads fine but during post-back we get a javascript error message as

uncaught exception: [CKEDITOR.editor] The instance "myCKEditor" already exists.

The error states about the existence of the CKEditor in the browser. So, we have to get rid of the ones that already exists using the following method:

<script language="javascript" type="text/javascript">
    if (CKEDITOR.instances['myCKEditor']) { delete CKEDITOR.instances['myCKEditor'] };
    if (CKEDITOR.instances['myCKEditor']) { CKEDITOR.instances['myCKEditor'].destroy(); }
</script>

The above code will remove the existence of the ‘myCKEditor’ editor from the browser memory and recreates it thereby resolving the issue.

Happy Programming!!!

Sunday, July 08, 2012

Delivering Compressed and Combined files for MVC 3 applications

It is very difficult to stay in the race without delivering application that performs “The Best” in the web world. To help us be in the race, we have lot of resources available in the internet to search for and plug in to our web application to gain optimal performance. One such tool is Squish It.

SquishIt is a framework for ASP.NET web application that compresses and combines javascript and css files. There are lot more options available with the SquishIt framework, but let’s walk-through the quick process of setting up the framework for ASP.NET MVC 3 application to compress and combine the css and javascript files.

Ok here we go…

1.       Download the latest framework from the GitHub from the following location: https://github.com/jetheredge/SquishIt/downloads

2.       Extract the zip file and reference the SquishIt.Framework.dll and SquishIt.Mvc.dll in your MVC application.
Note: If the dlls are not available in the bin folder of the extracted zip file, then you will have to open the solution in VS and built it (in release mode) and then reference the dlls in your MVC application.

3.       Next open the page (cshtml) where you have references to javascript and css files

4.       Add the following library references at the top of the cshtml page:

@using SquishIt.Framework
@using SquishIt.Mvc

5.       Next we have to transform the code that references the css files from:

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
       <link href="@Url.Content("~/Content/ jquery.alerts.css")" rel="stylesheet" type="text/css" />
       <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />

                to

                @(Bundle.Css()
            .Add("~/Content/Site.css")
            .Add("~/Content/jquery.alerts.css")
            .Add("~/Content/bootstrap.css")
            .ForceRelease()
            .MvcRender("~/Content/Site_#.css")
       )

6.       And then we transform the code that references the javascript files from:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>

                to           

       @(Bundle.JavaScript()
            .Add("~/Scripts/jquery.validate.min.js")
            .Add("~/Scripts/jquery-ui-1.8.11.min.js")
            .Add("~/Scripts/MicrosoftAjax.js")
            .ForceRelease()
            .MvcRender("~/scripts/combined_#.js")
)

And that’s it! Go ahead and run your application. Open the Firefox YSlow plugin and verify the number of requests for the css and javascript files. It should be two. Also, you would find that the size of the output file is a reduced one.

Happy programming!!!


Monday, July 02, 2012

MVC 3 Get the Html ID of a control for jQuery calls

jQuery makes the life of web developer simpler by addressing most of the browser compatibility issues. Every developer wants to make use of jQuery library to leave (most of) the browser related compatibilities to be taken care of by jQuery and concentrates on the actual requirements instead of worrying about other factors.

Integration of jQuery in any web project is as easier as it can be. The only important thing is to carefully pass the correct or appropriate id to jQuery calls. It is easier to view the generated source and hard code the corresponding ID to the jQuery calls. Ofcourse this would work and good for short term projects however for long term projects hard coding is not the best idea and nor is it recommended.

With traditional ASP.NET application, we use the following method to get hold of the Html ID that will  be generated for a control:

var id = $(“#<%=aspNetDotnetControl.ClientID %”>

This technique doesn’t work with ASP.NET MVC architecture. The following is one of the easiest way to do this in MVC 3:

1.       Define the extension method for the HtmlHelper class to return the fully qualified name for the given html (partial) field
2.       Define another extension method that just takes the fully qualified name and return the ID of the HTML element

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),
        System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static string NameFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            return htmlHelper != null ? htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)) : string.Empty;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),
        System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static string IdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            return HtmlHelper.GenerateIdFromName(NameFor(htmlHelper, expression));
        }

                After defining the above two extension methods, we are now ready to make use of it in our cshtml files as follows:

                $('#@Html.IdFor(m => m.Service.Name)')

       And that’s it.