06th Jan 2010

CO2 Net : A Concept of Future Networking

It was a nice normal working Tuesday at Digicorp.

We were a bit busy and a bit relaxed as it was nearly end of the day, around 5:15 PM or something. I was digging my mind to crack a complex feature in Unisite calendar module. and suddenly my colleague Vishal Parmar jumped to me and asked me Nilesh what if Internet because usual part and normal part of every computer, just like a disk-drive or any other part. and he was looking at me with his a bit childish face.. and thinking as he has cracked some kinda joke and waiting for the response from me.

…………and kboom I got a small spark in my brain……

and we guyz literally fall in to all new kind of discussion, and I got the idea that vishal was thinking right that Internet should be a part of every computer, or mobile or any device which falls in to digital categories. and it should be also provided free as well, but the problem is its not possible as our current Internet is hanging on a tree of massive cabling of OFC, conductive and satellite etc . and all this costs so Internet too.

but then I came up with an idea a Network using Naturally available and spread resource ;) and I had selected Co2 ( Carbon Dioxide )   as my network resource.

The idea is straight simple using few component

CO2 Net

  • Build small New gen modem (Device) which will send / receive,
  • and the device will send / receive using the molecular structure of Co2 of the earth’s atmosphere, and the signals will travel across the atmosphere by riding the Co2 enabling any capable device to reCapture / receive,
  • A small authentication will be bounded to each packet exhausted in the Co2, so the right candidate can only receive them

That’s it.

I know the idea might look silly at first, but think and you will find possibilities.

waiting to welcome your responses.

cheers

Posted by Posted by Nilesh under Filed under Concept/Idea Comments 13 Comments »

07th Dec 2009

Find HTML Editor in QTP

Follow below steps to read and write contents from an HTML Editor if you are testing using QTP

Step 1: QTP by default can not find an HTML Editor so you have to add HTML Editor in object repository. It will add HTML Editor as a frame.

See below image for an example

HTML Editor

Step 2:  Below is an example of how to write contents in an HTML Editor. Write below line once you have added HTML Editor as an object.

Browser(”NewRelease”).Page(”Registration”).Frame(”Frame_2″).Object.write “Testing of add news page.”

Step 3: Below is an example of how to read contents from an HTML Editor.

fName = browser(” New Release”).Page(“ Registration “).Frame(”Frame_2″).WebElement(”testing”).Object.innerText

Posted by Posted by mehul.brahmbhatt under Filed under QA Comments 1 Comment »

09th Nov 2009

Paypal shopping cart integration using HTML for Beginners

In online payment paradigm Paypal is one of the best and popular online payment services. Through this article I will share my experience with you about integration of online payment services.

Novice developer may find this post very useful.

I have used following methods for the online payment integration in my shopping cart.

In development process you need to create paypal testing account for that create paypal sandbox account for the testing purpose.

Step 1: https://developer.paypal.com/
Step 2: Create new account
Step 3: Paypal will send you activation link in your email inbox.
Step 4: Login in sandbox
Step 5: Create Test Accounts for buyer and seller accounts

Go to the Test Account page in paypal. Basically you need to type of account for your site integration
1.Buyer Account
2.Merchant Account.

Select country “United States”.
If you want to create buyer account choose Account Type: Buyer
Fill the form accordingly. Keep your login and password some where.
Click on “Show Advanced Options”.
Choose what card you want to use when will do online purchase for testing.
Set Account Balance.

Create seller account in same way as above.

Paypal gives you many ways to integrate your site with but here I will explain one method for the integration.

Simple Integration
==================
In simple integration with your site you need to know some predefined html variable created by paypal.

Not all the HTML variables I shown here but some of the important that I showed here out of other it is depend on your merchant account and situation.

Ref: https://cms.paypal.com/us/cgi-bin/?&cmd=_render-content&content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables

set following html variable as hidden in your Buy Now button page in your shopping cart page.

Replace all the value as per given instructions under the value attribute.
<FORM name=”redirectoPaypal” METHOD=”POST” ACTION=”https://www.sandbox.paypal.com/cgi-bin/webscr” />
<INPUT TYPE=”hidden” name=”CMD” value=”_xclick” />
<INPUT TYPE=”hidden” name=”amount” value=”shopping cart total amount of selected items” />
<INPUT TYPE=”hidden” name=”item_name” value=”shopping cart item description or name” />
<INPUT TYPE=”hidden” name=”item_number” value=”selected item number” />
<INPUT TYPE=”hidden” name=”quantity” value=”selected item quantity” />
<INPUT TYPE=”hidden” name=”currency_ code” value=”USD” />
<INPUT TYPE=”hidden” name=”invoice” value=”invoice number” />
<INPUT TYPE=”hidden” name=”business” value=”your merchant paypal login id” />
<INPUT TYPE=”hidden” name=”return” value=”site url for success page” />
<INPUT TYPE=”hidden” name=”cancel_return” value=”site url for cancel paypal payment page” />
</FORM>

more explanation of html variables.
“CMD” is use for shopping cart do not change it.
“business” in testing set seller account id here after complete testing change to real merchant account id.
“return” is page url of your site paypal will redirect on this page with some extra variable such as transaction id. just debug with var_dump($_GET)
and use.
“cancel_return” is page url of your site. paypal will redirect on this page if user will denied to confirm the payment.

put above code in your page and test it.
when your set-up working successfully. change the action url to “https://www.paypal.com/cgi-bin/webscr” for live.

API Integration
================
coming soon……

Posted by Posted by devdatt.mehta under Filed under php Comments 6 Comments »

23rd Oct 2009

Different Type of Monkey Testing

Monkey Testing

Monkey testing is used with fully automated testing tool. This tool doesn’t know how to use any application, so it performs mouse clicks on the screen or keystrokes on the keyboard randomly. The test monkey is technically known to conduct random testing, which is in the category of black-box testing. Below are different types of monkey testing.

  • Dumb monkeys
  • Semi-smart monkeys
  • Smart monkeys

Dumb Monkey Testing

The initial and the lowest level of testing service is called Dumb Monkey Testing, which is run without specific test in mind and often by a person with no or very limited education in testing.

But Dumb Monkey Tester does not mean a person of no intelligence at all, it rather means absence of any planning in the testing process.

Dumb Monkey software testing services:

  • Guesstimate about required time and staff
  • No formal planning and acceptance criteria
  • Click-through an application or a system
  • Very fast results from a done work

Semi-Smart Monkey Testing

Having some experience and improved testing skills the Dumb Monkey reaches the next stage in evolution: Semi-Smart Monkey Tester, who is the most effective when working in small groups.

Semi-Smart Monkey software testing services:

  • Initial level of planning and acceptance criteria
  • Guesstimate about required time and staff
  • Reading requirements before test run
  • Semi-technical bug reports, logs recording
  • Initial level of regression testing

Smart Monkey Testing

Smart Monkey is a crown of monkeys testing evolution. Having the army of Smart Monkeys it is possible to finalize vast testing projects, use tools and initial testing theory, bug trackers. Usually Smart Monkey area of activity is limited by his/her testing environment.

Smart monkeys are valuable for load and stress testing; they will find a significant number of bugs, but are also very expensive to develop.

Smart Monkey software testing services:

  • Repetitive planning and estimations
  • Attempts to analyze requirements before test run
  • Creating test scenarios
  • Issues Tracking Systems usage
  • Initial level of regression testing
  • Finding memory or resource bugs

Posted by Posted by jignesh.patel under Filed under QA Comments 2 Comments »

23rd Oct 2009

Create Virtual Machine in VMware Workstation

Vmware Workstation makes it simple to create and run multiple virtual machines on your desktop or laptop computer. You can convert an existing physical PC into a VMware virtual machine, or create a new virtual machine from scratch. Each virtual machine represents a complete PC, including the processor, memory, network connections and peripheral ports. VMware Workstation lets you use your virtual machines to run Windows, Linux and a host of other operating systems side-by-side on the same computer. You can switch between operating systems instantly with a click of a mouse, share files between virtual machines with drag-and-drop functionality and access all the peripheral devices you rely on every day.
Steps to Create a Virtual Machine
1. Create a Virtual Machine
Open a File menu and select a new Virtual Machine or you can directly click on the virtual machine from home tab of Vmware Workstation.
v6
2 .Now select a type of the configuration ( Typical )
a) Typical (Recommended): It creates workstation with recommended option. For Example: It will automatically select recommended workstation, memory, processor and network connection.
b) Custom (Advanced): You can manage your custom settings from this type. For example: User can set number of processor, select memory of virtual machine and network connection.
3 .Guest Operating System Installation
a) Installer disc image file (iso): User needs to select an iso image of the respective operating system which he needs to install on virtual machine. User has to select this option if he wants to install operating system.
b) I will install operating system later: If user do not want to install operating system for now then he can select this option. It will create a blank operating system in virtual machine and user can later install the operating system..
4. Guest Operating System
User has to select an operating system type from this option. For example User select Microsoft Windows, Linux and Sun Solaris etc. Based on selected operating system type it will display respective version of the operating system. User can also select it and go ahead.
5. Name the Virtual Machine
User has to enter name of the virtual machine and needs to give location to save the selected operating system image, System will save the image of operating system on the given location.
6. Specify Disc Space
User has to specify disk space to create a virtual machine. He has to give disc size in GB. Recommended size for Operating System window XP is 9 GB.
7. Final Step: Ready to Create Virtual Machine
It will display preview of all the details which you had selected. For example Virtual Machine Name, Location, Version, Os, Hard Disk, Memory etc.
Before Finish, You can also customize Hard ware settings if required otherwise you can finish the step. User can customize memory, CD / DVD, Display and Processor etc.

v3

Once all the customization completed then user can finish the step and it will create a virtual machine as per given details.

v9

Posted by Posted by mehul.brahmbhatt under Filed under vmware Comments No Comments »

13th Sep 2009

Google Map, Camera, iPod Library and Facebook Connect with iPhone

iphone_home

Displaying Google map

The iPhone SDK 3.0 offers a class of map view in MapKit framework. You just need to declare an object of MKMapView and add it to your current view.

MKMapView *mapview=[[MKMapView alloc]initWithFrame:(CGRectMake(0, -20, 320, 320))];

[self.view addSubview:mapview];

Now, to display the user location on map, I was trying to insert a pin annotation on map. Soon, I realized that was wrong approach. User location is meant for changing. It will be updated many time.

The solution for this was to use the MKUserLocation class object. The object of this class will return “Blue dot” of built-in Google map application on iPhone. It will also show animated circle with radius of probable range of user location.

MKUserLocation *ulocation=[[MKUserLocation alloc]init];

[mapview setShowsUserLocation:TRUE];

[mapview addAnnotation:ulocation];

That’s it. You don’t need to worry any more about the current location of user. The ulocation object will change its co-ordinates and display the dot whenever the position is updated.

iPhoneMap

Sending encoded image

You can send images to web service either by mail or by encoding it to string. I have used base64 encoding method to encrypt the image taken from iPhone camera and to send it to web service.

Generally, the image taken from iPhone camera is of very large size (800 kb to 2 mb). So, it may take very long time to encode the image.

I found another way to do the same thing. After taking the picture, you can display the image taken in full view of screen (320*480). Then take the screenshot at that stage and fetch the new image for encoding. In this way, you can make your encoding faster as this was the same picture taken using camera.

I have used following process to take the screenshot.

UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];

UIGraphicsBeginImageContext(screenWindow.frame.size);

[screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

NSData *screenshotPNG = UIImagePNGRepresentation(screenshot);

Now, since you have the image in screenshotPNG, you can encode it using your base64 method.

NSString *dstring=[[NSString alloc]init];

dstring=[self base64StringFromData:screenshotPNG length:[screenshotPNG length]];

Playing a specific song

With iPhone SDK 3.0, we have the access to iPod library on iPhone. The apple documentation “iPodLibraryAccess Guide” covers most of the part needed for understanding this functionality. Here, I will describe how to play a specific song stored on iPhone.

Let’s assume our song name is in songtitle which is NSString. To begin, we need objects of

MPMusicPlayerController and a MPMediaQuery.

MPMusicPlayerController* iPodMusicPlayer;

MPMediaQuery *everything = [[MPMediaQuery alloc] init];

everything=[MPMediaQuery songQuery];

NSArray *itemsFromGenericQuery = [everything items];

for (MPMediaItem *song in itemsFromGenericQuery)

{

NSString *mysong = [song valueForProperty: MPMediaItemPropertyTitle];

if([mysong isEqualToString:songtitle])

{

iPodMusicPlayer=[MPMusicPlayerController iPodMusicPlayer];

[iPodMusicPlayer setNowPlayingItem:song];

[iPodMusicPlayer play];

break;

}

}

Using Facebook Connect on iPhone

Facebook Connect used in iPhone lets user connect to their facebook account. I am facing one problem in maintaining session of facebook. The sample application provided with facebook sdk allows user to stay logged-in even if iPhone application is terminated. So, the user will not have to enter facebook account username and password next time.

We can know the status of user if he is logged in by using -

(void)dialogDidSucceed:(NSURL*)url  and – (void)sessionDidLogout:(FBSession*)session method from FBLoginDialog.m.

Whenever user logsin using facebook account, the session will stored using NSUserDefaults. We can know this by tracking -(void)save; method in FBSession.m file.

The save method in FBSession.m  stores 4 objects in userdefaults: FBUserId, FBSessionKey, FBSessionSecret and FBSessionExpires.

I am facing problem here. Whenever I try to resume previous session, using -(BOOL)resume; method in FBSession.m, I get correct userid, but rest of the values will be nil. i.e.session key, sesison secret and session expirary date are nil. So, I get one fatal error at that time saying: “attempt to insert nil value (key: session_key)”  I am still trying to find out the solution for that.

Posted by Posted by pratik.joshi under Filed under Code, facebook, iPhone Comments 2 Comments »

11th Sep 2009

Efficient Usage Of FCKEditor

Table of Contents

  • Introduction
  • What is FCKEditor?
  • When Should We Use FCKEditor?
  • The features that attracts the user to use it
  • What are improvement needs in it?
  • Integrate FCKEditor    Step by Step
  • How to apply Themes
  • How to apply Language
  • Conclusion
  • Bibliography
  • References
  • History

Introduction

There are many editors available in the market. Each editor has its own features, benefits and drawbacks. FCKEditor is top one of them in Open Source category. In this article, I will explain some of good features.

What is FCKEditor?

FCKEditor   is HTML text editor brings to the web much of the power of desktop editors like MS Word. FCKEditor is powerful tool which provides the html editing, theme to suit your web interface, multiple language supports, selection of tools to be displayed as per requirement, image upload, flash file upload and many more. It’s lightweight and doesn’t require any kind of installation on the client computer.

The features that attracts the user to use it

  1. Open source
  2. User friendly and easy to integrate
  3. Toolbar selection facility
  4. Support of multiple language
  5. Support of skin to suite web page UI
  6. Light weight
  7. Image and flash file upload

The improvement which could be done

  1. Inbuilt facility to select theme at client side
  2. Inbuilt facility to select language at client side
  3. More font type and font size to improve user interface

Integrate FCKEditor Step by Step

  1. Download FCKEditor  source code from following link: http://sourceforge.net/projects/FCKEditor /files/FCKEditor /2.6.4.1/FCKEditor _2.6.4.1.zip/download
  2. Create new/ Open existing web project/ website 1.CreateWbsite
  3. Copy FCKEditor source code folder and paste it to website root directory. 2.Pastfckeditor
  4. Copy FCKEditor  FredCK.FCKEditor V2.dll file from source code and paste it to website Bin folder 3.DllPaste
  5. You have to register FCKEditor to use it in your page. There are two way to register it. Manual: Following script will register it.  You have add this script in every page you want to use FCKEditor. 4.PlaceFckeditorFrom Toolbar: : You can Otherwise, you can browse FCKEditor by right click on Toolbar >> Choose Items. A dialog box will appear as shown in following image. Select .Net Framework Components >> Click on Browse button located at right hand bottom. Choose the .dll of FCKEditor from the bin directory of your application. An item called FCKEditor will be added to your Toolbar. Now you are ready to drag and drop editor in your page. If you place editor in your page, it will also add same code in your web page as we have done in manual method. ChooseFckEditorfrom
  6. Run website, you can see the FCKEditor in your browser with default theme and default English language. 5.RunFCKEditor

How to apply Theme?

FCKEditor   having a great themeing feature. User can apply the theme in two ways. One way is dynamically and another statically. The site of FCKEditor provides 3 themes to be downloading. There are many third party open source themes available to download. I have shared few themes with this article.

[1]. Default Theme

DefaultTheme[2]. Office2003 Theme

Office2003Theme

[3]. Silver ThemeSiverTheme

Now, how can assign default theme and apply dynamic theme?

Answer is here:

First of all you can set default theme from fckconfig.js, look at below image:

1.setdefaultTheme

You can also set the language from .aspx /html /php page where you have declare FCKEditor  .

Just set the SkinPath Property.

2.applytheme

Now run the application you can view the office2003 theme in FCKEditor as you have set in above page.

3.ThemePreview

How to apply Language?

FCKEditor   provides a great multiple language support feature. User can able to change the language dynamically or set default language as per website language.

FCKEditor provides 56 languages that is you can use as per your requirement.

Now, how can assign default language or apply dynamic language?

Answer is here:

First of all you can set default language from fckconfig.js, look at below image:

1.configsetting

You can also set the language from .aspx /.html /.php page where you have declare FCKEditor.

Just set the DefaultLanguage Property.2.Setlanguage

Now run the application you can view the Arabic language in FCKEditor as you have set in above page.

3.LanguagePreview

Conclusion

FCKEditor   is very simple, easy to integrate and can be used in almost all the web application as html editor/ rich textbox editor.

Bibliography

FCKEditor

References

FCKEditor

History

4th September, 2009: initial post

  1. Run
  2. website, you can see the FCKEditor in your browser with default theme and default English language.

Posted by Posted by amit.shah under Filed under Uncategorized Comments 1 Comment »

08th Sep 2009

iPhone Application Deployment Steps

Following steps may help you deploying your application successfully on the device.

  • Download your .mobileprovision and .cer certificates from developer.apple.com website.
  • Add the certificates to your keychain in Mac.
  • Add your mobile provision certificate in Xcode project. Drag the certificate to Xcode in left pane of window and drop there.
  • Select the Project and go to Edit Project Settings

1_New

  • Select Build Tab
  • Select Configuration as Release
  • Go to code signing
  • Add your certificate in Any iPhone OS Device section
  • When you add certificate in for Code Signing Identity, then it must be in list of Any iPhone OS Device option.

2

  • Follow same steps for Debug configuration also.
  • Do same change for Debug and Release configuration in Edit Active Target “Project Name” setting also

3

  • Edit the ProjectName-info.plist file in resources group and change the company name with yourcompany name on which you have registered your certificate in following value com.digicorp.${PRODUCT_NAME:rfc1034identifier} and save the project.

4

  • To solve invalid entitlement issue first right click on application and add new file
  • Under the iPhone OS select Code Signing
  • Select the Entitlements
  • Make sure it is saved as Entitlements.plist

5

  • Now uncheck the box of get-task-allow property in Entitlements.plist

6

  • Set the Any iPhone OS Device with saved entitlements certificate under Code Signing Entitlements for Debug and Release configuration.

7

  • Set the device OS for which you want to deploy your application from top left bar of Xcode window.
  • Save the Project and Build it.

It will successfully deploy your application on device.

Posted by Posted by vivek.navadia under Filed under iPhone Comments No Comments »

08th Sep 2009

CLR Stored Procedure in Linq based n-tier architecture

Table of contents

  1. Introduction
  2. Define Tiers for the Application
  3. Role of Tiers
  4. Implementing CLR Stored Procedure in LINQ based n-tier Architecture Step by Step
  5. Steps to Create Architecture
  6. Using the code
  7. Conclusion
  8. Points of Interest
  9. History

Introduction

This article is a sequence of my previous article about “CLR Stored Procedure & creating it step by step”. In my previous article I have explained CLR Stored Procedure, benefits & drawbacks of it and also how to implement it. CLR Stored Procedure is very powerful and gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management, etc. Development of any project in n-tier architecture is different taste and having its own benefits and drawbacks. Microsoft has launched LINQ i.e. Language Integrated Query with .net framework 3.0. LINQ can be implemented in variety of ways for e.g. LINQ with SQL, LINQ with objects, LINQ with dataset and LINQ with xml etc. I have implemented simple n-tier architecture few years back in my company. It is suitable for both web as well as desktop applications. It is a centralized n-tier architecture i.e. all the objects are resides at the same place in the target system. I don’t claim this as best but I have implemented this architecture as I want at least following benefits out of it.

  1. It must be secure, easy to implement and easy to deploy
  2. It must be tiered based and at least 3 tiered so that if we change code of any tier, we need to deploy dll of that tier only.
  3. Single architecture for web and desktop application with standard application performance
  4. Parallel development should be possible i.e. one developer can work with database, another can work with business logic and one more can work with user interface and so on
  5. No in-line SQL queries
  6. It must not be complex so that new developer can easily set on development without undergoing long training and existing developers can be easily migrated to and from any of the projects as basic development architecture of all the projects will remain same

Define Tiers for the Application

Now, let me explain various tiers of the architecture. Any good architecture will consist at least 3 important tiers viz. 1) User Interface or Presentation Layer 2) Business Logic Layer 3) Data Layer. The architecture which I am going to explain have 5 tiers. Any architecture having more than 3 tiers is called n-tier architecture. Following image will clarify it.

Architecture

Following is the image showing architecture in our application. It contains following 4 tiers (see image) and 1 database so total 5 tiers.

SolutionExplorer

Role of Tiers

Let me explain each of above tier in brief.

  1. Tier – 1: Presentation Layer: This layer will be responsible for various activities between Users and application. All the user interface related logic will reside at this layer. That means web forms or Win forms will reside here. This layer does not have direct access to the database or Data Access Layer. So, all the data goes in or comes out to Presentation Layer will be through the Business Logic Layer only. A reference of Business Logic Layer will be added to this layer. A separate project will be there for this layer.
  2. Tier – 2: Business Logic Layer: Business Logic Layer will perform all the Business Logics of the application. Business logic consists of two things viz., Core business logic and Data access logic. Data access logic is been segregated to different layer to provide more security and data encapsulation to the application. There will be a separate class for each table of the database to provide better management, in this layer. This class will have various methods. Business logic will be applied to data coming from or going to Presentation Layer and Data Access Layer. A reference of Data Access Layer will be added to this layer. A separate project will be there for this layer.
  3. Tier – 3: Data Access Layer: This layer is a part of Business logic but is separated from core business logic. All the data related operations between application and database will be performed over here. This layer will be created using “LINQ”. One LINQ to SQL class will be created over here and all the needed database tables or Stored Procedures will be dragged and dropped over here. This layer will have minimum manual coding. A separate project will be there for this layer.
  4. Tier – 4: CLR Stored Procedure Layer: This layer will be responsible for defining various CLR Stored Procedures. There will be a separate class for each table of the database to provide better management, in this layer. This layer is not directly associated with Presentation Layer, Business Logic Layer or Data Access Layer. CLR Stored Procedure will be deployed to SQL server. A separate project will be there for this layer. To know, what is CLR Stored Procedure and how to create it refer my article “CLR Stored Procedure and Creating It Step by Step”.
  5. Tier – 5: Database: This is core data and other objects to maintain and access it. For e.g. SQL server database. Core data is data in various tables and objects to maintain & access such data are various tables, Stored Procedures, CLR Stored Procedures, Views and Functions etc.

Physically there are 5 layers but logically they are 4 layers as assembly of CLR Stored Procedure will be the part of Database at the time of deployment.

To add reference of one project to another project is very simple. Just right click on the project >> Click on Add Reference. A dialog box will be displayed. Select “Projects” tab and select appropriate project in the list of projects. Click “OK” button. We can not add circular reference within project for e.g. In our case, Presentation Layer refers to Bussiness Layer and Business Layer refers to Data Access Layer. Now, we can not add reference of Presentation Layer to Data Access Layer as it will create circular reference.

Implementing CLR Stored Procedure in LINQ based n-tier Architecture Step by Step

Let us implement CLR Stored Procedure in LINQ based n-tier architecture. I have listed all SQL statements used for creating database, creating table, inserting dummy records in the table, etc. in the script attached with this article.

Application Development Specification

  • IDE: Visual Studio 2008
  • Framework: 3.5 with SP 1
  • Language: C# 3.0
  • Database: Microsoft SQL Server 2005 Express edition
  • Operating system: Windows XP with SP 2

Steps to Create Architecture

1. Open Microsoft Visual Studio 2008 >> Create New Project. A dialog box will be opened. Select, Visual C# >> Windows on left side “Project Types” panel. Select, “Windows Forms Application” on right side “Templates” panel. Give proper name to project, solution and select location to save this solution. This project will be our presentation layer. Following image will make it clear.

1

A default form with the name “Form1” will be created with the project. Rename it to “Demo”. Design it as shown in following image. There is a Label control for heading, one Data Grid View control, a Group Box control to hold various buttons viz., Get Data, Insert Random Record, Delete Selected Record, Clear Grid and Exit. Following image will make it clear.

BlankDemoForm

2.    Right click on Solution, click on Add >> New Project. A dialog box will be opened. Select, Database Projects >> Microsoft SQL Server >> SQL CLR on left side “Project Types” panel. Select, “SQL Server Project” on right side “Templates” panel. Give proper name to project and select location to save this solution. This project will be our CLR Stored Procedure Layer. Follow the steps I have explained in my article “CLR Stored Procedure and Creating It Step by Step” to add CLR Stored Procedure in this project. Following image will make it clear.

SQLServerProject

Right click on the project >> Select Add >> Add New Items. A dialog box will be displayed as shown in following image. Select Visual C# Items from left “Categories” panel. Select Stored Procedure from right side “Templates” panel. Give proper name to it.

AddClrSP

3.    Right click on Solution, click on Add >> New Project. A dialog box will be opened. Select, Visual C# >> Windows on left side “Project Types” panel. Select, “Class Library” on right side “Templates” panel. Give proper name to project and select location to save this solution. This project will be our Business Logic Layer. I have added two classes to this project i.e. 1) “ConvertToDataTable” and 2) “CustomerSalesInformation”. “ConvertToDataTable” class has various methods to convert array of objects to DataTable or DataSet. CustomerSalesInformation class consist various methods to Insert a record, Delete a record and Get records from database. Following image will make it clear.

BusinessLayer

4.    Once again, Right click on Solution, click on Add >> New Project. A dialog box will be opened. Select, Visual C# >> Windows on left side “Project Types” panel. Select, “Class Library” on right side “Templates” panel (same as step 3). Give proper name to project and select location to save this solution. This project will be our Data Access Layer.

5.    Right click on “DataAccessLayer” project, Select Add >> New Item option from the menu. A dialog box shown in following image will be displayed. Select on Visual C# Items in left side “Categories” panel and “Linq to SQL Classes” in right panel “Templates”.

LinqToSqlDal

6.    Open Server explorer and click on “Connect to database” button given at
top-middle of the server explorer window. It will start a new wizard to
connect to the database. Now drag and drop Stored Procedures
“CustomerSalesInformationDelete” and
“CustomerSalesInformationInsertRandomRecord”. Do NOT drag and drop
“CustomerSalesInformationGet” right now as we need to change it. I have
added “AccessData” class to add various useful methods and variables to
be used on Business Logic Layer. Write now I have declared one private
object of “LinqToSqlDataContext” and exposed it using property “Call”.
Following images will make it clear. Change the connection string I
have statically wrote while declaring object of “LinqToSqlDataContext”.

Dbml

7.    I have suggested not to drag and drop “CustomerSalesInformationGet” because it is a Stored Procedure which does not contain any SELECT query. That is why if you drag and drop it in .dbml file, the return type of the method of the said Stored Procedure will be “int” instead of ISingleResult and so it will not produce any result which we are expecting from this Stored Procedure. You can see this in .cs file of dbml. The work around I am going to explain is not the standard way but it works fine. Let me know if you find any better option. Following are the steps of the work around.

Step 1: Go to query analyzer and drop the Stored Procedure “CustomerSalesInformationGet” which was automatically created at the time of deploying CLR stored procedure, using following SQL statement.

DROP PROCEDURE [dbo].[CustomerSalesInformationGet]

Step 2: Create new stored procedure with the same name as stored procedure created at the time of deploying CLR stored procedure, using following SQL statements.

CREATE PROCEDURE [dbo].[CustomerSalesInformationGet]
AS
BEGIN
	SELECT * from CustomerSalesInformation
END

Step 3: Now come to the Visual Studio and refresh the “Stored Procedure” element of the tree view. You can simply right click on the element and click on “Refresh” option of the menu or cliking on refresh icon at the top-left of Server Explorer. Now drag and drop “CustomerSalesInformationGet” stored procedure to the .dbml file. This will create a method for the said stored procedure with the return type “ISingleResult”. You can verify this in .cs file of dbml. So this will return the result per our expectation.

Step 4: Once again go to query analyzer and drop the manually created stored procedure “CustomerSalesInformationGet” using following SQL statement.

DROP PROCEDURE [dbo].[CustomerSalesInformationGet]

Step 5: Now come to the Visual Studio and Right click on “ClrStoredProcedureLayer” project and click on “Deploy” option of the menu. This will deploy CLR stored procedure to the database once again. Now do NOT drag and drop this stored procedure to the dbml file otherwise we have to repeat this whole work around.

8.    You have to change connection at two places while using my sample source code.

1.    In the “AccessData.cs” file where we have declared an object of “LinqToSqlDataContext”. Following will clarify this.

private static LinqToSqlDALDataContext objLinqToSqlDALDataContext = _
new LinqToSqlDALDataContext("Data Source=OM\\SQLEXPRESS;Initial Catalog=DbForClrDemo;User ID=sa;Password=airborne");

2.    In the “CLRStoredProcedureLayer” project. Right click on the said project in solution explorer and click on “Properties”. A screen like following image will be displayed. Select “Database” tab and change the connection string at “Connection String” option where a textbox and Browse button is given.

ChangeConnectionInClrProject

9.    Save the whole solution. Right click on the solution in solution explorer and click on “Build” option. Now, you can run the application by hitting F5. A dialog box will be opened as shown in following image. Click on “Get Data” button, it will retrieves records from the database and loads in to the grid. “Insert Random Record” will insert random record in the table and once again retrieves records from the database and loads in to the grid. “Delete Selected Record” deletes the selected record. “Clear Grid” button clears the records from the grid. “Exit” button will close and exit the application. Following is the demo of the same.

DemoFormWithData

Using the Code

  1. Download the zip files for source code and sql script  and extract them
  2. Create Database and tables using “Script to create Database and Table.sql”. Also, insert records in the table using same file
  3. Change connections at 2 places in application as explained in Step 8
  4. Run the demo.
  5. When you hit “Get Data” button for the first time, it will take little time to fetch data from database. Now, hit “Clear Grid” button and hit “Get Data” button once again, you will realize the speed. Also, try to hit “Insert Random Record” button continuously for many time. It inserts record to the database and fills the grid at every hit, but still see the speed of it.
  6. This will give little slow performance in web application than windows application.

Conclusion

Clr Stored Procedures can be efficiently implemented in n-tier architecture

Suggestion

Refer my another article “CLR Stored Procedure and Creating It Step by Step

Points of Interest

  1. Exploring IMultipleResult in LINQ.

History

  1. 08th September, 2009: Initial release

using System;
using System.Windows.Forms;
using BusinessLayer;

namespace ClrInNTierPresentationLayer
{
/// <summary>
/// Represents demo form for the application
/// </summary>
public partial class frmDemo : Form
{
#region Constructor

/// <summary>
/// Constructor of the application
/// </summary>
public frmDemo()
{
InitializeComponent();
}

#endregion

#region Event Handler

#region Buttons

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnGetData_Click(object sender, EventArgs e)
{
try
{
FillDataGridView();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnInsertRandomRecord_Click(object sender, EventArgs e)
{
try
{
CustomerSalesInformation.CustomerSalesInformationInsertRandomRecord();
FillDataGridView();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Deletes selected record from the database
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnDeleteSelectedRecord_Click(object sender, EventArgs e)
{
try
{
if (dgvData.Rows.Count > 0)
{
if (MessageBox.Show(”Are you sure to delete selected record?”, “Confirmation”, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
CustomerSalesInformation.CustomerSalesInformationDelete(Convert.ToDouble(dgvData.CurrentRow.Cells["ID"].Value.ToString()));
FillDataGridView();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnClearGrid_Click(object sender, EventArgs e)
{
try
{
dgvData.DataSource = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnExit_Click(object sender, EventArgs e)
{
try
{
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

#endregion

#endregion

#region Private Methods

/// <summary>
/// Fills the data in the DataGridView
/// </summary>
private void FillDataGridView()
{
try
{
//Filling the grid with data
dgvData.DataSource = CustomerSalesInformation.CustomerSalesInformationGet();

//Formating the columns of the grid
dgvData.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dgvData.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dgvData.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

dgvData.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

#endregion
}
}

Posted by Posted by virat.kothari under Filed under asp.net Comments No Comments »

01st Sep 2009

How to integrate Amazon Web Services in your Web Application?

What is Amazon Web Services (AWS)?
Amazon Web Services (AWS) has provided companies of all sizes with an infrastructure web services platform in the cloud. With AWS you can requisition compute power, storage, and other services–gaining access to a suite of elastic IT infrastructure services as your business demands them.

Amazon Web Services provides a number of benefits for IT organizations which are:cost effective,dependable,flexible.

How  to integrate amazon in your site?
-> You need to get an access_key_id.
-> Authorized your Product API or Access_key.

How to get an access_key_id?
To get an access_key you have to create aws account from the below link:
https://aws-portal.amazon.com/gp/aws/developer/registration/index.html

After submitting the form you will get a mail from amazon. In that mail you will find a link link:
https://aws-portal.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&action=access-key

From this link you will get your access key and private key. Store your public key(access key) and private key(secret key) in your config file. Using this access_key you can access all amazon  books and its details  in your page.

How to make your Product API or Access_key Authorized?
You need to create a two demo files and one function file using below code

1) Function file-  aws_signature.php
2) Example file- example1.php
3) Example file- example2.php

1)Make one file named as aws_signature.php
<?php
function aws_signature($location, $params, $public_key, $private_key)
{
$private_key=”your secret key”;
$method = “GET”;
$hostname = “ecs.amazonaws.”.$location;
$uri = “/onca/xml”;

// additional parameters
$params["Service"] = “AWSECommerceService”;
$params["AWSAccessKeyId"] = $public_key;

// GMT timestamp
$params["Timestamp"] = gmdate(”Y-m-d\TH:i:s\Z”);

// API version
$params["Version"] = “2009-03-31″;

// sort the parameters
ksort($params);

// create the query
$query = array();
foreach ($params as $param=>$value)
{
$param = str_replace(”%7E”, “~”, rawurlencode($param));
$value = str_replace(”%7E”, “~”, rawurlencode($value));
$query[] = $param.”=”.$value;
}
$query = implode(”&”, $query);
$string_to_sign = $method.”\n”.$hostname.”\n”.$url.”\n”.$query;
$signature = base64_encode(hash_hmac(”sha256″, $string_to_sign, $private_key, True));

// create request
$request = “http://”.$hostname.$url.”?”.$query.”&Signature=”.$signature;
// do request
$request=str_replace(” “,”+”,$request);
$response = @file_get_contents($request);
if ($response === False)
{
return False;
}
else
{
// parse XML
$parsed_xml = simplexml_load_string($response);
if ($parsed_xml === False)
{
return False; // no xml
}
else
{
return $parsed_xml;
}
}
//Note:You can use  $parsed_xml as you requested array.You will get all the records from this array.
?>

2)Make one file named as example1.php
//To get the data for particular ISBN.
<?php
include(‘aws_signature.php’);
$isbn=”your book isbn value”;
include(’aws_signature.php’);
$public_key = “your public key”;
$private_key = “your private key”;

//You can select response group from this site:http://docs.amazonwebservices.com/_
AWSECommerceService/2008-03-03    /DG/index.html?ItemLookup.html

//Operation is ItemLookup for Particular item page.
$parsed_xml = aws_signature(”com”,  array(”Operation”=>”ItemLookup”,”ResponseGroup”=>”VariationSummary,_
SalesRank,Medium,Reviews,ItemAttributes,Offers,Images”,”ItemId”=>$isbn),   $public_key, $private_key);
?>

3)Make one file named as example2.php
//To get all books from amazon without knowing any book isbn value.
<?php
include(’aws_signature.php’);
$public_key = “YOur public key”;
$private_key = “your private key”;
$new_keyword=”Your keyword”;

//Operation is ItemSearch for all books.
$parsed_xml = aws_signature(”com”,   array(”Operation”=>”ItemSearch”,”SearchIndex”=>”Books”,”ResponseGroup”=>”VariationSummary,_
SalesRank,Medium,Reviews,ItemAttributes,Offers,Images”,”Keywords”=>$new_keyword),  $public_key, $private_key);
?>

Posted by Posted by archit.patel under Filed under Amazon Comments 1 Comment »