Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Developing a mobile PhotoBlog with .NET

We will create an application for Windows Mobile that will allow people to take pictures with their cell phones and send them directly to a PhotoBlog, using a web service.

Developing a mobile PhotoBlog with .NET

 

It is not any news that Blogs are part of our life. Everybody has or follows many of people’s life routines using  the Internet. The PhotoBlog, specifically, is the most recent item in these digital “diaries”, where people tell a little bit of their history using pictures taken with their digital cameras.

In this article, we will show how we can simplify these people’s lives a little. We will create an application for Windows Mobile 5.0 that will allow people to take pictures with their cell phones and send them directly to a PhotoBlog, using a web service. To do so, we will use Compact Framework 2.0 and Visual Studio 2005 new features.

 

Preparing the environment

Let us begin our system’s development creating a solution (set of projects in Visual Studio) that will contain our projects. In this article, we will create three different projects: (1) an application for Smartphone that will allow the user to send pictures directly from his cell phone; (2) a Web Service to provide the photographs upload services and (3) a site to display the PhotoBlog, as shown in Figure 1.

 image001.png

Figure 1.  Applications that compose the PhotoBlog project

 

To go along with our development, you will need to install Microsoft Visual Studio 2005 (www.microsoft.com/visualstudio) and SQL Server Express Edition (msdn.microsoft.com/sql/express) or even SQL Server Standard.

After having prepared these technologies, the first step is the creation of the web site that will display the photographs. We will call the project “PhotoBlogger”. Next, we will create two more projects, one for the web service and another for the Smartphone.

For the creation of the web site, we must open Visual Studio and select the File>New>Web Site option to create an ASP.NET project, according to Figure 2.

 

image004.jpg

Figure 2. Creating a ASP.NET project

 

Following we will create the database to be used in the application.

 

Creating the database

Before we create the site, the strongest suggestion is to define beforehand the database scheme. We can do this directly at Visual Studio. For that, we shall follow these steps:

 

1.      First, create a new database using the  Server Explorer, as in Figure 3. In case the Server Explorer is not visible click the View>Server Explorer option in Visual Studio 2005 menu bar.

 

image005.png

Figure 3. Connecting to SQL Server

 

2.      By selecting Create New SQL Server Database, the window in Figure 4 will be displayed. The fields of the window are sufficiently simple, and we shall fill it in as in the Figure. Notice that the name of the server will be the name of your machine (in this example, ASUS).

 

image007.png

Figure 4. Creating the database

 

3.      We will also create the tables in a visual manner. For this, still in the Server Explorer, create a new diagram, in accordance to Figure 5. Using this diagram, we will be able to create the tables and the relationships of our database in a visual manner, without using SQL commands.

 

image009.png

Figure 5. Creating the tables’ diagram

 

4.      Having done this, we will divide the database in three tables: one table (Blogs) to store information about the PhotoBlog, one table (BlogEntry) that will store information about the photographs sent to the PhotoBlog and a table (EntryComment) that will contain the comments made by the users about a photograph.

 

We will start by the Blogs table. Add a table following the scheme in Figure 6.

 

image011.png

Figure 6. Structure of the Blogs table

 

In this table, we will store the name and the description of a PhotoBlog and the information of the user who is the creator of this PhotoBlog. Notice that the ID key field must be specified as Identity in the table properties so that the SQL Server automatically attributes its value.

After, create a table that will store the photos (BlogEntry) like in the structure seen in

 

Figure 7:

 

image013.png

Figure 7. Structure of the BlogEntry table

 

In this table, we will store the date and a comment about an image that was sent to the server by the author of a specific PhotoBlog. Notice that the Picture column is of the Image kind since, in the SQL Server, there is already a special kind of data to store images, which will satisfactorily facilitate our work and, of course, we are going to use it.

Notice that the ID key field is the table Identity. Proceed in the same way as in the Blogs table we created previously.

Now, all we lack is the table that will store the comments about our photographs made by other users of the site. Create the EntryComment table as shown in Figure 8.

 

image015.png

Figure 8. Structure of the EntryComment table

 

The ID key field is also the table’s Identity. There. Our database scheme is ready. Save the project and Visual Studio will automatically create the tables in SQL Server. Let us now create the web service that will handle this database.

Project 1: creating the web service

The web service will be responsible for the PhotoBlogger “core”. The business of our site is very simple: a user may register to the site, register a PhotoBlog, and once authenticated, upload photos. Since it escapes the purpose of this article, we will not implement functions of a real PhotoBlog that are more complex, such as the PhotoBlog customization; register information update, among others. I leave it to the reader as an exercise in learning.

So let us begin the development of the web service. Initially, we must click File>Add>New Web Site. Select the ‘ASP.NET Web Service’ project kind and name it “PhotoBloggerWS”, as in Figure 9.

 

image018.jpg

Figure 9. Creating the Web Service project

 

After that, we will create the classes of our business. We will have three classes, Blog that represents a user and his PhotoBlog, BlogEntry that represents an entry (photo) in the PhotoBlog and EntryComment, which represents a comment made by a user about the photo. Figure 10 clarifies these classes. Observe that these classes correspond to the tables created in our database.

 

image020.gifimage022.gifimage024.gif

Figure 10. Web Service classes

 

Then add a new class to the project and add to that the code in Listing 1.

 

Listing 1. Business class code

using System;

using System.Web;

using System.Collections.Generic;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Drawing;

 

public class Blog

{

    public string UserName;

    public string UserPassword;

    public string BlogName;

    public string BlogDescription;

    public long ID;

    public string UserEMail;

    public string UserLogin;

}

 

public class BlogEntry

{

    public long ID;

    public byte[] PictureBytes;

    public DateTime Date;

    public string Description;

}

 

public class EntryComment

{

    public long ID;

    public string Comment;

    public string UserLogin;

    public DateTime Date;

}

 

I have kept all of the classes in a single file only for reason of simplicity. Feel free to place them in separate files.

Notice that in the BlogEntry class, the PictureBytes attribute contains the bytes of the image that will be passed using the web service. We will speak a little more about this technique in the course of this article.

Now we will create the service. In the project there is already a file named Service.cs that contains a method created automatically by Visual Studio (“HelloWorld”) to serve as an example. Delete it, for they will not be necessary.

Our web service has to expose methods to create a PhotoBlog, send a photo, send a comment and authenticate a user. Theses methods are sufficiently simple and all that needs to be done is connect to SQL Server and run the SQL commands that perform the desired work. So, let us follow these steps:

 

Step 1. Everything starts by obtaining a connection to the SQL Server

For this, add the code described in Listing 2. This code returns an active connection with the database since your connection string. Notice that you shall modify this connection string according with your local setup. Any doubt about the connection string, refer to the Visual Studio help or visit the site www.connectionstrings.com.

 

Listing 2. Obtaining an active connection with the database

private SqlConnection GetConnection()

{

    SqlConnection objConnection = new SqlConnection("Data Source=ASUS\\SQLEXPRESS;Initial Catalog=PhotoBlogger;Integrated Security=True;Pooling=True");

    objConnection.Open();

    return objConnection;

}

 

Step 2. Now we need to create a method for a user create a new PhotoBlog.

Also simple, it is enough for the user to inform the instance of a Blog object containing the information of his PhotoBlog and insert this object’s data in the SQL Server. This code can be seen in Listing 3.

 

Listing 3. The method that creates a new PhotoBlog

[WebMethod]

public Blog CreateBlog(Blog theBlog)

{

    SqlConnection objConnection = GetConnection();

    try

    {

        SqlCommand objCmd = new SqlCommand(

          "INSERT INTO [Blogs]([Name], [Login], "+

          "[EMail], [Password], [BlogName], "+

          "[BlogDescription]) VALUES (@Name, @Login, "+

          "@EMail, @Password, @BlogName, "+

          "@BlogDescription)", objConnection);

        SqlParameter parameter =

          objCmd.Parameters.Add("Name", SqlDbType.VarChar);

        parameter.Value = theBlog.UserName;

        parameter = objCmd.Parameters.Add("Login",

          SqlDbType.VarChar);

        parameter.Value = theBlog.UserLogin;

        parameter = objCmd.Parameters.Add("EMail",

          SqlDbType.VarChar);

        parameter.Value = theBlog.UserEMail;

        parameter = objCmd.Parameters.Add("Password",

          SqlDbType.VarChar);

        parameter.Value = theBlog.UserPassword;

        parameter = objCmd.Parameters.Add("BlogName",

          SqlDbType.VarChar);

        parameter.Value = theBlog.BlogName;

        parameter = objCmd.Parameters.Add(

          "BlogDescription", SqlDbType.VarChar);

        parameter.Value = theBlog.BlogDescription;

 

        objCmd.ExecuteNonQuery();

 

        return Authenticate(theBlog.UserLogin,

          theBlog.UserPassword);

    }

    finally

    {

        objConnection.Close();

    }

}

 

At this moment, we have only created the connection with the SQL Server and inserted a new Blog, using an “Insert Info” SQL command in the table of Blogs with the values of the attributes of this class. Once stored in the database, we reload the created Blog and return it in the method.

 

Step 3. With the Blog created, the user now needs authentication to send photographs ands comments.

The authentication will be made informing the user login and password. If it is made successfully, the web service shall return an instance of the ‘Blog’ class that represents the authenticated user’s PhotoBlog. This code is described in Listing 4.

 

Listing 4. User authentication method

[WebMethod]

public Blog Authenticate(string User, string Password)

{

    Blog objBlog = null;

    SqlConnection objConnection = GetConnection();

    try

    {

        SqlCommand objCmd = new SqlCommand(

          "select * from Blogs where Login=@login "+

          "and Password=@password", objConnection);

        SqlParameter parameter = objCmd.Parameters.Add(

          "login", SqlDbType.VarChar);

        parameter.Value = User;

        parameter = objCmd.Parameters.Add(

          "password", SqlDbType.VarChar);

        parameter.Value = Password;

        SqlDataReader objReader =

          objCmd.ExecuteReader();

        if (objReader.Read())

        {

            objBlog = new Blog();

            objBlog.ID = (long) objReader["ID"];

            objBlog.BlogDescription = "" +

              objReader["BlogDescription"];

            objBlog.BlogName = "" +

              objReader["BlogName"];

            objBlog.UserEMail = "" +

              objReader["EMail"];

            objBlog.UserLogin = "" +

              objReader["Login"];

            objBlog.UserPassword = "" +

              objReader["Password"];

            objBlog.UserName = "" + objReader["Name"];

        }

        objReader.Close();

    }

    finally

    {

        objConnection.Close();

    }

    return objBlog;

}

 

Step 4. Once authenticated, the user may add new entries (photos) to his PhotoBlog. This service is offered by the method described in Listing 5.

 

Listing 5. Method to send photos to the PhotoBlog

[WebMethod]

public void AddEntry(BlogEntry theEntry, long BlogID)

{

    SqlConnection objConnection = GetConnection();

    try

    {

        SqlCommand objCmd = new SqlCommand(

          "INSERT INTO [BlogEntry] ([BlogID], "+

          "[Picture], [Date], [Description]) VALUES "+

          "(@BlogID, @Picture, @Date, @Description)",

          objConnection);

        SqlParameter parameter = objCmd.Parameters.Add(

          "BlogID", SqlDbType.BigInt);

        parameter.Value = BlogID;

        parameter = objCmd.Parameters.Add("Picture",

          SqlDbType.Image);

        parameter.Value = theEntry.PictureBytes;

        parameter = objCmd.Parameters.Add("Date",

          SqlDbType.DateTime);

        parameter.Value = theEntry.Date;

        parameter = objCmd.Parameters.Add("Description",

          SqlDbType.VarChar);

        parameter.Value = theEntry.Description;

 

        objCmd.ExecuteNonQuery();

    }

    finally

    {

        objConnection.Close();

    }       

}

 

Here, again, nothing special, we only added the attributes of the object to the SQL Server. Notice that the PictureBytes attribute can be passed directly to the SQL Server due to its Image data type.

 

Step 5. Once a photo has been submitted to the site, it can receive comments from other users.

The method that allows the user to add comments to a photo is described in Listing 6.

 

Listing 6. Method to add comments to a photo

[WebMethod]

public void AddComment(EntryComment theComment,

  long entryID )

{

    SqlConnection objConnection = GetConnection();

    try

    {

        SqlCommand objCmd = new SqlCommand(

          "INSERT INTO [EntryComment] ([EntryID], "+

          "[Login], [Comment], [Date]) VALUES "+

          "(@EntryID, @Login, @Comment, @Date)",

          objConnection);

        SqlParameter parameter = objCmd.Parameters.Add(

          "EntryID", SqlDbType.BigInt);

        parameter.Value = entryID;

        parameter = objCmd.Parameters.Add("Login",

          SqlDbType.VarChar);

        parameter.Value = theComment.UserLogin;

        parameter = objCmd.Parameters.Add("Comment",

          SqlDbType.VarChar);

        parameter.Value = theComment.Comment;

        parameter = objCmd.Parameters.Add("Login",

          SqlDbType.DateTime);

        parameter.Value = theComment.Date;

 

        objCmd.ExecuteNonQuery();

    }

    finally

    {

        objConnection.Close();

    }       

}

 

Step 6. We need a mechanism to display the photos of a blog. The code for this feature is described in Listing 7.

 

Listing 7. Obtaining a blog’s photos

[WebMethod]

public List<BlogEntry> GetEntries(long BlogID)

{

   SqlConnection objConnection = GetConnection();

   try

   {

       SqlCommand objCmd = new SqlCommand(

         "select * from BlogEntry where BlogID=@BlogID",

         objConnection);

       SqlParameter parameter = objCmd.Parameters.Add(

         "BlogID", SqlDbType.BigInt);

       parameter.Value = BlogID;

       

       SqlDataReader objReader = objCmd.ExecuteReader();

       List<BlogEntry> objEntries = new List<BlogEntry>();

       while (objReader.Read())

       {

           objEntries.Add(FillEntry(objReader));

       }

       objReader.Close();

       return objEntries;

   }

   finally

   {

       objConnection.Close();

   }       

}

 

private BlogEntry FillEntry(

  SqlDataReader theDataReader)

{

   BlogEntry objEntry = new BlogEntry();

   objEntry.Date =

     (DateTime) theDataReader["Date"];

   objEntry.Description= "" +

     theDataReader["Description"];

   objEntry.ID = (long)theDataReader["ID"];

   objEntry.PictureBytes =

     (byte[])theDataReader["Picture"];

   return objEntry;

}

 

Here again, nothing special, we just created one more private method, the FillEntry, which creates an instance of a BlogEntry object from a DataReader.

It is interesting to notice also the kind of return, List, which creates a list of objects of the BlogEntry kind using the Generics feature available in the .NET 2.0. This makes our work a lot easier, for we do not have to create a specific collection class for this. Notice that the image is recovered by just placing its bytes in the PictureBytes property of the object created by the FillEntry method.

At the end of this procedure, you shall have a web service with the methods visualized in Figure 11. Now, let us make them work.

 

image026.gif

Figure 11. Our web service

 

Project 2: creating the site

It is not the purpose of this article to create a complete PhotoBlog site, but we will demonstrate how to use the web service and let the reader develop the presentation part (graphic interface) of the site how it better suits him. Along this article will be cited only the fields necessary in each page.

Before anything, add the reference to the web service in your project of the web site we have created in the beginning of the article. For this, right-click over the project and select Add Web Reference, as in Figure 12.

 

image028.jpg

Figure 12. Adding the reference to the web service

 

Selecting this option, the window in Figure 13 will open.

 

image030.jpg

Figure 13. Locating the web service

 

Choose the Web Services in this Solution option, then select the “service” web service and inform the name of the reference that will be created as “service”, according to Figure 14.

 

image032.jpg

Figure 14. Adding the reference to the web service

 

There. The Visual Studio creates a class called service.Service, which is the reference to our web service.

Let us create, next, some methods to call these methods of the web service and clarify their use.

First, it will be necessary to have, in the site, a page for the user to register and get a PhotoBlog to which he can send the photos. This page will collect the necessary data to instance a Blog class object and call the code of Listing 8.

 

Listing 8. Creating a PhotoBlog

protected void AddBlog(Blog theBlog)

{

    service.Service objService = new Service();

    objService.CreateBlog(theBlog);

}

 

Simple, is it not? All we do is call upon our web service’s CreateBlog method. To authenticate a user it is equally simple, all we need is a page where the user can fill in his login and his password and call upon the method in Listing 9.

 

Listing 9. Authenticating a user

protected Blog Authenticate (

  string Login, string Password)

{

    service.Service objService = new Service();

    return objService.Authenticate(Login, Password);

}

 

This code will return the user’s Blog, in case he authenticated successfully or null, in case of a failure. The Blog object returned will be used in the calling of other methods to identify in which Blog we want the operations to be performed.

For example, if we wanted to add a photo to the Blog, we should create a page where you inform which image and a brief description of it. This form shall perform the image upload and call upon the method in Listing 10.

 

Listing 10. Adding photos to a PhotoBlog

protected void AddEntry(Blog theBlog, string File,

  string Description)

{

    //Load the image

    System.Drawing.Bitmap objPicture =

      new System.Drawing.Bitmap(@"File");

 

    //Create a BlogEntry object

    BlogEntry newEntry = new BlogEntry();

    newEntry.Date = DateTime.Now;

    newEntry.Description = Description;

    //Get image’s bytes

    MemoryStream stream = new MemoryStream();

    objPicture.Save(stream, ImageFormat.Jpeg);

    newEntry.PictureBytes = stream.GetBuffer();

    //Add an entry to the PhotoBlog

    service.Service objService = new Service();

    objService.AddEntry(newEntry, theBlog.ID);

}

 

Notice that this method receives the Blog to which we want to perform Upload, the name and path of the uploaded image file and a description provided by the user for the photo.

In this method, first we load the image through a Bitmap class object and then fill in the attributes of a BlogEntry class object that will contain this photo’s information in the PhotoBlog. This object needs the image’s bytes so that it can be passed to the web service. To obtain these bytes, we create a stream in memory with the new image’s data and then pass these bytes to the newEntry object that represents the new entry that is being created in the PhotoBlog.

After, we merely call the web service and our photo will be sent to the server and stored in the SQL Server.

In the same way, to add a comment it is equally simple, just inform the data to the method in Listing 11.

 

Listing 11. Adding comments

protected void AddComment(string Comment,

  string Login, BlogEntry theEntry)

{

    //create the EntryComment object

    EntryComment objComment = new EntryComment();

    objComment.Comment = Comment;

    objComment.Date = DateTime.Now;

    objComment.UserLogin = Login;

    //Send to the database

    service.Service objService = new Service();

    objService.AddComment(objComment, theEntry.ID);

}

 

Another thing the site has to have is the exhibition of the list of photos of a user’s PhotoBlog. See the code for this feature in Listing 12.

 

Listing 12. Obtaining a PhotoBlog’s images

protected BlogEntry[] GetEntries(Blog theBlog)

{

    service.Service objService = new Service();

    return objService.GetEntries(theBlog.ID);

}

 

protected Bitmap GetBitamp(BlogEntry theEntry)

{

    MemoryStream stream = new MemoryStream(

      theEntry.PictureBytes);

    return new Bitmap(stream);

}

 

The GetEntries method returns the list of entries in the specified PhotoBlog. Notice that we still need to convert the bytes’ array into a Bitmap object so that we can treat it as an image. This procedure is done by the GetBitmap method that merely creates a Bitmap based on a stream in memory, which contains the image’s bytes that came from the SQL Server.

With this, we can create a site where the user may create PhotoBlogs, perform images uploads and add comments. I suggest to the reader, as an exercise, to add new functionalities to this service, such as removing and updating photos, for example.

Project 3: blogging from the Smartphone

Now let us move on to what interests us. Since we the service that we need is implemented, it is time to make it accessible using a device running the Windows Mobile 5. Through his mobile device, the user can take a photo and send it directly to the web site, using the same web service that we created previously.

The author prefers to use a Smartphone, but the reader may use the same code to make the same program in a PocketPC. In the Visual Studio 2005, right-click over the solution and choose Add>New Project, as in Figure 15.

 

image034.jpg

Figure 15. Adding a new project in the solution

 

When the Add New Project window appears, select Visual C# and, in Smart Device, select Windows Mobile 5.0 Smartphone. Select Device Application, inform the name of the project (“PhotoBlogger”) and, next, click on “ok”, as in Figure 16.

 

image036.jpg

Figure 16. Creating the project for SmartPhone

 

Our application will contain two forms. The first one will contain the main window, with the application title, name of the blog and the button to capture the photo. The second form will be responsible for the application setup, such as name of the user, name of the blog etc. Let us go.

 

The main form

In this form, the user can capture a photo, inform a description and send it to the blog. Start by adding a PictureBox that will display the photo to be sent. Adjust it so that it occupies the upper part of the form, modify its SizeMode property to StretchImage and its ID property to “pbPhoto”.

After, add a TextBox that will contain the description of the photo. Modify its Multiline property to True and its ID to “txDescription”. Modify its Text property to empty and adjust its size to occupy the lower part of the window.

Now, add a Label that will display the name of the blog on the upper part of the window, modify its ID property to “lbBlog” and modify its Text property to “Blog:”.

Finally, modify the Text property of the form to “PhotoBlogger”.

The menu will have only two basic functions. To capture and send the photo, to adjust the setup of the Blog and to leave the application. Thus, select the mainMenu1 object in the form and modify its ID property to “mainMenu”. After, create the menu according to Figure 17.

 

image037.png

Figure 17. Layout of the elements in the main form and Menus

 

Capturing the photo

The part of image capture could be a great problem due to the enormous amount of models of devices available in the market. The Windows Mobile 5.0, however, centralized all the photo camera access API (called Camera API) and now we can do, in a simple way, an application that uses the camera, which works in an independent way from the device.

This entire marvel is done by the CameraCaptureDialog class, available in the Windows Mobile 5.0. With it, we can control the entire process of image capture, being photos or videos, with sound or not, define its quality, file format etc.

It is available in the assembly Microsoft.WindowsMobile.Forms, so we have to add a reference to this assembly in our project. This is simple. Right-click over the References folder of the project, add the o assembly Microsoft.WindowsMobile.Forms and that is it.

The idea is that when the user selects the option to capture the photo, the standard window of the device will be displayed. Once the photo has been captured, we will open the main form and exhibit the image in the PictureBox. The user can then add a description and send the photo to his blog  using the Send option. Simple, is it not?

So, double click on the option from the Capture menu and type the code in Listing 13.

 

Listing 13. Capturing the photo

 

private void menuItem2_Click(object sender,

  EventArgs e)

{

    CameraCaptureDialog cameraCapture =

      new CameraCaptureDialog();

 

    cameraCapture.Owner = this;

    cameraCapture.Title = "PhotoBlogger";

    cameraCapture.Mode = CameraCaptureMode.Still;

    cameraCapture.StillQuality =

      CameraCaptureStillQuality.High;

    cameraCapture.InitialDirectory = @"\Temp";

    cameraCapture.DefaultFileName = @"picture.jpg";

 

    if (cameraCapture.ShowDialog() == DialogResult.OK)

    {

        Bitmap capturedImage =

          new Bitmap(@"\Temp\picture.jpg");

        pbPhoto.Image = capturedImage;

    }                       

}

 

In this code, first we create an instance for the CameraCaptureDialog and specify several attributes to inform how we want to make the image capture. The Owner property informs to the dialogue which control is calling upon the image capture dialogue and is important especially if another application requests the same dialogue, thus being able to warn the user which other application is using the same resource at that moment.

The Title property is only the name of the window that will make the image capture. This property is simply ignored in most of the Smartphones. The Mode property is the most important one. It informs what we intend to capture, that is, just photos (Still), mute videos (VideoOnly) or videos with sound (VideoWithAudio). Since we have selected the Still mode, the StillQuality property informs the desired quality of the picture. Here, we used high quality.

Each captured photo or video is stored in a file inside a specific folder that is informed in the InitialDirectory  and DefaultFileName properties, respectively. After the image capture, we create a Bitmap with the content of the file and exhibit it inside the PictureBox. At the end of this article will de be presented the visualization of an image in the mobile device.

 

Configurations

Before we send the photo to the site, we have to store some configurations necessary to the functioning of the web service. For this, we will create a new form to collect this information. Add a new form doing a right-click over the Smartphone project, select Add>Add Windows Form. Call the file “Settings.cs”.

Now add a Label control and modify its Text property to “Login”. Add a TextBox and modify its ID property to “txtLogin” and the Text property to empty.

Add another Label and modify its Text property to “Password:”. Add another TextBox, modify its ID property to “txtPassword” and the Text property to empty.

Finally, add two menu items, “Ready” and “Cancel”. In the end, your form shall be as in Figure 18.

 

image039.png

Figure 18. Settings form appearance

 

When the user clicks in Ready, we must close the window, informing that the user has confirmed the configuration. For this, double click the menu item Ready and type the code in Listing 14.

 

Listing 14. Accepting the configurations form

private void menuItem1_Click(object sender,

  EventArgs e)

{

    DialogResult = DialogResult.OK;

    Close();

}

 

We will also need two properties to obtain the values informed by the user in this form. We can do this by simply exhibiting the Text properties of the respective Textboxes. Then type the code in Listing 15 just below the method in Listing 14.

 

Listing 15. Properties of the configurations form

public string Login

{

    get

    {

         return txtLogin.Text;

    }

    set

    {

         txtLogin.Text = value;

    }

}

 

public string Password

{

    get

    {

         return txtLogin.Text;

    }

    set

    {

         txtLogin.Text = value;

    }

}

 

We will use this form whenever we need to inform the login and the password of the user in the site, in such a way that we may know to which Blog the photo will be sent.

 

Sending the photo to the Blog

The code to send the photo is equally simple. All we have to do is send the photo and the other necessary information to the site using the created web service. First, let us create a reference to the web service, repeating the same procedure that we have done to add the web service reference to our ASP.NET project.

Once created the reference, we need to have, in the application, the user login and password so that we may obtain his Blog using the Authenticate method of the web service. Therefore, add these three attributes to the class of the main form (see Listing 16).

 

Listing 16. Attributes of the class of the main form

private Blog myBlog;

private string Login;

private string Password;

 

Of course, the user will have to inform the login and password of his Blog. So, double click in the Settings menu (Figure 17) and add the code in Listing 17 to call upon the configuration form.

 

Listing 17. Calling the configurations form

private void menuItem5_Click(object sender,

  EventArgs e)

{

    Settings objForm = new Settings();

    objForm.Password = Password;

    objForm.Login = Login;

    if (objForm.ShowDialog() == DialogResult.OK)

    {

        Password = objForm.Password;

        Login = objForm.Login;

    }

}

 

Now that the user already has a way to authenticate himself in his Blog, it is time to send the photo. For this, double click the Send option to create a method that will be responsible for the sending of the photo. We will show how to send the photo in a sequence of stages:

1.      First, we must check if the user has informed his Blog’s login/password. For this, add the code in Listing 18 to the method we have just created.

 

Listing 18. Checking if the user has already informed Login and password

if (string.IsNullOrEmpty(Login) ||

  string.IsNullOrEmpty(Password))

{

    MessageBox.Show(

      "Please inform a Login and Password!");

    return;

}

 

In this section, nothing special. We will just check if any of the Login and Password attributes are empty or null.

 

2.      After we need to obtain the user Blog, using the Authenticate method of the web service. For this, add the code in Listing 19.

 

Listing 19. Obtaining the user’s Blog

Service objService = new Service();

myBlog = objService.Authenticate(Login, Password);

if (myBlog == null)

{

    MessageBox.Show("Invalid Login or Password!");

    return;

}

lbBlog.Text = "Blog: " + myBlog.BlogName;

 

Observe that it is practically equal to the way we used to authenticate the user in the site. Once authenticated, we will have the user’s Blog in the myBlog class attribute.

 

3.      Now we will create a new entry (new photo). Remember that due to web service’s image transfer style, we need to obtain the image’s bytes in order to be able to use a BlogEntry type object, which represents a new entry (photo) in the PhotoBlog. For this, add the code in Listing 20.

 

Listing 20. Creating the BlogEntry object

BlogEntry newEntry = new BlogEntry();

newEntry.Date = DateTime.Now;

newEntry.Description = txDescricao.Text;

MemoryStream stream = new MemoryStream();

pbFoto.Image.Save(stream, ImageFormat.Jpeg);

newEntry.PictureBytes = stream.GetBuffer();

 

Again, we create a memory stream and copy the bytes of the images there using the Save method of the image that is stored in the PictureBox.

4.      Now, with the entry created, we will send it to the site using the AddEntry method of the web service. Add, then, the code in Listing 21.

 

Listing 21. Sending the photo

try

{

       objService.AddEntry(newEntry, myBlog.ID);

       MessageBox.Show("Photo sended!");

}

catch

{

       MessageBox.Show("Error sending photo!");

}

 

There! In Figure 19, we have our application working.

 

image042.jpg

 

Figure 19. Application running in the Smartphone

 

Conclusion

The new Windows Mobile 5.0 centralized many of the features of  existing hardwares in PocketPC’s and Smartphones. Thanks to this centralization, such as the Camera API, we can make a very sophisticated application today, which will use the camera in any device running the Windows Mobile 5.0, in a much more simple and safe way. Although  we choose a Smartphone application, nothing keeps the ideas and the code here exhibited from being used in a PocketPC application. In fact, the code is practically identical.

The use of the Image type of the SQL Server makes storage and image recovery from our PhotoBlog very much easier.

In this article, we sent only photos, but the sharper reader will discover that it is also very east to make a “VideoBlog”. Get to work!



colunista nao disponivel

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login