Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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-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-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);
  }