Sunday, October 28, 2012

What is a Delegate?

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.





Declaration


public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Friday, July 20, 2012

How To call Mvc Function With Json



    $(document).ready(function () {
        $("#ddlModelSeries").change(function () {

            var Mname = $(this).val();

            $.getJSON("AddModelSeries/LoadBrand", { id: Mname }, function (AreaData) {
                var select = $("#ddlBrand"); select.empty(); select.append($('
                $.each(AreaData, function (index, itemData) {

                    select.append($('
                        value: itemData.Value,
                        text: itemData.Text
                    }));
                });

            });

        });


    });

             



how to hide menu in mvc 3 on master page





@if(Session["username"] !=null)
    {
 

 
     
 @Html.ActionLink("Manange Step", "Index", "Adminmanage")
 &nbsp 
@Html.ActionLink("Manange Errorcode", "Index", "Admin")&nbsp&nbsp

 @Html.ActionLink("LogOut", "LogOn", "Account")&nbsp&nbsp
     

        }

how pass value from page to javascript with hidden varible


@model UFixnow.Models.ModelSeries
@{
    ViewBag.Title = "Index";
   Layout = "~/Views/Shared/_Adminlayout.cshtml";
    var id = Session["SeriesId1"];
}





Tuesday, July 10, 2012

oops Concepts



 Abstraction

The process of picking out (abstracting) common features of objects and procedures. A programmer would use abstraction, for example, to note that two functions perform almost the same task and can be combined into a single function. Abstraction is one of the most important techniques in software engineering and is closely related to two other important techniques -- encapsulation and information hiding. All three techniques are used to reduce complexity.



Difference between Struct and Class

Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.



Boxing and Un-Boxing

Boxing: means converting value-type to reference-type.

Eg:

int I = 20;

string s = I.ToSting();


UnBoxing: means converting reference-type to value-type.

Eg:

int I = 20;

string s = I.ToString(); //Box the int

int J = Convert.ToInt32(s); //UnBox it back to an int.


Note: Performance Overheads due to boxing and unboxing as the boxing makes a copy of value type from stack and place it inside an object of type System.Object in the heap.




http://dng-oops.blogspot.in/









Virtual Method

By declaring base class function as virtual, we allow the function to be overridden in any of derived class.

Eg:

Class parent

{

virtual void hello()

{ Console.WriteLine(“Hello from Parent”); }

}


Class child : parent

{

override void hello()

{ Console.WriteLine(“Hello from Child”); }

}


static void main()

{

parent objParent = new child();

objParent.hello();

}

//Output

Hello from Child.





Access Modifiers

Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

Public is visible to everyone. A public member can be accessed using an instance of a class, by a class's internal code, and by any descendants of a class.


Private is hidden and usable only by the class itself. No code using a class instance can access a private member directly and neither can a descendant class.

Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.




Encapsulation

Is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.

Real time
e.g. / Ink is the important component in pen but it is hiding by some other material

Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly; rather, they are encapsulated by the class.

For example code

Public class Calculations
{
  private void fnMultiply(int x, int y)
  {
  return x * y;
  }
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10)




ENCAPSULATION MEANS HIDING ALL THE INTERNAL DETAILS OF THE METHODS.

EXAMPLE cars and owners...
all the functions of cars are encapsulated with the owners..
No one else can access it...





Friday, June 8, 2012

how to set dropdownlist max item in asp net


Set these value in dropdown

onmouseover="this.size=4;"
onmouseout="this.size=1;"

Friday, March 23, 2012

what is CLR,JIT,GAC,GC


CLR means Common Language Runtime.It is  Major component of 
the .NET frameworkIt provides no of benefits to the 
developers such as Exception handling,Security,Debugging 
and Versioning.

Common Language Runtime is Runtime engine which converts 
Microsoft Intermediate Language in machine understandable 
code, it is similar to JVM in Java


working of CLR:-

When the .NET program is compiled, the output of the 
compiler is not an executable file but a file that contains 
a special type of code called  the Microsoft Intermediate 
Language (MSIL), which is a low-level set of instructions 
understood by the common language run time. This MSIL 
defines a set of portable instructions that are independent 
of any specific CPU. It's the job of the CLR to translate 
this Intermediate code into a executable code when the 
program is executed making the program to run in any 
environment for which the CLR is implemented. And that's 
how the .NET Framework achieves Portability. This MSIL is 
turned into executable code using a JIT (Just In Time) 
complier. The process goes like this, when .NET programs 
are executed, the CLR activates the JIT complier. The JIT 
complier converts MSIL into native code on a demand basis 
as each part of the program is needed. Thus the program 
executes as a native code even though it is compiled into 
MSIL making the program to run as fast as it would if it is 
compiled to native code but achieves the portability 
benefits of MSIL.

jit:

Before Microsoft intermediate language (MSIL) can be
executed, it must be converted by a .NET Framework
just-in-time (JIT) compiler to native code, which is
CPU-specific code that runs on the same computer
architecture as the JIT compiler. 
Rather than using time and memory to convert all the MSIL in
a portable executable (PE) file to native code, it converts
the MSIL as it is needed during execution and stores the
resulting native code so that it is accessible for
subsequent calls.

JIT compiler is a part of the runtime execution environment.
In Microsoft .NET there are three types of JIT compilers.

Pre-JIT : Pre-JIT compiles complete source code into native
code in a single compilation cycle. This is done at the time
of deployment of the application.

Econo-JIT : Econo-JIT compiles only those methods that are
called at runtime. However, these compiled methods are
removed when they are not required.

Normal-JIT : Normal-JIT compiles only those methods thar are
called at runtime.

What is GAC?
A shared assembly has version constraints. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named.
GC:
In .NET Garbage Collector maintained by CLR. The process of 
GC is reclaim the memory of objets which is no longer 
referenced by our program.Next thing is GC runs 
undeterministicly because of that we can't assure we the 
object will be released from the Heap Location

If there is any memory defeciency then only GC will called 
by CLR. GC always runs on the priority basis. If size of free 
memory is more, than GC runs on low priority basis.  And if 
memory becomes low than GC Starts running on high priority 
to free up the memory from those object which are no loger 
in used.

metadata: Metadata is information about a PE(Portable Executable)means information about Executable file

Sunday, January 15, 2012

dynamic sitemap in mvc 3


Getting the bits

As always, the bits are available on CodePlex: MvcSiteMapProvider 2.0.0
If you prefer to have the full source code, download the example application or check the source code tab on CodePlex.

Introduction


MvcSiteMapProvider is, as the name implies, an ASP.NET MVC SiteMapProvider implementation for the ASP.NET MVC framework. Targeted at ASP.NET MVC 2, it provides sitemap XML functionality and interoperability with the classic ASP.NET sitemap controls, like the SiteMapPath control for rendering breadcrumbs and the Menu control.
Based on areas, controller and action method names rather than hardcoded URL references, sitemap nodes are completely dynamic based on the routing engine used in an application. The dynamic character of ASP.NET MVC is followed in the MvcSiteMapProvider: there are numerous extensibility points that allow you to extend the basic functionality offered.


"MvcSiteMapProvider" enabled="true">
 
   
    "MvcSiteMapProvider"
         type="MvcSiteMapProvider.DefaultSiteMapProvider, MvcSiteMapProvider"
         siteMapFile="~/Mvc.Sitemap"
         securityTrimmingEnabled="true"
         enableLocalization="true"
         scanAssembliesForSiteMapNodes="true"
         skipAssemblyScanOn=""
         attributesToIgnore="bling"
         nodeKeyGenerator="MvcSiteMapProvider.DefaultNodeKeyGenerator, MvcSiteMapProvider"
         controllerTypeResolver="MvcSiteMapProvider.DefaultControllerTypeResolver, MvcSiteMapProvider"
         actionMethodParameterResolver="MvcSiteMapProvider.DefaultActionMethodParameterResolver, MvcSiteMapProvider"
         aclModule="MvcSiteMapProvider.DefaultAclModule, MvcSiteMapProvider"
         />
 

in site map





   
   
   
   
   
   
 
    dynamicNodeProvider="WhoTrackYou.Models.StoreDetailsDynamicNodeProvider, WhoTrackYou"/>
 

in page where you want to show site map use following function:

  • Html.MvcSiteMap().Menu() - Can be used to generate a menu
  • Html.MvcSiteMap().SubMenu() - Can be used to generate a submenu
  • Html.MvcSiteMap().SiteMap() - Can be used to generate a list of all pages in your sitemap
  • Html.MvcSiteMap().SiteMapPath() - Can be used to generate a so-called "breadcrumb trail"
  • Html.MvcSiteMap().SiteMapTitle() - Can be used to render the current SiteMap node's title 




The following attributes can be given on an XML node element:
Attribute Required? Default Description
title Yes (empty) The title of the node.
description No (empty) Description of the node.
area No (empty) The MVC area for the sitemap node. If not specified, it will be inherited from a node higher in the hierarchy.
controller Yes (empty) The MVC controller for the sitemap node. If not specified, it will be inherited from a node higher in the hierarchy.
action Yes (empty) The MVC action method for the sitemap node. If not specified, it will be inherited from a node higher in the hierarchy.
key No (autogenerated) The unique identifier for the node.
url No (autogenerated based on routes) The URL represented by the node.
roles No (empty) Comma-separated list of roles allowed to access the node and its child nodes.
resourceKey No (empty) Optional resource key.
clickable No True Is the node clickable or just a grouping node?
targetFrame No (empty) Optional target frame for the node link.
imageUrl No (empty) Optional image to be shown by supported HtmlHelpers.
lastModifiedDate No (empty) Last modified date for the node.
changeFrequency No Undefined Change frequency for the node.
updatePriority No Undefined Update priority for the node.
dynamicNodeProvider No (empty) A class name implementing MvcSiteMapProvider.Extensibility.IDynamicNodeProvider and providing dynamic nodes for the site map.



 public class StoreDetailsDynamicNodeProvider
      : DynamicNodeProviderBase
    {
        WhoTracksMeEntities storeDB = new WhoTracksMeEntities();

        public override IEnumerable GetDynamicNodeCollection()
        {
            // Build value
            var returnValue = new List();

            // Create a node for each Cookie
            foreach (var ck in storeDB.cookies1.Where(x => x.DescriptionStatus.ToUpper() == "MODERATION"))
            {
                DynamicNode node = new DynamicNode();
                node.Title = ck.Name;
                node.Controller = "Cookie";
                node.Action = "CookieDetail";// +"/" + ck.Id;
                node.RouteValues.Add("id", ck.Id);

                returnValue.Add(node);
            }

            // Return
            return returnValue;
        }

        public override CacheDescription GetCacheDescription()
        {
            return new CacheDescription("StoreDetailsDynamicNodeProvider")
            {
                SlidingExpiration = TimeSpan.FromMinutes(1)
            };
        }


    }


Note that these should be registered in Web.config, i.e. under pages tag  in webconfig .add the following:



  In    namespaces
     
        namespace="MvcSiteMapProvider.Web.Html" ;
 



Monday, January 9, 2012

how we add sitemap in mvc3


Once you’ve got your sitemap correctly configured and setup, you will be looking to use some of the features of a Sitemap – for example, breadcrumbs. In this post we will start with an empty MVC3 project, and add the asp.net sitemap provider, a few controller actions and corresponding views, and we will have the provider produce some breadcrumbs for us.

Setup

Lets start from an Empty MVC3 project. Fire up Visual Studio. Create a new Asp.Net MVC3 Web application. I’m going to call mine SitemapDemo:
Create new MVC3 project
For the sake of this demonstration, I have selected an empty template and have chosen Razor as my view engine.
Now before we go any further, lets go ahead and install the NuGet package.  Select View > Other Windows and then select “Package Manager Console”:
Package Manager Console Location VS2010
This will then dock the Package Manager Console somewhere into your view. In order to add the Asp.net MVC sitemap provider to the current project, we need to enter the following command into the Package Manager Console, and hit enter:
PM> Install-Package MvcSiteMapProvider
This command will then download the necessary files (dlls, cshtml files) and add them into your MVC project. This could take a few minutes depending on your connection. If this has been successful, your Package Manager Console should give you an output similar to the following:
PM> Install-Package MvcSiteMapProvider
Successfully installed 'MvcSiteMapProvider 3.1.0.0'.
Successfully added 'MvcSiteMapProvider 3.1.0.0' to SitemapDemo.

PM>

Now lets take a look at what exactly the NuGet package manager has added to our project:
  • SitemapDemo > References > MvcSiteMapProvider – This is the reference to the MvcSiteMapProvider dll
  • SitemapDemo > Mvc.sitemap – This file will be used to describe our MVC3 website in XML nodes
  • SitemapDemo > Views > Shared > DisplayTemplates > MenuHelperModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapHelperModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapNodeModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapNodeModelList.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapPathHelperModel.cshtml
  • SitemapDemo > Views > Shared > DisplayTemplates > SiteMapTitleHelperModel.cshtml
As we’re using Razor as our view engine, we can go ahead and delete the asax files that have been added to the SitemapDemo > Views > Shared > DisplayTemplates folder. Here’s how your solution should now look:
Sitemapdemo Solution Explorer
Now that’s the install over. Let’s add a half decent set of controller actions and views to the site before we go on to playing with the SiteMapProvider. The point of this is to capture the kind of structure that you would find in a typical website.
Important
The MVC Sitemap provider will fail silently in some fashion if we try to force it to work with controller actions that either don’t exist or that point to non existent views. This is why we are doing this stage first.
All sites have a homepage, so lets add this first. Right click on your Controllers folder, and add a controller called “HomeController”. Lets leave the scaffolding options blank:
HomeController-Add Blank
Once your controller is created and open, right click inside the Index action and select “Add View…”
Home Index Add View
In the Add View dialogue that pops up, just go a head hit add. Nothing will need changing.  Now lets change the text inside the created page’s h2 tag on the page – something like “Index – this is the home page” will do.
And now lets add another controller in the same way that we added the HomeController. Let’s call it NewsController. Update the newly created news controller to contain an additional action result called “Sports”:

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Web;
05using System.Web.Mvc;
06
07namespace SitemapDemo.Controllers
08{
09    public class NewsController : Controller
10    {
11        //
12        // GET: /News/
13
14        public ActionResult Index()
15        {
16            return View();
17        }
18
19        //
20        // GET: /News/Sports/
21        public ActionResult Sports()
22        {
23            return View();
24        }
25
26    }
27}

Now, lets add a view for each of our newly created NewsController actions. Lets do this in the same way that we added the view for the home page – by right clicking within the body of each controller action. Again, we can simply leave all of the defaults in the “Add View” dialogue and just hit “Add” for both views.
Now edit the h2 tag on the News Index cshtml file to read “News Index”. Lets also edit the h2 tag on the News Sports cshtml file to read “Sports News”.
Let’s now add one more Controller for illustration – AboutController. Once created, you can leave the controller unchanged, and can add a view for the Index controller action. This time, lets change the h2 to tags to read “About Page”.
As we have now added 4 pages to our website, it’s now worth just testing them out before we start integrating the Site Map Provider. Hit the debug button – below are screen shots and their corresponding URLs:
localhost:xxxx
SitemapDemo Index
localhost:xxxx/News
SitemapDemo News Index
localhost:xxxx/News/Sports
SitemapDemo News Sports
localhost:xxxx/About
SitemapDemo About Index
Ok, so we’ve now got a small site with a little bit of a structure. Lets represent that structure in an easy diagram:
SitemapDemo Sitemap Diagram
Visualising our layout like this will really help us describe our site’s structure in our Mvc.sitemap file correctly. Our Index page is our wrapper for the entire site as it is the page that sits in the root, and is the first port of call into the site.
Now lets get into configuring our Sitemap. Lets start by editing our Mvc.sitemap file, which is in the root of our project. This file contains all of the xml nodes needed to represent your controller and action combinations.
MVC Sitemap xml file vs
Edit your Mvc.Sitemap file so that it is the same as the listing below:

1xml version="1.0" encoding="utf-8" ?>
2<mvcSiteMap xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0" enableLocalization="true">
3  <mvcSiteMapNode title="Home" controller="Home" action="Index">
4    <mvcSiteMapNode title="News" controller="News" action="Index">
5      <mvcSiteMapNode title="Sports News" controller="News" action="Sports"/>
6    mvcSiteMapNode>
7    <mvcSiteMapNode title="About" controller="About" action="Index"/>
8  mvcSiteMapNode>
9mvcSiteMap>

We have now represented our website structure / workflow in the MVC.Sitemap file. A classic “gotcha” here is forgetting that your entire site is wrapped in a node that represents your homepage. Your sitemap file must contain this node – after all, your website’s homepage is the page that the client sees as the root of everything. So even though the Index action is actually at yourwebsite/Index, the client will typically see it just as yourwebsite/. The rest of the structure should make sense when compared to the website navigation diagram, earlier in this post.

Adding Navigation

Now that we’ve got some controllers and actions setup, and our site structure described properly in our Mvc.Sitemap file, lets add some navigation to all pages.
Open up your _Layout.cshtml partial, located in the Views/Shared folder. Update the listing so that the code between the body tags looks like this:

1<body>
2    @Html.MvcSiteMap().Menu(false, true, true)
3    @RenderBody()
4body>

We are now calling the MvcSiteMap library and telling it to output the website’s navigation on every page. The parameters specified mean that:
  • We don’t want it to start from the current node (changing this to true will break it!)
  • We want the starting node to appear in child level
  • We want to show the starting node. Setting this to false will hide the parental “Home” node
And now if we run our application, we should see the navigation laid out on every page, complete with links:
Index with navigation

News with navigation

Editing the navigation appearance

So now we’ve managed to output a simple navigation onto all pages of our website. If you want to change any styling, or how the navigation is displayed, simply alter the code in Views/Shared/DisplayTemplates/MenuHelperModel.cshtml. Lets make a simple change and add an inline style to change our bullet points from circles to squares:

1<ul>
2    @foreach (var node in Model.Nodes) {
3        <li style="list-style-type:square;">@Html.DisplayFor(m => node)
4            @if (node.Children.Any()) {
5                @Html.DisplayFor(m => node.Children)
6            }
7        li>
8    }
9ul>

You can now hit refresh in your browser without needing to re-compile. Your News index page should now look like this:
News Index Square Bullets

Breadcrumbs

We can add breadcrumbs in a similarly easy fashion. Let’s open up our _Layout.cshtml partial and edit the listing:

1<body>
2    @Html.MvcSiteMap().Menu(false, true, true)
3    <p>Start of Breadcrumbs:p>
4    @Html.MvcSiteMap().SiteMapPath()
5    @RenderBody()
6body>

Now all pages on our site will have a handy set of breadcrumb links:
News Breadcrumbs MvcSitemap
Sportsnews breadcrumbs MVCSitemap
Similarly, if we want to customise the presentation of our breadcrumbs, we need to change the Views/Shared/DisplayTemplates/SiteMapPathHelperModel.cshtml file.

Dynamic URLs / Parametered URLs

Every real site will need to employ a dynamic / Parametered URL at some point. Incorporating a dynamic URL into the MVC Sitemap is straightforward when you know how. Lets start by adding a new action to the NewsController:

1//
2//GET: News/Article/x
3public ActionResult Article(int id)
4{
5    ViewBag.id = id;
6    return View();
7}

Now lets add a view – right click anywhere within the new action and select “Add View…”. Again, just hit Add – we don’t need to change any of the options. Now update the newly created Article.cshtml file with the following:

1@{
2    ViewBag.Title = "Article";
3}
4
5<h2>Viewing Article @ViewBag.idh2>

Now lets browse to localhost:xxxx/News/Article/1234:
News Article 1234 mvcsitemap
Note that this new page does not appear anywhere in our sitemap, and that the breadcrumbs are totally empty.
In order to add the page into our navigation, we must first decide where it needs to go. I’d like this page to sit underneath the News section. So lets edit our Mvc.Sitemap file and add a Key attribute to the “News” node. This is simply to give it a unique identifier:

1<mvcSiteMapNode title="News" controller="News" action="Index" key="News">

Now we need to decorate our controller action with some attributes that tell it where to insert the action in the site’s structure. Update your Article action in your News controller:

1//
2//GET: News/Article/x
3[MvcSiteMapNode(Title = "Article", ParentKey = "News")]
4public ActionResult Article(int id)
5{
6    ViewBag.id = id;
7    return View();
8}

Now lets compile and browse to localhost:xxxx/News/Article/1234:
Article Dynamic MVCSitemap