Thursday, November 4, 2010

MaskEdit Code

If no MaskEdit found do the following rough code

private void ultraTextEditor1_KeyUp(object sender, KeyEventArgs e)
{

UltraTextEditor te = (UltraTextEditor)sender;
var q = from _ in
new List() {
Keys.D0, Keys.D1, Keys.D2,Keys.D3, Keys.D4, Keys.D5,
Keys.D6, Keys.D7, Keys.D8,Keys.D9,
Keys.NumPad0, Keys.NumPad1, Keys.NumPad2,Keys.NumPad3, Keys.NumPad4, Keys.NumPad5,
Keys.NumPad6, Keys.NumPad7, Keys.NumPad8,Keys.NumPad9,
Keys.Delete, Keys.Decimal,Keys.Left, Keys.Right,Keys.OemPeriod,Keys.Back,Keys.Home,
}
where e.KeyCode == _
select _;
e.SuppressKeyPress = q.Count() == 0;
if ((e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod) && te.Text.Count(s => s == '.') == 1)
{
e.SuppressKeyPress = true;
}

var q1 = from _ in
new List() {
Keys.Left, Keys.Right,Keys.Back,Keys.Home,
}
where e.KeyCode == _
select _;
if (q1.Count() > 0) return;

if (te.Text.Length > 0)
{
string t = te.Text.Replace(",", "").Replace("..", ".");
double Data = Convert.ToDouble(t);
int i = (int)Math.Floor(Data);
string sInt = string.Format("{0:#,#}", i);
string dec = +t.IndexOf('.') >= 0 ? t.Substring(t.IndexOf('.')) : "";
te.Text = "";
te.AppendText(sInt + dec);
}
}

Monday, November 1, 2010

Dynamically Create Event Handler

 
public static class UIExtensioins
{
public class Inclusion
{
public string ComponentTypeFullName { get; set; }
public string EventName { get; set; }
public string[] SenderPropertyNames { get; set; }
public string[] EventArgsPropertyNames { get; set; }
}

public static void AttachLoggerToUIEvent(this Form f, IContainer components,List inclusionList)
{
foreach (Inclusion i in inclusionList)
{
foreach (Component c in FindComponent(f, i.ComponentTypeFullName, components))
{
AttacheEventHandler(c, i);
}
}
}

public static IEnumerable FindComponent(Control ownerControl,string typeFullName, IContainer containter)
{
bool topComponentFound = false;
foreach (Component c1 in containter.Components)
if (c1.GetType().FullName == typeFullName)
{
topComponentFound = true;
yield return c1;
}
if (topComponentFound) yield break;

foreach (Control c1 in ownerControl.Controls)
{
if (c1.GetType().FullName == typeFullName) yield return c1;
else foreach (Control c2 in FindComponent(c1, typeFullName, containter))
if (c2.GetType().FullName == typeFullName) yield return c2;
}
}


public static void Log(Inclusion i, object sender, T args) where T : EventArgs
{
string logMsg="";
StringBuilder sb = new StringBuilder();

try
{
foreach (string s in i.SenderPropertyNames)
{
if (s != null)
{
PropertyInfo pi = sender.GetType().GetProperty(s);
object v = pi.GetValue(sender, null);
sb.Append(s + "=" + v + ";");
}
}
foreach (string s in i.EventArgsPropertyNames)
{
if (s != null)
{
string[] parts = s.Split('.');
PropertyInfo pi;
object v = args;
for (int k = 0; k < parts.Length; k++)
{
pi = v.GetType().GetProperty(parts[k]);
v = pi.GetValue(v, null);
}
sb.Append(s + "=" + v + ";");
}
}
string Name = "";
Control c = sender as Control;
if (c != null) Name = c.Parent.Name + ":" + c.Name;
logMsg = Name + " " + i.EventName + " " + sb.ToString();
}
catch (Exception ex)
{
logMsg = ex.Message + " " + ex.InnerException.Message + " " + ex.StackTrace;
}

finally
{
Action act = delegate
{
Console.WriteLine(logMsg);
ILog LOG = LogManager.GetLogger(typeof(TradeEntryMainForm));
LOG.Info(logMsg);
};
act.BeginInvoke(ar => { try { act.EndInvoke(ar); } catch { } }, null);
}

}

private static void AttacheEventHandler(Component c, Inclusion i)
{
foreach (EventInfo ei in c.GetType().GetEvents())
{
if (c.GetType().FullName == i.ComponentTypeFullName && ei.Name == i.EventName)
{
Type eventArgsType = ei.EventHandlerType.GetMethod("Invoke").GetParameters()[1].ParameterType;
MethodInfo mi = typeof(UIExtensioins).GetMethod("Log",
BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(eventArgsType
);
ei.AddEventHandler(c,
Delegate.CreateDelegate(ei.EventHandlerType, i, mi));
}
}
}
}

App Setting Json serialization


public class Inclusion
{
public string ComponentTypeFullName { get; set; }
public string EventName { get; set; }
public string[] SenderPropertyNames { get; set; }
public string[] EventArgsPropertyNames { get; set; }
}

static List li = new List()
{
new Inclusion(){
ComponentTypeFullName="Infragistics.Win.Misc.UltraButton",
EventName="Click",
SenderPropertyNames=new string[]{null},
EventArgsPropertyNames=new string[]{null}},
new Inclusion() {
ComponentTypeFullName="Infragistics.Win.UltraWinEditors.UltraComboEditor",
EventName="SelectionChanged",
SenderPropertyNames=new string[]{"Text"},
EventArgsPropertyNames=new string[]{null}},
new Inclusion() {
ComponentTypeFullName="Infragistics.Win.UltraWinToolbars.UltraToolbarsManager",
EventName="ToolClick",
SenderPropertyNames=new string[]{null},
EventArgsPropertyNames=new string[]{"Tool.Key"}},

};

//Read
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List));
string cd = Settings.Default.Inclusion;
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(cd));

List li2 =(List) ser.ReadObject(ms);
ms.Close();

//write to see the format
Type t = li.GetType();
DataContractJsonSerializer ser2 = new DataContractJsonSerializer(t);
FileStream fs = new FileStream(@"c:\3.txt", FileMode.CreateNew);
ser.WriteObject(fs, li);
fs.Flush();
fs.Close();

Wednesday, September 1, 2010

Simulating Anchro in WPF Form


1. xmal has <Border><Canvas> multiple sub canvas
2. Each sub-canvas hold different UI
3. Top canvas has SizeChanged event and where we transform button (btn1/2),
size datagrid (dg) and listbox (lb)

double dx=0,dy=0;
private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
this.dg.Width=e.NewSize.Width;
this.lb.Width = e.NewSize.Width;
if (e.PreviousSize.Width != 0)
{
dx += e.NewSize.Width - e.PreviousSize.Width;
dy += e.NewSize.Height - e.PreviousSize.Height;
this.btn1.RenderTransform = new TranslateTransform(dx, dy);
this.btn2.RenderTransform = new TranslateTransform(dx, dy);
this.dg.Height += e.NewSize.Height - e.PreviousSize.Height;
}
}



Friday, July 30, 2010

Generating Large and more decimal Number in SQL


DECLARE @RandomNumber decimal(32,12)
DECLARE @RandomInteger bigint
DECLARE @MaxValue bigint
DECLARE @MinValue bigint

SET @MaxValue = 4000000000
SET @MinValue = 2

SELECT @RandomNumber = RAND()

SELECT @RandomInteger = ((@MaxValue + 1) - @MinValue) * @RandomNumber + @MinValue

--SELECT @RandomNumber as RandomNumber, @RandomInteger as RandomInteger

--select cast(@RandomInteger as varchar(200))+cast(@RandomNumber as varchar(200))

select [dbo].[FormatDecimalCharWithCommaRound](cast(@RandomInteger as varchar(200))+cast(@RandomNumber as varchar(200))
,4),cast(@RandomInteger as varchar(200))+cast(@RandomNumber as varchar(200))

select [dbo].[FormatDecimalCharWithCommaRound](.12345678,2)

Sunday, July 25, 2010

Hosting Http Server in WPF Form


public partial class MainWindow : Window
{
protected HttpListener Listener;
protected bool IsStarted = false;
public event delReceiveWebRequest ReceiveWebRequest;


public void Start(string UrlBase)
{
if (this.IsStarted) return;
if (this.Listener == null)
{
this.Listener = new HttpListener();
}
this.Listener.Prefixes.Add(UrlBase);
this.IsStarted = true;
this.Listener.Start();
IAsyncResult result = this.Listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.Listener);
}

public void Stop()
{
if (Listener != null)
{
this.Listener.Close();
this.Listener = null;
this.IsStarted = false;
}
}

protected void WebRequestCallback(IAsyncResult result)
{
if (this.Listener == null) return;
HttpListenerContext context = this.Listener.EndGetContext(result);
this.Listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.Listener);
if (this.ReceiveWebRequest != null)
this.ReceiveWebRequest(context);
this.ProcessRequest(context);
}
string txt="";
protected virtual void ProcessRequest(HttpListenerContext Context)
{
NameValueCollection data = Context.Request.QueryString;
StringBuilder sb = new StringBuilder();
foreach (string s in data.Keys)
sb.Append(s + "=" + data[s]);
txt += sb.ToString() + "\r\n"; ;
HttpListenerResponse response = Context.Response;
string responseString = "<HTML><BODY>ACK</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}

public MainWindow()
{
InitializeComponent();
// Server = new HttpServer();
}

private void Grid_Loaded(object sender, RoutedEventArgs e)
{


}
// public HttpServer Server = null;

List d = new List();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Start("http://127.0.0.1:7777/");
//wkr = new BackgroundWorker();
//wkr.DoWork += new DoWorkEventHandler(StartHttpListener);
//server = new HttpListener();
//server.Prefixes.Add("http://127.0.0.1:7777/");
//server.Start();
//StartHttpListener(null, null);
// wkr.RunWorkerAsync();

listBox1.ItemsSource = d;



}


private void Window_Unloaded(object sender, RoutedEventArgs e)
{
this.Stop();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = txt;

}
}
public class TestData
{
public string name { get; set; }
public string value { get; set;}
}
}

Client Code to call
string url="123",userCd="test";
string dataComponentType="dc";
long[] ids= new long[]{1,2,3};
System.Net.WebClient c= new WebClient();
NameValueCollection nc= new NameValueCollection();
nc.Add("url",url);
nc.Add("userCd",userCd);
nc.Add("dataComponentType",dataComponentType);
foreach( long l in ids)
nc.Add("id"+l.ToString(),l.ToString());
c.QueryString=nc;
c.DownloadData("http://127.0.0.1:7777");

Monday, July 5, 2010

MSMQ in Java


One way to access Microsoft MSMQ from java is using http://msmqjava.codeplex.com/
JNI Library

Queue queue= new Queue("DIRECT=OS:ding-j-bos\\jqd3");
String qLabel="Created by jimmy.java";
String body= "Hello, World!";
byte[] correlationId = { 0,2,4,6,8,9 };
Message msg=new Message(body, qLabel, correlationId);
queue.send(msg);