AkraTech

Impacting lives through technology - www.akra-tech.com

CRUD Using Dapper a lightweight ORM Framework

clock June 4, 2013 19:58 by author AkraTech

 

Dapper.NET is a Micro ORM written by the developers behind Stack Overflow. It is simple to use, and is compatible with any database which implements a provider for .NET (i.e.: provides an implementation of the IDbConnection interface).We have been using Dapper.Net extensively for our projects.

Here is Small Example to Implement Dapper.NET 

We have an Entity class Employee with following properties: 

public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public string Salary { get; set; }
}

 

Ex:1 This is example shows how to retrieve values from database using Dapper

 

public IEnumerable<Employee> SelectEmployeeDetails()
{
using (IDbConnection connection = OpenConnection())
    {
        const string query = "SELECT EmployeeID, " +
              " Name,  Location , Salary FROM Employee " ;
        return connection.Query<Employee>(query);
    }
}

Ex2: Instead of writing inline query statements here it demonstrates by using stored procedure

 

public int AddNewEmployee(Employee value)
        {
            var parameters = new DynamicParameters();
            parameters.Add("@Name", value.Name, DbType.Int32, ParameterDirection.Input);
            parameters.Add("@Location",value.Location, DbType.String, ParameterDirection.Input);
            using (IDbConnection connection = OpenConnection ())
            {
                const string storedProcedure = "dbo.DeleteUsers";
               int rowsaffected = connection.Execute(storedProcedure, parameters,                                                                               commandType:CommandType.StoredProcedure);
               return rowsaffected;
            }
        }

 

 

Ex3: Dapper.NET supports Transactions. For Example, the following code deletes the employee record from company  table as well as  the employee table:

 

public int DeleteEmployeeRecord(Employee value)
{
try
{
    using (IDbConnection connection = OpenConnection())
    {               
        const string deleteEmployeeFromCompany = "DELETE FROM Company " +
                                                                                      "WHERE EmployeeID = @ EmployeeID ";
        const string deleteEmployeeDetails = "DELETE FROM Employee" +
                                                                           " WHERE EmployeeID = @ EmployeeID ";
        IDbTransaction transaction = connection.BeginTransaction();
        int rowsAffected = connection.Execute(deleteEmployeeFromCompany, new { EmployeeID = value.EmployeeID}, transaction);
        rowsAffected += connection.Execute(deleteEmployeeDetails,  new { EmployeeID = value.EmployeeID}, transaction);
        transaction.Commit();
        return rowsAffected;
    }
 }
catch (Exception ex)
     {
         transaction.Rollback();
     }
 }

 



Start / Stop Windows Services using C# / ASP.NET

clock May 28, 2013 19:27 by author AkraTech

Usually applications have windows services to be started / stopped , why have a Windows Administrator login and start / stop a service when this can be done remotely from the Asp.net Web site itself?

To accomplish this you need to add System.ServiceProcess reference in your application. This namespace holds ServiceController Class to access the windows service. By default, IIS application runs under ASP.NET account which doesn't have access rights permission to windows service. So, main thing is  Impersonation. You need to impersonate the application/part of the code with the User Credentials which is having proper rights and permission to access the windows service. Unless, If you try to access windows service it will generate "access denied" error. To Overcome this you can  impersonate the application by adding Identity tag in web.cofig as:

<identity impersonate="true" userName="XYZ" password="XYZ"/>

under System.Web and the user impersonated should have rights to access the Windows Service

You can just call ServiceController class  Start() and Stop() methods to start or stop a window service.

 

 

//Code to start the windows service

public void StartService()
    {
        try
        {
            ServiceController sc = new ServiceController();
             sc.ServiceName = "Servicename";
            if (sc.Status != ServiceControllerStatus.Running && sc.Status != ServiceControllerStatus.StartPending)
            {
                sc.Start();
            }
      }
        catch (Exception ex)
        {
             throw ex;
        }
 }

//Code to stop the windows service

 public void Stopservice()
    {
        try
        {
            ServiceController sc = new ServiceController();            
            sc.ServiceName = "Servicename";
            if (sc.Status == ServiceControllerStatus.Running)
            {
                sc.Stop();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
  }

//Code to check the status of the windows service

 public List<string> ServiceStatus()
    {
        try
        {
	    List<string> serviceList = new List<string>();
            string[] services = new string[] { "service1", "service2", "service3", "service4" };
           ServiceController sc = new ServiceController();
	    foreach (string servicesname in services)
            {
                sc.ServiceName = servicesname;
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    serviceList.Add("Stopped");
                  
                }
                else { serviceList.Add("Running"); }
            }
            return serviceList;
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
 

 

 

 



C# Visitor Pattern - A simple example

clock May 25, 2013 15:36 by author AkraTech

Visitor Pattern

Developers find it difficult to understand and implement the Visitor Pattern.Below is a simple example which shows how to implement and use the Visitor Pattern in C#.

 

Visitor Design pattern is a way of Injecting Operations into a concrete entity without modifying its object structure . A concrete Object is made “visitable” and Visitor “visits” the concrete object to perform operations

Class Diagram

 

Source Code

Visitor Interface

 

 interface IVisitable    {

        void Accept(IIncomeVisitor visitor);

    }

 

Visitable Interface

interface IVisitable    {

        void Accept(IIncomeVisitor visitor);

    }

A Sample Visitor

     class TaxVisitor : IIncomeVisitor

    {

        double tax;

        public void Visit(Income i)

        {

            tax = i.TotalIncome * 0.40;

        }

 

        public double ValueDeducted

        {

            get { return tax; }

        }

    }

 A  Concrete "Visitable" Class

 

    class Income : IVisitable

    {

        int m_totalIncome = 0;

 

        public int TotalIncome

        {

            get { return m_totalIncome; }

            set { m_totalIncome = value; }

        }

 

        public Income(int totalIncome)

        {

            m_totalIncome = totalIncome;

        }

 

        public void Accept(IIncomeVisitor visitor)

        {

            visitor.Visit(this);

        }

    }

 

Sample Code attached

 



Calendar

<<  December 2017  >>
MoTuWeThFrSaSu
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

View posts in large calendar

Page List

    RecentComments

    None

    Sign In