Monday, March 14, 2016

Convert Json string to C# object



MapPolicySnapshop snap = JsonConvert.DeserializeObject<MapPolicySnapshot>(responseString);
using Newtonsoft.Json;
String To Object
public T StringToObject<T>(string json){
 return JsonConvert.DeserializeObject<T>(responseString);
}

obj
public string ObjectToString(T obj){
   return JsonConvert.DeserializeObject<T>(obj);
}

Tuesday, March 8, 2016

Get elements inside elementes jquary

 <div id="sortable-horizontal" style="width:100%">
            <img src="https://s-media-cache-ak0.pinimg.com/736x/88/70/72/8870729d814f13885f8dc25d9c90111e.jpg"  id="1"/>
            <img src="http://www.dailyfreepsd.com/wp-content/uploads/2013/06/Face-Expression-of-surprise-and-scare-120x120.png" id="2"/>
            <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRxW0ma1d149zo2koacBtH7YUkGQMbVid6QsdhzKjxfwGg2XjQl" id="3"/>
            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Face-kiss.svg/120px-Face-kiss.svg.png"id="4" />
            <img src="http://images.clipshrine.com/getimg/PngThumb-Sad-Face-3301.png" id="5"/>
        </div>

 function GetOrder() {
                    var liIds = $('#sortable-horizontal img').map(function (i, n) {
                        return $(n).attr('id');
                    }).get().join(',');

                    console.log(liIds);
                }

if class
                    var liIds = $('#sortable-horizontal .className').map(function (i, n) {
                        return $(n).attr('id');
                    }).get().join(',');

                    console.log(liIds);
                }

Thursday, February 11, 2016

Sample UIService Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using App.DBAccess;
using App.Model;

namespace App.UIService
{
    interface ISubjectUIService
    {

        ActionDetails SubjectInsert(SubjectModel obj);
        ActionDetails SubjectsSelect();
        ActionDetails SubjectSelect(int subjectID);
        ActionDetails SubjectDelete(int subjectID);
        ActionDetails SubjectUpdate(SubjectModel obj);
    }

    public class SubjectUIService:Repository,ISubjectUIService
    {
        public SubjectUIService()
            : base()
        {

        }

        public ActionDetails SubjectInsert(SubjectModel obj)
        {
            try
            {
                List<string> elist = new List<string> ();
                if (ValidateSubjectModel(obj, out elist)) {

                    return Message.NotSuccess(content: null, messageContent: Message.MessageBody("subject insert is not success", EErrorCode.ValidateionError, elist));
                }

                dba.TB_SUBJECTS.Add(
                    BoObjectsToDb(new List<SubjectModel>() { obj }).FirstOrDefault()
                    );
                dba.SaveChanges();

                return Message.Success(content:obj,messageContent:Message.MessageBody("subject insert is success"));

            }
            catch (Exception ex)
            {
                return Message.Error(ex);
            }

        }

        public ActionDetails SubjectsSelect()
        {
            try
            {
                var c = DBObjectToBo(dba.TB_SUBJECTS.ToList());
                return Message.Success(content: c, messageContent: Message.MessageBody("subject select is success"));

            }
            catch (Exception ex)
            {
                return Message.Error(ex);
            }
        }

        public ActionDetails SubjectSelect(int subjectID)
        {
            try
            {
               var c = DBObjectToBo(new List<TB_SUBJECTS>() { dba.TB_SUBJECTS.Where(p => p.ID == subjectID).FirstOrDefault() }).FirstOrDefault();
               return Message.Success(content: c, messageContent: Message.MessageBody("subject select is success"));

            }
            catch (Exception ex)
            {
                return Message.Error(ex);
            }
        }

        public ActionDetails SubjectDelete(int subjectID)
        {
            try
            {


                var o = dba.TB_SUBJECTS.SingleOrDefault(p => p.ID == subjectID);
                if (o == null)
                {
                    return Message.NotSuccess(content: null, messageContent: Message.MessageBody("invalied oparation", EErrorCode.ValidateionError));
                }
                dba.TB_SUBJECTS.Remove(o);
                dba.SaveChanges();

                return Message.Success(content: null, messageContent: Message.MessageBody("subject delete is success"));

            }
            catch (Exception ex)
            {
                return Message.Error(ex);
            }
        }

        public ActionDetails SubjectUpdate(SubjectModel obj)
        {
            try
            {
                List<string> elist = new List<string>();
                if (ValidateSubjectModel(obj, out elist))
                {
                    return Message.NotSuccess(content: null, messageContent: Message.MessageBody("subject update is not success", EErrorCode.ValidateionError, elist));
                }

                var o = dba.TB_SUBJECTS.SingleOrDefault(p => p.ID == obj.ID);
                if (o == null)
                {
                      return Message.NotSuccess(content: null, messageContent: Message.MessageBody("invalied oparation", EErrorCode.ValidateionError));
                }
                o.NAME = obj.Name;
                o.FEES = obj.Fees;
                dba.SaveChanges();

                return Message.Success(content: obj, messageContent: Message.MessageBody("subject update is success"));

            }
            catch (Exception ex)
            {
                return Message.Error(ex);
            }
        }

        #region validate subject model

        bool ValidateSubjectModel(SubjectModel obj,out List<string> errors) {

            List<string> emessages = new List<string>();
            bool isvalied = true;
            if (string.IsNullOrEmpty(obj.Name))
            {
                emessages.Add("subject name requred");
                isvalied = false;
            }

            if (obj.Fees==null)
            {
                emessages.Add("invalied subject fee");
                isvalied = false;
            }
            else if (obj.Fees.Value <= 0 || obj.Fees >= 10000)
            {
                emessages.Add("invalied subject fee");
                isvalied = false;
            }
            errors = emessages;
            return isvalied;
        }

        #endregion

        #region objectConverter

        List<SubjectModel> DBObjectToBo(List<TB_SUBJECTS> lst)
        {

            if (lst == null || lst.Count == 0)
            {
                return new List<SubjectModel>();
            }
            else
            {
                List<SubjectModel> lstSubjects = new List<SubjectModel>();
                foreach (var item in lst)
                {
                    lstSubjects.Add(new SubjectModel
                    {
                        Fees = item.FEES,
                        ID = item.ID,
                        Name = item.NAME
                    });
                }
                return lstSubjects;
            }

        }

        List<TB_SUBJECTS> BoObjectsToDb(List<SubjectModel> lst)
        {

            if (lst == null || lst.Count == 0)
            {
                return new List<TB_SUBJECTS>();
            }
            else
            {
                List<TB_SUBJECTS> lstSubjects = new List<TB_SUBJECTS>();
                foreach (var item in lst)
                {
                    lstSubjects.Add(new TB_SUBJECTS
                    {
                        FEES = item.Fees,
                        ID = item.ID,
                        NAME = item.Name
                    });
                }
                return lstSubjects;
            }

        }

        #endregion
    }
}

MVC Important

MVC Important


 Caching

 [OutputCache(Duration = int.MaxValue, VaryByParam = "none")]
        public ActionResult Index()
        {
            Thread.Sleep(5000);
            return View();
        }

 [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
        public ActionResult Index(int id,string message)
        {
            Thread.Sleep(5000);
            return View();
        }

--------------------------------------------
Page Navigation
return Redirect("http://www.website.com");
 return RedirectToAction("Index", "Home");

Sample Page for bootstrap

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="http://getbootstrap.com/favicon.ico">

    <title>Student Manegement system</title>

    <!-- Bootstrap core CSS -->
    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="http://getbootstrap.com/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="http://getbootstrap.com/examples/navbar-fixed-top/navbar-fixed-top.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="http://getbootstrap.com/assets/js/ie-emulation-modes-warning.js"></script>

     <script>

         function Message(msg) {

             return "<div class='alert alert-info' role='alert>" + msg + "</div>";
         }

      </script>
  </head>

  <body>

    <!-- Fixed navbar -->
    <nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Student Menegement System</a>
        </div>
        @if (Request.IsAuthenticated)
                {
           
                      Html.RenderPartial("_TopMenu");
          }

      </div>
    </nav>

    <div class="container">

      <!-- Main component for a primary marketing message or call to action -->
      <div class="jumbotron">
           @RenderBody()
      </div>

    </div> <!-- /container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>

   

  </body>
</html>

Auuthontication MVC

 protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
        {
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    try
                    {
                        //let us take out the username now              
                        string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                        string roles = string.Empty;

                        using (userDbEntities entities = new userDbEntities())
                        {
                            User user = entities.Users.SingleOrDefault(u => u.username == username);

                            roles = user.Roles;
                        }
                        //let us extract the roles from our own custom cookie
                       

                        //Let us set the Pricipal with our user specific details
                        e.User = new System.Security.Principal.GenericPrincipal(
                          new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                    }
                    catch (Exception)
                    {
                        //somehting went wrong
                    }
                }
            }
        }

 FormsAuthentication.SetAuthCookie(username, false);

 [Authorize(Roles="admin")]
 [Authorize]
[Authorize(Roles="members, admin")

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>

 FormsAuthentication.SignOut();

 @if (Request.IsAuthenticated)
                {
}

Friday, January 15, 2016

ASP Caching

Caching

 Duration --> TIme taken between 2 cache
VarByParam --> give controls id to filter cache
Location --> set where cache file store (server,client,proxy)  

important
  1. VarByParam can be only one contrall.


<%@ OutputCache Duration ="30" VaryByParam="None" %>
Duration --> cach duration in second

<%@ OutputCache Duration ="30" VaryByParam="ddProducts" %>
cache for every single entity in list box
<Asp:DropDownList id ="ddProducts">
<Item> One </Item>
<Item> Two</Item>
<Item> Three</Item>
<Item> Four</Item>
</Asp:DropDownList>


Fragment Caching
Fragments are User contralls
set each and every user contral to cache derective
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="SEcond.Cache.WebUserControl1" %>
<%@ OutputCache Duration="30" Shared="true"  VaryByParam="None"%>


Cache Data

if(Cache["data"]==null){
    Gridview1.Datasource = Cache["Data"] = GetData();
    Gridview.DataBind();
}
else{

    Gridview1.Datasource = (DataTable)Cache["Data"] ;
    Gridview.DataBind();
}



















Sql server row level policy