Search This Blog

Wednesday, March 23, 2011

Main.cs

#region Full Table Requests

private void employeesToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table emp = Accessor.GetEmployeeTable();
dataGridView1.DataSource = emp;
}

private void shippersToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table ship = Accessor.GetShipperTable();
dataGridView1.DataSource = ship;
}

private void ordersToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table orders = Accessor.GetOrderTable();
dataGridView1.DataSource = orders;
}

private void employeeTerritoryToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table empTerrs = Accessor.GetEmployeeTerritoryTable();
dataGridView1.DataSource = empTerrs;
}

private void territoryToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table terrs = Accessor.GetTerritoryTable();
dataGridView1.DataSource = terrs;
}

private void regionToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table regs = Accessor.GetRegionTable();
dataGridView1.DataSource = regs;
}

private void customerToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table cust = Accessor.GetCustomerTable();
dataGridView1.DataSource = cust;
}

private void customerDemoToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table custdemo = Accessor.GetCustomerDemoTable();
dataGridView1.DataSource = custdemo;
}

private void customerDemographicToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table custdemograph = Accessor.GetCustomerDemographicTable();
dataGridView1.DataSource = custdemograph;
}


private void orderDetailsToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table ordDetails = Accessor.GetOrderDetailsTable();
dataGridView1.DataSource = ordDetails;
}

private void productToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table prods = Accessor.GetProductTable();
dataGridView1.DataSource = prods;
}

private void supplierProductToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table prods = Accessor.GetSupplierTable();
dataGridView1.DataSource = prods;
}

private void categoToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Data.Linq.Table cats = Accessor.GetCategoryTable();
dataGridView1.DataSource = cats;
}

#endregion



#region Queries


///
/// Find and display an employee by
/// the employee's ID
///

///
///
private void employeeByIDToolStripMenuItem_Click(object sender, EventArgs e)
{

Employee emp = Accessor.GetEmployeeById(1);

StringBuilder sb = new StringBuilder();
sb.Append("Employee 1: " + Environment.NewLine);
sb.Append("Name: " + emp.FirstName + " " + emp.LastName + Environment.NewLine);
sb.Append("Hire Date: " + emp.HireDate + Environment.NewLine);
sb.Append("Home Phone: " + emp.HomePhone + Environment.NewLine);

MessageBox.Show(sb.ToString(), "Employee ID Search");
}


///
/// Gets an Order by the order ID and
/// displays information about the first
/// single matching order.
///

///
///
private void orderByIDToolStripMenuItem_Click(object sender, EventArgs e)
{
Order ord = Accessor.GetOrderById(10248);

StringBuilder sb = new StringBuilder();
sb.Append("Order: " + Environment.NewLine);
sb.Append("Order ID: " + ord.OrderID + Environment.NewLine);
sb.Append("Date Shipped: " + ord.ShippedDate + Environment.NewLine);
sb.Append("Shipping Address: " + ord.ShipAddress + Environment.NewLine);
sb.Append(" City: " + ord.ShipCity + Environment.NewLine);
sb.Append(" Region: " + ord.ShipRegion + Environment.NewLine);
sb.Append(" Country: " + ord.ShipCountry + Environment.NewLine);
sb.Append(" Postal Code: " + ord.ShipPostalCode + Environment.NewLine);
sb.Append("Shipping Name: " + ord.ShipName + Environment.NewLine);

MessageBox.Show(sb.ToString(), "Shipping Information");
}



///
/// Displays a list of employeess ordered by
/// their dates of hire
///

///
///
private void employeesByHireDateToolStripMenuItem_Click(object sender, EventArgs e)
{
List emps = Accessor.GetEmployeesByHireDate();
dataGridView1.DataSource = emps;
}


///
/// Displays all orders that match
/// on Order ID
///

///
///
private void ordersByIdToolStripMenuItem_Click(object sender, EventArgs e)
{
List orders = Accessor.GetOrdersById(10248);
dataGridView1.DataSource = orders;
}

///
/// Returns values based on joining the Order and
/// Order_Details tables
///

///
///
private void ordersAndDetailsToolStripMenuItem_Click(object sender, EventArgs e)
{
List oad = Accessor.OrdersAndDetails();
dataGridView1.DataSource = oad;
}


///
/// Query across entity set
/// This example collections information from the orders table
/// and the order_details table through the orders table
/// entity reference to orders_details.
///

///
///
private void ordersAndDetailsEntityRefToolStripMenuItem_Click(object sender, EventArgs e)
{
List opr = Accessor.GetOrderAndPricingInformation();
dataGridView1.DataSource = opr;
}



///
/// Retrieves values across an entity set to
/// display both order and pricing information
/// by filtering for an order ID
///

///
///
private void ordersAndDetailsByOrderIDEntityRefToolStripMenuItem_Click(object sender, EventArgs e)
{
List opr = Accessor.GetOrderAndPricingInformationByOrderId(10248);
dataGridView1.DataSource = opr;
}



///
/// Displays to total dollar value of the selected order
/// by multiplying each order product's unit cost by
/// the units ordered, and then summing the total of each
/// individual cost.
///

///
///
private void orderValueByOrderIDToolStripMenuItem_Click(object sender, EventArgs e)
{
// get the dollar value
decimal? d = Accessor.GetOrderValueByOrderId(10248);

// convert the decimal value to currency
string dollarValue = string.Format("{0:c}", d);

// display the dollar value
MessageBox.Show("The total dollar value of order 10248 is " +
dollarValue, "Order 10248 Value");
}



///
/// Displays the top five orders in the order table
/// on first selection and then increments up by
/// five orders to show the list five orders
/// at a time
///

///
///
private void getTopFiveOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
// get the top five orders starting at the current position
List ords = Accessor.GetTopFiveOrdersById(OrderPosition);
dataGridView1.DataSource = ords;

// increment the formwide variable used to
// keep track of the position within the
// list of orders
OrderPosition += 5;

// change the text in the menu strip item
// to show that it will retrieve the next
// five values after the current position
// of th last value shown in the grid
getTopFiveOrdersToolStripMenuItem.Text = "Get Next Five Orders";
}
catch
{
MessageBox.Show("Cannot increment an higher, starting list over.");
OrderPosition = 0;
}
}

#endregion



#region Insert Update Delete


private void insertOrUpdateCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Accessor.InsertOrUpdateCustomer("AAAAA", "BXSW", "Mookie Carbunkle", "Chieftain",
"122 North Main Street", "Wamucka", "DC", "78888", "USA", "244-233-8977",
"244-438-2933");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}

private void deleteCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Accessor.DeleteCustomer("AAAAA");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}


#endregion



#region Stored Procedures

///
/// Execute stored procedure: Sales By Year
///

///
///
private void salesByYearToolStripMenuItem_Click(object sender, EventArgs e)
{
DateTime start = new DateTime(1990, 1, 1);
DateTime end = new DateTime(2000, 1, 1);

List result = Accessor.SalesByYear(start, end);
dataGridView1.DataSource = result;
}



///
/// Execute stored procedure: Ten Most Expensive Products
///

///
///
private void tenMostExpensiveProductsToolStripMenuItem_Click(object sender, EventArgs e)
{
List result = Accessor.TenMostExpensiveProducts();
dataGridView1.DataSource = result;
}


#endregion


#region Housekeeping

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

#endregion

Accessor.cs

///
/// This class defines functions used to
/// select, insert, update, and delete data
/// using LINQ to SQL and the defined
/// data context
///

public class Accessor
{


#region Full Table

// This section contains examples of
// pulling back entire tables from
// the database

///
/// Displays the full Employee table
///

///
public static System.Data.Linq.Table GetEmployeeTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Shipper table
///

///
public static System.Data.Linq.Table GetShipperTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Order table
///

///
public static System.Data.Linq.Table GetOrderTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full EmployeeTerritory table
///

///
public static System.Data.Linq.Table GetEmployeeTerritoryTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays Territory Table
///

///
public static System.Data.Linq.Table GetTerritoryTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Region table
///

///
public static System.Data.Linq.Table GetRegionTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Customer table
///

///
public static System.Data.Linq.Table GetCustomerTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full CustomerCustomerDemo table
///

///
public static System.Data.Linq.Table GetCustomerDemoTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full CustomerDemographic table
///

///
public static System.Data.Linq.Table GetCustomerDemographicTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Order_Detail table
///

///
public static System.Data.Linq.Table GetOrderDetailsTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Product table
///

///
public static System.Data.Linq.Table GetProductTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Supplier table
///

///
public static System.Data.Linq.Table GetSupplierTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


///
/// Displays the full Category table
///

///
public static System.Data.Linq.Table GetCategoryTable()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.GetTable();
}


#endregion



#region Queries

// This region contains examples of some
// of the sorts of queries that can be
// executed using LINQ to SQL

///
/// Example: Where Clause
/// Returns an employee where the
/// employee ID matches the value
/// passed in as empID
///

///
/// The single matching or default value
public static Employee GetEmployeeById(int empId)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from e in dc.GetTable()
where (e.EmployeeID == empId)
select e).SingleOrDefault();
}



///
/// Example: Select to a single returned object
/// using a Where Clause
///
/// Returns the first matching order
///

///
/// The single matching or default value
public static Order GetOrderById(int orderId)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from ord in dc.GetTable()
where (ord.OrderID == orderId)
select ord).SingleOrDefault();
}



///
/// Example: Select to a typed List
/// using a Where Clause
///

///
///
public static List GetOrdersById(int orderId)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from ord in dc.GetTable()
where (ord.OrderID == orderId)
select ord).ToList();
}



///
/// Example: Return an ordered list
///
/// Converts the returned value to a List
/// of type Employee; the list is ordered
/// by hire date
///

///
public static List GetEmployeesByHireDate()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return (from emp in dc.GetTable()
orderby emp.HireDate ascending
select emp).ToList();
}




///
/// This class is used to define the return type
/// for the next function - OrdersAndDetails
///
/// When results are extracted from multiple tables
/// you can either return the results as anonymous
/// or as a type; this class defines the return
/// type used by OrdersAndDetails
///

public class OrdersAndDetailsResult
{
public System.String CustomerID
{ get; set; }
public System.Nullable OrderDate
{ get; set; }
public System.Nullable RequiredDate
{ get; set; }
public System.String ShipAddress
{ get; set; }
public System.String ShipCity
{ get; set; }
public System.String ShipCountry
{ get; set; }
public System.String ShipZip
{ get; set; }
public System.String ShippedTo
{ get; set; }
public System.Int32 OrderID
{ get; set; }
public System.String NameOfProduct
{ get; set; }
public System.String QtyPerUnit
{ get; set; }
public System.Nullable Price
{ get; set; }
public System.Int16 QtyOrdered
{ get; set; }
public System.Single Discount
{ get; set; }
}



///
/// Example: Joins
/// Joining using the join keyword
///
/// The values are set to each of the
/// properties contained in the
/// OrdersAndDetailsResult class
///
/// The value returned is converted
/// to a list of the specified type
///

///
public static List OrdersAndDetails()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from ords in dc.GetTable()
join dets in dc.GetTable()
on ords.OrderID equals dets.OrderID
orderby ords.CustomerID ascending
select new OrdersAndDetailsResult
{
CustomerID = ords.CustomerID,
OrderDate = ords.OrderDate,
RequiredDate = ords.RequiredDate,
ShipAddress = ords.ShipAddress,
ShipCity = ords.ShipCity,
ShipCountry = ords.ShipCountry,
ShipZip = ords.ShipPostalCode,
ShippedTo = ords.ShipName,
OrderID = ords.OrderID,
NameOfProduct = dets.Product.ProductName,
QtyPerUnit = dets.Product.QuantityPerUnit,
Price = dets.Product.UnitPrice,
QtyOrdered = dets.Quantity,
Discount = dets.Discount
}
).ToList ();
}


///
/// Defined to support following function:
/// GetOrderAndPricingInformation - this class
/// supplies the return type for that function
///

public class OrderandPricingResult
{
public System.Int32 OrderID
{ get; set; }
public System.String Company
{ get; set; }
public System.String OrderCountry
{ get; set; }
public System.String ProductName
{ get; set; }
public System.Nullable UnitPrice
{ get; set; }
public System.Int16 UnitsOrder
{ get; set; }
public System.String ShipperName
{ get; set; }
public System.String SalesFirstName
{ get; set; }
public System.String SalesLastName
{ get; set; }
public System.String SalesTitle
{ get; set; }
}


///
/// Example: Query across an entity ref
/// This example collections information from the orders table
/// and the order_details table through the orders table
/// entity association to the orders_details table.
///
/// An entity is a representation in the model of a table
/// in the database, foreign key relationships are maintained
/// as entity references to the related tables in the model.
/// It is possible to query across tables through this
/// relationship in LINQ to SQL
///

///
public static List GetOrderAndPricingInformation()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from ords in dc.Orders // orders table
from dets in ords.Order_Details // entity set in orders table
select new OrderandPricingResult
{
OrderID = ords.OrderID,
Company =ords.Customer.CompanyName,
OrderCountry = ords.Customer.Country,
ProductName = dets.Product.ProductName,
UnitPrice = dets.Product.UnitPrice,
UnitsOrder = dets.Quantity,
ShipperName = ords.Shipper.CompanyName,
SalesFirstName = ords.Employee.FirstName,
SalesLastName = ords.Employee.LastName,
SalesTitle = ords.Employee.Title
}).ToList < OrderandPricingResult>();
}



///
/// Example: Query across entity ref with Where class
/// Same as previous function with added where clause
///
/// An entity is a representation in the model of a table
/// in the database, foreign key relationships are maintained
/// as entity references to the related tables in the model.
/// It is possible to query across tables through this
/// relationship in LINQ to SQL
///

///
///
public static List GetOrderAndPricingInformationByOrderId(int orderId)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from ords in dc.Orders // orders table
from dets in ords.Order_Details // entity set in orders table
where ords.OrderID == orderId
select new OrderandPricingResult
{
OrderID = ords.OrderID,
Company = ords.Customer.CompanyName,
OrderCountry = ords.Customer.Country,
ProductName = dets.Product.ProductName,
UnitPrice = dets.Product.UnitPrice,
UnitsOrder = dets.Quantity,
ShipperName = ords.Shipper.CompanyName,
SalesFirstName = ords.Employee.FirstName,
SalesLastName = ords.Employee.LastName,
SalesTitle = ords.Employee.Title
}).ToList();
}


///
/// Example: Aggregation
///
/// Returns the total sum of the order
/// selected by order ID by selecting
/// unit price multiplied by quantity
/// ordered and then calling sum for
/// the total
///

///
///
public static decimal? GetOrderValueByOrderId(int orderID)
{

NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

var matches =
(from od in dc.GetTable()
where od.OrderID == orderID
select od.Product.UnitPrice * od.Quantity).Sum();

return matches;

}



///
/// Example: Using Take to get a limited
/// number of returned values for display and
/// using Skip to sequence to a different
/// starting point within the returned values -
/// can be used to navigate through a large
/// list
///

///
///
public static List GetTopFiveOrdersById(int SkipNumber)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

return (from ord in dc.GetTable()
orderby ord.OrderID ascending
select ord).Skip(SkipNumber).Take(5).ToList();
}



#endregion



#region Inserting, Updating, Deleting Data


///
/// Insert or Update a Customer Record
///
/// If the customer ID exists, the existing
/// customer record is updated.
///
/// If the customer ID does not exist, the
/// new customer record is inserted into
/// the database
///

///
///
///
///
///
///
///
///
///
///
///
public static void InsertOrUpdateCustomer(string customerId, string companyName,
string contactName, string contactTitle, string address, string city,
string region, string postalCode, string country, string phone, string fax)
{

NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

var matchedCustomer = (from c in dc.GetTable()
where c.CustomerID == customerId
select c).SingleOrDefault();

if(matchedCustomer == null)
{
try
{
// create new customer record since customer ID
// does not exist
Table customers = Accessor.GetCustomerTable();
Customer cust = new Customer();

cust.CustomerID = customerId;
cust.CompanyName = companyName;
cust.ContactName = contactName;
cust.ContactTitle = contactTitle;
cust.Address = address;
cust.City = city;
cust.Region = region;
cust.PostalCode = postalCode;
cust.Country = country;
cust.Phone = phone;
cust.Fax = fax;

customers.InsertOnSubmit(cust);
customers.Context.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}
else
{
try
{
matchedCustomer.CompanyName = companyName;
matchedCustomer.ContactName = contactName;
matchedCustomer.ContactTitle = contactTitle;
matchedCustomer.Address = address;
matchedCustomer.City = city;
matchedCustomer.Region = region;
matchedCustomer.PostalCode = postalCode;
matchedCustomer.Country = country;
matchedCustomer.Phone = phone;
matchedCustomer.Fax = fax;

dc.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}

}


///
/// Delete a customer by customer ID
///

///
public static void DeleteCustomer(string customerID)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();

var matchedCustomer = (from c in dc.GetTable()
where c.CustomerID == customerID
select c).SingleOrDefault();

try
{
dc.Customers.DeleteOnSubmit(matchedCustomer);
dc.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}


#endregion



#region Stored Procedures


///
/// Stored Procedure: Sales By Year
///

///
///
///
public static List SalesByYear(DateTime? beginningYear, DateTime? endingYear)
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.Sales_by_Year(beginningYear, endingYear).ToList();
}



///
/// Stored Procedure: Ten Most Expenisve Products
///

///
public static List TenMostExpensiveProducts()
{
NorthWindDataClassesDataContext dc = new NorthWindDataClassesDataContext();
return dc.Ten_Most_Expensive_Products().ToList();

}


#endregion


}

Tuesday, March 22, 2011

EncryptionHelper

public class EncryptionHelper
{

# region Function to encrypt QueryString
public static string EncryptText(string pass)
{
return Encrypt(pass, "&%#@?,:*");
}
#endregion

#region EncryptQuery string
///
/// Encrypts a particular string with a specific Key
///

///
///
///

public static string Encrypt(string stringToEncrypt, string encryptionKey)
{
byte[] key = { };
byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)

try
{
key = Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex)
{
return (string.Empty);
}
}
#endregion

#region Function decrypt Querystring
public static string DecryptText(String pass)
{
return Decrypt(pass, "&%#@?,:*");
}
#endregion

#region Decrypt QueryString
///
/// Decrypts a particular string with a specific Key
///

public static string Decrypt(string stringToDecrypt, string sEncryptionKey)
{
byte[] key = { };
byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
byte[] inputByteArray = new byte[stringToDecrypt.Length];
try
{
key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(stringToDecrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex)
{
return (string.Empty);
}
}
#endregion


}

GroupHelper

public class GroupHelper
{

public GroupHelper()
{
//
}
private string _GroupName, _LoginGroupTypeID;

public static string LoginUSername
{
get
{


SPSite spSite; SPWeb spWeb;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
SPUser sUser = spWeb.CurrentUser;
//string str = sUser.Name + sUser.LoginName + sUser.Email + sUser.Groups.Count;
return sUser.LoginName;
}
}



}

}

public static string DisplayName
{
get
{


SPSite spSite; SPWeb spWeb;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
SPUser sUser = spWeb.CurrentUser;
//string str = sUser.Name + sUser.LoginName + sUser.Email + sUser.Groups.Count;
return sUser.Name;
}
}



}

}


public static string USername
{
get
{
SPSite spSite; SPWeb spWeb;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
SPUser sUser = spWeb.CurrentUser;
string str = sUser.Name + sUser.LoginName + sUser.Email + sUser.Groups.Count;
string[] name = sUser.Name.Split('\\');
if (name.Count() != 1)
{
return name[1].ToString();
}
else
{
return sUser.Name;
}
}
}



}

}


ArrayList _GroupList;

public ArrayList GroupList
{
get { return _GroupList; }
set { _GroupList = value; }
}
public string LoginGroupTypeID
{
get { return _LoginGroupTypeID; }
set { _LoginGroupTypeID = value; }
}

public string GroupName
{
get { return _GroupName; }
set { _GroupName = value; }
}
private string _ApproverGroupname;

public string ApproverGroupname
{
get { return _ApproverGroupname; }
set { _ApproverGroupname = value; }
}
public string GetCurrentUserGroup()
{
SPSite spSite; SPWeb spWeb;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
SPUser sUser = spWeb.CurrentUser;

GroupList = new ArrayList();
string str = sUser.Name + sUser.LoginName + sUser.Email + sUser.Groups.Count;
foreach (SPGroup grp in sUser.Groups)
{
GroupName = grp.Name;
GroupList.Add(grp.Name);
}

}
}
return GroupName;
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;

// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}

if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}

DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
object obVal = coll["Display name"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
public static string GetCompleteName(string loginname)
{
string RequestorFullName = string.Empty; ;
//try
//{
// string[] name = loginname.Split('\\');
// if (name.Count() != 1)
// {
// DirectoryEntry de = new DirectoryEntry("WinNT://" + name[0] + "/" + name[1]);
// return de.Properties["fullName"].Value.ToString();
// }
// else
// {
// return name.ToString();
// }
//}
// catch { return null; }

try
{
SPSite spSite; SPWeb spWeb;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
SPUserCollection us = spWeb.SiteUsers;

foreach (SPUser item in us)
{
if (loginname == item.LoginName)
{
RequestorFullName = item.Name;
}


}

}

}


}

catch
{
return null;
}
return RequestorFullName;
}


public string GetRequestoreApproverGroup(string Groupname)
{
SPSite spSite; SPWeb spWeb; SPList spList;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
spList = spWeb.Lists["DET_MappingGroup"];
var query = from SPListItem pi in spList.Items
where (pi["RequestorGroup"].ToString() == Groupname.ToString())
select pi["ApprovarGroup"];
if (query != null)
{
if (query.Count() > 0)
{
ApproverGroupname = query.Single().ToString();
}
}

}
}
return ApproverGroupname;
}

public string GetCurrentUserLoginGroup(string Groupname)
{
SPSite spSite; SPWeb spWeb; SPList spList;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
spList = spWeb.Lists["DET_Semi Group"];
var query = from SPListItem pi in spList.Items
where (pi["GroupName"].ToString() == Groupname.ToString())
select pi;
if (query != null)
{
if (query.Count() > 0)
{
foreach (var item in query)
{
LoginGroupTypeID = item["GroupTypeID"].ToString();
GroupName = item["GroupName"].ToString();
}
}
}

}
}
return LoginGroupTypeID;
}
public bool IsApprover(string groupname, int workorderrowid, bool IsExit)
{
SPSite spSite; SPWeb spWeb; SPList spList;

using (spSite = new SPSite(SPContext.Current.Site.Url))
{
using (spWeb = spSite.OpenWeb())
{
spList = spWeb.Lists["DET_WorkOrders"];
var query = from SPListItem pi in spList.Items
where pi.ID.ToString() == workorderrowid.ToString()
select pi["ApproverGroup"];
if (query != null)
{
if (query.Count() > 0)
{
ApproverGroupname = query.Single().ToString();
if (groupname == ApproverGroupname)
{
IsExit = true;
}
}
}

}
}
return IsExit;
}
}

InfoPath Forms vs ASP.NET ASPX Forms


InfoPath Forms

Let’s begin by taking a look at InfoPath.  InfoPath is a great tool for creating simple data-entry forms, and for retrieving data from a variety of data sources.  In addition, it’s great when you need to submit data to a SharePoint form library for the purposes of leveraging a SharePoint workflow.  Where InfoPath breaks down is when we need to submit data to other sources, or when we need to provide a rich user-interface with robust controls and data validation.  Let’s take a look at some pros and cons of InfoPath:

Pros

  • Great for submitting data to SharePoint or a SharePoint workflow
    Most of the time when we’re using electronic forms, it is to support a workflow process.  As you [should] know, a SharePoint workflow runs for a specific list item, and data needed for the workflow needs to be entered into the fields for that particular list item in order for the workflow to see it.  Because of this fact that the data actually needs to be a list item, InfoPath is a great choice, because you can effortless promote form fields as columns in your list, which the workflow can then use.
  • Great for retrieving data
    InfoPath provides a very simple wizard interface for selecting a data source for data retrieval.  You can easily select a web service, and XML document, or a SharePoint list and have that data appear in your form pretty easily.  You can also connect to a SQL database and retrieve data from tables, views, or stored procedures.
  • Great for simple end-user form development
    InfoPath is great for creating a simple form with a few fields and simple rules and simple data validation.  I keep emphasizing simple because once you introduce complex business rules, data validation, conditional formatting, or complex data presentation that pushes the limitations of InfoPath, you will be forced to get very creative which often involves some sort of custom coding.
  • Most of the time only requires SharePoint site permissions
    Unless you are creating a browser-enabled form with .NET code-behind, or your form requires Full Trust and uses the InfoPath client, it’s relatively easy to deploy a form to SharePoint.  Simply publish the form to the desired form library and you’re good to go.  However, as soon as you introduce .NET code in a browser-enabled form, you need to install and activate the form to Central Administration and activate the newly-created feature at the site collection level.  You will need to have access to Central Administration and to the site collection in order to activate these features.

Cons

  • Difficult to submit data to non-SharePoint data sources
    Like I mentioned, InfoPath is great for submitting data to a SharePoint form library.  It is not so great for submitting the data to anything else.  If your form is submitting data to a single (single being the operative word here), then you could potentially configure the form to submit directly to a table.  However if the data needs scrubbed or manipulated, chances are you will need to submit the data via a stored procedure, which InfoPath cannot do.  For this, you will be forced to develop a custom web service that accepts the data either field-by-field, or as a giant blob of XML that you have to parse through, which you then have to submit to the database by writing traditional ADO.NET code.  Not too simple anymore, huh?
  • Limited user-interface
    InfoPath allows you to create forms with a variety of standard controls, such as textboxes, date pickers, radio buttons, checkboxes, buttons, drop-down lists, repeating tables, etc..  Unfortunately, it is pretty much limited to those items (you get a few more with the rich client, but that’s beyond the scope of this post).  You don’t have any type of tree view control, no multi-select list box, no tab control, no image buttons, and no grid view control. The lack of a grid view control is a deal breaker in many cases, because we often have to present long lists of data, and the built-in repeating table doesn’t support sorting, grouping, or paging.  Yuck.  Finally, there’s no way to add HTML or CSS to your form, meaning that it can’t inherit any SharePoint styles, and you’re limited to what you can design in the form.  This frequently gives an inconsistent look and feel for a SharePoint process.  Again, yuck.
  • Difficult to secure sensitive data
    Assuming the InfoPath form is being submitted to a SharePoint form library, any data the form contains is inherently insecure.  The form is just saved to the form library like any other document, except as an XML document.  This means if your form contains social security numbers, salary information, or any other type of sensitive data, a user could download the XML file and open it in Notepad.  Even if the data isn’t visible through InfoPath, the data is still stored in the form and can be viewed by any user that knows how to download.
  • Difficult to integrate with Forms-Based Authentication
    Although browser-enabled forms will work with forms-based authentication, the useful username() function no longer works.  This means that even if you’re logged into your SharePoint site as a valid FBA user, InfoPath will have no idea who you are.
  • Not developer-friendly
    If you’ve made it this far in this post, you’ll have already read that while simple things are easy to accomplish in InfoPath, complicated things aren’t and often requires .NET code.  While you can definitely add .NET code to a form, it’s not the same type of form coding a typical developer is used to.  You have to parse XML to retrieve field values, you have to parse XML to set field values, and you’re still pretty much limited to the functionality that you have through the designer.  You can just write more complex business rules and logic, you can’t make the form or the field controls behave any differently.
  • Licensing
    Obviously your users need to be licensed for InfoPath Forms Services before they’re able to use it. Even if you have licenses for the InfoPath client, separate licenses are required for browser forms. If the users are internal and members of your domain, you must be licensed for InfoPath Forms Services, which is available either through the MOSS Enterprise CAL or the standalone InfoPath Forms Services CAL.  If the forms are going to be available externally to non-domain users or anonymous users, then you must be licensed for either Office Forms Services for Internet Sites or be licensed for SharePoint for Internet Sites, which is the external connector that provides the ability for an unlimited number of users to access and use InfoPath through a browser.

ASP.NET ASPX Forms
Creating ASP.NET ASPX forms offer the most in terms of flexibility, as you can do anything that you can do in a traditional ASP.NET web site, including HTML, CSS, JavaScript, and even AJAX.  A lesser-known technique is integrating these pages into the SharePoint “shell” to give users a seamless experience.  It doesn’t take much effort to have SharePoint host these pages and have the master page and styles applied to your custom forms.  Let’s take a look at some pros and cons associated with ASP.NET forms:

Pros

  • Great for submitting data to non-SharePoint data sources
    While InfoPath is great at submitting data to a SharePoint form library, ASP.NET forms are great for submitting data to everything else.  You can easily write your ADO.NET code or whatever-you-like code to submit to your data source, and not have to worry about parsing a bunch of InfoPath XML first in order to pull out the values.  It’s a lot less work to get the data into your data source.
  • Great for providing a rich user interface
    Unlike InfoPath, you aren’t limited to a tiny set of field controls.  You can use whatever an ASP.NET web site supports, including tree view, tab controls, grid views, AJAX – even Silverlight if you really really want.  You can also provide any type of business rules and validation you like as well, including summaries, friendly pop ups, etc.  Also, since the pages are inheriting the SharePoint styles and master page, your forms will automatically pick these styles up, and will also use the master page.  This gives the appearance that they’re actually built-in SharePoint pages.  It’s slick. There are plenty more options for developing a rich and clean user interface if you’re developing ASP.NET forms.
  • Developer friendly
    This one’s a no-brainer.  Obviously if you’re familiar with ASP.NET and .NET programming, creating data-entry forms are a cinch.  There’s no learning curve with learning how to code an InfoPath form, and you don’t have to learn the ins and outs of the InfoPath object model.  This opens up the development work to a wider audience of our developers, as not many have hands-on experience with writing .NET code behind an InfoPath form.  In addition, should any future updates be required to the form or the code, finding resources on ASP.NET online or hiring someone with ASP.NET skills will not be a difficult task.  It’s a widely practiced technology, and there are a ton of resources.
  • Can provide secure means of sensitive data access
    Since no data is actually stored in the ASP.NET form, it provides a much more secure way of viewing sensitive data, as it will have to be retrieved and submitted to the database directly.  A user can’t download an ASP.NET form and see the data like they can with an InfoPath form.
  • Integrates well with Forms-Based Authentication
    By using an ASP.NET form in an FBA-enabled site, we are able to see the user that is currently logged in, unlike with an InfoPath form.
  • Access to the SharePoint Object Model
    Since the ASP.NET forms are running under the context of the SharePoint site they’re accessed from, we can use the SharePoint Object Model to do whatever we wanted.  We could very easily access SharePoint list or site data, user profile information, etc., and bind that information to controls on the form.  To do this in InfoPath, you’d have to use the unfriendly out-of-the-box SharePoint web services, or write your own.
  • Licensing
    Not required! There aren’t any licensing headaches when exposing ASP.NET forms to users, even externally.  Obviously since they’re going to be integrated into SharePoint, you’ll have to have the appropriate licenses for that, but nothing specific to the forms themselves.

Cons

  • Potential additional development overhead
    Obviously writing custom ASP.NET forms requires a competent ASP.NET developer, which may not always be available (though I’d argue that in order to develop some of the complex forms that we have had to do in the past – you will still need a very competent .NET developer).  In addition, changes to simple business rules or data validation is more difficult to accomplish in ASP.NET than in an InfoPath form.  If the form is simple and doesn’t require data going to SQL, then an end-user is probably better of just using InfoPath.
  • Requires file system access on SharePoint server
    To deploy custom ASP.NET forms to SharePoint, they need to be placed onto each web front-end’s file system.  In addition, the assembly must be deployed to the GAC or to the web site root’s BIN directory.  Either way, the developer must have access to the file system, or to someone that has access to the file system.
  • Not business-user friendly
    One good thing about InfoPath is that business users can even build simple forms.  They will probably not be able to develop an ASP.NET form in .NET.  If the form is truly that simple, then creating ASP.NET forms is probably overkill anyways, and InfoPath should be the recommended solution.

 

So, How Do I Choose?
Great question! The answer should be easy -- do the simplest thing possible that will result in a clean solution.  If you can implement the desired functionality quickly and painlessly in an InfoPath form, then by all means do that.  If developing an InfoPath will actually be prohibitive to functionality and future maintainability, then consider building custom ASP.NET forms.