Monday, October 19, 2009

Client Side AJAX Calling Part 2

In continuation to my earlier post, I am showing here how to access the data from the server using simple JavaScript calls.

In this example the user will enter the customer id to retrieve the corresponding salary. For simplicity lets have following data model for this example. The data is stored in table named, tbAccounts.
I will be using Sql Server 2008 as database server.
image

In our application user will enter one among the above three customerID to test the application.

Enter the following data access code inside function RaiseCallbackEvent. This function will query the tbAccount able for the salary corresponding to the user entered customer ID.

image 

The value retrieved from database is stored in private variable, ValueToSendClient.

As described in my earlier post, the value to be sent to the client is retuned using the function GetCallbackResult(), which is implemented as follows.

image 

The value returned by above function is accessed by the client side function GetRequiredDataFromServer which then populates the salary textbox. This function is implemented as follows.

image 

The above method is one among the many methods of accessing data from server using AJAX calls. In my subsequent post I will blogg about these methods.

Sunday, October 11, 2009

Client Side AJAX Calling Part 1.

AJAX capability in web page can be accomplished by using JavaScript to communicate with the server side. ASP.NET uses Page.ClientScript property to add JavaScript functions to ASP.NET pages. In this posting I will show how web page can communicate using  JavaScript to access the data from the server side without refreshing the whole content of web page. Before I get started with the steps required to accomplish this task , I would like to give brief introduction on few important methods of Page.ClientScript which helps in communicating with server.

Note:Page.RegisterStartUpScript and Page.RegisterClientScriptBlock from .NET framework 1.0/1.1 is now obsolete. Page.ClientScript property will help now in bringing all the script registration under one umbrella.

  1. Page.ClientScript.RegisterClientScriptBlock 
    This method allows to place java script at the top of the page.
  2. Page.ClientScript.RegisterStartUpScript
    This method allows to place the java script at the bottom of the page. This method helps if you want to work on any controls of the page.
  3. Page.ClientScript.RegisterClientScriptInclude
    This method helps in registering the script files with the ASP.NET page. If you prefer to write all java script functions in a separate .js file , then using this method you can attach the file to web page.

Let me now get started with steps to access the data from the server side using the java script.

Step 1: Create an ASP.NET page with 2 TextBox controls and a Button controls as shown below. Make sure for button you use the HTML control. Here is a screen shot of the web page. Customize the look and design to your convenience.
image 

Note: I will explain the code in Part 2 of this posting.

Step 2: To Page_Load event add the following code. 
image

Also make sure your page class inherits System.Web.UI.CallbackEventHandler like this.

image

Step 3: Add following code to client side of the webpage.

image

That's it…!!!! Now all you need to add is some code in server side which will talk to database and gets the required data. Don’t get overwhelmed by the above code. I will explain every line of code in Part 2 of this topic.

Wednesday, September 16, 2009

Session State compression in ASP.Net 4.0

One among the many features introduced in ASP.Net 4.0 is the capability to compress serialized session state. The default options provided by ASP.Net for storing session state across the web farm are…

  1. A session state provider that invokes an out of process session state server.
  2. A session state provider that stores data in Sql server database.

The session data is stored outside the web application’s  workers process. So the session state has to be serialized before been sent to remote storage. Depending on the information stored in session by the developer, the size of the serialized data can grow large. To over come this draw back ASP.NET 4.0 introduces a new compression option for both kinds of out-of-process session state providers. This can be achieved by setting “compressionEnabled” option in configuration file:

image 

Wednesday, September 9, 2009

Tids and Bits of OOPs concepts in C#.

C# is a very vast language. I am sure everyone agrees with me. It is very highly object oriented which makes it a versatile language.

I was trying to brush-up my OOP’s concepts and came across few concepts which are too good not to forget related to polymorphism. So I decided to blog about these concepts. So here it comes…

  1. sealed key word helps in preventing further inheritance of a class.
      Assume Class employee which is inherited by salesperson and manager class. Let salesperson class be inherited by a new class ,parttimesale. If you want to prevent further inheritance of parttimesale, then you need to declare the class parttimesale as sealed.
sealed class parttimesale : SalesPerson
{ // this class cannot be further inherited...
// Logic comes here...
}






     2. Containment/delegation: Inheritance are basically of 2 types, is-a and and has-a. Sometime you might want to create a class which does not full fill the criteria as is-a. For example, if for an employee class you want to establish an benifitpackage class then you cannot say benifitpackage is-a employer. In such situations has-a rule applies. Employee has a benifitpackage. Once you have contained the  benifitpackage object within the employee class, you can expose the functionality of contained object using the delegation method.To achieve this you can update the employer class as follows…



partial class Employee
{
class BenifitPackage
{
public double ComputeBenifit()
{
// Logic Here
return 500.00;
}
}
//Contain a BenifitPakage within the object.
protected BenifitPackage bnPackage = new BenifitPackage();

//Expose certian benifit behaviors of object
public double getBenifitCost()
{
// some logic here...
}

// Expose object through a custom property
public BenifitPackage Benefits
{
get { };
set {};

}

}






       3. Abstract class vs Abstract method: If you ever want to prevent a class definition from being instantiated then you need to prefix the class definition as abstract. An abstract class can define any number of abstract members. Abstract members are used to make it mandatory for the inheriting class to implement the abstract method.


    Consider a an abstract class Shape which is inherited my class Rectangle and Circle. Since the method of drawing a rectangle and circle differs, it does not make sense for the abstract class to implement the Draw method. So the Shape class can declare an abstract method as Draw which should be implemented by the inheriting class. So both the Circle and Rectangle will implement the Draw method as per requirement.  Here comes an example…


abstract class Shape
{
// force the inheriting class to implement Draw method.
public abstract void Draw();
}

public class Circle : Shape
{
// some logic here...

public override void Draw()
{
// Logic to draw circle...
}


}
public class Rectangle : Shape
{
// some logic here...

public override void Draw()
{
// Logic to draw rectangle...
}

}





Reference:Pro C# 2008 and the .Net 3.5 Plaform by Andrew Troelsen.

Monday, August 10, 2009

Sharing Values between ASP.Net Pages…..

If you have ever worked on a multiple page online form , I am sure you might have felt the need of a method through which you could share values between pages. ASP.Net 3.5 introduced a concept called ..."Cross Page Posting" through which you could share values between pages. Basically there are 2 types of method through which cross page posting can be achieved. For all the methods explained below I will be using following form:

FormImage

Method 1:

1. If the value entered in the Name field in Page 1 needs to be passed to Page 2 , then assign the value for PostBackUrl of button "Send to Page 2" to the "Page2.aspx".

2. In in form load event of Page2.aspx create an instance of TextBox Object then access the value from Page 1 textbox using the findcontrol method on PreviousPage object as shown below:

public partial class Page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox txt_name;

txt_name = (TextBox)PreviousPage.FindControl("txtName");
lbName.Text = txt_name.Text;

}
}



lbName is the id of the label in Page2 to which the value from Page1 needs to be assigned.







Method 2:



Another way of exposing the values from Page1 to Page 2 is by creating properties for controls in Page 1 as shown below:




public TextBox NameText
{
get
{
return txtName;
}

}





In Page2 strongly type the PreviousPage property to Page1.aspx as shown below:




<%@ PreviousPageType VirtualPath ="~/page1.aspx" %>





Now in the PageLoad event of Page2 you can access the value entered into Textbox in Page1 by using the following code..




protected void Page_Load(object sender, EventArgs e)
{

lbName.Text = PreviousPage.NameText.Text;


}





It’s that simple….!!!!!



What if the user directly access the Page2 ..??? This scenario can be handled by using the following code on Page_Load event of Page2.aspx:




protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
lbName.Text = PreviousPage.NameText.Text;
}
else
{
Response.Redirect("Page1.aspx");
}


}



Have fun using the Cross Page Posting…..

Tuesday, June 9, 2009

iPhone App got Accepted....!!!!

After almost a week, I finally got my first iphone app accepted by Apple.
App can be downloaded from this link….
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=318565038&mt=8
It’s time to work on my next project. Keep guessing and visiting this blog to learn more about it.
Find attached few pictures of my approved iphone App details…!!!!





Saturday, May 30, 2009

My First Iphone App is Ready ..!!!

At last I was able to finish my first iphone App, "Pyschic Reader". I plan to submit this by this weekend. Now all I can do is to keep fingers crossed and expect Apple to approve my application and put it on Itunes store...!!!.

Here comes the screen shots of the application. Very soon I will post more about this application.

1. Screen 1

2. Screen 2

3. Screen 3

4. Screen 4.1

5. Screen 4.2

6. Screen 4.3

7. Screen 5

Monday, May 11, 2009

Login Control for iPhone …!!!!


In this post I will be briefly explaining the creation of object and displaying it on iPhone. Please note that, Interface builder available in Xcode  decreases the pain it takes to create objects from scratch. I will be creating a object containing a Label and a Text box. This object will be assumed to be used as Login Control.
1. Create a window based project using the Xcode and call it “forBlog”.
2. Add a new class to this project and call it “LoginClass”.
Some of the important files which gets created now are forBlogAppDelegate.h, forBlogAppDelegate.m, LoginClass.h and LoginClass.m.
3. Declare the required instance variables needed for Login control in LoginClass.h. For our example we will define a Lable and textbox control. Also declare a method “setMyColor” which will help us in setting the background color of the label to match with main window ie super. Your code should look as below.
//
// loginClass.h
// forBlog
//
// Created by Bharath Panyadahundi on 5/11/09.

//

#import <UIKit/UIKit.h>


@interface loginClass : UIView {

UILabel *lbName;
UITextField *txtName;


}

@property(nonatomic,retain) UILabel *lbName;
@property(nonatomic,retain) UITextField *txtName;

-(void)setMyColor:(UIColor *) color;



@end

4. Provide definition for each instance variable and method declared in LoginClass.h. Your code should look as below:


//
// loginClass.m
// forBlog
//
// Created by Bharath Panyadahundi on 5/11/09.

//

#import "loginClass.h"


@implementation loginClass
@synthesize lbName,txtName;


- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {

// Initialization code

// Create Label Object...

lbName = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 60, 20)];
lbName.text = @"Login:";
lbName.textColor = [UIColor whiteColor];

// Create Text Object

txtName = [[UITextField alloc] initWithFrame:CGRectMake(120, 100, 100, 20)];
txtName.borderStyle= UITextBorderStyleRoundedRect;


[self addSubview:lbName];
[self addSubview:txtName];


}
return self;
}


- (void)drawRect:(CGRect)rect {
// Drawing code
}

-(void) setMyColor:(UIColor *) color
{
[lbName setBackgroundColor: color];
[super setBackgroundColor:color];
}


- (void)dealloc {
[lbName release];
[txtName release];

[super dealloc];
}
@end

5. Now that we have the object creation class available, we need to create an object of this type in forBlogAppDelegate.m file. Make sure that you import the file LoginClass.h to this file before trying to create the LoginClass Object. Once done your code will look as below:

//
// forBlogAppDelegate.m
// forBlog
//
// Created by Bharath Panyadahundi on 5/11/09.

//

#import "forBlogAppDelegate.h"
#import "loginClass.h"
@implementation forBlogAppDelegate

@synthesize window;


- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after application launch

loginClass *objLogin = [[loginClass alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[objLogin setMyColor:[UIColor blueColor]];

[window addSubview:objLogin];
[window makeKeyAndVisible];
}


- (void)dealloc {
[window release];
[super dealloc];
}


@end

6. The header file forBlogAppDelegate.h need not be touched in order to get the required result. However  here is the default template of this file which gets created when the project for created.



//
// forBlogAppDelegate.h
// forBlog
//
// Created by Bharath Panyadahundi on 5/11/09.

//

#import <UIKit/UIKit.h>

@interface forBlogAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end




7. You can now build the project. Assuming you were able to build the project successfully, you should be getting the following output on iphone simulator.




Picture 1




Wednesday, May 6, 2009

C#.Net vs Objective C

Having got impressed by applications running on my iPod touch  I decided to spend my free time towards learning cocoa framework which is used for developing iphone application. The cocoa framework uses Objective C language. The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. Its additions to C are mostly based on Smalltalk, one of the first object-oriented programming languages. Objective-C is designed to give C full object-oriented programming capabilities, and to do so in a simple and straightforward way.

Having been working on C#.Net from many years I had to glance through the new syntax of Objective C. To make the difference clear, I am presenting here a sample code for printing a Fraction, both in C# and Objective C.

1. C# code for printing fraction:
   Program File: Program.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectiveCInC
{
    class Program
   
{
        static void Main(string[] args)
        {
            Fraction myFraction = new Fraction();
            myFraction.numerator = 1;
            myFraction.denominator = 3;
            myFraction.printMe();

            Console.ReadKey();
        }
    }

}

   Class File: Fraction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectiveCInC
{

class Fraction
{
public int numerator;
public int denominator;

public void printMe()
{
Console.WriteLine("{0} / {1}", numerator, denominator);

}

public void setNumerator(int n)
{

numerator = n;
}

public void setDenominator(int d)
{
denominator = d;

}

}

2. Above code in Objective C:





#import <stdio.h>
#import <objc/Object.h>

@interface Fraction: Object
{
int numerator;
int denominator;


}

-(void) printMe;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;

@end

@implementation Fraction;

-(void) printMe
{
printf("%i / %i ", numerator,denominator);
}

-(void) setNumerator: (int) n
{
numerator = n;

}

-(void) setDenominator: (int) d

{

denominator = d;

}


@end

int main(int argc , char *argv[])
{

Fraction *myFraction = [[Fraction alloc] init];




[myFraction setNumerator: 1];
[myFraction setDenominator: 3];

printf("The value of myFraction is : ");

[myFraction printMe];

printf("\n");

[myFraction free];

return 0;

}






Tuesday, May 5, 2009

How to become an Iphone Developer….!!!!

 

With the release iphone SDK to public, apple gave all the developers out their a good reason to love Mac OS. In this blog I am going to provide essentials step required in becoming an iphone developer.In my next blog post I will try to share some code.

Making the jump from one programming language to another isn’t always an easy thing to do, and usually requires some specific motivation — a problem to solve, or a market to satisfy. I’ve dabbled with various kinds of programming for years, but have never really considered myself a developer. Apple’s iPhone and Google’s Android platforms are, I think, making really compelling platforms to entice people to make the jump to start creating their own programs. The barrier to entry is low, the distribution is handled for you, and the cost to potential customers is cheap.

1. Buy a Mac:You'll need one with an Intel-based processor, running the Leopard version of MacOS X. It doesn't have to be a top of the range model, though.

2.Download the Iphone SDK which apple provides it for free from apple website.

3.Learn Objective C:This is the primary programming language for iPhone development. It's an extension of C to include object-orientated principles. It has scripting elements to it, so is easier to pick up than some languages and anyone with programming experience should be able to transfer their skills.

4.Start writing something:Forget theory; forget mastering Objective C with your first attempt. Just set yourself a project and start working. I knew nothing about Objective C, Cocoa, or OpenGL prior to stepping into Iphone SDK.  having been a C# programmer for 5 years,it was quite an adjustment moving from a nice safe language like Visual Studio to one where a single misplaced byte can instantly crash your program.

5. Sign-up as an official developer:If you plan on releasing your masterpiece at any point, you'll need to sign up with the iPhone Developer Program. The Standard cost is $99, and it involves agreeing to Apple's terms and conditions, and signing and returning the contract. Even if you're nowhere near completing the project, you'll need to sign up in order to test your code on an actual iPhone rather than an onscreen emulator. Once you're on the Developer Program you're sent a certificate, which allows you to pair up with an iPhone device.

6.Prepare for a few weeks of work…
Depending on the time available, and your level of programming knowledge, set aside few hours everyday towards getting comfortable with iphone SDK. The hardest part for me is adjsuting to an unsafe language…after 5 years working in C#, its very difficult to get back into proper mindset for debugging crashes.

7. Submit you app to Apple:It's a straightforward process of zipping up the file, uploading it with a description, a large and small icon, and screenshots. If everything is alright then it usually takes Apple a week to approve the content and it finds itself in the store. If there is a problem, such as obvious bugs or Lite apps that are mentioned as demos or aren't fully featured, then this can take longer to review and ultimately reject. In this instance you can fix the issue and resubmit as many times as you like.