วันศุกร์ที่ 30 พฤษภาคม พ.ศ. 2557

Captcha image in asp.net c#

step 1
download dll mscaptcha to my computer
step 2
Add references from mscaptcha.dll file
step 3
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" %>
in aspx file
step 4
<div>
    <cc1:CaptchaControl ID="Captcha1" runat="server"
 CaptchaBackgroundNoise="Low" CaptchaLength="5"
 CaptchaHeight="60" CaptchaWidth="200"
 CaptchaLineNoise="None" CaptchaMinTimeout="5"
 CaptchaMaxTimeout="240" FontColor = "#529E00" />
    </div>
    <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <asp:Label ID="lblMessage" runat="server" Text="lblMessage"></asp:Label>
input to the aspx file
step 5
protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
            Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
            if (Captcha1.UserValidated)
            {
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "Valid";
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "InValid";
            }
            }
            catch
            {
                Page_Load(sender,e);
            }
        }
input to cs file

วันพุธที่ 28 พฤษภาคม พ.ศ. 2557

get folder structure asp.net c#

step 1 using System.IO;
step 2
Create Button and traeeview on design view.
step3 create function on cs file.
protected void Button1_Click(object sender, EventArgs e)
        {
            Listdirectory(TreeView1,"D:\\program");
        }

        private void Listdirectory(TreeView treeview,string part)
        {
            treeview.Nodes.Clear();
            var rootdirectoryinfo = new DirectoryInfo(part);
            treeview.Nodes.Add(Createdirtolynode(rootdirectoryinfo));
        }
        private static TreeNode Createdirtolynode(DirectoryInfo directory)
        {
            var directorynote = new TreeNode(directory.Name);
            foreach (var direc in directory.GetDirectories())
            {
                directorynote.ChildNodes.Add(Createdirtolynode(direc));
            }
            foreach (var file in directory.GetFiles())
            {
                directorynote.ChildNodes.Add(new TreeNode(file.Name));
            }
            return directorynote;
        }

วันจันทร์ที่ 19 พฤษภาคม พ.ศ. 2557

Edit file web configuration

step 1
using System.Web.Configuration;
using System.Configuration;
step 2
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
Find file the web config.
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
select tax for editor.
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
Edit name tax.
configuration.Save();
save file web config.

วันพฤหัสบดีที่ 17 เมษายน พ.ศ. 2557

connection string by ConfigurationManager

step 1
using System.Configuration;

step 2
add string connection string in file webconfig
<add name="default" connectionString="Driver={Microsoft Access Driver (*.mdb)}; DBQ=part-file database;"/>

step 3
create string connection on file cs
public String strcon = ConfigurationManager.ConnectionStrings["default"].ConnectionString;

Exchange-rate by yahoo

step 1
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

step2
create class ConvertCurrency
public static decimal ConvertCurrency(decimal amount, string from, string to)
        {
            try
            {
                WebClient web = new WebClient();
                const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
                string url = String.Format(urlPattern, from, to);
                string response = new WebClient().DownloadString(url);
                decimal exchangeRate = decimal.Parse(response, System.Globalization.CultureInfo.InvariantCulture);
                return exchangeRate;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

step 3
core function
decimal apiRate = 0;
            apiRate =Class1.ConvertCurrency(1, "USD", "THB");

วันพุธที่ 12 มีนาคม พ.ศ. 2557

sent Email in C#

step 1
using System.Net.Mail
using System.Net

step 2
create mail ,mailto,mail from,mail body,mail subject
MailMessage myMail = new MailMessage();
myMail.From = new MailAddress("info@travexgo.com");
myMail.To.Add(new MailAddress(TextBox4.Text));
myMail.IsBodyHtml = true;
myMail.Subject = "Booking";
myMail.Body ="เนื้อความ"

Step 3
กำหนด Smtp
SmtpClient sm = new SmtpClient("smtp domain");
sm.Port = 25;
sm.Credentials = new NetworkCredential("User", "Password");

Step 4
ทำการส่งโดยใช้ SMTP และ เคลียค่าเมลล์
sm.Send(myMail1);
myMail1 = null;

การใช้งาน Ispostback c#

Ispostback ใช้ในกรณีในการ Refresh หน้าตัวเองหรือกดปุ่ม ที่ runat="server" จะทำให้ IsPostback เป็น True แต่ถ้าเป็นการเรียกหน้านั้นครั้งแรก Ispostback จะเป็นค่า false
ตัวอย่าง
if (IsPostBack)
            {
                condition += check_sqlcondition(var_search_cabin_class, var_search_form, "", "", "");
            }

วันอังคารที่ 11 มีนาคม พ.ศ. 2557

loop droupdown List

public void datalist_qry(string sql_condition,DropDownList var_object)
        {
            SqlConnection con = new SqlConnection(connectionString);
            string var_sql_condition= sql_condition;
            DataTable ds1 = new DataTable();
            SqlDataAdapter da1 = new SqlDataAdapter(var_sql_condition,con);
            da1.Fill(ds1);
            for(int i=0; i<ds1.Rows.Count; i++)
            {
               var_object.Items.Add(new ListItem(ds1.Rows[i][0].ToString(), ds1.Rows[i][0].ToString()));
            }
           
        }

วันศุกร์ที่ 21 กุมภาพันธ์ พ.ศ. 2557

การ redirect

redirect+query string
Response.Redirect("./Backoffice.aspx?+query string);
redirect+deary
Response.AddHeader("REFRESH", "5;URL=../");
redirect normal
Response.Redirect("./Backoffice.aspx");

วันพฤหัสบดีที่ 20 กุมภาพันธ์ พ.ศ. 2557

ดึงข้อมูลจากฐานข้อมมูลแสดงบน button

Button1.Text = CStr(dt.Rows(0).Item(1).ToString)
Button2.Text = CStr(dt.Rows(1).Item(1).ToString)
Button3.Text = CStr(dt.Rows(2).Item(1).ToString)

Button4.Text = CStr(dt.Rows(3).Item(1).ToString)
cr.by greatfriends

Encode decode Url

step 1.
using System.Security.Cryptography;
using System.IO;
step 2.
create class
public class EncryptDecryptQueryString
{
    private byte[] key = { };
    private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
    public string Decrypt(string stringToDecrypt, string sEncryptionKey)
    {
        byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
        try
        {
            key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(stringToDecrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
              des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

    public string Encrypt(string stringToEncrypt, string SEncryptionKey)
    {
        try
        {
            key = System.Text.Encoding.UTF8.GetBytes(SEncryptionKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
              des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
}

step 3.
Page 1

if (HttpContext.Current != null)
                                {
                                    string strURLWithData = "Backoffice.aspx?" + EncryptQueryString(string.Format("Typeuser={0}", strtype));
                                    HttpContext.Current.Response.Redirect(strURLWithData);
                                }
                                else
                                {
                                }

public string EncryptQueryString(string strQueryString)
        {
            EncryptDecryptQueryString objEDQueryString = new EncryptDecryptQueryString();
            return objEDQueryString.Encrypt(strQueryString, "r0b1nr0y");
        }

step 4.
Page 2.

if (!IsPostBack)
            {
                string strReq = "";
                strReq = Request.RawUrl;
                strReq = strReq.Substring(strReq.IndexOf('?') + 1);

                if (!strReq.Equals(""))
                {
                    strReq = DecryptQueryString(strReq);

                    //Parse the value... this is done is very raw format..
                    //you can add loops or so to get the values out of the query string...
                    string[] arrMsgs = strReq.Split('&');
                    string[] arrIndMsg;
                    string strtype = "";
                    arrIndMsg = arrMsgs[0].Split('='); //Get the Name
                    strtype = arrIndMsg[1].ToString().Trim();
                    if (strtype == "Admin")
                    {
                        Label1.Visible = true;
                    }
                    else if (strtype == "User")
                    {
                        Label1.Visible = false;
                    }
                }
                else
                {
                    Response.Redirect("Page1.aspx");
                }

end