tag:blogger.com,1999:blog-45326793833280348562024-03-08T14:13:07.656-08:00Ahasan HabibAhasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.comBlogger29125tag:blogger.com,1999:blog-4532679383328034856.post-49531330350176549902011-01-13T18:58:00.000-08:002011-01-13T19:22:22.749-08:00MaxLength Property set to HTML TextArea controlOften we need to set maxlength property to textarea. But problem is, it is not working in textarea. It works fine to TextBox. Then how to solve this similar to textbox control.<br /><br />Code example are given bellow<br /><br /> var control = $("[id$='txtPairTitle']");<br /> $(document).ready(function() {<br /> $(control).keypress(function(event) {<br /> var e = event || window.event;<br /> var keyCode = e.which || e.keyCode;<br /> //46 delete; 8 backspace; 37 left arrow, 39 right arrow; 39 top; 40 bottom <br /> if (keyCode == 46 || keyCode == 8 || keyCode == 37 || keyCode == 39 || keyCode == 38 || keyCode == 40)<br /> return true;<br /><br /> var isExit = isExitMaxLength(140);<br /> if (isExit) {<br /> event.returnValue = false;<br /> }<br /> return !isExit;<br /> });<br /> });<br /><br /> function isExitMaxLength(maxLength) {<br /> var length = control.val().length;<br /> return length > maxLength;<br /> }<br /><br /> function maxLengthPaste(maxChars) {<br /> window.setTimeout(function() {<br /> if (window.event)<br /> window.event.returnValue = false;<br /> data = control.val();<br /> if ((data.length > maxChars)) {<br /> control.val('');<br /> alert("more than " + maxChars + " chars");<br /> return false;<br /> }<br /> if (window.event)<br /> window.event.returnValue = true;<br /> }, 10);<br /> }<br /><br />Note: OnPaste event not work in safari. So you can search some jquery plugin to handle that issue.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-9636897710393951432010-04-07T03:53:00.000-07:002010-04-07T05:02:21.513-07:00Load Asp.net User Control dynamically using ajax enabled wcfMany times we need to write user control. Why? Some reasons are UI decomposition for better managability, UI reuse for many pages etc. Now we need to load that user control. In static way we refer that controls in our markup and another dynamically load that controls using postback.<br /><br />In ajax based web application hate postback. So we need to load that usercontrol without postback and when user wants. The problem is that there is no simple way you can do it.<br /><br />However we can do one thing for solve the problem. In application's main page load time we can render all user control and then show and hide using javascript. <br /><br />But in that solution some problem are there. If many user control is written then page will be very heavy and first load time will be very slow. User memory will be consumed more. Clients PC need to be powerful and may be others.<br /><br />So we need to go ondemand load user control and when no need then remove it. But how?<br /><br />I do it using Ajax enable wcf service. I wrote a method which is responsible for accept user control name and produce that user controls output html and sent to the client as json message format.<br /><br />The service code like the following<br /><br /><br /> [OperationContract]<br /> [WebInvoke(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]<br /> public String GetUserControl(String controlName)<br /> {<br /> var page = new Page();<br /> //usercontrol path<br /> String controlPath = String.Concat(@"~\UC\" , controlName);<br /> //load usercontrol in memory<br /> UserControl control = (UserControl) page.LoadControl(controlPath);<br /> //create html form<br /> var form = new HtmlForm();<br /> //add control to form<br /> form.Controls.Add(control);<br /> //add form to page<br /> page.Controls.Add(form);<br /><br /> //create textwriter for accept html<br /> var sw = new StringWriter();<br /> HttpContext.Current.Server.Execute(page, sw, false);<br /><br /> //receive desired html<br /> var data = sw.GetStringBuilder().ToString();<br /> //return to the client<br /> return data;<br /> }<br /><br /><br />Now the client code. which is called the service. Here I use JQuery library for ajax communication. You may be use other library too.<br /><br />function loadUserControl() { <br /> jQuery.ajax({<br /> url: "ControlLoader.svc/GetUserControl", //name of the service and service method<br /> type: "POST",<br /> data: '{"controlName":"SignUp.ascx"}', //parameter data as json string format<br /> contentType: 'application/json; charset=utf-8',<br /> success: function(data) { //success callback. where usercontrol html will be received<br /> var obj = self.eval('(' + data + ')'); //create json object from string using eval functin. You may use other jsonconverters. <br /> jQuery("#divSignUp").html(obj.d); //add this html to a specific div.<br /> },<br /> error: function(error) { //error<br /> self.alert('Error for loading user control');<br /> }<br /> });<br /> }<br /><br /> //Remove Loaded user control using javascript. No need to call any server side code.<div> function removeUserControl() {<br /> jQuery("#divSignUp").html('');<br /> }<br /><br /><br />Lastly you need to create a aspx page with 2 buttons and call those 2 javascript functions loadUserControl() and removeUserControl(). Then you can see the output.<br /><br /><br />Thanks for reading.</div>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com4tag:blogger.com,1999:blog-4532679383328034856.post-8535782184087053252010-03-25T01:49:00.001-07:002010-03-25T02:38:12.091-07:00Javascript namespace implementationTodays web applications day by day implement ajax behaviour havily. <br />To implement that behaviour you need to write lots of javascript code.<br />Sometimes it becomes so talf to manage that javasript code.<br />In that situation we need to organize our code cleverly. <br /><br />Then question raise how traditional oop language organize their code. <br />Well actually they create classes/structures/enumes/interfaces and that are grouped by namespace/package and it is alreay proven solution for code organization.<br /><br />So why we donot follow oop languages style.<br />Well javascript does not support directly to declare namespace/package.<br />But we need to use namespace/package in javascript.<br />We need to follow same tricks like traditional oop. <br /><br />In javascript everying is object(function, array etc) and no direct support of inheritance(means normally traditional oop language support.<br /><br />So we will create objects to support namespace.<br /><br />The code example is given bellow<br />================================<br />//first create a Manager, it will responsible to register namespaces.<br />var NamespaceManager = function(){<br /><br /> this.Register = function(name){ <br /> var parent = self; //set window reference<br /> var arr = name.split('.');//consider user may use . relational operator <br /><br /> for(var index in arr){ <br /> var name = arr[index]; //retrive namespace name<br /> parent[name] = new Object(); //create object. <br /> parent = parent[name]; //reset parent object reference<br /> }<br /> } <br />}<br /><br />//Actually NamespaceManager object's Register method will register our requested //namespace. under the hood it will create object(s).<br /><br />//ok first we register our own namespace<br /><br />var manager = new NamespaceManager();<br />obj.Register ('Root.Data.Xml'); //dummy namespace<br /><br />//registration completed<br />//Now need to implemenet an object under that namespace.<br /><br />Root.Data.Xml.Country = function(countryName){<br /> this.CountryName = countryName,<br /> this.Show = function(){ <br /> self.alert(this.CountryName);<br /> }<br />};<br /><br />//Object Country with 2 members is created. 1 property CountryName and 1 method Show //is inside that class.<br /><br /><br />//Now Need to call use that Country object under Root.Data.Xml namespace<br /><br />var obj = new Root.Data.Xml.Show('Bangladesh');<br />obj.Show();<br /><br />//and see it will show alert with 'Bangladesh'.<br /><br />That way we can easily use namespace in javascript. But when we use javasript namespace we need to cosider some disadvantages<br /><br />1. Complexity may little increase your code.<br />2. Performace may little decrease.<br /><br />You obviouly consider some advantages too<br /><br />1. Structured Code.<br />2. Unique classes<br />3. Easy integration with other projects.<br /><br />So decission is yours based on your project context and other factors.<br /><br />======<br />Thanks<br />======Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-34057607232412213822009-05-30T09:10:00.000-07:002009-05-30T11:17:54.925-07:00Feeling of a new fatherIt was 27th may 2009. My daughter came to the world after many days staying in her mothers body. Normal delivery date was 09th june 2009. Due to some pregnancy decease specially blood high pressure, doctor's strongly recommend to do a cezer operation. We followed doctors recommendation and admitted my wife for that.<br /><br /><br />It was around 7-30 to 8-00 PM. My wife was entered to the operation theater(OT). I was affraid of that time. Praying to almighty allah for a successful operation. Finally my prayer was accepted by allah.<br /><br /><br />My daughter came from OT with the help of her anty. (Her anty, my younger sister is a doctor was in ot at that moment.)<br /><br /><br />My relatives were in Cabin. They saw the little baby and looks happy. Finaly the baby was in my hand. I was so surprised, that moment my brain was hang for little time. I did not think anything. Just looking the baby and interestingly my baby was looking to me. That moment I felt so pleasure and feel I am the happiest person of the world.<br /><br /><br />I don't know the others how they felt when they became papa. I share this of all my friends.<br />After finish my essay about my feelings I read and think i did not express anything about my feelings. But believe me I tried my best for drawing a picture about my feelings. Surly I know I failed. Sorry for my failure.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com9tag:blogger.com,1999:blog-4532679383328034856.post-80347639180025118092009-04-29T22:36:00.000-07:002009-04-29T22:40:57.619-07:00Custom Json Serializer for Entity FrameworkTo day my fist article has been published at codeproject.com.<br /><br />Article links<br /><br /><a href="http://www.codeproject.com/KB/aspnet/Custom_Json_Serializer.aspx"> Cusom Json Serializer for Entity Framework </a>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com2tag:blogger.com,1999:blog-4532679383328034856.post-35235949347609862622009-03-01T22:34:00.000-08:002009-03-02T05:59:53.631-08:00Object Oriented Software Design Principle<div style="text-align: justify;">A degree of importance that grants a design decision may called Prinipal. When we will design any software based on OO that time we should follow some principals.<br /></div><br />If we follow that principal then we will get some benifits. Ex<br /><br />1. Software will be scalable.<br /><br />2. Easily extendable.<br /><br />3. Maintance phase will be very simple.<br /><br />4. Programming code is easily readable.<br /><br />5. Easy production code changable.<br /><br />6. Easily backword compatable.<br /><br />7. Easily re-usable.<br /><br />and many more.<br /><br />Principals are separated by Class Desing Principal and Package Design Principal<br /><br /><span style="font-weight: bold;">Class Design Principles are:</span><br /><br />1. Single Responsibility Principal (SRP) :<br />================================<br /><div style="text-align: justify;">A class should have only one responsibility. The difination of responsibility is "a reason for change". If any class has more then one responsibility then threre will be more coupled. Change of one responsibility may impact others.<br /></div><br /><br />2. Open Close Principle(OCP):<br />==========================<br /><div style="text-align: justify;">Able to extend class behavior without modifing existing begaviour. That means we should desing class or component that shold never change. If requirement change then we extend the behaviour of such component/class by adding new code, not the tested old code.<br /></div><br />3. Liskov Substitution Principle(LSP):<br />==============================<br /><div style="text-align: justify;">Also known as "Design by Contract". Derived class must be substitutable for their base classes. Means derived class must be usable through the base class interface without the need for the user to know the difference.<br /></div><br /><br />4. Dependency Inversion Principle(DIP):<br />==================================<br /><div style="text-align: justify;">Depends on abstraction not concretion. Another way we can express like Details should depend upon abstraction, Abstraction should not depends on Details. Main befinit of it is, it creates decoupling between classes. For that reason if we change detail class it should not affect existing class that are using that detail class. Currently many framework/pattern created for dependency inject. Microsoft Uniti Application block, ObjectBuilder etc are examples. Microsoft Composit Application Block (Smart Client Software Factory/ Web Client Software factory/Web service software factory) is havily depends on that principal.<br /></div><br /><br />5. Interface Segregation Principle(ISP):<br />================================<br /><div style="text-align: justify;">Create Interface that are client specific. Client should not be forced to depends upon interfaces that they dont use. The interface which contain extra methods which are not related to all clients is called fat interface. It is preferable to remove fat interface and create many small interfaces based on groups of methods.<br /></div><br /><br /><span style="font-weight: bold;">Package Design Principles are:</span><br /><br />1. Release re-use Equivalency Principle(REP) :<br />=====================================<br /><div style="text-align: justify;">A reusable element can be class, component cannot be reused unless it is managed by a released system. One criteria for grouping classes into packages is reuse, Packages are unit of release, also unit of reuse. So we should group reusable classes into packages and deploy to the clients. This package should be under any version no. Clients are fully independent and has full knowledge to use or used package version.<br /></div><br />2. Common Closure Principle(CCP):<br />===============================<br /><div style="text-align: justify;">Classes that are change together are packaged together. If two classes are tightly bound(phisically/conceptually), they almost change together, then they belongs to the same package. It minimize the workload to releasing, revalidating, redistributing software and impact minimum from release to release.<br /></div><br /><br />3. Common Reuse Principle(CRP):<br />===============================<br /><div style="text-align: justify;">Classes that are not reused together should not be group together. Depency of a package is dependency of everything within that package. When package changed, new release no will be assigned and client musht varify they work with new package even if nothing they use within a package that changed.<br /></div><br />4. Acyclic Dependency Principle(ADP):<br />================================<br /><div style="text-align: justify;">Dependency between package must not form of cycles. If found any cycle then it will be breked. For breking cycle We can use Dependency Inversion Principle.<br /></div><br /><br />5. Stable Dependency Principle(SDP):<br />=================================<br /><div style="text-align: justify;">Depend in the direction of stability. Means package should stable on that package that are more stable that it is. All packages are not stable of any software. If so then the software is difficult to change. So comparatively less stable package should depends on more stable package.<br /></div><br /><br />6. Stable Abstraction Principle(SAP):<br />===============================<br /><div style="text-align: justify;">Stable package may be abstract. Instable package should be concrete. Means its stability does not prevent it from being extended and instability allows the concreate code within it to be easily changed.<br /><br /><br /></div>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com1tag:blogger.com,1999:blog-4532679383328034856.post-41959810407154210472009-02-24T06:09:00.000-08:002009-02-24T06:49:15.671-08:00Callback FunctionMany times we need to implement callback function. So I am wrting about that.<br />There are 3 ways we can allow to provide callback functionality.<br /><br /><br />1. Events<br /><br />2. Delegates<br /><br />3. Interface<br /><br /><br /><br />1. Events:<br />=========<br /><br />Most often we use that callback to gue based application. Standard Windows control fire events. We set handler against particular event and write our own logic in that event handler. We can use event based callback in our business class also.<br /><br />Ex.<br /><br />public class MyForm: Form<br />{<br /> private Button btnExecute = new Button(); //Standard Windows Button Control<br /> Public MyForm()<br /> {<br /> InitializeComponet();<br /> btnExecute.Click += new EventHandler(OnButtonClick);<br /> }<br /><br /> //Event Handler/CallBack Function<br /> private void OnButtonClick(object sender, EventArgs e)<br /> {<br /> MessageBox.Show("Good Morning");<br /> }<br />}<br /><br /><br />Event based callback function usage guideline:<br /><br />1. When we need to implement method registration/un-registration.<br /><br />2. More then one object will want notification of the event.<br /><br />3. Add listen with the help of Visual Designer. Ex GUI based control event.<br /><br /><br /><br />2. Delegates<br />===========<br /><br />Delegates are nothing but similar to function pointer in C. Many times we can use delegate for callback function. There are 2 types of delegates are single cast and another is multicast.<br /><br />Delegate callback example<br /><br /><br />public delegate void MyDel;<br /><br />public class Bangladesh<br />{<br /> public void GetPM(MyDel d)<br /> {<br /> d.Invoke("Sheck Hasina");<br /> }<br />}<br /><br />public class MyForm : Form<br />{<br /> void OnButtonClick(object sender, EventArgs e)<br /> {<br /> Bangladesh b = new Bangladesh();<br /> MyDel myD = new MyDel(ShowPM);<br /><br /> b.GetPM(myD); //Passing delegate<br /> }<br /><br /> //CallBack Method<br /> void ShowPM(string pm)<br /> {<br /> MessageBox.Show(pm);<br /> }<br />}<br /><br />GuideLine of Using Delegate Callback:<br /><br />1. Want to use C style function pointer.<br /><br />2. Want to use single callback function.<br /><br />3. Want registration occur at a constraction time.<br /><br />4. Notification requirement is to havy with many arguments.<br /><br /><br />3. Interface:<br />===========<br /><br />Message based commpunication technology ex. WCF duplex communication (Chat software) is not possible without Interface based callback.<br /><br />Ex:<br /><br />public interface IPMName<br />{<br /> void GetPMName(string pm);<br />}<br /><br />public class Bangladesh<br />{ <br /> public void P1(IPMName p)<br /> { <br /> p.GetPMName("Sheck Hasina"); <br /> } <br />}<br /><br /><br />public class India<br />{<br /> public void P1(IPMName p)<br /> {<br /> p.GetPMName("Monmohan Sing"); <br /> } <br />}<br /><br />public class MyForm : Form, IPMName<br />{<br /> //Callback method<br /> public void GetPMName(string pm)<br /> {<br /> MessageBox.Show(pm);<br /> } <br /><br /> void OnButtonClick(object sender, EventArgs e)<br /> {<br /> Bangladesh b = new Bangladesh();<br /> b.P1(this);<br /><br /> India i = new India();<br /> i.P1(this);<br /> }<br />}<br /><br />Interface based Callback Guideline<br /><br />1. Use Message based communication application.<br /><br />2. Anyother complex callback senario.<br /><br /><br /><br /><br />Reference:<br />C#/VB .NET Coding GuideLines by Steave SartainAhasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com1tag:blogger.com,1999:blog-4532679383328034856.post-1079784514660214472009-01-18T02:38:00.000-08:002009-01-31T04:27:41.634-08:00Check User Authentication ProgrammaticallyIntroduction<br />=========<br /><br />Many often it is required to check user authentication programmatically. Suppose you want to create a UI for taking user input of User ID and Password. Based on that UserID and password, Your windows service will run. So when user input userid and password then you must authenticate before store that information.<br /><br /><br />Solution<br />======<br /><br />So far no direct Donet framework(upto 3.5 sp1) component available for check user authentication programmatically. So you need to take help from windows api for that service.<br /><br />The following code can capable to authenticate both local or domain account.<br /><br />How Windows API help you<br />====================<br /><br />In "advapi32.dll" contain a function name "LogonUser". That function will help you to authenticate user programmatically.<br /><br />To use that function you need to declare 2 enumaration named "LogonSessionType" and "LogonProvider"<br /><br /><br />Code Example is given bellow<br />=====================<br /><br />class Program<br />{<br /> static void Main(string[] args)<br /> {<br /> IntPtr token = new IntPtr();<br /><br />//First Parameter is User Name, second: domain/machine name, third password<br /> bool result = AuthenticationManager.LogonUser("Administrator", "bd.com.bd", "abcd", AuthenticationManager.LogonSessionType.Network, AuthenticationManager.LogonProvider.Default, out token);<br /><br /><br /> if (result)<br /> {<br /> Console.WriteLine("User ID and Password is correct");<br /> }<br /> else<br /> {<br /> Console.WriteLine("Not real user");<br /> }<br /><br />}<br /><br /><br />/// <summary><br />/// Authentication Programmatically<br />/// </summary><br />class AuthenticationManager<br />{<br /> [DllImport("advapi32.dll", SetLastError=true)]<br /> public static extern bool LogonUser(string principal, string authority, string password, LogonSessionType logonType, LogonProvider logonProvider, out IntPtr token);<br /><br /> public enum LogonSessionType : uint<br /> {<br /> Interactive = 2, Network, Batch, Service, NetworkClearText = 8, NewCredencials<br /> }<br /><br /><br /> public enum LogonProvider : uint<br /> {<br /> Default = 0, WinNT35, WinNT40, WinNT50<br /> }<br /><br />}<br /><br /><br />Note: Microsoft Pattern an Practices have a nice artical related to that. The heading of that artical is<br /><br /> "How To Use Impersonation and Delegation in ASP.NET 2.0"<br /><br />If you read that then i think many others problem you can solve realted to that issue.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-16812894509334025672008-12-11T02:15:00.000-08:002008-12-11T02:44:53.837-08:00Interfacing with ATM<strong>Problem</strong><br />=======<br /><br />Most of the Banking System have ATM Booth for limited banking service. Services are like money withdraw, balance query, mini statement, fund-transfer etc. Banking Software should interfacing with that ATM system.<br /><br /><br /><br /><strong>Description</strong><br />==========<br /><br />I have got an oppertunity to work with Banking Solution and my modulte was ATM interfacing. To fullfill that requirement I learn many things. I want to share it.<br />ATM devices that I worked used ISO 8583 message protocol for communication. So I need to understand first what the protocol, how look like the message pattern is!<br />Total Message was 128 bytes hexadecimal value. First 4 bit used for Message Type Identification. next 64 bit for bit pattern, and next was the actual message.<br />If you need to detail then go to online and collect specification.<br /><br /><br /><br /><strong>Solution</strong><br />=======<br /><br />I wrote a windows service for interct with atm host. There I use tcp socket. Actually it was a host to host communication service. One side is ATM boot's host another side in Bank is my service. ATM Host side is called Acquire and My service is called Issuer.<br /><br />Suppose One person want to withdraw money from ATM booth. First he/she punch the card and pin number. ATM Host authenticate it then request to my service for update db. My service execute query to banking db for confirmation that the account has sufficiant balance for fullfill that request. If yes then send success signal to atm host otherwise send specific error code like not sufficient balance, account closed or something else.<br /><br />When day-end process(well-known process in banking system) will run that time atm transaction will temporary store in difference place and after finish that process it will marge to main db.<br /><br /><br /><br /><strong>Some Important Issues raised when working on that</strong><br /><br />1) After Day-end how ATM transaction will effect in profit calculation.<br /><br />2) How transaction will be handled.<br /><br />3) How reversal process will be executed.<br /><br />4) How exception will be handled.<br /><br />5) How load testing will be done.<br /><br />and many more...........Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com5tag:blogger.com,1999:blog-4532679383328034856.post-54495312245882123842008-09-11T01:06:00.000-07:002008-09-11T01:25:01.468-07:00UI element access from chield thread<div>Problem:</div><div>======</div><div><br /></div><div>Accesseing UI element from Chield Thread.</div><div><br /></div><div>Detail:</div><div>====</div><div><br /></div>In windows application, many times it is required to access/manipulated ui threads control property from chield thread. <div><br /><div>Basically UI thread block its control. So if you normally try to access control property from different thread then exception will raise. So you need to do work-around.</div><div><br /></div><div>Solution:</div><div>=======</div><div><br /></div><div>Indivisual Invokation is required to solve the problem. Every ui control has a boolean property name InvokeRequired and a method invoke(delegate). You first need to check its invokation is required or not. If yes then call invoke() with a delegate.</div><div><br /></div><div><br /></div><div>Code Objective:</div><div>===========</div><div><br /></div><div>I just want to change a button caption from a chield thread.</div><div><br /></div><div>Code Sample:</div><div>=========</div><div><div><br /></div><div>namespace WindowsFormsApplication1</div><div>{</div><div><br /></div><div> public partial class Form1 : Form</div><div> {</div><div><span class="Apple-tab-span" style="white-space:pre"> </span>//declare a delegate<br /></div><div> public delegate void SetData();</div><div><br /></div><div> public Form1()</div><div> {</div><div> InitializeComponent();</div><div> }</div><div><br /></div><div> private void button1_Click(object sender, EventArgs e)</div><div> { </div><div><span class="Apple-tab-span" style="white-space:pre"> </span> //Create a chield thread.<span class="Apple-tab-span" style="white-space:pre"> </span><br /></div><div> Thread t = new Thread(</div><div><span class="Apple-tab-span" style="white-space:pre"> </span>new ThreadStart(SetCaptionToButton));</div><div><br /></div><div><span class="Apple-tab-span" style="white-space:pre"> </span> //Run the thread.<br /></div><div> t.Start(); </div><div> }</div><div><br /></div><div> private void SetCaptionToButton()</div><div> { </div><div><span class="Apple-tab-span" style="white-space:pre"> </span> //Create a delegate<br /></div><div> Delegate del = Delegate.CreateDelegate(typeof(SetData), </div><div><span class="Apple-tab-span" style="white-space:pre"> </span>this, "SetCaptionToButton");</div><div><br /></div><div><br /></div><div> if (button1.InvokeRequired)</div><div> {</div><div> //Either 1 or 2 the following statement you can use.</div><div> button1.Invoke(del); //1</div><div> </div><div> button1.Invoke(new MethodInvoker</div><div><span class="Apple-tab-span" style="white-space:pre"> </span> (SetCaptionToButton)); //2</div><div> }</div><div><br /></div><div> button1.Text = "Click ME!"; </div><div> }</div><div> }</div><div>}</div></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div></div>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com58tag:blogger.com,1999:blog-4532679383328034856.post-4753302585233306912008-08-26T23:09:00.000-07:002008-08-26T23:39:09.764-07:00Distributed Transaction using .NETAny distributed application has a common requirement to use distributed transaction. So .NET provide facility to full-fill the requirement.<br /><br />TransactionScope class (namespace System.Transactions) has accomplish that task.<br /><br />In previously I knew that without "Distributed Transaction Coordinator" service run, distributed transaction is not possible. But if you stop that service, TransactionScope class work fine. So now that service dependency has removed. The followling i show code sample<br /><br />namespace TestConsole<br />{<br /><br /> class Program<br /> { <br /> static void Main(string[] args)<br /> {<br /> TransactionController _controoler = new TransactionController();<br /> _controoler.TestDistributedTransaction(); <br /> }<br /><br /> }//end of program<br /><br /><br /> class TransactionController<br /> {<br /><br /> string cnnStringDB = @"Data Source=db; Database=Test_Habib; uid=sa; pwd=1;";<br /><br /> string cnnStringZahid = @"Data Source=Zahid\SqlExpress; Initial Catalog=MwMD; trusted_connection=true;";<br /><br /> string sql = "INSERT INTO Test_Transaction(ID, Name) VALUES (4, 'Bona');";<br /><br /> <br /> public void TestDistributedTransaction()<br /> { <br /> SqlCommand cmd = new SqlCommand(sql);<br /><br /> int result = -1;<br /> <br /> using (System.Transactions.TransactionScope sc = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required))<br /> {<br /><br /> try<br /> {<br /> SqlConnection con1 = new SqlConnection(cnnStringZahid);<br /> con1.Open();<br /> SqlCommand cmd1 = new SqlCommand(sql, con1);<br /> result = cmd1.ExecuteNonQuery(); <br /> con1.Close(); <br /><br /> using (System.Transactions.TransactionScope sc2 = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Suppress))<br /> {<br /> SqlConnection con2 = new SqlConnection(cnnStringDB);<br /> con2.Open(); <br /> SqlCommand cmd2 = new SqlCommand(sql, con2);<br /> result = cmd2.ExecuteNonQuery();<br /> } <br /> <br /> // RPC call to another appdomain using serialization.<br /> sc.Complete();<br /> }<br /> catch (Exception ex)<br /> { <br /> sc.Dispose();<br /> }<br /> } <br /> } <br /><br /> }//end class <br /><br />}//end namespace<br /><br />In above sample System.Transactions.TransactionScopeOption enum is important.<br />It has 3 values<br /><br />i) Required<br />ii)RequiredNew<br />iii)Suppress<br /><br />In the second block i use System.Transactions.TransactionScopeOption.Suppress. Otherwise it will through exception. TransactionScope.Complete() method commit all transaction. If not call this method explicitly then all transaction will be rollbacked automatically.<br /><br /><br />The following code sample you can use for multi-threaded distributed transaction handling.<br /><br /><pre> private static void WorkerThread(object transaction)<br /> {<br /> DependentTransaction dTx = (DependentTransaction)transaction;<br /> <br /> using (TransactionScope ts = new TransactionScope(dTx))<br /> {<br /> //Perform transactional work here. <br /> //Call complete on the transaction scope<br /> ts.Complete();<br /> }<br /> <br /> //Call complete on the dependent transaction<br /> dTx.Complete();<br /> }<br /></pre><br />Thanks.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com1tag:blogger.com,1999:blog-4532679383328034856.post-82304993530743652982008-07-04T10:04:00.000-07:002008-07-04T10:58:29.123-07:00Test Driven Development - The BasicWhat is Test Driven Development ?<br />========================<br /><br />An advance technique to develop software using automated unit tests to drive the design of the software and force decoupling of dependencies.<br /><br />What is the Origin of Test Driven Development ?<br />=================================<br /><br />Test Driven development is a core part of the agile process formalized by Kent Beck called extrime Programming (XP). The rule of XP was to test everything that could possible break. The practice of testing in XP has evolved into Test Driven Development.<br /><br />Is it Necessary to adopt XP to practice Test Driven Development ?<br />=============================================<br /><br />The answer is no.<br /><br />What is the Characteristics of Test Driven Development ?<br />======================================<br /><br />* Maintain an exhaustive suite of Programmers Test.<br />* No code goes into production unless it has associated tests.<br />* Write the tests first.<br />* Test determine what code you need to write.<br /><br />What is the Life Cycle of Test Driven Development ?<br />==================================<br /><br />Step 1: Write Test<br />Step 2: Compile<br />Step 3: Run and see fail<br />Step 4: Refector as needed<br />Step 5: Go to Step 1<br /><br />What are the benefits of Test Driven Development ?<br />==================================<br /><br />* Better Code.<br />* Very few bugs.<br />* Meet requirement.<br />* Remove duplication.<br />* Less debug time.<br />* Tests become an Asset.<br />* Tests are documentation.<br />* De-couple.<br /><br />What can be Tested ?<br />=============<br /><br />* Valid Input.<br />* In-valid Input.<br />* Exceptions.<br />* Boundary Conditions.<br />* Everything that should be possible break.<br /><br />What are the characteristics of Testing framework ?<br />==================================<br /><br />* Test must be automated.<br />* A simple tool collect, oraganizes and automatically call test code.<br />* Graphical Test runner.<br />* Could be added to build environment.<br /><br />Give some example of popular Testing framework ?<br />==================================<br /><br />* NUnit - Dot Net<br />* JUnit - Java<br />* VBUnit - Visual Basic<br />* CppUnit - C++<br />* JSUnit - JavascriptAhasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-58576421370844595722008-06-17T22:48:00.000-07:002008-06-17T23:14:32.518-07:00Encode-DeCode required for data transfer in HTTP protocolMany times Encode and Decode of data is required in web application. The name of the problem may call URL Encoding problem.<br /><br />Situation:<br />=======<br /><br />Suppose I want to select a file from client pc for upload to server. This file contains some special charecter like +, @, %, & etc. Then Http automatically change that charecter, because http understand some special meaning of that charecters. So when I receive that file from server, files actual name is changed. So this is the main problem.<br /><br />How to Solve:<br />==========<br /><br />You need to encode those files name from javascript and send it to server. Server automatically decode those. If you send data from server then you need to decode those from client(javascript). Bellow I write javascript methods for Encode, Decode special data. We can use those method to solve those problem.<br /><br />NB.<br />==<br />You may thought javasript escape(), deescape() function solve that. Javascript has escape(), deescape() function for encode decode those. But you need to some extra work on those methods, make your code wrox-solid.<br /><br />You may thought using ajax you transport those data as post request and fixed those. But post request can't solve that.<br /><br /><br />Javascript Encode Method<br />--------------------------<br /><br />function encode(str)<br />{<br />str = escape(str);<br /><br />str = str.replace('+', '%2B');<br /><br />str = str.replace('%20', '+');<br /><br />str = str.replace('*', '%2A');<br /><br />str = str.replace('/', '%2F');<br /><br />str = str.replace('@', '%40');<br /><br />return str;<br />}<br /><br /><br />Javascript Decode Method<br />--------------------------<br /><br />function decode(str)<br />{<br /><br />str = str.replace('+', ' ');<br /><br />str = unescape(str);<br /><br />return str;<br />}Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-83481374602351490992008-05-01T09:39:00.000-07:002008-05-01T09:45:04.430-07:00Factory Pattern - The Basic<strong>Factory Pattern is a Creational Pattern. If you want to create a database independent application then you can use Factory Pattern. My Previous Post I publish Builder Pattern. Factory Pattern & Builder Pattern has sometime create confustion. In Factory an extra class is required which is responsible to create object base on parater. Client directly request the class to give a specific type of object. The code example is here.</strong><br /><br /><br /><br />namespace TestConsole<br />{<br />class Program<br />{<br />static void Main(string[] args)<br />{<br />string p = Console.ReadLine();<br />Creator obj = new Creator();<br />ICar car = obj.Factory(p);<br />Console.WriteLine(car.CreateCar());<br />Console.ReadKey();<br />}<br />}<br />class Creator<br />{<br /> public ICar Factory(string prm)<br /> {<br /> ICar car = null;<br /> if (prm.ToUpper() == "S")<br /> {<br /> car = new Suzuki();<br /> }<br /> else<br /> {<br /> car = new Marcidise();<br /> }<br /> return car;<br /> }<br /><br />}<br /><br />interface ICar<br />{<br /> string CreateCar();<br />}<br /><br />class Suzuki : ICar<br />{<br /> public string CreateCar()<br /> {<br /> return "Suzuki";<br /> }<br />}<br /><br />class Marcidise :ICar<br />{<br /> public string CreateCar()<br /> {<br /> return "Marcidise";<br /> }<br />}<br /><br />}Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-91501268150158723142008-05-01T08:49:00.000-07:002008-05-01T08:58:22.046-07:00Builder Pattern - The Basic with example<span style="font-weight:bold;"><span style="font-weight:bold;">Builder pattern is a creational Pattern. If you use Builder pattern then we can capable to make our application more extensible & loosely couple. In builder paatern 1 extrac class Director and 1 extra interface IBuilder is required. Client create Director object and create IBuilder type object conditionally and pass this object to Director object. Director object call Builder objects method for required operation. I show a code example. This is for very beginers who wants to learn builder desing pattern. Please see the code and write that code on your test project. Then you can easily understand.</span></span><br /><br />namespace TestConsole<br />{<br /><br /><br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> string carName = Console.ReadLine();<br /> Director direct = new Director();<br /> ICarBuilder car = null;<br /> if (carName.ToUpper() == "SUZUKI")<br /> { <br /> car = new Suzuki(); <br /> }<br /> else if (carName.ToUpper() == "MARCIDISE")<br /> {<br /> car = new Marcidise(); <br /> }<br /> direct.ConstructCar(car);<br /> Console.ReadKey();<br /> }<br /> }<br /><br /><br /> interface ICarBuilder<br /> {<br /> void CreateCar();<br /> }<br /> class Suzuki : ICarBuilder<br /> { <br /> public void CreateCar()<br /> {<br /> Console.WriteLine("Suzuki Card is Created. Thanks for Bye Suzuki.");<br /> } <br /> }<br /><br /> class Marcidise :ICarBuilder<br /> { <br /> public void CreateCar()<br /> {<br /> Console.WriteLine("Marcidesce car is created. You will becode proude for using Marcidise");<br /> } <br /> }<br /><br /><br /> class Director<br /> {<br /> public void ConstructCar(ICarBuilder builder)<br /> {<br /> builder.CreateCar();<br /> }<br /> }<br /><br /><br />}Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com1tag:blogger.com,1999:blog-4532679383328034856.post-51951047567141577552008-04-25T02:46:00.000-07:002008-04-25T02:51:44.003-07:00Data Encryption using SQL Server 2005Many times need to encript/decript data from my database. If I want to Encrypt/Decrypt my database using SQL Server2005<br /><br />I need to do some task.<br /><br />Step:1<br /> I have to enable database encryption.<br /><br /> Syntax: ALTER DATABASE <<db_name>> SET ENCRYPTION ON<br /><br />Step:2<br /> I have to create a master key using my own password<br /><br /> Syntax: CREATE MASTER KEY ENCRYPTION BY PASSWORD = <<my_password>><br /><br />Step:3<br /> I have to create a certificate<br /><br /> Syntax: CREATE CERTIFICATE <<certificate_name>> WITH SUBJECT = <<subject_name>><br /><br />Step: 4<br /> I have to create symmetric key<br /><br /> Syntax: CREATE SYMMETRIC KEY <<key_name>> WITH ALGORITHM = TRIPLE_DES ENCRYPTION BY CERTIFICATE <<certificate_name>><br /><br />Step: 5<br /> I have to Open symmetric key when required insert/update/select operation.<br /><br /> Syntax: OPEN SYMMETRIC KEY <<key_name>> DECRYPTION BY CERTIFICATE <<certificate_name>><br /><br />Step:6<br /> I have to use built in function for encrypt data.<br /><br /> Syntax: CREATE TABLE Test(Name varchar(50) not null);<br /> <br /> INSERT INTO test VALUES (EncryptByKey(Key_GUID('key_name'), 'habib1'));<br /><br /> SELECT CAST(DecryptByKey(name) AS varchar) FROM test;<br /><br />Step:7<br /> Close My open symmetric key<br /><br /> Syntax: CLOSE SYMMETRIC KEY <<my_key>>;<br /><br /><br />There are also many algorithms you can use for sqlserver dataencryption. I use only TRIPLE_DES.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com3tag:blogger.com,1999:blog-4532679383328034856.post-75999785211688734992008-04-16T00:19:00.000-07:002008-04-23T12:21:45.807-07:00Parent window refresh & Chield window close without confirmationMany Times it is required to close Refresh parent winsow then close Chield window without confirmation. It is very common senario. I know everybody knows it. But sometimes not remember. So i publish it.<br /><br /><script type="text/javascript"> <br /><br /> window.opener.location.href='Parent.aspx';<br /> window.open('','_parent',''); window.close(); <br /><br /></script"><br /><br />When you refresh your parent page, that time you loose all view state data. Many times client want to see controls showing data. If so then you need to write code to maintain data of control. Then you may create any class which can store pages last data to session and when required it retrive data from that also.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-58669772998050297502008-04-14T10:40:00.000-07:002008-04-14T10:43:30.294-07:00Retrive ProcessorID, HardDiskID, LANCardID, MotherboardID using c#<pre><tt><tt>Many times it is required to retrive processor, harddisk, lancard,<br />motherboard<br />identification for the purpose of Licenseing Issue.<br />So my code is helpful for you if you interested to manage license for<br />your application. You just receive clients webservers the above<br />information<br />first time, latter when User want's to lunch his/her appliation, then<br />you check it with the help of webserver which is hosted by you.<br /><br /></tt></tt><tt><tt>Requirement<br />==========<br />If you want to implement that model then you must host and live your<br />webserer. ohterwise clients app does not work. If you not like that then<br />you may change that model and implement any dirrerent technic for<br />license checking.<br /><br /><br /></tt></tt><tt><tt>The code is written by dotnet 2.0/3.0/3.5<br />===========================================<br /><br /></tt></tt><tt><tt>using System.Management;<br />using System.Management.Instrumentation;<br /><br />public string GetProcessorID()<br /> {<br /> string processorID = string.Empty;<br /> <br /> ManagementObjectSearcher searcher = new<br /> ManagementObjectSearcher("select * from Win32_Processor");<br /> <br /><br /> foreach (ManagementObject o in searcher.Get())<br /> { <br /> foreach (PropertyData prop in o.Properties)<br /> {<br /> if (prop.Name.Equals("ProcessorId"))<br /> {<br /> processorID = (String)prop.Value;<br /> break;<br /> }<br /> }<br /> }<br /> return processorID; <br /> }<br /><br /></tt></tt><tt><tt>public string GetDiskID()<br /> {<br /> string diskID = string.Empty; <br /><br /> ManagementObjectSearcher searcher = new<br /> ManagementObjectSearcher("select * from Win32_DiskDrive");<br /> <br /><br /> foreach (ManagementObject o in searcher.Get())<br /> { <br /> foreach (PropertyData prop in o.Properties)<br /> {<br /> if (prop.Name == "Caption")<br /> {<br /> diskID = (String)prop.Value;<br /> break;<br /> }<br /> }<br /> } <br /> return diskID;<br /> } <br /><br /><br /></tt></tt><tt><tt>public string GetMotherBoardSerialNumber()<br /> {<br /> string serialNumber = string.Empty;<br /><br /> ManagementObjectSearcher searcher = new<br /> ManagementObjectSearcher("select * from Win32_BaseBoard");<br /> <br /><br /> foreach (ManagementObject o in searcher.Get())<br /> { <br /> foreach (PropertyData prop in o.Properties)<br /> { <br /> if (prop.Name == "SerialNumber")<br /> return (String)prop.Value;<br /> }<br /> }<br /> return serialNumber;<br /> }<br /><br /><br /><br /></tt></tt><tt><tt> public string GetMacAddress()<br /> {<br /> string result = string.Empty;<br /><br /> foreach (NetworkInterface obj in<br /> NetworkInterface.GetAllNetworkInterfaces())<br /> {<br /> if (obj.NetworkInterfaceType !=<br />NetworkInterfaceType.Loopback)<br /> {<br /> result = obj.GetPhysicalAddress().ToString();<br /> break;<br /> } <br /> }<br /> return result;<br /> }<br /><br /><br /></tt></tt><tt><tt><br /></tt></tt></pre>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-22588825531070861982008-03-12T01:26:00.000-07:002008-03-12T01:30:24.965-07:00wmv file showing problem in SilverLightIn my project I need to replace flash to <span style="font-weight: bold;">silverlight</span>.<br /><br />I have a <span style="font-weight: bold;">wmv </span>file, currently which is working fine with <span style="font-weight: bold;">flash </span>player.<br /><br />But when I replace flash control to <span style="font-weight: bold;">silverlight </span>control then this file was not working.<br />I really surprised. I did not find any clue to solve that problem.<br /><br />After many times googling I was very much disappointed. But the other<br /><span style="font-weight: bold;">wmv </span>file was working file. So what I did so solve that problem.<br /><br />I just recreate that <span style="font-weight: bold;">wmv </span>file from <span style="font-weight: bold;">avi </span>file with the help of<br />windows media encoder and use that new <span style="font-weight: bold;">wmv </span>file to my silverlight media control.<br /><br />Then everything working fine. Nice experience.<br />So I share it all of you. Definitely in future It will safe your time.<br /><br /><br /><span style="font-weight: bold;">Good Bye Flash Welcome to Silverlight</span>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com2tag:blogger.com,1999:blog-4532679383328034856.post-30676107330585381962008-02-12T06:11:00.000-08:002008-02-12T06:55:23.565-08:00Find table(s) name and column(s) name by providing a value in SQLServer-2000 DatabaseMany times(specially bug fixing period) developer wants to search a specific value is present in database or the value is in which tables & which columns. If value found in database then easily understand the value is comming from database otherwise think it comes from application code or xml file.<br /><br />Most of the case data value comes from database. So developer first guess the value is in database. But it should be proved. otherwise bug cannot be solved.<br /><br /><br />I worte 2 stored procedure for searching data in database. Any one can call it form application and make a tools or directly execute it from database. the code examples are<br /><br /><br />1st SP<br />=====<br /><br />create proc dbo.GetColumnName<br />(<br />@tableName varchar(1000),<br />@value varchar(1000)<br />)<br />as<br /><br />SET NOCOUNT ON<br /><br />declare @colName varchar(1000),<br />@sql nvarchar(4000),<br />@counter int;<br /><br />set @sql = '';<br /><br />set @counter = 1;<br /><br />create table #Temp (sl int identity(1,1), [Name] varchar(1000));<br /><br />create table #TempNew ([Value] varchar(1000));<br /><br />create table #Result(name varchar(1000));<br /><br />set @sql = N'insert #temp ([Name]) select name from syscolumns<br />where id = object_id(''' + @tableName + ''')' + ' AND XType NOT IN(36,61,58,34,35,165,99) ORDER BY name ASC';<br /><br /><br />EXEC SP_EXECUTESQL @sql while(1=1) begin<br /><br />select @colName = [Name] from #temp where sl = @counter;<br /><br />if (@@rowcount = 0) break;<br /><br />--print @colName;<br /><br />set @sql = N'insert #TempNew([Value])<br />select ' + @colName + ' from ' + @tableName<br />+ ' where ' + 'CAST('+ @colName + ' AS VARCHAR(1000))=''' + @value + '''';<br /><br />EXEC sp_executesql @sql;<br /><br />IF (@@ROWCOUNT > 0) --print @colName;<br /><br />INSERT INTO #Result(name) VALUES(@colName);<br /><br />set @counter = @counter + 1;<br /><br />end<br />--print @counter; select all * from #Result;<br />go<br />--exec dbo.GetColumnName 'dbo.reader' , 3<br /><br /><br />2nd SP<br />=====<br /><br />CREATE PROCEDURE dbo.GetColumnNameFromDB<br />(<br />@Value VARCHAR(8000)<br />)<br />AS<br /><br />SET NOCOUNT ON<br />DECLARE @NewTable VARCHAR(1000)<br /><br />IF (OBJECT_ID('tempdb.dbo.##Result') IS NOT NULL)<br />DROP TABLE tempdb.dbo.##Result;<br /><br />CREATE TABLE tempdb.dbo.##Result(SL INT IDENTITY(1,1), TableName Varchar(1000), ColumnName varchar(1000))<br /><br />--DECLARE @Result TABLE(SL INT IDENTITY(1,1), TableName Varchar(1000), ColumnName varchar(1000)) DECLARE C1 CURSOR FOR SELECT table_name FROM information_schema.tables<br />WHERE table_type='BASE TABLE'<br /><br />OPEN C1<br /><br />FETCH NEXT FROM C1 INTO @NewTable;<br /><br />WHILE(@@FETCH_STATUS = 0) BEGIN<br /><br />INSERT ##Result(ColumnName)<br />EXEC dbo.GetColumnName @TableName = @newTable, @Value = @Value;<br /><br />IF (@@ROWCOUNT > 0)<br /><br />UPDATE ##Result SET TableName = @NewTable WHERE SL = (SELECT MAX(SL) FROM ##Result)<br /><br />FETCH NEXT FROM C1 INTO @NewTable; END CLOSE C1 DEALLOCATE C1;<br /><br />SELECT ALL * FROM ##Result;<br /><br />GOAhasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-65845931723891521242008-02-08T01:05:00.000-08:002008-02-08T01:07:50.948-08:00Oracle Object Name - Casing Issue<div align="justify">One interesting things find in oracle (if you are a Sql server developer) is that if I create objects name like MyTable then oracle transform it MYTABLE (upper case). </div><div align="justify"> </div><div align="justify">If I want to maintain case then I should use "MyTable"(with double quate).<br /></div><div align="justify">Sometimes It make me confuse. Speciall when create view. Suppose I Create a view like<br />CREATE VIEW "MyView"ASSELECT id AS "ID", name AS "Name" FROM "MyTable"<br />If I call that view from my application then I should use</div><div align="justify"><br />string SQL = "SELECT V.ID from MyView V WHERE V.Name = 'habib';</div><div align="justify"><br />If any application wants to support 2 databases like SQLServer & ORACLE then </div><div align="justify"> </div><div align="justify">it is very difficult to maintain casing. Because SQL Server developer never thinkcasing issue about database table/view/columns naming. If you convert Sql ServerObject to Oracle then always you should think and maintain that issue. OtherwiseOracle always gives you upper case object name. Some times It create problem of databinding.</div><div align="justify"><br />For Example</div><div align="justify"><br />MyComboBox.DataSource = MyDataSet[MyTable];<br />MyComboBox.DisplayMemeber = "Id";</div><div align="justify">MyComboBox.ValueMemeber = "Name";</div><div align="justify"><br />If Database is Sql SERVER then whatever the case is, its does not create any problem.</div><div align="justify"><br />But If it is Oracle then Oracle sent you [ID, NAME].</div><div align="justify">That ComboBox DataBinding behaves<br />interesting. </div><div align="justify"> </div><div align="justify">Why I am saying intersting, if you want to know then please write a demo<br />project and create the situation.</div>Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-18604062259466361832008-02-01T02:30:00.000-08:002008-02-01T02:33:48.296-08:00Dot Net implecit Casting Problem for Oracle DatabaseWhen you try to implecit convert integer from a ado.net' datarow, if database is oracle then it though Invalid casting error. You must use explicit casting with the help of Convert class( Convert.ToInt32()) to convert that.<br />But it is interesting that if your database is SQL Server then it works fine.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-11051747875016530862008-01-28T01:53:00.000-08:002008-01-28T01:56:23.354-08:00ORACLE BLOB, CLOB HandlingSome time it is necessary to convert blob, clob text data to varchar, want to datalenght of blob/clob field. That situation DBMS_LOB packgae can be utilize.<br /><br />Some Example<br /><br />1. SELECT DBMS_LOB.SUBSTR(CLOB_Field) AS VARCHAR_FIELD FROM AnyTable<br /><br />2. SELECT DBMS_LOB.LENGTH(CLOB_Field) AS VARCHAR_LENGTH FROm AnyTable<br /><br />I hope It helps.Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-79015535322841907262008-01-25T01:37:00.001-08:002008-01-25T01:50:56.135-08:00Oracle StatementWorking with BLOB type UTL_RAW package is important.<br /><br />===============================================<br />CREATE TABLE Data(Data BLOB);<br />INSERT INTO Data VALUES (rawtohex('hello world'));<br />SELECT UTL_RAW.CAST_TO_VARCHAR2(Data) FROM Data;<br />===============================================<br />Important DateCalculation Function<br /><br />CREATE OR REPLACE FUNCTION DateDiff( p_Interval IN CHAR, p_startDateIn IN TIMESTAMP, p_disconDateIn IN TIMESTAMP ) RETURN NUMBERAS<br /> v_duration INTERVAL DAY TO SECOND; v_myDay NUMBER; v_myHour NUMBER; v_myMinute NUMBER; v_mySecond NUMBER; v_totalSeconds NUMBER; v_Value NUMBER;BEGIN<br /> v_duration := (p_disconDateIn - p_startDateIn);<br /> v_myDay := TRUNC(to_number(extract(DAY FROM v_duration))*86400); v_myHour := to_number(extract(HOUR FROM v_duration))*3600; v_myMinute := to_number(extract(MINUTE FROM v_duration))*60; v_mySecond := to_number(extract(SECOND FROM v_duration));<br /> v_totalSeconds := v_myDay + v_myHour + v_myMinute + v_mySecond ;<br /> IF UPPER(p_Interval) = 'MS' THEN v_Value := v_totalSeconds * 1000;<br /> ELSIF UPPER(p_Interval) = 'S' THEN v_Value := v_totalSeconds;<br /> ELSIF UPPER(p_Interval) = 'M' THEN<br /> v_Value := ROUND(v_totalSeconds / 60);<br /> ELSIF UPPER(p_Interval) = 'H' THEN v_Value := ROUND(v_totalSeconds / 3600);<br /> ELSIF UPPER(p_Interval) = 'D' THEN<br /> v_Value := TRUNC(v_totalSeconds / 86400);<br /> ELSE RAISE_APPLICATION_ERROR(-20001, 'Invalid parameter value p_Interval');<br /> END IF;<br /> RETURN v_Value;<br />END;<br /><br />CREATE OR REPLACE FUNCTION ca_fn_GetUTCDateRETURN TIMESTAMPAS v_UTCDateTime TIMESTAMP;BEGIN SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP) INTO v_UTCDateTime from dual;<br /> RETURN v_UTCDateTime;END;/<br />CREATE OR REPLACE FUNCTION ca_fn_NEWIDRETURN VARCHAR2AS v_GUID VARCHAR2(50) := ''; v_GUID1 VARCHAR2(50) := ''; BEGIN SELECT SYS_GUID INTO v_GUID1 FROM dual; v_GUID := SUBSTR(v_GUID1, 0, 8) '-' SUBSTR(v_GUID1, 8, 4) '-' SUBSTR(v_GUID1, 12, 4) '-' SUBSTR(v_GUID1, 16, 4) SUBSTR(v_GUID1, 20, 4) SUBSTR(v_GUID1, 24);<br /> RETURN v_GUID;<br />END;<br /><br />=================================================================<br />Various Syntax<br />-----------------<br />CREATE DATABASE LINK EventLink CONNECT TO cic IDENTIFIED BY cic using 'caEvents'<br /><br />CREATE OR REPLACE TRIGGER tr_Delete_DvrConfigBEFORE DELETE ON DvrConfigFOR EACH ROW<br />DECLARE<br /> v_Old xmltype; v_TableName nvarchar2(50) := 'DvrConfig'; v_OperatorName nVarChar2(50); v_StationName nVarChar2(50); v_Description nvarchar2(100) := 'DvrConfig ID ' TO_CHAR(:OLD.DvrID);<br />BEGIN SELECT XMLELEMENT("DvrConfig", XMLATTRIBUTES(:OLD.DvrID AS DvrID, :OLD.ServerName AS ServerName, :OLD.ServerIP AS ServerIP, :OLD.UserName AS UserName, :OLD.Password AS Password, :OLD.UserType AS UserType, :OLD.Active AS Active, :OLD.EnableNotification AS EnableNotification, :OLD.DVRVendor AS DVRVendor, :OLD.caObjectID AS caObjectID, :OLD.LastUpdated AS LastUpdated, :OLD.LastOperator AS LastOperator, :OLD.LastWorkStation AS LastWorkStation)) INTO v_Old FROM DUAL;<br /> ca_sp_OperatorWorkStation(:OLD.LastWorkStation, :OLD.LastOperator, v_OperatorName, v_StationName);<br /> INSERT INTO DBAudit(Tablename, Description, Actions, RevisionStamp, OldData, OperatorName,StationName) VALUES(v_TableName, v_Description, 'D', ca_fn_GETUTCDATE, v_Old, v_OperatorName, v_StationName);<br />END;<br />==================================================================<br /><br />CREATE ROLE UMR_Role_Admin;<br />GRANT CONNECT, RESOURCE, CREATE USER, DROP USER, ALTER USER, GRANT ANY ROLE TO UMR_Role_Admin;<br />GRANT EXECUTE ANY PROCEDURE, SELECT ANY TABLE, SELECT ANY DICTIONARY TO UMR_Role_Admin;<br /><br /><br /><br />CREATE USER proxyuser IDENTIFIED BY proxyuser;<br />GRANT CONNECT TO proxyuser;<br /><br />grant select,insert,update,delete on system.umr_patient to public<br /><br /><br />exp userid=BockDBA/Password file='USER100.dat' owner=USER100 grants=N indexes=Y compress=Y rows=Y<br />imp userid=BockDBA/password file='USER100.dat' fromuser=USER100 touser=USER101 rows=y indexes=y<br /><br />Based on the table of keywords, interpret the example import command given below:<br />imp userid=SCOTT/TIGER ignore=Y tables=(expenses, advances) full=N<br /><br /><br />CREATE OR REPLACE PUBLIC SYNONYM sp_PatientGet FOR system.sp_PatientGet;<br /><br /><br />CREATE OR REPLACE PROCEDURE sp_UserAdd( p_UserID IN nchar, p_FirstName IN nvarchar2, p_LastName IN nvarchar2, p_Visibility IN number, p_UserGroup IN number, p_Email IN nvarchar2, p_Phone IN nvarchar2, p_Password IN varchar2 )AS v_sql varchar2(2000) :=''; v_Count int :=0; v_ApplicationUserException EXCEPTION; v_DatabaseUserException EXCEPTION; v_PermissionException EXCEPTION;<br />BEGIN<br /> SELECT COUNT(*) INTO v_Count FROM sys.DBA_Role_Privs R WHERE R.Grantee = (SELECT UPPER(USER) FROM DUAL WHERE UPPER(R.Granted_Role) = 'UMR_ROLE_ADMIN');<br /> IF (v_Count <=0) THEN RAISE v_PermissionException; END IF;<br /> SELECT COUNT(*) INTO v_Count FROM UMR_Users U WHERE UPPER(U.User_ID) = UPPER(p_UserID);<br /> IF (v_Count > 0) THEN RAISE v_ApplicationUserException; END IF;<br /> SELECT COUNT(*) INTO v_Count FROM sys.DBA_Users U WHERE UPPER(U.USERNAME) = UPPER(p_UserID);<br /> IF (v_Count > 0) THEN RAISE v_DatabaseUserException; END IF;<br /> v_sql := 'CREATE USER ' p_UserID ' IDENTIFIED BY ' p_Password;<br /> EXECUTE IMMEDIATE v_sql; <br /> v_Sql := 'ALTER USER ' p_UserID ' GRANT CONNECT THROUGH proxyuser' ; EXECUTE IMMEDIATE v_Sql; <br /> IF (p_UserGroup >= 10) THEN v_Sql := 'GRANT UMR_Role_Admin TO ' p_UserID; ELSE v_Sql := 'GRANT UMR_Role_Operator TO ' p_UserID; END IF;<br /> EXECUTE IMMEDIATE v_Sql;<br /> INSERT INTO UMR_Users ( User_ID, First_Name, Last_Name, Visibility, User_Group, Created_On, Email, Phone ) VALUES ( p_UserID, p_FirstName, p_LastName, p_Visibility, p_UserGroup, CURRENT_TIMESTAMP, p_Email, p_Phone );<br />EXCEPTION WHEN v_PermissionException THEN RAISE_APPLICATION_ERROR(-20010, ''); <br /> WHEN v_ApplicationUserException THEN RAISE_APPLICATION_ERROR(-20001, '');<br /> WHEN v_DatabaseUserException THEN RAISE_APPLICATION_ERROR(-20002, ''); <br />END<br /><br />==================================================================Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0tag:blogger.com,1999:blog-4532679383328034856.post-23514414084242669462008-01-23T23:03:00.000-08:002008-01-23T23:48:05.067-08:00Application support SQL Server & OracleSometimes it is requied to support sqlserver & oracle databaes for application. Both database came from different vendors. when you want to compatable both database then some issue you have to solve.<br /><br />1. First Issue Datatype<br /><br /><br /> SQL Server Oracle<br />------------------------------------------------------------------------------------------<br />1. TINYINT NUMBER(3)<br />2. SMALLINT NUMBER(6)<br />3. INT NUMBER(10)<br />4. BIGINT NUMBER(19)<br />5. BIT NUMBER(1)<br />6. VARCHAR VARCHAR2<br />7. SAMLLDATETIME/DATETIME DATE/TIMESTAMP<br />8. TIMESTAMP TIMESTAMP<br />9. MONEY NUMBER(19,4)<br />10. TEXT CLOB<br />11. BINARY/IMAGE BLOB<br />12. SQL_VARIANT SYS_ANYDATA<br />13. TABLE VARRAYS/NESTEDTABLE<br />14. UNIQUEIDENTIFIED VARCHAR2(50)Ahasan Habibhttp://www.blogger.com/profile/07122790325900611961noreply@blogger.com0