Thursday, 30 January 2014

Caching Absolute and Sliding

Absolute Expiration: A DateTime Object that specifies when the data should be removed from the cache.Whe you specify "Absolute Expiration",the cache item will expire at that time,irrecspective of whether the acached tem is access or not.
(In Short It will be expired after given time automatically);

Sliding Expiration:A TimeSpan object that idetfies how long the data should remain in the cache after was last accessed..
(In Short It will remain in cache from the time of last accessed)

Absolute and Sliding Expiration can not be used together.

1. Using "Cache" object's Insert() method

Example : Cache.Insert("KeyName", DATAFORCACHE);

2. Using "Cache" object's Add() method

Example: Cache.Add(""KeyName"", DATAFORCACHE, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);

CacheItemPriority enum values:

1) CacheItemPriority.Low
2) CacheItemPriority.BelowNormal
3) CacheItemPriority.Normal
4) CacheItemPriority.Default
5) CacheItemPriority.AboveNormal
6) CacheItemPriority.High
7) CacheItemPriority.NotRemovable

Wednesday, 29 January 2014

Fragment Caching

Fragment Caching
Caching parts of webform is called as Partial caching or Fragment caching. In a web application development, there might be scenarios where most parts of the web page changes, but only a specific section of the page is static. Let's say that specific section also takes a long time to load. This is an ideal scenario, where fragment caching can be used.

Steps to fragment cache a webform
1. Encapsulate that sepcific sections of the page that does not constantly change into a user control.
2. Use the OutputCache directive on the user control to specify the cache settings.
3. Drag and drop the user control on the webform.

<%@ OutputCache Duration="60" VaryByParam="None" Shared="true" %>

Difference between VaryByParam and VaryByControl?

When should we use VaryByParam over VaryByControl and vice versa?
                                                   OR
What is the difference between VaryByParam and VaryByControl?
If you want to cache multiple responses of a user control, based on a query string or a form "POST" parameter, then use VaryByParam. On the other hand, if you want to cache multiple responses of a user control, based on a control value then use "VaryByControl".

Tuesday, 28 January 2014

Multiple file upload

// Add multiple= true

<asp:FileUpload ID="FileUpload1" multiple="true" runat="server" />

// c# code on upload click
if (FileUpload1.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.
{
   int iUploadedCnt = 0;// to count files
   HttpFileCollection hfc = Request.Files;
 
   for (int i = 0; i <= hfc.Count; i++)
   {
      HttpPostedFile hpf = hfc[i];
      if (hpf.ContentLength > 0)
      {
         filename = Path.GetFileName(hpf.FileName);
         hpf.SaveAs(Server.MapPath("~/images/") + Path.GetFileName(hpf.FileName));
         iUploadedCnt += 1;
      

       }
   }
   lblMessage.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
}
else
{
  Give msg Here // lblMessage.Text ="No files selected.";
}

Saturday, 25 January 2014

Get Chechbox Bool Value With Id inside Gridview


<asp:TemplateField HeaderText="Publish">
   <ItemTemplate>
      <asp:CheckBox ID="chkStatus" runat="server" AutoPostBack="true" Checked='<%# Convert.ToBoolean(Eval("publish")) %>'
            Testid='<%# Eval("OptionId")%>' Text='<%# Eval("publish").ToString().Equals("True") ? " <img src=\"../App_Themes/CPTheme/Images/active.png\" alt=\"Yes\"/> " : " <img src=\"../App_Themes/CPTheme/Images/deactive.png\" alt=\"No\" " %>'
             OnCheckedChanged="chkStatus_CheckedChanged" />
   </ItemTemplate>
</asp:TemplateField>

protected void chkStatus_CheckedChanged(object sender, EventArgs e)
{
  CheckBox chkStatus = (CheckBox)sender;
  GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
  string id = chkStatus.Attributes["Testid"];
  bool status = chkStatus.Checked;
}
 

Friday, 24 January 2014

Change SessionId By code

SessionIDManager Manager = new SessionIDManager();
string NewID = Manager.CreateSessionID(Context);
string OldID = Context.Session.SessionID;
bool redirected = false;
bool IsAdded = false;
Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);
Response.Write("Old SessionId Is : " + OldID);
if (IsAdded){ Response.Write("<br/> New Session ID Is : " + NewID); }
else{Response.Write("<br/> Session Id did not saved : ");}

GridView Multiple Delete By Jquery toggle or Without Postback

---------------------------- Add this script in head section------------
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        function toggleSelectionUsingHeaderCheckBox() {
            $("input[name$='chkChild']").each(function () {
                if ($("input[name$='chkHeader']").prop('checked')) {
                    $("input[name$='chkChild']").prop('checked', true);
                }
                else {
                    $("input[name$='chkChild']").prop('checked', false);
                }
            });
        }
        function toggleAll() {
            $("input[name$='chkChild']").change(function () {
                if ($("input[name$='chkChild']:checked").length == $("input[name$='chkChild']").length) {
                    $("input[name$='chkHeader']").prop('checked', true);
                }
                else {
                    $("input[name$='chkHeader']").prop('checked', false);
                }
            });
        }
        $(document).ready(function () {
            $("#<%=lbwthDelete.ClientID%>").click(function () {
                var totalSelected = $("input[name$='chkChild']:checked").length;
                if (totalSelected == 0) {
                    alert('No Row Selected');
                    return false;
                }
                else
                    return confirm(totalSelected + ' row(s) will be Deleted?');
            });
        });
    </script>------Add template field in Gridview Header Checkbox and child Chekbox------------------------
<asp:TemplateField>
  <HeaderTemplate>
      <asp:CheckBox ID="chkHeader" onClick="toggleSelectionUsingHeaderCheckBox();"
runat="server" />
  </HeaderTemplate>
  <ItemTemplate>
      <asp:CheckBox ID="chkChild" onClick="toggleAll();" runat="server" />
  </ItemTemplate>
</asp:TemplateField>

-----------------------Click Event get selected checkbox value and delete it---

protected void btnDelete_Click(object sender, EventArgs e)
    {
        List<string> listofEmployeeIdtoDelete = new List<string>();
        foreach (GridViewRow a in GridView1.Rows)
        {
            if (((CheckBox)a.FindControl("chkChild")).Checked)
            {
                string EmployeeID = ((Label)a.FindControl("lblEmployeeID")).Text;
                listofEmployeeIdtoDelete.Add(EmployeeID);
            }
        }
        if (listofEmployeeIdtoDelete.Count > 0)
        {
            lblMessage.ForeColor = System.Drawing.Color.Navy;
            foreach (string strEmployeeID in listofEmployeeIdtoDelete)
            {
                EmployeeDataAccessLayer.DeleteEmployee(Convert.ToInt32(strEmployeeID));
            }
            lblMessage.Text = listofEmployeeIdtoDelete.Count.ToString() + "row(s) Delete";
        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "No records selected to delete.";
        }
        bindgridview();
    }

Thursday, 23 January 2014

Capitalize Name By Code

* Include Name Space* 

using System.Threading;
using System.Globalization;


string MenuName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
    ToTitleCase(MenuName.ToLower());

C#

C#

Required Field By Code

<script type="text/javascript">
     function fnCheck() {
         if ((document.getElementById("<%=txtname.ClientID%>").value).length == 0) {
             alert("Name should not be empty!");
             return false;
         }
         else if ((document.getElementById("<%=txtEmail.ClientID%>").value).length == 0) {
             alert("Email should not be empty!");
             return false;
         }
         else if ((document.getElementById("<%=txtfeedback.ClientID%>").value).length == 0) {
             alert("Feedback should not be empty!");
             return false;
         }
         else {
             return true;
         }
     }
    </script>

<asp:Button ID="btnsubmit" runat="server" Text="SUBMIT" OnClientClick="return fnCheck();" />

Allow Only Numbers

<script type="text/javascript">
    //Function to allow only numbers to textbox
    function validate(key) {
        //getting key code of pressed key
        var keycode = (key.which) ? key.which : key.keyCode;
        var phn = document.getElementById('txtSortOrder');
        //comparing pressed keycodes
        if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
            return false;
        }
        else {
            return true;
        }
    }
    </script>

<asp:TextBox ID="txtPhn" runat="server"

onkeypress="return validate(event)"></asp:TextBox>
 

Javascript

Javascript related posts