Friday, November 27, 2015

Export DataTable to Excel with Open XML in c#

This code sample will illustrate how we can create Excel file from a data table in c#.
You will need to add DocumentFormat.OpenXml and WindowsBase dll references to make it work.
private static void WriteExcelFile(string outputPath, DataTable table)
{
 using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileToGenerate, SpreadsheetDocumentType.Workbook))
 {
  WorkbookPart workbookPart = document.AddWorkbookPart();
  workbookPart.Workbook = new Workbook();

  WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
  var sheetData = new SheetData();
  worksheetPart.Worksheet = new Worksheet(sheetData);

  Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
  Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };

  sheets.Append(sheet);

  Row headerRow = new Row();

  List<String> columns = new List<string>();
  foreach (System.Data.DataColumn column in table.Columns)
  {
   columns.Add(column.ColumnName);

   Cell cell = new Cell();
   cell.DataType = CellValues.String;
   cell.CellValue = new CellValue(column.ColumnName);
   headerRow.AppendChild(cell);
  }

  sheetData.AppendChild(headerRow);

  foreach (DataRow dsrow in table.Rows)
  {
   Row newRow = new Row();
   foreach (String col in columns)
   {
    Cell cell = new Cell();
    cell.DataType = CellValues.String;
    cell.CellValue = new CellValue(dsrow[col].ToString());
    newRow.AppendChild(cell);
   }

   sheetData.AppendChild(newRow);
  }

  workbookPart.Workbook.Save();
 }
}

Wednesday, June 10, 2015

Configure StyleCop with MSBuild to treat Warnings as Errors

We can easily configure StyleCop with MSBuild to make warnings appear as errors with the help of StyleCop.MSBuild NuGet package.

First go to Package Manager Console and install it with following command.


Install-Package StyleCop.MSBuild
Then unload your project and open the project file to modify it.



Now you have to add "StyleCopTreatErrorsAsWarnings" property inside "PropertyGroup" tag as below.
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
  <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
  <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
</PropertyGroup>
<Error Condition="!Exists('..\packages\StyleCop.MSBuild.4.7.49.1\build\StyleCop.MSBuild.Targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\StyleCop.MSBuild.4.7.49.1\build\StyleCop.MSBuild.Targets'))" />
</Target>
Almost done, but sometimes auto generated files gives errors when we build the project, to overcome that we need to modify "Settings.StyleCop" file.

Go to project folder and inside that you can find folder called "packages". It contains StyleCop files and inside "tools" folder you can find that setting file. You can open it with a test editor.


Now you can add new value to GeneratedFileFilters as bellow to ignore those generated files.
<Parser ParserId="StyleCop.CSharp.CsParser">
  <ParserSettings>
 <CollectionProperty Name="GeneratedFileFilters">
   <Value>\.g\.cs$</Value>
   <Value>\.generated\.cs$</Value>
   <Value>\.g\.i\.cs$</Value>
   <Value>TemporaryGeneratedFile_.*\.cs$</Value>
 </CollectionProperty>
  </ParserSettings>
</Parser>
Now reload your project and try to build your project. You will be able to see that all the warnings appear as errors.

Wednesday, April 22, 2015

MVC 5 with Unity for Dependency Injection

Dependency Injection allows us to inject objects into a class, instead of constructing them internally. Unity is a dependency injection container that we can use for constructor, property, and method call injections.

You can get good idea about dependency injection by reading answers to this stack-overflow question.

This tutorial is an step-by-step guide with screen-shots where you can learn how to use Unity with Asp.Net MVC5.

I'm going to create sample web application for academic course listing website. There I have Institution and Course as main entities.

I will not connect this sample application with a database and will illustrate with hard-coded data. Let's start...

1. Create Sample Web Application

In this example I'm using Visual Studio 2013 and let's start by creating sample MVC web application.

Check whether you can run the created web application and if there are no issues it should give following output.

2. Install Unity.Mvc5 Library

To install Unity.Mvc5 Library using nuget, we have to go to Package Manager Console and execute the following command.

Install-Package Unity.Mvc5

Wait until it completes the installation.

After completion if you check the Solution Explore, you can see newly added UnityConfig class inside App_Start folder. That's where we register all our components with the container.

3. Update Sample Application

Let's update our sample application now, first I'll add two another Class Library projects called Entities and Services. There Entities project holds all the entity (model) classes we are going to use and Services project will be used to put our service classes.

Then I'll add following classes to created Entity project.

Institution Class

namespace Entities
{
    public class Institution
    {
        public long InstitutionID { get; set; }
        public string Name { get; set; }
        public string Telephone { get; set; }
        public string Address { get; set; }
    }
}

Course Class

namespace Entities
{
    public class Course
    {
        public long CourseID { get; set; }
        public long InstitutionID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}

Next I will create the Services Class Library project and add reference to Entities project from Services project.

Now I will create two service classes for institutions and courses. And also I will add relevant interfaces for those classes.

IInstitutionService Interface

using Entities;

namespace Services
{
    public interface IInstitutionService
    {
        Institution GetInstitutionByID(long institutionID);
    }
}

InstitutionService Class

using Entities;

namespace Services
{
    public class InstitutionService : IInstitutionService
    {
        public Institution GetInstitutionByID(long institutionID)
        {
            return new Institution { InstitutionID = institutionID, Name = "Sample Institution", Address = "Sample Address", Telephone = "0123456789" };
        }
    }
}

ICourseService Interface

using Entities;

namespace Services
{
    public interface ICourseService
    {
        Course GetCourseByID(long courseID);
    }
}

CourseService Class

using Entities;

namespace Services
{
    public class CourseService : ICourseService
    {
        public Course GetCourseByID(long courseID)
        {
            return new Course { CourseID = courseID, Description = "Sample course description", InstitutionID = 1, Title = "Sample Course Title" };
        }
    }
}

Your solution explore should looks like below now with all those projects and classes.

We need to add references to Entities and Service projects within Unity Web Application before we continue.

4. Configure Unity

Let's register our components with the unity container. There first we have to update our UnityConfig class as below.

using Microsoft.Practices.Unity;
using Services;
using System.Web.Mvc;
using Unity.Mvc5;

namespace UnityWebApplication
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType<ITestService, TestService>();

            container.RegisterType<ICourseService, CourseService>();
            container.RegisterType<IInstitutionService, InstitutionService>();
            
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}

This RegisterComponents method can be called within the Application_Start method in Global.asax. We can update our Global.asax as below.

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace UnityWebApplication
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            UnityConfig.RegisterComponents();

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

5. Continue with Sample Application

Now we are going to display these institution and course information in our web application. I'll add new Empty Controller called Institution to our MVC application by right clicking Controllers folder.

Normally if we want to use our InstitutionService within the InstitutionController, we need to create instance of InstitutionService inside InstitutionController. Dependency injection is basically providing the objects that an object needs (here the InstitutionService) instead of having it construct them itself. I'm going to use constructor injection in this application and let the unity to create new instance of InstitutionService for InstitutionController. There we need to add constructor to our InstitutionController with parameter as below.

using Services;
using System.Web.Mvc;

namespace UnityWebApplication.Controllers
{
    public class InstitutionController : Controller
    {
        private IInstitutionService institutionService;

        public InstitutionController(IInstitutionService institutionService)
        {
            this.institutionService = institutionService;
        }

        // GET: Institution
        public ActionResult Index()
        {
            return View(this.institutionService.GetInstitutionByID(1));
        }
    }
}

Let's add view to display our information, you can find folder called Institution inside Views folder and we will create new view called Index there.

Now modify your view code as below to display institution information.

@using Entities;
@model Institution

@{
    ViewBag.Title = "Institution";
}

<hr />

Institution ID : @(Model.InstitutionID)

<hr />

Institution Name : @(Model.Name)

<hr />

Institution Address : @(Model.Address)

<hr />

Institution Telephone : @(Model.Telephone)

It's done, you can run your application and try /Institution/Index. You should get following output.

6. Move Unity Configuration to Separate File

We can move unity configuration to separate file which enable us to do modifications without recompiling existing application. We can do this by adding config section to web.config file as below.

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <unity configSource="unity.config" />
  <connectionStrings>

unity.config

<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>
    <register type="Services.IInstitutionService, Services" mapTo="Services.InstitutionService, Services" />
    <register type="Services.ICourseService, Services" mapTo="Services.CourseService, Services" />
  </container>
</unity>

We need to change the UnityConfig to load the configuration from given file, modified code can be found below.

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Services;
using System.Web.Mvc;
using Unity.Mvc5;

namespace UnityWebApplication
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType<ITestService, TestService>();

            //container.RegisterType<ICourseService, CourseService>();
            //container.RegisterType<IInstitutionService, InstitutionService>();

            container.LoadConfiguration();
            
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}
Download Source (Password:sara)

You can download the source code of sample application using above link. I have added some additional classes/methods to use InstitutionService inside CourseService. You can go through the code and will be able to understand easily.

Wednesday, January 22, 2014

Pass Complex JavaScript Object to MVC Controller

In this tutorial I'm going to illustrate how we can pass complex javascript objects to MVC controller.

I have two Model objects called Project and Employee as below.

    public class Project
    {
        public long ProjectID { get; set; }
        public string ProjectName { get; set; }
    }

    public class Employee
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

And I have view-model called "ProjectViewModel" which contains above models as below.

    public class ProjectViewModel
    {
        public Project Project { get; set; }
        public IList<Employee> EmployeeList { get; set; }
    }
Now I'm going to pass instance of ProjectViewModel and an Employee object to my MVC controller. Here is the controller method.
        [HttpPost]
        public ActionResult Create(ProjectViewModel projectViewModel, Employee anotherEmployee)
        {
            return Content("done");
        }
This is the JavaScript code that we can use to call the controller method.
        var projectViewModel = {};

        var project = {};
        project.ProjectID = 1234;
        project.ProjectName = "Test Project";

        projectViewModel.Project = project;

        var employeeList = [];

        var employee1 = {};
        employee1.Code = "1111";
        employee1.Name = "Saranga";

        var employee2 = {};
        employee2.Code = "2222";
        employee2.Name = "Rathnayaka";

        employeeList.push(employee1);
        employeeList.push(employee2);

        projectViewModel.EmployeeList = employeeList;

        var employee3 = {};
        employee3.Code = "3333";
        employee3.Name = "Test User";

        $.ajax(
  {
      url: 'Project/Create',
      data: JSON.stringify({projectViewModel : projectViewModel, anotherEmployee : employee3}),
      contentType: 'application/json',
      dataType: 'json',
      type: 'POST',
      success: function (data) {
          alert("success");
      },
      error: function () { alert('error'); }
  });

Tuesday, October 25, 2011

Android Web Service Access Tutorial

In this post I'm going to illustrate how we can access web service in Android using ksoap2-android project that provides a lightweight and efficient SOAP library for the Android platform.

You can download the jar file from following link;

http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.8/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar

Here is the sample code that illustrate SOAP web service call. I have access a live web service ConvertWeight from http://www.webserviceX.NET/ which convert weight from one unit to another. I have set "envelope.dotNet = true;" in Line 53 since I'm accessing .NET web service. You can comment that line if your web service is not .NET one.

package com.sencide;
 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
 
public class AndroidWebService extends Activity {
  
    private final String NAMESPACE = "http://www.webserviceX.NET/";
    private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
    private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
    private final String METHOD_NAME = "ConvertWeight";
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      
        String weight = "3700";
        String fromUnit = "Grams";
        String toUnit = "Kilograms";
      
        PropertyInfo weightProp =new PropertyInfo();
        weightProp.setName("Weight");
        weightProp.setValue(weight);
        weightProp.setType(double.class);
        request.addProperty(weightProp);
         
        PropertyInfo fromProp =new PropertyInfo();
        fromProp.setName("FromUnit");
        fromProp.setValue(fromUnit);
        fromProp.setType(String.class);
        request.addProperty(fromProp);
         
        PropertyInfo toProp =new PropertyInfo();
        toProp.setName("ToUnit");
        toProp.setValue(toUnit);
        toProp.setType(String.class);
        request.addProperty(toProp);
        
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
 
        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            Log.i("myApp", response.toString());
    
            TextView tv = new TextView(this);
            tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
            setContentView(tv);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

You have to add INTERNET permission to AndroidManifest.xml as follows;

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sencide"
      android:versionCode="1"
      android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidWebService"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

You can download the source code of above project (Password:sara).

I have updated my previous code in the post Android Login Screen Using HttpClient to authenticate users from web service. There I have illustrated how you can start new activity if the login is successful.

You can download the updated source code with sample .NET web service application (Password:sara).

Tuesday, June 21, 2011

Android Login Screen Using HttpClient

I have updated this code to use web service and open new screen if the login is successful in my post Android Web Service Access Tutorial.

In Android we can use HTTP POST request with org.apache.http.client.HttpClient to post data to a URL. This sample project illustrate how we can post data to a URL and get the response.


package com.sencide;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidLogin extends Activity implements OnClickListener {
 
 Button ok,back,exit;
 TextView result;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Login button clicked
        ok = (Button)findViewById(R.id.btn_login);
        ok.setOnClickListener(this);
        
        result = (TextView)findViewById(R.id.lbl_result);
        
    }
    
    public void postLoginData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        
        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://www.sencide.com/blog/login.php");

        try {
            // Add user name and password
         EditText uname = (EditText)findViewById(R.id.txt_username);
         String username = uname.getText().toString();

         EditText pword = (EditText)findViewById(R.id.txt_password);
         String password = pword.getText().toString();
         
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.w("SENCIDE", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);
            
            String str = inputStreamToString(response.getEntity().getContent()).toString();
            Log.w("SENCIDE", str);
            
            if(str.toString().equalsIgnoreCase("true"))
            {
             Log.w("SENCIDE", "TRUE");
             result.setText("Login successful");   
            }else
            {
             Log.w("SENCIDE", "FALSE");
             result.setText(str);             
            }

        } catch (ClientProtocolException e) {
         e.printStackTrace();
        } catch (IOException e) {
         e.printStackTrace();
        }
    } 
  
    private StringBuilder inputStreamToString(InputStream is) {
     String line = "";
     StringBuilder total = new StringBuilder();
     // Wrap a BufferedReader around the InputStream
     BufferedReader rd = new BufferedReader(new InputStreamReader(is));
     // Read response until the end
     try {
      while ((line = rd.readLine()) != null) { 
        total.append(line); 
      }
     } catch (IOException e) {
      e.printStackTrace();
     }
     // Return full string
     return total;
    }

    @Override
    public void onClick(View view) {
      if(view == ok){
        postLoginData();
      }
    }

}

Following code is the content of mail.xml file that is used in the above code.

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:id="@+id/txt_username" android:layout_y="132dip" android:layout_x="128dip"></EditText>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:password="true" android:id="@+id/txt_password" android:layout_x="128dip" android:layout_y="192dip"></EditText>
<Button android:layout_width="100px" android:layout_height="wrap_content" android:id="@+id/btn_login" android:layout_x="178dip" android:layout_y="252dip" android:text="Login"></Button>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_username" android:text="User Name" android:layout_x="37dip" android:layout_y="150dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_password" android:text="Password" android:layout_y="207dip" android:layout_x="50dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_top" android:textSize="16sp" android:typeface="sans" android:text="Please Loggin First" android:layout_x="29dip" android:layout_y="94dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_y="312dip" android:layout_x="50dip" android:id="@+id/lbl_result"></TextView>
</AbsoluteLayout>
Following code is the content of AndroidManifest.xml file that is used in this project. There note that I have add the line <uses-permission android:name= "android.permission.INTERNET".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sencide"
      android:versionCode="1"
      android:versionName="1.0">

 <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidLogin"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

You can download the source code of above project (Password:sara).

Wednesday, June 8, 2011

SQL Server Authentication enabling using Microsoft SQL Server Management Studio

If you install the Microsoft SQL Server using Windows Authentication mode, the "sa" account is disabled by default. So if you plan to use SQL Server Authentication, you have to enable the "sa" account. This tutorial tells you how to enable the "sa" account.

1. First, Login to the SQL Server Management Studio using Windows Authentication. Right-click on the database instance, and go to Properties.

2. Then on Properties page, click on Security and select SQL Server and Windows Authentication mode, and click on OK to close the Server Properties page.

3. Now you will get dialog box saying that you should restart your SQL Server to take the changes take effect. Is is not done yet, you have to done one more thing to enable the "sa" login.

4. Now expand Security folder and go to Logins. You can see the "sa" account is disabled when you install SQL Server using Windows Authentication mode.

5. Then right-click on the "sa" account and go to Login Properties. There you can set a password for the "sa" account.


6. Click on the Status page. There you can see the "sa" account is disabled by default. Click on the Enabled button to enable it. Then click on Ok to close the "sa" Login Properties.

Now "sa" account is enabled and you can login to the SQL instance using the "sa" account after restarting the SQL Server.

Note: SQL Server service needs to be restarted to make this change effective.

Tuesday, October 5, 2010

Install IIS in Windows 7 or Vista

This tutorial discuss how you can enable (Internet Information Service) IIS in Windows 7 or Windows Vista. I have provided screen-shots so that you can easily understand.

First go to control panel and select Programs.


Then select Internet Information Services. (If you plan to run web services you have to select ASP.NET under Application Development Features as following figure)

Now you have enabled IIS and try "http://localhost" in your browser and you will get following page.

Wednesday, September 29, 2010

Create Simple Web Service with Visual Studio

This tutorial explains how we can create simple Web Services using Visual Studio.

1. Create the Web Service

First create new project and select "New ASP.NET Web Service Application" and I'm giving the name "MyFirstWebService" to it, you can give any name to your project.

Now you can see auto generated code that you can add methods to create your web service. You can see simple method "HelloWorld" and in this sample code I have removed it.

I'm going to add simple method called "simpleMethod" which takes a string as an input and add "Hello" to beginning of that string. Now the code will appear like bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace MyFirstWebService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string simpleMethod(String srt)
        {
            return "Hello "+srt;
        }

        [WebMethod]
        public int anotherSimpleMethod(int firstNum, int secondNum)
        {
            return firstNum + secondNum;
        }

    }
}

Then you can run your code and you can see the resulting page as bellow.

2. Create the Client Program

We have created our simple web service and we have to create small client program to use this web service. There you can open another instant of Visual Studio and create new "Console Application" project.

Then you have to add Service Reference so that you can access your web service. Here are the screen-shots.



Here you have to give the URL of the web service we created earlier. As I said before previously created web service application should be running on another instant of Visual Studio.

Note that I have set the "Web reference name" as "TestWeb".

Now you can update your client program using following code. Note the line 5 "using WebServiceTest.TestWeb;".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServiceTest.TestWeb;

namespace WebServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1 webservice = new Service1();
            string srt = webservice.simpleMethod("Saranga Rathnayake");
            Console.WriteLine(srt);
            Console.WriteLine(webservice .anotherSimpleMethod(4,3));
        }
    }
}

Now you can run the client program to see the result.

3. Publish Our Web Service in Internet Information Service (IIS)

Let's see how we can publish our web service in IIS. Otherwise you always need to run your web service application in separate VS instant. There first stop the web service application and go to the Solution Explore and Right Click on the project. Then select "Publish...".

Then the following window will appear and there you can directly publish to the IIS by selecting "Web Deploy" as the publishing method. But here I'm going to use the "File System as the publishing method. There you have to provide the target location. I have created new folder called "MyApp" in my D drive and selected it.

Now click "Publish" and check the "MyApp" folder. There you will be able to see Service1.asmx file, Web.config file and bin folder which contains the DLL file has been generated. Then copy this "MyApp" folder to "wwwroot" folder. You may find it in "C:\inetpub\wwwroot".

Now enable IIS in your computer and open IIS Manager. I'm going to add my service to Default Web Site. There Right Click on the "Default Web Site" and click "Add Application...".

There you will get following window. Now you can provide appropriate Alias (I have given testservice) and select the physical path of your application. There you can provide the path to the folder we copied previously as following figure and click Ok.

You have to make sure that the application pool identity has Read access to the physical path. So it is better if you copy your files to the "wwwroot" folder other than keep it in separate partition. Please check the following screen-shot

Now restart the IIS and goto http://localhost/testservice/Service1.asmx. You will be able to see the Web Service running.

Now you have published your web service in IIS and you can update the Client Program by giving the new Web Reference URL using Properties Window.

If you are interested in creating web services in java, please follow my post Create Web Service in Java Using Apache Axis2 and Eclipse

Saturday, February 20, 2010

Form Validation and Suggestions using JQuery & PHP

In this post I’m going to describe about a practical use of my previous article JQuery AJAX. Here I’m going to discuss how to validate a form and how to add auto suggests to a form using JQuery and PHP.

Download Source (Password : sara)

In the above I have given you the source code of the whole project which saves the collected data to a MySQL database. It is good if you have a basic knowledge about JavaScript and PHP to understand the codes. You can learn them very easily by referring w3schools.

Since this I’m using PHP and MySQL in the above project, you have to run the code in a server like XAMP or WAMP. In this example I’m going to illustrate with WAMP. If you have the downloaded source code, you can see a folder called "jquery_form" and within that you can find folders css,js,scripts and images. Also you can see a file called index.php.

First thing you have to do is copy the "jquery_form" folder to your WAMP server’s "www" folder. Then open the "dbc.php" file inside the "scripts" folder and change its attributes. If you already haven’t a database called "userdata" and you haven’t given a password for root account, you don’t need to make any changes.

<?php
$host = "localhost";
$dbname = "userdata";
$username = "root";
$password = "";
?>

Now do the following things when the WAMP server started. I’ll also mention the result of the given action here.

1. First run the "sql.php" file located in the "scripts" folder. The only thing you need to do is give the address to the file in the address bar. E.g. http://localhost/jquery_form/scripts/sql.php. This should be done when the first time you run the project.

I wrote this file to create a MySQL database with one table and needed fields to store the collected data. If you didn’t make changes to "dbc.php" file, there will be a databased called "userdata" and table called "details_user".

2. Then run the "index.php" file and fill the form correctly and submit. You will see your data in the database. If you try to give the same login name again, you will see the suggestions related to the name and birthday.

Let’s see the codes and check how we can add validation and suggestions. Here the JavaScript which do the above task is "validation.js" which is located in "js" folder. I’ll put the real line numbers in following piece of codes as they appear in actual file.

<title>JQuery Ajax Form | Saranga Rathnayake</title>

<!-- CSS -->
<link rel="stylesheet" href="css/styles.css" type="text/css"/>
<link type="text/css" href="css/jquery-ui-1.7.2.custom.css" rel="stylesheet" /> 

<!-- JavaScript -->
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script src="js/validation.js" type="text/javascript"></script>
<script type="text/javascript">
 $(function(){
  $('#datepicker').datepicker({
   dateFormat:'dd/mm/yy',
   changeMonth: true,
   changeYear: true,
   yearRange: '-90:+0',
   maxDate: '+0'
  });
 });
</script>
</head>
<div id="container">
<form id="logform" name="logform" class="logform" method="post" action="" >
<?php if(

Above lines are from the "index.php" file, there I have linked necessary CSS and JavaScipt files. You can see a JavaScipt code which use to DatePicker.

//On blur
 name.blur(validateNameAndSuggest);
 iname.blur(validateIName);
 address.blur(validateAddress);  
 email2.blur(validateEmail);
 nic.blur(validateNIC);
 phno.blur(validatePhNo);
 email.blur(validateLoginEmailAndSuggest); 
 imgveri.blur(validateImg); 
 
 // on changed
 bday.change(validateDOB);
 
 //On key press
 //name.keyup(validateName);
 //iname.keyup(validateIName); 
In the above lines I have called the validation functions in "blur" and "keyup" events. I have commented the "keyup" events, if you want them you can uncomment. Then I’ll show you how the validation works.
function validateNIC(){
  var a = $("#nic").val();
  var filter = /^[0-9]{9}[v|V]$/;
  if(filter.test(a)){
   nic.removeClass("error");
   nicInfo.text("");
   nicInfo.removeClass("error");
   return true;
  }
  //if it's NOT valid
  else{
   nic.addClass("error");
   nicInfo.text("Type a valid NIC please, format: xxxxxxxxxV");
   nicInfo.addClass("error");
   return false;
  }
 } 

In the above code I have use Regular Expressions to make the validation more easier. If the Regular Expression dose not match with the input, then I have changed the CSS Class of the text box which change its color. And also I have added some information about the error. Then let’s see how suggestions work.

function suggestLogginName(){
  
  var name = $("#fname").val();
  var bday = $("#datepicker").val();
  
  if(validateName() && validateDOB()){
   $.post("scripts/isValiedName.php",  { loginName:name, birthday:bday,suggestion:"OK" },
     function(data){
     emailInfo.html(data);
   }); 
  }

 } 

The above function calls if the entered login name exist in the database. It will post the Full Name and Birthday to "isValiedName.php" file and that PHP file will return suggested names.