Tuesday, August 28, 2012

Writing your own SOAP based web service for iPhone Part 2

In this tutorial we will have a look at the pending part for creating a web service.

Summary from the past tutorial: We will be creating a web service in dot net that will be used to do some calculation and post the result in JSON format, we have already created the web service class and the response class in the past tutorial and in this tutorial we will be making the use of it.

Note for iOS developers: Web services are nothing but methods that we declare and implement in our .h and .m files the only difference is that they act as a media to pull the data from the server and present it in a particular format. JSON is nothing but a string representation of the data that you pull from a server.

For our first step we will have a look at simple web service which would accept a parameter from the user and return the data entered by the user in JSON.

Select the .cs file of the web service and just add a function to print the data entered by the user, for this you should know the syntax of C# and I am sure if you have a look at the syntax for creating function then it would be a piece of cake.



Code Explanation: First I am giving memory to the response class, since it’s the response class that we will be using to print any kind of success or failure message to the user.

In the second line of code I am having a check whether the user has entered some data or not and If not then in that case what I am doing is with the help of the properties in the response class I am notifying the user that something is pending.

Note: In C# the properties can be accessed with the help of the DOT operator.



If the user has entered the required filed data then the code knows what to do and will throw the JSON response accordingly filling in all the properties from the response class and displaying the appropriate data to the user.

The final step is to convert the output in JSON format and to do this I am using the JavaScriptSerializer class which has a unique method named Serialize to convert an object in JSON format as per the data given in the object. So again cheers to dot net and Microsoft for such beautiful function.

Note: The concept is pretty much straight forward:

-    Whatever data has been entered by the user goes through the validation code.
-    If there are no issues in the validations I proceed with my normal execution.

-    During the execution process I fill in the properties of the response class so that later I can encapsulate them in JSON string.

-    Encapsulation of the JSON string is done with the help of JavaScriptSerializer class Serialize method which comes from the framework using System.Web.Script.Serialization.

The last task is to run the web service and this is done with the help of a small play button that you can see above, asp.net will automatically create a new development server for your application and will run your application.



Note: When you are done with creating the web service do remember to host these web service on your companies test server so that you can test the services and do stuff and once you are done then host these services to the live server.

When you hit the run button you will see a small pop up indicating that the ASP.NET has loaded your application in its default development server which is used by the  dot net developers for testing the code that they have wrote.



After running the application you will see that the application will get loaded in your default web browser (Chrome or Safari etc) and will look something like the one given in the below image.



From the list of the service we have to select the web service that we want to test locally and since we have created the print something web service its time to test the web service so click on it and you will see a page which would look something like the one given below



Given below is the explanation of what you are seeing in the image



Now let’s try to hit the web service without entering any data in the parameter box and see what kind of response we get from the service




Response Explanation: As you can see from the response you have an ErrorCode which is screaming that you have forgot to enter some data inside the parameter box and all the other response flags are 0 since they don’t have any data to display.

Now let’s try to hit the web service by entering some data in the parameter box.




And when you hit the invoke button then let’s see the response




Response Explanation: As you can see now the response seems to be bit different from the earlier response, SuccessFlag is 1 which means that the code has executed successfully and we have the response value filled with the data that the user has entered in the parameter box.

So as you can see how simple the entire scenario was, similarly you can prepare the code for your calculator service as well. 

Given here is the updated code copy of this project with basic calculator functions, and given below is the snap shot for the same.



If you want to know how to call these services from iphone when they are successfully hosted in any web server then you can refer this tutorial of mine which I wrote earlier and if you are having any sort of queries then do let me know via mails or via comments.

Join us on facebook iPhone by radix Facebook group.

Until then Happy iCoding and have a great day.

Monday, August 27, 2012

Writing your own SOAP based web service for iPhone



Part 1: Many of the times I have seen that in companies it is expected that the ios developer should know how to develop the web services for their iphone application and iPhone developers after doing lots of hard work in iphone technology they get stuck with how to develop web services for their ios application so this tutorial is an effort took by me to make the iOS developer understand how to develop a simple web service in dot net.


Note: By default any web service that you create in dot net is a SOAP based web service whose response is in XML format, but JSON is considered more flexible as a response so I will teach you that as well the tool that I will be using to create the web service is visual studio 2010. For creating web services in dot net it is compulsory that you should know the base language C#.

Now your main task is to create a web service so for creating a web service you need to add the web service file here which is a very easy task.

So let’s get down for creating a simple SOAP based service.


Step 1: Visual studio is a tool from Microsoft which is used to create business class application using C# as the base language. You can launch visual studio by typing devenv command in run of by directly pressing the visual studio icon from your desktop.

After you click the visual studio(VS) icon you will see a screen in front of you from their you have to select the File menu and from File menu select the New - > Project given below is the snap shot that will guide you regarding the same.



After you select the new project you will be asked various options like for which environment you would like to create you new project is it for desktop, console or web from all the given options you have to select ASP.NET Web Application and don’t forget to mention your project name which is given at the bottom of the screen I have given the name DemoServices.





After filling in all the details click the OK button. 


And if you see a screen just like the one given below then congratulations you have successfully created a web app. 






Step 2: The best advantage of using visual studio tool is that it has each and everything structured with itself and there is a systematic way of handling files for various purposes.

For adding the web service file right click your project name in this case DemoServices there will be a menu in front of you from that menu select the Add option, the Add option will have several submenu items in it from those sub menu items select New Item




After you select New Item there will be a form in front of you asking what kind of file you want to add in your project. Select the web service file from the list which will be present somewhere at the bottom select it give the web service an appropriate name and save it. The extension of the web service created in dot net is asmx which means active server methods.





After giving a meaningful name to you webservice hit the Add button after you do this you will see a screen like the one given below





And if you are seeing this screen then congratulations you have learned how to add a web service file into dot net project. 

By default there is the HellowWorld web service in your project and when you run the application the output will be in XML format and not JSON so in the part 2 of this tutorial we will learn how to create some other functions which we can use as per our application needs and display the output in JSON format.

Dot net follows a code behind model approach hence when you add the asmx file you will be seeing one more file with the extension .cs and this is the file were all the coding will take place hence separating the code from design.

Step 3: Given below is the image which contains few basic details regarding the code snippet and some comparison with Objective C language so that iOS developers can understand.





As I have said earlier that by default if you run the web services then the output will be in xml format so to convert the output in json format you need to import two namespaces (just like framework in objective c) in C#, the name of those namespaces is given below



We have to keep a note of it that the web services will be called from a hand held device so it’s very important for the developer to know any kind of error messages or success messages from the server side and to do this I have my own procedure what I do is I create a response class with some properties and assign values to these properties and throw the appropriate response depending upon the code scenarios.

Step 4: We will be creating a response class so that whatever response is collected after the execution it is stored in the response class and is returned back in JSON format to us.
So to create the response class you need to add a .cs (.cs indicates that the given file contains some code in it with c sharp as the base language) class file in your project the same way you added the web service file.






Hit the Add button and the file will be added in your project.
It’s time to code for the response class I have just added three properties in the response class which are as follows:

-    ErrorCode: This property will be used to print exception messages.

-    SuccessFlag: This property will be used to print the success message which will be 0 for failure and 1 for success.

-    ResponseValue: This property will be used to print the result of calculator operations.

Given below is the snap shot in which I have displayed how what is the code to write properties in C# with code explanation




Step 5: Alright then that would be it for this session of the tutorial in the next session I will show how to use this response class. Also you can download the code till now from here.

This code is only workable in visual studio in the next tutorial we will discuss how to work with the response class. I have used visual studio 2010 for this demo.

Some bullet points on web services

- Web services are created only to communicate with the server.


-         - Web service can be made in C#, PHP and Java.
   -  While creating the web service the developer who is creating the service should keep a note that the required value in the web service is validated like email, user id or date etc.

-        NULL value should not be returned from web service.

-    Web services are nothing but functions just like the normal instance methods that we create while developing any application the only difference is that they are used as a media for communication between the web server and the hand held devices.

I hope that you have understood the basic concepts of creating SOAP based web services in Dot net and in case if you have not then feel free to contact me via mail or via comments.

Join us on facebook iPhone by radix Facebook group.

Until then Happy iCoding and have a great day. 

Saturday, August 25, 2012

Get Profile Image from Facebook

In this post we will learn on how to get your the profile image from facebook.

You may also refer the tutorial 1 and tutorial 2 of the facebook series.


Note: In order to for this tutorial to work you should have the FBGraph API and JSON API in your project folder.


Step 1: Create an empty application with an image view and a UIButton which would look something like this




On the hit of the button we will call the facebook graph api and will get the users profile image from facebook.


Step 2: Create the function that will be called on the button and associate it with its touch up inside event




- (IBAction)displayFBGraphPopup:(id)sender
{
    showActivityIndicator();
    objFBGraph = [[FbGraph alloc]initWithFbClientID:FbClientID];
    
    //mark some permissions for your access token so that it knows what permissions it has
    
    [objFBGraph authenticateUserWithCallbackObject:self andSelector:@selector(FBGraphResponse) andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins,publish_checkins,email"];
}




Also do remember to add the FBGraphResponse method which will provide you all the necessary detail of your account



- (void)FBGraphResponse
{
    @try 
    {
        if (objFBGraph.accessToken
        {
            SBJSON *jsonparser = [[SBJSON alloc]init];
            
            FbGraphResponse *fb_graph_response = [objFBGraph doGraphGet:@"me" withGetVars:nil];
            
            NSString *resultString = [NSString stringWithString:fb_graph_response.htmlResponse];
            NSDictionary *dict =  [jsonparser objectWithString:resultString];
            
            self.userID = [NSString stringWithFormat:@"%@",[dict valueForKey:@"id"]];
            
            
            [self performSelectorOnMainThread:@selector(getProfilePic) withObject:nil waitUntilDone:NO];
            
        }
    }
    @catch (NSException *exception) {
        UIAlertView *objALert = [[UIAlertView alloc]initWithTitle:@"Alert" message:[NSString stringWithFormat:@"Something bad happened due to %@",[exception reason]] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [objALert show];
    }
    
    
}



Step 3: In the FBGraphResponse their is one method named getProfilePic which i am calling on the main thread and where all the code to get the profile image of the user is written.




- (void)getProfilePic
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", self.userID]];

    NSData *tempData =  [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url] returningResponse:nil error:nil];
    UIImage *FBimage = [UIImage imageWithData:tempData];
    self.imgvprofileImage.image = FBimage;
    hideActivityIndicator();
}



Code Explanation: To get the profile image of the user their is one URL provided by the facebook where if you enter the user id then you can get the profile image.



Step 4: You can even get your friends profile image just like this i.e get all your friends by using the keyword "me.friends" and then select any one friend from the list and supply his facebook id in the above picture URL that's all


Step 5: Add view controller view to the iPhone window by selecting the app delegate file. Run the application and press the GetFBProfilePic button enter your credentials and wait for sometimes after that you can see your profile image just like the below image.




I hope this tutorial has helped you out in getting the profile image from facebook and in case if you have any sort of queries then feel free to ask them via mail or via comment

You can download the source code from here


Join us on facebook iPhone by radix Facebook group.

Happy iCoding and have a great day


Post Data on your friends Facebook wall


Important Message : Facebook has updated the Graph API and as per their Feb 6 2013 norms you cannot post data on your friends wall like the way it's mentioned in the below post, but you have to use the feed dialog to post the data.

Removing ability to post to friends walls via Graph API 
We will remove the ability to post to a user's friends' walls via the Graph API. Specifically, posts against [user_id]/feed where [user_id] is different from the session user, or stream.publish calls where the target_iduser is different from the session user, will fail. If you want to allow people to post to their friends' timelines, invoke the feed dialog. Stories that include friends via user mentions tagging or action tagging will show up on the friend’s timeline (assuming the friend approves the tag).
For more info, see this blog post.

In this post we will learn now to populate all your friends name in the table view and then we will be selecting any one friend from the list and we will be posting the data on his/her wall.

Note: I will be upgrading my part 1 tutorial so that I can cut short the detailing part and jump right to the code, so in case if you have missed the action you can visit part 1 of this tutorial.

Revision of tutorial 1: Earlier in tutorial one I have created a view based application which will provide me with the facebook graph api pop up and when I enter my credentials I receive a valid access token with the help of which I am able to post some text on my wall.

 If you are creating an application for any smart phone and want that application to post some messages on facebook then in that case you have to register your application on facebook and get the application ID, with the help of application ID facebook is able to identify that something has been printed or uploaded on your wall with the help of a registered application. It will also display the application name that printed the text of uploaded a file into your facebook wall.

So how do you register your application with facebook ? Well you can read all about it from here

Step 1: Create an empty application in Xcode with two view controller.

- First view controller will call the facebook graph api and will populate the table with the name of your friends and when you will select any one friend on who's wall you want to post data then in that case you will navigate to the second view controller.

- On the second view controller their will be one text view on which you can write the text that you want to post on your friends wall or navigate back to the first view.


Step 2: I have used few code from the tutorial 1 on facebook so i am directly jumping to the response method of the graph API.

When you receive the response in the FBGraphResponse method then earlier to get our information we were using the "me" keyword but now we want to get the list of our friends then in that case you have to use the keyword "me/friends". By using this keyword you will get all the names and facebook ID of your friends in JSON format which you can parse and display the name on the table view.

- (void)FBGraphResponse

{

    @try 

    {

        if (objFBGraph.accessToken
        {
            [self loadAlert];
            SBJSON *jsonparser = [[SBJSON alloc]init];
            
            FbGraphResponse *fb_graph_response = [objFBGraph doGraphGet:@"me/friends" withGetVars:nil];
            
            NSString *resultString = [NSString stringWithString:fb_graph_response.htmlResponse];
            NSDictionary *dict =  [jsonparser objectWithString:resultString];
            
            friendNameArray = [NSMutableArray arrayWithArray:[dict valueForKey:@"data"]];
            [fbfriendsTableView reloadData];
            
            
        }
    }
    @catch (NSException *exception) {
        UIAlertView *objALert = [[UIAlertView alloc]initWithTitle:@"Alert" message:[NSString stringWithFormat:@"Something bad happened due to %@",[exception reason]] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [objALert show];
    }
    
    
}




Code Explanation: With the above code you are asking the graph api to get the list of all your friends.

Step 3: When the above code will execute it will populate your table view with the list of all your friends from facebook, so when you select any one person name from the list you should move to the second view controller, so you will write some code in the did select row at index delegate method of the table view in which you will create the object of the second view controller and will push that view in the iPhone window

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    MessageViewController *objMessageVC = [[MessageViewController alloc]init];

    objMessageVC.friendID = [[friendNameArray objectAtIndex:indexPath.row] valueForKey:@"id"];

    objMessageVC.title = [[friendNameArray objectAtIndex:indexPath.row] valueForKey:@"name"];
    
    objMessageVC.graphref = objFBGraph;
    
    [self.navigationController pushViewController:objMessageVC animated:YES];
}




Code Explanation: I have made few properties in the MessageViewController class which will help me to post the data on my friends wall.



Step 4: In the MessageViewController i am having one method that will help me to post data on my friends wall


- (IBAction)postButtonClicked:(id)sender

{

    if ([[messageTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]!=0

    {

        NSMutableDictionary *variables = [[NSMutableDictionary alloc]init];
        [variables setObject:messageTextView.text forKey:@"message"];
        
        [graphref doGraphPost:[NSString stringWithFormat:@"%@/feed",self.friendID] withPostVars:variables];
        
        UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Data Posted on friends wall" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [objAlert show];
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }
    else {
        UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Enter data to post on wall" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [objAlert show];
    }
   
}



Code Explanation: In the first line of code i am checking if the user has entered some data on the text view or not.

- In the second line of code i am creating a mutable dictionary which will post the data on the friends wall.

- graphref is the FBGraph reference from my first view controller with the help of which i can call the graph api method to do post.

- And finally when your post is done you will be navigated back to the main view containing the list of your facebook friends.


Step 5: Alright this is our favorite step, we are all set and done to launch our application on the iPhone simulator. So add the first view controller view to the iPhone window and hit the run button.


























"The source code of this post has been disabled and will be posted soon"

You may follow our facebook group.

I hope this post has helped you out in understanding the concept if you have any questions or queries then feel free to contact me via mail or you may enter your queries as comments,

Until then Happy iCoding and have a great Day.