2015-09-27

d3.js Html5 svg circle and bar chart Example


<html>
  <head>
    <title></title>
  </head>
  <body>
    <svg width="720" height="120">
    </svg>
    <div id="myChart">
    </div>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
 
   <script type="text/javascript">
     var svg = d3.select("svg");

     //three circle
     //---create a circles for each item in data to svg
     var circle = svg.selectAll("circle")
      .data([32, 57, 293], function(d) { return d; });

     circle.enter().append("circle")
      .style("fill", "steelblue")
      .attr("cy", 60)
      .attr("cx", function(d, i) { return i * 100 + 30; })
      .attr("r", function(d) { return Math.sqrt(d); });

     //bar chart
     var chartdata = [40, 60, 80, 100, 70, 50, 100, 60, 70, 60, 90, 120,30];

     //---the size of the overall svg element
     var height = 200;
     var width = 720;

     //the width of each bar and the offset between each bar
     var barWidth = 40;
     var barOffset = 15;


     var bar = d3.select('#myChart').append('svg')
     .attr('width', width)
     .attr('height', height)
     .style('background', '#dff0d8')
     .selectAll('rect').data(chartdata);

     //add a bar for each item in array chartdata to chart
     bar.enter().append('rect')
     .style({'fill': '#3c763d', 'stroke': '#d6e9c6', 'stroke-width': '3'})
     .attr('width', barWidth)
     .attr('height', function (data) {
         return data;
     })
     .attr('x', function (data, i) {
         return i * (barWidth + barOffset);
     })
     .attr('y', function (data) {
         return height - data;
     });

     //add text for every bar in chart to display the value of the bar
     bar.enter().append("text")
     .attr('x', function (data, i) {
         return (i * (barWidth + barOffset)) + 5;
     })
     .attr('y', function (data) {
         return (height - data)+15;
     })
     .attr("dy", ".35em")
     .style({'fill':'#FFFFFF'})
     .text(function(data) { return data; });

 </script>
</body>
</html>

2015-09-26

SQL Server 2012 AlwaysOn - Disaster Recovery

SQL Server 2012 AlwaysOn Reference:


  1. SQL Server 2012 新功能 - AlwaysOn安裝與設定
  2. SQL High Availability and Disaster Recovery Using AlwaysOn
  3. Microsoft SQL Server AlwaysOn Solutions Guide for High Availability and Disaster Recovery
  4. AlwaysOn Architecture Guide: Building a High Availability and Disaster Recovery Solution by Using AlwaysOn Availability Groups
  5. AlwaysOn Architecture Guide: Building a High Availability and Disaster Recovery Solution by Using Failover Cluster Instances and Availability Groups

d3.js First Example


<html>
  <head>
    <title></title>
    <style>
     .chart div {
         font: 10px sans-serif;
         background-color: steelblue;
         text-align: right;
         padding: 3px;
         margin: 1px;
         color: white;
      }
    </style>
  </head>
  <body>
  <div class="chart">
  </div>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
 
  <script type="text/javascript">
        var data = [4, 8, 15, 16, 23, 42];

        var x = d3.scale.linear()
                .domain([0, d3.max(data)])
                .range([0, 420]);

        d3.select(".chart")
          .selectAll("div")
          .data(data)
          .enter().append("div")
          .style("width", function(d) { return x(d) + "px"; })
          .text(function(d) { return d; });
  </script>
</body>
</html>


2015-09-24

EventWaitHandle C# Example


using System;
using System.Threading;

namespace WaitEvent
{
        class MainClass
        {
                static EventWaitHandle waitEvent = new AutoResetEvent (false);
                public static void Main (string[] args)
                {
                        //this thread will wait the notification from waitEvent 
                        Thread wait = new Thread (WaitForPrintEvent);
                        wait.Start ();
                        Thread.Sleep (3000); 

                        //this thread will trigger the waitEvent
                        Thread print = new Thread (printMsg);
                        print.Start ();

                        print.Join ();
                        wait.Join ();
                }

                static void WaitForPrintEvent()
                {
                        //wait the notification from waitEvent to continue
                        waitEvent.WaitOne ();
                        Console.WriteLine ("after wait!");
                }

                static void printMsg()
                {
                        Console.WriteLine ("Print Message!");
                        //waitEvent is set,and will notify the guys that wait this event
                        waitEvent.Set ();
                }
        }
}



Reference 
C# Threading 

2015-09-23

C# Event Handler Example

Program.cs

using System;

namespace EventHandlerTest
{
   class MainClass
   {
      public static void Main (string[] args)
      {
        //Account的money先給500
        Account myAccount = new Account (500);
        //加入Event發生後要執行的function
        myAccount.AlarmHandler += c_TriggerAlarmMessage;
        //提領超過200,會觸發事件
        myAccount.DrawMoney (300);
      }

      static void c_TriggerAlarmMessage(object sender, AlarmEventArgs e)
      {
        Console.WriteLine("The Alarm is trigger.");
        Environment.Exit(0);
      }
   }
}


Account.cs

using System;

namespace EventHandlerTest
{
 public class Account
 {
    public int totalMoney;

    //從帳戶提領錢
    public void DrawMoney(int money)
    {
      //超過200會觸發事件
      if (money > 200) {
        Trigger ();
      } else {
        totalMoney -= money;
      }
    }

    public Account (int totalMoney)
    {
       this.totalMoney = totalMoney;
    }


    public void Trigger()
    {
       AlarmEventArgs e = new AlarmEventArgs ();
       e.active = true;
       EventHandler handler = AlarmHandler;
       if (handler != null)
       {
         handler(this, e);
       }
    
    }

    public event EventHandler AlarmHandler;
  }
}


AlarmEventArgs.cs

using System;

namespace EventHandlerTest
{
   public class AlarmEventArgs
   {
     public AlarmEventArgs ()
     {
     }

     public bool active;
   }
}

2015-09-22

Chart.js Example - Bar Chart

A bar chart example for chart.js.

$(document).ready(function () {
    var data = {
        labels: ["Taipei", "Tainan", "Kaohsiung", "Pintung", "Taoyuan", "Miaoli", "Chiayi"],
        datasets: [
            {
                label: "# of store",
                fillColor: "rgba(220,220,220,0.5)",
                strokeColor: "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data: [20, 40, 30, 21, 56, 45, 60]
            },
            {
                label: "# of staff ",
                fillColor: "rgba(151,187,205,0.5)",
                strokeColor: "rgba(151,187,205,0.8)",
                highlightFill: "rgba(151,187,205,0.75)",
                highlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var option = {
        scaleBeginAtZero : true,

        //Boolean - Whether grid lines are shown across the chart
        scaleShowGridLines : true,

        //String - Colour of the grid lines
        scaleGridLineColor : "rgba(0,0,0,.05)",

        //Number - Width of the grid lines
        scaleGridLineWidth : 1,

        //Boolean - Whether to show horizontal lines (except X axis)
        scaleShowHorizontalLines: true,

        //Boolean - Whether to show vertical lines (except Y axis)
        scaleShowVerticalLines: true,

        //Boolean - If there is a stroke on each bar
        barShowStroke : true,

        //Number - Pixel width of the bar stroke
        barStrokeWidth : 2,

        //Number - Spacing between each of the X value sets
        barValueSpacing : 5,

        //Number - Spacing between data sets within X values
        barDatasetSpacing : 1,

    };
    var ctx = document.getElementById("myChart").getContext("2d");
    var myLineChart = new Chart(ctx).Bar(data, option);
});

Chart.js Example - Line Chart

A line chart example for chart.js, a good and beautiful chart library!!

$(document).ready(function () {
    var data = {
        labels: ["Taipei", "Tainan", "Kaohsiung", "Pintung", "Taoyuan", "Miaoli", "Chiayi"],
        datasets: [
            {
                label: "# of store",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [20, 40, 30, 21, 56, 45, 60]
            },
            {
                label: "# of staff ",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var option = {

        ///Boolean - Whether grid lines are shown across the chart
        scaleShowGridLines : true,

        //String - Colour of the grid lines
        scaleGridLineColor : "rgba(0,0,0,.05)",

        //Number - Width of the grid lines
        scaleGridLineWidth : 1,

        //Boolean - Whether to show horizontal lines (except X axis)
        scaleShowHorizontalLines: true,

        //Boolean - Whether to show vertical lines (except Y axis)
        scaleShowVerticalLines: true,

        //Boolean - Whether the line is curved between points
        bezierCurve : true,

        //Number - Tension of the bezier curve between points
        bezierCurveTension : 0.4,

        //Boolean - Whether to show a dot for each point
        pointDot : true,

        //Number - Radius of each point dot in pixels
        pointDotRadius : 4,

        //Number - Pixel width of point dot stroke
        pointDotStrokeWidth : 1,

        //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
        pointHitDetectionRadius : 20,

        //Boolean - Whether to show a stroke for datasets
        datasetStroke : true,

        //Number - Pixel width of dataset stroke
        datasetStrokeWidth : 2,

        //Boolean - Whether to fill the dataset with a colour
        datasetFill : true,

    };
    var ctx = document.getElementById("myChart").getContext("2d");
    var myLineChart = new Chart(ctx).Line(data, option);
});

2015-09-21

C# Scheduler Example - Quartz

Create a class that impelement IJob class

using System;
using Quartz.Impl;
using Quartz;

namespace quartz
{
 public class MyJob : IJob
 {
  public void Execute(IJobExecutionContext context)
  {
   Console.WriteLine("Hello");
  }
 }
}


create a job and a cron scheduler in main function, and schedule the job with the cron scheduler

using System;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System.Threading;

namespace quartz
{
 class MainClass
 {
  public static void Main (string[] args)
  {
   IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
   scheduler.Start();

   IJobDetail job2 = JobBuilder.Create().
    WithIdentity("job2", "group1")
    .Build();

   //run every 2 seconds.
   ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithCronSchedule("0/2 * * * * ?")
    .Build();

   scheduler.ScheduleJob(job2, trigger);

   Thread.Sleep(30000);
   scheduler.Shutdown ();
   Console.ReadKey ();
  }
 }
}

2015-09-20

cefSharp example by using c# (Chromium-based browser component)



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CefSharp.WinForms;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace cefsharpform
{
    public partial class Form1 : Form
    {
        CefSharp.WinForms.ChromiumWebBrowser browser;
        public Form1()
        {
            InitializeComponent();
            browser = new ChromiumWebBrowser("http://www.google.com");
            browser.Name = "Simple Page";
            browser.Dock = DockStyle.Fill;
            //當load結束的時候,所要執行的事件方法
            browser.FrameLoadEnd += new EventHandler(browser_FrameLoadEnd);
            this.Controls.Add(browser);
        }

        
        void browser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
        {
            if (e.HttpStatusCode == 200)
            {
                //在browser中執行一段Javascript
                browser.ExecuteScriptAsync("alert('Test!');");

                //呼叫一個javascript function, 並取得其回傳值
                var task = browser.EvaluateScriptAsync(@"
                            (function () {
                               return 'hello!';
                            })();
                           ");

                var complete = task.ContinueWith(t =>
                {
                    if (!t.IsFaulted)
                    {
                        var response = t.Result;
                        object result = response.Success ? (response.Result ?? "null") : response.Message;
                        MessageBox.Show(task.Result.Result.ToString());
                    }
                }, TaskScheduler.Default);
                complete.Wait();
            }
            else
            {
                
                this.Close();
            }
        }
    }
}



2015-09-19

jQuery Call Web Service using Ajax - ASP.NET asmx

1. Create a folder, call webService, in your project, and create myService.asmx in this folder
2. and create a html file student.html.
add studentList method to myService.asmx.cs namespace MyWebTest { public class myService : System.Web.Services.WebService { [WebMethod] public List studentList() { List list = new List (); list.Add ("John"); list.Add ("David"); list.Add ("Kelly"); return list; } } } In student.html, use ajax to call web service studentList $(document).ready(function () { $.ajax({ type: "POST", url: "../webService/myService.asmx/studentList", data: "", dataType: "json", contentType: "application/json; charset=utf-8", success: function (data) { var studs = data.d $.each(studs, function (idx, stud){ $("#list").append(stud); }); } }); });

2015-09-18

Json.NET using c# - Json Serialize/Deserialize Object

Create class User First

using System;

namespace JsonTest
{
 public class User
 {
  public string name;
  public string addr;
  public string phoneNo;

  public User ()
  {
   
  }
 }
}


Than in main function



public static void Main (string[] args)
  {
   User me = new User ();
   me.addr = "Taipei";
   me.name = "peichun";
   me.phoneNo ="123456789";

   string jsonString = JsonConvert.SerializeObject (me);
   Console.WriteLine (jsonString);

   User you = JsonConvert.DeserializeObject(jsonString);
   Console.WriteLine ("Second me : " + you.name);
  }

2015-09-17

MongoDB using Node.js - Part 2



var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://username:yourpassword@serveraddress:yourport/database", function(err, db) {

    if(err) { return console.dir(err); }

    var collection = db.collection('nodejs');

    var doc1 = {'_id':'doc1', 'city':'taipei', 'num' :25};
    var doc2 = {'_id':'doc2', 'city':'kaohsiung', 'num' :35};

    //insert
    collection.insert(doc1, {w:1}, function(err, result){});

    collection.insert(doc2, {w:1}, function(err, result) {
        console.log('insert');
        collection.update({city:'taipei'}, {$set:{num:55}}, {w:1}, function(err, result) {});
        
        collection.find().toArray(function(err, items) {});

        collection.find({city:'taipei'}).toArray(function(err, docs){
            console.log("retrieved records:");
            console.log(docs);
        });
    });
        
    var cursor = collection.find({city:'taipei'}).toArray(function(err, docs) {
          console.log("Printing docs from Array");
          docs.forEach(function(doc) {
                console.log("Doc from Array ");
                console.dir(doc);
                console.log(doc.city);
          });
    });
    //update
    collection.update({city:'taipei'}, {$inc:{num:25}}, {w:1}, function(err, result) {
        if(err)
        {
            console.log('fail update');
            return console.dir(err);
        }
        console.log('Successfully update');
    });
    //remove
    collection.remove({city:'kaohsiung'}, {w:1}, function(err, result) {});
});


MongoDB using Node.js - Part 1



// Retrieve
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://yourusername:yourpassword@yourserveraddress:yourport/yourdatabase", function(err, db) {
  if(err) { return console.dir(err); }

  db.createCollection('nodejs', function(err, collection) {});
    
  var collection = db.collection('nodejs');
  var doc1 = {'hello':'doc1'};
  var doc2 = {'hello':'doc2'};
  var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];

  collection.insert(doc2, {w:1}, function(err, result) {});

  collection.insert(lotsOfDocs, {w:1}, function(err, result) {});

});

2015-09-16

MongoDB using Java Part 3 - select



package mongodb;

import java.util.ArrayList;
import java.util.List;
import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoCredential;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongodbSelect {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try
  {
   // 認證
   MongoCredential journaldevAuth = MongoCredential.createMongoCRCredential("your username", "your database", "your password".toCharArray());
   List auths = new ArrayList();
   auths.add(journaldevAuth);

   //連線
   ServerAddress serverAddress = new ServerAddress("your server", your port);
   MongoClient mongo = new MongoClient(serverAddress,auths);

   //選擇連線database
   DB db = mongo.getDB("your database");

   //選擇collection (table)
   DBCollection site = db.getCollection("site");

   //iterate the table
   System.out.println();
   System.out.println("iterate the table");
   DBCursor cursor = site.find();
   try {
    while(cursor.hasNext()) {
     System.out.println(cursor.next());
    }
   } finally {
    cursor.close();
   }

   //query -->  city==Taipei
   System.out.println();
   System.out.println("query -->  city==Taipei");
   BasicDBObject query = new BasicDBObject("city", "taipei");

   cursor = site.find(query);

   try {
    while(cursor.hasNext()) {
     System.out.println(cursor.next());
    }
   } finally {
    cursor.close();
   }

   //query --> num>=50 && city==Taipei
   System.out.println();
   System.out.println("query --> num>=50 && city==Taipei");
   query = new BasicDBObject("num", new BasicDBObject("$gte", 50))
   .append("city", "taipei");

   cursor = site.find(query);

   try {
    while(cursor.hasNext()) {
     System.out.println(cursor.next());
    }
   } finally {
    cursor.close();
   }
   
   //query num > 20 && num<=30
   //only display columns city , address
   System.out.println();
   System.out.println("query num > 20 && num<=30");
   System.out.println("only display columns city , address");
   query = new BasicDBObject("num", new BasicDBObject("$gt", 20).append("$lte", 30));
   cursor = site.find(query, new BasicDBObject("city",true).append("address", true));

   try {
       while (cursor.hasNext()) {
           System.out.println(cursor.next());
       }
   } finally {
       cursor.close();
   }
   
   //iterate the table and sort by num
   System.out.println();
   System.out.println("iterate the table and sort by num");
      cursor = site.find().sort(new BasicDBObject("num",1));
   try {
    while(cursor.hasNext()) {
     System.out.println(cursor.next());
    }
   } finally {
    cursor.close();
   }
  }
  catch(UnknownHostException ex)
  {

  }
 }

}

MongoDB using Java part 2 - delete



package mongodb;

import java.util.ArrayList;
import java.util.List;
import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoCredential;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongodbDelete {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try
  {
   // 認證
   MongoCredential journaldevAuth = MongoCredential.createMongoCRCredential("your username", "your database", "your password".toCharArray());
   List auths = new ArrayList();
   auths.add(journaldevAuth);

   //連線
   ServerAddress serverAddress = new ServerAddress("your address", your port);
   MongoClient mongo = new MongoClient(serverAddress,auths);

   //選擇連線database
   DB db = mongo.getDB("your database");

   //選擇collection (table)
   DBCollection site = db.getCollection("site");

   BasicDBObject searchQuery = new BasicDBObject();
   searchQuery.put("city", "Taipei");
   site.remove(searchQuery);
  }
  catch(UnknownHostException ex)
  {

  }
 }

}

2015-09-15

MongoDB using Java part 1 - update


package mongodb;

import java.util.ArrayList;
import java.util.List;
import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoCredential;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongdbUpdate {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try
  {
   // 認證
   MongoCredential journaldevAuth = MongoCredential.createMongoCRCredential("username", "database", "password".toCharArray());
   List auths = new ArrayList();
   auths.add(journaldevAuth);

   //連線
   ServerAddress serverAddress = new ServerAddress("your server address", your port);
   MongoClient mongo = new MongoClient(serverAddress,auths);

   //選擇連線database
   DB db = mongo.getDB("database");

   //選擇collection (table)
   DBCollection site = db.getCollection("site");
   
   // $set
   BasicDBObject query = new BasicDBObject();
   query.put("city", "taipei");
   BasicDBObject newDocument = new BasicDBObject();
   newDocument.put("num", 125);
   
   BasicDBObject updateObj = new BasicDBObject();
   updateObj.put("$set", newDocument);
   
   site.update(query, updateObj, true, true);
   
   // $inc
   updateObj.clear();
   updateObj.put("$inc", newDocument);
   site.update(query, updateObj, true, true);
  }
  catch(UnknownHostException ex)
  {

  }
 }

}