Friday, 28 December 2012

Code First Approach For New Database

I was trying my hands on Entity-framework. As i was completely blank on this areas, I Googled about it and found some interesting links. This link helped me to have some conceptual understanding( Though i have to read it again a couple of times to get what it actually means. )

Later, to have some practical know-how, i followed this link. I found the link on this page very useful to begin with. There are various approaches to work on. Lets begin with Code First Approach for New Database -

The page is itself the best place to follow the approach. No doubt , you won't find better details here. So whats the use of this page. I got stuck in a couple of places. (as was with my first HelloWorld program  )
  1. I was using VS2010.The tutorial do not mention to place the connection string anywhere in the code. Obviously, it was not necessary to mention it but as i ran the program with exactly the same code, this exception popped up  -
    "The provider did not return a ProviderManifestToken string."
     When i checked the details of this exception, it found that it was an error related to database connection. But where should i mention these details. First, i mentioned a connection string in the app.config.
     <add name="BlogContext" 
    connectionString="Data Source=ZZZ;User ID=XXX;Password=XXX;Initial Catalog=YYY;Persist Security Info=true" 
    providerName="System.Data.SqlClient" />

     Then i update the BlogContext class by supplying it a constructor. 
     public BlogContext()
                : base("Name=BlogContext")
            {
    
            }

    The next time i ran it. It created the tables in the DB defined in the connection string. 
  2. When we change the POCO Classes in order to change the DB. We won't get the error till the code actually hits the DB. The error indicates us to use Data Migration tool to get the changes to the Database.
    To do this, Open the Package Manager Console(Tools->Library Package Manager->Package Manager Console), And Fire the command -
      Enable-Migration
    Tip- To use intellisense, hit [tab], not [Ctrl+Space]. It's console not editor.
    Then run the command below after you have changed the classes -
    Add-Migration AddChange
    Here, AddChange  is the Name of migration which could be anything(Name it properly so that you can easily recall the changes). A file is created with the migration name where you can see all the upgrade/downgrade related changes.
    Finally, run the Update-Database command to migrate the Changes to DB.
      
Thanks,
S. Shafique
Fok at RnD Team member

Wednesday, 26 December 2012

Using view as both View and Partial View


A couple of days back, we were in a situation where we have to display the same view (say "AddTicket") as
  • View in some cases(new tab) and
  • as partial view in other(in modal pop-up).
To accomplish that, there might be various approaches but two thoughts came in my mind-
  • Create separate view and partial view (which was discarded as we would have to write the same HTML layout twice).
  • Create a Partial View and use it as View wherever and whenever required.

To do that, first create a partial view with Layout property set to "null".(Obviously)

public ActionResult AddTicket()
        {
            /*
             We are using the same as View and Partial View here.
             */
            if (Request.IsAjaxRequest()|| ControllerContext.IsChildAction)
            {
                return PartialView("PartialViewName");
            }
            else
            {

               //Set the Layout for the partial view
                return View("PartialViewName","~/Views/Shared/_Layout.cshtml");
            }
        }

Needless to say, i am expecting there should be a better approach than this. Looking forward for the suggestions.

Thanks,
S. Shafique
Fok at RnD Team member

Friday, 21 December 2012

Create ComplexType If Stored procedure returns multiple Select statements in Entity Framework



Guys, Today during our daily development we faced another big problem.
We are using Ef4(Entity Framework) in our project using EDM(Entity Data Model) approach .
The problem is that we have one stored procedure which returns two select statement in the output
For ex – Select * from emp;
                Select * from library;
1.In function import the complex type will only hold one type of object like either emp or library , so we can’t able to show result of the stored procedure .
2.If we manually execute Stored procedure query  then also it will return the result of first select.
Like this ->
var query = _cxt.ExecuteStoreQuery<TestModel>("exec testselect");

And the drawback is that EF4 is not supporting multiple select in edm.
It is available in EF5 by nugget.

Now we have come up with the result.
Here we go.

1.First we have downloaded extension for Entity Framework

2. Include that project in your project.
3.Create new class file and Create a partial class in the same name of your Entities Class
In my case
       public partial class TestDatabaseEntities : ObjectContext

Now suppose my stored procedure return as an output like this.

       Select * from tblState;
       Select * from tblCountry;
Include that extension in that file.

4.As there is two type of object returning from SP tblState and tblCountry.
So create two private readonly variable of same type.
Like this

       private static readonly Materializer<tblState> s_StateMaterializer = new Materializer<tblState>(r =>
            new tblState
            {
                id = r.Field<int>("id"),
                StateName = r.Field<string>("StateName"),
            });

        private static readonly Materializer<tblCountry> s_CountryMaterializer = new Materializer<tblCountry>(r =>
            new tblCountry
            {
                countryId = r.Field<int>("countryId"),
                countryName = r.Field<string>("countryName"),
                isActive = r.Field<bool>("isActive")

            });

5.Now Comes the Method which will return multiple record Set.

public void GetMultiple()
        {
            DbCommand command = this.CreateStoreCommand("TestSelect", CommandType.StoredProcedure); //Create the command which will call the sp.
            List<tblCountry> country;
            List<tblState> state;

            using (command.Connection.CreateConnectionScope()) //Opening Connetion
            using (DbDataReader reader = command.ExecuteReader()) // Getting Data on Data reader
            {
                state = s_StateMaterializer
                        .Materialize(reader)
                        .Bind(this.tblStates)
                        .ToList<tblState>();  //Extracting the State from the output

                if (reader.NextResult())
                {
                    country = s_CountryMaterializer
                        .Materialize(reader)
                        .Bind(this.tblCountries)
                        .ToList<tblCountry>();  //Extracting the Country from the output
                }
               
            }

        }
In my case it is void type you can change acc to your requirement.
That’s all now call this method and see the output.

Thanks
Morpheus
Fokat RND Team Member

Thursday, 20 December 2012

Custom or User define Attribute in MVC


Hello frnd ,
I am writing this blog for a type of problem which we face during development in mvc-3 or mvc4 .
For a registered user we have to check Session  in every action of every controller ,which is very tedious.
Like this ,
                If (YourSessionObject != null)
{
                //your code goes here.
}

It is very tedious.
So Here is the solution.
You all know about Mvc Attributes. So we can make one attribute which will check our session object and if found null then return back to login page.
So the question is where to write this class, The class will be written in App_Start .
The class should implement ActionFilterAttribute.

In that class you have to over ride OnActionExecuting method.
Here is the code below

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            CurrentCustomer objCurrentCustomer = new CurrentCustomer(); //This is session object
            objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
            if (objCurrentCustomer == null)
            {
                // check if a new session id was generated
                filterContext.Result = new RedirectResult("~/Users/Login"); // if null then return back to login page .
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }
That’s all just include App_Start in controller and just add [SessionExpireFilter] attribute in your action method.
This will check session in every action .

Kendo Tab Control

Using Tab control has always been an easy task to accomplish. But due to lack of sufficient documentation(IMO) of Kendo Tabstrip for MVC, it took me a while to get what i was looking for.

To begin with -
You can follow the basic documentation link of Kendo.
For everything else that was not exactly there in doc -
  1. Display image with absolute URL -  Simply use
    .ImageUrl("http://Absolute/path/of/the/image.")
  2. Display content from Partial View - I found a couple of ways for that. 
    1- .Content(@<text> @(Html.Partial("_PartialView1"))</text>);
     
    2- .Content(Html.Partial("_PartialView2").ToHtmlString());
    
    3- .Content(@<text> @(Html.Action("View3"))</text>);
  3. Change the animation from "expand" to "toggle" - 
  4. .Animation(animation =>
        {
            animation.Enable(true);
            animation.Open(config =>
            {
                config.Duration(AnimationDuration.Fast);
                config.Fade(FadeDirection.In);
            });
        })
    
  5.  Difference in LoadContentFrom  and Content in case someone is confused. 
     
Thanks,
S. Shafique
Fok at RnD Team member

Hide specify column in Kendo grid

Some of my Coolidge tried to hide one specify column in kendo grid table.

Finally I got the correct solution for the same.

Assuming #grid is already bound as the kendo grid, you can use the hide Column function

Your bound column is like
{ 
    field: "CreatedDate",
    title: "Create Date",

}
--------------------------------
Script for hiding the column

var grid = $("#grid").data("kendoGrid");
grid.hideColumn("CreatedDate");

or 
$("#grid").data("kendoGrid").hideColumn("CreatedDate");

you can supply the bound field or column index in hideColumn method

This will hide both the header and data column.There is also a showColumn
function when you need to show the column as well.



Thanks
V. K. Rajput
Fokat RnD Team member
 

Partial View Rendering methods

I've noticed there are several ways to use Views and PartialViews:

RenderAction, RenderPartial, and "return PartialView"

RenderAction when placed inside HTML, will simply call an Action and Render the View returned (the View returned can be partial view or view?)

RenderPartial will simply retrieve the contents of a View without executing any Controller action.

return View() returns the view with a Layout enabled so you get full HTML page with <html> and <body> tags. return PartialView() on the other hand disables the Layout and you get only the HTML fragment contained in this view.


Thanks
V. K. Rajput
Fokat RnD Team member