Thursday, December 15, 2011

C# Text Messages by Email Queues


Summary
This tutorial shows how to simply send a text message (SMS) by Email and .

Description
There are two goals  The first is simple and described in the beginning, send a text message by email.  The second is to send text messages of unlimited length via email as text messages have a character length limit.  As an addition, we are using a queue data structure to get the job done.  The format of this article explains the concept of a code chunk then shows the entire code.

Before we begin
For the tutorial, take a look at the following:

Send Email C# - Example Only - Find the clsSmtpClient class in this post.

Send Text Messages
     Want to send a text message by email? It's easy, and free.  Compose a new email and send it to "your 10 digit number@smsgateway.com".  For example, my pretend Verizon phone number is (555)123-0987.  If someone wanted to send a text message to me, they would send an email to "5551230987@vtext.com".  This is free.  
     "number@vtext.com" will get the message to Verizon customers.  In order for this to work you will need to use the correct SMS gateway.  Thankfully, you can find a list of them here.
     Lastly, all text messages have a character limit of 160 characters.  I can only send 140 characters per email sent to "@vtext.com".  This means that if I write a 1000 character email and want to send it as a text message to someone, only the first 140 will be sent as a text message.  This could be different for each SMS gateway as I have only worked with the Verizon SMS gateway.


Queue the Queue
     Data structures class was one of my favorite classes.  To me, data structures bring organization to the processing of data in a way that just makes sense.   I like to use them whenever relevant/needed not only for what they do but also to practice using them.  In short, the queue is a collection of objects that processes objects in a first-in/first-out manner.
     As an example (analogy), the queue is like standing in line at the grocery store.  In this example, the people waiting in line are our objects in the queue.  The idea of getting into line is called, Enqueue.  The idea of calling the next person in the line to check-out is called, Dequeue.   People (objects) get into the single-file line (Enqueue) and are processed at the check-out (Dequeue) in the order which they got into the line (the queue).
     As a programming example, we have three strings we want to put into a queue:  Customer1, Customer2, and Customer3.  Let's pretend we already have a queue called "checkOutLine" for our string objects.  We get them into the queue (our grocery store check-out line) by saying:

checkOutLine.Enqueue(Customer1);
checkOutLine.Enqueue(Customer2);
checkOutLine.Enqueue(Customer3);

     You, the programmer, are at the counter waiting to check these Customers (and their strings) out.  We  call the next Customer in line up to the counter. While the Customer is at the counter, we take a look at what they have and then the Customer leaves the queue (Dequeue).

// For example

// This string represents the string of the customer we call to the counter to check-out...
string nextCustomer = "";

// Call the next customer in line to the counter
nextCustomer = checkOutLine.Dequeue();

// Do something with the nextCustomer string

     We can also iterate through all of the customers in line using a foreach loop:

foreach (string str in checkOutLine)
{
     // Do something with each customer until there are none in the queue
}

Send Text Messages, No Length Limit
     Well, technically this isn't true.  Due to the limitations of the Short Message Service (again SMS), we are limited to 160 characters.  For those interested in why, an SMS message can only contain 1120 bits  (Reference here).  The commonly used GSM 7-bit alphabet gives us 160 characters.  While it's possible to send a long SMS using a  User Data Header (reference here), we aren't going to cover it.
      Instead we are going to take the original message (of any length), chop the whole message into 140 character or less separate messages, place each message in a queue, and send each message as a separate email.

The clsMessageQueue Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SmsDemo
{
    public class clsMessageQueue
    {
        Queue<string> _messageQueue = new Queue<string>();
        string _wholeMessage;
        int _max_length;
        int _totalMessages;
        int _messageLength;

        public clsMessageQueue(String SmsMessage, int length)
        {
            // Pass the entire message in
            WholeMessage = SmsMessage;
         
            // Pass the desired max length of the SMS message
            Max_Length = length;
         
            // Set the message length based on the entire message
            MessageLength = WholeMessage.Length;

            // Start processing the message and ready it in the queue
            Setup();
        }


        public Queue<string> MessageQueue
        {
            get { return _messageQueue; }
        }

        public string getMessage()
        {
            return _messageQueue.Dequeue();
        }

        public void setMessage(string str)
        {
            _messageQueue.Enqueue(str);
        }

        public string WholeMessage
        { get { return _wholeMessage; } set { _wholeMessage = value; } }

        public int Max_Length
        { get { return _max_length; } set { _max_length = value; } }

        public int TotalMessages
        { get { return _totalMessages; } set { _totalMessages = value; } }

        public int MessageLength
        { get { return _messageLength; } set { _messageLength = value; } }


        private void Setup()
        {

            // Find the amount of messages we need to make
            // based on the length of the total message


            // If there is any remaining characters (remainder)
            // there will be an extra message with less than
            // 140 characters
            if (MessageLength % Max_Length > 0)
            {
                // divide the messageLength by the Max_Length
                // in order to get the amount of messages and
                // add one for the extra message
                TotalMessages = (MessageLength / Max_Length) + 1;
            }
            // Otherwise - there is no remainder
            else
                TotalMessages = (MessageLength / Max_Length);

            // The total times we loop is equal to the amount of message
            // we need to make (see the above if statement)
            for (int i = 0; i <= (TotalMessages - 1); i++)
            {

                // if the length of the message is less than the Max_length
                if (MessageLength <= Max_Length)
                {
                    // all we need to do is put the message in the queue
                    setMessage(WholeMessage);
                }

                // if the length of the message is more than the Max_length
                else if (MessageLength > Max_Length)
                {
                    // take the first 140 chars (Max_Length)
                    // and put this into the queue
                    setMessage(WholeMessage.Substring(0, Max_Length));
                 
                    // cut the first 140 chars (Max_length) out
                    WholeMessage = WholeMessage.Substring(Max_Length, (WholeMessage.Length - Max_Length));
                 
                    // reset the length of the message
                    MessageLength = WholeMessage.Length;
                }
            }
        }

    }
}



How do we use it?
     Now that we have a queue full of 140 character or less messages, we need to send them in the order that we put them in (first in, first out).  For this demo we simple text boxes to get user input, a button named "btnSend", the clsMessageQueue (above) to process the messages, and the clsSmtpClient class to send each message.



namespace SmsDemo
{
    public partial class SendSMS : System.Web.UI.Page
    {
        int MAX_LENGTH = 140;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSend_Click(object sender, EventArgs e)
        {

             // Get the email of who this text is from
            string fromEmail = Server.HtmlEncode(txtSmsFrom.Text);
         
            // I'm assuming the phone number is for a Verizon subscriber
            string toEmail = Server.HtmlEncode(txtSmsTo.Text) + "@vtext.com";
            // Get the message we want to send from the user
            string messageBody = Server.HtmlEncode(txtMessageBody.Text);


            clsMessageQueue messageQueue = new clsMessageQueue(messageBody, MAX_LENGTH);

            /*
             * Logic tier - clsSmtpClient
             *      Mail logic is put in another class
             *      and implemented here concisely.
            */

            // Smtp Client - other settings in web.config for safeness.
            clsSmtpClient mySmtpClient = new clsSmtpClient(fromEmail,
                                                           "Sean");
            // set the to email address
            mySmtpClient.setToAddress(toEmail);


            // This is where we send all the messages.
            // For every 140 char or less message, we send an email
            // and because we're using a queue, they are being sent int
            // the order that we cut them up.
            foreach (string str in messageQueue.MessageQueue)
            {
                // set the message content
                mySmtpClient.setMessageBody(str);

                // Send the email!! - Hiz-zah's are in order.
                mySmtpClient.SendEmail();

                // Need to wait a couple seconds
                // Otherwise the messages may get out of
                // order when they hit the SMS gateway.
                System.Threading.Thread.Sleep(2000);

            }

            if (mySmtpClient.Complete)
            {
                // When sending the messages, everything went fine
            }

            else if (!mySmtpClient.Complete)
            {
                // Something happened when sending the messages

            }
        }


Done!!!

Tuesday, December 13, 2011

Multiplatform Project

Project Summary
The current project is an ongoing, multiplatform project.  The purpose is to collect and analyze data from agricultural areas (farms) using simple, inexpensive technology.  It is a project that connects together a website, a mobile device, a database, and some hardware lead by an Arduino.  The Arduino-led hardware is a quadcopter (Figure 1.1), the mobile device is my Android device, the site is an ASP.NET site (C#), and MS SQL 2008 for the database.  

Figure 1.1
I like to keep things as simple as possible. The quadcopter goes to predetermined lat/long coordinates without direction, but can accept commands in-flight.  The Android device is on-board the quadcopter.  It has two purposes.  The first is to pass commands to the quadcopter via SMS and data.   The second is to get sensor data and images back to the ASP.NET website.  The ASP.NET site has three purposes.  It will process data, analyze it (if needed), and send it to the database.  The website is also the place where information is presented.  Lastly, it's the only place to control the quadcopter.  The idea can visually be summed up in Figure 2.1.



Progress

  • The quadcopter is put together (Figure 1.1).   Creating an image library for the site is rough around the edges but done.  Image library information (mapping) is stored in a database.  Broadcast Receiver for SMS on Android is kinda stock-ish code but works.
  • The quadcopter was built in a weekend and broke in the next.  The longest time with the quadcopter has been spent getting board, props, motors, speed control stuff set correctly.  Other than the RC Car project, I don't have any prior experience with RC stuff..  not a big deal though.  Best flight was about five feet for a few seconds at a little over 1.5Kg under 50% throttle.  Very sturdy but a prop broke (Figure 3.1). 

Monday, December 12, 2011

Send Email C# - Example Only


Summary
This example is a simple class that can be used to send email, written in C#

Description
This example shows everything needed to send an email except for the SMTP settings.  These settings will vary depending on who you are sending your email through.  While these settings can be hard coded, always place them in the web.config file or the app.config file.

Before We Begin
You'll need the SMTP settings in your web.config or app.config file.  Do a search for your email provider's SMTP settings.  Here is a skeleton to use:


<system.net>
    <mailSettings>
      <smtp>
        <network host="You email provider will tell you what to use (example. smtp.gmail.com)"
                 password="The password you use to log into your email account"
                 port="Your email provider will tell you what port to use"
           userName="youremailaddress@something.com"/>
      </smtp>
    </mailSettings>
  </system.net>

The clsSmtpClient Class




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

namespace EmailDemo
{
    public class clsSmtpClient
    {
        private string _fromEmailAddress;
        private string _fromEmailName;
        private string _toEmailAddress;
        private string _messageSubject;
        private string _messageBody;
        private bool _complete = false;
        private string _error;
        SmtpClient mailClient = new SmtpClient();
        MailMessage message = new MailMessage();

        public string FromEmailAddress
        {
            get { return _fromEmailAddress; }
            set { _fromEmailAddress = value; }
        }

        public string FromEmailName
        {
            get { return _fromEmailName; }
            set { _fromEmailName = value; }
        }

        public string ToEmailAddress
        {
            get { return _toEmailAddress; }
            set { _toEmailAddress = value; }
        }

        public string MessageSubject
        {
            get { return _messageSubject; }
            set { _messageSubject = value; }
        }

        public string MessageBody
        {
            get { return _messageBody; }
            set { _messageBody = value; }
        }

        public string Error
        {
            get { return _error; }
            set { _error = value; }
        }

        public bool Complete
        {
            get { return _complete; }
            set { _complete = value; }
        }


        /*
         * Constructor
         */
        public clsSmtpClient(string fromEmailAddress,
                             string fromEmailName,
                             string toEmailAddress,
                             string messageSubject,
                             string messageBody)
        {
            FromEmailAddress = fromEmailAddress;
            FromEmailName = fromEmailName;
            ToEmailAddress = toEmailAddress;
            MessageSubject = messageSubject;
            MessageBody = messageBody;

            setupClient();
        }

        /*
         * Default Constructor
         */
        public clsSmtpClient(string fromEmailAddress, string fromEmailName)
        {
            mailClient.EnableSsl = true;
            FromEmailAddress = fromEmailAddress;

            FromEmailName = fromEmailName;

            MailAddress fromAddress = new MailAddress(FromEmailAddress, FromEmailName);
        }


        private void setupClient()
        {
            // Smtp Client - other settings in web.config for safeness
            mailClient.EnableSsl = true;

            // To and From address objects
            MailAddress fromAddress = new MailAddress(FromEmailAddress, FromEmailName);
            MailAddress toAddress = new MailAddress(ToEmailAddress);

            // Build the message
            message.From = fromAddress;
            message.To.Add(toAddress);
            message.Subject = MessageSubject;
            message.Body = MessageBody;
        }


        public void setToAddress(string str)
        {
            MailAddress toAddress = new MailAddress(str);
            message.To.Clear();
            message.To.Add(toAddress);
        }

        public void setMessageBody(string str)
        {
            message.Body = str;
        }

        public void SendEmail()
        {
            try
            {
                mailClient.Send(message);
                Complete = true;
                Error = "Complete!";
            }
            catch (Exception mailException)
            {
                Complete = false;
                Error = mailException.Message.ToString();
            }
        }

    }
}

How do we use it?
Below is an example of how to use this class to make emailing simple.

             // In a winform project, remove "Server.HtmlEncode"
           
             // This is the email address you want to send to, taken from a textbox control.

            string toEmail = Server.HtmlEncode(txtMessageTo.Text);
             // This is the email subject taken from a textbox control
            string messageSubject = Server.HtmlEncode(txtMessageSubject.Text);
             // This is the actual message of the email taken from a textbox control
            string messageBody = Server.HtmlEncode(txtMessageBody.Text);
         
            /*
             * Logic tier - clsSmtpClient
             *      Mail logic is put in another class
             *      and implemented here concisely.
            */

            // Smtp Client - other settings in web.config for safeness.
            clsSmtpClient mySmtpClient = new clsSmtpClient("the email address you are sending from",
                                                           "the from email name you want to use",
                                                           toEmail,
                                                           messageSubject,
                                                           messageBody);

                // Send the email.
                mySmtpClient.SendEmail();
             
                // After sending an email, we have two outcomes... it either sent or failed.
                // Below, we check for both.
                // check to see if the email got sent.
                if (mySmtpClient.Complete)
                {

                    // If the email was sent without problems,
                    // do the following..  yours will be different
                    // Everything below is just a summary of what was sent.

                    pnlInput.Visible = false;
                    pnlResult.Visible = true;

                    lblEmailToReturn.Text = toEmail;
                    lblMessageSubjectReturn.Text = messageSubject;
                    lblMessageBodyReturn.Text = messageBody;
                }
             
                // If the email failed to send for some reason, no internet connection, etc.
                else if (!mySmtpClient.Complete)
                {
                    // This code gets the error message and sets a label with it.
                    lblError.Text = mySmtpClient.Error;
                    pnlInput.Visible = false;
                    pnlResult.Visible = false;
                    pnlError.Visible = true;
             
                }
        }







Thursday, November 10, 2011

Computer Projects


Summary
This post is a listing of any completed or ongoing projects as well as a running tally of completed computer repairs.

Description
The accomplishment of finishing a project is a great thing.  It's awesome to start from imagining a new project to completing it.  This is especially true if I had no experience before starting.  Often times, between work and school, this sense of accomplishment is lost to quickly focusing on new problems.  Posting the major projects is both for reflection and maybe it helps someone else. If there is interest in a tutorial from one of the projects listed, let me know!

Below the projects is a section of repairs.  Repairs are accepting an unusable computer from somebody and making it a working computer.  A repair is a project but are excluded from the project list as the final product of a repair is always the same, a working computer.  I do these repairs because I believe computers greatly increase the quality of life.  Unfortunately, a machine could become completely unusable at any moment and not everyone knows what to do or may not have the financial means when their computer becomes unusable. If you can make computer repairs, have a little extra time, and get approached by anyone that needs help, I would encourage you to take the extra time and help.  Repair projects are both rewarding and a great source of learning experience.

The Projects
Almost all of these projects were written after June 2011.

Name: Project Mendel
Goal:Complete multiple tasks related to genetics. Determine if something is due to chance (better than chi-squared test). Perform a test cross using a punnett square diagram.
Concepts:Math for genetics, C# Winforms, Java, string manipulation


Name: Sequence Cutter
Goal:In a 40 page document full of nothing but the letters A, T, G, C, N, remove and label the data between each set of N characters. (Remove all non-read sequences from sequence data).
Concepts:C# Winforms, Java, Generics, Queues


Name: RC Car Hack
Goal:Pair a broken remote control (RC) car with an arduino and PC, through bluetooth to control with simple keypress or xbox 360 controller.
Concepts:C#, Winforms, Bluetooth, System.IO.Ports, Arduino, Motor Driver


Name:Arduino Vending Machine - Accepting Dollar Bills
Goal:Use a bill validator (BA-30) and Arduino to show when a bill has been accepted.
Concepts:C#, Winforms, System.IO.Ports, Arduino, Bill Validator


Name: Image Viewer
Goal:Display all available images from a designated folder in an ASP.NET site
Concepts:C#, ASP.NET, MS SQL Server 2008, GridView control, DirectoryInfo, FileInfo


Name: Word Counter
Goal:Get the count of words from the page source of any specified webpage in order to analyze or make associations with the content
Concepts:C#, Winforms, ASP.NET, HtmlAgility Library, Dictionary object


Name: Contact Us
Goal:Send an email filled with user input
Concepts:C#, Winforms, ASP.NET, SmtpClient, MailMessage


Name: Message Station
Goal:Send text messages (SMS), of unlimited length, to a contact picked from a saved list.
Concepts:C#, Winforms, SMS Gateway, SmtpClient, Queue, System.IO.File


Name: PDF Form Filler
Goal:Take user input and fill fields in an existing PDF file
Concepts:C#, ASP.NET, ITextSharp Library, SmtpClient, MailMessage, Android, WebView


Name: Mobile Learning Center
Goal:On Android, create an application that only uses HTML for presentation. Additional HTML modules can be added/downloaded to extend the application (Dynamic) while running.
Concepts:Android, Download Manager, HTML, java, java.io.*, java.util.zip.*, ASP.NET


Name: Android FTP
Goal:Upload a text file via FTP
Concepts:Android, Java, java.io.*, java.net.*, Apache Commons Net Library


Name: Agricultural Surveyor (IN PROGRESS)
Goal:Make a platform to collect data from agricultural areas using an automated quadcopter, ardupilot mega, and android phone. Analyze, manipulate, and present data collected using C#/ASP.NET. Store data using MS SQL Server 2008.
Concepts:ASP.NET, MS SQL Server 2008, GridView, DirectoryInfo, FileInfo, Android, Intents/Broadcast receivers/Content Provieders for SMS and sensor information, Arduino, hobby hardware


Name:Scrape Web Info System
Goal:Get links from a search, separate all words from each page retrieved, and count all the words.   
Concepts:ASP.Net, C#, MS SQL 2008, HtmlAgility Library


Name:Maximum Data Rate of a Channel
Goal:Calculate the maximum data rate of a channel according to Nyquist and Shannon.  
Concepts:Android, Java, static methods







Still working on listing more....



Repairs
2011

  • Hardware Replaced
    • Hard drives - 5 (includes either reimage, clone, or file transfer)
    • Optical drives - 2
    • RAM - 3
    • Graphics Card - 1

  • Malware Removal - 8
  • Network problem resolved - 6
2012

  • Hardware Replaced
    • Hard drives - 1 (includes either reimage, clone, or file transfer)
    • Optical drives - 0
    • RAM - 0
    • Graphics Card - 0

  • Malware Removal - 2
  • Network problem resolved - 2

Saturday, November 5, 2011

ASP.NET - Add Membership Schema to Existing Database

Summary
This tutorial shows how to add all the membership stuff to an existing data and use it in an ASP.NET Web Application.

Description
The goal here is to easily add all the ASP.NET membership tables and related info to an existing Microsoft SQL Server 2008 R2 database and use this database in an ASP.NET Web Application.  Plainly, this means updating an existing MS SQL 2008 R2 database with stuff needed to allow users of the ASP.NET application to do things like login. 

Before we begin
For the tutorial, you'll need the following:

Visual Studio 2010 Web Developer or Professional - When we start a new ASP.NET Web Application project it will be in C#. 

Microsoft SQL Server 2008 R2 - You'll need at least the express edition installed, a database created, and a user.  The database can be a normal new database.  The user must use "SQL Server Authentication".  If you want to know how to create a new database, new user, and assign the user a role from the new database then see the previous tuorial here

Microsoft .NET Framework 4.0 - This is good to have, find it here and install it.  This tutorial is based on .NET 4.0.

Steps


  1. Find the "ASP.NET SQL Server Setup Wizard"
  2. Run the Wizard
  3. Start a new ASP.NET Web Application
  4. Open the Web.config file
  5. Modify the Connection String
  6. Done!!  Hit F5, make a new user, Login, Logout, Login
  7. Not convinced?  Check the database.
  8. Done, for reals.

1.  Find the "ASP.NET SQL Server Setup Wizard" - Open your C drive (or find your windows directory).  For me, the location is "C:\Windows\Microsoft.NET\Framework\v4.0.30319".  In the picture below, you'll see the other versions of .NET.  We want to choose "v4.0" because our ASP.NET Web Application project will use the .NET 4.0 Framework (Figure 1.1).  Within this folder find a file named "aspnet_regsql.exe" (Figure 1.2).


Figure 1.1
Figure 1.2

2.  Run the Wizard - Open the file from above, "aspnet_regsql.exe".  The wizard will start and the first page comes up.  Read it or not but click the "Next" button.  The next page says "What database task do you want to perform?".  On this page select the radio button next to "Configure SQL Server for application services" (Figure 2.1) and click Next. 

Figure 2.1


For the next page, we'll need to specify the Server, authentication type, user name, password, and select a Database.   The goal of this page is to find the existing database.  If you're lost here, I recommend going through the previous post here.  I'm assuming you went through the previous post.  This information we use here (Figure 2.2) should be the same we used to test the new user in the last step of the previous post.  NOTE:  Fill out the username and password before selecting a Database.  The username will be "mytestuser", the password will be "password", and select "TestDatabase" from the drop-down box for our database.   Just to compare the last step of the previous post to this one, here's the login information we used for our test server (Figure 2.3)

Figure 2.2
Figure 2.3 - Compare with 2.2


After the settings are filled in, click Next.  If you're sure click Next again. When it's finished, click Finished.  That's it, for the first part.

3.  Start a new ASP.NET Web Application Project - Open Visual Studio and start a new project.  Start a new ASP.NET Web Application, for the name use "LoginApplicationDemo" (Figure 3.1).  Do not select the "ASP.NET Empty Web Application",  we will be using the awesome default login setup with master pages.  Select the OK button.

Figure 3.1
4.  In the or new project, open the Web.config file. In the Web.config file, the "connectionStrings" tag we want to work with next is at the top (Figure 4.1).

Figure 4.1


5.  Modify the Connection String - We will add the following to replace the default connection tag in step 4 (Figure 4.1).  We are replacing this with a connection string that points to the existing database (TestDatabase) that we are going to use with this project (LoginApplicationDemo).  Our new connection string looks like this:

<conectionStrings>
  <add name="ApplicationServices"
connectionString="Data Source=DUTCHESS;Initial Catalog=TestDatabase;User Id=mytestuser;Password=password;"
           providerName="System.Data.SqlClient" />
</connectionStrings>

  You can see the new connection string in place in Figure 5.1.  What does this connection string mean?  Well, it's all relative to the other steps.  The "Data Source" was known as "Server Name".  The "Initial Catalog" was known as the name of the "Database".  The "User Id" was "Login" or "Username".  The "Password" is... well just compare the login information of Figure 5.1, Figure 5.2, and Figure 5.3.  Also, our new Web.config file is shown in Figure 5.1.

Figure 5.1
Figure 5.2
Figure 5.3
6.  Done!! Hit F5, make a new user, Login, Logout, Login - That was it.  (Figure 6.1, 6.2, and 6.3) Debug > Start Debugging (F5).  When you site comes up in your favorite browser, create a new user, logout, and login again.  You can even close the browser, stop debugging in Visual Studio.  To prove it's still in the database, select Start debugging (F5) again, and log into the site (Figure 6.1 and 6.3)



7.  Not convinced? Check the database. - Before completing this step, make sure you have completed step 6.  We're going to check the database (TestDatabase) for the new user created in step 6.  Open Microsoft SQL Server Management Studio, log in as "mytestuser" (Figure 7.1).  Click on "New Query" (Figure 7.2).  From the available databases drop-down list (currently says "master"), select "TestDatabase".  In the query area write "select * from aspnet_Membership;" and "Go;" (Figure 7.3).   Finally, click the "Execute" button and see your results towards the bottom of the page.  Scroll through this result, it is the user that you registered in step 6.

Figure 7.1


Figure 7.2
Figure 7.3

That is all.  I hope this tutorial has been helpful to you.

Comments/Questions?
I'm always wanting to improve the quality of the content here. If you have questions, want to see a better explanation, a better picture, let me know. Thanks - Sean

MS SQL Server 2008 R2 - New Database and User

Summary:
This tutorial is about creating a new user, new database, and assigning the new user a role in Microsoft SQL Server 2008 R2.


Description:
We will do a step-by-step walkthrough of how to add a create a new database, create a new user, and add the user to the "db_owner" role for the new database in Microsoft SQL Server 2008 R2.


This is one of the first steps in starting to use Microsoft SQL Server 2008 R2.


Before we start:
This tutorial assumes you have Microsoft SQL Server 2008 R2 Express Edition installed.  I assume you enabled Windows Authentication and have a default instance of SQL Server.

Steps:


  1. Open MS SQL Server 2008 R2
  2. Connect as Admin
  3. Create a TestDatabase
  4. Creating the New User
  5. The New User's Role
  6. Done!! Login with the new user

1.  Open MS SQL Server 2008 R2 - Go to 'Start', 'Microsoft SQL Server 2008 R2', and select 'SQL Server Management Studio'.



2.  Connect as Admin - If your installation went well, you should be able to set "Authentication" to "Windows Authentication", server name to "(local)", and click the "Connect" button.  As one alternative, you can use your computer name as the server name.  Another alternative is to click the drop-down box for server name, select "browse", and find your server name under "Database Engine". 



3.  Create a TestDatabase - On the left-hand side is a section called the "Object Explorer".   In the Object Exporer, right-click on "Databases", and select "New Database...".  A new window appears named, "New Database". 



In this window, find the textbox labeled "Database name:" and write "TestDatabase".  After this, click "OK" to create the new database. 



4.  Create the New User - Go to the Object Explorer and open the Security folder.  Inside, you will find a folder named "Logins".  Right-click on the folder named "Logins" and select "New Login".



For the login name, type "mytestuser".  Below this, select the radio button labeled "SQL Server authentication".  In the Password boxes, type "password" or something easy to remember. NOTE: It's not good practice to use easy passwords like this, but this is just for learning.  Next, make sure the following three checkboxes are not selected: "Enforce password policy", "Enforce password expiration", and "User must change password at next login".  Lastly, on the left-hand side under "Select a Page", select "User Mapping".  Don't select the OK button yet... move to the next step.



5.  The New User's Role -  Before we create the new user, we want to make the new user a member of the "db_owner" role for the table we created in step 2.  After selecting "User Mapping" in the previous step, look for your database "TestDatabase" from step 2 in the top half of this window.  Next to the name "TestDatabase" is a checkbox, select this check box.  With this checkbox selected and this row highlighted, the bottom half of the current window will show all of the "Database role membership for: TestDatabase".  In this area, click the checkbox next to "db_owner".  Now, select the OK button. 



6.  Done!!  Login with the new user - The database, user, and mapping are all done.  We now need to test everything we've done by logging in using the new user we've created and access the new database.  So.. Close and reopen Microsoft SQL Server Management Studio.  (Another way is to select "Disconnect Object Explorer" and then select "Connect Object Explorer" under "File" menu.)  Either way, the login screen should appear.  In the drop-down box labeled "Authentication", select "SQL Server Authentication" from the drop-down box.  Now, the "Login" and "Password" boxes will become enabled.  For login, type the name of the user we created, "mytestuser". For password, type the password we used, "password".  Select the "Connect" button.  That's it!  Lastly, if you want to make sure we assigned "mytestuser" the "db_owner" role, open the "TestDatabase".  If you can open this database, without error messages, everything should be good.  If you want to see what happens when you don't have permission, try to open any other database.




Comments/Questions?
I'm always wanting to improve the quality of the content here. If you have questions, want to see a better explanation, a better picture, let me know. Thanks - Sean


Saturday, August 27, 2011

Android - Use websites in your app (WebView Tutorial)

Summary
This is an Android tutorial on a really simple way to get started using the WebView.

Description
You can use a WebView to display a website the same way you would when you open a browser on your Android device.  You can use a WebView to display a saved or self-made html document, view a website, or display strings in html format.
Although it is beyond this really simple tutorial, you can bind javascript to Android code.  You can find more information on this at http://developer.android.com/guide/webapps/webview.html.

Before we begin
I'm using Eclipse (Indigo x64) with the ADT plugin on Windows 7 x64.  My target API is Android 1.6 so that the application is backwards compatible with all others beyond 1.6.


Steps

  1. Create a new Android project
  2. Add a WebView to your activity layout
  3. Add the permission to the manifest file
  4. Add the code to your Activity

1.  Create a new Android project
Go to File > New > Android Project.  For the project name, I choose "WebViewDemo".  In the build target, select Android 1.6 for compatibility.  For the package name, I choose "com.projects.WebViewDemo".
Select Finish and you should have a project that looks like Figure 1.1.

Figure 1.1

2.  Add a WebView to your activity layout
In the Project Explorer, find your project, and navigate to "res\layout\main.xml".  Open "main.xml" and you eclipse will show "main.xml" in the Graphical Layout Editor (Figure 2.1).  Just under the Graphical Layout Editor, select the tab "main.xml" (This tab is circled in Figure 2.1).  

Figure 2.1

Now that we can see the XML document.  Lets add the following code as show in Figure 2.2.

<android.webkit.WebView 
android:id="@+id/wvwMain" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent">
</android.webkit.WebView>

Figure 2.2

3. Add the permission to the manifest file
Your WebView will need to access the internet and your application will need to ask for permission to do this.  
In the Project Explorer, find your project, and open "AndroidManifest.xml".  Eclipse will open the "AndroidManifest.xml" (Figure 3.1).  Just under this editor, select the tab "AndroidManifest.xml" (This tab is circled in Figure 3.1).  

Figure 3.1

Now that we can see the XML document.  Lets add the following code as show in Figure 3.2.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Figure 3.2

4.  Add the code to your activity
In the Project Explorer, find your project, and navigate to "res\com.projects.WebViewDemo\WebViewDemoActivity.java".  If you used a different project name or package name than the ones I used,  you will find the .java file under the names you used.  Open the ".java" file, mine is "WebViewDemoActivity.java" (Figure 4.1).  

Figure 4.1

Lets add the following code to the activity as in Figue 4.2:

Starting at the import section add:
import android.webkit.WebView;

After the Activity starts (and before the "@Override" line) add:
WebView browser;

In the OnCreate method of the Activity add:

        // find the WebView by name in the main.xml of step 2
        browser=(WebView)findViewById(R.id.wvwMain);
        
        // Enable javascript
        browser.getSettings().setJavaScriptEnabled(true);  
        
        // load a webpage
        browser.loadUrl("http://news.google.com/");

Figure 4.2

That's it!
Run your program and see the results! 


Final Notes:
You'll notice that the browser you created has no status bar or navigation URL portion at the top.  This was the goal.  For example, I make an ASP.NET website and want my android application to view only certain pages as well as control the navigation.  Another example, I could make an html document, store it locally, load it with the WebView, and bind the javascript to your Android code.  

Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean

Friday, August 26, 2011

Fill PDF forms in C# with iTextSharp

Summary:
This tutorial is about using the iTextSharp library using C# in Visual Studio 2010


Description:
We will take user input from a Windows Forms project and place the input into the appropriate fields of an existing PDF document.


I fill out a lot of forms at work.  These forms never change.  Every week, I'm always using the same form and entering data in the same fields (on paper).  It seems like a perfect opportunity to make the process easier by doing it electronically.  


Before we start:
This tutorial assumes that you have an editable PDF with text fields named: "NAME", "ADDRESS", "CITY", and "STATE".  If I could post the template PDF to use as an example I would.  This is the only thing I can't provide with this tutorial.  If you can make a pdf file (somehow), and add the above listed textfields.  The rest of the tutorial should be easy.  If you want to substitute your own template PDF with editable text fields, rock on.  Pay special attention to matching the name (and case) of the PDF text field with the "fields.SetFields("pdf text field", string) parts.  


Steps:


  1. Download the iTextSharp library
  2. Extract the iTextSharp library
  3. Start new C# Windows Forms project
  4. Add reference to the iTextSharp library
  5. Add the needed controls (textboxes, buttons, labels) to our form
  6. Add a folder for the template PDF and place the PDF file in the folder
  7. Add the code to the project
  8. Done!! Check for the output file


1. Download iTextSharp
Download the iTextSharp library at http://sourceforge.net/projects/itextsharp/






2. Extract the iTextSharp library
Extract the library to a new folder that you can find again.  I extracted mine to my Visual Studio directory.  For example, "\Visual Studio 2010\external libraries\iText lib"


3. Create a new C# Windows Forms project
Start Visual Studio 2010.  Select "New Project".  Next, under C#, select "Windows Forms Application".  Name the solution something like "FormFillerPDF" and select "OK".


4.  Add a reference to the iTextSharp library
In your Solution Explorer, right click on "Reference".  Left-click on "Add Reference..." (Figure 4.1)
(Alternatively, you can also select "Project" then "Add Reference..." from the menu.)  Now you'll need to find the folder where you extracted the iTextSharp library in step 2. In that location, find "itextsharp.dll" and select "OK".  (Figure 4.2) 




Figure 4.1




Figure 4.2


5.  Add the needed controls to our form
Add five labels, four textbox, and two button controls to the form. (Figure 5.1)
Arange the controls the same way as they are arranged in Figure 5.1
Name the textboxes (from top to bottom): txtName, txtAddress, txtCity, txtState
Name the buttons (from left to right): btnReset, btnSubmit
Name the labels (from top to bottom): Name, Address, City, State 
Place the last label below everything else, name it "lblResult", and change the text to "Result: "


Figure 5.1


6,  Add a folder for the template PDF and place the PDF file in the folder
In the Solution Explorer, right-click on your project name (FormFillerPDF), and select "Add" then "New Folder".  Name the folder "PDF", place your template PDF in the folder.  Name your PDF file "BasePDF".


7.  Add the code to the project



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using System.IO; // This is for file access
using iTextSharp.text.pdf; // This is for iText


namespace FormFillerPDF
{
    public partial class frmFiller : Form
    {
        public frmFiller()
        {
            InitializeComponent();
        }


        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {


                // get the file paths


                // Template file path
                string formFile = "PDF\\BasePDF.pdf";
                
                // Output file path
                string newFile = "PDF\\Filled-out Form.pdf";                


                // read the template file
                PdfReader reader = new PdfReader(formFile);


                // instantiate PDFStamper object
                // The Output file will be created from template file and edited by the PDFStamper
                PdfStamper stamper = new PdfStamper(reader, new FileStream(
                            newFile, FileMode.Create));


                // Object to deal with the Output file's textfields
                AcroFields fields = stamper.AcroFields;


                // set form fields("Field Name in PDF", "String to be placed in this PDF text field");
                fields.SetField("NAME", txtName.Text);
                fields.SetField("ADDRESS", txtAddress.Text);
                fields.SetField("CITY", txtCity.Text);
                //fields.SetField("STATE", txtState.Text);


                // form flattening rids the form of editable text fields so
                // the final output can't be edited
                stamper.FormFlattening = true;


                // closing the stamper
                stamper.Close();                


                // If the code above works, we should see the following
                lblResult.Text = "Result: Success";


                // After everything is done, we are setting the textbox text properties to ""
                btnReset_Click(sender, e);


            }


            catch (Exception ex)
            {
                // Make my exception's visible (if any)
                lblResult.Text = ex.ToString();
            }            
        }


        private void btnReset_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtState.Text = "";
        }
    }
}





8.  Done!!! Check for the output file.  Look for the file "Filled-out Form.pdf".  It will be located in your project directory\bin\debug




Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean