Tuesday 28 April 2015

create cookie in asp.net mvc

create cookie in asp.net mvc

create cookie in asp.net mvc

//assembly
using System.Web.Security;
                -----------------------
//Web config
 <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
//Cookiie name and Time set
      <forms cookieless="UseCookies" name="TGAUTHCookies" loginUrl="~/Login/Login" slidingExpiration="true" protection="All" timeout="1300" />
    </authentication>
//save mode 
    <sessionState mode="InProc" cookieless="UseCookies" timeout="1300" />
  </system.web>

                   -----------------

//Create Cookie

                 FormsAuthentication.SetAuthCookie("vijay", this.isExist);
                HttpCookie TGAUTH = new HttpCookie("TGAUTH");
                TGAUTH.Values.Add("userId", 2);
                TGAUTH.Values.Add("firstName", "vijay");       
//set the time Expire        
                TGAUTH.Expires = DateTime.Now.AddDays(2);
                Response.Cookies.Add(TGAUTH);

              ------------------           

//Clear Cookie

                FormsAuthentication.SignOut();
//Expire day set -2
                Response.Cookies["TGAUTH"].Expires =               DateTime.Now.AddDays(-2);
                Response.Cookies["TGAUTHCookies"].Expires = DateTime.Now.AddDays(-2);
 //// Removes the cache
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                Response.Cache.SetNoStore();
                string[] cookies = Request.Cookies.AllKeys;
                foreach (string cookie in cookies)
                {
                    Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
                }
                Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);    


Friday 24 April 2015

mvc ajax call example

mvc ajax call example :

JQuery AJAX with ASP.NET MVC :


View

  <div id="InfoModalColor" class="modal-header">               
                <h4 class="modal-title">CHANGE PASSWORD</h4>
            </div>
            <div class="modal-body">               
                        <label for="exampleInputEmail1">Old Password</label>                                   
                        <input type="password" class="form-control bg-info-form" id="txtCurrentPassword">                   
                <br clear="all" />              
                        <label for="exampleInputPassword1">New Password</label>                   
                        <input type="password" class="form-control bg-info-form" id="txtNewPassword">
                <br clear="all" />              
                        <label for="exampleInputPassword1">Retype New Password</label>
<input type="password" class="form-control bg-info-form" id="txtRetryPassword">
                <br clear="all" />
            </div>
            <div class="modal-footer">
//Button Call
                <span id="lblError" style="color:red;float: left" ></span>
                <button type="button" id="btnSave" class="btn btn-info" data-toggle="modal">Save changes</button>              
            </div>

JQuery :

 $(document).ready(function () {
                $('#btnSave').click(function () {
//Function Name
                        changePassword();
                            });

            });

function changePassword() {       
        var currentPassword = $("#txtCurrentPassword").val();
        var newPassword = $("#txtNewPassword").val();
        var retypePassword = $("#txtRetryPassword").val();
        var userId = $("#txtUserId").val();   
//Data JQuery URL Passed Parameters    
        var data = {
            "userId": userId,
            "currentPassword": currentPassword,
            "newPassword": newPassword
        };

        $.ajax({
//passed URL :
            url: '@Url.Content("~/UserSetting/changePassword")',
            type: "POST",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json",
            success: function (data) {
                console.log(data);
                if (data.success == true) {                  
                    $('#txtCurrentPassword').val('');
                    $('#txtNewPassword').val('');
                    $('#txtRetryPassword').val('');
                    $('#SuccessModalColor').modal('show');
                }
                else {
                    $('#lblError').text("Current password not correct");
                    $('#SuccessModalColor').modal('hide');
                }
            },
            error: function () {

            }
        });
    }
//Controller
//Method Name
//
[HttpPost]
        public JsonResult changePassword(UserPasswordchange objChangePassword)
        {
            try
            {
                db = new AdminContext();

                
                var userProfile = db.GetBy<User>(x => x.id == objChangePassword.userId && x.passcode==objChangePassword.currentPassword);                
                if (userProfile != null)
                {
                    userProfile.passcode = objChangePassword.newPassword;
                    userProfile = db.Update<User>(userProfile);
                    return Json(new { success = true }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { success = false }, JsonRequestBehavior.AllowGet);
                }
            }
            catch
            {
                return Json(new { success = false }, JsonRequestBehavior.AllowGet);
            }                       
        }

//Model
public class UserPasswordchange
    {
        public long userId { get; set; }
        public string currentPassword { get; set; }
        public string newPassword { get; set; }
    }




Monday 20 April 2015

Group by and Count in Entity Framework

Group and Count in Entity Framework


Group and Count in Entity Framework


DbContext Db = new DbContext();



var messageList =
 from UM in Db.userMessages.ToList()
                              where (UM.fromUserId == toMailId
                            || UM.toUserId == toMailId) 
                              group UM by new {UM.fromUserId,UM.toUserId} into m 
                              select new userMsgGroup
                              { 
                                fromUserId = m.Key.fromUserId,
                                toUserId = m.Key.toUserId,
                                msgCount = m.Count()
                                                              };
List<userMsgGroup> msgGroup = new List<userMsgGroup>();
            msgGroup = messageList.ToList();

 public class userMsgGroup
{
public long fromUserId { get; set; }
public long toUserId { get; set; }
public int msgCount { get;set;}
}



Monday 13 April 2015

entity framework using stored procedure

entity framework using stored procedure :

entity framework using stored procedure :


[Route("Messages/{Id:long}")]

 public class MessageList
    {
        public long Id { get; set; }       
        public string FirstName { get; set; }
        public string LastName { get; set; }      
        public int msgCount { get; set; }
    }

 public dynamic Get(long Id)
        {

 List<MessageList> msgList = new List<MessageList>();

            var messageList =
//exec storedprocedure name and passed paramaters
 Db.Database.SqlQuery<MessageList>("Exec getUserMessageList @userId " ,new SqlParameter("@userId",Id));

            msgList = messageList.ToList();

}

Thursday 2 April 2015

sql create function example

sql create function example :

sql create function example:



Crearte function [dbo].[fnCurrentCompanyIndustryName]
(@userId bigint)
RETURNS varchar(500)
AS
BEGIn
DECLARE @IndustryName varchar(500);
select top 1 @IndustryName=Industry.name
 From UserJob
  join Industry on UserJob.industryId = Industry.id 
  where UserJob.userId=@userId
order by startDate desc
return @IndustryName
END

mvc join query linq to sql c#

mvc join query linq to sql c# :



mvc join query linq to sql c# :


SQL :


select uj.id,uj.skillId,uj.userId ,s.name
From UserSkill as uj inner join Skill as S 
on uj.skillId = s.id 
where uj.userId=11




Linq :
 public string getSkills(long userId)
        {
            string skill = null;
            var jobReq = SampleDb.GetBy<UserRequirement>(x => x.userId == userId);
            if (jobReq != null)
            {
                string userSkill = string.Empty;
                var jobReqSkill = (from R in SampleDb.UserSkill
                                   join S in SampleDb.skills on R.skillId equals S.id
                                   where R.userId == userId
                                   select new { R.id, R.userId, R.skillId, S.name }).ToList();
                if (jobReqSkill != null)
                {
                    foreach (var ski in jobReqSkill)
                    {
                        userSkill = userSkill + ski.name + ',';
                    }
                    
                    skill = userSkill.TrimEnd(',');
                }
                
            }
            return skill;
        }



Result :

C++,Java,Customer Serice,Research,MVC

Tuesday 17 March 2015

sql server displayed all tables foreign keys

sql server displayed all tables foreign keys

sql server displayed all tables foreign keys



SELECT 
'ALTER TABLE ' +OBJECT_NAME(f.parent_object_id) AS TableName ,
' ADD CONSTRAINT ' + f.name AS ForeignKey, 
' FOREIGN KEY  (['+ COL_NAME(fc.parent_object_id,fc.parent_column_id) +'])'AS ColumnName,
' REFERENCES [' + OBJECT_NAME (f.referenced_object_id)+'] ' AS ReferenceTableName,'('+
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) + ')'  AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id

TableName ForeignKey ColumnName ReferenceTableName ReferenceColumnName 

ALTER TABLE profile ADD CONSTRAINT FK_User_UserId FOREIGN KEY  ([userId]) REFERENCES [User] (id)

ALTER TABLE UserAddress ADD CONSTRAINT FK_UserAddress_UserId FOREIGN KEY  ([userId]) REFERENCES [User] (id)

ALTER TABLE UserContact ADD CONSTRAINT FK_UserContact_UserId FOREIGN KEY  ([userId]) REFERENCES [User] (id)


sql server drop all tables foreign keys

sql server drop all tables foreign keys

sql server drop all tables foreign keys


SELECT 'ALTER TABLE  ' + OBJECT_NAME(parent_object_id) AS TableName ,
  'DROP CONSTRAINT  '+ OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
WHERE type_desc LIKE 'FOREIGN_KEY_CONSTRAINT'--'%CONSTRAINT'
GO



TableName NameofConstraint

ALTER TABLE  profile DROP CONSTRAINT  FK_User_UserId
ALTER TABLE  UserAddress DROP CONSTRAINT  FK_UserAddress_UserId
ALTER TABLE  UserContact DROP CONSTRAINT  FK_UserContact_UserId

enum in c#

enum in c#

enum in c#


  public enum UserType
    {
        Admin,
        Manager,
        Employee
    }


   public class ProfileResponse
    {

        public long id { get; set; }
        public long user_id { get; set; }
        public string first_name { get; set; }
       public int userType { get; set; }
   }


Profile profile = Db.GetBy<Profile>(x => x.userId == user_id);
var response = new ProfileResponse();
            response.id = profile.id;
            response.user_id = profile.userId;
            response.first_name = profile.firstName;
           response.userType = getUserType(profile.userId);






public int getUserType(long userId)
        {
            int type = 0;
            var user = (from u in Db.Users where u.id == userId select u.Type).FirstOrDefault();

            if (user == UserType.Admin)
            {
                type = 0;
            }
            else if (user == UserType.Manager)
            {
                type = 1;
            }
            else if (user == UserType.Employee)
            {
                type = 2;
            }
            return type;
        }




create random password in c# asp.net

create random password in  c# asp.net

create random password in  c# asp.net


string pwd = Guid.NewGuid().ToString("d").Substring(1, 5);


Ans:
5caf9
27dae

Thursday 19 February 2015

automatic inserted in sql tables multiple rows

automatic inserted in sql tables multiple  rows :


automatic inserted in sql tables multiple  rows :


declare @id int 
select @id = 1
while @id >=1 and @id <= 50
begin
insert into [sample] values ('c' +convert(varchar(5),@id)+'@gmail.com','123')
   print 'c' +convert(varchar(5),@id)+'@gmail.com
    select @id = @id + 1
end

Tuesday 10 February 2015

Create temp table in sql

Create temp table in sql :



SQl Temp Table


SELECT  [EmpID]
      ,[FirstName]
      ,[LastName]
      ,[Salary]
      ,[Address]
      ,[id] 
    INTO #TempEmp   --> TableName
  FROM [sample].[dbo].[Employee]


  
  Select * From #TempEmp

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"}