Monday, 21 April 2014

RSS news

http://www.jquery-plugins.net/FeedEK/FeedEk_demo.html

http://www.jquery-plugins.net/FeedEK/FeedEK.html

https://github.com/enginkizil/FeedEk

Friday, 18 April 2014

Find Block url status using C#

private bool isValidURL(string url)
    {
        WebRequest webRequest = WebRequest.Create(url);
        WebResponse webResponse;
        try
        {
            webResponse = webRequest.GetResponse();
        }
        catch //If exception thrown then couldn't get response from address
        {
            return false;
        }
        return true;
    }

Thursday, 17 April 2014

Encrypt and Decrypt password using C#

using System.Security.Cryptography;


 private string Encrypt(string clearText)
    {
        string strmsg = string.Empty;
        byte[] encode = new byte[clearText.Length];
        encode = Encoding.UTF8.GetBytes(clearText);
        strmsg = Convert.ToBase64String(encode);
        return strmsg;
    }

    private string Decrypt(string cipherText)
    {
        string decryptpwd = string.Empty;
        UTF8Encoding encodepwd = new UTF8Encoding();
        Decoder Decode = encodepwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(cipherText);
        int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        decryptpwd = new String(decoded_char);
        return decryptpwd;
    }

Decrypt and Encrypt password using asp .net C#

using System.Security.Cryptography;
/*-----------------------------------------------*/

private string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
/*-----------------------------------------------------------------------------------------*/
    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }

Wednesday, 16 April 2014

JQuery Slider

http://www.jssor.com/demos/x-fly.html

In C# Code Behind Validate Valid user or not using basepage

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for BasePage
/// </summary>

public class BasePage : System.Web.UI.Page
{
    protected override void OnPreInit(EventArgs e)
    {
        string cTheFile = HttpContext.Current.Request.Path;

        // here select what part of that string you won to check out
        if (!GetAuthenticatedRolesByModuleName(cTheFile))
        {
            // some how avoid the crash if call the same page again
            if (!cTheFile.EndsWith("Default.aspx"))
            {
                Response.Redirect("Default.aspx", true);
                return;
            }
        }

        // continue with the rest of the page
        base.OnPreInit(e);
    }

    private bool GetAuthenticatedRolesByModuleName(string cTheFile)
    {
        if (Session["Name"]!=null)
        {
            return true;
        }
        else
        {

            return false;
        }
    }
}

Wednesday, 9 April 2014

send mail using C#

 {
        string status = "";
        try
        {
            if (!string.IsNullOrEmpty(ToEmail))
            {
                ToEmail = ConfigurationManager.AppSettings["toMailId"].ToString();
            }
            string MailSenderEmail = ConfigurationManager.AppSettings["SenderEmail"].ToString();
            string MailSenderPwd = ConfigurationManager.AppSettings["SenderPwd"].ToString();
            string smtpInfo = ConfigurationManager.AppSettings["smtpInfo"].ToString();
            string Port = ConfigurationManager.AppSettings["Port"].ToString();

            MailMessage mail = new MailMessage();
            mail.Subject = subj;
            mail.From = new MailAddress(MailSenderEmail);
            mail.To.Add(ToEmail);
            mail.Body = bodymsg;
            mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient(smtpInfo, Util.ToInt32(Port));
            smtp.EnableSsl = true;
            NetworkCredential netCre = new NetworkCredential(MailSenderEmail, MailSenderPwd);
            smtp.Credentials = netCre;
            smtp.Send(mail);
            status = "1";
        }
        catch (Exception e)
        {
            e.Message.ToString();
            status = e.Message.ToString();
        }
        return status;
    }

Tuesday, 8 April 2014

Paging and shorting in grid view using C#


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridviewSortPaging.aspx.cs"
    Inherits="gridviewSortPaging" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Gridview Paging and Sorting </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="font-size: 20px; font-family: Verdana">
            <u>Gridview Paging and Sorting</u>
            <br />
            <br />
        </div>
        <div>
            <asp:GridView ID="GridVwPagingSorting" runat="server" AutoGenerateColumns="False"
                Font-Names="Verdana" AllowPaging="True" AllowSorting="True" PageSize="5" Width="75%"
                OnPageIndexChanging="PageIndexChanging" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" OnSorting="Sorting">
                <AlternatingRowStyle BackColor="#BFE4FF" />
                <PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
                <HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="15px" BorderColor="#CCCCCC"
                    BorderStyle="Solid" BorderWidth="1px" />
                <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
                    BorderWidth="1px" />
                <Columns>
                    <asp:BoundField DataField="ContactName" HeaderText="Employee Name" SortExpression="ContactName" />
                    <asp:BoundField DataField="CustomerID" HeaderText="Employee ID" SortExpression="CustomerID" />
                    <asp:BoundField DataField="City" HeaderText="Job title" SortExpression="City" />
                    <%--<asp:BoundField DataField="Emp_Dep" HeaderText="Department" SortExpression="Emp_Dep" />--%>
                </Columns>
            </asp:GridView>
        </div>
        <div style="color: Green; font-weight: bold">
            <br />
            <i>You are viewing page
                <%=GridVwPagingSorting.PageIndex + 1%>
                of
                <%=GridVwPagingSorting.PageCount%>
            </i>
        </div>
    </div>
    </form>
</body>
</html>
/*-----------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class gridviewSortPaging : System.Web.UI.Page
{
    string Sort_Direction = "ContactName ASC";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["SortExpr"] = Sort_Direction;
            DataView dvEmployee = Getdata();
            GridVwPagingSorting.DataSource = dvEmployee;
            GridVwPagingSorting.DataBind();
        }
    }
    private DataView Getdata()
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
        {
            DataSet dsEmployee = new DataSet();
            string strSelectCmd = "select * from customers";
            SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
            da.Fill(dsEmployee, "Employee");
            DataView dvEmp = dsEmployee.Tables["Employee"].DefaultView;
            dvEmp.Sort = ViewState["SortExpr"].ToString();
            return dvEmp;
        }
    }
    protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridVwPagingSorting.PageIndex = e.NewPageIndex;
        DataView dvEmployee = Getdata();
        GridVwPagingSorting.DataSource = dvEmployee;
        GridVwPagingSorting.DataBind();
    }
    protected void Sorting(object sender, GridViewSortEventArgs e)
    {
        string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
        if (SortOrder[0] == e.SortExpression)
        {
            if (SortOrder[1] == "ASC")
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
            }
        }
        else
        {
            ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
        }
        GridVwPagingSorting.DataSource = Getdata();
        GridVwPagingSorting.DataBind();
    }
}

Find HOST Name using C#

 private string GetHOSTName()
    {      
        return "Your HOST Name is " + System.Net.Dns.GetHostName();
    }

Find Clint IP Address using C#

        string strHostName = "";
        strHostName = System.Net.Dns.GetHostName();
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
        IPAddress[] addr = ipEntry.AddressList;
        return addr[addr.Length - 1].ToString();

Find MAC Address using C#

public string GetMACAddress()
    {
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        String sMacAddress = string.Empty;
        foreach (NetworkInterface adapter in nics)
        {
            if (sMacAddress == String.Empty)// only return MAC Address from first card
            {
                //IPInterfaceProperties properties = adapter.GetIPProperties();
                sMacAddress = adapter.GetPhysicalAddress().ToString();
            }
        } return sMacAddress;
    }

Thursday, 3 April 2014

browser close event

 window.onbeforeunload = function(e) {
            // check condition

            return 'Dialog text here.';
        };

Wednesday, 2 April 2014

export html table to csv file

$(document).ready(function() {

    function exportTableToCSV($table, filename) {

        var $rows = $table.find('tr:has(td)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
            tmpColDelim = String.fromCharCode(11), // vertical tab character
            tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
            colDelim = '","',
            rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
            csv = '"' + $rows.map(function(i, row) {
                var $row = $(row),
                    $cols = $row.find('td');

                return $cols.map(function(j, col) {
                    var $col = $(col),
                        text = $col.text();

                    return text.replace('"', '""'); // escape double quotes

                }).get().join(tmpColDelim);

            }).get().join(tmpRowDelim)
                .split(tmpRowDelim).join(rowDelim)
                .split(tmpColDelim).join(colDelim) + '"',

        // Data URI
            csvData = 'data:application/csv;charset=utf-8,' +
             encodeURIComponent(csv);

        $(this)
            .attr({
                'download': filename,
                'href': csvData,
                'target': '_blank'
            });
    }

    // This must be a hyperlink
    $(".export").on('click', function(event) {
        // CSV
        var fileName = $(this).attr('fileName');
        exportTableToCSV.apply(this, [$('#dvData>table'), fileName + '.csv']);

        // IF CSV, don't do event.preventDefault() or return false
        // We actually need this to be a typical hyperlink
    });
});

Read data on web page and export in excel

<script type="text/javascript">

        $(function() {
            if ($('#ctl00_ContentPlaceHolder1_hdnIsPostBack').val() == '1') {
                OpenWordList();
            }
            $('#<%= FileUploadToServer.ClientID %>').on('change', function(e) {
                $('#<%= btnUpload.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
            });

            $('#<%= SheKeyFileUploadToServer.ClientID %>').on('change', function(e) {
                $('#<%= tbnSheKeyUpload.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
            });

            $('#<%= BenHeKeyFileUploadToServer.ClientID %>').on('change', function(e) {
                $('#<%= btnBenHeKeyUpload.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
            });

            $('#<%= BenSheKeyFileUploadToServer.ClientID %>').on('change', function(e) {
                $('#<%= btnBenSheKeyUpload.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
            });
        });

        function IsConfirmationExist() {
            var msg = confirm("The entered word is already there in the Blocked Word(s) List and you cannot add it here. \n Do you want to Delete from the Blocked Word(s) List to add here.");
            if (msg == true) {
                $('#ctl00_ContentPlaceHolder1_hdnIsExist').val(1);
            }
            else {
                $('#ctl00_ContentPlaceHolder1_hdnIsExist').val(0);
            }
            $('#<%= btnUpdateImportData.ClientID%>').trigger('click');
        }
        function getFile(FileUploadType) {
            if (FileUploadType == 'He') {
                $('#<%= FileUploadToServer.ClientID%>').click();
            }
            if (FileUploadType == 'She') {
                $('#<%= SheKeyFileUploadToServer.ClientID%>').click();
            }

            if (FileUploadType == 'BenHe') {
                $('#<%= BenHeKeyFileUploadToServer.ClientID%>').click();
            }
            if (FileUploadType == 'BenShe') {
                $('#<%= BenSheKeyFileUploadToServer.ClientID%>').click();
            }
        }

        var tr = '<table id="testTable"><tr><td style="font-size:16px; font-weight:bold; color:blue;" id="PageTitle"></td></tr>';
        function ExportPick_Words_Male(fileName) {
            $('#HEwordlist table td:has(:input[type=text])').each(function() {
                //tr = tr + '<tr><td>' + $(this).find("input").val() + '</td></tr>';
                tr = tr + '<tr><td>' + $(this).find("span").html() + '</td></tr>';
            });
            tr = tr + '</table>';
            $('#tblExportList').empty();
            $('#tblExportList').append(tr);
            $('#PageTitle').html('Pick Words - Male');
            tableToExcel('testTable', fileName)
        }


        function ExportPick_Words_Female(fileName) {
            $('#SHEwordlist table td:has(:input[type=text])').each(function() {
                // tr = tr + '<tr><td>' + $(this).find("input").val() + '</td></tr>';
                tr = tr + '<tr><td>' + $(this).find("span").html() + '</td></tr>';
            });
            tr = tr + '</table>';
            $('#tblExportList').empty();
            $('#tblExportList').append(tr);
            $('#PageTitle').html('Pick Words - Female');
            tableToExcel('testTable', fileName)
        }
        function ExportStop_Words(fileName) {
            $('#HEBlock_wordlist table td:has(:input[type=text])').each(function() {
                tr = tr + '<tr><td>' + $(this).find("span").html() + '</td></tr>';

            });
            tr = tr + '</table>';
            $('#tblExportList').empty();
            $('#tblExportList').append(tr);
            $('#PageTitle').html('Stop Words');
            tableToExcel('testTable', fileName)
        }
        function ExportObscene_Words(fileName) {
            $('#SHEBlock_wordlist table td:has(:input[type=text])').each(function() {
                //tr = tr + '<tr><td>' + $(this).find("input").val() + '</td></tr>';
                tr = tr + '<tr><td>' + $(this).find("span").html() + '</td></tr>';
            });
            tr = tr + '</table>';
            $('#tblExportList').empty();
            $('#tblExportList').append(tr);
            $('#PageTitle').html('Obscene Words');
            tableToExcel('testTable', fileName)
        }

        var tableToExcel = (function() {

            var uri = 'data:application/vnd.ms-excel;base64,'
            , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
            , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
            , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
            return function(table, name) {
                if (!table.nodeType) table = document.getElementById(table)
                var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
    </script>