Building and Consuming Web services in Windows phone 7

8 Comments

this post doesn’t assume that u have any background on what the services is , so let’s start with a simple definitions

Service-oriented architecture :

simply it’s when your architecture is divided into separated components of code each one have it’s own functionality and they communicate together through a standard protocol of communication  , so these services or components can communicate interoperably also each component can serve multiple clients so it can be reused from different domains

Main benefits from SOA  

  • interoperability : for example a Java based project could use a .net based web service , because the use same communication standard
  • reuse : let’s assume a translator web service written once and could serve   millions of applications ( phone , desktop , web applications )
  • scalability  and agility : the same translator web service when i change in it’s functions or add new dictionaries or languages i don’t need to contact all the clients that use this service to rechange their code . i can just change the service and it’s changed in all clients because they don’t copy the code they only use the service . as long as i keep the same contract

WEB services : 

it’s a standard way for communication between web based applications in two  devices over a network (internet ) using XML , SOAP , WSDL  . XML is used to tag data and SOAP is the protocol of sending data  and WSDL is the web services describing language used to describe the available webservice . unlike normal web applications  WEBservices don’t need a browser also it doesn’t offer a GUI

web services examples :

  • bing search service
  • Microsoft translator service
  • IMDB service
  • AMAZON services
  • Twitter / Facebook services
  • Google API services

some drawbacks of WEBservices :

  • internet connection is required
  • transfer of large data across the internet may affects the performance

WCF services : 

a part of the .NET Framework that provides a unified programming model for rapidly building service-oriented applications that communicate across the web and the enterprise.

WCF ABC : 

  • address : it’s the uri of the service or where you can find the service on the web
  • binding : Specifies how a service is accessible. In other words: how the two parties will communicate in terms of transport (HTTP , TCP ,NamedPipe , Peer2Peer ,MSMQ)
  • contract : it’s simply what the service can do  ( the data and methods that the service can provide )
and now comes the Fun Part

DEMO1 : Building a WCF service:

open microsoft visual studio and open a new project
from the open window choose C# , WCF  and from the left choose new WCF service
after creating the new project  you will find the project explorer file called IService.cs
which is the Interface the service  the “web contract”  mentioned before which contains all the methods and data variables
that the service offers
methods offered by the services their definition is written and  followed by [OperationContract]
to add a new method in the service  add the function definition in the Iservice.cs  file followed by [OperationContract]
and in the file  service1.cs  add the function code inside the service1 class that implements the Iservice1 interface   
now you can run the service this is the landing page of the created  service in which you can find the service address from the service url of written in the page

DEMO2 : Consuming a WCF service from Windows phone 7 :

this will be a sample demo on how to consume a webservice in windows phone 7

the only difference between normal consumption of webservices  in WP7 and in any normal application

is that in normal application the communication is synchronous  ( application calls web services and services responds in the same time to the application )   but in WP7 it’s asynchronous communication ( in which when windows phone calls the webservice the response in not in the same time but when the web service is done with the response it fires an event in the windows phone and we need to write in the event handler the code that needed to utilize the response ) don’t get confused with the above comparison , it will be elaborated in the code below

to consume a webservice , let’s take for an example microsoft translator web service which we can find on this link

http://msdn.microsoft.com/en-us/library/ff512435.aspx

the service uri  (adress) is : http://api.microsofttranslator.com/V2/Soap.svc

now open a new windows phone project

from the project explorer right click the project icon and add service reference

copy paste the service URL :  http://api.microsofttranslator.com/V2/Soap.svc   in the address field and click Go

then change the namespace to  TranslatorService for example  in which all the Generated code will be under this namespace

once you added a reference to the web service now you can create new object of the service client class this object you will use it to call all the methods of the service

so open the mainpage.xaml.cs file and let’s write some code

let’s assume that the program that we are writing will translate  the sentence in the textbox1   in french and show it in a text Block called textblock1 when we click a button called button1

from the toolbox drag  a textbox  textblock and a button  , it’s supposed to look like this  after changing the page title and subtitle and labels of the components

double click the button to handle the on click event

in the on click event  , initialize a new object from the service  by writing the following code :

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            TranslatorService.LanguageServiceClient myclient = new TranslatorService.LanguageServiceClient(); 

        }

after this myclient object is the object that i’ll use to call all the service methods

now we are going to call the translateasync  function to translate  it takes appid , text , from , to , contenttype , category

you can create your own appid or just feel free to use my temp one i’d generated

you can see the function documentation in the service website

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            TranslatorService.LanguageServiceClient myclient = new TranslatorService.LanguageServiceClient();

            myclient.TranslateAsync("5F5CBEB15E4D9847AEB2C93B525EAC9B2A89465", textBox1.Text, "en", "fr", "text/plain", "general");
        }

we know that when the service is done with the response  a translatecompleted  event will be fired so we will add to this event a new event handler  with arguments inside the <>  and  the function name to be executed between the ()

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            TranslatorService.LanguageServiceClient myclient = new TranslatorService.LanguageServiceClient();

            myclient.TranslateAsync("5F5CBEB15E4D9847AEB2C93B525EAC9B2A89465", textBox1.Text, "en", "fr", "text/plain", "general");

            myclient.TranslateCompleted += new EventHandler<TranslatorService.TranslateCompletedEventArgs>(translatecompleted);

        }
  • <TranslatorService.TranslateCompletedEventArgs>  is the event args to be passed to the invoked function when executed 
  • tanslatecompleted is then name of the function to be executed  of the new event handler 

and we will add the function implementation in a separate function

        private void translatecompleted(object obj , TranslatorService.TranslateCompletedEventArgs e )
        {

            textBlock1.Text = e.Result.ToString();

        }

the object ” e ” of type  TranslatorService.TranslateCompletedEventArgs

contains the event arguments and it’s attribute Result contains the results of the invoked method in the webservice

which will be the translated text which then we will convert it to string and display it in the textblock1

the whole file would look like this :

now we are done let’s compile Run and try to see if there will be any bugs

now you are supposed to know:

  • what’s the SOA , and webservices , WCF services
  • how to build a WCF services
  • how to consume a web service in windows phone 7 applcations
imagine the unlimited number of applications that you can build and creative ideas you can generate depending on existing webservices that gives u a lot of capabilities
and always remember those available services when Generating ideas for WP7 applications
for any Questions or feedback don’t hesitate to ask me here or  on twitter @hadyelsahar 
and to keep updated with all Microsoft  similar Events  follow the hashtag #mspegypt and the twitteraccount   @mspegypt  on twitter  or our Fanpage
Advertisements

NameSpaces “using namespace std “

Leave a comment

actually most of us when beginning to write a C++ code for example we write

using namespace std ;

but most of us doesn’t recognize what does that mean and what’s the Namespace  so this topic basically will talk about namespaces

what’s the NAMESPACE :

it’s and entity that can group inside it a number of classes , object and functions . it’s name is divided into two section ” name ” , ” space ” so actually it’s a space designed for the name of the variable , to prevent the collision of names , suppose you have a function called connect ()  and you want to make a newer version of it inside the same File , and you don’t want to go through alot of naming Connect_new , Connect_newer  …etc so we assign a namespace for  each one

to access elements inside the name space we need to use the operator  ” :: ”  ;

for example

namespace  mynamespace
{
int x , y ;
} 
void main () {
mynamespace::x ;
mynamespace::y ;
}

multiple name spaces in the same file :


more things that make naming collision :

if you are including two header files, those header files have a common function naming inside it which function will get  executed when called ?  acutally nothing will get executed and and error appears calling

 error C2084: function 'connect()' already has a body

the using operator :

using operator is a keyword that introduces a certain namespace to a specific region so when you write

using namespace mynamespace  ;

you can call connect function without using the operator ::

mynamespace::connect () ;
using namespace mynamespace ;
connect() ;    // it should work now  =)

Namespace STD :

all standard libraries inside C++ standard library lies in the name space std , so we  always write the name space std to call the attributes at once  instead of writing

std::cout<<"hellow world " ;
std::cin>> x ;
using namespace std ;
cout <<"now no need to use std:: " ;

that’s it , this is acutally every thing about the explanation of ” using namespace std ; ” for any further questions  don’t hesitate to ask here or DM me  i always check my DMs  @hadyelsahar

Linked Lists in C++

Leave a comment

First of all :

working with linked lists requires a good knowledge about pointers so if you still finding pointers is a hard topic you can practice out this topic
linked listsLinked lists are type of data structures :

In computer science, a linked list (or more clearly, “singly-linked list”) is a data structure that consists of a sequence of nodes each of which contains a reference (i.e., a link) to the next node in the sequence.

source :wikipedia

so the linked list is a type of datastructure that can stand alone or used to create other data structures it consists of Nodes and each node has the reference to the next node ie : “linked to it ”  until the final node where it doesn’t have anything to point to

you can Create a linked list using Classes or Structures but we are using structure and may it be a good thing just to remember how to deal with structures

here’s a little example about how to initialize a Linked list Item and fill any of it’s data

#include <iostream>
#include <string>
using namespace std ;

 struct  listItem {
 string  name  ;  // name of the item 
listItem * next ;  // pointer points to the next node 
 } ;

void main (){
listItem * head ; // pointer will always points on the first node
listItem * myListItem ;   // creating a new instant from ListItem  
myListItem.name = " Greetings Egyptian Geeks "  ; //filling it's data 
cout << myListItem.name ;
head = &myListItem ;  // making the pointer to the adress of the First Item
}

download from here

simple enough !! , it’s a normal Structure  ,  So let’s Move to the NEW part !

Adding New Item to the beginning of the LinkedList

listItem   myListItem2 ;   // creating a new instant from ListItem 
 myListItem2.name = " add me to the beginnning  "  ; //filling it's data 

 myListItem2.next = head ; // making it point to the Next item -that was first- 

 head = & myListItem2 ;  // making the Head pointer points to the new head one

Adding new element to the End

mylastListItem.Next = &newLastItem ;

Addin new element in the Middle

we have two list items listitem1 and listitem2 we want to put middleListItem in the middle we create a new temp pointer to save the adress of listitem2 in it  – as we can’t access it unless by  listitem1.next

temp = listitem1.next ;
listitem1.next = & middleListItem ;
middlelistItem.next = temp ;

Delete elements after a specific number of nodes (n):

temp = head ;
For( i =0 ; i< n ; i++ )
{
temp = temp->next ;  //  hint : there's no something called *temp.next
}
temp = Null ;  // we usually check Temp.next = null then this is the final node

of course this topic doesn’t cover all the operations done on the linked lists , it’s all about the concept but other operations don’t contain any new concepts it’s a Mix between conditions and Pointers

for any suggestions or adds , feel free to post below  or DM me on twitter @hadyelsahar i do always check my DMs

Hello world program in C++ & VS2010 “D&A episode #1”

1 Comment

before going into code we need first to settle some important informations

C++ is originally called C with classes so it’s really a subset of C  , however C++ have a lot more Features than C ; including some basic things like inputs and outputs

do you mean that Scanf () and printf() and getche()  works in C++ ? yeah they do  =)  actually all C functions do work on C++

Great  so that means we don’t need to read about functions , arrays and all the C stuff ,,, yeah however we will elaborate some important things and offcourse things related to data structure

so let’s  code :

in the begining this is a let’s describe how to configure visual studio for a hello world program ,and a sample code to make a simple hello world program

the source code project  from here : Download

  • open new project  cntrl + shift + N
  • click new win 32 console application
  • click on console application  and empty project
  • then on the right click on the solution explorer
  • if you cant find the solution explorer click show it from View next to file in the menu  or click  cntrl +alt + L
  • and write the following in the  main file

  • #include <iostream>
    using namespace std ; 
    void main () { 
     cout << "hello world " ; 
    }
  • click cntrl +f5 to run

NOTES :

  • #include <iostream>    // this to include the libraries for console output  .. has alot of similarities with stdio.h “standard input and output” library in C
  • using  .. this keyword in C++ is like we say assume that we are using , the following so we write using namespace std  , in order not to say  std::cout  and write cout  alone , (we will explain what’s the name space later on )
  • cout is like printf  it takes a string and prints it into the console

How to get a free Microsoft Visual studio 2010

2 Comments

microsoft visual studio 2010

Hello to my new  series of  lessons  “data structure and algorithms using C++ and Ms VisualStudio2010 “

before going through algorithms and Data Structure or even C++ we need First to install an IDE : “integrated development environment ”

is a software application that provides comprehensive facilities to
 computer programmers for software development    src : wikipedia 

the most of  IDEs  mainly consists of  :

  • text editor
  • compiler
  • debuggerr
  • design tools

the IDE main benefit is it’s integrates all the processes of writing code in one program which is the “IDE” as well as configuration to the files and writing a preparation code to let developers start developing at once

some examples of an IDE ,

in the early ages  people used  the command line tools

lately :

Microsoft visual studio  on windows platform  , Eclipse , Netbeans , ActiveState Komodo .

how to get a free microsoft visual studio :

for any user :

you can download visual studio 2010  express version it’s for free but it has  less feature than the other version but for a beginner developer , it doesn’t matter  : http://www.microsoft.com/express/Downloads/#2010-Visual-CPP

and here’s a little comparison about different visual studio version

for students  :

if you have a  live@edu email , -if you don’t have one contact your campus –  you can logi nto Microsoft Dream Spark then you could download a punch of developers stuff including microsoft visual C++ express which is already free as well as Microsoft visual studio 2010  professional edition which is not .

for students in computer science and computer engineering   :

contact your campus MSP –microsoft student partnersfor an MSDNAA account this MSDNAA account provides alot of Free Microsoft stuff only for students that helps them in their study like : windows 7 professional , Ms visual studio professional , expression studio version 3 & version 4  ….etc . if you already have one you could login through here : bit.ly/MSDNAA_account   (only for ASU , engineering Campus  )

….. to be contiued