Thursday, April 19, 2012

EF 5.0 makes developer’s life a lot easier who has had concern to use Repository Pattern and Unit of Work with Entity Framework

Fellows, Here is a simple project link to understand how canonical EF 5.0 code first approach has shown its magic with the help of DbContext Class, which has many built in capabilities in his pocket.

http://msdn.microsoft.com/en-us/librar/system.data.entity.dbcontext%28v=vs.103%29.aspx

http://efmvc.codeplex.com/

Cheers !!!

Monday, October 17, 2011

An Engineering Solution for a Showstopper Problem


We have had windows OS like update mechanism in order to update our server/client applications. Few days back, I have made one of my applications a windows service and I initiated the updater control and all other relevant actions of the controller from code behind, but once applying update from a remote location for the first time, the service could not launch itself after being updated , saying starting…. and went for an indefinite state. The same condition remains, even if I uninstall the service and install the updated service again from command prompt. I have tried several ways to fix the problem.... and at the end as a precaution measure, instead of applications executable and other necessary files, I have set the full bin folder on the update repository to be updated, so that nothing can get missed, but........still no luck!!!


As it is hard to track a tricky problem while you are residing inside the problem,so I had to apply my rule of thumb for this scenario and that was to go and think out of the box. Then I found that some common assemblies that have been referenced in different projects were the firebrand of the scenario. Furthermore, as we start some processes inside from the service as well … they were also the show stopper. So, found the obstacles, now I have separated those processes and have made the service light weighted so that it can lift itself without extra burden after getting updated . I have made a separate service monitor app, from where I launch my extra processes, stop/start service and monitor the service continuously.....


Now it’s working...... excellent!

Thursday, October 13, 2011

Implementation of Windows like cool Notification Service


Please click on above image to see the architectural design details on large view.


This is a small but essential utility tool for any project in order to receive notifications like Windows OS. Here is the overall scenario - I have so many core applications running on different parts of the world, those are connected with different LOGIC services and there are many LOGIC services running under different / same network. We have maintained WCF connection in between LOGIC service and core ends in order to communicate, send/receive data. To communicate with LOGIC services and Central, we have used XMPP client/server mechanism. Central server broadcasts notification messages to every LOGIC service, which has an unique Id to receive and then LOGIC service send notifications among cores using request callback of each core.

important code snippets has been provided below --

/// The callback notification interface.

public interface INotifyClientCallback
{
[OperationContract(IsOneWay = true)]
void NotificationCallBack(NotifyEventArg guid);
}

/// WCF data contract

[DataContract]
public class NotifyEventArg : EventArgs
{
[DataMember]
public bool isSuccessFull { get; set; }

[DataMember]
public object Data { get; set; }
}


/// A class to keep reference of InstanceContext & INotifyClientCallback

public class CommunicationStore
{
public InstanceContext IService { get; set; }
public INotifyClientCallback NotifyCallback { get; set; }

}


/// An implementation of NotifyCallback class

public class NotifyCallback : INotifyClientCallback
{

public void NotificationCallBack(NotifyEventArg args)
{
if (ProxyHelper.OnNotificationFromServer != null)
{
ProxyHelper.OnNotificationFromServer(null, args);
}

}

}

/// An implementation of WCF service class
/// IMyService interface defines all operation contracts


[ServiceBehavior(IncludeExceptionDetailInFaults = false, InstanceContextMode = InstanceContextMode.PerSession)]
[MyServiceBehavior]
public partial class MyService : IMyService, IDisposable
{
private bool _isServiceBusy;
private string _clientIpAddress;
public static event EventHandler OnClientAdded;
public static event EventHandler OnClientRemoved;


//list that keeps the all callback reference
private static readonly Dictionary ClientSubscribers = new Dictionary();


public void InitializationService()
{
INotifyClientCallback callback =
OperationContext.Current.GetCallbackChannel();
string IPAddress = GetAddressAsString();
lock (ClientSubscribers)
{
_clientIpAddress = IPAddress;
if (!ClientSubscribers.ContainsKey(IPAddress))
{
ClientSubscribers[IPAddress] = new CommunicationStore()
{
NotifyCallback = callback,
IService = OperationContext.Current.InstanceContext
};
if (OnClientAdded != null)
{
OnClientAdded(IPAddress, null);
}
}
}
}

public string GetAddressAsString()
{

if(OperationContext.Current.IncomingMessageProperties.ContainsKey(
RemoteEndpointMessageProperty.Name))
{
//check if the IP is 127.0.0.1(XP) or ::1 (Vista)(meaning client is in
the same PC)
RemoteEndpointMessageProperty remoteEndPoint =
(RemoteEndpointMessageProperty)(OperationContext.Current.
IncomingMessageProperties.ElementAt(3).Value);

if (remoteEndPoint.Address.Equals("127.0.0.1") ||
remoteEndPoint.Address.Equals("::1"))
{
//this will execute when the service and client are on the same machine
string pipedString = this.GetServiceInformation();
string[] names = pipedString.Split('|');
return "IP: " + names[1];
}
//this will execute if the service and client are on different machines
RemoteEndpointMessageProperty clientEndpoint = OperationContext.Current.
IncomingMessageProperties[RemoteEndpointMessageProperty.Name]
as RemoteEndpointMessageProperty;

return "IP: " + clientEndpoint.Address;
}
else
{
//this will execute when the service and client are on the same machine
string pipedString = this.GetServiceInformation();
string[] names = pipedString.Split('|');
return "IP: " + names[1];
}

}


#region IDisposable Members

public void Dispose()
{
if (OnClientRemoved != null)
{
if (_clientIpAddress != null)
{
ClientSubscribers.Remove(_clientIpAddress);
OnClientRemoved(_clientIpAddress, null);
}
}

}
#endregion
}

/// Method for broadcast notification messages from LOGIC service

public static void BroadCastNotification(string ipAddress, NotifyEventArg args)
{
if (ClientSubscribers.ContainsKey(ipAddress))
{
CommunicationStore com = ClientSubscribers[ipAddress];
//subscribers.Remove(ip);
if (((ICommunicationObject)com.NotifyCallback).State ==
CommunicationState.Opened)
{
try
{
//fires the callback method
com.NotifyCallback.NotificationCallBack(args);
}
catch (Exception)
{
// throw;
}
}
}
}

// On send message event

private static void XmppNotifyConnection_OnMessage(object sender, agsXMPP.protocol.client.Message msg)
{
// On send message event from XMPP client reside in Notification Service in Central
}

// On Receive message event

private static void XmppNotifyConnection_OnMessage(object sender, agsXMPP.protocol.client.Message msg)
{
// On Receive message event to XMPP client reside in LOGIC service
}


In your client data handler project use a helper class like below—

public static class MyServiceConnectionHelper
{
public static EventHandler OnNotifyFinished;

static MyServiceConnectionHelper()
{
ProxyHelper.OnNotificationFromServer += OnNotificationReceiveFromServer;
}

private static void OnNotificationReceiveFromServer(object sender, NotifyEventArg
e)
{
OnNotifyFinished(null, e);
}

}


From Core End in your UI code behind write something like ----

MyConnectionHelper.OnNotifyFinished += OnNotificationReceive;

private void OnNotificationReceive(object sender, NotifyEventArg arg)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
{

Use a classy cool notify icon to represent - arg.Data.ToString();
}
}


So, here it is… If you guyz have any query regarding the design or implementation, do not hesitate to ping me @ --- a.rahmanbd@yahoo.com.

Wednesday, September 7, 2011

XMPP Client Implementation like Spark IM for .NET developers


We can use Spark IM for extensive client support like as help desk, agent services, duplex messaging service, group discussion, conferencing, a full-fledge instant messenger or as call center application. But Spark IM is a Java based implementation, so If you guyz need an open source for solid and extensive implementation of XMPP client version like Spark IM, based on C#.Net, ping me at -- a.rahmanbd@yahoo.com

Saturday, January 1, 2011

Cinch MVVM framework (V1 & V2) - I'm lovin' it.

I have seen couple of MVVM implementations for WPF/Silverlight apps but loved mostly the Sacha Barber’s one. He has fantastically shown how we can really left our Views with zero code behind, just awesome…..

DI/IOC using Unity DI Container for V1 but later changed his mind for the V2 with MEF.

And the another part of V2 has an implementation of MVVM, PRISM(modularity design) & MEF in one single plate.

I am posting the reference links here to see in details..

http://www.codeproject.com/KB/WPF/Cinch.aspx

http://www.codeproject.com/KB/WPF/CinchV2_1.aspx

http://www.codeproject.com/KB/WPF/CinchV2AndPRISM4.aspx

PRISM4 : With UNITY or MEF ? –Dependency Injection (DI) & Inversion of Control (IOC)

Managing Dependencies Between Components, we outline some of the differences between the containers and leave the choice to the developer based on the needs of the project.  With Prism being container agnostic, developers can write a few simple classes for any container and plug it into Prism.  In the box, we have support of Unity and MEF, but the extension point is there and documented.

Here are some of the big differences between MEF and Unity:

  • MEF is not a DI container (it’s a dynamic add-in framework that uses DI techniques), but can be made to act like a DI container for simple scenarios. It has the advantage of being in the .NET 4.0 framework.
  • Unity is a full DI container. It supports .NET 3.5 and 4.0. It also supports more complex DI things like open generics, policy injection (AOP), etc.

The development styles differ quite a bit due to the different approaches in design an scenarios for usage.  With MEF, it is recommended to do declarative programming (attributes for registration/exporting and importing).  With Unity, the more common approach is a lot more imperative (registration via code rather than attributes). Constructor injection is preferred in Unity (even though it can do property injection) vs property injection is preferred in MEF (even though it can do constructor injection).

 

- Microsoft Patterns & Practice.

Thursday, October 28, 2010

Reconfigurable Computing

Quartus II is an excellent tool/emulator for designing your desired computing architecture and making simulation within very short time with ease. Then load the design to Altera/Xilinx FPGA device so that it works according to your need. Now it’s time to say ‘good bye’ to ramshackle manual electronic system design & testing. I just wonder how easily & quickly i can build and do analysis a Turing Machine by the help of this tool. however design of an algorithm in hardware level requires hard effort and huge brain work.

For details-

http://www.altera.com/support/software/sof-quartus.html

Support Vector Machine (SVM)

SVM is a pattern/data classifier. This is a better approach than Neural Network based classifier and It’s optimization is a frontier research area in recent time. Those who would like to have a clear visualization on underlying mathematics of support vector machine, can collect a document written & compiled by me. It might be a solace to your pain on SVM. The doc also includes a sample example on how to use SVM tools (LibSVM) in case of your need.

Just ping me at a.rahmanbd@yahoo.com for the doc file.

My AT89S51 Microcontroller based Trainer Board

trainerboard

Please click on the image in order to see clear view.


The objective of the project is to develop an AT89S51 microcontroller based trainer kit having an onboard ADC with provision for port access [for integrating devices outside to the trainer kit], a 4x4 keypad, LCD display and serial interface with PC.

Task breakdown
- Interfacing ADC with AT89S51
- Interfacing 16x2 LCD with AT89S51
- Interfacing 4x4 keypad with AT89S51
- ADC must get data from outside
- Bridge microcontroller with the PC via COM port (serial) to read/write data to/from the board.

Heart of the System

The software has been written using AT89S51 microcontroller compatible assembly language. The provision for choosing assembly language is, I can directly talk/listen to/from hardware, no wrapping and more handling capability on my own hands. For editing/ compiling/creation of hex file, I have used the MIDE-51 Editor. I have used C# serial port class for pc + microcontroller communication and data exchange. our project required an internal interrupt and an external interrupt in order to functioning the whole system without extra hand, i.e. no re-dumping of hex file into the controller engine.

We didn’t use IC MM74C922 for check bouncing of key press since it will increase the product cost rather we have checked it by software using delay technique.

 

Project Code

//////////////////////////////////////////
Code that has been used as hex file inside microcontroller
//////////////////////////////////////////


;the following experiment is used to scan 
;keypad 4x4 and result of scan will be released
;to LCD Character as normal operation
;an ADC o/p will be available to port when
;external interrupt triggered and serial port data
;fetch using serial port interrupt(internal interrupt)

row1 bit P1.4
row2 bit P1.5
row3 bit P1.6
row4 bit P1.7
col1 bit P1.0
col2 bit P1.1
col3 bit P1.2
col4 bit P1.3
;

keybounc  equ 71h
keyport   equ P1

org 0h
LJMP start
ORG 0003h ; vector address for interrupt 0
LJMP ISR0 ; jump to start of ISR0

ORG 23h ; vector address serial port interrupt
LJMP ISR_SERIAL

ORG 0100h

start:
MOV IE, #10010001B
SETB IT0
call keypad4x4    ;calling subroutine keypad4x4
Mov A,R7;keydata     ;A = keydata 
Cjne A,#0FFh,WrLCD;
sjmp start        ;LOOPING FOREVER PART 1
;

WrLCD: call Init_lcd
Mov R1,#80h       ;Pick DDRAM 1st row and 1st col
call write_inst
Mov R1,A
call write_data   ;write data
Ljmp start        ;LOOPING FOREVER PART 2
;
Init_lcd:
mov r1,#00000001b ;Display clear
acall write_inst  ;
mov r1,#00111000b ;Function set,
;Data 8 bit,2 line font 5x7
acall write_inst  ;
mov r1,#00001100b ;Display on,
;cursor off,cursor blink off
acall write_inst
mov r1,#00000110b ;Entry mode, Set increment
acall write_inst
ret
;
Write_inst:
clr P3.4  ; RS = P3.4 = 0, write mode instruction
mov P2,R1 ; D7 s/d D0 = P2 = R1
setb P3.5 ; EN = 1 = P3.5
call delay; call delay time
clr P3.5  ; EN = 0 = P3.5
ret
;
Write_data:
setb P3.4 ; RS = P3.4 = 1, write mode data
mov P2,R1 ; D7 s/d D0 = P0 = R1
setb P3.5 ; EN = 1 = P3.5
call delay; call delay time
clr p3.5  ; EN = 0 = P3.5
ret
;
delay: mov R0,#0
delay1:mov R2,#50
djnz R2,$
djnz R0,delay1
ret

;===================================
; subroutine scan keypad 4x4
;===================================
Keypad4x4:
mov keybounc,#50    ;keybounc = 50         
mov keyport,#0FFh   ;keyport=P1= FF, inut port
clr col1                        ;col1= P1.0 = 0
Detect:jb row1,key1        ;jump to Key1 if row1=1
djnz keybounc,Detect
mov R7,#'0';0h          ;Keydata =00h
ret
;
key1: jb row2,key2         ;jump to key2 if row2=1
djnz keybounc,key1
mov R7,#'4';04h     ;Keydata = 04h
ret
;
key2: jb row3,key3        
djnz keybounc,key2
mov R7,#'8';08h
ret
;
key3: jb row4,key4       
djnz keybounc,key3
mov R7,#'c';0Ch
ret
;
key4: setb col1
clr col2
jb row1,key5
djnz keybounc,key4
mov R7,#'1';01h
ret
;
key5: jb row2,key6
djnz keybounc,key5
mov R7,#'5';05h
ret
;
key6: jb row3,key7
djnz keybounc,key6
mov R7,#'9';09h
ret
;
key7: jb row4,key8
djnz keybounc,key7
mov R7,#'d';0Dh
ret
;
key8: setb col2
clr col3
jb row1,key9
djnz keybounc,key8
mov R7,#'2';02h
ret
;
key9: jb row2,keyA
djnz keybounc,key9
mov R7,#'6';06h
ret
;
keyA: jb row3,keyB
djnz keybounc,keyA
mov R7,#'A';0Ah
ret
;
keyB: jb row4,keyC
djnz keybounc,keyB
mov R7,#'E';0Eh
ret
;
keyC: setb col3
clr col4
jb row1,keyD
djnz keybounc,keyC
mov R7,#'3';03h
ret
;
keyD: jb row2,keyE
djnz keybounc,keyD
mov R7,#'7';07h
ret
;
keyE: jb row3,keyF
djnz keybounc,keyE
mov R7,#'B';0Bh
ret
;
keyF: jb row4,Nokey
djnz keybounc,keyF
mov R7,#'F';0Fh
ret
Nokey:mov R7,#0FFh   
ret
;================================
;The end of Keypad 4x4 subroutine
;================================

ISR0:
Hundreds equ 30h
tens     equ 31h
ones     equ 32h
call init_LCD

call ADC
call Bin2Dec
call Write2LCD
RETI

;
;===================================
;this subroutine is used to take data from ADC and
;keep to Accumulator
;===================================
ADC:   mov A,P0
nop
nop
ret

;===================================
;this subroutine is used to convert binary data from ADC
;become decimal 3 digit
;===================================
;
write_char:      
mov dptr,#word1 ;DPTR = [ address word1 ]
mov r3,#16      ;R3=16,number character to be display
mov r1,#80h     ;R1=80h,address DDRAM start position
acall write_inst
;
write1:clr a           ; A = 0
movc a,@a+dptr  ; A = [A+ DPTR]
mov r1,A        ; R1 = A
inc dptr        ; DPTR = DPTR +1
acall write_data;   
djnz r3,write1  ; R3 = R3-1,
ret
;

word1: DB '  Data ADC0804  '
;end lcd

ISR_SERIAL:
nop
call initserial
call inchar                     
call init_LCD       
call Bin2Dec
call Write2LCD
RETI
;
initserial:
mov scon,#52h
mov tmod,#20h
mov th1,#-13
setb tr1
ret
;
inchar:
detect1: jnb ri,detect1;
clr ri
mov a,sbuf
ret
;

Write2LCD:      
mov r1,#0c9h
call write_inst
mov a,hundreds
add a,#30h
mov r1,a
call write_data
;
mov r1,#0cah
call write_inst
mov a,tens
add a,#30h
mov r1,a
call write_data
;
mov r1,#0cbh
call write_inst
mov a,ones
add a,#30h
mov r1,a
call write_data
ret

Bin2Dec:
mov b,#100d
div ab
mov hundreds,a
mov a,b
mov b,#10d
div ab
mov tens,a
mov ones,b
ret          

end

//////////////////////////////////////////Code that has been used in pc side to communicate with microcontroller
//////////////////////////////////////////

using System.IO.Ports;
public void SendByte(byte packet)
{
try
{
SerialPort port = new SerialPort("COM1", 2400, Parity.None, 8, 
StopBits.One);
port.Open();
byte[] writeByte = new byte[1];
writeByte[0] = packet;
port.Write(writeByte, 0, 1); // write to port
port.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}  
}

public void ReadByte()
{
byte byteRead = new byte();

try
{
SerialPort port = new SerialPort("COM1", 2400, Parity.None,
8, StopBits.One);

port.Open();
int byteValue = port.ReadByte(); // read from port
port.Close();

byteRead = Convert.ToByte(byteValue);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}           
}

Tuesday, August 3, 2010

The Knuth-Morris-Pratt Algorithm in my own words

For the past few days, I’ve been reading various explanations of the Knuth-Morris-Pratt string searching algorithms. For some reason, none of the explanations were doing it for me. I kept banging my head against a brick wall once I started reading “the prefix of the suffix of the prefix of the…”.

Finally, i got an online help, which is pretty much appreciable, originally published at http://jboxer.com/...but the site contains potentially dangerous virus, which caused me post the help here as well.


The Partial Match Table(Prefix Computation Function)

The key to KMP, of course, is the partial match table. The main obstacle between me and understanding KMP was the fact that I didn’t quite fully grasp what the values in the partial match table really meant. I will now try to explain them in the simplest words possible.


Here’s the partial match table for the pattern “abababca”:

char: | a | b | a | b | a | b | c | a |
index: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
value: | 0 | 0 | 1 | 2 | 3 | 4 | 0 | 1 |


If I have an eight-character pattern (let’s say “abababca” for the duration of this example), my partial match table will have eight cells. If I’m looking at the eighth and last cell in the table, I’m interested in the entire pattern (“abababca”). If I’m looking at the seventh cell in the table, I’m only interested in the first seven characters in the pattern (“abababc”); the eighth one (“a”) is irrelevant, and can go fall off a building or something. If I’m looking at the sixth cell of the in the table… you get the idea. Notice that I haven’t talked about what each cell means yet, but just what it’s referring to.


Now, in order to talk about the meaning, we need to know about proper prefixes and proper suffixes.


Proper prefix: All the characters in a string, with one or more cut off the end. “S”, “Sn”, “Sna”, and “Snap” are all the proper prefixes of “Snape”.


Proper suffix: All the characters in a string, with one or more cut off the beginning. “agrid”, “grid”, “rid”, “id”, and “d” are all proper suffixes of “Hagrid”.


With this in mind, I can now give the one-sentence meaning of the values in the partial match table:


The length of the longest proper prefix in the (sub)pattern that matches a proper suffix in the same (sub)pattern.


Let’s examine what I mean by that. Say we’re looking in the third cell. As you’ll remember from above, this means we’re only interested in the first three characters (“aba”). In “aba”, there are two proper prefixes (“a” and “ab”) and two proper suffixes (“a” and “ba”). The proper prefix “ab” does not match either of the two proper suffixes. However, the proper prefix “a” matches the proper suffix “a”. Thus, the length of the longest proper prefix that matches a proper suffix, in this case, is 1.


Let’s try it for cell four. Here, we’re interested in the first four characters (“abab”). We have three proper prefixes (“a”, “ab”, and “aba”) and three proper suffixes (“b”, “ab”, and “bab”). This time, “ab” is in both, and is two characters long, so cell four gets value 2.

Just because it’s an interesting example, let’s also try it for cell five, which concerns “ababa”. We have four proper prefixes (“a”, “ab”, “aba”, and “abab”) and four proper suffixes (“a”, “ba”, “aba”, and “baba”). Now, we have two matches: “a” and “aba” are both proper prefixes and proper suffixes. Since “aba” is longer than “a”, it wins, and cell five gets value 3.

Let’s skip ahead to cell seven (the second-to-last cell), which is concerned with the pattern “abababc”. Even without enumerating all the proper prefixes and suffixes, it should be obvious that there aren’t going to be any matches; all the suffixes will end with the letter “c”, and none of the prefixes will. Since there are no matches, cell seven gets 0.

Finally, let’s look at cell eight, which is concerned with the entire pattern (“abababca”). Since they both start and end with “a”, we know the value will be at least 1. However, that’s where it ends; at lengths two and up, all the suffixes contain a c, while only the last prefix (“abababc”) does. This seven-character prefix does not match the seven-character suffix (“bababca”), so cell eight gets 1.


How to use the Partial Match Table

We can use the values in the partial match table to skip ahead (rather than redoing unnecessary old comparisons) when we find partial matches. The formula works like this:

If a partial match of length partial_match_length is found and table[partial_match_length] > 1, we may skip ahead partial_match_length - table[partial_match_length - 1] characters.

Let’s say we’re matching the pattern “abababca” against the text “bacbababaabcbab”. Here’s our partial match table again for easy reference:

char: | a | b | a | b | a | b | c | a |
index: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
value: | 0 | 0 | 1 | 2 | 3 | 4 | 0 | 1 |

The first time we get a partial match is here:
bacbababaabcbab
X|
Xabababca

This is a partial_match_length of 1. The value at table[partial_match_length - 1] (or table[0]) is 0, so we don’t get to skip ahead any. The next partial match we get is here:

bacbababaabcbab
XXXX|||||
XXXXabababca

This is a partial_match_length of 5. The value at table[partial_match_length - 1] (or table[4]) is 3. That means we get to skip ahead partial_match_length - table[partial_match_length - 1] (or 5 - table[4] or 5 - 3 or 2) characters:

// x denotes a skip
bacbababaabcbab
YYYYXX|||
YYYYXXabababca

This is a partial_match_length of 3. The value at table[partial_match_length - 1] (or table[2]) is 1. That means we get to skip ahead partial_match_length - table[partial_match_length - 1] (or 3 - table[2] or 3 - 1 or 2) characters:

// x denotes a skip
bacbababaabcbab
YYYYYYXX|
YYYYYYXXabababca


At this point, our pattern is longer than the remaining characters in the text, so we know there’s no match.


So there you have it. it’s a walk through of brain work, with the parts I found extremely confusing spelled out here in extreme detail. If you have any questions or notice something I messed up, please leave a comment; maybe we’ll all learn something.

Sunday, June 20, 2010

Collocation or Tessellation of incongruent right angles quadrilateral onto a plane / Making sprite image for CSS Sprite technique- A Greedy Approach.

It’s easy to combine small images to make one giant image, but if there is certain constraint like you have fixed width of the resulting image and you have to make the best use of your space so that things can get in order then there is an opportunity for little brainstorming. Here is a sample code to serve the purpose written in C#. Somebody can use better search and sorting technique according to their need.

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Drawing;

namespace SpriteImage

{

class Program

{

public List<System.Drawing.Bitmap> images = new

List<System.Drawing.Bitmap>();

public int MaxWidth = 90, _index = 0;

public bool[] IsImageSet;

public int[] imageWidth;

Dictionary<int, List<int>> _recordes;

public Dictionary<int, List<int>> Recordes

{

get { return _recordes; }

}

static void Main(string[] args)

{

string[] files = Directory.GetFiles(@"C:\Img\");

Program p = new Program();

System.Drawing.Bitmap combinedImage = p.Combine(files);

combinedImage.Save(@"C:\stitchedImage.Png",

System.Drawing.Imaging.ImageFormat.Png);

}

public void MarkImageAsSet(int index)

{

IsImageSet[index] = true;

}

public Bitmap SearchNextFitImage(int Offset)

{

int[] temp = new int[imageWidth.Length]; int j = 0;

for (int i = 0; i < imageWidth.Length; i++)

{

if (imageWidth[i] <= Offset)

{

if (!IsImageSet[i])

{

temp[j++] = imageWidth[i];

}

}

}

int bigValue = 0;

// find the highest magnitude

for (int i = 0; i < j; i++)

{

bigValue = temp[i] > bigValue ? temp[i] : bigValue;

}

bool IsFound = false;

for (int i = 0; i < imageWidth.Length; i++)

{

if (imageWidth[i] == bigValue)

{

if (!IsImageSet[i])

{

IsFound = true; _index = i;

break;

}

}

}

if (IsFound)

{

return images[_index];

}

else

return null;

}

public Bitmap Combine(string[] files)

{

System.Drawing.Bitmap finalImage = null;

try

{

foreach (string image in files)

{

if (String.Compare("C:\\Img\\Thumbs.db", image) != 0)

{

System.Drawing.Bitmap bitmap = new

System.Drawing.Bitmap(image);

images.Add(bitmap);

}

}

int[] ImageId = new int[images.Count];

for (int i = 0; i < ImageId.Length; i++)

{

ImageId[i] = i;

}

Bitmap temp; int t;

// sort in descending order according to image height.

for (int i = 0; i < images.Count; i++)

{

for (int j = 0; j < images.Count; j++)

{

if (images[i].Height > images[j].Height)

{

temp = images[i];

images[i] = images[j];

images[j] = temp;

t = ImageId[i];

ImageId[i] = ImageId[j];

ImageId[j] = t;

}

}

}

IsImageSet = new bool[images.Count];

imageWidth = new int[images.Count];

// set image width

for (int i = 0; i < images.Count; i++)

{

imageWidth[i] = images[i].Width;

}

//// simulate the possible height

int count = 0, indexTop = 0, offset = 0, width = 0, height =

0;

while (count != images.Count)

{

if (count == 0)

{

// set 1st image

width = images[0].Width;

offset = MaxWidth - width;

MarkImageAsSet(count);

count++; continue;

}

Bitmap nextFitImage = SearchNextFitImage(offset);

if (nextFitImage != null)

{

MarkImageAsSet(_index);

count++;

offset = offset - nextFitImage.Width;

// offsetX = MaxWidth - offset;

Cordinate(offsetX,images[indexTop].Height)

}

else

{

if (!IsImageSet[indexTop + 1])

{

height += images[indexTop].Height;

indexTop++;

offset = MaxWidth - images[indexTop].Width;

count++;

MarkImageAsSet(indexTop);

//Cordinate(0,images[indexTop].Height)

}

// find next available image

else

{

for (int i = 0; i < IsImageSet.Length; i++)

{

if (!IsImageSet[i])

{

height += images[indexTop].Height;

indexTop = i;

offset = MaxWidth - images[i].Width;

count++;

MarkImageAsSet(i);

break;

}

}

}

}

}

height += images[indexTop].Height;

//////////////////

///// now set the images

finalImage = new System.Drawing.Bitmap(MaxWidth, height);

_recordes = new Dictionary<int, List<int>>();

using (System.Drawing.Graphics g =

System.Drawing.Graphics.FromImage(finalImage))

{

g.Clear(System.Drawing.Color.Transparent);

IsImageSet = new bool[images.Count];

count = 0; indexTop = 0; offset = 0; width = 0; height =

0; _index = 0;

int offsetX = 0;

while (count != images.Count)

{

if (count == 0)

{

// set 1st image

width = images[0].Width;

offset = MaxWidth - width;

g.DrawImage(images[0],

new System.Drawing.Rectangle(0, 0,

images[0].Width, images[0].Height));

// set cordinate into dictionary

List<int> point = new List<int>();

point.Add(0); point.Add(0);

_recordes.Add(ImageId[0], point);

//-----------------------

MarkImageAsSet(count);

count++; continue;

}

Bitmap nextFitImage = SearchNextFitImage(offset);

if (nextFitImage != null)

{

MarkImageAsSet(_index);

count++;

offsetX = MaxWidth - offset;

offset = offset - nextFitImage.Width;

if (indexTop == 0)

{

g.DrawImage(images[_index],

new System.Drawing.Rectangle(offsetX, 0,

images[_index].Width, images[_index].Height));

// set cordinate into dictionary

List<int> point = new List<int>();

point.Add(offsetX); point.Add(0);

_recordes.Add(ImageId[_index], point);

//-----------------------

}

else

{

g.DrawImage(images[_index],

new System.Drawing.Rectangle(offsetX,

height, images[_index].Width, images[_index].Height));

// set cordinate into dictionary

List<int> point = new List<int>();

point.Add(offsetX); point.Add(height);

_recordes.Add(ImageId[_index], point);

//-----------------------

}

// Cordinate(offsetX,images[indexTop].Height)

}

else

{

if (!IsImageSet[indexTop + 1])

{

height += images[indexTop].Height;

indexTop++;

offset = MaxWidth - images[indexTop].Width;

g.DrawImage(images[indexTop],

new System.Drawing.Rectangle(0, height,

images[indexTop].Width, images[indexTop].Height));

// set cordinate into dictionary

List<int> point = new List<int>();

point.Add(0); point.Add(height);

_recordes.Add(ImageId[indexTop], point);

//-----------------------

count++;

MarkImageAsSet(indexTop);

//Cordinate(0,images[indexTop].Height)

}

// find next available image

else

{

for (int i = 0; i < IsImageSet.Length; i++)

{

if (!IsImageSet[i])

{

height += images[indexTop].Height;

indexTop = i;

offset = MaxWidth - images[i].Width;

g.DrawImage(images[i],

new System.Drawing.Rectangle(0,

height, images[i].Width, images[i].Height));

// set cordinate into dictionary

List<int> point = new List<int>();

point.Add(0); point.Add(height);

_recordes.Add(ImageId[i], point);

//-----------------------

count++;

MarkImageAsSet(i);

break;

}

}

}

}

}

}

return finalImage;

}

catch (Exception ex)

{

if (finalImage != null)

finalImage.Dispose();

throw ex;

}

finally

{

//clean up memory

foreach (System.Drawing.Bitmap image in images)

{

image.Dispose();

}

}

}

}

}

Wednesday, April 7, 2010

Using F# from Native Code via COM


Although it is more likely that you will want to call native code from F# code, sometimes you might want to call F# library functions from native code. For example, suppose you have a large application written in C++, and perhaps you are happy for the user interface to remain in C++ but want to migrate some logic that performs complicated mathematical calculations to F# for easier maintenance. In this case, you would want to call F# from native code. The easiest way to do this is to use the tools provided with .NET to create a COM wrapper for your F# assembly; you can then use the COM runtime to call the F# functions from C++.



To expose functions through COM, you need to develop them in a certain way.

First you must define an interface that will specify the contract for your functions, the members of the interface must be written using named arguments and the interface itself must be marked with the System.Runtime.InteropServices.Guid attribute. Then you must provide a class that implements the interface; this too must be marked with the System.Runtime.InteropServices.Guid attribute and also System.Runtime.InteropServices.ClassInterface, and you should always pass the ClassInterfaceType.None enumeration member to the ClassInterface attribute constructor to say that no interface should be automatically generated.


I’ll now show an example of doing this; suppose you want to expose two functions called Add and Sub to your unmanaged client. So, create an interface IMath in the namespaceTest, and then create a class Math to implement this interface. You then need to ensure that both the class and the interface are marked with the appropriate attributes. The resulting code is as follows:


namespace Test
open System
open System.Runtime.InteropServices

['<' Guid("6180B9DF-2BA7-4a9f-8B67-AD43D4EE0563") '>']
type IMath = interface
abstract Add : x: int * y: int -> int
abstract Sub : x: int * y: int -> int
end

['<'Guid("B040B134-734B-4a57-8B46-9090B41F0D62");
ClassInterface(ClassInterfaceType.None)'>']
type Math = class
new () = {}
interface IMath with
member this.Add(x, y) = x + y
member this.Sub(x, y) = x - y
end
end


The functions Add and Sub are of course simple, so there is no problem implementing
them directly in the body of the Math class. If you needed to break them down into other helper functions outside the class, then this would not have been a problem; it is fine to implement your class members in any way you see fit. You simply need to provide the interface and the class so the COM runtime has an entry point into your code.

Now comes arguably the most complicated part of the process—registering the assembly
so the COM runtime can find it. To do this, you need to use a tool called RegAsm.exe. Suppose you compiled the previous sample code into a .NET .dll called ComLibrary.dll; then you would need to call RegAsm.exe twice using the following command lines:


regasm comlibrary.dll /tlb:comlibrary.tlb
regasm comlibrary.dll


The first time is to create a type library file, a .tlb file, which you can use in your C++ project to develop against. The second registers the assembly itself so the COM runtime can find it. You will also need to perform these two steps on any machine to which you deploy your assembly.

The C++ to call the Add function appears after the next list; the development environment and how you set up the C++ compiler will also play a large part in getting this code to compile. In this case, I created a Visual Studio project, choosing a console application template, and activated ATL. Notice the following about this source code:

• The #import command tells the compiler to import your type library; you may need to use the full path to its location. The compiler will also automatically generate a header file, in this case comlibrary.tlh, located in the debug or release directory. This is useful because it lets you know the functions and identifiers that are available as a result of your type library.

• You then need to initialize the COM runtime; you do this by calling the CoInitialize function.

• You then need to declare a pointer to the IMath interface you created; you do this via the code comlibrary::IMathPtr pDotNetCOMPtr;. Note how the namespace comes from the library name rather than the .NET namespace.

• Next you need to create an instance of your Math class; you achieve this by calling the CreateInstance, method passing it the GUID of the Math class. Fortunately, there is a constant defined for this purpose.

• If this was successful, you can call the Add function; note how the result of the function is actually an HRESULT, a value that will tell you whether the call was successful. The actual result of the function is passed out via an out parameter.

Here’s the code:

#include "stdafx.h"
#import "ComLibrary.tlb" named_guids raw_interfaces_only
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
comlibrary::IMathPtr pDotNetCOMPtr;
HRESULT hRes = pDotNetCOMPtr.CreateInstance(comlibrary::CLSID_Math);
if (hRes == S_OK)
{
long res = 0L;
hRes = pDotNetCOMPtr->Add(1, 2, &res);
if (hRes == S_OK)
{
printf("The result was: %ld", res);
}
pDotNetCOMPtr.Release();
}
CoUninitialize ();
return 0;
}

The results of this example, when compiled and executed, are as follows:

The result was: 3

When you execute the resulting executable, you must ensure that ComLibrary.dll is in the same directory as the executable, or the COM runtime will not be able to find it. If you intend that the library be used by several clients, then I strongly recommend that you sign the assembly and place it in the GAC; this will allow all clients to be able to find it without having to keep a copy in the directory with them.


Tuesday, April 6, 2010

WCF with F#

This is a simple application to test WCF with F#. You can have a look and get into distributed application using F# .

#light
namespace WCF.Test
open System
open System.Data.Common
open System.Data.Sql
open System.Data.SqlClient
open System.ServiceModel
open System.Runtime.Serialization

type Person =
{FirstName:string;
LastName:string;
Email:string;
PhoneNumber:string}

module DB =
let connString = @"Data Source=.\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True;"
let conn = new SqlConnection(connString)
let query () =
seq { use conn = new SqlConnection(connString)
do conn.Open()
use comm = new SqlCommand("SELECT top 50 * FROM Person.Contact",conn)
use reader = comm.ExecuteReader()
while reader.Read() do
yield ({FirstName = reader.GetString 3;
LastName = reader.GetString 5;
Email = reader.GetString 7;
PhoneNumber = reader.GetString 9}) }

[<ServiceContract()>]
type IPersonService = interface
[<OperationContract()>]
abstract GetPersons: unit -> Person array
end

[<ServiceBehavior(Name="PersonService",InstanceContextMode=InstanceContextMode.Single)>]
type PersonService() =
interface IPersonService with
member v.GetPersons () =
Console.WriteLine("Retrieving people list...")
DB.query() |> Seq.to_array

do
Console.WriteLine("PersonService")
let serviceType = typeof<PersonService>
let address = new Uri("http://localhost:28888/PersonService")
let host = new ServiceHost(serviceType,[|address|])
host.Open()
Console.WriteLine("Press <ENTER> to terminate the host application")
Console.ReadLine() |> ignore
host.Close()

 

Here’s the configuration file for the WCF service:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- here is the base address of our service -->
<appSettings>
<add key ="baseAddress" value="http://localhost:28888/PersonService"/>
</appSettings>
<system.serviceModel>
<services>
<service name="WCF.Test.PersonService" behaviorConfiguration="PersonServiceBehaviors">
<endpoint address="http://localhost:28888/PersonService"
binding="basicHttpBinding"
contract="WCF.Test.IPersonService"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="PersonServiceBehaviors" >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug httpHelpPageEnabled="true"
includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

Now make a proxy using svcutil.exe that will generate a class file and a config file. Add those into client application project directory.

Here’s the client code:

#light
#I @"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0"
#I @"C:\WINNT\Microsoft.NET\Framework\v2.0.50727"
#r @"WindowsBase.dll"
#r @"PresentationCore.dll"
#r @"PresentationFramework.dll"
#r @"C:\Program Files\WPF Toolkit\v3.5.40320.1\WPFToolkit.dll"

open Microsoft.Windows.Controls


open System
open System.Windows
open System.Windows.Controls

let service = new PersonService()
let persons = service.GetPersons()
let win = new Window(Title="Test DataGrid w/WCF")
let datagrid = DataGrid()
datagrid.HeadersVisibility <- DataGridHeadersVisibility.Column
datagrid.ItemsSource <- persons
win.Content <- new ScrollViewer(Content=datagrid)
win.Show()

have fun guys………………

Friday, April 2, 2010

Prototype Chaining/ Inheritance in Js

Prototype chaining is the default way to implement inheritance, and is described in the ECMAScript standard. In order to implement our hierarchy, let's define three constructor functions.

function Shape(){
this.name = 'shape';
this.toString = function() {return this.name;};
}

function TwoDShape(){
this.name = '2D shape';
}

function Triangle(side, height) {
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){return this.side * this.height / 2;};
}


Efficient way:

function Shape(){}
// augment prototype
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};

function TwoDShape(){}
// take care of inheritance
TwoDShape.prototype = Shape.prototype;
TwoDShape.prototype.constructor = TwoDShape;
// augment prototype
TwoDShape.prototype.name = '2D shape';

function Triangle(side, height) {
this.side = side;
this.height = height;
}

// take care of inheritance
Triangle.prototype = TwoDShape.prototype;
Triangle.prototype.constructor = Triangle;
// augment prototype
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){return this.side * this.height / 2;}


The test code will give the same result:
>>> var my = new Triangle(5, 10);
>>> my.getArea()
25



Isolating the Inheritance Part into a Function:

Let's move the code that takes care of all of the inheritance details into a reusable extend() function:

function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}

Using this function (or our own custom version of it) will help you keep our code clean with regard to the repetitive inheritance-related tasks. This way you can inherit by simply using:

extend(TwoDShape, Shape);
and
extend(Triangle, TwoDShape);

This approach is the way the YUI (Yahoo! User Interface) library implements inheritance through its extend() method. For example, if you use YUI and you want your Triangle to inherit from Shape, you use:
YAHOO.lang.extend(Triangle, Shape)

Understanding 'Prototype' concept in Js


The prototype property of a function contains an object. It is only useful when you use this function as a constructor.
All objects created with this function keep a reference to the prototype property and can use its properties as their own

var some_obj = {
name: 'Arif',
say: function(){
return 'I am ' + this.name;
}
}

function F(){}
F.prototype = some_obj;

>>> var obj = new F();
>>> obj.name
"Arif"
>>> obj.say()
"I am Arif"

Digging Concept of 'Closure' in Js


A closure is created when a function keeps a link to its parent's scope even after the parent has returned.

function f(arg) {
var n = function(){
return arg;
};
arg++;
return n;
}

We can use the function like this in firefox consol:
>>> var m = f(123);
>>> m();
124

Another shot:

function f() {
var a = [];
var i;
for(i = 0; i < 3; i++) {
a[i] = function(){
return i;
}
}
return a;
}

Let's run the function, assigning the result to the array a.
>>> var a = f();
>>> a[0]()
3
>>> a[1]()
3
>>> a[2]()
3

So how do we implement the correct behavior? we need three different variables. An elegant solution is to use another closure:

function f() {
var a = [];
var i;
for(i = 0; i < 3; i++) {
a[i] = (function(x){
return function(){
return x;
}
})(i);
}
return a;
}

This gives the expected result:
>>> var a = f();
>>> a[0]();
0
>>> a[1]();
1
>>> a[2]();
2

Alternative Approach:

Alternatively, we can use a "normal" (as opposed to self-invoking) inner function to achieve the same result. The key is to use the middle function to "localize" the value of i at every iteration.

function f() {
function makeClosure(x) {
return function(){
return x;
}
}
var a = [];
var i;
for(i = 0; i < 3; i++) {
a[i] = makeClosure(i);
}
return a;
}

Another shot:

var getValue, setValue;
(function() {
var secret = 0;
getValue = function(){
return secret;
};
setValue = function(v){
secret = v;
};
})()

In this case, the function that contains everything is a self-invoking anonymous function. It defines setValue() and getValue() as global functions, while the secret variable remains local and inaccessible directly.
>>> getValue()
0
>>> setValue(123)
>>> getValue()
123

Recursion in F#

To use recursion in F#, we use the rec keyword after the let keyword to make the identifier available within the function definition. The following example shows recursion in action. Notice how on the fifth line the function makes two calls to itself as part of its own definition.


#light
let rec fib x =
match x with
| 1 -> 1
| 2 -> 1
| x -> fib (x - 1) + fib (x - 2)
printfn "(fib 2) = %i" (fib 2)
printfn "(fib 6) = %i" (fib 6)
printfn "(fib 11) = %i" (fib 11)


output:

The results of this example, when compiled and executed, are as follows:
(fib 2) = 1
(fib 6) = 8
(fib 11) = 89



This function calculates the nth term in the Fibonacci sequence. The Fibonacci sequenceis generated by adding the previous two numbers in the sequence, and it progresses as follows:
1, 1, 2, 3, 5, 8, 13, …. Recursion is most appropriate for calculating the Fibonacci sequence, because the definition of any number in the sequence, other than the first two, depends on being able to calculate the previous two numbers, so the Fibonacci sequence is defined in terms of itself.

Although recursion is a powerful tool, we should always be careful when using it. It is easy to inadvertently write a recursive function that never terminates. Although intentionally writing a program that does not terminate is sometimes useful, it is rarely the goal when trying to perform calculations. To ensure that recursive functions terminate, it is often useful to think of recursion in terms of a base case and the recursive case. The recursive case is the value for which the function is defined in terms of itself; for the function fib, this is any value other than 1 and 2. The base case is the nonrecursive case; that is, there must be some value where the function is not defined in terms of itself. In the fib function, 1 and 2 are the base cases. Having a base case is not enough in itself to ensure termination. The recursive case must tend toward the base case. In the fib example, if x is greater than or equal to 3, then the recursive case will tend toward the base case because x will always become smaller and at some point reach 2. However, if x is less than 1, then x will grow continually more negative, and the function will recurse until the limits of the machine are reached, resulting in a stack overflow error(System.StackOverflowException).

Monday, March 29, 2010

Caveat!!! WPF Memory Leak

I was using this class (PngBitmapEncoder) of the WPF framework in order to make thumbnail of something but while evaluating the performance then the .NET memory profiler revealed that this class has potentially dangerous memory leak problem.

Friday, March 13, 2009

Traverse a tree Using SQL/ MLM Commissioning


Here is the simplified data table consisting of a id for the table itself, memberId, generated commission, ParentId, BranchId for the member, BranchId for the parent.

Few days ago, one of my friends had been asked about one impediment to me that he had gone through. He had rung several times to my cell and frantically searching me to do the job on behalf of him. Though I was busy with my stuffs, I didn’t make him disappoint. He somehow related with MLM concept (multilevel marketing) and wanted to generate the commission for all the members belongs to the company. The structure of participating members is almost like a binary tree. The company has several branches inside the country and collects data at the end of the day to a central database from many remote repositories. The hard part of the solution was that a parent can be from different branch for a child. However, I came up with a specific data table from merging many data table and found the solution in one SQL. The commission will have to be calculated based on the rule that is each parent will get 1 point for his all subordinate children.

alter proc mlmIncCom
@MemberId int,
@BranchId int

as

Declare @_MemberId int
Declare @_ParentId int
Declare @_BranchId int
Declare @_pBranchId int
Declare @_Comission decimal

if exists(select ParentId from test_Recursion where MemberId=@MemberId and BranchId=@BranchId)
begin
select @_ParentId=ParentId,@_pBranchId=pBranchId from test_Recursion where MemberId=@MemberId and BranchId=@BranchId
print Convert(varchar(10),@_ParentId)+ ': '+Convert(varchar(10),@_pBranchId)
select @_Comission=Commission from test_Recursion where MemberId=@_ParentId and BranchId=@_pBranchId
update test_Recursion set Commission=@_Comission+1 from test_Recursion where MemberId=@_ParentId and BranchId=@_pBranchId
print Convert(varchar(10),@_ParentId)+ ': '+Convert(varchar(10),@_Comission)

exec mlmIncCom @_ParentId,@_pBranchId
end


-- exec mlmIncCom 3,2


alter proc mlmTest
as

Declare @_MemberId int
Declare @_BranchId int

Declare Rec_Cursor cursor for select MemberId, BranchId from test_Recursion
Open Rec_Cursor
Fetch next from Rec_Cursor into @_MemberId, @_BranchId

while @@FETCH_STATUS = 0
begin
exec mlmIncCom @_MemberId,@_BranchId
Fetch next from Rec_Cursor into @_MemberId, @_BranchId
end
close Rec_Cursor
deallocate Rec_Cursor

-- exec mlmTest 1,1