Thursday 22 January 2015

Web API using Stored Procedures and passed optional parameters

Web API using Stored Procedures  and passed optional parameters :


Web API using Stored Procedures :

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;
using Sample.API.Database;
using Sample.API.Models;
using Sample.API;
using Sample.API.Controllers;
using Sample.Common;
using System.Web.Http;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Entity.Core.EntityClient;
using System.Collections;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Reflection;
using System.Net;

namespace Sample.Controllers
{
    //[RoutePrefix("users/profileSearch/{keyword}")]
    public class profileSearchController : TGApiController
    {

        #region DTO & Validation
        public class profileSearchRequest
        {
            public string keyword { get; set; }
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string summary { get; set; }            
            public int userId { get; set; }           
            public int rowfrom { get; set; }
            public int rowto { get; set; }          
            public int count { get; set; }
           
        }

        public class profileSearchResponseJSON
        {
            public int rowfrom { get; set; }
            public int rowto { get; set; }
            public int count { get; set; }
            public int pageSize { get; set; }
            public int pageing { get; set; }
            public List<profileSearchResponse> profilesearch { get; set; }
            public List<profileSearchlistsParameter> searchParameter { get; set; }
           
        }
       
        public class profileSearchResponse
        {
            public long id { get; set; }
            public long userId { get; set; }
            public string currentTitle { get; set; }
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string summary { get; set; }         
            public string emailAddress { get; set; }          
            public string pictureURL { get; set; }
            public DateTime? created { get; set; }
            public string profileName { get; set; }          
            public string city { get; set; }
            public string firstNames { get; set; }
        }
        
        #endregion     
        
        //Route
        [Route("search/profileSearch")]
        public dynamic Post(profileSearchRequest request)
        {
            var lstRecSearch = new List<profileSearchResponse>();
            string Cou = WebConfigurationManager.AppSettings["RecSearchpagesize"];
            string pictureHostUrl = WebConfigurationManager.AppSettings["ProfilePictureURL"];
            int PageSize = Int32.Parse(Cou.ToString());

            List<SqlParameter> objSqlParams = new List<SqlParameter>();
            string strFiled = string.Empty;
            var searchlistParameter = new profileSearchlistsParameter();
            List<profileSearchlistsParameter> lstsearchParameter = new           List<profileSearchlistsParameter>();
            if (request.keyword != null && request.keyword != "")
            {
                strFiled = " @keyword,";
                var keywordParm = new SqlParameter { ParameterName = "keyword", Value = request.keyword };
                objSqlParams.Add(keywordParm);
                searchlistParameter.keyword = request.keyword;
            }
            if (request.firstName != null && request.firstName != "")
            {
                strFiled += "@firstName,";
                var firstNameParm = new SqlParameter { ParameterName = "firstName", Value = request.firstName };
                objSqlParams.Add(firstNameParm);
                searchlistParameter.firstNames = request.firstName;
            }
            if (request.lastName != null && request.lastName != "")
            {
                strFiled += "@lastName,";
                var firstNameParm = new SqlParameter { ParameterName = "lastName", Value = request.lastName };
                objSqlParams.Add(firstNameParm);
                searchlistParameter.mostplacelastName = request.lastName;
            }
            if (request.summary != null && request.summary != "")
            {
                strFiled += "@summary,";
                var firstNameParm = new SqlParameter { ParameterName = "summary", Value = request.summary };
                objSqlParams.Add(firstNameParm);
                searchlistParameter.summary = request.summary;
            }

            if (request.userId != 0 && request.userId != null)
            {
                strFiled += "@userId,";
                var firstNameParm = new SqlParameter { ParameterName = "userId", Value = request.userId };
                objSqlParams.Add(firstNameParm);
                searchlistParameter.userId = request.userId;
            }
            
            List<profileSearchResponse> getlist = null;
            var _list = new profileSearchResponseJSON();
 //Stored Procedures Call
            SampleDb.Database.Connection.Open();
            DbCommand cmd = SampleDb.Database.Connection.CreateCommand();
            if (objSqlParams.Count != 0)
            {
 //Stored Procedures Name
                cmd.CommandText = "searchprofiles";
                cmd.Parameters.AddRange(objSqlParams.ToArray<SqlParameter>());
                cmd.CommandType = CommandType.StoredProcedure;
                using (var reader = cmd.ExecuteReader())
                {
//MapToList
                    getlist = reader.MapToList<profileSearchResponse>();
                }
            }
            var listprofile = new List<profileSearchResponse>();

            if (getlist != null)            {
               
                foreach (var lstSearch in getlist.ToList())
                {
                   string pictureUrl = string.Empty;
                        if (lstSearch.pictureURL != null)
                        {
                            pictureUrl = pictureHostUrl + lstSearch.pictureURL;
                        }
                        var response = new profileSearchResponse()
                        {
                             id = lstSearch.id,
                            userId = lstSearch.userId,
                            firstName = lstSearch.firstName,
                            lastName = lstSearch.lastName,
                            currentTitle = lstSearch.currentTitle,
                            summary = lstSearch.summary,                       
pictureURL = pictureUrl,
                            created = lstSearch.created,
                            profileName = lstSearch.profileName,                           
                            city = lstSearch.city,
                            firstNames = lstSearch.firstNames                          
                        };
                        listprofile.Add(response);
                   
                }

                _list.pageSize = PageSize;
                _list.pageing = _list.count / PageSize;
                _list.profilesearch = listprofile;
                _list.count = getlist.Count();             
                List<profileSearchResponseJSON> lstprofileSearch = new List<profileSearchResponseJSON>();
                lstprofileSearch.Add(_list);
                return lstprofileSearch;
            }
            else
            {

                _list.pageSize = PageSize;
                _list.pageing = _list.count / PageSize;
                _list.profilesearch = listprofile;               
                _list.count = _list.profilesearch.Count();
                List<profileSearchResponseJSON> lstprofileSearch = new List<profileSearchResponseJSON>();
                lstprofileSearch.Add(_list);
                return lstprofileSearch;
            }

        }
}

}

//MapToList


 public static List<T> MapToList<T>(this DbDataReader dr) where T : new()
        {
            if (dr != null && dr.HasRows)
            {
                var entity = typeof(T);
                var entities = new List<T>();
                var propDict = new Dictionary<string, PropertyInfo>();
                var props = entity.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                propDict = props.ToDictionary(p => p.Name.ToUpper(), p => p);

                while (dr.Read())
                {
                    T newObject = new T();
                    for (int index = 0; index < dr.FieldCount; index++)
                    {
                        if (propDict.ContainsKey(dr.GetName(index).ToUpper()))
                        {
                            var info = propDict[dr.GetName(index).ToUpper()];
                            if ((info != null) && info.CanWrite)
                            {
                                var val = dr.GetValue(index);
                                info.SetValue(newObject, (val == DBNull.Value) ? null : val, null);
                            }
                        }
                    }
                    entities.Add(newObject);
                }
                return entities;
            }
            return null;
        }


Run Program :
using Fiddler
http://localhost:1234/search/Search

Type:Post

User-Agent: Fiddler
Content-Type: application/json;charset=UTF-8
Host: localhost:5321
Content-Length: 18

//Passed Optional parameter 

{"keyword":"test","firstname":"aaa"} 
             (or)
{"keyword":"test"}

Thursday 8 January 2015

Web API using Stored Procedures and passed optional parameters

Web API using Stored Procedures  and passed optional parameters :


Web API using Stored Procedures :


using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;
using Sample.API.Database;
using Sample.API.Models;
using Sample.API;
using Sample.API.Controllers;
using Sample.Common;
using System.Web.Http;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Entity.Core.EntityClient;
using System.Collections;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;

namespace Sample.Controllers
{
    //[RoutePrefix("users/ProfileSearch/{keyword}")]
    public class ProfileSearchController : SampleApiController
    {

        #region DTO & Validation
        public class ProfileSearchRequest
        {
            public string keyword { get; set; }
public string firstName { get; set; }
            public string lastName { get; set; }
            public string summary { get; set; } 
            public int rowfrom { get; set; }
            public int rowto { get; set; }      
public int count { get; set; }

        }

        public class ProfileSearchResponseJSON
        {
            public int rowfrom { get; set; }
            public int rowto { get; set; }
            public int count { get; set; }
            public int pageSize { get; set; }
            public int pageing { get; set; }
            public List<ProfileSearchResponse> Profilesearch { get; set; }


        }
        public class ProfileSearchResponse
        {
            public long id { get; set; }
            public long userId { get; set; }
            public string keyword { get; set; }
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string summary { get; set; }          
            public string emailAddress { get; set; }
            public string pictureURL { get; set; }
            public DateTime? created { get; set; }
            public string profileName { get; set; }
            public string profileLI { get; set; }           
            public string city { get; set; }         
            }
        #endregion
//Route
        [Route("search/ProfileSearch")]
        public dynamic Post(ProfileSearchRequest request)
        {
            var lstRecSearch = new List<ProfileSearchResponse>();

            List<SqlParameter> objSqlParams = new List<SqlParameter>();
            string strFiled = string.Empty;

//optional parameters Set Wep Api

            if (request.keyword != null)
            {
             
                strFiled = " @keyword,";
                var keywordParm = new SqlParameter { ParameterName = "keyword", Value = request.keyword };
                objSqlParams.Add(keywordParm);
            }
            if (request.firstname != null && request.firstname!="")
            {
                strFiled+="@firstname,";
                var firstnameParm = new SqlParameter { ParameterName = "firstname", Value = request.firstname };
                objSqlParams.Add(firstnameParm);
            }
            if (request.lastname != null)
            {
                strFiled += "@lastname,";
                var firstnameParm = new SqlParameter { ParameterName = "lastname", Value = request.lastname };
                objSqlParams.Add(firstnameParm);
            }
            if (request.summary != null)
            {
                strFiled += "@summary,";
                var firstnameParm = new SqlParameter { ParameterName = "summary", Value = request.summary };
                objSqlParams.Add(firstnameParm);
            }
           
            if (request.city !=null)
            {
                strFiled += "@city,";
                var firstnameParm = new SqlParameter { ParameterName = "city", Value = request.city };
                objSqlParams.Add(firstnameParm);
            }
            
         //Stored Procedures Call
            var getlist = SampleDb.Database.SqlQuery<ProfileSearchResponse>("Exec [searchProfiles] " + strFiled.TrimEnd(','), objSqlParams.ToArray());

            var _list = new ProfileSearchResponseJSON();

            string Cou = WebConfigurationManager.AppSettings["RecSearchpagesize"];
            int PageSize = Int32.Parse(Cou.ToString());
             _list.pageSize = PageSize;
            _list.pageing = _list.count / PageSize;

            _list.Profilesearch = getlist.ToList();
            _list.count = _list.Profilesearch.Count();
            List<ProfileSearchResponseJSON> lstProfileSearch = new List<ProfileSearchResponseJSON>();
            lstProfileSearch.Add(_list);
            return lstProfileSearch;
           
        }
      }

}



Run Program :
using Fiddler
http://localhost:1234/search/Search

Type:Post

User-Agent: Fiddler
Content-Type: application/json;charset=UTF-8
Host: localhost:5321
Content-Length: 18

//Passed Optional parameter 

{"keyword":"test","firstname":"aaa"} 
             (or)
{"keyword":"test"}



Thursday 1 January 2015

MVC - Entity Framework using ConnectionExtension (Insert,update,selet,Delete)

MVC - Entity Framework using Connection Extension (Insert,update,selet,Delete) :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FluentValidation;
using API.Database;
using API.Models;


namespace API.Controllers
{
    [RoutePrefix("users/{user_id:long}/profile")]
    public class UserprofileController : ApiController
    {
        // GET: userprofile

        #region DTO & Validation
        public class UserprofileRequest
        {
           
            public long user_id { get; set; }
            public string profile_certificate { get; set; }
            public string profile_profileUrl { get; set; }
           public IEnumerable<UserprofileRefrences> profileRefrencesRequest { get; set; }
        }
        public class UserprofileResponseJSON
        {
           public long id { get; set; }
           public long user_id { get; set; }
           public string jobDetails { get; set; }
           public string Amount { get; set; }
           public int amount_type { get; set; }
        }
        public class UserprofileStatus
        {
            public long user_id { get; set; }
            public bool Isprofile_status { get; set; }
        }
        public class UserprofileResponseStatusJSON
        {
           
            public long user_id { get; set; }
            public int Isprofile_status { get; set; } 
        }
      public class UserprofileRefrencesRefrences:IDataModel
{
        public long id { get; set; }
public long user_id { get; set; }
        public string jobDetails { get; set; }
        public string Amount { get; set; }
        public int amount_type { get; set; }
}
        #endregion


        #region Routes


        [Route]
        public dynamic Get(long user_id)
        {

            var profileResponse = new List<UserprofileResponseJSON>();
http://vijubook.blogspot.in/2014/12/mvc-entity-framework-using-connection.html
            // FetchBy
            var _profileRefrences =      Db.FetchBy<UserprofileRefrences>x=>x.user_id==user_id);
            foreach (var profile in _profileRefrences)
            {

                var _flReferences = Db.Get<UserprofileRefrences>(profile.id);
                var _userprofile = new UserprofileResponseJSON()
                {
                 
                    id=_flReferences.id,
                    user_id=user_id,
                    jobDetails=_flReferences.jobDetails,
                    Amount=_flReferences.Amount,
                    amount_type = _flReferences.amount_type.GetHashCode()
                  
                   
                };
                profileResponse.Add(_userprofile);
            }
            return profileResponse;

        }
       
        [Route]
        public dynamic post(long user_id, UserprofileRequest request)
        {
            var response = new UserprofileResponseJSON();
            try
    // GetBy
                var _profile = Db.GetBy<Profile>(x => x.user_id == user_id);

                if (_profile != null)
                {
                    _profile.profile_profileUrl = request.profile_profileUrl;
                    _profile.profile_certificate = request.profile_certificate;
                }
                else
                {
                    return _profile;

                }
                var _profile = Db.Update<Profile>(_profile);

                var _flReferences = request.profileRefrencesRequest.ToList();


                foreach (var _flRequest in _flReferences)
                {
                    if (_flRequest.jobDetails != null && _flRequest.jobDetails != "" && _flRequest.Amount != null && _flRequest.Amount != "")
                    {
                        var flR_ID = Db.GetBy<UserprofileRefrences>(x => x.id == _flRequest.id);
                        if (flR_ID == null)
                        {
                            var _fl = new UserprofileRefrences
                              {
                                  user_id = user_id,
                                  jobDetails = _flRequest.jobDetails,
                                  Amount = _flRequest.Amount,
                                  amount_type=_flRequest.amount_type
//Save
                            Db.Save<UserprofileRefrences>(_fl);
                        }
                        else
                        {
                            flR_ID.jobDetails = _flRequest.jobDetails;
                            flR_ID.Amount = _flRequest.Amount;
                            flR_ID.amount_type = _flRequest.amount_type;
http://vijubook.blogspot.in/2014/12/mvc-entity-framework-using-connection.html
//Update
                            Db.Update<UserprofileRefrences>(flR_ID);
                        }
                    }
                    else
                    {

                    }


                }
            }
            catch
            {

            }
            return response;
        }

        [Route("{Isprofile_status:int}")]
        public dynamic put(long user_id, int Isprofile_status)
        {
           // var response = new List<UserprofileResponseStatusJSON>();
            var _userprofile = new UserprofileResponseStatusJSON();
            try
            {
                var _profile = Db.GetBy<Profile>(x => x.user_id == user_id);

                if (_profile != null)
                {
                    _profile.Isprofile_status = Isprofile_status;
                   
                }
                else
                {
                    return _profile;

                }
                var _profile = Db.Update<Profile>(_profile);
                _userprofile = new UserprofileResponseStatusJSON()
                {

                  
                    user_id = user_id,
                    Isprofile_status = _profile.Isprofile_status,
                    

                   
                };
               // response.Add(_userprofile);

            }
            catch (Exception ex)
            {

            }
            return _userprofile;
        }
        

        [Route("{id:long}")]
        public dynamic Delete(long user_id, long id)
        {
            try
            {
                var _userprofileReferences = Db.GetBy<UserprofileRefrences>(x => x.id == id && x.user_id == user_id);
                if (_userprofileReferences == null || _userprofileReferences.user_id != user_id)
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No profile References found for given id:{0}", id));
http://vijubook.blogspot.in/2014/12/mvc-entity-framework-using-connection.html
//Delete
                Db.Delete<UserprofileRefrences>(_userprofileReferences);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch(Exception ex) {
                return Request.CreateErrorResponse(ex, HttpStatusCode.BadRequest, "Failed userfreeaReferences code");

            }
        }
        
        #endregion

    }
}

MVC - WebApi Route , RoutePrefix

MVC - WebApi Route , RoutePrefix


MVC - WebApi Route , RoutePrefix:

Added Namespace :

using System.Web.Routing;



public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapRoute(
            //    name: "Default",
            //    url: "{controller}/{action}/{id}",
            //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            //);
        }


Contoller RoutePrefix :


http://localhost:1234/users/10/profile
 [RoutePrefix("users/{user_id:long}/profile")]

        public dynamic Get(long user_id)
        {
              ....
              ....
          }

Contoller Route :

http://localhost:1234/users/10/profile/2   2-Status
 [Route("{Isstatus:int}")]
        public dynamic put(long user_id, int status)
        {

                 .....
        }


Contoller Route :

http://localhost:1234/users/Search/aaa
 [Route("users/Search/{keyword}")]
        public dynamic Get(string keyword)
        {
         .....
         }