Wednesday, May 4, 2016

The 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

excite submit URL

go to this, please:
http://www.excitesubmit.com

Wednesday, April 20, 2016

$("#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 += "" + JSONObject[key]["gender"] + ""; peopleHTML += ""; } } // Replace table’s tbody html with peopleHTML $("#people tbody").html(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

Here 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


      
           
                 maxJsonLength="50000000"/>
           

Sunday, April 10, 2016

$("#bntSubmit").on('click', function (e) {

    // Initialize the object, before adding data to it.
    //  { } is declarative shorthand for new Object()
    var obj = {};
    obj.first_name = $("#txtFirstName").val();
    obj.last_name = $("#txtLastName").val();
    obj.qualification = $("#txtQualication").val();
    obj.age = $("#txtAge").val();

    //In order to proper pass a json string, you have to use function JSON.stringfy
    var jsonData = JSON.stringify(obj);

    $.ajax({
        url: 'myGenericHandler.ashx',
        type: 'POST',
        data: jsonData,
        success: function (data) {
            console.log(data);
            alert("Success :" + data);
        },
        error: function (errorText) {
            alert("Wwoops something went wrong !");
        }
    });

    e.preventDefault();
});

# Add Generic Handler ( ashx file) in your Asp.net Application.

 

using System.Web.Script.Serialization;
using System.IO;

 

 // we create a userinfo class to hold the JSON value
  public class userInfo
  {
     public string first_name { get; set; }
     public string last_name { get; set; }
     public string qualification { get; set; }
     public string age { get; set; }
  }

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    try
    {
        string strJson = new StreamReader(context.Request.InputStream).ReadToEnd();

        //deserialize the object
        userInfo objUsr = Deserialize(strJson);
        if (objUsr != null)
        {
            string fullName = objUsr.first_name + " " + objUsr.last_name;
            string age = objUsr.age;
            string qua = objUsr.qualification;
            context.Response.Write(string.Format("Name :{0} , Age={1}, Qualification={2}", fullName, age, qua));
        }
        else
        {
            context.Response.Write("No Data");
        }
    }
    catch (Exception ex)
    {
        context.Response.Write("Error :" + ex.Message);
    }
}

 

<%@ WebHandler Language="C#" Class="myGenericHandler" %>

using System;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;

public class myGenericHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            string strJson = new StreamReader(context.Request.InputStream).ReadToEnd();

            //deserialize the object
            userInfo objUsr = Deserialize(strJson);
            if (objUsr != null)
            {
                string fullName = objUsr.first_name + " " + objUsr.last_name;
                string age = objUsr.age;
                string qua = objUsr.qualification;
                context.Response.Write(string.Format("Name :{0} , Age={1}, Qualification={2}", fullName, age, qua));
            }
            else
            {
                context.Response.Write("No Data");
            }
        }
        catch (Exception ex)
        {
            context.Response.Write("Error :" + ex.Message);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    // we create a userinfo class to hold the JSON value
    public class userInfo
    {
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string qualification { get; set; }
        public string age { get; set; }
    }


    // Converts the specified JSON string to an object of type T
    public T Deserialize(string context)
    {
        string jsonData = context;

        //cast to specified objectType
        var obj = (T)new JavaScriptSerializer().Deserialize(jsonData);
        return obj;
    }

}

Wednesday, April 6, 2016

Introduction

This article explains how to download and install a default instance of Microsoft SQL Server 2008 R2 Express.

Instructions

Before proceeding, verify that you don't already have an instance of Microsoft SQL Server installed on the computer. If any edition (excluding the Compact Edition) of Microsoft SQL Server 2000 or later is already installed, you can use this existing installation with RealtyWare. Previous versions of Microsoft SQL Server may have to be updated or can be kept side-by-side with newer versions.
Follow these steps to download and perform a new default instance installation of Microsoft SQL Server 2008 R2 Express:
  1. Download Microsoft SQL Server 2008 R2 Express. There are 32-bit (x86, file name SQLEXPRWT_x86_ENU.exe) and 64-bit (x64, file name SQLEXPRWT_x64_ENU.exe) versions available for download. If you are unsure if your operating system is 64-bit, download the 32-bit version:

    Microsoft SQL Server 2008 R2 Express 32-bit (x86)
    - or -
    Microsoft SQL Server 2008 R2 Express 64-bit (x64)

    This download also includes basic management tools for the database server.

    Important: You may have to install Microsoft .Net Framework 3.5 SP1, Windows Installer 4.5 and Windows PowerShell 1.0 before installing Microsoft SQL Server 2008 R2 (typically required for Windows XP and Windows Server 2003).
  2. Open the downloaded file (SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe) to start the SQL Server Installation Center.
  3. Click on New installation or add features to an existing installation.
  4. Follow the installation wizard.
  5. When prompted for the Instance Configuration, select Default instance.
  6. Follow the installation wizard.
  7. When prompted for the Database Engine Configuration, it is recommended that you select Mixed Mode (SQL Server authentication and Windows authentication) and provide a strong password.
  8. Follow the installation wizard and wait until the installation is complete.
For security reasons, network access to the database server is disabled by default. Follow these steps to enable TCP/IP network access:
  1. Go to Start > All Programs > Microsoft SQL Server 2008 R2 > Configuration Tools > SQL Server Configuration Manager.
  2. Open the node SQL Server Network Configuration and select Protocols for MSSQLSERVER.
  3. Double-click on TCP/IP.
  4. Set Enabled to Yes.
  5. Click on OK.
  6. Close the SQL Server Configuration Manager.
  7. Restart the computer or the SQL Server service.