Friday, 31 March 2017

How to print Datetime in JavaScript?

//Html Div
<div id='ct'></div>


//JavaScript Code
 <script type="text/javascript">
        function startTime() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            var x1 = checkTime(today.getDate()) + "-" + checkTime(today.getMonth() + 1) + "-" +             checkTime(today.getFullYear());
            document.getElementById('ct').innerHTML = x1 + " " + h + " " + m + " " + s;
            var t = setTimeout(startTime, 500);
        }
        function checkTime(i) {
            if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
            return i;
        }
    </script>

Friday, 10 March 2017

How to display data in datalist in c#?

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class displaydata : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\gtu.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {

        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from table_name";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        d1.DataSource = dt;
        d1.DataBind();
    }
}


////display.aspx - source page

<asp:DataList ID="d1" runat="server" RepeatColumns="3">
    <HeaderTemplate>
        <table>
            <tr>
                <td style="background-color: White;">
                    Name</td>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <center>
                    <span style="color: #6b633f">
                        <%#Eval("column_name") %>
                    </span>
                </center>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:DataList>

SQL Database connection with Store Procedure in c#.






using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class login : System.Web.UI.Page
{
    SqlConnection _con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\gtu.mdf;Integrated Security=True;User Instance=True");
    string uname, password;
    protected void Page_Load(object sender, EventArgs e)
    {
        uname = txt_username.text;
        password = txt_password.text;

        _con.Open();
        SqlCommand _cmd = _con.CreateCommand();
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.CommandText = "c_login";
        _cmd.Parameters.Add("@unm", SqlDbType.VarChar).Value = uname.ToString();
        _cmd.Parameters.Add("@pwd", SqlDbType.VarChar).Value = password.ToString();

        _cmd.ExecuteNonQuery();
        DataTable _dt = new DataTable();
        SqlDataAdapter _da = new SqlDataAdapter(_cmd);
        _da.Fill(_dt);

        foreach (DataRow _dr in _dt.Rows)
        {
            Session["uname"] = _dr["unm"].ToString();
            Response.Write("aa");
        }
        _con.Close();
    }
}


//Store Procedure Create in DB

CREATE PROCEDURE c_tlogin
/*
Parameter Declare
*/
@unm varchar(50),
@pwd varchar(50)
AS
/* SET NOCOUNT ON */
select * from login where username=@unm and password=@pwd
RETURN

Thursday, 9 March 2017

How to upload / download file from the FTP Server in Asp.net c#?

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    // Upload file
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        //fileName = Name of the file to be downloaded from FTP server.
        string fileName = "test.txt";

        //filePath = The full path where the file is to be created. Here i put local system path.
        string filePath = "C:\\FTP";

        string ftpServerIP = "IP Address";
        string ftpUserID = "User ID";
        string ftpPassword = "Password";
        FtpWebRequest reqFTP;
        try
        {
            FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
            string errMsg = (ex.Message);
        }
    }

 
    // Download file
    protected void btn_Download_Click(object sender, EventArgs e)
    {
        string filename = "c:\\test.txt";
        string ftpServerIP = "IP address";
        string ftpUserID = "User ID";
        string ftpPassword = "Password";

        FileInfo fileInf = new FileInfo(filename);

        string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

        FtpWebRequest reqFTP;

        // Create FtpWebRequest object
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

        //Provide ftp userid and password
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        // By default KeepAlive is true, where the control connection is not closed
        // after a command is executed.
        reqFTP.KeepAlive = false;

        //Specify the command to be executed. Here we use upload file command
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

        //data transfer type we use here is binary
        reqFTP.UseBinary = true;

        // Notify the server about the size of the uploaded file
        reqFTP.ContentLength = fileInf.Length;

        // The buffer size is set to 2kb
        int buffLength = 2048;

        byte[] buff = new byte[buffLength];

        int contentLen;

        // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
        FileStream fs = fileInf.OpenRead();

        try
        {

            // Stream to which the file to be upload is written
            Stream strm = reqFTP.GetRequestStream();

            // Read from the file stream 2kb at a time
            contentLen = fs.Read(buff, 0, buffLength);

            // Till Stream content ends
            while (contentLen != 0)
            {

                // Write Content from the file stream to the FTP Upload Stream
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }

            // Close the file stream and the Request Stream
            strm.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            string ErrMsg = ex.Message;
        }
    }
}

What is the difference between Autopostback and Ispostback in c#?

Autopostback - Property of the control.

IsPostback - Property of the Page class.


--------------------------------------------------------------------------------------------------------------------------
Autopostback - get and set property to control postback on changes made for control.
for e.g.
this.ListBox1.AutoPostBack = true;
whenever user will select item the page will get post back.

--------------------------------------------------------------------------------------------------------------------------
IsPostback - get property of the Page class to check if page is post back
i.e. if it is true then page has already executed Init function of the page else it is first time the page has requested to be executed.

Wednesday, 8 March 2017

How To use POST Method in C#?


//Code Behiend
//Add Library
using System.Web.UI.HtmlControls;

[WebMethod]
public static string PostMethod(string parameter)
{
//you can return your string value
return parameter;
}

//Design Page
//Add javascript Library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

//Add This Script
<script type="text/javascript">
 $.ajax({
type: "POST",
url: "pagename.aspx/PostMethod",
data: "{parameter:'123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r.d);
}
});
</script>

How To Check Control is Exits or Not in Javascript?

if (document.getElementById('Your_Control_Id') != undefined)
{
    document.getElementById('Your_Control_Id').textContent = valueofmeter;
}

How To Assign Value In Textbox using JavaScript?

-------------------------------------------------------------------------
//Asp C# Controls
-------------------------------------------------------------------------
document.getElementById('textbox_name').value = "Your value";


-------------------------------------------------------------------------
//Html Controls For All Operating System
-------------------------------------------------------------------------
document.getElementById('Control_Name').innerText = "Your value";

OR

-------------------------------------------------------------------------
//For Linux Ubuntu Operating System
-------------------------------------------------------------------------
document.getElementById('Control_Name').textContent = "Your value";

How to Encrypt/Decrypt Password in C#?

//Code Behiend C#
public static void PageLoad()
{
string strKey = "Your Private Key";

//For Encrypt
strKey strName = "administrator";
string strEPassword = Encrypt(strName,strKey);

//For Decrypt
string strEncryptKey = "3zm5dPl2XoXFFcCite50AiKVto/mOlKCR24YFh4XSU0=";
string strDPassword = Decrypt(strEncryptKey,strKey);

}

//Add This Library in Your Page
using System.Security.Cryptography;

public static string GenerateAPassKey(string passphrase)
{
string passPhrase = passphrase;
string saltValue = passphrase;
string hashAlgorithm = "SHA1";
int passwordIterations = 2;
int keySize = 256;
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] Key = pdb.GetBytes(keySize / 11);
String KeyString = Convert.ToBase64String(Key);
return KeyString;
}

public static string Encrypt(string plainStr, string KeyString)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = 256;
aesEncryption.BlockSize = 128;
aesEncryption.Mode = CipherMode.ECB;
aesEncryption.Padding = PaddingMode.ISO10126;
byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);
aesEncryption.Key = KeyInBytes;
byte[] plainText = ASCIIEncoding.UTF8.GetBytes(plainStr);
ICryptoTransform crypto = aesEncryption.CreateEncryptor();
byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherText);
}

public static string Decrypt(string encryptedText, string KeyString)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = 256;
aesEncryption.BlockSize = 128;
aesEncryption.Mode = CipherMode.ECB;
aesEncryption.Padding = PaddingMode.ISO10126;
byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);
aesEncryption.Key = KeyInBytes;
ICryptoTransform decrypto = aesEncryption.CreateDecryptor();
byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length);
return ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length));
}

Tuesday, 7 March 2017

Send Mail With Attached File in C#.

public static void SendEmail()
{
try
{
string ToID = "ToMailId@demo.com", subject = "TestMail", message = "Test Mail Message.", FromId = "FromMailId@demo.com", username = "user", password = "pwd", smtp = "demo.mail.com";
int port = 25;

var loginInfo = new NetworkCredential(username, password);
var msg = new MailMessage(FromId,ToID);
var smtpClient = new SmtpClient(smtp, port);

msg.Subject = subject;
msg.Body = message;

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:\\test.txt");
msg.Attachments.Add(attachment);

msg.IsBodyHtml = true;

smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
catch (Exception ex)
{
LogInfo.ExceptionLog(ex, "SendEmail", "SendEmail", true);
}
}

How to send main in C#?

public static void SendEmail()
{
try
{
string ToID = "ToMailId@demo.com",
                                        subject = "TestMail",
                                        message = "Test Mail Message.",
                                        FromId = "FromMailId@demo.com",
                                        username = "user",
                                        password = "pwd",
                                        smtp = "demo.mail.com";
int port = 25;

var loginInfo = new NetworkCredential(username, password);
var msg = new MailMessage(FromId,ToID);
var smtpClient = new SmtpClient(smtp, port);

msg.Subject = subject;
msg.Body = message;

msg.IsBodyHtml = true;

smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
catch (Exception ex)
{
LogInfo.ExceptionLog(ex, "SendEmail", "SendEmail", true);
}
}

Postgres Database backup in C#.

public static void DatabaseBackup()
{
BackupDatabase("127.0.0.1","5432","postgres","password","MyDataBase",C:\\Users\\Admin\\Desktop\\,"MyDatabase_","C:\\Program Files\\PostgreSQL\\9.4\\bin");
}

public static string BackupDatabase(
            string server,
            string port,
            string user,
            string password,
            string dbname,
            string backupdir,
            string backupFileName,
            string backupCommandDir)
{
try
{

Environment.SetEnvironmentVariable("PGPASSWORD", password);

string backupFile = backupdir + backupFileName + DateTime.Now.ToString("yyyy") + "_" + DateTime.Now.ToString("MM") + "_" + DateTime.Now.ToString("dd") + ".backup";
string BackupString = "-ibv -Z3 -f \"" + backupFile + "\" " +
"-Fc -h " + server + " -U " + user + " -p " + port + " " + dbname;

Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = backupCommandDir + "\\pg_dump.exe";
proc.StartInfo.Arguments = BackupString;

proc.Start();
proc.WaitForExit();
proc.Close();

return backupFile;
}
catch (Exception ex)
{
return null;
}
}

Generate XLSX File using NPOI in c#.


//Add References
NPOI.dll
NPOI.OOXML.dll
NPOI.OpenXml4Net.dll
NPOI.OpenXmlFormats.dll

//Add Library --
using NPOI.XSSF.UserModel;

public void GenerateXLSFileNPOI(DataTable _dt)
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = new XSSFSheet();

wb = new XSSFWorkbook();

// create sheet
sh = (XSSFSheet)wb.CreateSheet("Sheet1");

//Add Header Row
var r0 = sh.CreateRow(0);
//Add Header in Row From The Datatable
for (int j = 0; j < _dt.Columns.Count; j++)
{
r0.CreateCell(j);
sh.GetRow(0).GetCell(j).SetCellValue(_dt.Columns[j].ToString());
}

//Data Add In Rows From The DataTable
for (int i = 0; i < _dt.Rows.Count; i++)
{
var r = sh.CreateRow(i + 1);
for (int j = 0; j < _dt.Columns.Count; j++)
{
r.CreateCell(j);
sh.GetRow(i + 1).GetCell(j).SetCellValue(_dt.Rows[i][j].ToString());
}
}

//Finaly Write Data InTo Xlsx File
using (var fs = new FileStream("test.xlsx", FileMode.Create, FileAccess.Write))
{
wb.Write(fs);
}
}

Sunday, 5 March 2017

How To Convert Datatable To HTML Table Using StringBuilder in C#?

Add Library --
using System.Text;

public static string ConvertDataTableToHTML(DataTable dt)
    {
        string tab = "\t";

        StringBuilder sb = new StringBuilder();

        sb.AppendLine("<table class='classname'>");

        // headers.
        sb.Append(tab + tab + tab + "<tr>");

        foreach (DataColumn dc in dt.Columns)
        {
            sb.AppendFormat("<td>{0}</td>", dc.ColumnName);
        }

        sb.AppendLine("</tr>");

        // data rows
        foreach (DataRow dr in dt.Rows)
        {
            sb.Append(tab + tab + tab + "<tr>");

            foreach (DataColumn dc in dt.Columns)
            {
                string cellValue = dr[dc] != null ? dr[dc].ToString() : "";
                sb.AppendFormat("<td>{0}</td>", cellValue);
            }

            sb.AppendLine("</tr>");
        }

        sb.AppendLine("</table>");

        return sb.ToString();
    }

How To Convert Datatable To HTML Table Using HTmlGenericContorl in C#?

Add Library --
using System.Web.UI.HtmlControls;

public static void ConvertDataTableToHTMLWithHTmlGenericContorl(DataTable dt)
    {
        HtmlGenericControl table = new HtmlGenericControl("table"); //Table create
        table.Attributes.Add("class", "classname"); //assign class

        HtmlGenericControl thead = new HtmlGenericControl("thead"); // add thead tag
        HtmlGenericControl tr = new HtmlGenericControl("tr"); //add header row

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            HtmlGenericControl th = new HtmlGenericControl("th"); // add column of header
            th.InnerText = dt.Columns[i].ColumnName.ToString();
            th.Attributes.Add("class", "classname");

            tr.Controls.Add(th); // add every th in header row
        }
        thead.Controls.Add(tr); // header row add in thead
        table.Controls.Add(thead); //thead add in table

        HtmlGenericControl tbody = new HtmlGenericControl("tbody"); //add tbody tag
        //for datatable row count loop
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            HtmlGenericControl dataTR = new HtmlGenericControl("tr"); // add row
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                HtmlGenericControl td = new HtmlGenericControl("td"); // add column
                td.InnerText = dt.Rows[i][j].ToString();
                td.Attributes.Add("class", "classname");
                dataTR.Controls.Add(td);//add every column in row
            }
            tbody.Controls.Add(dataTR); //row will add in tbody tag
        }

        table.Controls.Add(tbody); // tbody all row will add in table.

        //Finaly table content add in your page div id
        DataDiv.Controls.Add(table);
    }

How To Convert Datatable To HTML Table in C#?

public static string ConvertDataTableToHTML(DataTable dt)
    {
        string html = "<table class='classname'>";

        //add header row
        html += "<tr>";
        for(int i=0;i<dt.Columns.Count;i++)
            html+="<td>"+dt.Columns[i].ColumnName+"</td>";
        html += "</tr>";

        //add rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html += "<tr>";
            for (int j = 0; j< dt.Columns.Count; j++)
                html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
            html += "</tr>";
        }
        html += "</table>";

        return html;
    }

How to Blink Border Using JQuery?

Border Blink Using JQuery

<div class="divborder"></div>

/* CSS Class */
.divborder
{
/*or other element you want*/
animation-name: blink;
animation-duration: .8s;
animation-timing-function: step-end;
animation-iteration-count: infinite;
animation-direction: alternate;
}

/* JQuery Code */
$(function () {
var flag = true;
setInterval(function () {
if (flag) {
$(".divborder").css('border', '1px solid #007baf');
flag = false;
}
else {
$(".divborder").css('border', '1px solid #d9d9d9');
flag = true;
}
}, 500);
});