Tuesday, August 30, 2011

Chart Helpers in ASP.NET MVC3- Create chart with asp.net mvc3

I am exploring ASP.NET MVC3 and everyday I am learning something new. In today’s post I am going to explain how we can create chart with ASP.NET MVC3.

Chart is one of greatest way of expressing figures. We all need that functionality in any commercial application. I am still remembering old days with ASP.NET  where we have to use the third party controls for charts or we have to create it with the use of CSS and Server side controls. But now with ASP.NET MVC Helpers you can very easily create chart in few lines of code.

ASP.NET MVC Chart helper and other helpers comes inbuilt with the latest ASP.NET Tools update. If you don’t have ASP.NET MVC Chart helpers then you can find more information about it from here.

http://haacked.com/archive/2011/04/12/introducing-asp-net-mvc-3-tools-update.aspx

But still if you have not updated it then don’t worry about it. There is nuget package called “ASP.NET Webhelper Library”. You can add that package like following and still use same functionality.

ChartHelper-ASP.NET Web Helpers Library Pacakge

Now once you have all set for reference. We can start working on coding part. So draw a chart I have taken simple example like number of records vs time take chart. This Chart Helper support there types of cjart.
  1. Bar Chart
  2. Pie Chart
  3. Column Chart
In this example we are going to use Bar Chart. Following is code for that. I have create one simple action result called “DrawChart” which will return chart as PNG format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Helpers;

namespace CodeSimplifiedTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

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

        public ActionResult DrawChart()
        {
            var chart = new Chart(width: 300, height: 200)
                .AddSeries(
                            chartType: "bar",
                            xValue: new[] { "10 Records", "20 Records", "30 Records", "40 Records" },
                            yValues: new[] { "50", "60", "78", "80" })
                            .GetBytes("png");
            return File(chart, "image/bytes");
        }
    }
}

Here you can see that first I have included System.Web.Helper name space on top and then in DrawChart Action Result I have created chart variable where I have specified the height and width of chart and in add series method of it I have provided the chart type and x axis and y axis value. Now as we have to display it as image so for that I have used @URL.Action to point src to our Action Result DrawChart like following.
<img src="@Url.Action("DrawChart")" alt="Drawing chart with HTML Helper" />

Now let’s run this application in browser via pressing Ctrl+F5 and following is the output as expected.

Output

That’s it. You can see its very to create any kind of chart with Chart Helpers in ASP.NET MVC 3. Hope you like it. Stay tuned for more.. Till then happy programming and Namaste!!

Shout itkick it on DotNetKicks.com
Share:
Sunday, August 28, 2011

Visual Studio 2010 Features post list on my blog

Share:
Saturday, August 27, 2011

ILSpy-Alternative of .NET Reflector

Sometimes we need to have decomposer tool or reflector tool for our applications to improve the performance or to know the internals of the assembly we have created. I was using Red Gate .NET Reflector earlier for same as it was free. Now Red Gate has made that tool paid version so I was finding some tools from that I can decompile the stuff. After digging some time on the internet I have found a great tool ILSpy which almost giving same functionalities like .NET Reflector. You can download that tool from following link.

http://wiki.sharpdevelop.net/ilspy.ashx

You will get following features in ILSpy. It is also listed on above page.
  • Assembly browsing
  • IL Disassembly
  • Decompilation to C#
    • Supports lambdas and 'yield return'
    • Shows XML documentation
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)

Now let’s see how we can use ILSpy for decompiling our application. I have created a very basic console application which will concat string and print name. Here I have intentionally used string concatenation instead of StringBuilder class to show what’s going internally with ILSpy. Following is code for that.

using System;
namespace ThisExample
{
     class Program
     {
          static void Main(string[] args)
          {
              Test test = new Test();
              test.PrintName();
           }
     }
     public class Test
     {
          private string name = "Jalpesh Vadgama";
          public void PrintName()
          {
              name += " vishal vadgama";
              Console.WriteLine(name);
          }
     }
}

Once we are done with code let’s run that application and following will be a output.

Output window for ILSpy-Alternative of .NET Reflector

Let’s check that console application with the ILSpy. Once you double click exe of ILSpy it will look like following.

ILSpy- Alternative of .NET Reflector

Now let’s open our application via File->Open Menu. So it will load our application like following


ClassHirerchay with ILSpy-.NET Reflector Alternative

As you can see in above screenshot It has loaded whole class hierarchy of console application we have just created as we can see Program and Test class directly and on right hand pane it has loaded whole assembly information for this application. You can see that in below image.


AssemblyInformation from ILSpy- Alternative of .NET Reflector

Now once you click on program it will load program information on right pane like following.

RightPane of code from ILSpy-.NET Reflector Alternative

Event it’s provide IL mode also so you can see what’s going on internally on top its having button like this.

You can select IL from ILSpy-Alternative .NET Reflector

Once you select IL you right pane will load IL like following.In that you can see its using concat method

ILRightPane

So you can see its almost providing functionalities which was provided by .NET Reflector. Hope you like it.. stay tuned for more..till then happy programming.

Shout it
kick it on DotNetKicks.com
Share:
Wednesday, August 17, 2011

Creating Basic RSS Reader in ASP.NET MVC 3

In this post I am going to explain you how we can create a basic RSS Reader with the help of Linq-To-Xml and ASP.NET MVC3 Razor. Those who are writing or reading Blogs already knows what is RSS Reader. But those who does not know What is RSS. Below is the definition for RSS as per Wikipedia.


RSS (originally RDF Site Summary, often dubbed Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.[2] An RSS document (which is called a "feed", "web feed",[3] or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship.
 

You can find more information about RSS from the following links.

Now let’s start writing code creating a Basic RSS Reader. So first We need two things to create RSS Reader. A RSS Entity class which hold properties for RSS and Another method which populate IEnumerable of particular RSS Class. We are creating this example with ASP.NET So I have create One Model class called RSS Like following.
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace CodeSimplified.Models
{
public class Rss
{
public string Link { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
}

Now our entity class is ready. Now we need a class and a method which will return IEnumerable of RSS Class. So I have created a Static Class RSS Reader which has “GetRSSFeed” Method which return RSS Feeds like following.

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace CodeSimplified.Models
{
public class RssReader
{
private static string _blogURL = "http://feeds.feedburner.com/blogspot/DotNetJalps";
public static IEnumerable<Rss> GetRssFeed()
{

   XDocument feedXml = XDocument.Load(_blogURL);
   var feeds = from feed in feedXml.Descendants("item")
               select new Rss
               {
                   Title = feed.Element("title").Value,
                   Link = feed.Element("link").Value,
                   Description = Regex.Match(feed.Element("description").Value, @"^.{1,180}\b(?<!\s)").Value

               };

   return feeds;

}
}
}

As you can see in above code. I am loading RSS feed with XDcoument Class with my Blog RSS feed URL and Then I am populating RSS Class Enumerable with the help of the Linq-To-XML. Now We are ready with Our Model classes so Now it’s time to Add ActionResult in Home Controller. So I have added Action Result which return View with RSS IEnumerable like following.

public ActionResult RssReader()
{
    return View(CodeSimplified.Models.RssReader.GetRssFeed());
}

Now everything is ready. So its time to create a view. So I have created strongly typed view for RSS Model class like following.

@model IEnumerable<CodeSimplified.Models.Rss>
@{
ViewBag.Title = "RssReader";
}

<h2>RssReader</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
   Title
</th>
<th>
   Description
</th>
<th>
   Link
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
   <a href="@item.Link" target="_blank">@Html.Encode(item.Title)</a>
</td>
<td>
  @System.Web.HttpUtility.HtmlDecode(item.Description)
</td>
<td>
   <a href="@item.Link" target="_blank">More</a>
</td>
</tr>
}
</table>

Let's run application via pressing F5 and Following is the output as expected.


RssReader

So that’s it. Isn’t that cool? With the few lines of code we have created a Basic RSS Reader. Hope you like it. Stay tuned for more.. Till then Happy Programming..

Shout itkick it on DotNetKicks.com
Share:
Tuesday, August 16, 2011

Setting default value for @Html.EditorFor in asp.net mvc

Yesterday one of my friend asked me to set default value for @HTML.EditorFor in ASP.NET MVC. So I decided to write this blog post. In this blog post I am going to Explain How we create Default values for model Entities. So Let’s start this via taking a simple example Model class called User. In User Model class I have created two properties UserName and UserJoinedDate. Following is a code for that.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;



namespace CodeSimplified.Models

{

public class User

{

    private DateTime _userJoinDate = DateTime.Now;



    public DateTime UserJoinDate

    {

        get

        {

            return _userJoinDate;

        }

        set

        {

            _userJoinDate = value;

        }

    }



    public string UserName

    { get; set; }

}

}
As you can see in above class username is default property while for UserJoinedDate I have used old method of declaring properties. Where I have assigned a private variable with System DateTime.
Now let’s Create a Action Result User in Home Controller like following where I am returning a new User View like following.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;



namespace CodeSimplified.Controllers

{

public class HomeController : Controller

{

    public ActionResult Index()

    {

        ViewBag.Message = "Welcome to ASP.NET MVC!";



        return View();

    }



    public ActionResult About()

    {

        return View();

    }



    public ActionResult User()

    { return View(new CodeSimplified.Models.User()); }

}

}

Now Let’s Create User View from the action right click Add view like following. Here I have created Strongly Typed view like following.


User

Once you click Add It will add a new View like following.

@model CodeSimplified.Models.User



@{

ViewBag.Title = "User";

}



<h2>User</h2>



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

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



@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

    <legend>User</legend>



    <div class="editor-label">

        @Html.LabelFor(model => model.UserJoinDate)

    </div>

    <div class="editor-field">

        @Html.EditorFor(model => model.UserJoinDate)

        @Html.ValidationMessageFor(model => model.UserJoinDate)

    </div>



    <div class="editor-label">

        @Html.LabelFor(model => model.UserName)

    </div>

    <div class="editor-field">

        @Html.te

        @Html.EditorFor(model => model.UserName)

        @Html.ValidationMessageFor(model => model.UserName)

    </div>



    <p>

        <input type="submit" value="Create" />

    </p>

</fieldset>

}



<div>

@Html.ActionLink("Back to List", "Index")

</div>


Now everything is ready so Let's run that in browser. Following is the output as expected.

Browser

So that’s it. It’s very easy. Hope you liked it. Stay tuned for more.. Till then happy programming.

Shout itkick it on DotNetKicks.com
Share:
Saturday, August 13, 2011

Visual Studio 2010 Color Theme Editor- Customize look of visual studio

We have all love Visual Studio 2010 and I am sure you all want to change color for menus, toolbars and title etc. Today I have found one of the most interesting Extension for Visual studio 2010 from which you can manage all this things. Don’t believe me I’m sure you won’t believe but this reality and You can change the look of your favorite visual studio look and feel. There is a new extension called “Visual Studio Color Theme Editor” from which you can do all this stuff. Here is the link for that.

http://visualstudiogallery.msdn.microsoft.com/20cd93a2-c435-4d00-a797-499f16402378

Once you download and install this link a Theme Menu will be added to Visual Studio like following.

ThemeMenu

There are 8 themes provided by the Default. You can choose any one of them. Lets choose Emerald theme for visual studio and It will look like following.

EmerlandThemeForVisualStudio

Isn’t that great?. Even you can also design your own theme also. Click on Theme->Customize colors and then It will popup a dialog like following. where you can will get lots of things for which you can customize the color.


CustomisedColorDialogForVisualStudio

Isn’t that Great. Hoped You liked it. Stay tuned for more..Till then happy programming..


Shout itkick it on DotNetKicks.com
Share:
Tuesday, August 2, 2011

Surround with feature in Visual Studio 2010

Everyday I am discovering something new with Visual Studio 2010 and today Once again I have discovered a new feature called “Surround with” feature. This feature is quite useful when you have very big HTML element and You want to surround it some HTML or ASP.NET element i.e. Suppose there is one very big div there and you want to add update panel for Ajax . So let’s take a Simple Example over there. I am having a div which contain very big HTML in it. Like following.

<div>

 Very big HTML here.

</div>

Now let's put that div into update panel with Surround with feature. You can right click and click Surround With or You can directly have shortcut Ctrl+k, Ctrl +S like following.

SurroundMenu

Now once you click it It will popup three things. 1) ASP.NET 2) ASP.NET MVC 2 and 3) HTML. You can select element of any of that like following.

SurroundPopup

I am going select ASP.NET as we want to put Update panel over there. Once you click ASP.NET It will popup elements of asp.net. Here I have selected update panel as I want to put update panel covering this div like following.

UpdatePanel

Now once you click update panel it will put Update panel and div will be in content template of Update panel. Now our code will like following.

<asp:UpdatePanel runat="server">

 <ContentTemplate>

     <div>

         Very big HTML here.

     </div>

 </ContentTemplate>

</asp:UpdatePanel>

That's it. Isn't that cool?.Isn't visual studio 2010 is a great IDE? Hope you like it. Stay tuned for more.. Till then Happy Programming..

Shout itkick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews