Saturday, 20 December 2014

MVC in ASP.Net,C# : Insert and Validate your program

Standard
Introduction:

Here in this post I will show you how to make a form  and how to save the inputted value of the form into database  and how to validate your textbox before saving the data using MVC4.0 using Razor view engine.

So first create or choose an existing database and create a table named MVC_Details. Give any name to table .

Now start a MVC project and choose Razor as a view engine. 

Create a Class in Model Folder whose name is ColumnSetGet.cs (give any name according to your project).In this class you just provide all the column name with set and get method.This class will reflect the table columns.


After creation of set and get method in a class , now you have to create one another class in Model folder whose name is InsertMVCModel.cs ( give any name according to you ). In this class you jsut write the SQL Query to Insert, Update ,Delete aur any SQL Query to interact with Database.


Now do some coding work in Controller .

So create a Controller class within the Controller folder named InsertController( give any name according to you ).Add the namespace using PracticeMVC.Models; [ PracticeMVC is my project name and Model is a Model folder name, give your project name.model in controller class ]  for accessing the model folder into your Controller class. If you put the classes in any other folder add that folder name as namespace.

I took InsertView as the ActionMethod, so there will be two Action method named InsertView. The first one for just showing the form and second one is for getting the value after submit button click. We don't need to write any code within the first method, But in the second method write down the code.

using PracticeMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PracticeMVC.Controllers
{
    public class InsertController : Controller
    {
        public ActionResult InsertView()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult InsertView(FormCollection frm)
        {
                ColumnSetGet csg = new ColumnSetGet();
        
                if (string.IsNullOrEmpty(frm["Name"]))
                {
                    ModelState.AddModelError("Name", "Enter Your Name");
                    if (string.IsNullOrEmpty(frm["Msg"]))
                    {
                        ModelState.AddModelError("Msg", "Enter Your Message");
                    }
                }
                else if (ModelState.IsValid)
                {
                    csg.Name = frm["Name"];
                    csg.Msg = frm["Msg"];

                    InsertMVCModel inm = new InsertMVCModel();
                    if (inm.AddDetails(csg) == 1)
                    {
                        ViewBag.Status = "Success!!";
                    }
                }
              
            return View("InsertView");
        }
    }
}


Now create the View part. To create the View right_click on the Action Method and keep the name as it is. Just one change you have to do. Check the Create Strongly typed view and choose ColumnSetGet as your Modal class. Now click on the Add  button to make your View.

In the view we have to make form first. To create a form we have to use Html.BeginForm() and within that you have to put labels, textboxes and buttons.

So lets create our own form.


Now your form is ready to Insert data into Database .

Now follow the some more Images below to know how to Validate your Textbox fields before Insertion
In Controller Class you have to call  the method IsValid with refrence variable ModelState in if else condition like ..

//  If TextBox is not Empty
if(ModelState.IsValid)   
{
       // your code;
}

// If TextBox is Empty
else if(string.IsNullOrEmpty(frm["Name"]))
{
      ModelState.AddModelError("Name", "Enter Your Name");
}
for more see the Image below....
Now in View Page add One Attribute @Html.ValidationSummary()

Now  Your Form is ready with Insertion SQL Query with Textbox Validation .Run your program

Friday, 19 December 2014

MVC in ASP.Net,C# [PART-2]

Standard
Avoid to write Long URL in Browser

In this article all screen shots are based on " How to avoid to write long URL in Browser to Run your MVC Project ".

First create your MVC Project as i discussed in my Previous Artical. After createing your  MVC Web Application project with default files and folders as per the Template Selection.

Now Visual Studio created our project in place and the solution file looks like , 

In Solution Explorer there is a folder name is App_Start.In this folder there is a .cs file whose name is RouteConfig.cs open this file and configure the Setting .



By Default RouteConfig.cs file have default setting like this..


Now you have to Configure RouteConfig.cs file First Copy and Past the default code and configure the code according to your Controller Name, View Name and URL .
If you want to run your project after giving any URL like /HOME then......follow the Image below.

1. In name tag give any name but it must be UNIQUE with other.
2. In url tag give any name which you want give in browser after slash"/" like ----> url="Home"
     now after run your project give URL like localhost:39876/Home press enter

3. In defaults tag give Controller name and View name.


Suppose if you dont want to give any extra URL like /Home ..etc as i shown above.
then there is a tag whose name is url left them blank like  url="" only and do all the configuration same as show above images.

Only this much you have to do according to your requirement.Now do your configuration and feel free to run your project without giving url

Monday, 8 December 2014

MVC in ASP.Net,C#

Standard

Introduction     

ASP.NET MVC 4 is a framework for building scalable, standards-based web applicationsusing well-established design patterns and the power of ASP.NET and the .NET Framework.In this article I will give an introduction to ASP.NET MVC 4 from a beginner’s perspective.
This article is meant for all kind of beginner users who wanted to get started with ASP.NET MVC 4. I have included a small comparison between ASP.NET MVC and ASP.NET Web forms for those who have already explored ASP.NET Web forms 
Currently ASP>NET MVC 4 is supported in Visual Studio 2010 and Visual Studio 2012, previous versions of Visual Studio does not support ASP.NET MVC 4 as of now. If you don’t have ASP.NET MVC 4 in your box then install MVC 4 for Visual Studio 2010 or else use Visual Studio 2012 to get started with this article, You may refer Setup Environment article for more installation details/procedures. 

What is ASP.NET MVC?  

ASP.NET supports three different development models named Web Pages, MVC and Web Forms.


ASP.NET MVC is a web application development framework built on top of Microsoft’s .NET Framework. ASP.NET Web Form was a replacement for Microsoft’s Active Server Pages (ASP) but ASP.NET MVC is not a replacement for ASP.NET Web Forms and it’s just an alternate way of making an ASP.NET website.
ASP.NET MVC is open source!- In March 2012, Scott Guthrie announced on his blog that Microsoft had released part of their web stack (including ASP.NET MVC, Razor and Web API) under an open source license (Apache License 2.0).

Why MVC?  

ASP.NET MVC helps to reduce the complexity of the web application by dividing an application into three layers, Model, View and Controller. This separation (loose coupling) helps in some long term benefits like isolation of components while development and also this separation provides better support for test-driven development (TDD). ASP.NET MVC web site are good in performance and also easy to maintain. 

MVC Release History   

The Current Version of ASP.NET MVC is 4 and it was released on 15th Aug 2012. ASP.NET MVC 4 is packaged with Visual Studio 2012 and MVC 4 can be installed for Visual Studio 2010. Below I have mentioned the release history of ASP.NET MVC.            

Date Version  
10 Dec 07 ASP.NET MVC CTP 
13 Mar 09  ASP.NET MVC 1.0 
16 Dec 09 ASP.NET MVC 2 RC
04 Feb 10 ASP.NET MVC 2 RC 2
10 Mar 10 ASP.NET MVC 2 
06 Oct 10ASP.NET MVC 3 Beta 
09 Nov 10ASP.NET MVC 3 RC
10 Dec 10ASP.NET MVC 3 RC 2
13 Jan 11ASP.NET MVC 3
20 Sep 11  ASP.NET MVC 4 Developer Preview 
15 Feb 12ASP.NET MVC 4 Beta
31 May 12  ASP.NET MVC 4 RC
15 Aug 12 ASP.NET MVC 4 
In this article we are discussing more about the latest version of MVC, that's MVC 4. Read more from Wikipedia on MVC Release History.  

MVC Architecture  
The Model-View-Controller (MVC) pattern is an architectural design principle that separates the application components of a Web application into three layers. This separation gives you more control over the individual parts of the application, which lets you more easily develop, modify, and test them.


Model contains and exposes the properties and application logic  In a better way we can say that The model represents core business logic and data. In the ePhoneBook Sample the 'PhoneBookModel' class represents the properties of a “Phone Book” in the application and may expose properties such as First Name,  Last Name and Mobile Number etc and also it may expose methods.    
The View is responsible for creating the response HTML or any responses back to the browser like pdf, html or excel etc. In other way we can sat that the view is responsible for transforming a model or models into a visual representation.  
Controller is responsible for processing user inputs from view and give responses back to the view. It means that the controller decides the action and performs the tasks/logic based on the parameters.Controller acts as the coordinator between the view and the model. 

Creating an ASP.NET MVC Application

In this article all screen shots are based out of Visual Studio 2012 but If you are using Visual Studio 2010 then you will find similar UIs there too.To Create a new MVC 4 application we need to click on 'New Project' menu. 'New Project' menu can be accessed from the start page itself or File->New->Project menu. 
The below given image shows how to create 
1. New Project from start page.  


2. Creating New Project from File->New->Project.
3.Clicking on New Project menu will show a popup for selecting the required type of Project from      the installed templates list. We can create Windows Application or normal ASP.NET Web                  Application etc using this popup but now we are more interested to create a new ASP.NET MVC 4    Web Application from scratch. 
Give a proper name for this new MVC 4 application and click 'OK' button. I have given 'HelloWorld' name (or any other Name,what you want to give ) as I'm going to use this project for all my MVC 4 series.  
When you click 'OK', you’ll be presented with another dialog with Project Templates 


Select appropriate Project Template (discussed in another section), View Engine and also if you want you can opt for creating a Test Project for this application. You can create a test project later also if you don't want to do right now. I have selected the Internet Application with Razor View Engine. 

View Engine are responsible for rendering the HTML from your views to the browser. The view engine template will have different syntax for implementation. Currently there are few number of view engines available for MVC and the top four view engines are Razor, traditional ASPX, Spark and NHaml. I have written another article on comparison of different view engines.  
Razor is the preferred View Engine for MVC, ASPX View Engine is the legacy View Engine and this option is there for backward compatibility. 


Once you click 'OK' after selecting the appropriate project template Visual Studio will create a MVC Web Application project with default files and folders as per the Template Selection.

Now Visual Studio created our project in place and the solution file looks like , 


Now Expend Controller Folder,Views Folder see some default folder is created.Just Delete all the Default files from Controller Folder and Delete all the Default files from Views Folder( only files, do not delete Web.config file ).Model folder already empty

Now Right_Click on Controller Folder and Add ---> Controller

Now change the name of DefaultController to "HomeController" ( or give any name ).I use "HomeController". But do not delete Controller word bymistake Only delete Defalut word and give your file name












Right_Click on Views folder and create New Folder .Give the folder name,name of your Controller name which you created in Controller Folder.Now


Now Right_Click on newlly created Folder on Views folder ---> Add ---> View


Give the View Name and Uncheck the option "Use a layout and mastre page:". This option is by Default checked.



Click on MyHomePage.cs.Html page which is created in Views --> New folder 
and write some Message what you want to display in side the <div tag >.



Now Goto Controller folder and Click on HomeController.cs file. and write the code to call the Views page
give the Viwes page name in side the return View(); no need to write extension of the file like.....
return View("MyHomePage.csHtml"). Only write return View("MyHomePage");


Now press F5 and run your Program.

If it will show an Error Message just Run Your progarm and go to URL  and type /Home/GotoHome
like....  localhost: port number/Home/GotoHome   press enter
           localhost:39454/Home/GotoHome prss enter
 now it will show your Message

Sunday, 7 December 2014

JAVA : HOW CAN WE SEE, HOW MANY OBJECTS ARE CREATED FOR CLASSES AT MEMORY LEVEL(AT HEAP LEVEL)

Standard
In this post we will see how can we see how many objects are created for classes at memory level. means that how many objects are created in heap we can see by using java visual machine this is a .exe file available in jdk ,with in bin folder.
see path : C:\Program Files\Java\jdk1.7.0_71\bin 

By double cliking on this .exe file we can open this tool so that we can analyze how many objects were created  in heap for classes, before going to see first of all let me create one java sample program so that we can see how many objects are created for that program. so let's go.


Program:-
------------
  1. package com.system;  
  2.   
  3.    
  4.  class Test{  
  5.     
  6.   public void m1(){  
  7.    System.out.println("We are in Test class");  
  8.   }  
  9.  }  
  10.    
  11.  class Team extends Test{  
  12.     
  13.   public void m1(){  
  14.    System.out.println("We are in Team class");  
  15.   }  
  16.     
  17.  }  
  18. public class TestMemoryLevel {  
  19.   
  20.  public static void main(String[] args) throws InterruptedException {  
  21.   // TODO Auto-generated method stub  
  22.   
  23.   Team t =new Team();  
  24.   t.m1();  
  25.   Test t1 =new Test();  
  26.   t1.m1();  
  27.   TestMemoryLevel t2=new TestMemoryLevel();  
  28.   Thread.sleep(10*500*40);  
  29.     
  30.  }  
  31.   
  32. }  

In the above program  you can observe that i have created three classes . In main class that is TestMemoryLevel i have created objects for  Three classes i.e for Test,Team,TestMemoryLevel from that you can say how many objects are created for these classes easily.Answer is 3 for each class we are creating one object.But our aim is to see is  really three objects are created for three classes or not in heap level i.e is in memory level.SO for proof let's go.In our program we are  calling sleep method of Thread class , so that our program will have some process ID , so that we can analyse easily for better understanding  i will explain step wise with screenshots.

1) compile and run the program.

2) Then go to C:\Program Files\Java\jdk1.7.0_71\bin folder you can see jvisualvm.exe double click on this.



3) After that you can observe that one process ID coming with package name see below. then double click on that.


4) After that you will see below window beside of above window. then click on "monitor"  button


5) After clicking on monitor button you will see some graphical charts.On the top of the right side corner you can see "Heap Dump" button


6) click on that Heap Dump button you will see below window , there you can see classesoption click on that. there you will see lot of classes . search with your  package name, you can see search option below of the window. Finally you will see how many objects were created with memory level proof  for your classes. That's it guys if you have any doubts please leave comment below i will clarify as soon as possible.