11 December 2010

Find position Javascript

On this page I give the necessary code to find out where an element is on the page. This script finds the real position, so if you resize the page and run the script again, it points to the correct new position of the element.

offset
In all browsers it's necessary to use the offsetTop and offsetLeft of the element. These properties give the coordinates relative to the offsetParent of the element.
The script moves up the tree of offsetParents and adds the offsetTop and offsetLeft of each. Eventually, regardless of the actual composition of the offsetParent tree, this leads to the real coordinates of the element on the screen.

JavaScript code.
The script is very simple. Hand it the object whose position should be calculated and set the variables curleft and curtop to 0:
function findPosY(obj) {
  var curtop = 0;
   if (obj.offsetParent)
     while (1) {
      curtop += obj.offsetTop;
      if (!obj.offsetParent)
         break;
         obj = obj.offsetParent;
      }
      else if (obj.y)
      curtop += obj.y;
     return curtop;
}
function findPosX(obj) {
  var curleft = 0;
   if (obj.offsetParent)
    while (1) {
     curleft += obj.offsetLeft;
     if (!obj.offsetParent)
         break;
      obj = obj.offsetParent;
      }
      else if (obj.x)
      curleft += obj.x;
      return curleft;
}
Now assign it to control.In my case it is a div panel. 
var positioY = findPosY(obj);
var positionX = findPosX(obj);
var curtop = 0;
div.style.top = positioY + "px";
div.style.left = (positionX + 10) + "px";

07 November 2010

Ping a Server from .NET

Everyone will know, what is PING? But ever thoughts from where this word comes and what it means. As we all know Ping is an acronym for the words 'Packet Internet Groper'. The name comes from active sonar terminology. Submarine - Navy uses this method to when they looking for objects under the sea. That means send out sonar waves and then waits for a return wave when it bounces off something, such as another sub, whale, ocean floor etc. This, in turn, was adopted from bats and dolphins! The “PING” is the sound that sonar makes!
Ping is a computer network administration utility used to test the reach ability of a host on an Internet Protocol (IP) network and to measure the round-trip time for messages sent from the originating host to a destination computer. A small packet is sent through the network to a particular IP address. This packet contains 64 bytes - 56 data bytes and 8 bytes of protocol reader information. The computer will send the packet and then waits for a return packet. If the connections are good and the target computer is up, a good return packet will be received.
PING is also a useful utility for programmers. Often it is a good practice to see if an endpoint is "up" before attempting to send a message. Also, it can be very useful to estimate the response time from the host. Generally if the server is available, it sends the response immediately. We have a requirement in our application where we have thick client in .net and need to talk to another application through web url. Here by sharing the code samples.
public bool  Ping()
{
   using (Ping pingSender = new Ping())
   {
     PingOptions pingOptions = null;
     bool pingResults = false;
     PingReply pingReply = null;
     IPAddress ipAddress = null;
     int numberOfPings = 4, pingTimeout = 1000, byteSize = 32, sentPings = 0;
     byte[] buffer = new byte[byteSize];
     string ipAddressString = "10.22.24.174";
     pingOptions = new PingOptions();
     ipAddress = IPAddress.Parse(ipAddressString);
     for (int i = 0; i < numberOfPings; i++)
     {
       sentPings++;
       pingReply = pingSender.Send(ipAddress, pingTimeout, buffer, pingOptions);
        if (pingReply.Status == IPStatus.Success)
        {
           pingResults = true;
        }
      }
    return pingResults;
   }
}
The PING sends an ICMP (Internet Control Message Protocol) echo request to the server and waits to receive the echo back. If the value of Status is success, the PingReply is successful.
Also in few case may be server will be up and may be we have to perticulerly ping the url, in that case we can go ahead and use the below code:
public bool IsUrlAvailable(string url)
{
  try
  {
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
    {
      if (rsp.StatusCode == HttpStatusCode.OK)
      {
         return true;
      }
     }
    }
    catch (WebException)
    {
        // Eat it because all we want to do is return false
    }
    return false;
}




25 October 2010

MS Exception Handling Block Error

The problem.
We have multiple components in .net ,was communicating each other for the business use cases and in case of error it should come back to entry point and log the exceptions.  We have used Enterprise Library exception handling block to handle the logging and exception part.While testing it is observed that logging was not happening to the desired files.Basically from the exception handling block we were getting  an error something like:
The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, DefaultPolicy]) failed:
And to read it completely:
The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, DefaultPolicy]) failed: The type 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' cannot be resolved. Please verify the spelling is correct or that the full type name is provided. (Strategy type ConfiguredObjectStrategy, index 2) 
try
{
   Exception ex = new Exception();
   throw ex;
}
catch (Exception ex)
{
   bool rethrow = ExceptionPolicy.HandleException(ex, "UI Ploicy");
   if (rethrow)
   {
      throw;
    }
   throw;
}
Note: It is assumed that we have configured the config files properly.

The solution
Add following dlls as reference where ever you are doing the log. 
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling 
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging
Microsoft.Practices.EnterpriseLibrary.Logging 
The ExceptionHandling.Logging dll is must to use ExceptionHandling as while logging the exception, Exception handling block use this .dll. 
In my case I am having a console application and here I will have to explicitly refer the exception handling blocks into services or console application projects where I log the exceptions.

08 October 2010

WebDataGrid in ASP.NET MVC Application

After writing the other three blogs (introduction/Code Sample/Test sample) on ASP.NET MVC 2.0, I was planned to get in to some of the details of routing, areas stuff like that. But some of my friends who were working with some sample MVC using WebDataGrid, were asking me few questions on that. So I thought to come up with a code sample on that. But I did not got any evolution version of WebDataGrid from Infragistics to work with.So for time being we can see the sample of ASP.NET Grid view. The same way you can consume WebDataGrid too. But it is true that we can’t give samples for lot of in built features which coming with   WebDataGrid like sorting, column resizing or whatever. 
Ok come back to the sample that we already created. If we don’t have please visit the link. We are going to do following steps:
  1. Create a view data model.
  2. Add new action/method in controller class.
  3. Modify the link button action in Site.Master.cs.
  4. Create a new View and add a WebDataGrid/Grid on it.
First we have to create a view model. Go ahead and create a view model under Models folder. The code looks something like this:
public class GridViewModel
{
   public IList<EmployeeModel> listEmployee { get; set; }
}
Secondly we need to add a controller method/action in the EmployeeControoler.cs and the code is going to looks:
public ActionResult SampleGridView()
{
    EmployeeDAL empDAL = new EmployeeDAL();
    List<EmployeeModel> employyesList = new List<EmployeeModel>();
    employyesList = empDAL.GetAllEmployees();
    var gvSample = new GridViewModel();
    gvSample.listEmployee = employyesList;
    return View(gvSample);
}
Thirdly Modify the link button to redirect to the new method/action we have created.
Html.ActionLink("Employee", "SampleGridView", "Employee")
Lastly we need to create a view which holds our WebDataGrid/grid. Go ahead and create a strongly typed view under employee sub folder:
Run the application and nothing is going to display on the new view that we created. Ok let’s see that what we have to do for displaying data in the grid. We need to open up a server side script now. The reason is that this is a data bound control and need data source properties to be set.

Now run the application and you will be able to see the grid populated with data. So for those who are using the code samples for WebDataGrid can still go ahead and play with rich behaviors properties that comes with Infragistics.
  

26 September 2010

ASP.NET MVC 2 Unit Testing

ASP.NET MVC frame work is designed to be very testing friendly. Here we are trying to understand the easy testing aspect of the MVC Framework.For that we are going to build our test application on top of the sample application that we tried out in part2. So recommended to have a look on that for a better understanding.

Why we need to do unit testing ?
Million dollar question! Testing is needed mainly because it's an automated way to make sure the piece of code is always behaving the way it is supposed to behave. This way we can make changes to the code and re factor pieces of the application without the fear of breaking something somewhere else in the application.This question looks silly but was the first one which came to my mind when I was writting this , hope the readeres excuse me!

Why testing is a pain with traditional ASP.NET web forms?
If you wrote unit testing in classic web application it really sucks.One of the reasons of the classic approach to developing web applications with .NET, the WebForm approach, is not easily testable: it's because the main class of ASP.NET, System.Web.UI.Page, has dependencies to HttpContext, HttpResponse, HttpRequest, HttpCookie and all the other objects coming from the fact that the Page is being executed inside a web server. And all these classes are "just" concrete classes, and cannot be replaced by fake implementations for the purpose of testing the web applications outside the context of the web server.

What makes ASP.NET MVC very good for TDD?
If the controller got a method call and it does not care about who called it then you could go and call inside of a test file and that how testing framework works. On top of this MVC made separation of components.

Code Sample?
We will discuss how to build three different types of unit tests. basically how to test the view returned by a controller action, how to test the View Data returned by a controller action, and how to test whether or not one controller action redirects you to a second controller action bla... bla... bla...
So in a nut shell  we need to test following things. 
  • Test Routes
  • Test Controller
  • Test Views.
  • Test Model
  • Test Functionality

Right click on controller folder under test project and add EmployeeControllerTest.cs.See the sample code that we need to add in this class.
[TestMethod]
public void EmployeeList_Action_Returns_View()
{
    // Arrange 
    var EmployeeController = new EmployeeController();
    // Act 
    var result = EmployeeController.EmployeeList();
    // Assert 
    Assert.IsNotNull(result, "Should have returned a ViewResult");
}
[TestMethod]
public void AddEmployee_Action_Returns_View()
{
  // Arrange 
  var EmployeeController = new EmployeeController();
  // Act 
  var result = EmployeeController.AddEmployee();
  // Assert 
    Assert.IsNotNull(result, "Should have returned a ViewResult");
}
[TestMethod]
public void TestCreateEmployee_Method()
{
   EmployeeDAL empDAL = new EmployeeDAL();
   List<EmployeeModel> employeeList = new List<EmployeeModel>();
   employeeList = empDAL.GetAllEmployees();
   // Assert 
   Assert.IsNotNull(employeeList, "Should have returned a Employee    Collection");
}
[TestMethod]
public void Add_Employee_Action_Returns_RedirectToRoute_Result()
{
   // Arrange 
   const string expectedRouteName = "EmployeeList";
   EmployeeModel emp = new EmployeeModel();
   emp.EmpName = "New Employee";
   var EmployeeController = new EmployeeController();
   // Act 
   var result = EmployeeController.Create(emp) as RedirectToRouteResult;
            // Assert 
   Assert.IsNotNull(result, "Should have returned a RedirectToRouteResult");
   Assert.AreEqual(expectedRouteName, result.RouteName, "Route name should have been {0}", expectedRouteName); 
}
Our all tests related to employee controller will be in this file.  And finally run the project and you are going to get the test results like this.

So as a conclusion we have seen some theories and code samples for building and testing MVC applications. These are the basic levels of information’s and we need to go more deep dives for better understandings. Anyway I am not quitting my  journey on MVC Framework here rather decide to take a long drive on it. In future MVC is going to rule in web development and as a developer I need to upgrade myself to this more and more. As always if you have any queries you are most welcome. 

25 September 2010

ASP.NET MVC 2 Code Sample

Sample Project
In the previous section we piece the theories together and tried to understand what is MVC and why we need to learn this programming architecture. So before reading this piece I would recommend you to go through the ASP.NET MVC Introduction Part 1 link for some basic theories. OK, now let's start with building a sample application. 

Prerequisites
If you are in VS 2008 you need to download ASP.NET MVC 2. Click here to download release candidate for .NET 3.5 and VS 2008.With VS 2010, it is already shipped and has an automated upgrade wizard that can automatically migrate your existing ASP.NET MVC 1 applications to ASP.NET MVC 2 for you. Also remember MVC 2.0 can be installed side-by-side with ASP.NET MVC 1.0 on the same machine.
Ok, let’s get start with. Open your VS IDE 2008 go to File > New Project > ASP.Net MVC give it a name I named it SampleMVC. A dialog box will prompt you to create test projects. If you are a bad programmer skip the test project.
Now have a look at the project structure that created by MVC frame work by default.

The structure of your Project
if you explore the solution that we created there are three main folders – Model, View, and Controller. Views are nothing more than .aspx pages. Other folders here are content folders which can hold resources files, images and Model folder can be represented by entity classes, can be also represented by data table’s data sets etc. This is more related if you are doing data driven based programs. Script file as name indicates can hold JavaScript files. And also you can see another test project if you selected the options for the same while creating project. To create more controller and views right click on the folder and will give you options to create both. So we are created our first ASP.NET application on MVC 2.0 framework!!! Let’s go home!
1. So take the homeController.cs now. In this controller class MVC framework has created 2 new ActionResults by default.One named Index, and one named About. These are nothing more than calling a View titling their names.
2. Inside Index we have a View Data, which is nothing more than a way for a controller to pass data to the view.
3. Inside the view of Index you see that there is that ViewData ["Message"] using the Html.Encode is just a way of accessing the ViewData.
Before that you might be noticed one interesting thing in the web URL something like http://localhost:1744/Home/About . If you have a classic asp.net back ground you might be asking where is the .aspx extension?  That is what MVC routing is coming to picture and we already discussed in part1.
Ok we are done with the basic stuff. Now let’s come out and think in terms of real time scenarios.See the screen shot for now.

How to do CURD operations?
Now being in this frame work we are going to see that how we can add a view, Model and controller by giving a sample CURD operation.
We will create a sample application which has following things.
  1. A basic view which has look up values from DB. - EmployeeList.(View1)
  2. Take the user inputs and save it to DB. - AddEmployee.(View2)
  3. Read the updated DB and display on EmployeeList.(View1)
To start with we need a data model. But we are not going to worry much on the data model as this framework is going to talk with all most all databases with almost same manner. To take with a simple example I am going to have an employee data model and save and retrieve to an xml file.
In order to add the new view first I am going to add a menu item for my employee view. Go to Site. Master files under shared folder and add this line.
In the Action link we need to specify what action it should take and what the routing values are.
Now we need to handle the action in Controller class, for keeping the modularity we are creating separate controller class called EmployeeController.cs. Microsoft recommends putting your Controller classes underneath the /Controllers directory, (also data model classes underneath your /Models directory, and your view templates underneath your /Views directory). 
Let’s go ahead and add our action in it as a method in the controller class and add a view of the same name what we have given for method. Rich MVC template will guide you all these actions. Now we have following classes ready in general.
  1. EmployeeDataModel.cs - It could be a simple data model.
  2. EmployeeDAL.cs - This class is to read/ write data model to xml file.
  3. EmployeeControoler.cs
  4. EmployeeList.aspx
We are not going to explain the files one and two as it is nothing but having an employee data model and read/write logic to xml file. But See the code in other file:
EmployeeController.cs
public ActionResult AddEmployee()
{
   EmployeeDAL empDAL = new EmployeeDAL();
   List<string> allRoles = new List<string>();
   allRoles = empDAL.GetAllRoles();
   EmployeeModel empData = new EmployeeModel();
   ViewData["Roles"] = new SelectList(allRoles);
   return View(empData);
}
[HttpPost]
public ActionResult Create(EmployeeModel employeeModel)
{
  if (ModelState.IsValid)
  {
    EmployeeDAL empDAL = new EmployeeDAL();
    EmployeeModel empData = new EmployeeModel();
    empData = (EmployeeModel)ViewData.Model;
    EmployeeController controller = new EmployeeController();
    empDAL.CreateEmployee();
    return RedirectToAction("EmployeeList");
   }
   else
   {
   return View("AddEmployee");
 }
}
Go ahead and press F5 to display the home page, the new menu item – Employee that we created and on click of Employee it will take you to the new screen. We are going to add the code now to display the employee List Employees below (EmployeeList.aspx):

Now we have a view which read data from model using controller. We are going to add one link button on click of that it should display another view to accept user inputs to add new employee. So go ahead and repeat the same steps and call from a link button on down. Do not forget to add subsequent events in controller class.
And the Add Employee.aspx file look like this:
So how this sample application works?
1. When we are giving http://localhost:2500/Employee/EmployeeList in the address bar the routing engine will look it in global.asax file and for matching our request we have a default routing {controller}/{action}/{id}.So if we receive a URL request of /Employee/EmployeeList, the routing rule will treat " Employee" as the name of the action, and the EmployeeList () method will be invoked to process the request , which will finally load the EmployeeList UI.
2. Now when the user gives new Employee details and click on save. This will call /Employee/Create message or Cretate () method on EmployeeController which will pass view object to data model and redirect the view back to EmployeeList view. Simple right?
So we have some bullet points here:
1. Create Routing and route table to route to controller.
2. Controller does some logics and invokes the message or method where these messages call a view files.
3. Controller says get me a object / model example Employee here, I do whatever I can and pass this to view.
3. Do create your model, it should be an object or ORM model or SQL or whatever. We are not much interested on that.
4. View looks like aspx page but not exactly same. Some people put code behind in view but remember it will break single responsibility principle. Once we add code behind we can do all the non sense there to break the MVC basic rules. Separation of controls is most important concept of MVC.

5. In MVC views job is only to display the data what controller passed.It is not supposed to do any calculations.For example If you want to do tax calculation inside a view..STOP, that is not view job.Do that calculation in controler in pass it back to view.
6. Controller does not know who has called. So this is one of the fundamental for testing frame work. Call your controller from testing and test your controller, model, functionality.
So on successful creation of this sample application I am sure you will be getting ideas on URL Routing basics, creating view/Controller, how to capture a user interaction and how the control updates the model and updates the view back. So now time to look in to test project which is automatically created by MVC framework for you for unit testing. Recommend you to go through the link.