Thứ Hai, 10 tháng 6, 2013

Return nhiều giá trị từ webservices và gửi mảng json xuống webservices

Cách return nhiều giá trị từ webservices

Code dưới webservices

JavaScriptSerializer js = new JavaScriptSerializer();
     return js.Serialize(new
     {
          accounts = accounts,
          schools = schools,
          subjclass = subjclass

      });

accounts  : tên biến
accounts : giá trị

Code phía client 

Cần phải parse chuổi json trả về để lấy được từng giá trị

success: function (msg) {
                 var data = $.parseJSON(msg.d);
                 accounts = data.accounts;
            }


Cách gửi 1 chuổi json xuống webservices
// ===================== CHUẨN BỊ DỮ LIỆU  GỬI XUỐNG SERVICES =====================
      // ĐỐI VỚI BÀI VÍ DỤ NÀY, MÌNH LỒNG TỚI 3 LỚP DỮ LIỆU NÊN HƠI LẰNG NHẰNG, NẾU KHÔNG MUỐN BẠN CÓ THỂ BỎ BỚT, DÙNG 1,2 HAY 10 LỚP CŨNG THẾ THÔI @@

    // Dữ liệu gửi xuống là kiểu json chứa 2 đối tượng programs và name.
    // Trong đó programs là kiểu object (ko biết diễn tả, tạm gọi là json con)
    // Bên trong programs sẽ chứa các đối tượng lessons, description
    // Trong đó kiểu lessons lại là kiểu object (gọi json con tiếp nhá @@)
    // Bên trong lessons chứa lesson_id

    //Nói lằng nhằng quá để dể hình dung đối tượng gửi xuống có dạng tổng quát như sau
    /*
        Object
        {
            name,
            programs
            {
                object
                {
                    description,
                    lessons
                    {
                        lesson_id,
                        lesson_id,
                    }
                }
                object
                {
                    description,
                    lessons
                    {
                        lesson_id,
                        lesson_id,
                    }
                }
            }
        }
    */


    // Get dữ liệu name
    var name = $("#name").val();

    // Khai báo 1 mảng programs để chứa các giá trị con
    var programs = [];

    // Cấu trúc vòng lặp trong jquery để get giá trị, ở đây ý nghĩa là lặp qua từng thẻ li trong thẻ cha có id là ulxyz
    $('#ulxyz > li').each(function (index, elem) {

        // Khai báo 1 mảng lessons để chứa các giá trị con (giống trên)
            var lessons = [];

        // Lại vòng lặp tiếp nha @@
        $(this).children().find(".dragLesson").each(function (i, e) {
            var lesson_id = $(this).children(".lesson_id").text();
            // Gán giá trị con vào mảng
            lessons.push(lesson_id);
        });
        var des = "abcxyz";

        // Sử dụng 1 mảng tạm (temp) để lấy lấy các giá trị, sau đó gán nó vào mảng cha
        var temp = {lessons: lessons, description: des };
        programs.push(temp);
    })


// Rồi giờ chỉ việc gửi đi thôi @@ xuống dưới mình sẽ chỉ các bạn cách nhận nó sau       
$.ajax({
    type: 'POST',
    url: 'Program.asmx/Program',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ programs: programs, name: name }),
    success: function (s) {

    }
});

// ===================== VÂNG VÀ BÂY GIỜ SẺ LÀ CÁCH NHẬN DỮ LIỆU =====================
Nói thì dài dòng, chứ thật ra nó đơn giản là ... gửi kiểu ji` thì nhận kiểu đó

public bool Program(List<Program_Data> programs, string name)
{

}
Mình sử dụng List<Program_Data> programs để nhận dữ liệu gửi xuống (chú ý tên biến phải giống nhau nha, programs : programs)
Và tất nhiên các đối tượng chứa bên trong Program_Data cũng giống như dữ liệu gửi xuống

public class Program_Data
{
    public int[] lessons;
    public string description;
}

Rồi hết @@


Thứ Tư, 27 tháng 3, 2013

Làm việc với XML - C#

Create
XDocument xmlEnrollmentState = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XComment("this is comment"),
            new XElement("EnrollmentState",
               new XElement("Config",
                   new XElement("School_Name","1"),
                   new XElement("RegistNumber",registNumber),
                   new XElement("PassNumber", passNumber),
                   new XElement("BeginDate",beginXMLDate),
                   new XElement("EndDate",endXMLDate),
                   new XElement("Opportunity", Opportunity),
                   new XElement("TargetNumber", tagetnumber),
                   new XElement("PubDate", pubDate),
                   new XElement("Note", Note)),
                new XElement("Data"),
                new XElement("RootNow","0"))
           );
Save
xmlEnrollmentState.Save(Server.MapPath("~/Admin/Uploaded/OutputXML.xml"));

Add Element or Attribute
xmlEnrollmentState.Root.Element("Data").Add(new XElement("Row", new XAttribute("hide", dtBegin.ToString()), dtBegin.ToString("dd/MM") + " - " +end.ToString("dd/MM/yyyy")));

Change value Element
xmlEnrollmentState.Root.Element("RootNow").SetValue(123456);

Read file XML
// khai báo xmldocument
            XmlDocument xEnroll = new XmlDocument();

// đổ dữ liệu từ file xml
            xEnroll.Load(Server.MapPath("~/Admin/Uploaded/OutputXML.xml"));

// khai báo 1 danh sách các nút Row
            XmlNodeList nodes = xEnroll.SelectNodes("EnrollmentState/Data/Row");

// duyệt qua từng nút và lấy dữ liệu
            foreach (XmlNode i in nodes)
            {
                date.Add(new { begin = i.InnerText, hide = i.Attributes["hide"].Value });
            }

//đối với thẻ đơn thì chỉ cần lấy dữ liệu như thế này
            string k = xEnroll.SelectSingleNode("EnrollmentState/RootNow").InnerText;





Mã hóa MD5, Send Email, tạo password ngẫu nhiên

public string MD5(string password) // chuổi password cần mã hóa
    {
        byte[] textbytes = System.Text.Encoding.Default.GetBytes(password);
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider crythandler;
            crythandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash = crythandler.ComputeHash(textbytes);
            String ret = "";
            foreach (byte a in hash)
            {
                if (a < 16)
                    ret += "0" + a.ToString("x");
                else
                    ret += a.ToString("x");
            }
            return ret;
        }
        catch
        {
            throw;
        }
    }
 /// hàm mã hóa password md5
        public string EncodePassword(string originalPassword)
        {
            //Declarations
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;

            //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            md5 = new MD5CryptoServiceProvider();

            originalBytes = UTF8Encoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);

            //Convert encoded bytes back to a 'readable' string
            return BitConverter.ToString(encodedBytes);
        }

public bool SendMailDetails(string Frommail, string pass, string Tomail, string Tenhienthi, string Title, string Content, string Host)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(Frommail, Tenhienthi, Encoding.UTF8);
            mail.To.Add(Tomail);
            mail.Subject = Title;
            mail.SubjectEncoding = Encoding.UTF8;
            mail.Body = Content;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true;

            SmtpClient mySmtpClient = new SmtpClient();
            mySmtpClient.Host = Host;
            mySmtpClient.Credentials = new System.Net.NetworkCredential(Frommail, pass);
            mySmtpClient.EnableSsl = true;
            try { mySmtpClient.Send(mail); } //--Gửi mail
            catch { return false; }

            return true;
        }

       Host : smtp.gmail.com : nếu from mail là gmail



        // tạo ra password ngẫu nhiên
        public string GenerateRandomPassword(int length)
        {
            string allowedLetterChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
            string allowedNumberChars = "0123456789";
            char[] chars = new char[length];
            Random rd = new Random();
            bool useLetter = true;
            for (int i = 0; i < length; i++)
            {
                if (useLetter)
                {
                    chars[i] = allowedLetterChars[rd.Next(0, allowedLetterChars.Length)];
                    useLetter = false;
                }
                else
                {
                    chars[i] = allowedNumberChars[rd.Next(0, allowedNumberChars.Length)];
                    useLetter = true;
                }
            }
            return new string(chars);
        }










Thứ Ba, 26 tháng 3, 2013

Các kỹ thuật sử dụng Ajax với webservice - ASP

Đầu tiên ta tạo 1 file3313dd5a702c8223f0f674d8bc5ede57_54336530.ajaximg1.jpg (955×582)Trong Code behind của WebService.asmx ta phải gỡ ghi chú dòng [System.Web.Script.Services.ScriptService] Nếu không ta không thể gọi từ Script được
c149063ef539730f1fb2a57005bc897b_54336534.ajaximg2.png (541×194)


Tiếp theo ta xây dựng các hàm có kiểu trả về như bình thường (có thể string, int, bool ...)
Vd:
[WebMethod]
public int RestoPassword(string username, string email)
        {
            ibtEntities db = new ibtEntities();
            var user = db.users.FirstOrDefault(x => x.loginName == username);
            if (user != null)
            {
                if (user.email == email)
                {
                    Lib.Users users = new Lib.Users();
                    if (users.ForgetPass(username,email))
                        return 2; // khôi phục thành công
                    else
                        return 3; // khôi phục thất bại
                }
                else
                {
                    return 0; // email ko khớp với username
                }
            }
            else
            {
                return 1; // username ko tồn tại
            }     
        }       

Chú ý là trên mỗi hàm đều phải có [WebMethod] để hàm có thể thực thi được.
Trường hợp nếu bạn muốn sử dụng Session trong hàm thì thay vì khai báo thêm (EnableSession = true)]
Vd: [WebMethod(EnableSession = true)]
Cú pháp gọi session:
string name = HttpContext.Current.Session["CurrentUser"].ToString();


Cú pháp script để gọi hàm từ Service.asmx
$.ajax({
                type: "POST",
                url: "Service.asmx/RestoPassword",
                data: '{"username":"' + username + '","email":"' + emai + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#waiting").hide();
                    result = msg.d;
                    if (result == 0) {
                        $("#isValidEmail").addClass("info-show"); // email ko khớp với tài khoản                       
                    }
                    else {
                        if (result == 1) {
                            $("#info-username2").addClass("info-show");
                        }
                        else {
                            if (result == 2) {
                                $(".success").show(); // khôi phục thành công
                            }
                            else {
                                $(".fail").show(); // khôi phục thất bại
                            }
                        }
                    }

                }

            });
Chú ý :
url: "Service.asmx/RestoPassword",
Service.asmx : tên file .asmx
RestoPassword : tên hàm (không cần chú ý tới biến)

data: '{"username":"' + username + '","email":"' + emai + '"}',
username, email : tên biến khai báo bên trong hàm ở file .asmx
username : biến chứ giá trị (ví dụ luong, nguyen ...)

msg.d : Giá trị trả về (kiểu var)




Kết nối SQL server - C#

public String con_str = "Data Source=.;Initial Catalog=LTFDatabase;Integrated Security=True";

    public DataSet Opendataset(String sql)
    {
        SqlConnection con = new SqlConnection(con_str);
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }

    public DataTable Opendatatable(String sql)
    {
        SqlConnection con = new SqlConnection(con_str);
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dtb = new DataTable();
        da.Fill(dtb);
        return dtb;
    }

    public string ExecuteScalar(string sql)
    {
        SqlConnection con = new SqlConnection(con_str);
        SqlCommand cmd = new SqlCommand(sql, con);
        con.Open();
        string kq = cmd.ExecuteScalar().ToString();
        con.Close();
        cmd.Dispose(); return kq;
    }

    public bool ExcSql(string sql)
    {
        SqlConnection con = new SqlConnection(con_str);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = sql;
        cmd.Connection = con;

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            return true;

        }
        catch
        {
            return false;
        }
        finally
        {
            con.Close();
        }
    }