Friday 28 November 2014

C# Important Code Snippets and Utility Function


      public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }
        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

       public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
 
      public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
      public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
     public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }
  
  public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }
  
  public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
  
   public class PGUtil
    {
        private static WindowsImpersonationContext impersonationContext;

        public PGUtil()
        {
        }

        public static string[] AppendArrayElement(string[] array, object param)
        {
            string[] strArrays;
            if ((array == null ? false : param != null))
            {
                List list = array.ToList();
                list.Add(param.ToString());
                strArrays = list.ToArray();
            }
            else
            {
                strArrays = array;
            }
            return strArrays;
        }

        public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }

      

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
        public static extern bool CloseHandle(IntPtr handle);

        public static DataSet CreateDummyScalarDataSet(string columnValue)
        {
            return PGUtil.CreateDummyScalarDataSet(null, columnValue);
        }

        public static DataSet CreateDummyScalarDataSet(string columnName, string columnValue)
        {
            DataSet ds = null;
            try
            {
                ds = new DataSet();
                DataTable tbl = new DataTable();
                tbl.Columns.Add("Id");
                tbl.Rows.Add(new object[] { columnValue });
                ds.Tables.Add(tbl);
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return ds;
        }

        public static int dateComparison(DateTime date1, DateTime date2)
        {
            return DateTime.Compare(date1, date2);
        }

        

        public static string FormatCSVstring(string inputString)
        {
            string str;
            string outPutString = string.Empty;
            try
            {
                inputString = PGUtil.escapeSpecialChar(inputString);
                string[] arrData = inputString.Split(new char[] { ',' });
                for (int i = 0; i < (int)arrData.Length; i++)
                {
                    string tempString = string.Format("'{0}'", arrData[i]);
                    outPutString = (i != 0 ? string.Concat(outPutString, ",", tempString) : tempString);
                }
                str = outPutString;
            }
            catch
            {
                str = inputString;
            }
            return str;
        }

        public static string FormatOracleDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("dd-MMM-yyyy");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(string date)
        {
            string str;
            string str1;
            try
            {
                if (!date.Equals("NULL"))
                {
                    if (date == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = PGUtil.ToDateTime(date).ToString("yyyy-MM-dd");
                    }
                    str = str1;
                }
                else
                {
                    str = null;
                }
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("yyyy-MM-dd");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatString(string formatString, params string[] values)
        {
            string str;
            if (!string.IsNullOrEmpty(formatString))
            {
                if (values == null)
                {
                    throw new ArgumentNullException("values");
                }
                for (int index = 0; index < (int)values.Length; index++)
                {
                    formatString = formatString.Replace(string.Concat("{", index, "}"), values[index]);
                }
                str = formatString;
            }
            else
            {
                str = formatString;
            }
            return str;
        }

        public static DateTime GetCurrentIndiaDate()
        {
            return DateTime.UtcNow.AddHours(5.5);
        }

        public static TimeSpan GetCurrentIndiaTime()
        {
            return DateTime.UtcNow.AddHours(5.5).TimeOfDay;
        }

        public static object GetDataFromSession(string key)
        {
            object returnValue = null;
            try
            {
                returnValue = HttpContext.Current.Session[key];
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return returnValue;
        }

        public static T GetDataFromSession(string key)
        {
            T item;
            T returnValue = default(T);
            try
            {
                if (HttpContext.Current.Session[key] is T)
                {
                    item = (T)HttpContext.Current.Session[key];
                    return item;
                }
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            item = returnValue;
            return item;
        }

        public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
 

        public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }

        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

        public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

       
        public static string[] QTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (utcNow.Month - 1) / 3 + 1;
            utcNow = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(utcNow.Year, (quarterNumber - 1) * 3 + 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }

        public static void ReDimArray(ref string[] sourceArray, int newLength)
        {
            if (newLength >= (int)sourceArray.Length)
            {
                string[] newArray = new string[newLength];
                for (int i = 0; i < (int)sourceArray.Length; i++)
                {
                    newArray[i] = sourceArray[i];
                }
                sourceArray = newArray;
            }
        }

       

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body)
        {
            bool flag = PGUtil.SendEmail(server, AuthUser, password, subject, from, recipients, body, null);
            return flag;
        }

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }

        public static int timeComparison(TimeSpan time1, TimeSpan time2)
        {
            return TimeSpan.Compare(time1, time2);
        }

        public static bool ToBoolean(object str)
        {
            bool flag;
            try
            {
                flag = Convert.ToBoolean(str);
                return flag;
            }
            catch
            {
            }
            flag = false;
            return flag;
        }

        public static DateTime ToDateTime(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            string strDate = str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(strDate);
            }
            catch
            {
            }
            return dateTime;
        }

        public static string ToDBString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) || string.IsNullOrEmpty(obj.ToString()) ? "NULL" : obj.ToString());
        }

        public static double ToDouble(object str)
        {
            double num;
            try
            {
                num = Convert.ToDouble(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static int ToInt(object str)
        {
            int num;
            try
            {
                num = Convert.ToInt32(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static long ToInt64(object str)
        {
            long num;
            try
            {
                num = Convert.ToInt64(str);
                return num;
            }
            catch
            {
            }
            num = (long)0;
            return num;
        }

        public static string ToString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) ? "" : obj.ToString());
        }

        public static bool TryParseDate(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            bool flag = true;
            str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(str);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool tryParseInt(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToInt32(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseRealNumber(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToDouble(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseWholeNumber(object num)
        {
            bool flag1;
            bool flag = true;
            if (!(num as string).Contains("."))
            {
                try
                {
                    Convert.ToInt32(num);
                }
                catch
                {
                    flag = false;
                }
                flag1 = flag;
            }
            else
            {
                flag1 = false;
            }
            return flag1;
        }

        public static void UndoImpersonation()
        {
            PGUtil.impersonationContext.Undo();
        }

        public static string[] YTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int year = utcNow.Year;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }
  

     private string GetActiveDirUserDetails(string userid)
    {
 System.DirectoryServices.DirectoryEntry dirEntry = default(System.DirectoryServices.DirectoryEntry);
 System.DirectoryServices.DirectorySearcher dirSearcher = default(System.DirectoryServices.DirectorySearcher);
 string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
 try {
  dirEntry = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainName);
  dirSearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
  dirSearcher.Filter = "(samAccountName=" + userid + ")";

  dirSearcher.PropertiesToLoad.Add("GivenName");
  //Users e-mail address
  dirSearcher.PropertiesToLoad.Add("sn");
  //Users last name
  SearchResult sr = dirSearcher.FindOne();
  //return false if user isn't found 
  if (sr == null) {
   return false;
  }
  System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();
  dynamic userFirstLastName = de.Properties("sn").Value.ToString() + ", " + de.Properties("GivenName").Value.ToString();
  return userFirstLastName;
 // return false if exception occurs 
 } catch (Exception ex) {
  return ex.Message;
 }
    }
 
 }
  
  
  
  
  

Saturday 22 November 2014

STEP BY STEP WEBAPI FOR BEGINEERS

Asp.Net Web API Overview

download code from here:WebApi Example
Note:please change database connection in web.config
Asp.Net Web API is a framework build on .NET for building HTTP services that can be consumed by a wide range of clients including browsers, mobiles, iphone ...... If you know MVC then you can are already know 75%  webApi. It contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container/ dependency injection. Remember,It is a part of the core ASP.NET platform and not MVC and can be used with MVC and Web applications like Asp.Net WebForms.

ASP.NET Web API Features

  1. It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
  2. Responses have an Accept header and HTTP status code.
  3. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
  4. It has default  support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  5. It can be hosted on IIS and in  application also
  6. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.
  7. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
  8. It is light weight architecture and good for devices which have limited bandwidth like smart phones
Point to be Noted:- You can use WebAPI only with HTTP which make it different from WCF ,which supports all protocols
So, we can say that using ASP.NET Web API, we can create HTTP services
  • WebAPI is non-SOAP based like plain XML or JSON string.
  • using full features of HTTP.So, can reach broader range of clients (browsers and mobile devices...).
Following is the typical ASP.NET Web API processing architecture.

What is the difference between Asp.Net Web API and Asp.Net MVC

Asp.Net MVC is used to develop web applications that returns both views and data but Asp.Net Web API is used to create HTTP services with easy way that returns only data not view like in MVC.
Apart,Web API helps to build true REST-FUL services over the .NET Framework and it also support CONTENT NEGOTIATION which mean deciding or choosing the best response format data like (JSON,XML,ATOM or any other formatted data) that could be acceptable by the client.


CREATE ASP.NET WEBAPI

  • Open Visual Studio/Visual Express and create “New Project” i.e. File -> New Project.
  • Choose “ASP.NET MVC 4 Web Application” template and name project as “WebAPIExample”.
  • When you click “OK” button, a new window will appear for selecting a sub-template. Actually for ASP.NET MVC 4 Web Application, we have multiple sub-options i.e. Empty, Internet Application, Web API etc.
  • Choose “Web API” and simply press “OK” button.

CREATE REAL TIME WEBAPI :

Let us modify existing service and create webapi service to perform CRUD operation on User:-
we need to prepare the model.
  • Right click on the “Model” folder and fallow below steps
7

We are done with domain creation.
CREATE CONTROLLER
Controller class plays an important role, because request coming from client hits the controller first. Then the controller decides which model to use to serve the incoming request. So, in order to add a controller:
  • Right click on the “Controller” folder and choose “Controller” under “Add” from the context menu as shown in figure.
  • Name the controller as “UserController”.

So you have created Controller which looks like shown above.
Before you continue,Just think what all Actions/Methods you need .I will assume that we need to create WebAPI Service Which will
  • Get All Users

  • Get User based on Id

  • Insert User

  • Delete User

 Let We first Create Data Access related Class for above functionality

Considering you as begineers in WebApi ,please fallow  below steps
  1.  Go to Model folder and add folder with "DAL" name.
  2. Right Click on folder and add class with name UserRepository as show below
     public class UserRepository
        {
            p10Entities p10entities;
            public List DbGetAllUsers()
            {
                p10entities = new p10Entities();
    
                return p10entities.users.ToList();
    
            }
            public User DBGetUser(string username)
            {
                User user = p10entities.users.SingleOrDefault(u => u.UserName == username);
                return user;
            }
    
            public string DBRegisterUser(User user)
            {
                p10entities.users.Add(user);
                int recSaved = p10entities.SaveChanges();
                if (recSaved == 1)
                    return "Saved";
                else
                    return "Failed";
    
            }
            public void RemoveUser(int id)
            {
             // code for deletion
            }
    
            public bool UpdateUser(User userrname)
            {
               //code for updation
                return true;
            }
        }
    
    

    So,in above code youy will see " p10Entities". what is it ? DbContext :Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model. So,we are done with dataAccess related functionality,now we have to expose it to external world in the form of JSON or XML
  3. Go to Controller which we created at the begining and add below code
     public class UserController : ApiController
        {
            UserRepository userRepository;
            public HttpResponseMessage GetAllUsers()
            {
               userRepository = new UserRepository();
               var users=userRepository.DbGetAllUsers();
               var resp = new HttpResponseMessage(HttpStatusCode.OK);
               resp.Content = new ObjectContent>(
                users, new JsonMediaTypeFormatter());
               resp.Headers.ConnectionClose = true;
               resp.Headers.CacheControl = new CacheControlHeaderValue();
               resp.Headers.CacheControl.Public = true;
               return resp;
            }
            public HttpResponseMessage UserByUserName(string username)
            {
                userRepository = new UserRepository();
                var users = userRepository.DbGetUser(username);
                var resp = new HttpResponseMessage(HttpStatusCode.OK);
                resp.Content = new ObjectContent(
                                        users, new JsonMediaTypeFormatter());
                resp.Headers.ConnectionClose = true;
                resp.Headers.CacheControl = new CacheControlHeaderValue();
                resp.Headers.CacheControl.Public = true;
                return resp;
            }       
            public string AddUser(User user)
            {
                userRepository = new UserRepository();
                userRepository.DbAddUser(user);
                return "Added";
            }
            public string Delete(string id)
            {
                userRepository = new UserRepository();
                userRepository.DbRemoveUser(id);
                return "Deleted";
            }
        }
    
  4. Finally, just build your solution and try to put API's in action like shown below.

Next we will see how to clean up code and use DEPENDENCY INJECTION AND UNIT OF WORK Patterns..

HOW TO BUY ,CREATE & HOST OR DEPLOY YOUR OWN WEBSITE

Introduction A website is a collection of Web pages, images, videos or other digital assets that is hosted on...