--Views and indexes --View is stored query or filter -- use CommunityAssist go Create View vw_Employee As Select LastName [Last Name], firstName [First Name], HireDate [Hire Date], SSNumber [Social Security No.], Dependents From Person p inner Join Employee e on p.PersonKey=e.PersonKey go Select * from vw_Employee --you have to use the aliases as the field names --when you query a view --the view helps abstract the database --users of the view don't know the underlying --table structure or column names Select [Last Name], [Social Security No.] From vw_Employee Where Dependents is not null go --another view --after you create a view if you want to change it --you must alter it --also the ORDER BY clause is forbidden in views Alter View vw_DonationSummary AS Select MONTH(DonationDate) [Month], Year(DonationDate) [Year], '$' + cast(SUM(donationAmount) as varchar(7)) [Total] From Donation Group by Year(DonationDate), MONTH(donationDate) Select * from vw_DonationSummary Where [Year]=2010 --binary tree non clustered index Create index ix_LastName on Person(LastName) --a clustered is where table is physically order by the indexed field create clustered index ix_lastnameClustered on Person(LastName) --unique and filtered--filtered because of the where clause --it only applies to the values that meet the condition --also a index can be on more than one column in a table --just separate them by commas in the parentheses Create unique index ix_uniqueEmail on PersonContact(contactinfo) Where ContactTypeKey = 6 Select * from PersonContact --will generate an error because it is a duplicate Insert into PersonContact(ContactInfo, PersonKey, ContactTypeKey) Values('lmann@mannco.com', 2,6) --drops an index Drop index ix_uniqueEmail on PersonContact --syntax for forcing an index Select LastName, firstname from Person with (nolock,index(ix_LastName))
Monday, April 30, 2012
Views and Indexes
Sunday, April 29, 2012
Android: Passing Values Between Activities with Bundle
This example uses the same layout as the previous example which shows how to open a second activity. There only difference in the layout is that I added two TextView controls to the Confirm.xml.
I am not going to repeat all the code and layout of the previous example. I am only going to focus on the code where it changes.
To transfer the values from the EditText controls on the first activity, I added a Bundle object. A Bundle object is essentially a hash control that stores key value pairs. I create the bundle in the first Activity, in the private class which implements the onClick event. I create the bundle, then add the values using the putString() method. Finally, I must declare and instantiate the new Activity differently than I did before in order to add the bundle with the putExtras() method
Here is the modified code:
private class ConfirmClickListener implements View.OnClickListener{ public void onClick(View v){ //get the Edit text controls and their text value EditText nameText=(EditText)findViewById(R.id.editTextName); String fullName=nameText.getText().toString(); EditText emailText=(EditText)findViewById(R.id.editTextEmail); String email=emailText.getText().toString(); //create a bundle object to store the values Bundle bundle = new Bundle(); //assign the values (key, value pairs) bundle.putString("name", fullName); bundle.putString("email", email); //create the intent //this is different than we did it before Intent i = new Intent(MultiActivityExampleActivity.this, Confirmation.class); //assign the bundle to the intent i.putExtras(bundle); //start the new activity startActivity(i); } }
Now here is the code on the Confirmation side. It declares a Bundle object and assigns its value from the getExtras() method. It extracts the values using the keys and then assigns them the TextView.
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.confirm); //create a bundle object to store //the bundle we added to the intent Bundle bundle=getIntent().getExtras(); //get the values out by key String name=bundle.getString("name"); String email=bundle.getString("email"); //get the textview controls TextView txtName=(TextView)findViewById(R.id.textView2); TextView txtEmail=(TextView)findViewById(R.id.textView3); //set the text values of the text controls txtName.setText(name); txtEmail.setText(email); }
Now when you click on the comfirm button it passes the values from the first Activity to the second
Saturday, April 28, 2012
Android Multi-Activities One
Start a new Android project. For this demonstration we will use simple activities. The first one just takes a name and an email address in EditText boxes and a button. The second one for now will just have a ViewText that says "Thank you."
Here is the XML for first Activity
Main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="Last Name, First Name"> <requestFocus /> </EditText> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:hint="Email"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/buttonText" /> </LinearLayout>
here is the code for the strings resource
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Entry Form</string> <string name="app_name">MultiActivityExample</string> <string name="buttonText">Confirm</string> <string name="thankyou">Thank You</string> </resources>
Here is the code for the main activity MultiActivityExampleActivity.java
package com.spconger.multiactivityexample; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MultiActivityExampleActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Here is the first activity running
Now that we have the first activity set up, we will add another. Here is the XML for the second activity.
Confirm.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/thankyou" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout>
Now we will add a new class. It should have a superclass of android.app.Activity and it should inherit abstract methods
here is the code for the new Activity
package com.spconger.multiactivityexample; import android.app.Activity; import android.os.Bundle; public class Confirmation extends Activity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.confirm); }
Now we have to modify the Manifest file. Modify the xml so it looks like this:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.spconger.multiactivityexample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".MultiActivityExampleActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- add this for new activity --> <activity android:name="Confirmation"></activity> </application> </manifest>
Now when you press the button you should get the second activity
Thursday, April 26, 2012
New Donor ASP Net
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <p><asp:Label ID="Label1" runat="server" Text="Enter First Name"></asp:Label> <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox> </p> <p><asp:Label ID="Label2" runat="server" Text="Enter Last Name"></asp:Label> <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Last Name is required" ControlToValidate="txtLastName" Display="None" ForeColor="Red"></asp:RequiredFieldValidator> </p> <p><asp:Label ID="Label3" runat="server" Text="Enter Street"></asp:Label> <asp:TextBox ID="txtStreet" runat="server"></asp:TextBox> </p> <p><asp:Label ID="Label4" runat="server" Text="Enter City"></asp:Label> <asp:TextBox ID="txtCity" runat="server"></asp:TextBox> </p> <p><asp:Label ID="Label5" runat="server" Text="Enter State"></asp:Label> <asp:TextBox ID="txtState" runat="server"></asp:TextBox> </p> <p><asp:Label ID="Label6" runat="server" Text="Enter Zip Code"></asp:Label> <asp:TextBox ID="txtZipCode" runat="server"></asp:TextBox> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtZipCode" Display="None" ErrorMessage="invalid zip code" ForeColor="Red" ValidationExpression="\d{5}(-\d{4})?"> </asp:RegularExpressionValidator> </p> <p><asp:Label ID="Label7" runat="server" Text="Enter home Phone"></asp:Label> <asp:TextBox ID="txtHomePhone" runat="server"></asp:TextBox></p> <p><asp:Label ID="Label8" runat="server" Text="Enter Email"></asp:Label> <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> </p> <p><asp:Label ID="Label9" runat="server" Text="Enter DonationAmount"></asp:Label> <asp:TextBox ID="txtDonation" r unat="server"></asp:TextBox> <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtDonation" ErrorMessage="Be sure to enter a numeric value" Operator="DataTypeCheck" Type="Double"></asp:CompareValidator> </p> <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /> <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label> </div> <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" /> </form> </body> </html>
Default.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { //this method writes all the values from the text field //to the Donor class //it is in a try catch to catch errors, though you //should try to prevent errors by validating fields try { Donor d = new Donor(); d.FirstName = txtFirstName.Text; d.LastName = txtLastName.Text; d.Street = txtStreet.Text; d.City = txtCity.Text; d.State = txtState.Text; d.ZipCode = txtZipCode.Text; d.HomePhone = txtHomePhone.Text; d.Email = txtEmail.Text; d.DonationAmount = double.Parse(txtDonation.Text); DonationManager dm = new DonationManager(d); lblResult.Text = "Your donation has been Processed"; //Exception exc = new Exception("This is a new Error"); // throw exc; } catch (Exception ex) { //this puts the error in a session and //redirects us to the error page Session["err"] = ex; Response.Redirect("error.aspx"); } } }
Donor.cs,/p>
using System; using System.Collections.Generic; using System.Linq; using System.Web; ////// this class just stores all the values /// related to the donor and donation /// public class Donor { private string lastName; public string LastName { get { return lastName; } set { lastName = value; } } private string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } private string street; public string Street { get { return street; } set { street = value; } } private string city; public string City { get { return city; } set { city = value; } } private string state; public string State { get { return state; } set { //if (state.Length > 2) //{ // Exception e = new Exception("Must use 2 letter abreviation"); // throw e; //} state = value; } } private string zipCode; public string ZipCode { get { return zipCode; } set { zipCode = value; } } private string homePhone; public string HomePhone { get { return homePhone; } set { homePhone = value; } } private string email; public string Email { get { return email; } set { email = value; } } private double donationAmount; public double DonationAmount { get { return donationAmount; } set { donationAmount = value; } } public Donor() { } }
DonorManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Configuration; ////// this is the complex class. It uses ADO to write the /// donation information to several different database /// tables /// public class DonationManager { //declare the connection and donor //at class scope SqlConnection connect; Donor donor; public DonationManager(Donor d) { //in the constructor instantiate the connection //assign the donor to the local variable //and call the WriteDonor() method //the actual connection string is in the //web.config file connect = new SqlConnection(ConfigurationManager.ConnectionStrings ["CommunityAssistConnection"].ToString()); donor = d; WriteDonor(); } //Write first and last name to person //get the personkey //write the address information to PersonAddress //write phone number and email to personContact //need write donation to donation private void WriteDonor() { try { connect.Open(); //connect.BeginTransaction(); not working //the following lines call the methods //that configure the sqlCommand for inserts //into each table SqlCommand cmdPerson = WritePerson(); SqlCommand cmdAddress = WriteAddress(); SqlCommand cmdPhone = WriteHomePhone(); SqlCommand cmdEmail = WriteEmail(); SqlCommand cmdDonation = WriteDonation(); //execute the commands cmdPerson.ExecuteNonQuery(); cmdAddress.ExecuteNonQuery(); cmdPhone.ExecuteNonQuery(); cmdEmail.ExecuteNonQuery(); cmdDonation.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { connect.Close(); } } private SqlCommand WritePerson() { //define the sql string string sql="Insert into Person(Lastname, Firstname) Values(@Last, @First)"; //define the command SqlCommand cmd = new SqlCommand(sql, connect); //provide values for the parameters using the values //in the donor class which was passed through the constructor cmd.Parameters.AddWithValue("@Last", donor.LastName); cmd.Parameters.AddWithValue("@First", donor.FirstName); return cmd; } //all the other commands behave as the first one private SqlCommand WriteAddress() { string sql = "Insert into PersonAddress(Street, City, State, Zip, PersonKey)" + " Values(@street, @city, @state, @zip, Ident_Current('Person'))"; SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.AddWithValue("@street", donor.Street); cmd.Parameters.AddWithValue("@city", donor.City); cmd.Parameters.AddWithValue("@state", donor.State); cmd.Parameters.AddWithValue("@zip", donor.ZipCode); return cmd; } private SqlCommand WriteHomePhone() { string sql = "Insert into PersonContact(ContactInfo, ContactTypeKey, PersonKey) " + " Values(@info, 1, Ident_Current('Person'))"; SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.AddWithValue("@info", donor.HomePhone); return cmd; } private SqlCommand WriteEmail() { string sql = "Insert into PersonContact(ContactInfo, ContactTypeKey, PersonKey) " + " Values(@info, 6, Ident_Current('Person'))"; SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.AddWithValue("@info", donor.Email); return cmd; } private SqlCommand WriteDonation() { string sql = "Insert into Donation(DonationDate, DonationAmount, PersonKey, EmployeeKey) " + " Values(GetDate(), @Amount, Ident_Current('Person'), null)"; SqlCommand cmd = new SqlCommand(sql, connect); cmd.Parameters.AddWithValue("@Amount", donor.DonationAmount); return cmd; } }
error.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="error.aspx.cs" Inherits="error" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
error.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class error : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //check to see if the session exists if (Session["err"] != null) { //cast the session to the type Exception Exception ex = (Exception)Session["err"]; //view the message Label1.Text = ex.Message; } } }
Tuesday, April 24, 2012
Sequence Diagram
Here is the original Visio diagram
Here is Scanner.css
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SequenceTest { class Scanner { Scan scan; string doorState; public string DoorState { get { return doorState; } set { doorState = value; } } public Scanner(string cardNumber, string scannerNumber) { scan = new Scan(); scan.CardNumber = cardNumber; scan.ScannerNumber = scannerNumber; scan.ScanTime = DateTime.Now; DoorState="Closed"; ValidateScan(); } private bool ValidateScan() { bool valid = false; Validator validator = new Validator(scan); valid = validator.ScanValidation(); if (valid) DoorState = "open"; return valid; } } }
Here is the code for scan.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SequenceTest { public class Scan { private string cardNumber; public string CardNumber { get { return cardNumber; } set { cardNumber = value; } } private string scannerNumber; public string ScannerNumber { get { return scannerNumber; } set { scannerNumber = value; } } private DateTime scanTime; public DateTime ScanTime { get { return scanTime; } set { scanTime = value; } } } }
Here is the Validator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SequenceTest { class Validator { Scan scan; public Validator(Scan s) { scan = s; } public bool ScanValidation() { bool isvalid = false; if (scan.CardNumber.Equals("100") && scan.ScanTime.ToShortDateString().Equals("4/24/2012")) { isvalid = true; } return isvalid; } } }
Here is Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SequenceTest { class Program { static void Main(string[] args) { Scanner s = new Scanner("100", "1"); Console.WriteLine(s.DoorState); Console.ReadKey(); } } }
Here is the Sequence diagram generated by Visual Studio
Here are the Visual Studio generated class diagrams
Monday, April 23, 2012
The Changing Face of Programming
Below is an article I wrote on trends for developers. It is not all that I would like it to be, but it is a beginning.
Here is a link to a PDF of the article: Programming Report
When you finish the article I would appreciate it if you can complete a very brief survey after reading the article
Overview
Developers are used to change. It is part of the job description: new tools, new languages, no problem. But of late, it seems, changes have been more substantial. Not only tools, but platforms and paradigms are in flux. There is the drive to the cloud. Companies are beginning to turn to the cloud to help with the burden of supporting their own server infrastructures. Consumers are storing more of their data on the web, drawn by the convenience of having their books, music, and files available wherever they are and whatever device they are currently using. Further, the explosion of mobile devices such as the IPhone and the various Android phones have created a new class of program called Apps. The sudden rise of tablet computing has further expanded the scope of these apps. Finally, an increasing number of devices offer programming opportunities. GPS devices and devices embedded in dashboards and household appliances are becoming more common. These trends are not isolated from each other. In fact, they are all aspects of a larger trend: the movement away from the desktop computer to more mobile, more specialized platforms and devices. Many of the tools and concepts are the same, and all of them require a strong foundation in programming fundamentals. The question for IT instructors and their students is what skills are required to take advantage of these new trends. What of the traditional programming concepts and practices still apply? What additional concepts and skills should they acquire?
This report is not going to focus on all the convolutions associated with the adoption and expansion of these new technologies. There are complex arguments about whether moving to the cloud is actually cost effective for companies. There are many discussions about the nature and future of apps and what the effect of Windows 8 will have the markets. Strong opinions are expressed on all sides of these issues. There are also the facts, the numbers of cell phones using Android vs. IOS, the numbers of companies adopting cloud strategies, the specific successes and failures of these strategies, etc. This report is going to focus only on the implications for developers and specifically on the implications for IT students who intend to become developers.
Programming For the Cloud
"The Cloud" is essentially equivalent to the Internet. Specifically, using the cloud means using the Internet to provide functions normally associated with a personal computer: storing files, accessing applications, accessing company data and services. There are a least three distinct facets of cloud computing. On the consumer side using the cloud means storing personal files such as music and photographs on an Internet server. It also is where most of the apps they use on their phones and tablets store their data. For companies using the cloud means outsourcing applications and company data to another company's Internet servers. From the developer's point of view, the cloud represents a programming paradigm, and sets of tools for creating applications and accessing cloud stored data.
Consumer and corporate adoption of cloud computing has followed a complex pattern. Two large issues stand out: security and availability. For consumers the security issue is essentially one of privacy. Can they trust the companies that provide storage to keep their files and information confidential? To what extent will they allow these companies to use that information to support directed advertising and business intelligence research. For businesses the security issue is even more central. Can they trust the cloud providers to protect their core business secrets and data? Can they trust the providers to back it up and have complete disaster management plans in place? This touches on availability as well, can a company trust that its data will always be available when it is needed? There have already been a couple of high profile failures of cloud services. For a consumer, not being able to access a music file is an inconvenience, for a company the inability to access its data can be a disaster. There is also some question of whether Cloud computing is actually cost effective for companies, and, if so, what specific uses of the cloud make financial sense. All these caveats aside, though, the cloud is likely to grow increasingly central to computing in the foreseeable future.
For developers, and for IT students who intend to become developers, developing for the Cloud and leveraging resources stored on the cloud will become increasingly important activities. The question is what skills do developers need to work with the cloud? Two areas stand out: web development and service oriented architectures.
Basic Web Development
Web applications are still a major component of cloud computing; interfaces for saving and retrieving files from the cloud to actual business applications that allow to create documents or access services. Developing and maintaining these applications will require most of the traditional tools of web:
• HTML, XHTML, especially HTML 5 • CSS • Some knowledge of IP and http protocals • JavaScript, especially JQuery • Ajax • Php, ASP.net with c#, and perhaps other scripting languages like Python • Some knowledge of SQL and database design • A good knowledge of secure data access and development
Service Architecture
Much of the data on the Cloud is accessed through web services. These services offer a front end to data stores without the client having to know where or how the data is kept. Service Oriented Architecture (SOA) focuses on the development of these services and how to aggregate existing services into applications. Developers should know how to incorporate these services and how to develop their own. Again the web development skills listed above are relevant.
There are also platforms for Cloud Development. Microsoft has its Azure development environment. There are also several other IDEs such as Cloud 9 and eXo. Google, Amazon, and Oracle also have cloud development tools and APIs. The Amazon Cloud, it should be noted, is extremely easy to utilize and, for a student or developer, quite inexpensive (often only a few cents a month). Anyone with an Amazon account can sign up for a year’s free service and have a Linux or Windows server created, configured and set up in the cloud.(Links to these and others are listed at the end of the document.)
Secure coding techniques are especially critical in developing for Cloud based services and applications.
Apps (Mobile Devices, Tablets)
The term "app" is short for “application”, but it has come to have a special meaning when applied to mobile devices such as phones, mp3 players and tablets. To some extent, these apps, like the term, are abbreviated. They are streamlined to run on the limited resources of a phone or tablet. That isn't to say that some of them aren't quite complex, but no matter how sophisticated, they must run within the constraints of the device they are on.
Apps have become big business, just as a decade ago every company had to have a web site, now every company has to have an app on your phone. Companies are advertising for programmers to create apps. Typically they want people who can program for Apple's IOS and also for Android. (Links for some app development job listings are provided at the end of the document.)
The financial model for these apps is still developing. Many are free. They either generate no revenue for the app creator or they generate revenue by incorporating advertisements. Company based apps are usually free, the app itself being a form of advertising. Many other free apps are "lite" versions which encourage you to upgrade to a more feature rich version for a price. Some apps are sold at a 99 cent level. If an app takes off and is downloaded often enough this can add up to significant revenue. Other, usually serious productivity apps, such as Quick Office, charge comparatively large fees for download. But even these fees are miniscule compared to the prices of comparable software for the PC. An expensive app might be priced around 25 dollars, whereas its pc equivalent would be hundreds of dollars.
For a student, then there would seem to be two opportunities. One would be to work for a company that wants to build and distribute apps to support its business customers and processes. Another is to build their own apps and try to sell them in the app stores.
Typically the industry often wants the same app developed for all platforms, or at least, at this point for both Apple’s IOS and Android.
There are several unique aspects to phone and tablet development. Some of these include:
• Location awareness via the GPS services built into the phone or tablet hardware, • Web, cloud enabled. Data is accessed from and stored on the cloud. • Wireless, blue tooth and 3G or 4G connectivity • On phones apps must surrender focus to a phone call, this can involve threading and saving in background • Memory and storage limits (much less of either than on a laptop or PC) • Processor limits (typically slower processors)
IPhone, IPod, IPad
The apple products use Objective C as a basis for their development. The tools for creating Objective C applications are only available on Apple’s Macintosh computers. Further in order to test a product on an actual device, a developer must join the Apple developers group (free for students, but otherwise for a fee). Then they must upload the program to the developer’s site and download it to their device.
Despite the difficulties, currently apps for Apple Devices—the IPhone, IPod and IPad—have the most potential and are the most sought after.
Android Phones and Tablets
Currently, Android devices are very competitive with Apple devices on the market. Android uses a subset of Java and Xml for developing apps. Android’s chief advantages for developers are the inexpensiveness and availability of its tools. Both Java and the Android SDK are free and can be incorporated into free, but robust programming environments such as Eclipse and the Motorola programming environment. One can also copy apps directly from the computer to a device for testing.
The disadvantages of Android are found in the variety of versions of the operating system in simultaneous use. It is hard to create an app that is guaranteed to work on all devices. Also distribution is less centralized and incorporates less quality control than the Apple products. The SDK itself is not entirely stable. Frequent bugs are encountered.
Windows Phones and Tablets
Windows phones offer an opportunity to develop apps for an operating system that currently doesn’t have many apps—an opportunity to get in on the ground floor. Currently, phones with the Microsoft OS are a distant 4th in commercial sales (behind Apple, Android and Blackberry ), but with Nokeia’s now manufacturing Windows’ phones and Microsoft’s new Windows 8 operating system (see below) , the Window’s platform has the potential to grow enormously.
Windows Phone apps are developed using C# and Xml, specifically XAML (was Silverlight) and XNA (Xbox). They can also be developed using HTML 5 and JavaScript.
Blackberry Apps
Blackberry is fading from the consumer phone scene. They recently made the decision to focus on Commercial business customers. Like Android, Blackberry apps are written mainly in Java.
HTML 5 and Cross platform development
It is possible, with HTML 5, CSS, JavaScript and a platform like PhoneGap (http://phonegap.com/) to develop once and deploy on all platforms. The applications developed this way run in the device browser though without the address bar or any browser toolbars. Because of a JavaScript add in, these applications can access most of the native services of the OS.
The advantages are obvious, especially for someone who is more familiar with Web Development than with Java or Objective c. Design of the application is just a matter of html and CSS. JavaScript is used to tie into the native API. Development times can be faster and one can develop for IOS, Android and Windows phones all at once. In the case of PhoneGap, a developer can send the raw files to PhoneGap and they will return them with an executable for each platform.
The disadvantages are more subtle. The html platforms typically are a little behind the primary phone developments, so not all the latest features of the operating systems and devices may be available. Because the HTML5 apps run in a browser control, essentially as a web page, they may not have the appropriate look and feel of a native app. It is entirely up to the developer to implement this in CSS. Additionally, especially for complex apps, the fact that the app runs in a browser control may affect performance to some degree.
Which approach to take, native code development or HTML5, depends on the nature of the app being developed. There is a lot to be said for the HTML5 approach, especially for simpler apps. For more control, greater extensibility and guaranteed access to the system, native coding is better.
Windows Eight
Windows Eight is Microsoft’s attempt to create an operating system that is consistent across all platforms. It should look and behave essentially the same whether on a desktop, laptop, tablet, phone, or embedded device. All will share the same interface called “Metro,” which can be manipulated by mouse, touch, voice and possible gesture. Metro applications are deeply integrated with the cloud and social networks. Opinions vary as to the potential success and effect of Windows 8. Some see it as the paradigm for computing in the near future and others see it as a belated attempt by Microsoft to make inroads into a market already controlled by Apple and Android. But whatever the ultimate outcome, Windows 8 will be on millions of computers and developers should grow comfortable with developing for it.
In its current form Windows eight has two development targets. A developer can develop for the Windows 7 desktop, or for the Metro applications native to Windows 8. The desktop applications will not transfer to tablets or phones, and it is likely that Microsoft will phase out the Windows 7 compatibility in future versions of the operating system. Therefore it is prudent to focus on the new Metro interface.
Programming for Window's Metro can be done with a variety of tools. A developer can use HTML 5 and JavaScript, he or she can use c# or VB with XAML, or a developer can use the XBox XNA tools (also c# and XML). Visual Studio is the default developers platform, though Microsoft has also introduced the Web Expression IDE which provides a less code centric way of producing sophisticated applications.
Social Networking
Existing Social Networking does offer some opportunities for the developer. These opportunities are really of two kinds. One is to develop secondary apps such as games and services that can be accessed through a social network like Facebook such as Farmville. These games are typically created in Adobe’s Flash platform. A second opportunity exists in data mining, in creating programs that collect and analyze information about the users of social networks.
The more likely interaction with the social networks for the app or web developer is the need to incorporate social networking into their programs. This can be as simple as linking to Facebook or Twitter or as complex as developing new social networking tools specific to their app or site.
Device Programming
By Device programming I am referring to devices other than phones and tablets. These devices are numerous and becoming more so every day. They include things that are common now like GPS devices. But there are many others. Cars increasingly have computer applications built into their dashboards (as well as the code that is now necessary for their engines to run). Household appliances may soon have computer code that will link them to phones and tablets.
Currently, the language of choice for these devices is Java. That may or may not change with time.
Conclusions
As noted at the beginning all these topics are related. Apps use the Cloud. The Cloud and app both incorporate the web. Social networking is ubiquitous throughout it all. Many of the skill sets required are also the same.
Basic programming skills are still required. Nobody can approach the more advanced features or make use of these development opportunities who does not have a good foundation in programming fundamentals. Below is a list of some of those skills in no particular order:
• One still has to master declaring variables, writing statements, using selection and repetition structures, creating and accessing arrays, etc.. • In addition, one needs the object oriented concepts. One must understand how to instantiate and use objects. • One should also know how to extend them through inheritance. • Using collections such as lists and hash tables is valuable. • File IO, especially with XML is important. • Understanding event driven architecture and how to respond to event calls is critical. • Algorithms and program planning--UML • Security requirements. How to write secure code
In addition to these skills a developer should also have a good grasp of:
• Service Oriented architecture, how to create and consume services • Threading, separating processes for background operations • Forms and user Interface development • Database structures with some SQL (for SQL lite in Android and for developing services that talk to databases) • Code and memory optimization • Networking protocols particularly IP, http, https. • Incorporating social networking
Notes and References
ICT Trends Book, Center of Excellence for Information and Computing Technology,Bellevue College. Bellevue, 2011
Cloud Computing
Wikipedia:
http://en.wikipedia.org/wiki/Cloud_computing
PC Magazine
http://www.pcmag.com/article2/0,2817,2372163,00.asp
IBM
http://www.ibm.com/cloud-computing/us/en
Wired
http://www.wired.com/cloudline/2011/12/moores-law-cloud/MSNBC (on cloud computing and other trends)
http://gadgetbox.msnbc.msn.com/_news/2012/01/05/9956634-ces-2012-preview-top-7-mobile-and-computing-trends-to-watch
Cloud Service Providers
Microsoft
http://www.microsoft.com/en-us/server-cloud/readynow/
Amazon
http://aws.amazon.com/ec2/
Apps
Articles
http://www.marketwatch.com/story/the-app-economy-is-creating-jobs-2011-09-20
http://www.crainsnewyork.com/article/20110323/SMALLBIZ/110329951
http://www.wired.com/magazine/2010/08/ff_webrip/all/1
Article from ReadWriteWeb: http://www.readwriteweb.com/mobile/2010/09/native-apps-account-for-half-of-mobile-internet-traffic.php
Developers Sites
Android Development http://developer.android.com/guide/topics/fundamentals.html
Windows Phone Development
http://msdn.microsoft.com/en-us/library/ff402531(v=vs.92).aspx
Blackberry Phone Development
https://bdsc.webapps.blackberry.com/devzone/
Phone Gap
http://phonegap.com/
Android Object Model
This image comes from the Android development web site( http://www.android.org ). It depicts the basic Android Object model.
Android runs on a Linux kernel. Android is Java and runs on a specially taylored Java run time virtual machine called "Dalvik"
Above that are the basic Android libraries that tie into graphics libraries and sql lite among other things.
Next is the application Framework which provides the APIs for Android application development
Android applications ride on the top most layer
Create and alter Table
--Create tables use CommunityAssist --creating a table -- if you need a schema just add the schema.TableName --employee.Meeting Create table Meeting ( MeetingID int identity(1,1) primary key, MeetingDate Date not null, MeetingTopic NVarchar(255) not null, MeetingNotes xml ) --an example of a auto generated key --PK__Meeting__E9F9E9AC33D4B598 --table with keys as named constraints Create Table MeetingAttendance ( MeetingAttendanceId int identity(1,1), MeetingID int not null Foreign key references Meeting(MeetingID), EmployeeKey int not null, Constraint PK_MeetingAttendance Primary Key(MeetingAttendanceID), Constraint FK_EmployeeAttending Foreign Key (EmployeeKey) References Employee(EmployeeKey) ) --this table is made without any constraints Create table MeetingRating ( MeetingRatingID int identity (1,1), MeetingId int not null, Rating int default 0 ) --the constraints are added in alter table statments Alter table MeetingRating Add Constraint PK_MeetingRating Primary key(MeetingRatingID) Alter table MeetingRating Add Constraint FK_Meeting Foreign Key(MeetingID) References Meeting (MeetingID) --this does a check constraint that --limits the value to values between 0 and 5 Alter Table MeetingRating Add Constraint ck_RatingValue Check (Rating between 0 and 5)-- --this would force the Meeting Rating value --to be unique Alter table MeetingRating Add Constraint uq_Rating unique (Rating) --this drops the rating constraint Alter Table MeetingRating Drop Constraint uq_Rating --Drop Table MeetingRating --to alter or even rename a column --you must drop it an re add it --you will lose any data in the column --if you don't copy it somewhere Alter table Meeting Drop column MeetingNotes Alter table Meeting Add MeetingNotes xml
Thursday, April 19, 2012
Activity Diagrams
Here is an example of a basic Activity diagram. Activity diagrams depict the flow of actions in a process
Here is a second version of the same Activity but using "Swim Lanes." Swim Lanes divide the activities according to which objects or areas have responsibility for that activity.
Wednesday, April 18, 2012
Refactoring Example Class
Refactoring
Refactoring refers to the process of rearranging code to make it more elegant and efficient. These rearrangements do not affect the function of the code, but make it more readable and maintainable
Refactoring can involve any of the following activities
1. Renaming variables
2. Encapsulating Fields in sets and gets
3. Extracting methods (taking repeating code putting it in its own method)
4. Extracting an interface
5. Extracting classes (breaking code into new separate classes)
6. Extracting super classes<
Here is a picture of the class diagram for the class
here is the code for a class we will practice refactoring in class
public class Tip { /* * Assume the programmer wanted to expand the tip class * to handle tips for things other than a meal * such as taxis and valet parking * For taxis the suggested tip is a percent of the * meter cost plus a dollar per bag * For the valet parking it is a little looser * based on the expense or quality of the venue and the * expensiveness of your car * The programmer has adapted the one class to handle the * different types of tips */ private double mealAmount; private double tipPercent; private double taxPercent; private double cabFare; private int bags; private int eventRating; //1 to 5 five most expensive private int vehicleValue; //(1 to 5); private final double CABPERCENT =.07; //************************************************* //Constructors for the various uses //************************************************** //empty constructor public Tip(){ } //Meal tip constructor public Tip(double meal, double tipPerc, double tax){ setMealAmount(meal); setTipPercent(tipPerc); setTaxPercent(tax); } //constructor for taxis public Tip(double fare, int bags){ setCabFare(fare); setBags(bags); } //constructor for Valet public Tip(int event, int vehicle){ setEventRating(event); setVehicleValue(vehicle); } //********************************************* //gets and sets //********************************************* public double getMealAmount() { return mealAmount; } public void setMealAmount(double mealAmount) { this.mealAmount = mealAmount; } public double getTipPercent() { return tipPercent; } public void setTipPercent(double tipPercent) { if(tipPercent >=1){ tipPercent /= 100; } this.tipPercent = tipPercent; } public double getTaxPercent() { return taxPercent; } public void setTaxPercent(double taxPercent) { if(taxPercent >=1){ taxPercent /= 100; } this.taxPercent = taxPercent; } public double getCabFare() { return cabFare; } public void setCabFare(double cabFare) { this.cabFare = cabFare; } public int getBags() { return bags; } public void setBags(int bags) { this.bags = bags; } private int getEventRating() { return eventRating; } private void setEventRating(int eventRating) { if (eventRating < 1 ) eventRating = 1; else if (eventRating > 5) eventRating=5; this.eventRating = eventRating; } public int getVehicleValue() { if (vehicleValue< 1 ) vehicleValue = 1; else if (vehicleValue > 5) vehicleValue=5; return vehicleValue; } public void setVehicleValue(int vehicleValue) { this.vehicleValue = vehicleValue; } //************************************** //public methods //************************************* //calculate tip percent public double calculateMealTip(){ return getMealAmount() * getTipPercent(); } //calculate Taxi Tip public double calculateTaxiTip(){ return getCabFare() * CABPERCENT + getBags(); } public double calculateValetTip(){ int weight=getVehicleValue() + getEventRating(); double tipAmount=0; switch (weight){ case 1: case 2: case 3: tipAmount=5; break; case 4: case 5: case 6: tipAmount=10; break; case 7: case 8: tipAmount=15; case 9: case 10: tipAmount=20; break; default: tipAmount=10; break; } return tipAmount; } public double calculateTax(){ return getMealAmount()*getTaxPercent(); } public double CalculateMealTotal(){ return getMealAmount() + calculateTax() + calculateMealTip(); } public double CalculateTaxiTotal(){ return getCabFare()+calculateTaxiTip(); } public double CalculateValetTotal(){ return calculateValetTip(); } }
Insert, Update, Delete
--Inserts updates and deletes Use CommunityAssist --basic insert statement Insert into Person (LastName, FirstName) Values ('Bowie', 'David') --inserting multiple rows Insert into Person(LastName, FirstName) Values('Madonna', null), ('Dylan', 'Bob'), ('Gaga', 'Lady') --inserting into a child table (need to have the foreign key) Insert into PersonAddress( Street, Apartment, [State], City, Zip, PersonKey) Values('Somewhere on the Road',null,'Mn','Duluth',null, 54) Select * From Person Select LastName, FirstName, Street, [State], City From Person p inner join PersonAddress pa on p.PersonKey=pa.PersonKey Where LastName='Dylan' Insert into Person(LastName, FirstName) Values('Young', 'Neil') --the ident_current(table name) returns the last key generated --for the named table, though that only works --on tables with an int identity key Insert into PersonContact(ContactInfo, PersonKey, ContactTypeKey) Values('neilyoung@harvest.com',IDENT_CURRENT('Person'), 6) Select * from PersonContact -- create a new table Create table Person2 ( LastName nvarchar(255), firstName nvarchar(255) ) --copy all the lastnames and firstnames --from Person into the new table --the new table's columns must have --compatible datatypes and there must be --the same number of fields in the select --as in the insert Insert into Person2(Lastname, firstname) Select lastname, firstname from Person Select * from Person2 --basic update with criteria --almost always an update should have --clear and precise criteria Update Person2 Set firstName='Jane' where firstName='Jay' and LastName='Anderson' --updating multiple fields Update Person2 Set LastName='Manning', firstName='Lewis' where LastName='Mann' and firstName='Louis' --Deletes all records from person2 Delete From Person2 --same as delete Truncate table Person2 --you can manually control transactions --for safety --a transaction can either be committed (written to database) --or rolled back Begin tran Update Person2 Set LastName='smith' Where LastName='Carmel' commit tran Rollback tran Select * From Person2 Begin tran Delete from Person Delete from PersonAddress Select * from Person RollBack tran Begin tran Alter table Person2 Drop column firstname Rollback tran Update Donation set DonationAmount=DonationAmount *1.1 Select * from Donation
Tuesday, April 17, 2012
Login Example
Don't forget to add this line to the web.config file. Also don't break up the connectionString line. I did that to make it fit on the blog page.
<connectionStrings> <add name="CommunityAssistConnection" connectionString="Data Source=LocalHost; initial catalog=CommunityAssist; integrated security=true" /> </connectionStrings>
Here is the login class
using System; using System.Collections.Generic; using System.Linq; using System.Web; //the Ado and config libraries using System.Data; using System.Data.SqlClient; using System.Configuration; ////// Summary description for LoginClass /// public class LoginClass { private string user; private string pass; public LoginClass(string username, string password) { user=username; pass=password; } public bool ValidateLogin() { bool valid = false; SqlConnection connect = new SqlConnection (ConfigurationManager. ConnectionStrings["CommunityAssistConnection"]. ToString()); string Sql = "SELECT LastName, SSNumber " + "FROM Person " + "Inner Join Employee " + "On Person.PersonKey=Employee.PersonKey " + " Where Lastname=@user " + "And SSNumber=@pass"; SqlCommand cmd = new SqlCommand(Sql, connect); cmd.Parameters.AddWithValue("@user", user); cmd.Parameters.AddWithValue("@pass", pass); DataSet ds = new DataSet(); SqlDataReader reader = null; connect.Open(); reader = cmd.ExecuteReader(); ds.Load(reader, System.Data.LoadOption.OverwriteChanges,"Validate"); reader.Dispose(); connect.Close(); foreach (DataRow row in ds.Tables["Validate"].Rows) { if (row["LastName"].ToString().Equals(user) && row["SSNumber"].ToString().Equals(pass)) { valid = true; } } return valid; } }
here is source for Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt" onauthenticate="Login1_Authenticate1"> <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" /> </asp:Login> </div> </form> </body> </html>
Here is the code behind Default.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Login1_Authenticate1(object sender, AuthenticateEventArgs e) { LoginClass l = new LoginClass(Login1.UserName, Login1.Password); bool good = l.ValidateLogin(); if (good) { e.Authenticated = true; Session["loginName"] = Login1.UserName.ToString(); Response.Redirect("Default2.aspx"); } } }
Here is the source for Default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
Here is the code behind Default2.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string name = Session["loginName"].ToString(); Label1.Text = "Welcome " + name; } }
Kioak objects from Class
Kiosk Objects
Item (code, name, price, weight, restricted, sold by, taxable)
Scanner (item, scanitem(), AddToShoppingCart() )
BagScale
ProduceScale
Display
ATM (another who system--actors)
DataBase (Another system—actors)
Customer
Clerk
Alert
Shopping cart
Coupon
here is the diagram for the Item object
Monday, April 16, 2012
ArrayList Sample
These classes show a Sale class that contains an ArrayList of items. Item is a separate class that acts as a container for a set of fields.
Here is the code
Here is Item.java
public class Item { private String itemNumber; private String itemName; private double ItemPrice; public String getItemNumber() { return itemNumber; } public void setItemNumber(String itemNumber) { this.itemNumber = itemNumber; } String getItemName() { return itemName; } void setItemName(String itemName) { this.itemName = itemName; } double getItemPrice() { return ItemPrice; } void setItemPrice(double itemPrice) { ItemPrice = itemPrice; } }
Sale.java
import java.util.*; public class Sale { String saleNumber; String saleDate; ArrayList<Item> items; public Sale(String saleNumber, String saleDate){ this.saleNumber=saleNumber; this.saleDate=saleDate; items=new ArrayList<Item>(); } public void addItem(Item i){ items.add(i); } public ArrayList<Item> getItems(){ return items; } public double calculateTotalSale(){ double total=0; for(Item i : items){ total+=i.getItemPrice(); } return total; } }
Main.java
import java.util.*; public class Main { /** * @param args */ Sale s; public static void main(String[] args) { Main m = new Main(); m.CreateSale(); m.ReadSale(); } private void CreateSale() { s = new Sale("2221", "4/16/2012"); Item i = new Item(); i.setItemName("Apple"); i.setItemNumber("1"); i.setItemPrice(1000000.00); s.addItem(i); Item i2 = new Item(); i2.setItemName("IBM"); i2.setItemNumber("2"); i2.setItemPrice(100000.00); s.addItem(i2); } private void ReadSale(){ ArrayList<Item>items=s.getItems(); for(Item item : items ){ System.out.println(item.getItemName()); System.out.println(item.getItemPrice()); } System.out.println(s.calculateTotalSale()); } }
Sub Queries
--having example --where always comes before group by --having always comes after group by --having is for criteria that uses a aggregate function Select LastName, FirstName, Sum(DonationAmount) From Employee e Inner join Person p on p.PersonKey = e.PersonKey inner join Donation d on e.EmployeeKey =d.EmployeeKey Where LastName like 'l%' Group by LastName, FirstName Having SUM(DonationAmount) > 9000 Select MAX(DonationAmount) from Donation --using a sub query to get the info about --which donation is the maximum Select DonationKey, DonationDate, donationAmount, PersonKey From Donation Where DonationAmount = (Select MAX(DonationAmount) From Donation) --all the donations greater than the average donation Select DonationKey, DonationDate, donationAmount, PersonKey From Donation Where DonationAmount > (Select Avg(DonationAmount) From Donation) Select AVG(donationAmount) From Donation --include the average as a subquery in the select Select DonationKey, DonationDate, donationAmount, (Select AVG(donationAmount) From Donation) as Average, PersonKey From Donation Where DonationAmount > (Select Avg(DonationAmount) From Donation) --this assigns the subquery to a variable and uses it --whereever the subquery would be used Declare @Average money Select @Average=AVG(DonationAmount) From Donation Select DonationKey, DonationDate, donationAmount, @Average as Average, PersonKey From Donation Where DonationAmount > @Average --uses subqueries to get the differance --between the donation and the average donation Select DonationKey, DonationDate, donationAmount, (Select AVG(donationAmount) From Donation) as Average, DonationAmount-(Select AVG(donationAmount) From Donation) as [Difference], PersonKey From Donation Where DonationAmount > (Select Avg(DonationAmount) From Donation) --use in and a subquery as a substitute --for a join Select LastName, Firstname From Person Where PersonKey in (Select PersonKey from Donation) --this gets the lastname into the query by means --of a subquery (which contains a join) Select (select lastname From Person p where p.personkey = personAddress.personkey) Lastname,PersonAddressKey, Street, Apartment, [State], City, Zip, PersonKey From PersonAddress Where PersonKey in (Select PersonKey From Donation) --a three table sub query Select LastName, Firstname From Person where PersonKey in (Select PersonKey From Employee where EmployeeKey in (Select EmployeeKey from ServiceGrant)) --three table subquery with not in --returns everyone who is not an employee Select LastName, Firstname From Person where PersonKey in (Select PersonKey From Employee where EmployeeKey not in (Select EmployeeKey from ServiceGrant)) --use of any --returns any value that is greater than any other value --eveything except the minimum value Select DonationAmount from Donation where DonationAmount > any (Select DonationAmount from Donation) --use of all, returns a value that is greater than --or equal to all the values --same as returning the maximum value Select DonationAmount from Donation where DonationAmount >= all (Select DonationAmount from Donation) --exists returns a boolean. This tests --where a particular table exists in a system table if exists (Select name from sys.tables where name='donation') begin print 'yep it''s there' end else Begin print 'Nope it''s not' end --some system table stuff Select name from sys.Tables use master Select name from sys.databases use CommunityAssist --this system stored procedure returns everything --from the system tables about the table --Donation exec sp_Help 'Donation'
Sunday, April 15, 2012
Swing Menus
This code represents a simple example of how to use and implement Swing Menus to open additional forms. An alternate way, that doesn't use multiple forms but rather switches out JPanels in a single frame is the CardLayout. You may want to explore this in the documentation and with on-line examples.
Here are pictures of the programs menus and forms running.
File Menu
Edit Menu
After clicking the Form 1 menu
Here is the code for MainWindow.java which includes the menus.
import javax.swing.*; import java.awt.FlowLayout; import java.awt.event.*; public class MainWindow extends JFrame implements ActionListener { /** * this form creates a simple menu * under File there is only one menu item, Exit * under Edit you have option to open Form1 * and Form2 */ private static final long serialVersionUID = 1L; JFrame frame; JPanel panel; JMenu menuFile; JMenu menuEdit; JMenuBar menuBar; JMenuItem menuItem1; JMenuItem menuItem2; JMenuItem menuItem3; public MainWindow(){ createMenu(); frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setJMenuBar(menuBar); createPanel(); this.add(panel); } private void createMenu(){ //Declare a new menu bar menuBar = new JMenuBar(); //create a Menu on that menu bar menuFile = new JMenu("File"); //this sets a keyboard equivalent //on PCs ALT F menuFile.setMnemonic(KeyEvent.VK_F); //Define the menu items menuItem1 = new JMenuItem("Exit"); menuItem1.setMnemonic(KeyEvent.VK_X); menuItem1.addActionListener(this); menuEdit = new JMenu("Edit"); menuEdit.setMnemonic(KeyEvent.VK_E); menuItem2=new JMenuItem("Form1"); menuItem2.setMnemonic(KeyEvent.VK_1); menuItem2.addActionListener(this); menuItem3 = new JMenuItem("Form2"); menuItem3.setMnemonic(KeyEvent.VK_2); menuItem3.addActionListener(this); //Add the menu items to the menus menuFile.add(menuItem1); menuEdit.add(menuItem2); menuEdit.add(menuItem3); //add the menus to the menu bar menuBar.add(menuFile); menuBar.add(menuEdit); } private void createPanel(){ panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JLabel label=new JLabel("Main Form"); panel.add(label); //frame.add(panel); } @Override public void actionPerformed(ActionEvent arg0) { Object source = arg0.getSource(); if(source==menuItem1) System.exit(0); if(source==menuItem2){ JFrame frame = new Form1(); frame.setBounds(200,200,350,120); frame.setVisible(true); } if(source==menuItem3){ JFrame frame = new Form2(); frame.setBounds(200,200,350,120); frame.setVisible(true); } } }
Here are the two forms
Form1.java
import javax.swing.*; import java.awt.FlowLayout; public class Form1 extends JFrame { public Form1(){ JFrame frame=new JFrame(); JPanel panel; panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JLabel label=new JLabel("Form1"); panel.add(label); this.add(panel); } }
Form2.java
import javax.swing.*; import java.awt.FlowLayout; public class Form2 extends JFrame{ public Form2(){ JFrame frame=new JFrame(); JPanel panel; panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JLabel label=new JLabel("Form2"); panel.add(label); this.add(panel); } }
Here is the Main.java class
import javax.swing.*; public class Main { /** * @param args */ public static void main(String[] args) { JFrame m = new MainWindow(); m.setBounds(100,100,350,120); m.setVisible(true); } }
Thursday, April 12, 2012
ADO Example One
The form has a Gridview and a button. Here is the code for the first ADO example. I commented it thoroughly
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; //ADO libraries using System.Data; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //create a connection object for connecting to the database //the Data source is the server //the initial catalog is the database //integrated security means use your windows account for authentication //only works if your windows account has permission in sql Server SqlConnection connect = new SqlConnection ("Data source=localhost;Initial Catalog=CommunityAssist;integrated Security=true"); //sql string string sql = "Select * from [Service]"; //the command object passes the sql through the connection //to the server SqlCommand cmd = new SqlCommand(sql, connect); //the data reader reads the data //but doesn't retain it SqlDataReader reader = null; //open the connection //most errors will occur here because //this is the first time that any of the code //is actually executed connect.Open(); //execute the reader through the command object reader = cmd.ExecuteReader(); //write the data into the GridView GridView1.DataSource = reader; //bind the data to the grid GridView1.DataBind(); //get rid of the reader reader.Dispose(); //close the connection connect.Close(); } }
Use Cases
Here are the diagrams we did in class. The first diagram looks at the system from the employees perspective. The employee is seen as a child (inheriting) from the actor person. The change schedule use case is dependent on the employee logging in. The contact security use case extends the use case Access doors. If the door fails to open, security will be alerted.
here is a written description of the employee use case Access Assigned doors.
Use Case: Access Assigned Rooms Initial Condition: Valid Employee Card. Scheduled for Room. Door Locked. (System on and Armed) Trigger: Employee requires Access Steps: 1. Swipe card 2. Card number, Time, Date, Scanner Number sent to be Validated 3. Card number matched, access validated 4. Scan logged as good 5. Door unlocked Post Condition: Door Status Open
Here is the Security use case diagram.
Here is a link to an open source program that will do UML if you don't have or want Viso. It should also work on a MAC. ArgoUML
Wednesday, April 11, 2012
Joins
--Joins Use CommunityAssist --simple inner join you using the inner join syntax --you must specify how the tables relate in the on clause --almost always primary key=foreignkey (though --the order doesn't matter) --inner joins return only matching records Select Firstname, lastname, DonationAmount, donationDate From Person Inner Join Donation --inner join and just join are equivalent On Person.PersonKey=Donation.PersonKey --this is an older syntax to do the same thing Select Firstname, lastname, DonationAmount, donationDate From Person, Donation Where Person.PersonKey=Donation.PersonKey; --multiple table join --contacttypekey 1 = home phone --this returns fewer donors because 4 don't have --home phones Select Firstname, lastname, ContactInfo [phone], DonationAmount, donationDate From Person Inner Join Donation On Person.PersonKey=Donation.PersonKey inner join PersonContact on Person.PersonKey=PersonContact.PersonKey Where ContactTypeKey=1 --same as above older syntax Select Firstname, lastname, ContactInfo [phone], DonationAmount, donationDate From Person, Donation, PersonContact Where person.PersonKey=donation.PersonKey And person.PersonKey=PersonContact.PersonKey And ContactTypeKey=1 --inner join using table aliases Select p.personkey, Firstname, lastname, ContactInfo [phone], DonationAmount, donationDate From Person p Inner Join Donation d On p.PersonKey=d.PersonKey inner join PersonContact pc on p.PersonKey=pc.PersonKey Where ContactTypeKey=1 --explicit cross join syntax --a cross join matches each record in the --first named table with every record in the second one Select Lastname, DonationDate From Person Cross Join Donation --the older cross join syntax Select Lastname, DonationDate From Person, Donation Select * From [Service] --an outer join to see which grant types --have never been granted --an outer join returns all the records from one --table, here the left or first table, and only --matching records from the second (right) table --in the result set, those from the first table --that have no matches in the second table --show up as nulls Select Servicename, GrantAmount From [Service] s Left Outer Join ServiceGrant sg on s.ServiceKey = sg.ServiceKey Where GrantAmount is null --a full outer join returns all the records from each --table whether or not they have matching records --in the other Select Servicename, GrantAmount From [Service] s full Outer Join ServiceGrant sg on s.ServiceKey = sg.ServiceKey
Here is a little example of self joins
--a self join joins a table with itself --here is a little script to show --an example Create Database sample GO Use sample Go Create table Employee ( EmployeeID int Primary key, lastName varchar(30) not null, Supervisior int ) GO Insert into Employee Values(1,'Smith', 3) Insert into Employee Values(2,'Rogers', 3) Insert into Employee Values(3,'Johnson', null) Insert into Employee Values(4,'Larson', 2) Insert into Employee Values(5,'Standish', 3) --the self join Select e.LastName as employee, s.Lastname as supervisor From employee e Inner join employee s on s.employeeid=e.supervisior
Tuesday, April 10, 2012
Objects for Card Scan System
Objects for Door electronic security system. This is only a preliminary brainstorming of the objects.
These are Domain objects. that means that they relate to the main business logic of the application. typically there are also Display objects that describe the forms and views of the application, and Data objects that control the access to data through files or database connections
Card Employees Clock(Schedule) Lock Administrator Alarm(Alert) Scanner Security scan Validator Door Visitor
Here is a simple class object for the Scan object
Monday, April 9, 2012
Aggregate Functions
--aggregate functions --sum, max, avg, min, count use CommunityAssist --this and the next return all rows Select COUNT(DonationKey) [Number of Donations] From Donation Select COUNT(*) [Number of Donations] From Donation --this only returns the number of those with dependents Select COUNT(Dependents) from Employee Select COUNT (*) From Employee Select SUM(DonationAmount) total From Donation --Distinct only includes unduplicated values Select SUM(Distinct DonationAmount) total From Donation Select AVG(DonationAmount) average From Donation Select AVG(Distinct DonationAmount) average From Donation Select DonationAmount from Donation order by DonationAmount desc --return biggest (also with cast to format it) Select '$' + Cast(MAX(donationAmount) as CHAR(10)) From Donation --return smallest value Select MIN(donationAmount)From Donation -- Select * from Donation --any column in the SELECT that is not a part of an aggregate function, --must be included in a GROUP BY Clause Select EmployeeKey, COUNT(DonationKey) [number of Donations] From Donation Group by EmployeeKey --a scalar (row by row) function with an aggregate --you have to group by the scalar Select MONTH(DonationDate) [Month], SUM(DonationAmount) total From Donation Group by MONTH(DonationDate) Order by [Month] --You must use HAVING with any criteria that uses an --aggregate function --these examples have both a having and a where clause Select EmployeeKey, AVG(DonationAmount) Average From Donation Where EmployeeKey > 2 Group by EmployeeKey Having AVG(DonationAmount) < 1000 Select Lastname,COUNT(Lastname) From Person Where LastName Like 's%' Group by lastname Having count(LastName) > 1
Thursday, April 5, 2012
Assignment 1 Examples
Here is the Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="A1Example.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <h1>Calculator Example</h1> <div> <table> <tr> <td colspan="2"> <asp:TextBox ID="txtDisplay" runat="server"> </asp:TextBox></td> </tr> <tr> <td> <asp:Button ID="btn1" runat="server" Text="1" CssClass="button" OnClick="number_click" /></td> <!--These buttons share the same event--> <td> <asp:Button ID="btn2" runat="server" Text="2" CssClass="button" OnClick="number_click"/></td> </tr> <tr> <td> <asp:Button ID="btnAdd" runat="server" Text="+" CssClass="button" onclick="btnAdd_Click"/></td> <td> <asp:Button ID="btnClear" runat="server" Text="Clear" CssClass="button"/></td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnEqual" runat="server" Text="=" CssClass="button" onclick="btnEqual_Click" /></td> </tr> </table> </div> </form> </body> </html>
Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void number_click(object sender, EventArgs e) { //this handles the number buttons //determine which number was clicked //and get the text from it Button b = (Button)sender; txtDisplay.Text += b.Text; //add to existing text } protected void btnAdd_Click(object sender, EventArgs e) { //get the number from the textbox //using the GetNumber() method double num = GetNumber(); //check to see if there is a number in the session if (Session["number"] != null) { //add the new number to the one in the session double n1 = (double)Session["number"]; Session["number"] = n1 + num; } else { //otherwise just the store number Session["number"] = num; } //clear the text txtDisplay.Text = ""; //store the operator in the session Session["operator"] = "+"; } protected void btnEqual_Click(object sender, EventArgs e) { //get the number stored in the session double num1 = (double)Session["number"]; //get the last operator string op = Session["operator"].ToString(); //Get the number from the text box double num2 = GetNumber(); //test which it operator is if(op.Equals("+")) { //do the operation and display it txtDisplay.Text=(num1 + num2).ToString(); } if(op.Equals("*")) { txtDisplay.Text=(num1* num2).ToString(); } //clear the sessions Session["number"] = null; Session["operator"] = null; } protected double GetNumber() { //get the value from the text box string number = txtDisplay.Text; //double num = double.Parse(number); double num=0; //try to parse the number //if it is good it returns true and assigns the value to num bool isGood = double.TryParse(number, out num); //if false let the user know if (isGood == false) { //creates a javascript alert Response.Write ("<script type='text/JavaScript'>alert('Learn your numbers');</script>"); txtDisplay.Text = ""; } //return the number return num; } }
A1Stylesheet.css
body { } td { width:30px; } p { font-size: large; } h1 { color:Navy; font-size:150%; } .button { width:40px; }
Wednesday, April 4, 2012
Scalar Functions
Here is the code we did in class for functions
--scalar functions Use CommunityAssist --only eliminates duplicate rows Select MONTH(DonationDate), DonationAmount From Donation Select Distinct MONTH(DonationDate), DonationAmount From Donation Select Distinct YEAR(donationDate) as [Year] from Donation Select Distinct DAY(DonationDate) as [Day] From Donation Select DATEPART(YY, DonationDate) From Donation Select DATEPART(dd, DonationDate) From Donation Select DATEPART(mm, DonationDate) From Donation Select DATEPART(WEEKDAY , DonationDate) From Donation Select DATEPART(Hour, DonationDate) From Donation Select DATEDIFF(hour, GETDATE(), '6/4/2012') Select GETDATE() Select Cast(DATEADD(dd, 20, GetDate()) as CHAR(11)) Select * From Donation Select Donationkey, '$' + CAST(DonationAmount as Char(10)) as Amount From Donation Select * from Employee Select SUBSTRING(SsNumber,1,3) + '-' + SUBSTRING (SSNumber,4,2) + '-' + SUBSTRING(SSNumber, 6, 4) From Employee Select * From PersonAddress Select SUBSTRING(Street, 1, charIndex(' ',Street,1)) From PersonAddress
Tuesday, April 3, 2012
First ASP
here is the asp code for Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="White" BorderWidth="1px" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="190px" NextPrevFormat="FullMonth" Width="350px" > <DayHeaderStyle Font-Bold="True" Font-Size="8pt" /> <NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" VerticalAlign="Bottom" /> <OtherMonthDayStyle ForeColor="#999999" /> <SelectedDayStyle BackColor="#333399" ForeColor="White" /> <TitleStyle BackColor="White" BorderColor="Black" BorderWidth="4px" Font-Bold="True" Font-Size="12pt" ForeColor="#333399" /> <TodayDayStyle BackColor="#CCCCCC" /> </asp:Calendar> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList><br /> <asp:Label ID="Label1" runat="server" Text="Enter Your Name" ></asp:Label> <asp:TextBox ID="txtName" runat="server" ></asp:TextBox><br /> <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" /> <br /> <asp:Label ID="lblResult" runat="server" Text="Label"> </asp:Label> </div> </form> </body> </html>
Here is the c# code Behind: Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //an array of animals if (!IsPostBack) { string[] animals = new string[4]; animals[0] = "Grizzly Bear"; animals[1] = "hamster"; animals[2] = "Zebra"; animals[3] = "Giraffe"; //binding the data to the control DropDownList1.DataSource = animals; DropDownList1.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { //retrieved all three values string animal = DropDownList1.SelectedItem.ToString(); string date = Calendar1.SelectedDate.ToShortDateString(); string name = txtName.Text; lblResult.Text = name + ", your animal is " + animal + ", your selected date is " + date; } }
Monday, April 2, 2012
Simple Selects
Use Automart; /*this is a multline comment */ --simple select Select Lastname, Firstname from Person --select with a wildcare Select * From Person --alias Select Lastname as [Last Name], FirstName as [First Name] From Person Select Lastname [Last Name], FirstName [First Name] From Person Select Lastname as "Last Name", FirstName as "First Name" From Person Select Lastname Last, FirstName First From Person --concatination Select LastName + ', ' + Firstname [Person Name] From Person --order by Select Lastname, Firstname From Person order by lastname Desc, firstname asc Select top 5 Lastname from Person order by lastname Select * From Person Where LastName='Smith' Select * from Person Where LastName Like 'S%' Select * From Employee.VehicleService Where ServiceDate between '4/1/2010' and '4/30/2010' Select * From Employee.VehicleService Where ServiceDate >= '4/1/2010' and ServiceDate <= '4/30/2010' Select * From Customer.AutoService Where ServicePrice > 100 Select * From Employee Where SupervisorID is not null Select * From Employee Where SupervisorID = null