Pages

Wednesday, June 27, 2012

How to find Length of an Enum..?

  List sqlDataType = new List();
  foreach (SqlDbType dbTypes in Enum.GetValues(typeof(SqlDbType)))
  {
         sqlDataType.Add(dbTypes.ToString());
  }
  int length = Enum.GetNames(typeof(SqlDbType)).Length;


Friday, June 15, 2012

jQuery to auto streach Textarea

 

Thursday, June 7, 2012

Manually Indexing an Entity with NHibernate Search and Lucene

NHibernate Search, which you can get in source format with SVN from the NHContrib trunk here, is an API that integrates NHibernate with the popular indexer Lucene.NET. Out of the box, it indexes the properties from your entities, the way you want it to (at the moment, only by using attributes), at insert/update/delete time, through the use of listeners. But what if you want to index an entity that already comes from the DB? Let's see how this can be done. First, out entity:
[Indexed]
public class SomeClass
{
 [DocumentId]
 public virtual Int32 Id
 {
  get;
  private set;
 }

 [Field(Index.Tokenized, Store = Store.Yes)]
 public virtual String SomeProperty
 {
  get;
  set;
 }
}
Then, use this code:
Configuration cfg = ...;
ISession session = ...;
SomeClass a = ...;

using (IFullTextSession searchSession = Search.CreateFullTextSession(session))
{
    searchSession.Index(a);
}

And, finally, query it using this:
IList items = searchSession.CreateFullTextQuery("SomeProperty:SomeValue").List();

NHibernate Pitfalls: SQL Queries and Parameter Prefix

When you execute an SQL query with NHibernate with named parameters, you would perhaps expect them to be prefixed with a symbol specific to the current DB you are accessing, for example, @ for SQL Server and : for Oracle; that is not the case. NHibernate requires that you always use it’s DB-neutral parameter prefix, :, the same that you use for HQL queries:
//for SQL queries
session.CreateSQLQuery("SELECT * FROM [Order] WHERE Id = :id").SetParameter("id", 1).List();
//for HQL queries
session.CreateQuery("from Order where id = :id").SetParameter("id", 1).List();

Differences Between NHibernate and Entity Framework

Introduction

NHibernate and Entity Framework are two of the most popular O/RM frameworks on the .NET world. Although they share some functionality, there are some aspects on which they are quite different. This post will describe this differences and will hopefully help you get started with the one you know less. Mind you, this is a personal selection of features to compare, it is by no way an exhaustive list.

History

First, a bit of history. NHibernate is an open-source project that was first ported from Java’s venerable Hibernate framework, one of the first O/RM frameworks, but nowadays it is not tied to it, for example, it has .NET specific features, and has evolved in different ways from those of its Java counterpart. Current version is 3.3, with 3.4 on the horizon. It currently targets .NET 3.5, but can be used as well in .NET 4, it only makes no use of any of its specific functionality. You can find its home page at NHForge.
Entity Framework 1 came out with .NET 3.5 and is now on its second major version, despite being version 4. Code First sits on top of it and but came separately and will also continue to be released out of line with major .NET distributions. It is currently on version 4.3.1 and version 5 will be released together with .NET Framework 4.5. All versions will target the current version of .NET, at the time of their release. Its home location is located at MSDN.

Architecture

In NHibernate, there is a separation between the Unit of Work and the configuration and model instances. You start off by creating a Configuration object, where you specify all global NHibernate settings such as the database and dialect to use, the batch sizes, the mappings, etc, then you build an ISessionFactory from it. The ISessionFactory holds model and metadata that is tied to a particular database and to the settings that came from the Configuration object, and, there will typically be only one instance of each in a process. Finally, you create instances of ISession from the ISessionFactory, which is the NHibernate representation of the Unit of Work and Identity Map. This is a lightweight object, it basically opens and closes a database connection as required and keeps track of the entities associated with it. ISession objects are cheap to create and dispose, because all of the model complexity is stored in the ISessionFactory and Configuration objects.
As for Entity Framework, the ObjectContext/DbContext holds the configuration, model and acts as the Unit of Work, holding references to all of the known entity instances. This class is therefore not lightweight as its NHibernate counterpart and it is not uncommon to see examples where an instance is cached on a field.

Mappings

Both NHibernate and Entity Framework (Code First) support the use of POCOs to represent entities, no base classes are required (or even possible, in the case of NHibernate).
As for mapping to and from the database, NHibernate supports three types of mappings:
  • XML-based, which have the advantage of not tying the entity classes to a particular O/RM; the XML files can be deployed as files on the file system or as embedded resources in an assembly;
  • Attribute-based, for keeping both the entities and database details on the same place at the expense of polluting the entity classes with NHibernate-specific attributes;
  • Strongly-typed code-based, which allows dynamic creation of the model and strongly typing it, so that if, for example, a property name changes, the mapping will also be updated.
Entity Framework can use:
  • Attribute-based (although attributes cannot express all of the available possibilities – for example, cascading);
  • Strongly-typed code mappings.

Database Support

With NHibernate you can use mostly any database you want, including:
  • SQL Server;
  • SQL Server Compact;
  • SQL Server Azure;
  • Oracle;
  • DB2;
  • PostgreSQL;
  • MySQL;
  • Sybase Adaptive Server/SQL Anywhere;
  • Firebird;
  • SQLLite;
  • Informix;
  • Any through OLE DB;
  • Any through ODBC.
Out of the box, Entity Framework only supports SQL Server, but a number of providers exist, both free and commercial, for some of the most used databases, such as Oracle and MySQL. See a list here.

Inheritance Strategies

Both NHibernate and Entity Framework support the three canonical inheritance strategies: Table Per Type Hierarchy (Single Table Inheritance), Table Per Type (Class Table Inheritance) and Table Per Concrete Type (Concrete Table Inheritance).

Associations

Regarding associations, both support one to one, one to many and many to many. However, NHibernate offers far more collection types:
  • Bags of entities or values: unordered, possibly with duplicates;
  • Lists of entities or values: ordered, indexed by a number column;
  • Maps of entities or values: indexed by either an entity or any value;
  • Sets of entities or values: unordered, no duplicates;
  • Arrays of entities or values: indexed, immutable.

Querying

NHibernate exposes several querying APIs:
  • LINQ is probably the most used nowadays, and really does not need to be introduced;
  • Hibernate Query Language (HQL) is a database-agnostic, object-oriented SQL-alike language that exists since NHibernate’s creation and still offers the most advanced querying possibilities; well suited for dynamic queries, even if using string concatenation;
  • Criteria API is an implementation of the Query Object pattern where you create a semi-abstract conceptual representation of the query you wish to execute by means of a class model; also a good choice for dynamic querying;
  • Query Over offers a similar API to Criteria, but using strongly-typed LINQ expressions instead of strings; for this, although more refactor-friendlier that Criteria, it is also less suited for dynamic queries;
  • SQL, including stored procedures, can also be used;
  • Integration with Lucene.NET indexer is available.
As for Entity Framework:
  • LINQ to Entities is fully supported, and its implementation is considered very complete; it is the API of choice for most developers;
  • Entity-SQL, HQL’s counterpart, is also an object-oriented, database-independent querying language that can be used for dynamic queries;
  • SQL, of course, is also supported.

Caching

Both NHibernate and Entity Framework, of course, feature first-level cache. NHibernate also supports a second-level cache, that can be used among multiple ISessionFactorys, even in different processes/machines:
Out of the box, Entity Framework does not have any second-level cache mechanism, however, there are some public samples that show how we can add this.

ID Generators

NHibernate supports different ID generation strategies, coming from the database and otherwise:
  • Identity (for SQL Server, MySQL, and databases who support identity columns);
  • Sequence (for Oracle, PostgreSQL, and others who support sequences);
  • Trigger-based;
  • HiLo;
  • Sequence HiLo (for databases that support sequences);
  • Several GUID flavors, both in GUID as well as in string format;
  • Increment (for single-user uses);
  • Assigned (must know what you’re doing);
  • Sequence-style (either uses an actual sequence or a single-column table);
  • Table of ids;
  • Pooled (similar to HiLo but stores high values in a table);
  • Native (uses whatever mechanism the current database supports, identity or sequence).
Entity Framework only supports:
  • Identity generation;
  • GUIDs;
  • Assigned values.

Properties

NHibernate supports properties of entity types (one to one or many to one), collections (one to many or many to many) as well as scalars and enumerations. It offers a mechanism for having complex property types generated from the database, which even include support for querying. It also supports properties originated from SQL formulas.
Entity Framework only supports scalars, entity types and collections. Enumerations support will come in the next version.

Events and Interception

NHibernate has a very rich event model, that exposes more than 20 events, either for synchronous pre-execution or asynchronous post-execution, including:
  • Pre/Post-Load;
  • Pre/Post-Delete;
  • Pre/Post-Insert;
  • Pre/Post-Update;
  • Pre/Post-Flush.
It also features interception of class instancing and SQL generation.
As for Entity Framework, only two events exist:

Tracking Changes

For NHibernate as well as Entity Framework, all changes are tracked by their respective Unit of Work implementation. Entities can be attached and detached to it, Entity Framework does, however, also support self-tracking entities.

Optimistic Concurrency Control

NHibernate supports all of the imaginable scenarios:
  • SQL Server’s ROWVERSION;
  • Oracle’s ORA_ROWSCN;
  • A column containing date and time;
  • A column containing a version number;
  • All/dirty columns comparison.
Entity Framework is more focused on Entity Framework, so it only supports:
  • SQL Server’s ROWVERSION;
  • Comparing all/some columns.

Batching

NHibernate has full support for insertion batching, but only if the ID generator in use is not database-based (for example, it cannot be used with Identity), whereas Entity Framework has no batching at all.

Cascading

Both support cascading for collections and associations: when an entity is deleted, their conceptual children are also deleted. NHibernate also offers the possibility to set the foreign key column on children to NULL instead of removing them.

Flushing Changes

NHibernate’s ISession has a FlushMode property that can have the following values:
  • Auto: changes are sent to the database when necessary, for example, if there are dirty instances of an entity type, and a query is performed against this entity type, or if the ISession is being disposed;
  • Commit: changes are sent when committing the current transaction;
  • Never: changes are only sent when explicitly calling Flush().
As for Entity Framework, changes have to be explicitly sent through a call to AcceptAllChanges()/SaveChanges().

Lazy Loading

NHibernate supports lazy loading for
  • Associated entities (one to one, many to one);
  • Collections (one to many, many to many);
  • Scalar properties (thing of BLOBs or CLOBs).
Entity Framework only supports lazy loading for:
  • Associated entities;
  • Collections.

Generating and Updating the Database

Both NHibernate and Entity Framework Code First (with the Migrations API) allow creating the database model from the mapping and updating it if the mapping changes.

Extensibility

As you can guess, NHibernate is far more extensible than Entity Framework. Basically, everything can be extended, from ID generation, to LINQ to SQL transformation, HQL native SQL support, custom column types, custom association collections, SQL generation, supported databases, etc. With Entity Framework your options are more limited, at least, because practically no information exists as to what can be extended/changed. It features a provider model that can be extended to support any database.

Integration With Other Microsoft APIs and Tools

When it comes to integration with Microsoft technologies, it will come as no surprise that Entity Framework offers the best support. For example, the following technologies are fully supported:

Documentation

This is another point where Entity Framework is superior: NHibernate lacks, for starters, an up to date API reference synchronized with its current version. It does have a community mailing list, blogs and wikis, although not much used. Entity Framework has a number of resources on MSDN and, of course, several forums and discussion groups exist.

Conclusion

Like I said, this is a personal list. I may come as a surprise to some that Entity Framework is so behind NHibernate in so many aspects, but it is true that NHibernate is much older and, due to its open-source nature, is not tied to product-specific timeframes and can thus evolve much more rapidly. I do like both, and I chose whichever is best for the job I have at hands. I am looking forward to the changes in EF5 which will add significant value to an already interesting product.

How to load partial view dynamically in ASP.NET MVC using JQuery

Below is the simple implementation which works with custom view engine and view context.
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult LoadTopDestinations()
{
    return PartialView("TopDestinations");
}
And this is how i call the controller from the javascript using jquery post.
function TopDestinationClick() {
    proxy.invoke("/Home/LoadTopDestinations", "", TopDestinationCallback, OnError);

}
And the Javascript is
function serviceProxy(serviceUrl)
{
    var _I = this;
    this.serviceUrl = serviceUrl;
    
    // *** Call a wrapped object
    this.invoke = function(method, data, callback, error) {
        // *** The service endpoint URL        
        var url = _I.serviceUrl + method;
        //alert(url);
        $.ajax({
            url: url,
            data: '',
            type: "GET",
            contentType: "html",
            timeout: 10000,
            success: callback,
            error: OnError
        });
    }
}

// *** Create a static instance
var serviceUrl = "";
var proxy = new serviceProxy(serviceUrl);
And the callback event, just use jquery.html() method to load the partial view result.

Wednesday, June 6, 2012

CSS Class to Glow Textbox on Focus


input {
    border: 1px solid black;
    margin-top: 150px;
    margin-left: 100px;
    
    height: 45px;
    width: 300px;
    padding: 5px;
    border-radius: 5px;
    
    font-size: 30px;
    
    transition:.2s linear;
    -webkit-transition:.2s linear;
    -moz-transition:.2s linear;
}

input:focus {
    outline: none;
    box-shadow: 0px 0px 7px #61C5FA;
    border-color: #61C5FA;
}

Check The Demo Below:

Saturday, June 2, 2012

Dynamic Filtering With LINQ

public enum MatchType
{
 StartsWith = 0,

 EndsWith = 1,

 Contains = 2,

 Equals = 3
}

public static List Filter(IEnumerable enumerable, String propertyName, String filter, MatchType matchType)
{
 return (Filter(enumerable, typeof(T), propertyName, filter, matchType) as List);
}

public static IList Filter(IEnumerable enumerable, Type elementType, String propertyName, String filter, MatchType matchType)
{
 MethodInfo asQueryableMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m => (m.Name == "AsQueryable") && (m.ContainsGenericParameters == false)).Single();
 IQueryable query = (enumerable is IQueryable) ? (enumerable as IQueryable) : asQueryableMethod.Invoke(null, new Object [] { enumerable }) as IQueryable;
 MethodInfo whereMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m => m.Name == "Where").ToArray() [ 0 ].MakeGenericMethod(elementType);

 MethodInfo matchMethod = typeof(String).GetMethod
 (
  (matchType == MatchType.StartsWith) ?
   "StartsWith" :
   (matchType == MatchType.EndsWith) ?
    "EndsWith" :
    (matchType == MatchType.Contains) ?
     "Contains" : 
      "Equals",
  new Type [] { typeof(String) }
 );

 PropertyInfo displayProperty = elementType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
 MemberExpression member = Expression.MakeMemberAccess(Expression.Parameter(elementType, "n"), displayProperty);
 MethodCallExpression call = Expression.Call(member, matchMethod, Expression.Constant(filter));
 LambdaExpression where = Expression.Lambda(call, member.Expression as ParameterExpression);

 query = whereMethod.Invoke(null, new Object [] { query, where }) as IQueryable;

 MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(elementType);
 IList list = toListMethod.Invoke(null, new Object [] { query }) as IList;

 return (list);
}

var list = new [] { new { A = "aa" }, new { A = "aabb" }, new { A = "ccaa" }, new { A = "ddaadd" } };

var contains = Filter(list, "A", "aa", MatchType.Contains);
var endsWith = Filter(list, "A", "aa", MatchType.EndsWith);
var startsWith = Filter(list, "A", "aa", MatchType.StartsWith);
var equals = Filter(list, "A", "aa", MatchType.Equals);


Finding Control Inside Grid View on Button Click

protected void Button1_Click(object sender, EventArgs e)
{
    // Iterates through the rows of the GridView control
    foreach (GridViewRow row in GridView1.Rows)
    {
        // Selects the text from the TextBox
        // which is inside the GridView control
        string textBoxText = _
          ((TextBox)row.FindControl("TextBox1")).Text;
        Response.Write(textBoxText);
        // Selects the text from the DropDownList
        // which is inside the GridView control
        string dropDownListText = ((DropDownList)
           row.FindControl("DropDownList1")).SelectedItem.Value;
        Response.Write(dropDownListText);
        // Selects items from the ListBox
        // which is inside the GridView control
        ListBox myListBox = (ListBox)row.FindControl("ListBox1");

        foreach(ListItem selectedItem in myListBox.Items)
        {
            // Checks if the item in the ListBox is selected or not
            if (selectedItem.Selected)
            {
                // Print the value of the item if its selected
                Response.Write(selectedItem.Value);
            }
        }
    }

to get dictionary object values one by one?

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary dictionary =
            new Dictionary();
        dictionary.Add("cat", 2);
        dictionary.Add("dog", 1);
        dictionary.Add("llama", 0);
        dictionary.Add("iguana", -1);
    }
}

If you want look up

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary dictionary = new Dictionary();
        dictionary.Add("apple", 1);
        dictionary.Add("windows", 5);

        // See whether Dictionary contains this string.
        if (dictionary.ContainsKey("apple"))
        {
            int value = dictionary["apple"];
            Console.WriteLine(value);
        }

        // See whether Dictionary contains this string.
        if (!dictionary.ContainsKey("acorn"))
        {
            Console.WriteLine(false);
        }
    }
}


using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Example Dictionary again
        Dictionary d = new Dictionary()
        {
            {"cat", 2},
            {"dog", 1},
            {"llama", 0},
            {"iguana", -1}
        };
        // Loop over pairs with foreach
        foreach (KeyValuePair pair in d)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
        // Use var keyword to enumerate dictionary
        foreach (var pair in d)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
    }
}

Begin with MVC

Introduction

This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.

MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.

Inside MVC Architecture

The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?

  1. MVC model is basically a C# or VB.NET class
  2. A model is accessible by both controller and view
  3. A model can be used to pass data from Controller to view
  4. A view can use model to display data in page.

What is a View?

  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method
What is a Controller?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. Controller uses ViewData to pass any data to view

MVC File Structure & File Naming Standards

MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
  • Root [directory]
    • Controller [directory]
      • Controller CS files
    • Models [directory]
      • Model CS files
    • Views [directory]
      • View aspx/ascx files
    • Global.asax
    • Web.config

ASP.NET MVC Execution Life Cycle

Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:

Browser Request (Step 1)

Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/

Job of Global.asax – MVC routing (Step 2)

The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [xyz.com]/home/index/:
  • Controller = home
  • Action = index()
  • ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string

Controller and Action methods (Step 3)

MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.

Call to View (Step 4)

Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.

Call ajax modalpopup extender from javascript






$find('MyMPE').show(); //To Show

$find('MyMPE').hide(); //To Hide

Force browser to download the file instead of opening it in the browser

Sometimes files such as images, videos, textfiles, XML files etc. are getting open in the browser window, when we give the download link directly to the file. To avoid that behavior and to force browser to download the file to the user’s computer when user clicks on the download link/button, we can use the below code on the button click event.
FileInfo fileInfo = new FileInfo("file_path_here");
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.WriteFile(fileInfo.FullName);
Response.End();