Friday, August 26, 2016
Create Windows Service and Send Mail Daily At Fixed Time Using C#
0 comments Posted by Duc Nguyen at 12:01 AMIntroduction
In this article I am explaining how
to create a Windows Service to schedule daily mail at a specified time.
Scheduling email and sending the email is a basic requirement of any
project.
Step 1
Open Visual Studio and
create a new project. Under Windows Desktop select Windows Service and
provide a proper name and click on the OK button.
More link...
Monday, August 15, 2016
1. Query tìm kiếm trong SQL
- Bản chất của việc tìm kiếm là việc chúng ta sẽ lập trình để thực thi một câu lệnh SQL với keyword được nhập từ người dùng, cấu trúc lệnh SQL cho việc tìm kiếm trong ví dụ này như dưới đây. Trong trường hợp này mình cho phép tìm từ khóa trong cả tiêu đề "Title" và nội dung "Content"
1
2
| select * from [Articles] where ([Title] like '%keyword%' or [Content] like '%keyword%' ) |
1
2
| select * from [Articles] where ([Title] like N '%Võ Khánh Thụy%' or [Content] like N '%Võ Khánh Thụy%' ) |
1
2
3
4
| select * from [Articles] where ([Title] like N '%Võ%' or [Content] like N '%Võ%' ) and ([Title] like N '%Khánh%' or [Content] like N '%Khánh%' ) and ([Title] like N '%Thụy%' or [Content] like N '%Thụy%' ) |
2. Xử lý từ khóa người dùng nhập vào
- Với yêu cầu tìm kiếm mà người dùng nhập vào từ form tìm kiếm sẽ phải qua một số bước xử lý dữ liệu như loại bỏ các ký tự cấm trong SQL, xử lý tiếng việt không dấu...Tuy nhiên trong phần này mình chỉ muốn nói qua về cách tách chuỗi từ khóa được nhập vào để tăng kết quả tìm kiếm như mình đã đề cập ở trên. Mình sử dụng đoạn code dưới đây để tách chuỗi từ khóa người dùng nhập vào thành 1 mảng các từ khóa độc lập
1
2
| // Turn user input to a list of keywords. string [] keywords = txtKeyWord.Text.Split( new string [] { " " }, StringSplitOptions.RemoveEmptyEntries); |
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| /// /// Search records from database. /// |
/// the list of keywords
/// all found records
public
List Search(List<
string
> keywords)
{
// Generate a complex Sql command.
StringBuilder sqlBuilder =
new
StringBuilder();
sqlBuilder.Append(
"select * from [Articles] where "
);
foreach
(
string
item
in
keywords)
{
sqlBuilder.AppendFormat(
"([Title] like '%{0}%' or [Content] like '%{0}%') and "
, item);
}
// Remove unnecessary string " and " at the end of the command.
string
sql = sqlBuilder.ToString(0, sqlBuilder.Length - 5);
return
QueryList(sql);
}
///
/// Excute a Sql command.
///
/// Command text
protected
List QueryList(
string
cmdText)
{
List articles =
new
List();
SqlCommand cmd = GenerateSqlCommand(cmdText);
using
(cmd.Connection)
{
SqlDataReader reader = cmd.ExecuteReader();
// Transform records to a list.
if
(reader.HasRows)
{
while
(reader.Read())
{
articles.Add(ReadArticle(reader));
}
}
}
return
articles;
}
3. Hightlight Keyword
- Sau khi hoàn thành các bước ở phần 1 & 2, chúng ta đã có thể lấy được kết quả tìm kiếm trả về, và các bạn có thể bind dữ liệu vào repeate, listview hay datalist... thì tùy vào mục đích sử dụng. Phần này mình muốn nói thêm về cách đánh dấu từ khóa tìm kiếm trên danh sách kết quả tìm kiếm trả về trên giao diện người dùng.- Đầu tiên mình sẽ viết css cho phân hightlight keyword của mình
1
2
3
4
5
6
|
|
1
| keyword thay thế bằng |
1
2
3
4
5
6
7
8
9
| //hight light keyword foreach ( string keyItems in keyList) { foreach (Article items in _ls) { items.Title = items.Title.Replace(keyItems, "" + keyItems + " |
);
items.Content = items.Content.Replace(keyItems,
""
+ keyItems +
"
);
}
}
- Với cách làm trên mình thấy chạy khá ổn khi tìm kiếm với lượng dữ liêu vừa phải, tuy nhiên nếu xử lý với dữ liệu lớn sẽ không được tối ưu.
Wednesday, May 4, 2016
File upload and download using JQuery and submit button ASP.net
0 comments Posted by Duc Nguyen at 8:33 PMThe Post method
This method will look in the Request object to see if there are any posted files. If so, it will loop over the files and create them on the server side. The server will return a 201 HttpStatus and a list of strings that will contain the full path of the file(s) at server side. When there are no files posted, the service will return a 401 status a.k.a. BadRequest.public HttpResponseMessage Post() { HttpResponseMessage result = null; var httpRequest = HttpContext.Current.Request; // Check if files are available if (httpRequest.Files.Count > 0) { var files = new List<string>(); // interate the files and save on the server foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName); postedFile.SaveAs( filePath); files.Add(filePath); } // return result result = Request.CreateResponse(HttpStatusCode.Created, files); } else { // return BadRequest (no file(s) available) result = Request.CreateResponse(HttpStatusCode.BadRequest); } return result; }
The Get Method
As mentioned before, the Get Method will accept a string file that will identify (= filename) the file that needs to be downloaded.public HttpResponseMessage Get(string id) { HttpResponseMessage result = null; var localFilePath = HttpContext.Current.Server.MapPath("~/" + id); // check if parameter is valid if (String.IsNullOrEmpty(id)) { result = Request.CreateResponse(HttpStatusCode.BadRequest); } // check if file exists on the server else if (!File.Exists(localFilePath)) { result = Request.CreateResponse(HttpStatusCode.Gone); } else {// serve the file to the client result = Request.CreateResponse( HttpStatusCode.OK); result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read)); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = id; } return result; }
Uploading a File
Using a submit button
<form name="form1" method="post" action="api/file" enctype="multipart/form-data"> <div> <label> Using submit</label> <input name="myFile" type="file" /> </div> <div> <input type="submit" value="Submit" /> </div> </form>
Using JQuery
<form enctype="multipart/form-data"> <label> Using JQuery</label> <input name="file" type="file" /> <input type="button" id="Upload" value="Upload" /> </form>
<script type="text/javascript"> $(function () { $('#Upload').click(function () { var formData = new FormData($('form')[0]); $.ajax({ url: 'api/file', type: 'POST', // Form data data: formData, //Options to tell JQuery not to process data or worry about content-type cache: false, contentType: false, processData: false }); }); }); </script>
Sunday, April 24, 2016
public static double StdDev<T>(this IEnumerable<T> list, Func<T, double> values)
{
// ref: http://stackoverflow.com/questions/2253874/linq-equivalent-for-standard-deviation
// ref: http://warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/
var mean = 0.0;
var sum = 0.0;
var stdDev = 0.0;
var n = 0;
foreach (var value in list.Select(values))
{
n++;
var delta = value - mean;
mean += delta / n;
sum += delta * (value - mean);
}
if (1 < n)
stdDev = Math.Sqrt(sum / (n - 1));
return stdDev;
}
Or
public static double StdDev(this IEnumerable values)
{
// ref: http://warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/
double mean = 0.0;
double sum = 0.0;
double stdDev = 0.0;
int n = 0;
foreach (double val in values)
{
n++;
double delta = val - mean;
mean += delta / n;
sum += delta * (val - mean);
}
if (1 < n)
stdDev = Math.Sqrt(sum / (n - 1));
return stdDev;
}
ref: http://stackoverflow.com/questions/2253874/linq-equivalent-for-standard-deviation
Friday, April 22, 2016
go to this, please:
http://www.excitesubmit.com
Wednesday, April 20, 2016
Convert and Loop through JSON with PHP and JavaScript Arrays/Objects
0 comments Posted by Duc Nguyen at 12:15 AM$("#gender").on("change", function() {
$.ajax({
type: "POST",
data: {
"gender": $("#gender").val()
},
url: "response.php",
dataType: "json",
success: function(JSONObject) {
var peopleHTML = "";
// Loop through Object and create peopleHTML
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
peopleHTML += "
"
;
peopleHTML += "" + JSONObject[key]["name"] + "
";
peopleHTML += "
see more:
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
Tuesday, April 19, 2016
//準備資料
string collapse_key = "score_update";
int time_to_live = 108;
bool delay_while_idle = true;
string score = "4x8";
string time = "15:16.2342";
List<string> registration_ids = new List<string>() { "4","8","15","16","23","42"};
//開始拼接字串
StringBuilder sb = new StringBuilder();
sb.AppendLine("{");
sb.AppendLine("\"collapse_key\":\""+collapse_key+"\",");
sb.AppendLine("\"time_to_live\":"+time_to_live+",");
sb.AppendLine("\"delay_while_idle\":"+delay_while_idle.ToString().ToLower()+",");
sb.AppendLine("\"data\":{");
sb.AppendLine("\"score\":\""+score+"\",");
sb.AppendLine("\"time\":\""+time+"\"");
sb.AppendLine("},");
sb.AppendLine("\"registration_ids\":[");
foreach (string item in registration_ids)
{
sb.Append("\""+item+"\",");
}
sb = new StringBuilder(sb.ToString().TrimEnd(','));//移除最後一個「,」字元
sb.AppendLine("]");
sb.AppendLine("}");
//輸出結果
Response.Write(sb.ToString());
More here:
https://dotblogs.com.tw/shadow/archive/2012/08/16/74099.aspx
Sunday, April 17, 2016
Make AJAX JSON call to ASP.Net WCF Service using jQuery and Javascript
0 comments Posted by Duc Nguyen at 10:01 PMHere Mudassar Ahmed Khan has explained how to modify the ASP.Net WCF (Windows Communication Foundation) service to make it accept AJAX JSON calls and to make AJAX JSON calls to ASP.Net WCF Service using JavaScript and jQuery
see more:
http://www.aspsnippets.com/Articles/Make-AJAX-JSON-call-to-ASP.Net-WCF-Service-using-jQuery-and-Javascript.aspx
$("#search").live("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/Services/Service.svc/GetCustomers") %>',
data: '{"prefix": "' + $("#prefix").val() + '"}',
processData: false,
dataType: "json",
success: function (response) {
var customers = eval(response.d);
var html = "";
$.each(customers, function () {
html += "Name: " + this.Name + " Id: " + this.Id + "
";
";
});
$("#results").html(html == "" ? "No results" : html);
},
error: function (a, b, c) {
alert(a.responseText);
}
});
});
Tuesday, April 12, 2016
500: Internal Server when call Webservice in jquery and Asp.net
0 comments Posted by Duc Nguyen at 2:55 AM
maxJsonLength="50000000"/>
Sunday, April 10, 2016
Subscribe to:
Posts (Atom)