Monday, March 23, 2015

Attach an event to element to execute only once.

Today I have been using JQuery and confront an  interesting situation to click once on a Div. .To do this use One function exist into JQuery .

Generally when we attach an event to any element, event functionality remains with the element till element gets removed .If we delete that elements means that functionality has been deleted but if you don’t want to remove that element and want to run the event functionality only once,Kindly use this approach.

Answer is JQuery one() method.

This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.

  1: $(document).ready(function() {
  2:     $("#DotnetPiper").one("click", function() {
  3:         alert("You have click once on DotnetPiper.com.");
  4:     });
  5: });​
  6: 


After the code is executed, a click on the element with ID dotnetpiper will display the alert. Subsequent clicks will do nothing.


This is best in use when you want to execute functionality once.


 


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

MVC Articles & WCF and WebApi

 


Thanks

Thursday, March 12, 2015

Route URL Request for Physical file using RouteExistingFiles in MVC4

Here we go:
Objective : RouteExistingFiles is beneficial in scenario when have you to prevent access to the files and allow ASP.Net to handle such request using Route.image
Open your visual studio, click on New Project and select ASP.NET MVC4 Web Application.


Specify the name of your first application and click OK.
New window will appear, from that window I picked up Intranet application whilst many options are there. Another intersting fact that there is a dropdown named as View Engine I seleccted Razor which is more specific to MVC 3 and MVC 4 and keep a checkbox “create a new unit test” unchecked.


Click on ok button.

The given below screen is default one comes after clicking on OK button. Having multiple folder’s.  

 

Let’s go into more detail for this. Routing is defined in Global.asax, open the file, and you can see the following lines of code. 


We need to make some amendments into this to understand how routing works. RouteConfig.cs class is responsible for registering the RegisterRoutes method. This Application_Start method is called by ASP.NET platform when the application is started first.


And this is the default structure which is depicted below. I’ve added two files in Content folder of root directory.

themes folder
Let’s see what happen when we run our application first time with default routing settings.


An idea to write this article is to be able to serve a physical file using a route, not by using a physical file in the site. I’ve created a route entry in the controller and action methods necessary to serve up the content:

  1: routes.MapRoute(  
  2:       name: "PNGFile", // Route name
  3:       url: "Content/{file}.png",  
  4:       defaults: new { controller = "Home", action = "Html", file = UrlParameter.Optional }//,// Parameter defaults
  5: //namespaces: new[] { "MVCSample.Controllers" }   // Namespaces
  6:   );  
  7: 
  8:  routes.MapRoute(  
  9:        name: "HtmlFIle", // Route name
 10:        url: "Content/{file}.html",  
 11:        defaults: new { controller = "Home", action = "Html", file = UrlParameter.Optional }//,// Parameter defaults
 12: //namespaces: new[] { "MVCSample.Controllers" }   // Namespaces
 13:    );  
 14: 


There are two entries into the RouteConfig.cs file which is pertinent to .png and .html files. So whenever URL keeps a .png or .html file, it will be served using route.
The job of routing system is to verify the incoming URL request and find out the value of segment variables,segment variables are defined using curly braces {}.


All is set so far. Now we’ll define a property into RouteConfig file to execute and verify the functionality.

Kindly refer an image below to know more.



Note: In a layman words : whenever “.png” or “.html” would be part of URLs than this route will take care of it to respond instead of physical location.
Now I run an applcation and see all factors.Paste the following url into brower and execute. http://localhost:63005/Content/logo.png
It’ll reach to an anticipated action of home controller as shown in depicted image below:

Final output would be like shown below image :



Now I perform another step and comment this line routes.RouteExistingFiles = true;


From code to see the effect. Press F5
Output: It returned an image from directory instead on using Route method.

Key Point: It didn’t hit an action method of controller this time.
Note: RouteExistingFiles is beneficial in that scenario when you to prevent access to the files and allow asp.net to handle such request using Route.


 


Hope it’ll help you some day down the line.
Enjoy MVC and Routing. Download source code Sample Application for Physical file Routing

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

MVC Articles & WCF and WebApi

Thanks.
Enjoy coding and reading.

Monday, March 9, 2015

Use Html attributes for TextBoxFor in ASP.NET MVC ?

Use Html attributes for TextBoxFor in ASP.NET MVC ?

This is the way to generate TextBox with certain properties.

 

image

 

  1: @Html.TextBoxFor(model => model.properyName, new { @maxlength="25",disabled = "disabled",@class = "form-control" })


This will generate a textbox that matches your property name and will also populate the textbox with any values that are contained within the Model.


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

MVC Articles & WCF and WebApi

Thanks.
Enjoy coding and reading.

Sunday, March 8, 2015

Bind DropDownListFor at runtime in MVC

Dotnetpiper

Hi Friends,


During an implementation of MVC View page ,I struggled little to bind the DropDownList with the runtime value from ViewModel . Here is the pictorial representation to Bind the DropDownList at runtime.

 

Image Representation As depicted below:

 

image

 

Hope it will help you to bind DropDownListFor at runtime.

 

Thanks

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

MVC Articles & WCF and WebAPI

Thanks.
Enjoy coding and reading.

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