Easy Data Access In Pages Of GWT/Swing Application

July 10th, 2009 by vishal.shukla § 0

When developing desktop based or similar applications, it becomes headache to synchronize data between different pages. Say when Delete is clicked in context menu of some node of tree, Grid and some other panels need to be notified. Here is one simple way for accessing data of other panels. We have singleton session object (only one object at runtime) at each client’s runtime. So when we have some data that need to be used in other pages, we can put those objects in the session map and access it from the other class. Here is how we can create class that gives singleton instance of session map.


import java.util.HashMap;
public class SessionFactory {

private static HashMap session;
private SessionFactory(){
}

public static HashMap getSessionInstance(){
if(session==null){
session = new HashMap();
}

return session;
}

}

SQL SERVER – Difference between Line Feed (\n) and Carriage Return (\r) – T-SQL New Line Char

July 5th, 2009 by pinaldave § 2

Today, we will examine something very simple and very generic that can apply to hordes of programming languages. Let’s take a common question that is frequently discussed – What is difference between Line Feed (\n) and Carriage Return (\r)?

Prior to continuing with this article let us first look into few synonyms for LF and CR.

Line Feed – LF – \n – 0×0a – 10 (decimal)

Carriage Return – CR – \r – 0×0D – 13 (decimal)

Now that we have understood that we have two different options to get new line, the question that arises is – why is it so?

The reason is simple. Different operating systems have a different way of understanding new line. Mac only understands ‘\r’ as new line, while Unix and Linux understand ‘\n’ as new line character. Our favorite OS windows needs both the characters together to interpret as new line, which is ‘\r\n’. This is the reason why a file created in one OS does not open properly in another OS and makes it messy.

Now, let us see how we can create a new line in SQL Server. It is a very simple script yet very useful when we have to do run print something or generate scripts. I have illustrated two examples below that are very easy to understand. In the first example, there are no new line chars inserted and for the same, everything is displayed in a single line. However, in the second example, new line char is inserted and the lines are separated with a new line.

Example 1: No new line feed char

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL SELECT SecondLine AS SL' )
GO


Example 2: With new line feed char

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL ' +@NewLineChar + 'SELECT SecondLine AS SL' )
GO

I hope my examples make things more clear to you all. Let me have your feedback on this article.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

Sql Server automatically adjusts nearest 3 milliseconds on Date Selection Criteria

July 4th, 2009 by kalpesh.patel § 3

Most of the time we grab the date and time using sql server GetDate() Function.

Sometimes if data is filtered between two dates it may give erroneous result. Why? Because while retrieving data using date as filter criteria, it will fetch records which are nearest 3 milliseconds.

It will be more clear by following example.

Create Table datetesting
(
PK_id INT IDENTITY,
Datefield DateTime
)

Insert into datetesting(DateField)
Values (’1/2/09 00:00′)
Insert into datetesting(DateField)
Values (’1/2/09 23:59′)

Insert into datetesting(DateField)
Values (’1/2/09 11:59:59.995 pm’)

Insert into datetesting(DateField)
Values (’1/3/09′)

Now Execute the following query

Select * from datetesting where Datefield Between ’1/2/9′ AND ’1/2/9 11:59:59.998 PM’

Result of the above query

PK_id        DateField
—————————————
1        2009-01-02 00:00:00.000
2        2009-01-02 23:59:00.000
3        2009-01-02 23:59:59.997

Now, Try the following query to retrieve data. I have just added 1 millisecond and it will retrieve date 2009-01-03 00:00:00.000 which does not match the criteria.

Select * from datetesting where Datefield Between ’1/2/9′ AND ’1/2/9 11:59:59.999 PM’

PK_id        DateField
—————————————
1    2009-01-02 00:00:00.000
2    2009-01-02 23:59:00.000
3    2009-01-02 23:59:59.997
4    2009-01-03 00:00:00.000

So next time when you face wrong data by filter, don’t get perplexed, This may be the reason!

Watch albums of strangers on Facebook!

June 27th, 2009 by divyang.shah § 8

Facebook has always been touted to have strong privacy controls.  To most extent it is true and it is much better than most of the other social networks. But as a biggest social network they do have loopholes which can be easily exploitable by atleast developers like us.

Today I am going to talk about one such exploit:

How to view albums of people who are not your friends?

So when we search for interesting people on Facebook most of the time you will find their profile having restrictions. Mostly you will be able to see their profile photo and will be able to send message to them. So to see their full profile or albums we have to send “add friend” request and if they approve then and then only we can see their photos and profile.

But here is one way to bypass this:

First you have to add developers application in Facebook which can be added from following link:

Link:  http://www.facebook.com/developers/?ref=sb

Then go to this link

http://developers.facebook.com/tools.php

It will open below page and choose you response formate and also method = photos.getalbum as shown in below image.

facebook1

So after that enter facebook user id whose photos you want to see, in “uid text box” as shown in below image and then press “call method button”.

Get the facebook id from the address bar/url bar or find the “add as a friend” link in the web page and move your mouse cursor over it and you will get facebook id in the status bar as shown in image.

facebook3

And you will get details of all the albums of that user if he or she have albums as shown in below image in right side box.

Just you have to copy link content from right box and paste it to another browser or tab and press enter and then you can see all photos from that album without adding the user as a friend.

facebook2

Note: I have changed all the ids they are not real.

I hope with the help of this article and community, facebook will notice this bug and will resolve it.

So enjoy peeking on stranger’s albums. :)

Update: It seems that Facebook has resolved this bug now.

Customized Radio button & Check Box

June 27th, 2009 by Supriya Agnihotri Jagani § 0

Here is the customized design that would give a new look to your radio buttons & check boxes.
You can use different images you show the checked/unchecked check boxes & selected/unselected radio buttons.

Here is how your customized Check box & Radio buttons will look.

customized checkbox

customized checkbox

customized radio button

customized radio button

View Demo

You can change the images (the css has the image paths) to give that different look to your radio button & check box elements.

Browser Compatibility: Script is compatible & checked in Firefox, IE 6 7 & 8, Safari 2.0, Opera 9.0 & above & Google Chrome.

Click to download the .zip file with the script, css, html page & images; to give that much needed customized look to your form elements.

Script reference taken from: www.flog.co.nz

How to bind jQuery function to CSS

June 22nd, 2009 by nikunj.padaliya § 1

In this article I have explained how to use CSS and jQuery function together.

I will give one example in which I have used CSS for textbox and one jQuery function for validation like numeric value and maximum 3 character allowed.

Example:

Create a CSS for textbox in which height, weight, border, font, text-align etc. is defined.

<style type =”text/css” >

.txt1

{

text-align :center ;

width :60px;

height :22px;

border: 1px solid #000000;

font-family: verdana;

font-size: 10pt;

font-weight:bold ;

}

</style>

Write jQuery function for validation for numeric value and maximum length of the textbox. Bind this function to textbox stylesheet on keypress event.

<script type =”text/javascript” >

$(document).ready(function (){

$(“.txt1″).bind(“keypress”,function(){

var str = (event.srcElement).value;

var len1 = str.length;

if (len1 > 2)

{

event.returnValue=false;

if(!(event.keyCode==45||event.keyCode==46||event.keyCode==48||   event.keyCode==49||event.keyCode==50||event.keyCode==51||   event.keyCode==52||event.keyCode==53||event.keyCode==54||   event.keyCode==55||event.keyCode==56||event.keyCode==57))

{
event.returnValue=false;
}

});

});

</script>

Now apply the CSS to the textbox.

<asp:TextBox ID=”Textbox1″ runat=”server” CssClass=”txt1></asp:TextBox>

By applying this CSS on textbox user can only enter numeric value upto 3 characters and also we have a good looking textbox.

I hope this simple solution will help you somewhere in your project.

» Read the rest of this entry «

How to Convert Cursor into While Loop In Sqlserver ?

June 22nd, 2009 by kuldip.bhatt § 10

I personally face this issues in many Store Procedures i.e. Cursor taking too much time to execute. I am sure many of you will be having similar problem.

I have worked on that issue and found following solution. It may not be perfect for cursor optimization but it does work in my case.

– Original Cursor Code —

Declare @fk_MedicationOrderId as Bigint
Declare @AdminTime as Bigint

declare CUR_MEDICATIONORDERID cursor FOR
select
fk_MedicationOrderId
from
tbl_medicationorderDetail_trn
where
Actiondate > Getdate()

OPEN CUR_MEDICATIONORDERID

FETCH NEXT FROM CUR_MEDICATIONORDERID
INTO @fk_MedicationOrderId

WHILE @@FETCH_STATUS =0
BEGIN

Select @AdminTime=AdminTime from tbl_medicationorderDetail_trn
where fk_medicationorderid = @fk_MedicationOrderId

Update tbl_TempMedicationOrderDetail_trn
set ActionTime = @AdminTime
set @AdminTime = ”

FETCH NEXT FROM CUR_MEDICATIONORDERID
INTO @fk_MedicationOrderId

END

CLOSE CUR_MEDICATIONORDERID
DEALLOCATE CUR_MEDICATIONORDERID

——————-

– Modified Cursor Code (faster) –

Declare @fk_MedicationOrderId as Bigint
Declare @AdminTime as Bigint

Declare Table for the fields you need in the cursor.

declare @IDList table (ID Bigint)

Insert into @IDList
select
fk_MedicationOrderId
from
tbl_medicationorderDetail_trn
where
Actiondate > Getdate()

while (select count(ID) from @IDList) > 0
begin
select top 1 @fk_MedicationOrderId = ID from @IDList

Select @AdminTime=AdminTime from tbl_medicationorderDetail_trn
where fk_medicationorderid = @fk_MedicationOrderId

Update tbl_TempMedicationOrderDetail_trn
set ActionTime = @AdminTime
set @AdminTime = ”

delete from @IDList where ID = @fk_MedicationOrderId

end

——————-

What I have done here is to convert “cursor” into “while loop”. It is just to get your data in any temporary table or table variable after that just delete the rows from that at end of loop.

It helps in improving performance, I have personally tried it in many stored procedures.

Let me know if you find any other useful way of improving performance.

CLR Stored Procedures and creating it step by step

June 15th, 2009 by virat.kothari § 6

Download code & SQL statements: BlueDownArrow

Introduction:

We usually face problem in Stored Procedures and other database object when we need to implement some complicated logic within it. We found inefficient performance when we try to implement complex logic & business rules in database objects. In many cases we found C# or VB classes more powerful to implement such things. Microsoft has launched a new concept to resolve such issues with SQL server 2005 called “CLR Stored Procedure”.

What is CLR Stored Procedure?

Now, let us understand CLR stored procedure. CLR as most of .Net programmer knows is Common Language Runtime and Stored Procedures are routine stored procedures of database. Thus, CLR Stored Procedures are combination of both. As we all know, Common Language Runtime is core .Net component. The Common Language Runtime is runtime execution environment which supplies managed code with various services like cross language integration, code access security, lifetime management of object, resources management, threading, debugging & type safety etc. So now, CLR Stored Procedures are .Net objects which run in the memory of database.

The very first usage of CLR Stored Procedures can be said accessing system resources. Accessing system resources could also be done using Extended Stored Procedures which are again database object like Stored Procedures, Functions etc. Extended Stored Procedures can do most of the things which a standard executable program can do. Then, why are CLR Stored Procedures? The very first advantage of CLR Stored Procedures is it is a managed object unlike Extended Stored Procedures, which are unmanaged objects. The common thing between them is both runs under database memory. In this way CLR Stored Procedures gives all the benefits of managed objects. Following screen explains memory allocation while execution of CLR Stored Procedure.

0

When should I use CLR Stored Procedure?

Extended stored procedures run in the same process space as the database engine, memory leaks, bugs etc., can affects the performance of database engine. CLR stored procedures resolves these issues as they are managed object and runs per specifications of Common Language Runtime. CLR Stored Procedures can replace a standard stored procedure that contains complex logic and business rules. CLR Stored Procedures takes benefit of .Net classes and thus makes easy to implement complex logic, calculation, intense string operations, complex iterations, data encryptions etc., that are difficult to obtain in standard stored procedures. Standard stored procedures are still best for data oriented tasks. CLR Stored Procedures not only includes stored procedures but also includes Functions, Triggers etc. CLR Stored Procedures are compiled one so gives better performance.

Benefits of CLR Stored Procedures:

  1. Gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management etc.
  2. CLR Stored Procedures are managed codes so ensures type safety, memory management etc.
  3. Better code management and provides object oriented programming capability thus enables encapsulation, polymorphism & inheritance.
  4. Convenient for programmer as CLR Stored Procedures can be written in C#, VB or any other language that .Net Framework supports.
  5. CLR Stored Procedures can also be used with Oracle 10g Release 2 or later versions.
  6. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  7. Deployment may be difficult in some scenarios.

Drawbacks of CLR Stored Procedures:

  1. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  2. Deployment may be difficult in some scenarios.

Standard Stored Procedures vs. CLR Stored Procedures:

You are the best judge when to use regular Stored Procedures and when to use CLR Stored Procedures. CLR Stored Procedures can be used in following scenarios.

  1. When the program requires complex logic or business rules.
  2. When the flow is CPU intensive. CLR Stored Procedures gives better results as they are in complied form and managed one.
  3. The tasks which are not possible in TSQL, accessing system resources, cryptography, accessing web services etc.
  4. In option of Extended Stored Procedures. One should always consider CLR Stored Procedures before going for Extended Stored Procedures.
  5. An operation requires higher data safety.

Creating CLR Stored Procedure step by step:

Let us create one simple CLR Stored Procedure which fetches all the rows from one table of the database. I have attached whole list of SQL statement used for creating database, creating table, inserting dummy records in the table etc., under “SQL statements used in the demo” section.

Application development specification:

  • IDE: Visual Studio 2008
  • Framework: 3.5 with SP 1
  • Language: C# 3.0
  • Database MS SQL Server 2005 Express edition

Steps to create CLR Stored Procedure:

1) Open Microsoft Visual Studio >> Click on New Project >> Select Database Projects >> SQL Server Project.

1

2) You can choose reference of existing database connection or click on Add New Reference.

2

3) If you selects from existing references skit step 3 else add new database reference as shown in following image and click on Test Connection to test the connection.

3

4) On clicking on OK button, Visual Studio will ask you to enable SQL/CLR debugging on the selected connection. You can select “Yes” to enable debugging or “No” to disable the same.

4

5) Once the database reference and debugging option is selected, the project will be displayed in Solution Explorer. Select the project and right click on Solution Explorer >> Click on Add >> Stored Procedure.

5

6) Add new procedure from the installed templates as shown in following screen. Give proper name to it.

6

7) Once you select the template, it will create .cs file with the content shown in following image.

7

8 ) Add following code in the method already created. Pass “context connection=true” as connection string in the constructor while creating new SqlConnection. This CLR stored procedure is going to be the part of the database, so it will be the internal part of database so no need to connect database externally. So, no need to provide connection string that we usually provide in applications. Then Click on Build menu >> Click on Build Solution. Also click on Build menu >> Deploy solution. This will deploy the assembly to the database for which we have made connection initially.

8

9) Now, select the database >> Programmability. Right click on Stored Procedures >> Click on Refresh. The list of Stored Procedures should show one newly added stored procedure. Also right click on Assemblies >> click on Refresh. This should show newly added Assembly. Also, enable CLR Stored Procedure by following query.

sp_configure ‘clr enabled’, 1

Run following query to take effect or above query.

RECONFIGURE

Now, execute the stored procedure. It should give similar results shown in following screen.

9

SQL statements used in the demo:

Following is the queries to create database, create table, insert records in the table etc.

–Create a new databse for demo

CREATE DATABASE DbForClrDemo

–Use database

USE DbForClrDemo

–Create table for CustomerSalesInformation

CREATE TABLE [dbo].[CustomerSalesInformation](

[Id] [int] IDENTITY(1,1) NOT NULL,

[Name] [varchar](50) NOT NULL,

[Sales] [decimal](18, 2) NOT NULL DEFAULT ((0)),

CONSTRAINT [PK_CustomerSalesInformation] PRIMARY KEY CLUSTERED

(

[Id] ASC

)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

–Insert dummy data to CustomerSalesInformation table

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Virat Kothari’, 50000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Dhruval Shah’, 5000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Urvish Sheth’, 15000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Rakesh Bajania’, 25000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Dhaval Shah’, 150000)

–Enable CLR Stored Procedure in database

sp_configure ‘clr enabled’, 1

–Run following statuement to take effect of above statement

RECONFIGURE

–Now execute our CLR Stored Procedure. Remember “ClrDemo” is name of our Stored Procedure

EXEC [dbo].ClrDemo

Conclusion:

CLR Stored procedures are very simple and can be used in most complex scenarios.

Bibliography:

  1. MSDN (http://msdn.microsoft.com/en-us/library/ms131094.aspx)
  2. Code project
  3. http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1251402,00.html

Reference : Virat Kothari (www.viratkothari.wordpress.com)

Introduction to .Net Remoting

June 15th, 2009 by Brijesh Patel § 2

This Article is just an introduction to .Net Remoting. We will see in which situation .Net Remoting is useful and technical view of .Net Remoting.

What is .Net Remoting?

In General, Remoting is communication between two application domains. One application domain can communicate with other application domain with help of some kind of medium. This is how .Net Remoting works.

Now let’s see how .Net Remoting is useful in our real life scenario.

Suppose there is one company name ‘ABC‘.

It main office is in Ahmedabad city location. And there are some branches are in Ahmedabad city only but in different areas. And Outside Branches also there may be in different cities like Surat, Baroda, and Mumbai etc.Now all the branches are connected with main office and all the transaction done through main office only. So all the branches in all the places should connect with main office and communicate their data also.

So in this kind of situation .Net Remoting is very useful technology.

.Net Remoting works on three tier Application.

1.    Client
2.    Interface
3.    Server

In this Client side, generally UI is there where user can directly interact with the application. They put some input and get some output in any format like reports, graphical or any.

And in Server side all the business logic is there. If user input some data then all the transaction is done in server side. And last one is interface. Interface is medium to connect server and client. So many clients are connected with one server only through interface.

For example,
In above situation of ‘ABC’ company.

Server application is installed in Ahmedabad main office only and all other branches clients are installed. So all clients are connected with server means Ahmedabad main office. In main office there is main server is there and database is also there.

So when one client application sent some request through interface then that will come into the main server machine and then if they want to some data from data base then go to database and get it back to server application and back data to the client. If data is huge then data base server is installed in different machine other than different machine where server application is installed so transaction gets very fast.

Now we understand how .Net Remoting works internally.

DCOM is replace by .Net Remoting. By using .Net remoting, we can make remote object calls which lies in different application domain.

What is Application Domain?

Before we start to understand .Net Remoting, we just go through what is Application Domain?

Generally process used their owned security boundaries. In the Process there are number of application can run and one process has its own virtual memory and does not effect or overlap to other processes virtual machines. So one process can’t crash with other process. So same thing this concept used in .Net and more over ahead of this, concept of Application Domain are used. In Application Domain, Multiple Application can run in same process without influencing each other.  In that, if one application domain throws errors it does not affect or stop whole process and not effect with other application domain. To invoke method in an object running application domain .Net Remoting is used.

General Concept of .Net Remoting and its Architecture

Remoting has at least three sections:
•    Interface
•    Client
•    Server

in .NET Remoting, the client does not call the methods directly. A proxy object is used to raise methods on the remote object. All the public methods that are defined in the remote object class are also available to be called from clients.

This method of calls is called Message. These messages are serialized using formatters and then send message through channel from client. Thus Client channel communicate server channel and there server channel receive message and de serialised through server formatter and sent to the server remote objects.Generally .Net Remoting can be used across any protocols.

Any objects are created outside to the boundaries of Application Domain then it is called remote object to the AppDomain.  These remote objects can access by references or by value.

What is marshalling and different kind of Marshall?

Marshalling is used when object are converted. So these objects can travel throughout the network by channel and formatter.
There are two types of marshalling in the .net remoting.

•    Marshall-By-Ref
•    Marshall-By-Values

In the MBR, create proxy to communicate with other side of the network or remote object and create ObjRef instance that itself serialized.

ObjRef Returns by all Marshall () methods and it contains location of remote object, Hostname, Port Number and Object name etc.

For example:

MarshalByRefObject obj  =(MarshalByRefObject)RemotingServices.Connect(typeof(Ilogin), “tcp://LOCALHOST:65101/ITestEndPoint”);

// Set a reference to the service. After this, you use testRemoteReference
// just as if it was a local instance of ITestImplementation.

loginreference = obj as Ilogin;

Whereas in MBVs objects, Copy of the object is created on the other side (i.e. server side). The object to marshal is stored in to a stream, and a stream is used to crate copy of the object.

So Marshalling is a process of packing object and a call and its arguments made by an AppDomain on a remote object into a unit that’s easily transferable across the network. In other we can say that Marshalling is process to transfer message from one place to other means its destination. Once marshal reached its destination, an unserialized process is taken place and returns its original data by this.

Difference between MBV and MBR

MBVs is that they get serialized with all the private and public data members. But that may be cause problem if a client intercepts the serialization/de-serialization phase to harm application.
While MBRs, only clients decide which objects can travel across there network. He doesn’t have to load entire copy of the object if he wants to call some functions or some procedures only. And MVB execute in its original native places only where it governed by CLR. So Application May misbehaviour in some cases but that is happened vary rarely.

In .Net Remoting there are two ways to create remote objects.

Server activated objects (SAO)
Client activated objects (CAO)

SAO has two modes named ‘Single call’ and ‘Singleton’.

Single call is an object that object created with every method all or server trip. So all these objects are stateless. And after use of that object it is destroyed and every time creates new objects. Single Call objects are useful in scenarios where the objects are required to do a finite amount of work.

While in other side, in Singleton the object is created only once and the object is shared with all clients. So this kind of objects is used for share object through out the application. So singleton objects are useful in many applications like chat application etc.

CAO is not stateless compare to SAO. Client holds proxy to the server object on the client side which is created on server object on server side.

Example of Single call and Singleton:

Singleton:

// Register the interface and end point.
//
// Each service has a unique endpoint and this endpoint is how a client
// accesses a specific service on a remote server.

Type ilogin = Type.GetType(“login”);
RemotingConfiguration.RegisterWellKnownServiceType
(ilogin,”IloginEndpoint”,WellKnownObjectMode.Singleton);

Singlecall:

// Register the interface and end point.
//
// Each service has a unique endpoint and this endpoint is how a client
// accesses a specific service on a remote server.

Type ilogin = Type.GetType(“login”);
RemotingConfiguration.RegisterWellKnownServiceType
(ilogin,”IloginEndpoint”,WellKnownObjectMode.SingleCall);

In next article we will see more about .Net Remoting like Channels and Formatters, Object Activation and Lifetime and simple example of .Net Remoting .