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

September 13th, 2009 by pratik.joshi § 4

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.

Efficient Usage Of FCKEditor

September 11th, 2009 by amit.shah § 4

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.

iPhone Application Deployment Steps

September 8th, 2009 by vivek.navadia § 8

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.

CLR Stored Procedure in Linq based n-tier architecture

September 8th, 2009 by virat.kothari § 1

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
}
}

How to integrate Amazon Web Services in your Web Application?

September 1st, 2009 by archit.patel § 1

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);
?>

How To Create Mirror Partition In Linux System

September 1st, 2009 by bhumish.shah § 1

This article shows how to configure raid 1 mirroring into your linux server

you must have two hard drive installed on your linux server with the same capacity

You can listed them using the following command

fdisk –l

This will display your currently installed hard drive on your linux server

/dev/hda/

/dev/hdb/

Then you have to create a logical partition on both hard drives with same capacity

Following command willl create a new partition on your linux server , for first hard drive (/dev/hda)

fdisk /dev/hda

This will ask for primary or extended partition

Type e for extended partition

Next will ask for cylinder size of your partition , don’t change anything

Next will ask for actual space for your extended partition

Type +10000M

Type w for write partition table

Now you have to create a logical partition using the following command

fdisk /dev/hda

N for new partition

L for logical partition

Just enter with the default configuration (cylinder size)

Type the size of your logical partition +5000m

Type w for write partition table

Remember by default when you create a new partition linux uses partition id number 82 .

You have to change this partition id fd for raid configuration with the following command

fdisk /dev/hda

Type l for change partition id

This will ask you which partition id would you like to change type your partition number

For example 5

Type fd for raid partition id

Type w for write partition table

You have to complete the same procces on second hard drive

Now you can start your raid 1 configuration using the following command

But before do this please check mdadm rpm package is installed or not

You can check this using rpm –q mdadm

You can also install this package using the following command

Type rpm –ivh mdadm

Now run the following command to create raid array

Type mdadm –create /dev/md0 –level=1 /dev/hda5 /dev/hdb5

This will create a raid partition on your linux server

You can see the details using the following command

Type mdadm –detail /dev/md0

Now you have to format this partition to use them

Type mkfs –t ext3 /dev/md0

This will write ext3 file system on your raid partition

Then you have to mount this raid partition on some directory using

Type mount /dev/md0 /raid1

If one of the hard drive faild on raid 1 type the following command to remove them from raid1

Type mdadm /dev/md0 –f /dev/hda5 (to fail your harddrive in raid1 )

Type mdadm /dev/md0 –r /dev/hda5 ( to remove your hard drive from raid1 )

Now you can join a new hard drive create logical partition with same capacity & join into you raid1 partition using the following command

Type mdadm /dev/md0 –a /dev/hdc5


You can see raid1 will syncs the data with the new hard drive using

Type mdadm –detail /dev/md0

Moving /opt/ Data To New Partition In Linux Due To Low Disk Space

September 1st, 2009 by bhumish.shah § 0

1. Introduction (Moving /opt data to a new partition)

The partition /opt is one of the most-often-moved partitions Because Linux Installs Third Party Software in /opt Directory. For Example Zimbra, Scalix.. So there is Disk Space Issue Occurs after Log Period

Some Times All Space On /opt Becomes Full and Your Application’s Performance Becomes Poor. In That Case you need an additional Harddrive or a Partition That Contains Big Space to Moved

In This Article I Will Show You How to Transfer Your /Opt Data to New Harddisk or Another Partition

Add New Hard Disk onto Your Server

When You Attach New Hard Drive on Server, It Will recognized as /dev/sdb.
Your First Hard Drive should be /dev/sda

2. Create new partition on your new hard drive with fdisk command:

fdisk /dev/sdb

Press n for Create a New Partition

This Will Ask For Primary or Extended Partition

Press p for Primary Partition

Press Enter for Default Setting in cylinder Size of Partition

Type the Size of the Partition That You Want To Allocate To Your New Partition

For Example: +80000M

This Will Create 80 GB New Primary Partition in to Your New Hard Drive

Press w for Save the Settings

Type partprobe Command to update The Kernel about newly added Partition

Now Format the Partition Using ext3 File System So That We Can Use Partition

mkfs –t ext3 /dev/sdb1

You Can Check Newly Created Partition Status Using fdisk –l Command . This Command Will Give You the Status of All the Partition

3. Mount the new file system in /mnt

Create a directory called /mnt/newopt, and then mount the new partition there:

# mount /dev/sdb1 /mnt/newopt

4. Drop to single-user mode

You must go To Single User Mode to Copy All Data in /opt to /mnt/newopt. You shouldn’t have any files open in /home, and entering single-user mode eliminates this possibility:

#Init 1

5. Change directories to /home and copy files

Type The Following

# cd /opt
# cp -avx * /mnt/newopt

The cp -avx command recursively copies the contents of /home to /mnt/newpopt, preserving all file attributes.
After this command finishes, /mnt/newopt will contain an exact copy of all the files and directories currently in /opt.

6a. If you installed /opt on separate partition then follow below steps

Unmount the old partition by typing:

# cd /
# Umount /opt/

Then, unmount and remount the new partition:

# umount /mnt/newopt
# mount /dev/sdb1 /opt

Now, the new partition is available at /opt and is ready to be used. We can perform the last few steps in multiuser mode. Exit single-user mode, so that the system is back up and running Type: init 5

Add This Entry To /etc/fstab File

/dev/sdb1   /opt   ext2   defaults   1   2

6b. If you installed /opt on shared partition then follow below steps

These instructions are for systems where the old /opt is on a shared partition.

# cd /
# mv /opt /opt.old
# mkdir /opt
# mount /dev/sdb1 /opt

Add This Entry to /etc/fstab File

/dev/sdb1   /opt   ext2   defaults   1   2

That way, your new partition will get mounted correctly the next time the system is rebooted.

We left the old /opt directory/partition behind, just in case there were problems copying files. After verifying that the system is running smoothly, you can remove the /opt.old directory.

Introduction to Palm Pre Development

August 26th, 2009 by Brijesh Patel § 1

Palm Pre

Palm Pre

Palm Pre is mobile technology and it mainly includes the following functionality

  • Move and open multiple applications very easily.
  • Palm Services like Backup and restore important data and erase data remotely if phone is stolen or misplace.
  • Palm web OS™ platform are integrated with other apps on the phone

What is webOS?
Palm webOS is an embedded operating system developed by Palm, Inc. for a range of devices. It includes many features like designing, coding and debugging.

What is Mojo?
Mojo is “an application framework based on the HTML5, CSS, and JavaScript standards”.  Applications built with Mojo “are installed and run directly on the device at native speeds and have access to a wide range of device services”.

While Mojo should be sufficient for developing a wide range of applications, other graphics-intensive programs such as games would probably require a lower-level webOS API.  There has been some speculation that Palm will release a second API that enables developers to access the hardware more directly for these types of applications.

Scene:
Scenes are mutually exclusive views of the application within a stage. Most applications provide different kinds of scenes within the same stage, while simple applications (such as Calculator) only have a single scene. Typically, a new scene is pushed after a user action, such as a tap on a UI widget, and the old scene can return with a “back” gesture. Scenes are managed by a scene stack, with new scenes pushed onto and off of the stack with the last scene visible.

Scene assistant:
A scene assistant is a “controller” for a scene.  It contains the logic behind how the scene behaves and responds to user input.

Widgets:
Widgets support webOS user interface, and Mojo definies styles for each of the widgets. The styles are available simply by declaring and using the widgets, or they can be overridden either collectively or individually with custom CSS.

The List widget is the most important in the framework, as “the webOS user experience was designed around a fast and powerful list widget, binding lists to dynamic data sources with instant filtering and embedding objects within other widgets and lists.”

Simple widgets include buttons, checkboxes, sliders, indicators, and containers.

The Text Field widget includes text entry and editing functions, including selection, cut/copy/paste, and text filtering, and can be used in conjunction with a list widget.

Menu widgets can be used with specified areas of the screen, including the view and command menus that are completely under your control. The app menu is handled by the system, but custom items can be added to the menu, as well as functions to service the help and preferences items.

Picker and viewer widgets are more complex, with pickers used for browsing and filtering files or contacts, or for selecting addresses, dates or times. Viewers are used to play or view items such as audio, pictures, video or web content within your application.

Requirement for development in Palm Pre

How to start development in Palm Pre?
Before starting development in Palm Pre you need  to download VirtualBox, Mojo SDK and Eclipse 3.4.2 version. Install VirtualBox first, then only download and install Mojo SDK. It is pre-requisite for Mojo SDK installation. When you start installing Mojo SDK, make sure that VirtualBox is not running.

Now Double-click the Palm SDK Installer file.

  • The Palm emulator becomes available in the Applications folder.
  • The Palm command-line tools become available from the Terminal.
  • Create or choose a directory to use as your application development workspace.

You can start the Palm Emulator by double clicking on its icon in the Application directory. At that time Virtual box starts up and creates virtual machine that hosts the Palm Web OS Platform. When you start VirtualBox first time there are several message will come. Just click ok on that diaglog box and continue.

In Eclipse you need to add Mojo SDK plug-ins. For that,

  • Start Eclipse.
  • go to Help Menu, Select Software Updates and click on Available Software tab.
  • click and select Add Site button. and in the location field http://cdn.downloads.palm.com/sdkdownloads/1.1/eclipse-plugin/eclipse-3.4/site.xml and click Ok.
  • check Palm Mojo SDK and click Install.
  • Restart Eclipse.

After installing Mojo SDK add plugins in the Eclipse,

Selecting the webOS Perspective

1.  Select Window > Open Perspective… > Other…

2.  Select webOS from the Open Perspective dialog.

3.  Click OK.

Preparing  webOS Application

From the New Project menu:

1.  Start Eclipse.

2.  Select File > New Mojo Application.

3.  On the next screen, type a name in the Project Name field.

4.  Enter your application info:

    • Title
    • Vendor
    • ID
    • Version

5.  Click Finish.

From the New App toolbar menu:

1.  In the Eclipse toolbar, click the Mojo Wizard icon and select New App from the drop down menu.

2.  On the New Project Wizard screen, type a name in the Project Name field.

3.  Enter your application info:

    • Title
    • Vendor
    • ID
    • Version

4.  Click Finish.

Adding a scene to your webOS Application,

From the New Project Menu:

1.  Select File > New > Mojo Scene.

2.  On the New Mojo Scene Screen, make sure the correct project is selected.

3.  Enter a name for your scene and click Finish.

From the New Scene toolbar menu:

1.  In the eclipse toolbar, click the Mojo Wizard icon and select New Scene from the drop down menu.

2.  On the New Mojo Scene Screen, make sure the correct project is selected.

3.  Enter a name for your scene and click Finish.

Running a webOS Application

1.  Select Run > Run Configurations…

2.  Select Palm Application and click the New Configuration icon to create a new launch configuration.

3.  Change the name.

4.  Select your project from the drop-down list.

5.  Select the Target:

    • Palm Emulator if you are using the emulator.
    • Palm Device if you are using a device (make sure your device is in Developer Mode).

6.  Click Run to install and run the application.

Installation starting problem when you run emulator first time.

If you are running on installing the application for the first time in Palm Emulator there is a possibility of getting following error.

Error Message

Error Message

To fix it you simply need to enter the following two commands in your terminal command prompt:

$ sudo chmod 644 /Library/LaunchDaemons/com.palm.novacomd

$ sudo /opt/nova/bin/post-install.sh

For more information please go through following site, you will find out more regarding this error.

http://www.ozmox.com/2009/07/25/webos-on-mac-os-x/


Tutorial of your First Palm Pre Application development:

Now how to develop first Palm Pre Application, following steps will guide you in details of Palm Pre development.

For that from New Project menu:

1. Start Eclipse.

2.  Select File > New Mojo Application.

Give the name of the application.

What is a Stage?

Now in the application you need to set the stage. A stage is the platform on which you build the user interface for your application. A stage generally corresponds to a single card, or application window. Most simple applications have a single stage, contained in the file index.html. An application that lets the user perform more than one action concurrently might require more than one stage. For example, an email application might show the inbox on one stage, but launch a second stage to compose a new email message. Notification and background applications have no stages at all.

So change in the Index.html page.

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”

“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en“>

<head>

<title>PalmTest</title>

<script src=”/usr/palm/frameworks/mojo/mojo.js” type=”text/javascript” x-mojo-version=”1″ />

<script src=”app/assistants/stage-assistant.js” type=”text/javascript“></script>

<script src=”app/assistants/first-assistant.js” type=”text/javascript“></script>

<!– application stylesheet should come in after the one loaded by the framework –>

<link href=”stylesheets/main.css” media=”screen” rel=”stylesheet” type=”text/css” />

</head>

<body>

<h2> Testing Application

</h2>

<p>

One stage application

</p>

</body>

</html>

Now create new scene named “First-scene”. It will add two files and one json file.

The palm-generate command creates the view and the assistant for the first scene. It also adds a few lines to sources.json to correlate the assistants and scenes. Take a look at the following files:

  • /app/views/first/first-scene.html — This is the view.
  • /app/assistants/first-assistant.js — This is the assistant.
  • sources.json — This file now includes JSON information that binds first-assistant.js to the first scene.

Now modify the first scene html file for adding new controls.

Open first-scene.html and replace the content with the following

<div>

<div class=”palm-header”>Header</div>

<div id=”count”>0</div>

<div id=”MyButton” x-mojo-element=”Button”></div>

</div>

Now to show the scene, you have to tell stage to push the scene.

To push the application scene

1.  Open stage-assistant.js.

2.  Edit the StageAssistant function to contain the following:

function StageAssistant () {

}

StageAssistant.prototype.setup = function() {

this.controller.pushScene(“first”);

}

Now how to bind and register the handler, there are two steps.

  • binding the handler to the scene assistant’s scope, using bind(this)
  • registering the handler as a listener, using Mojo.Event.listen()

Now open first-assistant.js and edit setup function and add following code into that.

FirstAssistant.prototype.setup = function() {

// set the initial total and display it

this.total = 0;

this.controller.get(“count”).update(this.total);

// a local object for button attributes

this.buttonAttributes = {};

// a local object for button model

this.buttonModel = {

“buttonLabel” : “CLICK HERE”,

“buttonClass” : “”,

“disabled” : false

};

// set up the button

this.controller.setupWidget(“MyButton”, this.buttonAttributes, this.buttonModel);

// bind the button to its handler

Mojo.Event.listen(this.controller.get(“MyButton”), Mojo.Event.tap, this.handleButtonPress.bind(this));

}

After creating build, run the application. It will shows the count that how many times you pressed “Click Here” button. It will increase every time you press click button.

PalmPre Sample

PalmPre Sample

Same way you can add more than one scene and navigate from one scene to other scene using following script which will help you to redirect to second scene by pushing the scene.

FirstAssistant.prototype.nextScene = function(event){

if (this.textModel.value == “Testuser”)

{

Mojo.Controller.stageController.pushScene(“second”,this.textModel.value,this.Passowrdmodel.value);

}

else

{

this.labelmodel.value=”Invalid User and Password”;

}

}

And you have your first Palm Pre application ready! I hope you enjoy Palm Pre development and leverage the first mover advantage of the platform.

Following are some good references for Palm Pre development:

http://developer.palm.com/

http://www.weboshelp.net/webos-mojo-development-resources

How to call procedure from another procedure or Use the data of dynamic sqlserver query in procedure

August 19th, 2009 by kuldip.bhatt § 0

Today I will explain very small but very useful feature which I have used in the past for the procedures. When I was new to SQL Server I was facing many problems and this was one of them.

We all know user defined functions has limitations that we can not use #temp table or table variables in UDF. Because of that we can not get the data from another function in the UDF.

So to overcome this problem, we can create the procedure in which we get data from another procedure for further manipulation. Question is how to get data from another procedure? You will get the answer of this question in this post.

e.g., suppose procedure ReturnStudentDetail returns the table with two fields “Name” and “City” so how can you get that table in another procedure for further manipulation.

– Create Table

Create table #StudentDetail

(Name varchar (50), City varchar (100))

– Below code will give you data in the procedure

Insert into #StudentDetail

Exec ReturnStudentDetail

This syntax works only if we use create table. You can also use dynamic sqlserver query output for inserting data in #temp table.

– Create Table

Create table #StudentDetail

(Name varchar (50), City varchar (100))

Declare @sql as varchar (500)

Set @sql = ‘Select Name, City from tbl_StudentDetail where ……..’

– Below code will give you data in table

Insert into #StudentDetail

Exec (@sql)

So, this is how you can get the data from another procedure or Dynamic sqlserver query output in Table. Basic thing is whatever the structure of data being returned, you have to create table on basis of that and use that table to get data from procedure or dynamic sqlserver query.

I hope this feature is useful for you in future. Let me know if you find any better way to achieve this.