Friday, December 28, 2012

Java JDBC

ILookup.java

import java.util.List;

public interface ILookup {
void SaveStudentSurveyFormData(StudentBean postData);
StudentBean GetStudentSurveyData(String studentId);
Surveys GetSurveys();
List<String> GetSurveyIds();
}

StudentDbDAO.java

package gmu.swe642.hw6;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentDbDAO implements ILookup {
private Connection con;

public StudentDbDAO(){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection ( "jdbc:oracle:thin:@",
dbusername, dbpassword);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public void SaveStudentSurveyFormData(StudentBean postData){
try {
PreparedStatement pstat = con.prepareStatement("insert into survey values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstat.setString(1, postData.getStudentId());
pstat.setString(2, postData.getFirstName());
pstat.setString(3, postData.getLastName());
pstat.setString(4, postData.getStreet());
pstat.setString(5, postData.getZip());
pstat.setString(6, postData.getCity());
pstat.setString(7, postData.getState());
pstat.setString(8, postData.getTelephone());
pstat.setString(9, postData.getEmail());
pstat.setString(10, postData.getUrl());
pstat.setString(11, postData.getDateOfSurvey());
pstat.setString(12, postData.getGraduationMonth());
pstat.setString(13, postData.getGraduationYear());
pstat.setString(14, postData.getLikes());
pstat.setString(15, postData.getInterests());
pstat.setString(16, postData.getRecommendation());
pstat.setString(17, postData.getComments());
pstat.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public StudentBean GetStudentSurveyData(String studentId){
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}

public Surveys GetSurveys(){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from survey");

while (rs.next())
{
String studentId = rs.getString(Consts.STUDENTID);
String firstName = rs.getString(Consts.FIRSTNAME);
String lastName = rs.getString(Consts.LASTNAME);
String street = rs.getString(Consts.STREET);
String zip = rs.getString(Consts.ZIP);
String city = rs.getString(Consts.CITY);
String state = rs.getString(Consts.STATE);
String telephone = rs.getString(Consts.TELEPHONE);
String email = rs.getString(Consts.EMAIL);
String url = rs.getString(Consts.URL);
String dateOfSurvey = rs.getString(Consts.DATEOFSURVEY);
String graduationMonth = rs.getString(Consts.GRADUATIONMONTH);
String graduationYear = rs.getString(Consts.GRADUATIONYEAR);
String likes = rs.getString(Consts.LIKES);
String interests = rs.getString(Consts.INTERESTS);
String recommendation = rs.getString(Consts.RECOMMENDATION);
String comments = rs.getString(Consts.COMMENTS);

StudentBean s = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likes, interests, recommendation, comments);
surveys.data.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}

return surveys;
}

public List<String> GetSurveyIds(){
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
}


Apache Struts with Actions and Form Beans

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>swe642hw5khuc</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
  <param-name>config</param-name>
  <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
    <form-beans>
    <form-bean name="surveyFormBean" type="package.SurveyFormBean"/>
    <form-bean name="surveyLookupFormBean" type="package.SurveyLookupFormBean"/>
    </form-beans>

    <action-mappings>
        <action path="/submitSurvey" type="package.SubmitSurveyAction" name="surveyFormBean" scope="session">        
        <forward name="simple-ack" path="/jsp/SimpleAcknowledgementJSP.jsp" />
        <forward name="winner-ack" path="/jsp/WinnerAcknowledgementJSP.jsp" />
        </action>
        <action path="/displaySurvey" type="package.DisplaySurveyAction" scope="session">
        <forward name="survey-found" path="/jsp/StudentJSP.jsp" />
        <forward name="survey-not-found" path="/jsp/NoSuchStudentJSP.jsp" />
        </action>
    </action-mappings>
</struts-config>

SubmitSurveyAction.java
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class SubmitSurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
SurveyFormBean formBean = (SurveyFormBean)form;

StudentBean studentBean = new StudentBean(formBean.getStudentId(),formBean.getFirstName(), formBean.getLastName(),
formBean.getStreet(), formBean.getZip(), formBean.getCity(), formBean.getState(),
formBean.getTelephone(), formBean.getEmail(), formBean.getUrl(), formBean.getDateOfSurvey(),
formBean.getGraduationMonth(), formBean.getGraduationYear(), formBean.getLikes(),
formBean.getInterests(), formBean.getRecommendation(), formBean.getComments());

StudentDAO.SaveStudentSurveyFormData(studentBean);

DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(formBean.getData());

List<String> surveyIdsBean = StudentDAO.GetSurveyIds();

HttpSession session = request.getSession();

session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);

if(dataBean.getMean() > 90){
return mapping.findForward("winner-ack");
}
return mapping.findForward("simple-ack");
}
}

DisplaySurveyAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DisplaySurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
String studentId = request.getParameter("studentId");
StudentBean studentBean = null;

if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}

HttpSession session = request.getSession();

if(studentBean == null){
session.setAttribute("badId", studentId);
return mapping.findForward("survey-not-found");
}
else{
session.setAttribute("student", studentBean);
return mapping.findForward("survey-found");
}
}
}

SurveyFormBean.java
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class SurveyFormBean extends ActionForm {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String[] likes;
private String interests;
private String recommendation;
private String comments;
private String data;

public String getStudentId(){
return this.studentId;
}

public void setStudentId(String studentId){
this.studentId = studentId;
}

public String getFirstName(){
return this.firstName;
}

public void setFirstName(String firstName){
this.firstName = firstName;
}

public String getLastName(){
return this.lastName;
}

public void setLastName(String lastName){
this.lastName = lastName;
}

public String getStreet(){
return this.street;
}

public void setStreet(String street){
this.street = street;
}

public String getZip(){
return this.zip;
}

public void setZip(String zip){
this.zip = zip;
}

public String getCity(){
return this.city;
}

public void setCity(String city){
this.city = city;
}

public String getState(){
return this.state;
}

public void setState(String state){
this.state = state;
}

public String getTelephone(){
return this.telephone;
}

public void setTelephone(String telephone){
this.telephone = telephone;
}

public String getEmail(){
return this.email;
}

public void setEmail(String email){
this.email = email;
}

public String getUrl(){
return this.url;
}

public void setUrl(String url){
this.url = url;
}

public String getDateOfSurvey(){
return this.dateOfSurvey;
}

public void setDateOfSurvey(String dateOfSurvey){
this.dateOfSurvey = dateOfSurvey;
}

public String getGraduationMonth(){
return this.graduationMonth;
}

public void setGraduationMonth(String graduationMonth){
this.graduationMonth = graduationMonth;
}

public String getGraduationYear(){
return this.graduationYear;
}

public void setGraduationYear(String graduationYear){
this.graduationYear = graduationYear;
}

public String[] getLikes(){
return this.likes;
}

public void setLikes(String[] likes){
this.likes = likes;
}

public String getInterests(){
return this.interests;
}

public void setInterests(String interests){
this.interests = interests;
}

public String getRecommendation(){
return this.recommendation;
}

public void setRecommendation(String recommendation){
this.recommendation = recommendation;
}

public String getComments(){
return this.comments;
}

public void setComments(String comments){
this.comments = comments;
}

public String getData(){
return this.data;
}

public void setData(String data){
this.data = data;
}
}

StudentDAO with FileReader and FilerWriter


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.*;

public class StudentDAO {
public static String fileName = "//data//temp//SurveyData.txt";

public static void SaveStudentSurveyFormData(StudentBean postData) throws IOException{
Surveys surveys = GetSurveys();
surveys.data.add(postData);
SaveFile(new Gson().toJson(surveys));
}

public static StudentBean GetStudentSurveyData(String studentId) throws IOException{
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}

public static Surveys GetSurveys() throws IOException{
Surveys surveys = null;
String fileText = ReadFile();
if(fileText.length() > 0){
surveys = new Gson().fromJson(fileText, Surveys.class);
}
else{
surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
}
return surveys;
}

public static List<String> GetSurveyIds() throws IOException{
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}

public static String ReadFile() throws IOException{
BufferedReader file = new BufferedReader(new FileReader(fileName));
String line;
StringBuffer fileText = new StringBuffer();
while((line=file.readLine()) != null){
fileText.append(line);
}
file.close();
return fileText.toString();
}

public static void SaveFile(String fileText) throws IOException{
FileWriter fWriter = new FileWriter(fileName,false);
BufferedWriter writer = new BufferedWriter(fWriter);
fWriter.append(fileText);
writer.flush();
writer.close();
}
}


import java.util.ArrayList;

public class Surveys {
public ArrayList<StudentBean> data;
}


public class StudentBean {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String likes;
private String interests;
private String recommendation;
private String comments;

public StudentBean(String studentId, String firstName, String lastName, String street, String zip,
String city, String state, String telephone, String email, String url, String dateOfSurvey,
String graduationMonth, String graduationYear, String likes, String interests,
String recommendation, String comments){
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.zip = zip;
this.city = city;
this.state = state;
this.telephone = telephone;
this.email = email;
this.url = url;
this.dateOfSurvey = dateOfSurvey;
this.graduationMonth = graduationMonth;
this.graduationYear = graduationYear;
this.likes = likes;
this.interests = interests;
this.recommendation = recommendation;
this.comments = comments;
}

public String getStudentId(){
return this.studentId;
}

public String getFirstName(){
return this.firstName;
}

public String getLastName(){
return this.lastName;
}

public String getStreet(){
return this.street;
}

public String getZip(){
return this.zip;
}

public String getCity(){
return this.city;
}

public String getState(){
return this.state;
}

public String getTelephone(){
return this.telephone;
}

public String getEmail(){
return this.email;
}

public String getUrl(){
return this.url;
}

public String getDateOfSurvey(){
return this.dateOfSurvey;
}

public String getGraduationMonth(){
return this.graduationMonth;
}

public String getGraduationYear(){
return this.graduationYear;
}

public String getLikes(){
return this.likes;
}

public String getInterests(){
return this.interests;
}

public String getRecommendation(){
return this.recommendation;
}

public String getComments(){
return this.comments;
}
}


Java Servlet with RequestDispatcher


import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/Display")
public class Display extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentid");
String address = "jsp/StudentJSP.jsp";
StudentBean studentBean = null;

if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}

HttpSession session = request.getSession();

if(studentBean == null){
address = "jsp/NoSuchStudentJSP.jsp";
session.setAttribute("badId", studentId);
}
else{
session.setAttribute("student", studentBean);
}

RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentId");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String state = request.getParameter("state");
String telephone = request.getParameter("telephone");
String email = request.getParameter("email");
String url = request.getParameter("url");
String dateOfSurvey = request.getParameter("dateOfSurvey");
String graduationMonth = request.getParameter("graduationMonth");
String graduationYear = request.getParameter("graduationYear");
String[] likes = request.getParameterValues("likes");
String interests = request.getParameter("interests");
String recommendation  = request.getParameter("recommendation");
String comments = request.getParameter("comments");
String data = request.getParameter("data");

String likesString = "";
for(int i=0; i< likes.length; i++){
likesString += likes[i] + ", ";
}
likesString = likesString.substring(0, likesString.length() - 2);

StudentBean studentBean = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likesString, interests, recommendation, comments);

StudentDAO.SaveStudentSurveyFormData(studentBean);

DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(data);

List<String> surveyIdsBean = StudentDAO.GetSurveyIds();

HttpSession session = request.getSession();

session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);

String address = "jsp/SimpleAcknowledgementJSP.jsp";
if(dataBean.getMean() > 90){
address = "jsp/WinnerAcknowledgementJSP.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}

Wednesday, November 21, 2012

Java RMI

1) Compute.java

package compute;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Compute extends Remote {
   <T> T executeTask(Task<T> t) throws RemoteException;
}

2) Task.java

package compute;

public interface Task<T> {
   T execute();
}

cd c:\home\waldo\src
javac compute\Compute.java compute\Task.java
jar cvf compute.jar compute\*.class

3) ComputeEngine.java

package engine;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import compute.Compute;
import compute.Task;

public class ComputeEngine implements Compute{
   public ComputeEngine(){
      super();
   }
  
   public<T> T executeTask(Task<T> t){
      return t.execute();
   }

   public static void main(String[] args){
      if(System.getSecurityManager() == null){
         System.setSecurityManager(new SecurityManager());
      }
      try{
         String name = "Compute";
         Compute engine = new ComputeEngine();
         Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
         Registry registry = LocateRegistry.getRegistry();
         registry.rebind(name, stub);
      } catch(Exception e){
         System.err.println("ComputeEngine exception: ");
         e.printStackTrace();
      }
   }
}

cd c:\home\ann\src
javac -cp c:\home\ann\public_html\classes\compute.jar
    engine\ComputeEngine.java

Pi.java

package client;
import compute.Task;
import java.io.Serializable;
import java.math.BigDecimal;

public class Pi implements Task<BigDecimal>, Serializable{
   private final int digits;
   public Pi(int digits){
      this.digits = digits;
   }
   public BigDecimal execute(){
      return computePi(digits);
   }
   public static BigDecimal computePi(int digits){
      return result;
   }
}

ComputPi.java

package client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.math.BigDecimal;
import compute.Compute;

public class ComputePi{
   public static void main(String args[]){
      if(System.getSecurityManager() == null){
         System.setSecurityManager(new SecurityManager());
      }
      try{
         String name = "Compute";
         Registry registry = LocateRegistry.getRegistry(args[0]);
         Compute comp = (Compute) registry.lookup(name);
         Pi task = new Pi(Integer.parseInt(args[1]);
         BigDecimal pi = comp.executeTask(task);
         System.out.println(pi);
      } catch(Exception e){
         System.err.println("ComputerPi exception:");
         e.printStackTrace();
      }
   }
}

cd c:\home\jones\src
javac -cp c:\home\jones\public_html\classes\compute.jar
   client\ComputePi.java client\Pi.java
mkdir c:\home\jones\public_html\classes\client
cp client\Pi.class
   c:\home\jones\public_html\classes\client

server.policy

grant codeBase "file:/home/ann/src/" {
   permission java.security.AllPermission;
};

client.policy

grant codeBase "file:/home/jones/src/" {
   permission java.security.AllPermission;
};

start rmiregistry (or javaw if start is not available)

java -cp c:\home\ann\src;c:\home\ann\public_html\classes\compute.jar
       -Djava.rmi.server.codebase=file:/c:/home/ann/public_html/classes/compute.jar
       -Djava.rmi.server.hostname=mycomputer.example.com
       -Djava.security.policy=server.policy
          engine.ComputeEngine

java -cp c:\home\jones\src;c:\home\jones\public_html\classes\compute.jar
       -Djava.rmi.server.codebase=file:/c:/home/jones/public_html/classes/
       -Djava.security.policy=client.policy
          client.ComputePi mycomputer.example.com 45

Thursday, November 8, 2012

Objective-C Header and Class Implementation

Person.h

#import <Foundation/Foundation.h>
@interface Person:NSObject{
   NSString *name;
   int age;
}
- (NSString *)name;
- (void) setName: (NSString *) newName;

- (int)age;
- (void) setAge: (int) newAge;

//actions
- (BOOL) isAllowedToVote;
- (void castBallot;
@end

Person.m

#import "Person.h"

@implementation Person
- (int) age{
   return age;
}

- (void) setAge: (int) value{
   age = value;
}

//... and other methods

@end

Using a class
id anObject = [[SomeClass alloc] init];

- (id) init
{
   self = [super init];
   if(self){
     //initializations
   }
   return self;
}

- (Person *) createPersonWithName: (NSString *) aName{
   Person *aPerson = [[Person alloc] init];
   [aPerson setName:aName];
   [aPerson setAge:21];

   return aPerson;
}

Class Inheritance

@interface Student : Person {
   NSString *major;
}
@end

@implementation Student
// Constructor for a student
- (id) init
{
   self = [super init];
   if(self != nil){
      //set attributes
      [self setMajor:@"Undefined"];
   }
   return self;
}
@end

Objective-C Selector

id object;
SEL anAction = @selector(action:);
if([object respondsToSelector:anAction]){
   [object performSelector:anAction withObject:self];
}

Objective-C Object Messaging

[receiver message]
[receiver message:argument]
[receiver message:arg1 argument2:arg2]
int status = [receiver message];
[receiver makeGroup:group, memberOne, memberTwo, memberThree];

[rectangle draw]
[rectangle setColor:blue]
[rectangle setStrokeColor:blue andThickness:2.0]
double length = [rectangle circumference];
[NSArray arrayWithObjects:one, two, three, nil];

Java vs. Objective-C

Java
Rectangle rect = Rectangle(someWidth, someHeight);
println(rect.getHeight());
boolean inside = rect.contains(x,y);

Objective-C
Rectangle *rect = [[Rectangle alloc] initWithWidth:someWidth andHeight:someHeight];
NSLog(@"%f", [rect height]);
BOOL inside = [rect containsPointWithX:x andY:y]

Objective-C Identiy vs. Equality

// test for object identity:
BOOL identical = @"Peter" == @"Peter";     //YES
            identical = @"Peter" == @" Peter ";    //NO

// test for string equality: will return YES
NSString *aName = @"Peter";
NSMutableString *anotherName = [NSMutableString stringWithString:@"P"];

[anotherName appendString:@"eter"];

BOOL same = [aName isEqualToString:anotherName];     //YES
BOOL equal = (aName == anotherName);         //NO

// test for existence
BOOL exists = (object != nil);

Saturday, October 20, 2012

Javascript Namespace with Require.js

index.html
<script src="scripts/require.js" data-main="scripts/lib/main.js"></script>

main.js
require(["Order"], function(Order){
   var o = new Order(1, "A Customer");
   alert(o.id);
   alert(o.customer.name);
});

Order.js
define('"Customer"],         // Required scripts (Customer)
   function(Customer){          // Get Required objects
      function Order(id, custName){
         this.id = id;
         this.customer = new Customer(custName);
      }
      return Order;
   }
);

Customer.js
define([],
   function(){
      function Customer(name){
         this.name = name;
      }
      return Customer;
   }
);

Javascript Namespace

main.js
$(function(){
   var o = new ProjectNS.Order(1, "A Customer");
   alert(o.id);
   alert(o.customer.name);
});

order.js
(function(ns){
   ns.Order = function(id, custName){
      this.id = id,
      this.customer = new ns.Customer(custName)
   };
}(window.ProjectNS = window.ProjectNS || {}));

Customer.js
(function(ns){
   ns.Customer = function(name){
      this.name = name
   };
}(window.ProjectNS = window.ProjectNS || {}));

Wednesday, September 26, 2012

Modular Javascript with RequireJS

<script data-main="/scripts/main" src="/scripts/require.js" type="text/javascript"></script>

main.js
(function(){
     requirejs.config(
            baseUrl: 'scripts',
            paths:{
                      'jquery': 'jquery-1.7.2'
            }
     );
     require(['alerter'],
            function(alerter){
                 alerter.showMessage();
            });
})();

alerter.js
define('alerter',
     ['jquery', 'dataservice'],
     function($, dataservice){
          var name = 'John',
               showMessage = function(){
                    var msg = dataservice.getMessage();
                    $('#messagebox').text(msg + ', ' + name);
                };
           return{
                 showMessage: showMessage
           };
      });

dataservice.js
define('dataservice',
      [],
      function(){
          var
               msg = 'Welcome to Code Camp',
               getMessage = function(){
                    return msg;
               };
          return{
               getMessage: getMessage
          };
      });

Modular Javascript Without RequireJS

dataservice.js
var dataservice = (function(){
var
msg = 'Welcome to Code Camp',
getMessage  = function(){
return msg;
};
return{
getMessage: getMessage
};
})();

alerter.js
var alerter = (function (dataservice){
var
name = 'John',
showMessage = function(){
var msg = dataservice.getMessage();
alert(msg + ', ' + name);
};
return{
showMessage: showMessage
};
})(dataservice);

main.js
(function (alerter){
alerter.showMessage();
})(alerter);

Wednesday, September 19, 2012

Issue: Nuget.Config is corrupted

Issue:  C:\Users\Administrator\AppData\Roaming\NuGet\Nuget.Config is corrupted.
Solution: Edit the Nuget.Config with the following text.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="NuGet official package source" value="https://go.microsoft.com/fwlink/?LinkID=230477" />
</packageSources>
<activePackageSource>
<add key="NuGet official package source" value="https://go.microsoft.com/fwlink/?LinkID=230477" />
</activePackageSource>
</configuration>

Friday, September 7, 2012

Issue: No implicit conversion between int and null

Issue: No implicit conversion between int and null
Solution:
int value = 999999;
int? result;
result = (value > 0) ? (int?)value : null;

Thursday, September 6, 2012

LINQ .ToArray().Aggregate() Function

Method 1 (OLD):
var stringVar = new StringBuilder();
foreach (var item in itemsCollection)
{
    stringVar.Append(item.PROPERTY + ", ");
}
if (codes.Length > 0)
{
    stringVar.Remove(item.PROPERTY - 2, 2);
}
else
{
    stringVar.Append("None");
}
return stringVar.ToString();

Method 2 (PREFERRED):
return itemsCollection.Any() ? itemsCollection.ToArray().Aggregate((first, second) => first + ", " + second) : "None";

Issue: Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.

Issue:
Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.

Solution:
Use .AsEnumerable() before .Select()

For example:
Table.Where(x=>...)
.AsEnumerable()
.Select(x=>...);

Wednesday, September 5, 2012

T-SQL Drop and Re-create Unique Constraint

ALTER TABLE [dbo].[TABLE_NAME]
DROP CONSTRAINT [UNIQUE_KEY_NAME]
GO

ALTER TABLE [dbo].[TABLE_NAME]
ADD CONSTRAINT [UNIQUE_KEY_NAME] UNIQUE NONCLUSTERED
(
    [COLUMN_ID_1] ASC,
    [COLUMN_ID_2] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

Saturday, September 1, 2012

Move SQL Server 2008 Databases


use master
go

sp_detach_db 'mydb'
go

sp_attach_db 'ShowsTix',
'C:\Data\mydb_log.ldf',
'C:\Data\mydb.mdf'
go

use mydb
go
sp_helpfile
go

Friday, August 31, 2012

dhtmlx TreeGrid

mygrid.setCellExcellType(100000, 2, "ro");
mygrid.setItemImage(100000, "blank.gif");

rowId = 100000
column index = 2
ro = read-only

Friday, August 24, 2012

TeamCity Edit Checkout Rules


+:.
-:/db
-:/docs

CI Build File and Web Application Deployment

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
         ToolsVersion="4.0"
         DefaultTargets="Compile">
  <UsingTask AssemblyFile="C:\svn\project\src\packages\ThirdParty\MSBuildCommunityTasks\AsyncExec.dll" TaskName="AsyncExec.AsyncExec"/>
  <UsingTask AssemblyFile="C:\svn\project\src\packages\ThirdParty\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll" TaskName="MSBuild.Community.Tasks.XmlRead" />
  <ItemGroup>
    <SolutionRoot Include="."/>
    <BuildArtifacts Include=".\buildartifacts\"/>
    <SolutionFile Include="..\src\Project.sln"/>
    <MsDeploy Include="..\src\packages\MSdeploy2\msdeploy.exe"/>
    <PackageFile Include=".\buildartifacts\package\Project.zip"/>
    <Website Include=".\buildartifacts\_PublishedWebsites\Project.Website"/>
  </ItemGroup>
  <Target Name="Clean">
    <RemoveDir Directories="@(BuildArtifacts)"/>
  </Target>
  <Target Name="Init" DependsOnTargets="Clean">
    <MakeDir Directories="@(BuildArtifacts)"/>
  </Target>
  <Target Name="Compile" DependsOnTargets="Init">
    <PropertyGroup>
       <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    </PropertyGroup>
    <MSBuild Projects="@(SolutionFile)" Properties="OutDir=%(BuildArtifacts.FullPath);
    Configuration=$(Configuration)"/>
  </Target>
  <Target Name="Package" DependsOnTargets="Compile">
    <PropertyGroup>
      <PackageDir>%(PackageFile.RootDir)%(PackageFile.Directory)</PackageDir>
      <Source>%(Website.FullPath)</Source>
      <Destination>%(PackageFile.FullPath)</Destination>
    </PropertyGroup>
    <MakeDir Directories="$(PackageDir)"/>
    <Exec Command='"@(MsDeploy)" -verb:sync -source:iisApp="$(Source)" -dest:package="$(Destination)"'/>
  </Target>
  <Target Name="DeployToDev" DependsOnTargets="Package">
    <PropertyGroup>
      <WebServerName>DEVSERVER</WebServerName>
      <Source>%(PackageFile.FullPath)</Source>
    </PropertyGroup>
    <Exec Command='"@(MsDeploy)" -verb:sync -source:package="$(Source)" -dest:iisApp="Default Web Site", computerName=$(WebServerName),username=,password='/>
  </Target>
</Project>

SQL Server Service Logon


Thursday, August 9, 2012

Refresh SVN Status Often

It will bring the 'Update Solution to Latest Version' option back.




Tuesday, July 10, 2012

ASP.NET MVC Remote Validation

public class TimeCard : IValidatableObject
{
...
[Remote("CheckUserName", "Home", ErrorMessage="Username is invalid")]
public string UserName{get; set;}
...
}

public class HomeController : Controller
{
...
public JsonResult CheckUsername(string username)
{
var result = false;
if(username == "tkhuc")
{
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}

ASP.NET MVC Custom Client Validation

Implement IClientValidatable
Implement a jQuery validation method
Implement an unobtrusive adapter

public class GreaterThanDateAttribute : ValidationAttribute, IClientValidatable
{
...
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
var rule  = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "greater";
rule.ValidationParameters.Add("other", otherPropertyName);
yield return rule;
}

customvalidation.js
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

jQuery.validator.addMethod("greater", function(value, element, param)
{
return Date.parse(value) > Date.parse($(param).val());
});

jQuery.validator.unobtrusive.adapters.add("greater", ["other"], function(options){
options.rules["greater"] = "#" + options.params.other;
options.messages["greater"] = options.message;                    // ~ rule.ErrorMessage
});

Generated html output
<input class="text-box-single-line" id="EndDate" name="EndDate" type="text" value="1/1/2010 12:00:00 AM"
data-val="true"
data-val-greater="EndDate must be greater than StartDate"
data-val-greater-other="StartDate"
/>

ASP.NET MVC Client Validation

<script src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Global Settings
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavascriptEnabled" value="true"/>
</appSettings>


Page-level Settings
@Html.EnableClientValidation(false/true)
@Html.EnableUnobtrusiveJavascript(false/true)


Unobtrusive Javascript Validation
<input id="ConfirmHours" name="ConfirmHours" type="text value="0" class="text-box-single-line"
data-val="true"
data-val-equalto="ConfirmHours and Hours do not match."
data-val-equalto-other="*.Hours"
data-val-number="The field ConfirmHours must be a number."
data-val-range="The field ConfirmHours must be between 1 and 120."
data-val-range-max="120"
data-val-range-min="1"
data-val-required="The ConfirmHours field is required."
/>
<span class="field-validation-valid" data-valmsg-for="ConfirmHours" data-valmsg-replace="true"/>

Data Validation using Data Annotations

Data Annotations

[Required()]
[StringLength(25)]

[Range(1,120)]
public int Hours{get; set;}

[Compare("Hours")]
public int ConfirmHours{get; set;}

<div class="editor-label">
@Html.LabelFor(model=>model.ConfirmHours, "Please confirm the hours worked")
</div>
<div class="editor-field">
@Html.EditorFor(model=>model.ConfirmHours)
@Html.ValidationMessageFor(model=>model)
</div>

Custom Validation Attributes

public class GreaterThanDateAttribute : ValidationAttribute
:base("{0} must be greater than {1}")
{
public string OtherPropertyName{get; set;}

public GreaterThanDateAttribute(string otherPropertyName)
{
OtherPropertyName = otherPropertyName;
}
public override string FormatErrorMessage(string name)
{
return String.Format(ErrorMessageString, name, otherPropertyName);
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(otherPropertyName);
var otherDate = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisDate = (DateTime)value;
if(thisDate <= otherDate)               //failed
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}

return null;                                      //succeeded
}
}

public DateTime StartDate{get; set;}

[GreaterThanDate("StartDate")]
public DateTime EndDate{get; set;}


Sunday, July 8, 2012

MVC 3 Child Output Caching

Controllers\HomeController.cs
public class HomeController : Controller
{
[OutputCache(Duration = 60)]
public ActionResult Index()
{
var model = DateTime.Now;
return View(model);
}

[ChildActionOnly]
[OutputCache(Duration = 10)]
public PartialViewResult CurrentTime(){
var model = DateTime.Now;
return PartialView(model);
}
}

Views\Home\CurrentTime.cshtml
@model DateTime
<p>This is the child action result, current time is: @Model.ToLongTimeString()</p>

Views\Home\Index.cshtml
@model DateTime
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>This is the index view for Home, rendering at time: @Model.ToLongTimeString()</div>
<div>@Html.Action("CurrentTime")</div>

MVC Request Validation

Be careful when sending HTML to server.

[ValidateInput(false)] - turn off all verification

[AllowHtml] - granular verification for view model

MVC 3 Action Results

HttpNotFoundResult
public ActionResult Results()
{
return HttpNotFound();
}

HttpRedirectResult
public ActionResult Results()
{
return RedirectPermanent("http://google.com");
}

HttpStatusCodeResult
public AtionResult Results()
{
return HttpStatusCodeResult(415, "Media type not recognized");
}

Global Filters

Controllers\HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
throw new InvalidOperationException();
return View();
}

Views\Shared\Error.cshtml
<h2>Sorry, an error occurred while processing your request.</h2>

Global.asax.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}

protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
}

Web.config
<system.web>
<customErrors mode="On"/>
....

Action filters: [Authorize], [HandleError]

Custom Action Filters
public class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext){}
public override void OnActionExecuted(ActionExecutedContext filterContext){}
public override void OnResultExecuting(ResultExecutingContext filterContext){}
public override void OnResultExecuted(ResultExecutedContext filterContext){}
}

Sunday, June 3, 2012

Testing the Sad Path

When_passing_null_measurements.cs

using NUnit.Framework;

namespace Domain.Tests.AveragingCalculator_Tests.SadPath
{
[Category("AveragingCalculator")]
public class When_passing_null_measurements
{

private AveragingCalculator _averageCalculator;

[SetUp]
public void Setup()
{
_averageCalculator = new AveragingCalculator();
}

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void When_measurement_is_null()
{
var measurements = Mother.Get4Measurements();
measurements.Add(null);

_averageCalculator.Aggregate(measurements);
}
}

AveragingCalculator.cs

namespace Domain
{
public class AveragingCalculator : IAggregateCalculator
{
if(measurements.Contains(null))
{
throw new ArgumentNullException();
}

return new Measurement()
{
HighValue=measurements.Average(m=>m.HighValue),
LowValue=measurements.Average(m=>m.LowValue)
};

}

Test Project Structure

Solution

  • Domain
    • AggregationType.cs
    • AveragingCalculator.cs
    • IAggregateCalculator.cs
    • IGrouper.cs
    • Measurement.cs
    • MeasurementAggregator.cs
    • ModalCalculator.cs
    • SizeGrouper.cs
  • Domain.Tests
    • References
      • Domain
    • AveragingCalculator_Tests
      • SadPath
        • When_passing_null_measurements.cs
          • When_measurements_are_null()
          • When_measurent_is_null()
      • When_averaging_4_numbers.cs
      • When_averaging_several_numbers.cs
    • MeasurementAggregator_Tests
      • When_aggregating_four_measurements.cs
    • Mother.cs

Thursday, May 24, 2012

LINQPad

string[] names = {"Michael", "Long"};

IEnumerable<string> query = names
.Where(n=>n.Contains("o"))
.OrderBy(n=>n.Length)
.Select(n=>n.ToUpper());

query.Dump();

// same query as above
IEnumerable<string>filtered = names.Where(n=>n.Contains("o"));
IEnumerable<string>sorted = filtered.OrderBy(n=>n.Length);
IEnumerable<string>finalQuery = sorted.Select(n=>n.ToUpper());

filtered.Dump("Filtered");
sorted.Dump("Sorted");
finalQuery.Dump("FinalQuery");

LINQ Dynamic Query

using System.Linq.Dynamic

var repository = new EmployeeRepository();

var query = repository.GetAll()
.AsQueryable()
.OrderBy("Name")
.Where("DepartmentID = 1");

LINQ Joins


var employeeRepository = new EmployeeRepository();
var departmentRepository = new DepartmentRepository();

Inner Join (Normal)

var employees =
from employee in employeeRepository.GetAll()
join department in departmentRepository.GetAll()
on employee.DepartmentID equals department.ID
select new {employee.Name, Department = department.Name};

Left Join (Grouping on Departments)

var query =
from d in departmentRepository.GetAll()
join e in employeesRepository.GetAll()
on d.ID equals e.DepartmentID
into ed
select new
{
Department = d.Name,
Employees = ed};

foreach(var group in query)
{
Console.WriteLine(group.Department);
foreach(var employee in group.Employees)
{
Console.WriteLine("\t" + employee.Name);
}
}

Cross Join (for completeness)


var employees =
from employee in employeeRepository.GetAll()
join department in departmentRepository.GetAll()
on employee.DepartmentID equals department.ID
select new {employee.Name, Department = department.Name};

LINQ Grouping and Projecting

var repository = new EmployeeRepository();

Comprehensive Query Syntax

var queryByDepartment =
from e in repository.GetAll()
group e by e.DepartmentID
into eGroup
orderby eGroup.Key descending
where eGroup.Key < 3
select new
{
DepartmentID = eGroup.Key,
Count = eGroup.Count(),
Employees = eGroup
};

Extension Methods with Lambda Expressions

var queryByDepartment2 =
repository.GetAll()
.GroupBy(e=>e.DepartmentID)
.OrderByDescending(g=>g.Key)
.Where(g=>g.Key < 3)
.Select(g=>
new
{
DepartmentID = g.Key,
Count = g.Count(),
Employees = g
});

foreach(var group in queryByDepartment2)
{
Console.WriteLine("DID: {0}, Count: {1}",
group.DepartmentID,
group.Count);

foreach(var employee in group.Employees)
{
Console.WriteLine("\t{0}:{1}", employee.DepartmentID, employee.Name);
}
}