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