Tuesday, February 24, 2015

Access Model State Property within the View of ASP.NET MVC 4

Hi Folks,

 

Dotnetpiper

If you want to access the ModelState property in the View , you can use the ModelState in your Razor View as depicted below in image:

 

This is the source code as shown below: 

  1: @model IEnumerable<MVCSample.Models.EmpRegistration>  
  2: @{  
  3:     ViewBag.Title = "Verify";  
  4: 
  5: if (@ViewContext.ViewData.ModelState.IsValid)  
  6:     {  
  7:         ViewBag.Title = "Verify";  
  8: 
  9: if (TempData["EmployeeRegistration"] != null)  
 10:         {  
 11:             var tempDataEmployeeRegistration = TempData["EmployeeRegistration"];  
 12:         }  
 13:     }  
 14: }  
 15: 
Thanks 

To know more MVC and WebApi Kindly go through with these links

MVC Articles & WCF and WebAPI


Thanks.
Enjoy coding and reading.


Why Constructor can't be declared Virtually? Why Destructor can't be Overloaded?

A ChildAction method is an action method thought its accessible from the View only, if you invoked this action via an URL then it prompts

This is what i found something very interesting about Constructor and Destructor.

Constructor can't be virtual, because constructor is an entity which initializes V-table(V-table contains address of all the virtual functions of class). So if we declare constructors as virtual then who will initialize V-table for this constructor.

Destructor can not be overloaded simply becoz we cant provide argument to a destructor and also its going to release the memory when an object goes out of scope.

 

I hope it will help you somewhere down the line.
Keep coding and smiling Smile

To know moew MVC and WebApi Kindly go through with these links

Learn MVC & WCF and WebAPI

Monday, February 16, 2015

WebApi Hosting in Internet Information Server (IIS 7.5)

The Web API is a platform to develop HTTP / HTTPS based services that can be used by native applications like on smartphones, tablets and browsers. The WebApi is a core part of ASP.NET and provides ways to create Restful services and can be used by any application that can understand HTTP communications.

Implementation of Restful operations using ASP.NET Web API

Before proceeding I recommend you go through with this link:
This article will cover the hosting of a WebApi in IIS using a sample demo. I hope you have gone through with the link above and now you at least understand the execution of WebApi. In this article we'll host the WebApi in IIS and execute all the CRUD operations step-by-step.
WebApi
Step 1
Build your solution in release mode.
To build the solution, kindly download the sample application from the link Restful CRUD Operations in WebApi Using ADO.NET Objects and SQL Server and start working further. Please choose the release option from the dropdown list as encircled in red.

dropdown

Step 2
Right-click on the project and choose the publish command to publish the Web API. Kindly look at the images shown below.

Web API

ftp

As soon as you click on the publish button it publishes the build and prompts for a message in the bottom of success as shown in the image below:

edit list

Step 3
Now type "Inetmgr” in the Start window and click on inetmgr to open IIS as shown in the image below:

Inetmgr

Step 4To add a new application as a virtual directory right-click on the default website and click on the Add application property. Please refer to the following image.

reference

Provide an alias name of your choice and provide the physical path from your directory.
Note:
  1. It should be a published solution path that we've created in Step 2 above.
  2. Change the application pool “DefaultAppPool” to ASP.Net v4.0 after clicking on the “select” option. If you encounter an error like “unrecognized attribute 'targetframework'. Note that attribute names are case-sensitive IIS7” then here is the solution for that.
    Unrecognized attribute 'targetframework'. Note that attribute names are case-sensitive IIS7

  3. targetframework
Step 5
The sample application has been hosted in IIS with the name DotnetPiper.

DotnetPiper

To verify that the WebApi has been hosted perfectly, browse to the application again. Go to IIS and right-click on the application then select Manage Application -> Browse. It will look as in the image shown below.

image

The preceding Blue screen shows that the Web API is up and running.
I've used Fiddler to trace the requests, so I will open Fiddler to execute the following link to retrieve the information of the EmployeeId 15: http://localhost/DotnetPiper/api/Employees/GetEmployeeById/15


GetEmployeeById

Execution of AddEmployee (POST) Method of WebApi
Since the WebApi is already in running mode, I'll execute the following link to add an employee to the database.http://localhost/DotnetPiper/api/Employees/AddEmployee and will pass the following JSON parameters { "EmployeeId": 30, "Name" : "AjayJadeja", "ManagerId" : 7 }.


EmployeeId

Please open the database to confirm whether or not the user “Ajay Jadeja” has been added to the database. Kindly look at the image shown below:

Ajay Jadeja

We are nearly done with the execution of the Post method.
Execution of DeleteEmployeeById (Delete) Method of WebApi.
Now open the EmployeeController again and paste the following code into that as the Delete WebApi method:


Since the WebApi is already in running mode, I'll execute the following link to delete an employee by the employee id database. http://localhost/DotnetPiper/api/Employees/Delete/20 or http://localhost/DotnetPiper/api/Employees/DeleteEmployee/20
Please open the database to confirm that EmployeeId “20” has been deleted. Kindly look at the image shown below.
Note: If you face an error at time of execution of DELETE and PUT.Kindly refer this link for resolution.
WepApi HTTP Error 405.0 - Method Not Allowed

EmployeeController

Note: I have intentionally left the implementation of the Update method so that the end user can have hands-on to this. I'll also add a database backup for user help.
Go through with these detailed links to learn more about the WebApi.
  • How MediaTypeFormatter and MediaTypeMapping are associated with each other in the WebApi.
  • WebAPI: MediaTypeFrommatters in WebAPI.
Detailed links to learn more about the WebApi.

Points to consider:
  • You should have a little knowledge of the WebApi.
  • You should have knowledge of the Fiddler tool to execute the functionality.
  • There is a need for SQL Server also.
I hope it will help you somewhere down the line.
Keep coding and smiling Smile

Unrecognized attribute 'targetframework'. Note that attribute names are case-sensitive IIS7

Scenario: I added a WebAPI application in IIS and tried to browse ,it prompt me a yellow error window as shown below.

Error is => unrecognized attribute 'targetframework'. Note that attribute names are case-sensitive IIS7.

 

To sort this issue please follow these steps.

Go to IIS and Right click on Application ->  Manage Application-> Advance Settings and change the Application pool value from "DefaultAppPool" to "ASP.NET v4.0" and press ok . Kindly follow the image given below to understand more:

 

Now browse an application again. Go to IIS and Right click on Application -> Manage Application-> Browse.

I hope it will work .Mine started working.

Happy Coding :)

Tuesday, February 3, 2015

WebAPI: Restful CRUD Operations in WebAPI Using ADO.NET Objects and SQL Server 2008

clip_image002

The Web API is a platform to develop HTTP / HTTPS based services that can be used by native applications like on smart phones, tablets and any browsers. The WebAPI is a core part of ASP.NET and provides ways to create Restful services and can be used by any applications that can understand HTTP communications.There were many example to perform CRUD using Entity Framework , so I though to implement with ADo.Net objects with SQL Server 2008.

Implementation of Restful operations using ASP.NET Web API
Let's create a sample application and do this step-by-step.


Step 1

Let's first create a sample web application and using "ASP.NET MVC 4 Web Application" and name it as you choose. I used "WebApiDemo" as shown in the following image:
Web Application


Step 2

Click OK and choose the Web API command from the templates shown in the wizard window.


Web API


Step 3

You will find the application structure as shown below at first sight.


application structure


Step 4

Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select "Add" ➤ "Controller" and provide a name of EmployeesController for the controller. Leave the option "Empty API Controller" selected in the Template dropdown and click "Add", as shown in the figure below. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework.

Controllers folder
Step 5

Right-click the Models folder in the Solution Explorer of Visual Studio. Select "Add" ➤ "Class" to add a new class with a name of Employee.


class


After creating the Employee class, kindly add the following code into this class.


Code Segment

  1: public class Employee  
  2: {  
  3:    public int EmployeeId { get; set; }  
  4:    public string Name { get; set; }  
  5:    public int ManagerId { get; set; }  
  6: }  
  7: 


emp class



This is the complete structure of the solution as depicted in the image below:



complete structure



Now we'll open the EmployeeController and implement the Get-Post-Delete-Update methods one by one.



Execution of Get Method of WebAPI:

Now open the EmployeeController and paste the following code into that as the Get WebAPI method:

  1: [HttpGet]  
  2:  [ActionName("GetEmployeeByID")]  
  3: public Employee Get(int id)  
  4:  {  
  5: //return listEmp.First(e => e.ID == id);
  6:      SqlDataReader reader = null;  
  7:      SqlConnection myConnection = new SqlConnection();  
  8:      myConnection.ConnectionString = @"Server=.\SQLSERVER2008R2;Database=DBCompany;User ID=sa;Password=xyz@1234;";  
  9: 
 10:      SqlCommand sqlCmd = new SqlCommand();  
 11:      sqlCmd.CommandType = CommandType.Text;  
 12:      sqlCmd.CommandText = "Select * from tblEmployee where EmployeeId=" + id + "";  
 13:      sqlCmd.Connection = myConnection;  
 14:      myConnection.Open();  
 15:      reader = sqlCmd.ExecuteReader();  
 16:      Employee emp = null;  
 17: while (reader.Read())  
 18:      {  
 19:          emp = new Employee();  
 20:          emp.EmployeeId = Convert.ToInt32(reader.GetValue(0));  
 21:          emp.Name = reader.GetValue(1).ToString();  
 22:          emp.ManagerId = Convert.ToInt32(reader.GetValue(2));  
 23:      }  
 24: return emp;  
 25:      myConnection.Close();  
 26:  }  
 27: 

In the same way we will implement the Post and Delete employee. Now I have run the application and see the results. Press F5, it will show you the following screen:



run application



The preceding Blue screen shows that the Web API is up and running.
I've used Fiddler to trace the requests, so I will open Fiddler to execute the following link to retrieve the information of the EmployeeID “15”. http://localhost:57888/api/Employees/GetEmployeeById/15.



GetEmployeeById



Employees



Execution of AddEmployee (POST) Method of WebAPI

Now open the EmployeeController and paste the following code into that as the Post WebAPI method. The code is shown below:


  1: [HttpPost]  
  2: public void AddEmployee(Employee employee)  
  3: {  
  4: //int maxId = listEmp.Max(e => e.ID);
  5: //employee.ID = maxId + 1;
  6: //listEmp.Add(employee);
  7: 
  8: 
  9:     SqlConnection myConnection = new SqlConnection();  
 10:     myConnection.ConnectionString = @"Server=.\SQLSERVER2008R2;Database=DBCompany;User ID=sa;Password=xyz@1234;";  
 11: //SqlCommand sqlCmd = new SqlCommand("INSERT INTO tblEmployee (EmployeeId,Name,ManagerId) Values (@EmployeeId,@Name,@ManagerId)", myConnection);
 12:     SqlCommand sqlCmd = new SqlCommand();  
 13:     sqlCmd.CommandType = CommandType.Text;  
 14:     sqlCmd.CommandText = "INSERT INTO tblEmployee (EmployeeId,Name,ManagerId) Values (@EmployeeId,@Name,@ManagerId)";  
 15:     sqlCmd.Connection = myConnection;  
 16: 
 17: 
 18:     sqlCmd.Parameters.AddWithValue("@EmployeeId", employee.EmployeeId);  
 19:     sqlCmd.Parameters.AddWithValue("@Name", employee.Name);  
 20:     sqlCmd.Parameters.AddWithValue("@ManagerId", employee.ManagerId);  
 21:     myConnection.Open();  
 22: int rowInserted = sqlCmd.ExecuteNonQuery();  
 23:     myConnection.Close();  
 24: }  
 25: 


Since the WebAPI is already in running mode, I'll execute the following link to add an employee to the database.http://localhost:57888/api/Employees/AddEmployee and will pass the given the following parameters


{"EmployeeId":20,"Name":"Mike Prior","ManagerId":6}.



AddEmployee



Please open the database to confirm whether or not the user “Roger” has been added to the data base. Kindly look at the image shown below:



Roger



We are almost done with the execution of the Post method.



Execution of DeleteEmployeeById (Delete) Method of WebAPI



Now open the EmployeeController again and paste the following code into that as the Delete WebAPI method:


  1: [ActionName("DeleteEmployee")]  
  2: public void DeleteEmployeeByID(int id)  
  3: {  
  4:     SqlConnection myConnection = new SqlConnection();  
  5:     myConnection.ConnectionString = @"Server=.\SQLSERVER2008R2;Database=DBCompany;User ID=sa;Password=xyz@1234;";  
  6: 
  7:     SqlCommand sqlCmd = new SqlCommand();  
  8:     sqlCmd.CommandType = CommandType.Text;  
  9:     sqlCmd.CommandText = "delete from tblEmployee where EmployeeId=" + id + "";  
 10:     sqlCmd.Connection = myConnection;  
 11:     myConnection.Open();  
 12: int rowDeleted = sqlCmd.ExecuteNonQuery();  
 13:     myConnection.Close();  
 14: }  
 15: 


 


DeleteEmployeeById



Since the WebAPI is already in running mode, I'll execute the following link to delete an employee by the employee id database. http://localhost:57888/api/Employees/DeleteEmployee/20.

Please open the database to confirm that EmployeeID “20” has been deleted. Kindly look at the image shown below:



DeleteEmployee



Note: I have intentionally left the implementation of the Update method so that the end user can have hands-on on this. I'll also add database backup for user help.
Go through with these detailed links to learn more about the WebAPI.


 


Detailed links to learn more about the WebAPI.

Points to consider:


  • You should have a little knowledge of the WebAPI.
  • You should have a knowledge of the Fiddler tool to execute the functionality.
  • There is a need for SQL Server also.

I hope it will help you somewhere down the line.You can download the code from here : Restful CRUD Operations in WebAPI Using ADO.NET Objects and SQL Server



Keep coding and Smile Smile

Count Number of Columns in a Table and Delay in Sql server

Hi Geeks,

A simple query to find the number of columns in a table .

Here in example i have used Northwind  database table named as 'Categories' which returns the no of columns.

  1: use Northwind
  2: 
  3: select count('c') 'Columns Count' from sys.syscolumns where id=object_id('Categories')
  4: 

Column.png

This is very simple ,it generally uses in lot of queries.

2. The second is very interesting fact about Sql server is that to put delay in your query execution or on demand execution of query after certain time or on any specified time.During execution of the WAITFOR statement, the transaction is running and no other requests can run under the same transaction.

Kindly find the depict image as an example.

Delay.png

I you notice at the right of the bottom ,it shows it took 10 seconds to print this message.

This is very cool feature could be used in your query only.WAITFOR can be used with query but not with UDF or cursors.

Hope will help you some where.

Enjoy Coding.

Sachin Kalia

Monday, February 2, 2015

How to Create a Simple Bubble Popup! in jQuery

How to Create a Simple Bubble Popup! in jQuery

Let's create a simple BubblePopup!


As I learn more about the jQuery function every day, I have researched a feature that helps to perform some operation in the runtime called "CreateBubblePopup()".
It may do the following:

  • Attach popups to any DOM element!
  • Mouseover/mouseout events automatically managed!
  • Set custom popups events!
  • Create smart shadowed popups! (In IE too!)
  • Choose popup's style templates at runtime!
  • Insert HTML messages inside popups!
  • Many other options: distances, velocity, delays, colors, shadows...

Popup's shadows and colorized templates are fully supported by Internet Explorer 6+, Firefox, Opera 9+, Safari.
I've created a sample application that demonstrates the locating and functioning done by this feature. To proceed further and get the advantages of this jQuery plugin you must add a few references into your solution. The image shown below shows the .css, .js and theme libraries being used in the solution. You can find the theme over the internet in ample amounts though I have used a few like all-azure, all-blue and so on.

 


BubbleJquery1.jpg


Jump into the themes folder and explore this.
All-azure keeps multiple .jpg files that helps to create Popup side boundaries. Because CreateBubblePopup is built up from multiple <td> under a main <div> and if you notice, each .jpg file is associated with respective <td> segments.

BubbleJquery2.jpg


BubbleJquery3.jpg


These are a few libraries being used in this solution; they are:


  1: <link href="../../Content/jquery-bubble-popup-v3.css" rel="stylesheet" type="text/css" />
  2: <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
  3: <script type="text/javascript" src="../../Scripts/MyCustomJquery.js"></script>
  4: <script src="../../Scripts/jquery-bubble-popup-v3.min.js" type="text/javascript"></script



You can have a look into the CreateBubblePopup function using intelligence libraries.



BubbleJquery4.jpg


Properties


There are plenty of properties being used in this solution; some of them are the following:


  • STRING innerHtml: HTML message in the Bubble Popup.
  • STRING bubbleAlign: accepts "center", "left" or "right" values
  • STRING tailAlign: Bubble Popup's tail alignment, accepts "center", "left" or "right" values.
  • INT distanceFromTarget: Bubble Popup's distance from element.
  • INT openingVelocity: fade in velocity.
  • INT closingDelay: accepts an integer.
  • BOOLEAN showOnMouseOver: disable "onmouseover" event.
  • STRING color: change Bubble Popup color based on default template folder; accepts "azure", "blue", "green", "orange", "violet", "yellow".
  • STRING imageFolder: folder name that stores color templates.
  • BOOLEAN hideTail: true or false.
  • ARRAY hideObjectID: hide specific object tags if it is needed for incompatibility.
  • STRING contentStyle: set a custom CSS style to the HTML message.
  • INT zIndex: CSS z-index property of Bubble Popup.
  • INT/STRING width: Bubble Popup's width: "auto" (as default), an integer value or a string like "200px".

Move ahead and I press F5 and the following image shows:



BubbleJquery5.jpg



If you take over the mouse on the div having multiple <li> list elements, it prompts you with a bubble popup and asks you to perform a certain set of actions or some other notification. It's all up to the user what they would like to perform using a relevant feature.
Let's see how it appears after hovering the mouse on the li elements.



BubbleJquery6.jpg



It asks you "Click on the given following link to see How to jQuery builtin plugin works!".
I've plugged in this function with $('#div2').CreateBubblePopup({});
Click on any of the li elements under $('#div2'), it performs the certain action that I have implemented in code. Here it calls the "Animate ()" function of the customized jQuery plugin.
A sample application has been attached in source code.


http://www.c-sharpcorner.com/UploadFile/97fc7a/how-to-create-a-simple-bubble-popup-in-jquery/


 


Thanks for reading this article Smile


To learn more about MVC please go to the following link.

MVC Articles

Thanks.
Keep coding and Stay Happy Smile