Wednesday, December 2, 2015

Event in C#

Events:
It is basically used for subscriber/publisher model.
subscriber of any delegate function can be declared as an event. In such case, Any operation can be done on the event inside the class, however only += and -+ can be done outside the class. eg:
public delegate void PriceChangedHandler();
class{
public event PriceChangedHandler PriceChanged;
}
Here inside the class we can do any operation on the PriceChanged but outside the class we can just do += and -=;

Standard event pattern:
 Class  extends System.EventArgs. It just contains some empty static property
 Next create delegate: return type should be void. It must accept 2 parameters. First is object  type. Second is subclass of EventArgs. Its name must end in "EventHandler"
 eg public delegate void EventHandler<TEventArgs>
  (object source, TEventArgs e) where TEventArgs : EventArgs;
 Next define event: public event EventHandler<PriceChangedEventArgs> PriceChanged;
 Finally, the pattern requires that you write a protected virtual method that fires the event. The name must match the name of the event, prefixed with the word"On", and then accept a single EventArgs argument: eg : protected virtual void OnPriceChanged (PriceChangedEventArgs e)
  {
    if (PriceChanged != null) PriceChanged (this, e);
  }

  Sample program:
  using System;

public class PriceChangedEventArgs : EventArgs
{
  public readonly decimal LastPrice;
  public readonly decimal NewPrice;

  public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)
  {
    LastPrice = lastPrice; NewPrice = newPrice;
  }
}

public class Stock
{
  string symbol;
  decimal price;

  public Stock (string symbol) {this.symbol = symbol;}

  public event EventHandler<PriceChangedEventArgs> PriceChanged;
  protected virtual void OnPriceChanged (PriceChangedEventArgs e)
  {
    if (PriceChanged != null) PriceChanged (this, e);
  }

  public decimal Price
  {
    get { return price; }
    set
    {
      if (price == value) return;
      OnPriceChanged (new PriceChangedEventArgs (price, value));
      price = value;
    }
  }
}

class Test
{
  static void Main(  )
  {
    Stock stock = new Stock ("THPW");
    stock.Price = 27.10M;   //1
    // register with the PriceChanged event
    stock.PriceChanged += stock_PriceChanged; //2
    stock.Price = 31.59M; //3
stock.Price = 31.59M; //4
    stock.Price = 35.69M; //5
    stock.PriceChanged -= stock_PriceChanged; //6
    stock.Price = 37.89M;//7
  }

  static void stock_PriceChanged (object sender, PriceChangedEventArgs e)
  {
    if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
      Console.WriteLine ("Alert, 10% stock price increase!");
  }
}

In this program, executino starts with main. value of Price is set at 1. Since there is price change, it will call OnPriceChanged. Inside this funciton, since PriceChanged is null, it is not doing anything. At 2, It is adding method stock_PriceChanged to PriceChanged. Notice stock_PriceChanged is static with void return type. At 3, it is again setting value of Price and which is calling OnPriceChanged. Now PriceChanged is not null. So PriceChanged is called which actually is calling stock_PriceChanged with arguments of type object and PriceChangedEventArgs(subclass of EventArgs). At 4, there is no price change, so it returns. 5 is same as 3. At 6, function stock_PriceChanged is removed from PriceChanged event. So in 7, stock_PriceChanged is not called.

If we don't need any other information other than just that event is fired, we can use EventArgs.Empty
eg: Lets modify Stock class to incorporate this:
public class Stock
{
  string symbol;
  decimal price;

  public Stock (string symbol) {this.symbol = symbol;}

  public eventEventHandler PriceChanged;

protected virtual void OnPriceChanged (EventArgs e)
  {
    if (PriceChanged != null) PriceChanged (this, e);
  }

  public decimal Price
  {
    get { return price; }
    set
    {
      if (price == value) return;
      price = value;
      OnPriceChanged (EventArgs.Empty);
    }
  }
}

C# delegate

Delegates C#

In simple words it is instance referencing to a method.
eg: Suppose there is a method int method1(int x){}
Create a delegate instance: delegate int delegateInstance(int k);
Assign this delegate instance to method1: delegateInstance instance1=method1
Now when we call this delegate method, it will actually call the method1: instance1(3), it will call method1(3).

Arithmetic can also be done on the delegate method assignment. eg:
instance1+=method2;
Now when the instance1 is called, it will call both method1 and method2 in order.
We can also do instance1-=method1. Now when instance1 is called, it will only call method2.
When a delegate method is assigned to a class method, it also maintains the reference to the method. In case of static method, it maintains null
eg:delegateInstance instance1=method1
  instance1.Target == this  //true
  instance1.Method; // Int32 method1(Int32)

  
Generic delegate:
public delegate T Transformer<T> (T arg);
public class Util
{
  public static void Transform<T> (T[] values,Transformer<T> t)
  {
    for (int i = 0; i < values.Length; i++)
      values[i] = t(values[i]);
  }
}

class Test
{
  static void Main(  )
  {
    int[] values = new int[] {1, 2, 3};
    Util.Transform(values, Square);      // dynamically hook in Square
    foreach (int i in values)
      Console.Write (i + "  ");           // 1   4   9
  }

  static int Square (int x) { return x * x; }
}

A delegate design may be a better choice than an interface design if one or more of these conditions are true:
The interface defines only a single method
Multicast capability is needed(calling more than one methods at a time. Hit: +=)
The listener needs to implement the interface multiple times  

Assigning one delegate instance to another results in compile time error. They are incompatible to each other.
D d1=m1;
D d2=d1; //Compile time error

Two delegates pointing to same method are equal.
  delegate void d();
  D d1=m1;
  D d2=m1;
  d1==d2; //true

A delegate method can be assigned with method instance which takes more wide parameter. Eg if delegate is for parameter class c1. We can assign a method which accepts super class of class c1. This is called contravariance.
delegate void SpecificDelegate (SpecificClass s);
class SpecificClass {}
class Test
{
  static void Main(  )
  {
    SpecificDelegate specificDelegate = GeneralHandler;
    specificDelegate (new SpecificClass(  ));
  }
  static void GeneralHandler(object o)
  {
    Console.WriteLine(o.GetType(  )); // SpecificClass
  }
}

the return type of a delegate can be super class of the return type of its target method. This is called covariance.
eg delegate Asset DebtCollector(  );
class Asset {}
class House : Asset {}
class Test
{
  static void Main(  )
  {
     DebtCollector d = new DebtCollector (GetHomeSweetHome);
     Asset a = d(  );
     Console.WriteLine(a.GetType(  )); // House
  }
  static House GetHomeSweetHome() {return new House(  ); }
}

Reference: https://msdn.microsoft.com/en-us/library/orm-9780596527570-03-04.aspx

Saturday, October 24, 2015

WikiHow: Get data using pageid

Get pageid using query API
?action=query&list=allpages&format=json&apfrom=A%24%24&aplimit=5

Other APIs to work on the obtained pageId
https://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=API|Main%20Page&rvprop=timestamp|user|comment|content
https://en.wikipedia.org/w/api.php?action=query&prop=revisions&pageids=27551355&rvprop=timestamp|user|comment|content
https://en.wikipedia.org/w/api.php?action=query&prop=revisions|pageprops&pageids=22989&rvprop=content
https://en.wikipedia.org/w/api.php?action=query&prop=revisions|pageprops&titles=Paris&rvprop=content
https://en.wikipedia.org/w/api.php?action=parse&pageid=27697087&contentmodel=wikitext
https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=info&format=json&pageids=27551355

Some other good APIs
https://www.mediawiki.org/wiki/API:Parsing_wikitext
https://www.mediawiki.org/wiki/API:Query
https://www.mediawiki.org/wiki/API:Query
https://www.mediawiki.org/wiki/API:Allpages
https://www.mediawiki.org/wiki/API:Categorymembers

Sunday, October 18, 2015

POST using jersey

Client client = ClientBuilder.newClient();
WebTarget target = client.target("target").path("path_text");;
              //path is optional

Form form = new Form();
form.param("action", "login");
form.param("lgname", "login_id");
form.param("lgpassword", "lgin_pass");
form.param("format", "json");

Response response = target.request().post(Entity.form(form));

Thursday, October 1, 2015

Conversion of wstring to PWSTR

Common examples
std::string s = SOME_STRING; // get temporary LPSTR (not really safe) LPSTR pst = &s[0]; // get temporary LPCSTR (pretty safe) LPCSTR pcstr = s.c_str(); // convert to std::wstring std::wstring ws; ws.assign( s.begin(), s.end() ); // get temporary LPWSTR (not really safe) LPWSTR pwst = &ws[0]; // get temporary LPCWSTR (pretty safe) LPCWSTR pcwstr = ws.c_str();


Solved problem:
Create( __in SomeMap &Metrics, __out PWSTR *metric ) { std::wstring *current = NULL; try { current = new std::wstring(); for (iterator iterator = Metrics.begin(); iterator != Metrics.end(); iterator++) { if (!current->empty()) { current->append (L";"); } current->append(L"{"); current->append(iterator->first.begin(), iterator->first.end()); current->append(L":"); current->append(iterator->second.begin(), iterator->second.end()); current->append(L"}"); } //Either of the following can be used. for the first one, it is directly converting wstring to PWSTR. //second one is using c_str() which converts first to PCWSTR. and then to PWSTR // Since it is first converting to PCWSTR, if we want to change the value later on of the *metric, it will cause memory corruption //*metric = &(*current)[0]; //*metric = const_cast<PWSTR> (current->c_str()); } catch (...) { } Cleanup: if (*metric == NULL) { PTR_FREE(current); } }