Monday 9 December 2013

Change TabIndex on Hide/Show Elements - JQuery

Hello Friends,

This scenario comes sometimes. when we need conditional tabbing with selecting some option will hide some elements or show some elements so in that case we need to change TabIndex dynamically like the following image.
When I select Cat2 in Dropdownlist all textboxes are visiable.


Now when I select Cat3 Textbox 4,6 and 9 are invisiable and Textbox7 comes in place of Textbox4. so after Textbox3 Cursor should move to Textbox7 and then Textbox5. so I need to change Tabindex of Textbox7 to 4.

for that I am using JQuery's nextuntil() function. so I can replace the following elements of Hidden Element to new TabIndex into the same div.

<script type="text/javascript">
    function changeDrp()
    {
        var value = $("#Select").val();
        if (value == "Cat1")
        {
            ResetAll();
            $("#Test8").hide();
            $("#Test5").hide();
            $("#Test6").hide();
            $("#Test1").hide();
            NewAssignTab();
        }
        else if (value == "Cat2")
        {          
            $("*[ dataitem ='Textbox']").show();
            ResetAll();
        }
        else if (value == "Cat3")
        {
            ResetAll();
            $("#Test6").hide();
            $("#Test9").hide();
            $("#Test4").hide();
            NewAssignTab();
        }
    }

    function NewAssignTab()
    {      
        jQuery("*[ dataitem ='Textbox']").each(function ()
        {        
            if (this.style.display == "none")
            {
                var pre,next;
                next = this.tabIndex;
                $("#" + this.id).nextUntil("#class:last").each(function ()
                {
                    pre = this.tabIndex;
                    this.tabIndex = next;
                    next = pre;                  
                });
            }
        });
    }

    function ResetAll()
    {
        jQuery("*[ dataitem ='Textbox']").each(function ()
        {          
            this.tabIndex = $("#" + this.id).attr("originaltab");
        });
    }
</script>

<div id="main">
     @{
        List<SelectListItem> listItems = new List<SelectListItem>();
        listItems.Add(new SelectListItem
        {
            Text = "Cat1",
            Value = "Cat1"
        });
        listItems.Add(new SelectListItem
        {
            Text = "Cat2",
            Value = "Cat2",
            Selected = true
        });
        listItems.Add(new SelectListItem
        {
            Text = "Cat3",
            Value = "Cat3"
        });
    }

    @Html.DropDownList("Select", listItems, new { onchange="changeDrp();" })<br />

    <div id="dv1" style="width: 33%; float: left;">
        <input id="Test1" type="Text" value="1" tabindex="1" dataitem ="Textbox" originaltab ="1" />
        <input id="Test4" type="Text" value="4" tabindex="4" dataitem ="Textbox" originaltab ="4" />
        <input id="Test7" type="Text" value="7" tabindex="7" dataitem ="Textbox" originaltab ="7" class="last" />
    </div>
    <div id="dv2" style="width: 33%; float: left;">
        <input id="Test2" type="Text" value="2" tabindex="2" dataitem ="Textbox" originaltab ="2" />
        <input id="Test5" type="Text" value="5" tabindex="5" dataitem ="Textbox" originaltab ="5" />
        <input id="Test8" type="Text" value="8" tabindex="8" dataitem ="Textbox" originaltab ="8" class="last" />
    </div>
    <div id="dv3" style="width: 33%; float: left;">
        <input id="Test3" type="Text" value="3" tabindex="3" dataitem ="Textbox" originaltab ="3" />
        <input id="Test6" type="Text" value="6" tabindex="6" dataitem ="Textbox" originaltab ="6" />
        <input id="Test9" type="Text" value="9" tabindex="9" dataitem ="Textbox" originaltab ="9" class="last" />
    </div>
</div>

Here in Last Element of the Div I had added class="last" attribute. so JQuery function will stop assigning new Index to the Elements.

Friday 6 December 2013

Bind JQgrid with Dynamic Columns in MVC

Hello Friends,
In this blog I am creating JQgrid with dynamic columns.

In this example Every time I am giving Connection String and Query dynamically to JQgrid to bind the data.
Code is as follows

<div class="editor-label">
@Html.Label("ConnectionString")
</div>
<div class="editor-field">
@Html.TextBox("ConnectionString")
</div>

<div class="editor-label">
@Html.Label("Query")
</div>
<div class="editor-field">
@Html.TextArea("Query")
</div>

<button type="submit" id="btnGetData" name="Command" value="GetData" onclick="return GetData();" class="btn">Get Data</button>

<div id="dvJqGrid" class="dvjq">
<table id="grid" class="scroll"></table>
<div id="pager" class="scroll" style="text-align: center;"></div>
</div>

<script type="text/javascript">  
function GetData() {
setTimeout(function () { $('#dvLoader').show();},1);
var ConnectionString = document.getElementById("ConnectionString").value;
var Query = document.getElementById("Query").value;

$("#dvJqGrid").empty();
$("#dvJqGrid").append($("<table>").attr("id", "grid"));
$("#dvJqGrid").append($("<div>").attr("id", "pager"));

$.ajax(
{
type: "POST",
url: "/QueryPad/JQGridGetDataWithColumn",
data: { "ConnectionString": ConnectionString, "Query": Query },
dataType: "json",
success: function (result) {
$("#Result").val(result.Msg);
colD = result.colData;
colN = JSON.parse(result.colNames);
colM = JSON.parse(result.colModel);

var SQL = ConnectionString;
var Oracle = ConnectionString;
jQuery("#grid").jqGrid({
jsonReader: {
cell: "",
id: "0"
},
url: '/QueryPad/JQGridGetData',
postData: { ConnectionString: ConnectionString, Query: Query, QueryType: QType },
datatype: 'json',
mtype: 'POST',
datastr: colD,
colNames: colN,
colModel: colM,
pager: jQuery('#pager'),
rowNum: 5,
page: 1,
rowList: [5, 10, 20, 50],
viewrecords: true,
loadonce: false
});
$('#dvLoader').hide();
},
error: function (x, e) {
$('#dvLoader').hide();              
}
});
setTimeout(function () { $('#dvLoader').hide(); }, 1000);
return false;
}
</script>

public string JQGridGetData(string sidx, string sord, int page, int rows,string ConnectionString,string Query)
{          
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
SqlTransaction sqlTran = con.BeginTransaction();
try
{
SqlCommand cmd1 = new SqlCommand(Query, con);
cmd1.Transaction = sqlTran;
DataTable dt = new DataTable();
SqlDataReader dr = cmd1.ExecuteReader();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
string StringData = ConvertDataTabletoString(dt);
sqlTran.Commit();
con.Close();
return StringData;
}
else
{
Exception exx = new Exception();
throw exx;
}
}
catch (Exception ex)
{
sqlTran.Rollback();
con.Close();
ViewBag.Result = ex.Message;
return "";
}
}
catch (Exception ex)
{
con.Close();
return "";
}

}

public JsonResult JQGridGetDataWithColumn(string ConnectionString, string Query)
{  
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
SqlTransaction sqlTran = con.BeginTransaction();
try
{
SqlCommand cmd1 = new SqlCommand(Query, con);
cmd1.Transaction = sqlTran;
DataTable dt = new DataTable();
SqlDataReader dr = cmd1.ExecuteReader();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
sqlTran.Commit();
con.Close();
string StringData = ConvertDataTabletoString(dt);
string[] columns = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
string columnNames = ConvertStringArrayToString(columns);
string columnModel = ConvertStringArrayToStringModel(columns);
return Json(new { colData = StringData, colNames = columnNames, colModel = columnModel, Msg = "Data Successfully Loaded" }, JsonRequestBehavior.AllowGet);
}
else
{
Exception exx = new Exception();
throw exx;
}
}
catch (Exception ex)
{
sqlTran.Rollback();
con.Close();
ViewBag.Result = ex.Message;
return Json(new {Msg = ex.Message },JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
con.Close();
return Json(new { Msg = ex.Message }, JsonRequestBehavior.AllowGet);
}
}

Bind JQgrid in MVC

Hello Friends,
Here is simple example how to bind JQgrid in MVC.

<table id="grid" class="scroll"></table>
 <div id="pager" class="scroll" style="text-align: center;"></div>

 $(document).ready(function () {

        $("#grid").jqGrid({
            url: "/QueryPad/GetData",
            datatype: "json",
            mtype: "GET",
            colNames: ["Product ID", "Name", "Price"],
            colModel: [
                        { name: "ProductID", index: "ProductID" },
                        { name: "Name", index: "Name" },
                        { name: "Price", index: "Price" }
            ],
            rowNum: 1,
            rowList: [20, 50, 100],
            pager: "#pager-json",
            sortname: "ProductID",
            sortorder: "ASC",
            viewrecords: true,
            caption: "Get Data"
        });
});

public string GetData()
{
string ConnectionString = ""; // Put your connection string here
string Query = "Select * from Product";
SqlConnection con = new SqlConnection(ConnectionString);
try
{
SqlCommand cmd1 = new SqlCommand(Query, con);
DataTable dt = new DataTable();
SqlDataReader dr = cmd1.ExecuteReader();
dt.Load(dr);
string StringData = ConvertDataTabletoString(dt);
con.Close();
return StringData;
}
catch (Exception ex)
{
con.Close();
ViewBag.Result = ex.Message;
return "";
}
}

public string ConvertDataTabletoString(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);              
}

Open Dialogbox in jQuery UI MVC

Hello Friends,
Open a Dialogbox is required so manytimes in our porject. so use the following code for this.

<link href="~/Content/themes/base/jquery.ui.dialog.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>

<button id="show-dialog" tabindex="3">Click Open Dialogbox</button>          
<div id="dialog" title="Dialogbox Title" >
   <p>This is a simple Dialogbox body</p>
</div>  

@section scripts {
    <script type="text/javascript">
        $('#dialog').dialog({
            autoOpen: false,
            width: 600,
            buttons: {
                "Ok": function () { $(this).dialog("close"); },
                "Cancel": function () { $(this).dialog("close"); }
            }
        });
        $("#show-dialog").button().click(function () {
            $('#dialog').dialog('open');
            $('#dialog').attr('tabIndex', -1).css('outline', 0).focus().keydown(function (ev)
            {
                if (ev.keyCode && ev.keyCode === jQuery.ui.keyCode.ENTER)
                {
                    $('#dialog').dialog('close');
                }
            });
            return false;
        });
     
    </script>
}

Thursday 14 November 2013

Create a chart using Chart Control of .NET

We need to create chart so many times in the project. I am using chart control of .NET.

Add the chart control from the toolbox just drag and drop in the aspx page it will create following code.

<asp:Chart ID="chtReport" runat="server" Height="500" Width="500">
 <Series>
  <asp:Series Name="Series1" XValueType="Auto" YValueType="Int32">
  </asp:Series>
 </Series>
 <ChartAreas>
  <asp:ChartArea Name="ChartArea1">
   <AxisX Interval="1">
   </AxisX>
  </asp:ChartArea>
 </ChartAreas>
</asp:Chart>


Now feed the data to chart control at the code behind in any event in which you like to bind

List<SPTopTenStudents_Result> ListStudents;
 ListStudents = dbContext.SPTopTenStudents().ToList();
 if (ListStudents != null && ListStudents.Count() > 0)
 {
  Series objseries = new Series();
  foreach (var item in ListStudents)
  {
   objseries.ChartType = SeriesChartType.Column;
   objseries.YValueType = ChartValueType.Int32;
   DataPoint objDS = new DataPoint();
   objDS.SetValueXY(item.Model, item.RequestCount);
   objseries.Points.Add(objDS);
  }
  chtReport.Series["Series1"] = objseries;
  chtReport.DataBind();
 }


when you add chart control it will also create chart handler at web.config file like following.

<appSettings>
<add key="ChartImageHandler" value="Storage=file;Timeout=20;Url=~/Images/;" />
</appSettings>

so create the Images folder if you don't have already in the project.

Export Gridview to PDF

Sometimes we need to export the gridview as pdf. I am using iTextShart to export the gridview to PDF.
Click Here to download iTextSharp.

First add attribute
EnableEventValidation="false"
 to your @Page directive in aspx page.


Second add the following method to your code behind page.

public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }


Third now add the following code on your Export button click.

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=InstituteReport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw1 = new HtmlTextWriter(sw);
                Label lblHead = new Label();
                lblHead.Text = "<img src='" + Server.MapPath("~/images/logo.png") + "' height='25'
                width='75'></img>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                lblHead.RenderControl(hw1);
                HtmlTextWriter hw2 = new HtmlTextWriter(sw);
                Label lblBr = new Label();
                lblBr.Text = "report";
                lblBr.ForeColor = System.Drawing.Color.White;
                lblBr.RenderControl(hw2);
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                GvInstitute.AllowPaging = false;
                GvInstitute.AllowSorting = false;
                GvInstitute.GridLines = GridLines.Both;
                GvInstitute.HeaderRow.Style.Add("font-size", "10px");
                GvInstitute.Style.Add("text-decoration", "none");
                GvInstitute.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
                GvInstitute.Style.Add("font-size", "8px");
                GvInstitute.Columns[0].ItemStyle.Width = Unit.Pixel(10);
                GvInstitute.Columns[0].HeaderStyle.Width = Unit.Pixel(10);
                BindInstitutes(); // To bind the data to Gridview
                GvInstitute.RenderControl(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(PageSize.A4, 7f, 7f, 7f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.Write(pdfDoc);
                Response.End();


 

Export Data to Excel in ASP.NET C#

I am using third party tool to export data to excel. The third party tool is EPPlus. Click here to download the dll and add refference to your porject.

Now you can add the following code to your button click of Export to Excel.

List<Institutes> ExportData = new List<Institutes>();
  ExportData = objReport.GetInstitutesData();

  using (ExcelPackage pck = new ExcelPackage())
  {
   ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Institute Report");
   ws.Cells["A2"].LoadFromCollection(ExportData, true);
   ws.Cells["A1"].Value = "Institute Report";
   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   Response.AddHeader("content-disposition", "attachment;  filename=InstituteReport.xlsx");
   Response.BinaryWrite(pck.GetAsByteArray());
   Response.End();
  }
 

Saturday 9 November 2013

Common Functions of C#

Common required functions of C#

To Convert Date to String and vice e versa.

public static string ToDate2String(DateTime dt)
    {
        string DateFormat = "MM/dd/yyyy";
        return dt.ToString(DateFormat);
    }
public static DateTime ToString2Date(string dt)
    {
        string DateFormat = "MM/dd/yyyy";
        return DateTime.ParseExact(dt, DateFormat, CultureInfo.InvariantCulture);
    }



To Convert List to DataTable

public static DataTable ListToDataTable<T>(IEnumerable<T> list)
    {
        DataTable table = new DataTable();
        if (list != null)
        {
            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(
                    prop.Name,
                    (prop.PropertyType.IsGenericType &&
                     prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        ? Nullable.GetUnderlyingType(prop.PropertyType)
                        : prop.PropertyType
                    );
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
        }
        return table;
    }



To Write the Error of the Project.

    public static void WriteError(Exception ex)
    {
        string err = null;
        try
        {
            string path = "~/ErrorLogs/" + DateTime.Today.ToString("dd-MMM-yy") + ".txt";
            if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
                File.Create(HttpContext.Current.Server.MapPath(path)).Close();
            using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                err = "Error in: " + HttpContext.Current.Request.Url.ToString() + Environment.NewLine +
                           "File Name : " + trace.GetFrame(0).GetFileName() + Environment.NewLine +
                           "Line : " + trace.GetFrame(0).GetFileLineNumber() + Environment.NewLine +
                           "Column: " + trace.GetFrame(0).GetFileColumnNumber() + Environment.NewLine +
                           "Error Message:" + ex.Message + Environment.NewLine +
                           "TargetSite:" + ex.TargetSite.ToString();
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception exc)
        {
            WriteError(exc);
        }
    }

CCS Server API (To Get, Post, Put & Delete the data on the server)

To access api you need to create get, post, put or delete requests so we can create requests like the following codes.

 <appSettings>
    <add key="CCSAPIURL" value="https://265.105.115.68:9303/" />
    <add key="CCSAPIUsername" value="admin" />
    <add key="CCSAPIPassword" value="admin" />
 </appSettings>

protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
   ServerOperations serverapi = new ServerOperations();
            string LoginID = txtLoginID.Text;
            string Password = txtLoginPassword.Text;
            string Email = txtEmail.Text;
 
   string Data = "groupName=bluevoip.com&userName=" + LoginID + "&password=" + Password + "&profileName=mobile_sip";
            serverapi.PostUserDetails(Data, "ccs/user");
            string data = "userName=" + LoginID + "&attributeName=account.notification._userEmailAddress&attributeValue=" + Email;
            serverapi.PostUserDetails(data, "ccs/user/attribute");  
  }

public class ServerOperations
    {
        string URL = Convert.ToString(ConfigurationManager.AppSettings["CCSAPIURL"]);
        string UserName = Convert.ToString(ConfigurationManager.AppSettings["CCSAPIUsername"]);
        string Password = Convert.ToString(ConfigurationManager.AppSettings["CCSAPIPassword"]);
        /// <summary>
        /// For Secure server certify
        /// </summary>
        public static void InitiateSSLTrust()
        {
            try
            {
                //Change SSL checks so that all checks pass
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(
                        delegate
                        { return true; }
                    );
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// Get the User Details from the CCS
        /// </summary>
        public void GetUserDetails()
        {
            try
            {
                InitiateSSLTrust();               
                string url = "https://265.105.115.68:9303/ccs/user?userName=test@test.com";
                WebRequest myReq = WebRequest.Create(url);
                string username = "developer1";
                string password = "D3v3l0p3r";
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();
                //txtResponse.Text = "Response : " + content;
            }
            catch (WebException ex)
            {
            }
        }
        /// <summary>
        /// Post Userdata to the server
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="AppendURL"></param>
        public void PostUserDetails(string Data, string AppendURL)
        {
            try
            {              
                InitiateSSLTrust();
                string url = URL + AppendURL;
                string data = Data;
                WebRequest myReq = WebRequest.Create(url);
                myReq.Method = "POST";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                myReq.ContentLength = bytes.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                string username = UserName;
                string password = Password;
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                using (var requestStream = myReq.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();
            }
            catch (WebException ex)
            {               
            }
        }
        /// <summary>
        /// Modify Userdate on the server
        /// </summary>
        /// <param name="data"></param>
        /// <param name="AppendURL"></param>
        public void PUTUserDetails(string data, string AppendURL)
        {
            try
            {
                InitiateSSLTrust();
                string url = URL + AppendURL;
                WebRequest myReq = WebRequest.Create(url);               
                myReq.Method = "PUT";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                myReq.ContentLength = bytes.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                string username = "developer1";
                string password = "D3v3l0p3r";
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                using (var requestStream = myReq.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();               
            }
            catch (WebException ex)
            {               
            }
        }
        /// <summary>
        /// Delete the user from the server
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="AppendURL"></param>
        public void DeleteUserDetails(string Data, string AppendURL)
        {
            try
            {
                InitiateSSLTrust();
                string url = URL + AppendURL;
                string data = Data;
                WebRequest myReq = WebRequest.Create(url);
                myReq.Method = "DELETE";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                myReq.ContentLength = bytes.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                string username = UserName;
                string password = Password;
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                using (var requestStream = myReq.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
            }
        }       
    }

Monday 28 October 2013

Add Textboxes Dynamically and get the values

Hello Friends,
      Sometimes we need to add the textboxes dynamically and get the values from that.

first add the code at design side.

<ul>
     <li class="websiteadd">
                        <label for="user_category">
                            Websites<sup>*</sup></label>
                        <div class="inputbox" style="width: 320px; height: 28px;">
                            <asp:TextBox ID="txtWebSite" MaxLength="50" Style="height: 28px; width:210px;" runat="server"
                                CssClass="input-text wid text txtWebSite addwebsite"></asp:TextBox>
                            <asp:Button CssClass="add-btn" ID="btnAddnewWebsite" OnClientClick="return fnAddCustomWebsite();"
                                runat="server" Text="+Add" />
                        </div>
                    </li>
                    <li class="websitedelete">
                        <asp:Panel ID="panelWebSite" CssClass="panelWebSite" runat="server" Style="margin-left: 131px;">
                        </asp:Panel>
                    </li>
                </ul>

Then add the script in the head part

<script type="text/javascript">
function fnAddCustomWebsite() {
            var web = $(".addwebsite").val();
            var re = /^(www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$/;
            if (!re.test(web)) {
                alert("Please Enter valid website name.");
                return false;
            }
            else {
                AddWeb++;
                var li_Web = $("<span></span>").append($("<div style='width: 320px; height:28px;'></div>").addClass("field-wrapper inputbox").append($("<input style='width: 220px; height:28px;' />").attr({ "id": "txtnewAddWeb" + AddWeb, "text": +web, "name": "txtnewAddWeb" + AddWeb }).val(web))
            .append($("<a></a>").attr({ "href": "javascript:void(0);", "class": "delete-amt", "style": "width:50px;" }).append("Delete").click(function () {
                $(this).parent().remove();
                return false;
            })));
                $(".panelWebSite").append($(li_Web));
                $(".addwebsite").val('');
                return false;
            }
        }
</script>


Then create the method to get the values as follows

public void AddWebSites()
        {
            try
            {
                UserWebsiteService objuserwebsiteservice = new UserWebsiteService();
               
                foreach (string key in Request.Params.AllKeys)
                {
                    if (key.Contains("txtnewAddWeb"))
                    {
                        string lblnewweb = Request.Params[key].ToString();
                        GEN_UserWebSite objNewWeb = new GEN_UserWebSite();
                        objNewWeb.CreatedBy = ProjectSession.UserID;
                        objNewWeb.CreatedDate = DateTime.Now;
                        objNewWeb.WebSiteName = lblnewweb.Trim();
                        objNewWeb.UserID = ProjectSession.UserID;
                        objuserwebsiteservice.InsertGEN_UserWebSite(objNewWeb);
                       
                    }
                }
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex);
            }
        }


Now call this function on submit button.

Maintain Page Scrol after Postback on the page

Hello friends,

    Sometimes we need to maintain scroll position of the page after postback due to dropdown change or button click in that case follow the code.

if Dropdown Control      : onChange="ab();"
if Button Control            : onClientClick ="ab();"


next take one hidden field to maintain scrol value.

<asp:HiddenField ID="TOS" runat="server" />


put the script in the head part.

<script type="text/javascript">
        function ab() {
            $("#<%= TOS.ClientID %>").val($(window).scrollTop());
        }
        function scrol() {
            setTimeout(function () { $(window).scrollTop($("#<%= TOS.ClientID %>").val()); }, 1);
        }
</script>


finally register the scrol function in last line of the event in code behind page.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "JavaScript:scrol();", true); 

Friday 25 October 2013

Form Validation Using jQuery and Regular Expressions

Form Validation Using jQuery and Regular Expressions

Regular expressions offer an extremely flexible and powerful way of adding validation to your website forms. Combined with jQuery, it allows you to ensure that data sent to the server matches all of your requirements.

In this post I have included several example regular expressions that we have used in our web design projects for validating form input.

For this tutorial we assume you know how to create the HTML form and add jQuery to your site. For samples you can refer to previous posts – check passwords using jQuery, email validation using jQuery or view the demo form.

1 – Validates Numeric Characters Only
Accepts only 0 – 9
$('#TxtUpdateTime').keyup(function () {
            var val = $(this).val();
            var orignalValue = val;
            val = val.replace(/[0-9]*/g, "");
            if (val != '') {
                orignalValue = orignalValue.replace(/([^0-9].*)/g, "")
                $(this).val(orignalValue);             
            }
        });


2 - No Special Characters
Allows only letters, numbers and spaces. All other characters will return an error.

$('.keyup-characters').keyup(function() {
    $('span.error-keyup-2').remove();
    var inputVal = $(this).val();
    var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-2">No special characters allowed.</span>');
    }
});

3 – Maximum Of 8 Characters
Allows all characters up to a maximum of 8. Useful for passwords, etc. The value can easily be increased/descreased by changing the {0,8}

$('.keyup-limit-8').keyup(function() {
    $('span.error-keyup-3').remove();
    var inputVal = $(this).val();
    var characterReg = /^([a-zA-Z0-9]{0,8})$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-3">Maximum 8 characters.</span>');
    }
});

4 - Check Email Address Format
This is a standard regular expression, which is used to validate email addresses to ensure they follow the standard format:

$('.keyup-email').keyup(function() {
    $('span.error-keyup-7').remove();
    var inputVal = $(this).val();
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-7">Invalid Email Format.</span>');
    }
});

4 - Regex for float numbers

/^[-+]?[0-9]*\.?[0-9]+$/

Wednesday 25 September 2013

Fix the Filter on top while scrolling the page


Hello All,
Some times we need to fix the filter on the top of the screen at the time we scroll the page. for that simply we need to change the css of that div in which we placed the filter. I have also fixed the header of the gridview.
For this code as follow

<script type="text/javascript">
        jQuery(function ($) {
           
            $(window).scroll(fixDiv);
            fixDiv();
        });
        function fixDiv() {
            var $cache = $('#getFixed');
            var $grid = $('#gvImage .FrozenHeader');
            if ($(window).scrollTop() > 80) {
                $cache.css({ 'position': 'fixed', 'top': '0px', 'padding-top': '10px', 'width': '1122px', 'margin': '0px 0px 0px 0px', 'border-bottom': '20px solid gray', 'border-top': '10px solid gray' });
                $grid.css({ 'position': 'fixed', 'top': '60px', 'left': '8px', 'width': '620px', 'padding-top': '0px', 'margin-top': '0px' });
            }
            else {
                $cache.css({ 'position': 'relative', 'width': '100%', 'top': '10px', 'padding-top': '10px' });
                $grid.css({ 'position': 'relative' });
            }
        }
</script>


and code for my filter and gridview is

<div id="getFixed" style="background-color: Yellow; height: 30px; top: 10px;">
            Filter :        
            <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button id="btnSearch" runat="server" Text="Search" />
</div>


<asp:GridView ID="gvImage" runat="server" AutoGenerateColumns="false" ClientIDMode="Static" BackColor="White">
                            <HeaderStyle CssClass="FrozenHeader" />
                            <Columns>
                                <asp:TemplateField HeaderText="Sr No." HeaderStyle-HorizontalAlign="Center">                                   
                                    <HeaderStyle Width="100" />
                                    <ItemStyle HorizontalAlign="Center" Width="100" />
                                    <ItemTemplate>
                                        <asp:Label ID="lblID" CssClass="lblID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <Columns>
</asp:GridView>