Sunday 13 September 2015

@model IEnumerable<Models>

@{
    ViewBag.Title = "List Articles";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}

<!-- DataTables CSS -->
<link href="../../Datatable/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" />
<script src="../../Datatable/DataTables/media/js/jquery.dataTables.min.js"></script>
<script src="../../Datatable/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<link href="../../Datatable/datatables-responsive/css/dataTables.responsive.css" rel="stylesheet" />
<!-- DataTables Responsive CSS -->

<div class="row">
    <div class="col-lg-12">


        <table class="table table-striped table-bordered table-hover" id="tblSearch">
            <thead>
                <tr>
                    <th style="display: none;">
                        ArticleId
                    </th>
                    <th style="width: 20%;">
                        Member Name
                    </th>
                    <th style="width: 50%;">
                        Article Name
                    </th>
                    <th style="width: 10%;">
                        Status
                    </th>
                    <th style="width: 10%;"></th>
                    <th style="width: 10%;">
                        <div style="text-align:center">
                            View
                        </div>
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td style="display: none;">
                            @Html.DisplayFor(modelItem => item.ArticleId)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.User.FirstName) &nbsp; @Html.DisplayFor(modelItem => item.User.LastName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.ArticleName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Status.StatusName)
                        </td>
                        <td align="center">
                            @(Convert.ToBoolean(item.IsActive) ? Html.ActionLink("Active", "ActiveInActive", new { id = item.ArticleId }) : Html.ActionLink("InActive", "ActiveInActive", new { id = item.ArticleId }))
                        </td>
                        <td align="center">
                            @Html.ActionLink("View", "View", new { Id = item.ArticleId , Area = "admin"})
                            @*<a href="/Article/View?Id=@item.ArticleId">View</a>*@
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>


<!--Date Time Picker-->
<link href="~/Content/datetimepicker-master/jquery.datetimepicker.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Content/datetimepicker-master/jquery.datetimepicker.js"></script>
<!--Date Time Picker-->
<script type="text/javascript">

    $(document).ready(function () {
        $('#tblSearch').DataTable({
            "oLanguage": { "sSearch": "Search:" },
            "iDisplayLength": 10,
            "bPaginate": true,
            "bLengthChange": true,
            "bFilter": true,
            "bSort": true,
            "bInfo": true,
            "bAutoWidth": false,
            "aaSorting": [[0, "Desc"]],
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
        });


        $('#datepicker2').datetimepicker({
            format: 'd/m/Y',
            scrollinput: false,
            formatDate: 'd/m/Y',
            minDate: '-1970/01/02',
            closeOnDateSelect: true,
            onShow: function (ct) {
                this.setOptions({

                    maxDate: $('#datepicker1').val() ? $('#datepicker1').val() : false
                })
            },
            timepicker: false
        });

    });

</script>

  [Required(ErrorMessage = "Plaese Select Event Date")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        [Display(Name = "Event Date")]

Thursday 16 July 2015

Encrypt and Decry-pt Password

  public  class Password
    {
      public static string CreateRandomPassword(int Length)
      {
          Random rnd = new Random(Convert.ToInt32(DateTime.Now.Millisecond));  //Creates the seed from the time
          string Password = "";
          while (Password.Length < Length)
          {
              char newChar = Convert.ToChar((int)((122 - 48 + 1) * rnd.NextDouble() + 48));
              if ((((int)newChar) >= ((int)'A')) & (((int)newChar) <= ((int)'Z')) | (((int)newChar) >= ((int)'a')) & (((int)newChar) <= ((int)'z')) | (((int)newChar) >= ((int)'0')) & (((int)newChar) <= ((int)'9')))
                  Password += newChar;
          }
          return Password;
      }
      public static string GetMd5Hash(string value)
      {
          var md5Hasher = MD5.Create();
          var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
          var sBuilder = new StringBuilder();
          for (var i = 0; i < data.Length; i++)
          {
              sBuilder.Append(data[i].ToString("x2"));
          }
          return sBuilder.ToString();
      }
      const string passphrase = "Password@123";  //consant string Pass key

      public string encrypt(string message)
      {
          byte[] results;
          UTF8Encoding utf8 = new UTF8Encoding();
          //to create the object for UTF8Encoding  class
          //TO create the object for MD5CryptoServiceProvider
          MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
          byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));
          //to convert to binary passkey
          //TO create the object for  TripleDESCryptoServiceProvider
          TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
          desalg.Key = deskey;//to  pass encode key
          desalg.Mode = CipherMode.ECB;
          desalg.Padding = PaddingMode.PKCS7;
          byte[] encrypt_data = utf8.GetBytes(message);
          //to convert the string to utf encoding binary

          try
          {

              //To transform the utf binary code to md5 encrypt
              ICryptoTransform encryptor = desalg.CreateEncryptor();
              results = encryptor.TransformFinalBlock(encrypt_data, 0, encrypt_data.Length);

          }
          finally
          {
              //to clear the allocated memory
              desalg.Clear();
              md5.Clear();
          }

          //to convert to 64 bit string from converted md5 algorithm binary code
          return Convert.ToBase64String(results);

      }




      public string decrypt(string message)
      {
          byte[] results;
          UTF8Encoding utf8 = new UTF8Encoding();
          MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
          byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));
          TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
          desalg.Key = deskey;
          desalg.Mode = CipherMode.ECB;
          desalg.Padding = PaddingMode.PKCS7;
          byte[] decrypt_data = Convert.FromBase64String(message);
          try
          {
              //To transform the utf binary code to md5 decrypt
              ICryptoTransform decryptor = desalg.CreateDecryptor();
              results = decryptor.TransformFinalBlock(decrypt_data, 0, decrypt_data.Length);
          }
          finally
          {
              desalg.Clear();
              md5.Clear();

          }
          //TO convert decrypted binery code to string
          return utf8.GetString(results);
      }
    }

Tuesday 30 December 2014

Gridview CheckBox checked and Unchecked With Javascript

1.) In Gridview   TemplateField

<asp:TemplateField HeaderStyle-Width="120px" HeaderStyle-HorizontalAlign="Center" >
                        <HeaderTemplate>
                            <asp:CheckBox runat="server" ID="chkAll" Text="Select All" />
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" Runat="server" AutoPostBack="False"></asp:CheckBox>
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        <HeaderStyle ForeColor="White" />
                    </asp:TemplateField>

2) Javascript for Check box

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox").click(function () {
            //Get number of checkboxes in list either checked or not checked
            var totalCheckboxes = $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox").size();
            //Get number of checked checkboxes in list
            var checkedCheckboxes = $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox:checked").size();
            //Check / Uncheck top checkbox if all the checked boxes in list are checked
            $("#<%=gvInvoices.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
        });

        $("#<%=gvInvoices.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            //Check/uncheck all checkboxes in list according to main checkbox 
            $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox").attr('checked', $(this).is(':checked'));
        });
    });

</script>

Thursday 27 November 2014

Database Related

Q !: Create A Split Function In databse

Ans:

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnSplitString]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'Create  FUNCTION [dbo].[fnSplitString]
(
 @RowData varchar(8000),
 @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
 Id int identity(1,1),
 Data nvarchar(100)

AS  
BEGIN 
 Declare @Cnt int
 Set @Cnt = 1

 While (Charindex(@SplitOn,@RowData)>0)
 Begin
  Insert Into @RtnValue (data)
  Select 
   Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
  Set @Cnt = @Cnt + 1
 End

 Insert Into @RtnValue (data)
 Select Data = ltrim(rtrim(@RowData))

 Return
END'
END


2) In Query
select * from [dbo].[tblInvoice] where [InvoiceID] in (select Data from fnSplitString('203,202',','))


2) My favourite Is

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fun_Split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[fun_Split]   
(
  @String varchar(8000),   
  @Delimiter char(1)  
) Returns @Results Table (Items varchar(8000))   
  
  
As      
Begin      
 Declare @Index int      
 Declare @Slice varchar(4000)      
  Select @Index = 1      
  If @String Is NULL Return      
  While @Index != 0      
  Begin      
   
  Select @Index = CharIndex(@Delimiter, @String)      
  If (@Index != 0)      
  Select @Slice = left(@String, @Index - 1)      
  else      
  Select @Slice = @String      
  
  Insert into @Results(Items) Values (@Slice)      
  Select @String = right(@String, Len(@String) - @Index)      
  If Len(@String) = 0 break      
  End      
Return      
End ' 

END

Ouery Wil Be
select * from [dbo].[tblInvoice] where [InvoiceID] in (select * from [dbo].[fun_Split]('203,202',','))

insert statment when not matches column name

insert into [dbo].[tblInvoice] (InvoiceID,Name
select  InvoiceID,'Mahesh' as Name from [dbo].[fun_Split]('203,202',','))

Column Name should be same if not then use as and create table same as above  table.



Thursday 28 August 2014


custom paging in gridview

1. Using your favorite graphic editor (Photoshop), create four buttons that will serve as your icon for the First, Previous, Next and Last buttons.

2. Set your GridView control’s AllowPaging property to true.
3. Add a PagingTemplate inside your GridView and insert 4 ImageButton, 1 DropDownList and a Label controls which will serve as your First, Previous, Next, Last, Page No., and Page Picker of your pager.



Your pager should look like this when you render the page.



4. Add an OnDataBound Event to your GridView. This will render and populate your DropDownList (for page picker) and Label (for page count) controls. Implementation can look like this.




5. Next, we implement an OnSelectedIndexChanged on our DropDownList to go to the selected page when a selection is made from our dropdown.

6. In order for you arrow buttons to work. We must implement an OnCommand event of your buttons. Before that we have to specify a CommandArgument properties to each of our buttons.


7. Finally, the OnCommand event implementation.


Summary

Customizing your GridView pager gives you flexibility and fine grain control over your grid listing. Just don’t be afraid of exploring, experimenting and playing with it to achieve the desired functionalities that you want. Happy coding.