Thursday, July 28, 2011

Links to HTML5

Dive into HTML5 http://diveintohtml5.org/
Web and Mobile Trends
HTML5 is shaping up to be the premier presentation technology for the “three screens and the cloud” vision!
The Web Takes Center Stage at Microsoft's MIX11 Conference http://www.microsoft.com/presspass/press/2011/apr11/04-12mix1pr.mspx
Desktops and Browsers
HTML5 is showing up everywhere, and it’s not just for web development anymore!
Development
You can make HTML5 work for you with these tools!
Announcing HTML5 and CSS3 support for Visual Studio 2010 http://vishaljoshi.blogspot.com/2011/06/announcing-html5-css3-support-for.html
Build JavaScript in C# with Script#

Wednesday, July 27, 2011

Online Cloud Storage

This page provides links to FREE Online CLOUD Storage sites:

Google Drive 
5GB free storage
Integrated with Google Docs, Gmail, and soon the whole Google ecosystem.
The problem is that the Google Drive Download is not able to connect - keeps saying "One Moment Please"

Update: 30 Nov 2012
The problem of "One Moment Please" is gone.
The actual Google Drive Sync application for Windows is very difficult to find and is available here:
https://tools.google.com/dlpage/drive?pli=1

Warning: SYNC usually means if you delete from one, it will delete from another location too. If a synced file on the web gets deleted accidentally or maliciously, then when the sync occurs, that file will be removed from the device/PC too. The strategy to avoid this is to disable automatic sync of the app (eg Google Drive Sync) on the device / PC. Instead use manual syncing.

Here is how to use Google Drive Sync on Windows PC.
1. Download the Google Drive Sync app from the link above.
2. Install the app on PC.
3. Follow the prompts to sign in with your Google account.
4. After signing in, the following 2 dialog must be done carefully.
At the first dialog, press Next.



In this second dialog, Do Not Press "Start Sync".
Instead press "Advanced Setup"

5. The Advanced Setup Dialog below is important to set this up to avoid accidents with files.

- First Click on the Change button to choose a directory to sync. Whatever you choose, it will be appended with "Google Drive" sub-directory. Everything to be synced must be on this Google Drive subdirectory.
- Sync Options - allow you to control if there are some sub-directories inside Google Drive that should not be synced.
- Sync Google Doc Files: This setting will affect those files that are in Google Docs already, and hence lie outside of Google Drive.
- Start Google Drive automatically when you start the computer. This should be UNTICKED. By choosing the manual way, you have full control of when the application perform the syncing. So if you realize one file is missing from the Google Drive on the web, then you can fix it - otherwise if syncing is on, it will automatically delete the same file on your local PC.


16 May 2013
Copy
https://www.copy.com/bigger/
15GB free and 5GB for every new user introduced (for a limited time)
Seems like a new service. There appears to be desktop app for Windows, Linux, Mac as well as iPhone and Android, that allows content to be sync across all platforms.



Tresorit
http://tresorit.com/
5 GB free storage
For Windows, more platforms coming later.
Not Web Based. So you need to install the software and it runs on your PC - which is totally fine because syncing your files from PC to cloud should not need a Web interface anyway.
Big selling point is Encryption. They are supposed to encrypt your files first, then it gets transferred to the cloud.
50GB SPECIAL to 20 May 2013 (according to life hacker). To get this offer, you need to download the Tresorit from:
http://lifehacker.com/5994394/get-50gb-of-free-encrypted-online-storage-from-tresorit
According to Tresorit website, if the 50GB does not show up then:

To get the 50GB extended storage, download directly from one of these links:

http://lifehacker.com/5994394/get-50gb-of-free-encrypted-online-storage-from-tresorit?tag=dealhacker
http://gigaom.com/2013/04/11/secure-cloud-storage-outfit-tresorit-posts-10k-hacker-bounty/

If this does not work, send us your Tresorit account's email address and we'll update your quota.



Syncplicity
http://www.syncplicity.com/
2 GB free storage
Able to sync with Google Docs

Pros:
- Has Backup as well as Sync functions
- Allow folders that are synced, to change their location in the local PC.

Usage Tips
- In Sync mode, when a file is delete from the cloud or PC, then the file is also deleted from PC or cloud.
- In Backup mode, deleting the file from the Cloud, does not delete the file on the local PC.


Skydrive
http://skydrive.live.com/
25 GB of free online storage for sharing Microsoft Office docs and photos.
Updated 1 Jan 2013: No longer 25GB. Sometime during 2012, Microsoft decided to reduce the free accounts from 25GB to 7GB. Those who have used more than 7GB were OK. New and existing users who have very little content will get 7GB accounts only.


Picasa Web Album
http://https/picasaweb.google.com/home
http://picasa.google.com/support/bin/answer.py?hl=en&answer=1224181
1GB Free photos and videos
Photos up to 2048 x 2048 pixels and videos up to 15 minutes won't count towards your free storage.

Started playing with this and it seems to work nicely. A few things to know about.
You need to get these pieces of technology:
- Picasa - an application to download to your PC. It is a photo album management tool with editing capabilities.
- Picasa Web Album - you would have access to this if you have a google account
- Google+ is the new Google social website. You need to have Google+, then any photos less than 2048x2048 pixels will not be counted as your storage limit.

The concept and steps to backup and synchronize your photos to Google are the following:
- After installing the Picasa application, and running it, it allows you to choose which photo folders in your PC to become albums in Picasa.
- From Picasa, after choosing the photos to make albums, just click synchronize on a specific folder, and the photos will be synchronized with both Picasa Web Album and Google+ Photos.
- Warning: At this time, Picasa Web Album does not have the concept of a folder tree, ie.no sub-folders available.
- In Picasa application, the albums can be in Folder or Tree View but the default view is a Flat folder structure. This is quite confusing since folders appear at the same level as sub-folders. However this can be easily changed by going to View - Folder View  - Tree View.

Box.com
https://www.box.com/personal/
5 GB free online storage
Not good for backup of hard drive. Does not seem to have an explorer interface for backup or syncing. (CHANGED NOW - see below)
Max file size: 100MB

Update: 2 Jan 2013 - BOX SYNC - https://www.box.com/business/features/box-sync/
- this enables backup and syncing of hard drive. Box Sync is an application that can be downloaded and installed. However, it presents a single top level folder for all Box content. That means it does not allow you to pick and choose which folders you want to sync from your PC.

Update: 9 Feb 2013 - Get 50GB of Box FREE for Life & 50GB for Coworkers or Friends.
https://www.box.com/signup/o/dell_50gb_give_get
This fantastic offer may be time limited.
Also had a more detailed play with BOX SYNC. Unlike SugarSync or GDrive, this Box Sync allow the user to logoff and login again as another Box User. This means user can have multiple Box accounts and login as one user to access one set of data, then logout and login as another use and sync another group of data.

Update: 30 June 2013 - Have set this up and started using. Main problem occurred when it recognized a bunch of files that need to be synced (orange tick icon) but refused to sync it. A few other files may be successful in syncing (blue tick icon). Almost abandoned Box.com because of this. Googling it leads to the support / forum of Box.com where many users have been complaining but seems to have no solution.
SOLVED: One useful feature of Box.com is if you right click on the Box.com icon on the task manger, there is an option to view the log files. Immediately the reason became obvious since the log stated file permission type errors. People on the forum seems to blame in on the Box guys, but the Wind..OS may be partly to blame for stuffing up permissions. To fix this, "move" by dragging files to another sub-directory, then drag it back. Check file properties have included your user to have full control. Then start syncing again and it should work.

iDrive.com
http://www.idrive.com
5 GB free online storage
Appears to have a good GUI explorer interface for backup and sync.
No limit on file size for Upload or Download.
Can increase storage if you share your contacts with iDrive.


Amazon Cloud Drive
https://www.amazon.com/clouddrive/learnmore
5 GB of free online storage
Store your music, videos, photos, and documents on Amazon's secure servers.
MP3 format not counted towards quota.

SugarSync
https://www.sugarsync.com/free/

Get a SugarSync 5 GB Plan Free!
Free online backup, free file sync, and free file sharing
Free cloud storage gives you instant and easy access to your data anytime, anywhere.
Online backup and automatic file sync for work files or personal files like photos, videos, and music.
Download free mobile apps to sync iPhone, iPad, Android, BlackBerry, Windows Mobile, and Symbian devices.
Sync 5 GB of data across an unlimited number of devices.

Usage Tips:
1. Files or Folders can be viewed 3 ways: Windows Explorer, SugarSync App, SugarSync website.
2. Sync means deleting file on Cloud will also delete file on local PC and vice versa.
3. Delete synced file from Windows Explorer - will delete file from cloud.
4. Delete synced file from SugarSync Website - will delete file from local PC.
5. Stop Sync will not affect files on local PC, but will delete files from cloud.
6. To Stop Sync, open SugarSync App, go to Manage Sync Folders. Click on the folder name, then click on the little X on the top right corner.
7. Pros: Synced files in the cloud, which gets deleted, can be recovered
8. Cons: the folders that can be added to Sync, all seem to appear on a flat structure. There does not appear to be a folder hierarchy.
9. Web Archive has the following special characteristics:
- it acts as Backup - it does NOT sync files.
- put files here manually as once off event.
- files that are deleted from the Web Archive, cannot be recovered. There is no Recycle bin.

AVG Live Kive
http://free.avg.com/us-en/free-online-backup
Free Version 5GB
AVG LiveKive automatically backs up and synchronizes all your files from your devices, enabling you to view and share data safely anytime, anywhere. Think of it as your very own virtual archive.
Note: This free version website starts with free.avg.com. The regular avg domain does not mention anything about this free 5GB version.




MediaFire
http://www.mediafire.com/
Not sure yet whether there is an explorer interface to allow easy backup.
50 GB free on line storage - this is currently the most generous - but the limitations of the Free Account is very vague.  See http://www.mediafire.com/policies/terms_of_service.php


"You control your data through your free or Premium account and/or cookies which may be placed on your computer. MediaFire maintains multiple copies of active files. MediaFire bears no responsibility for maintaining your data indefinitely."

"MediaFire is not a data warehousing service. Its intended use is for active accounts and active file sharing which may inadvertently result in backups of files being shared. Accounts with large amounts of stagnant data `collecting dust` or accounts with very limited user and sharing activity may, in MediaFire' sole discretion and without notice, be removed from the Services."



JustCloud.Com
http://www.justcloud.com
The website says "Get Free Cloud Storage", in the next section, two points listed next to each other says: "Free Cloud Storage"
"Unlimited Storage Space"
But be warned, the Free means 15MB of free storage.
This is a fantastic account (sarcasm) because it is almost like fantasy and unreal that they give free 15MB. Why do I write 15MB in such big words? Because JustCloud tries so hard to hide this fact on their main page. Check out another article about this.
http://www.bluehostforum.com/archive/index.php/t-32408.html
I cannot see 15MB on JustCloud website via Chrome browser on Windows 7. But when I used Chrome on Linux, their website writes that the free account is 15MB.
Recommendation: Yes, sign-up so you can upload all your home movies, wedding photos, graduation photos onto this generous 15MB totally free, totally unlimited storage.



DropBox - DANGER
http://www.dropbox.com/pricing
The free Dropbox account comes with 2GB of space that you can use for as long as you like.
Disclaimer: This is a personal view based on experience.
I was using DropBox to sync one of my major folders with many subfolders and total size above 1.5GB.

1. Dropbox Startup - this causes computer to FREEZE. Only solution is to reboot to Windows Safe Mode, go to MSconfig and disable Dropbox from starting automatically. Then Reboot and launch Dropbox. Make sure the very first thing you do after this is to set Preference for Dropbox to NOT startup automatically.

2. Selective Sync Conflict - With the 1.5GB syncing for a long time, that's fine. But when I wanted to have more control over the syncing, while it was syncing, I went into Preference and into Selective Sync, and removed a few subfolders. After a while is appeared DropBox had serious problems and got confused by the changed selective sync option. The result is I've got folder "A" with some files missing, and a second folder "A (Selective Sync Conflict)" which contains some other partial files. This is not desirable.

3. Original Files DELETED - After all this, I decide just to uncheck all subfolders from the Selective Sync list so I can pause and consider what happened. In front of my eyes, all the sub-folders under DropBox started Disappearing. Dropbox decided to delete all subfolders which I removed from selective sync.

All these effects may have been bugs OR it may have been that I am incorrectly using their features. BUT, to allow user mistakes to convert into actions that DELETES original files in the users PC is very unacceptable.
Use Dropbox with Extreme Caution.


Some articles on Online Cloud Storage:

War of the Cloud Drives
May 13, 2012  Talbott Crowell
"Today, users have many choices for synchronizing files and backing important memories and personal assets including music, pictures, notes, business documents, and other personal or business files.  Recently Microsoft and Google have upped the ante against Dropbox and Apple with their latest offerings.  The offerings range from free to premium services, also known as the “freemium” model.  Amazon also has some interesting benefits, such as unlimited music storage which I have started to use.  Finally Box which also competes in the space for “personal” cloud storage may be better suited for company or team based scenarios.  In this post I will cover some of the pros and cons of each and some common scenarios for usage.  I will also discuss what you get for free, and what some extra charges will get you an how much it will cost (measured in gigabytes per month)."


Cloud Storage Showdown: Dropbox - Google Drive - Skydrive
May 9, 2012 By Chris Hoffman
"The cloud storage scene has heated up recently, with a long-awaited entry by Google and a revamped SkyDrive from Microsoft. Dropbox has gone unchallenged by the major players for a long time, but that’s changed – both Google and Microsoft are now challenging Dropbox on its own turf, and all three services have their own compelling features. One thing’s for sure – Dropbox is no longer the one-size-fits-all solution."

Cloud Drive Comparison
By David Strom / June 7, 2011 06:30 AM

The Cloud, Day 25: The Cloud Is Becoming Mandatory
With cutting edge devices, and the trend toward mobility, relying on the cloud is becoming more of a requirement than a convenience.

The Cloud, Day 24: Backing Up Your Cloud
There always seems to be a lot of backlash and fuss going around the Internet about how much personal information is shared between my social networks and other sites or services. It occurred to me, though: what if the opposite happened, and rather than too much data being shared you went to visit Facebook or Twitter and all of your data was gone?

The Cloud, Day 13: Storing and Managing Pictures in the Cloud
By Tony Bradley
November 26, 2011 09:44 AM ET


"     On Day 12 of the 30 Days With the Cloud journey I extolled the virtues of having precious photographic memories stored in the cloud, and automatically synced from my primary camera--my smartphone. Today I am going to dig a little deeper into the cloud-based options for storing pictures.
      As I mentioned on Day 12, some of the cloud photo storage options have the benefit of being automatically synced with mobile devices. Every picture I take with my Motorola Xoom is uploaded to Picasa, the pictures I took with the Windows Phone 7 “Mango” smartphone were synced to a folder on my SkyDrive, and pictures I take with my iPhone or iPad are automatically shared with Photo Stream on iCloud."




Saturday, June 04, 2011

How to Make Photos with Black and White Background and Colour Subject

This is to make the photo basically black and white but only the specific subject in colour. The basic idea involves the following:
- Make two copies of the same image in 2 separate layers
- Convert one layer to grayscale
- Switch to the colour layer and select most of the photo leaving the subject unselected.
- Delete the selection, leaving just the colour subject on top of the grayscale subject.

The steps below shop how to achieve this using Photoshop Elements.
1. To make a copy of the image: Layer -> Duplicate layer.
2. To select the bottom layer to work with, go to the Layer Palette on the right side of the screen. Then click Background to select the bottom layer.
3. To convert bottom layer to black and white:
   Enhance -> Convert to Black and White.
Since the black and white layer is at the bottom, you would not see any difference to the top layer.
4. Use a selection tool to select the image that you want to be in colour. For example we can use the Magnetic Lasso to select the subject.
5. To remove everything else besides the subject, with the subject selected from the previous step, now choose Select -> Inverse. Then press Delete.
This will leave the subject in colour on top and the bottom black and white background will appear.

Wednesday, June 01, 2011

Notes ASP.Net

NotesASPdotNet

Contents
=========
Tutorial
Structure
ASP.Net Configuration
Connecting Events
HTML Control Class
Web / Server Control Class
ASP postback - eg like AJAX
Dispose, Finalize, Finally, Close
ADO.Net - Accessing Data the Easy Way
ADO.Net - Example
ADO.Net - command parameters
ADO.Net - Data Binding
ADO.Net - Data Binding - DataList
ADO.Net - Styles and Templates summary
Windows Service Applications
VS Setup Projects
Understanding ADO.Net - from AppDev video tutorial
Using MySQL in Visual Studio
Configuring MySQL with ASP.Net
DropDownList
DataGrid - Sorting
GridView
GridView - Sorting
GridView - Selecting Rows, Clickable Rows
WebService in ASP.Net
ASP.Net Custom Control
Strings
How to Add Google Maps to your ASP.Net page
ASP.Net inline Tags <%...%>
ASP.Net calling Javascript client side

Tutorial
=========
1. Visual Studio 2005 -> Help -> Contents -> .Net Development
-> Web Applications -> ASP.Net Quickstart Tutorials

Structure
===========
System.Web.UI - Generic Page Class
|
V
custom page class (my *.cs file, eg HelloClass.cs)
|
V
custom aspx file (my *.aspx file, eg Hello.aspx)
|
V
Page object

System.Web.HttpApplication
|
V
class GlobalApp (global.cs)
|
V
global.asax -> contain event handling code, each application can
have one global.asax.

The classes are linked together like this:
VS2005: Global.asax no longer created automatically but can be added by:
Add new item -> Global Application Class.
Also the code behind global.asax.cs is no longer created, instead put
the code inline in global.asax
Hello.aspx
-----------
<%@ Page Language="CS" Inherits="HelloClass" Src="HelloClass.cs" %> -
if source is supplied
<%@ Page Language="CS" Inherits="HelloClass" %> - if dll is supplied
<html>
<body>
<form id="Form" runat="server">
<asp:Label id="lblTest" runat="server" />
</form>
....
HelloClass.cs
--------------
public class HelloClass : System.Web.UI.Page {
protected System.Web.UI.WebControls.Label lblTest;
private void Page_Load(){
lblTest.Text = "Hello World";
}
}
some basic event available to global.asax inherited from HttpApplication:
Application_OnStart
Application_OnEnd
Application_OnBeginRequest
Application_OnEndRequest
Application_OnError
Session_OnStart
Session_OnEnd
ASP.Net Configuration
======================
1. machine.config - one per server, located at:
Microsoft.Net/Framework/Version/Config/
2. web.config - one per application, as well as one in each virtual
sub-directory.
3. Structure and contents of web.config
+++++++++++++
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- custome settings - using your own keyword -->
<appSettings>
<add key="ConnectionString" value="Data Source=localhost;Initial
Catalog=Pubs;User ID=sa"/>
<add key="SelectSales" value="Select * FROM Sales"/>
</appSettings>
<system.web>
<httpRuntime />
<pages />
<compilation />
<customErrors />
<authentication />
<authorization />
<identity />
<trace />
<sessionState />
<httpHandlers />
<httpModules />
<globalization />
</system.web>
</configuration>
+++++++++++++
4. To make use of the special custom settings, eg.
++++++++++
using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project
{
public partial class ShowCustomConfigSettings : System.Web.UI.Page
{
protected Label lblTest;
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = "This app will connect with the connection
string <br><br>";
lblTest.Text +=
ConfigurationSettings.AppSettings["ConnectionString"];
lblTest.Text += "<br><br> and will execute the SQL statement <br>";
lblTest.Text += ConfigurationSettings.AppSettings["SelectSales"];
}
}
}
++++++++++

Connecting Events
===================
case: A button called id="Convert" on the aspx page. Functionality is
in the function called
"Convert_ServerClick"
On the aspx page, have the attribute in the <%@Page .... >
AutoEventWireup="false"
To connect the function "Convert_ServerClick" to the event:
1. protected override void OnInit(EventArgs e) {
InitializeComponent();
base.OnInit(e);
}
2. private void InitializeComponent() {
Convert.ServerClick += new EventHandler(Convert_ServerClick);
}
Note that EventHandler is a DELEGATE that connects a the function
"Convert_ServerClick"
The EventHandler delegate would have the same prototype of the
function it points to, ie.:
protected void Convert_ServerClick(Object sender, EventArgs e)
The ServerClick would be a type of the EventHandler delegate; perhaps
public event EventHandler ServerClick
perhaps defined under the Convert's class - HtmlInputButton
HTML Control Class
=======================
System.Object
System.Web.UI.Controls
HtmlControl ---> System.Web.UI.HtmlControls namespace
HtmlImage
HtmlInputControl
HtmlInputButton
HtmlInputCheckBox
HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlContainerControl
HtmlAnchor
HtmlButton
HtmlForm
HtmlGenericControl
HtmlSelect
HtmlTable
HtmlTableCell
HtmlTableRow
HtmlTextArea
Web / Server Control Class
============================
System.Object
System.Web.UI.Controls
Repeater ---> System.Web.UI.WebControls
WebControl
AdRotator
Calendar
ValidationSummary
BaseDataList (abstract)
DataGrid
DataList
ListControl (abstract)
CheckBoxList
DropDownList
ListBox
RadioButtonList
Button
CheckBox
RadioButton
Hyperlink
Image
ImageButton
Label
BaseValidator (abstract)
CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator
LinkButton
Panel
Table
TableCell
TableHeaderCell
TableRow
TextBox
ASP postback - eg like AJAX
============================
1. Web control events that can use POSTBACK, when AutoPostBack property is set
to true:
Events Web Control
======= ===========================
Click Button, ImageButton
TextChange TextBox
CheckChanged CheckBox, RadioButton
SelectedIndexChange DropDownList, ListBox, CheckBoxList, RadioButtonList
2. ASP.Net automatically adds these to the HTML page:
<input type="hidden" name="__EVENTTARGET" value=""/>
<input type="hidden" name="__EVENTARGUMENT" value=""/>
<script language="javascript">
<!--
function __doPostBack(eventTarget, eventArgument){
var theform = document.Form1;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
-->
3. Add event handlers to the InitializeComponent() method
i.e. <button>.<Event> += new EventHandler(<functionName>)
eg txt.TextChanged += new EventHandler(CtrlChanged)
4. Implement using the added function:
private void CtrlChanged(Object sender, EventArgs e) { }
ADO.Net - Accessing Data the Easy Way
=============================
To retrieve information
1. Create Connection, Command and DataReader objects
2. Use DataReader to retrieve info and display it on web
3. Close connection.
4. Send page to user.
To add or update information
1. Create new Connection and Command objects.
2. Execute the Command
ADO.Net - Example
=========
using System.Data;
using System.Data.SqlClient; // for MS SQL
using System.Data.OleDb; // for general connector
// Define the connection to Database
<x>={Sql, OleDb, ...}
<x>Connection myConn = new <x>Connection();
myConn.ConnectionString = "Provider=SQLOLEDB.1; Data
Source=localhost;" + " Initial Catalog=Pubs; User ID=root";
// the provider is need when <x>=OleDb, but not when <x>=Sql.
// Password is not passed here if using "Integrated Windows Authentication"
myConn.ConnectionString = "Provider=SQLOLEDB.1; Data
Source=localhost;" + " Initial Catalog=Pubs; Integrated
Security=SSPI";
// Making the connection
try{
myConn.Open();
lblInfo.Text="<b>Server Version: </b>" + myConn.ServerVersion;
lblInfo.Text+="<br><b> Connection is:</b> " + myConn.State.ToString();
} catch(Exception err) {
lblInfo.Text = "Error reading the database.";
lblInfo.Text += err.Message;
} finally {
myConn.Close();
lblInfo.Text += "<br> Now Connection is";
lblInfo.Text += myConn.State.ToString();
}
//Alternative connection
using{
myConn.Open();
lblInfo.Text="<b>Server Version: </b>" + myConn.ServerVersion;
lblInfo.Text+="<br><b> Connection is:</b> " + myConn.State.ToString();
}
lblInfo.Text += "<br> Now Connection is";
lblInfo.Text += myConn.State.ToString();
// Creating the SQL statement and assigning to Command
<x>Command myCmd = new <x>Command();
myCmd.Connection = myConn;
myCmd.CommandText = "Select * from Authors";
//Alternative
<x>Command myCmd = new <x>Command("Select * from Authors", myConn);
// Using Command with DataReader
<x>DataReader myReader;
myReader = myCmd.ExecuteReader();
// Reading objects
myReader.Read(); // reads an object at a time sequentially
// Cleanup
myReader.Close();
myConn.Close();
ADO.Net - command parameters
==============================
Instead of using this:
insertSQL "Insert INTO authors (au_id) VALUES ('txtID.Text')"
.... where txtID is a from the GUI on the webpage.
This method can be hacked via SQL Injection. To solve this, Command
Parameters are used:
insertSQL "Insert INTO authors (au_id) VALUES (?)"
cmd.Parameters.Add("?", txtID.Text);
where cmd is a OleDBCommand, and note that "?" is for OleDB only.
MySQL or MSSQL may have different symbols or notation for their
command parameters.
For MSSQL,
// don't ever do this!
// SqlCommand cmd = new SqlCommand(
// "select * from Customers where city = '" + inputCity + "'";
// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = @City", conn);
// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "@City";
param.Value = inputCity;
// 3. add new parameter to command object
cmd.Parameters.Add(param);

ADO.Net - Data Binding
=======================
Simple Data Binding:
1) in the aspx page, have something like:
<asp:Label id="lbLabel" runat="server">
There were <%# TransactionCount %>
</asp:Label>
2) In the code behind, have something like:
private void Page_Load(...){
TransactionCount = 10;
this.DataBind();
Alternative to data bind above is to do this in-code.
3) private void Page_Load(...){
TransactionCount = 10;
lblDynamic.Text = "There were " + TransactionCount.ToString();
Multiple Binding:
1. Form an array list from whereever:
eg. ArrayList fruit = new ArrayList();
fruit.Add("Kiwi");
or from database
2. Define binding for list controls; eg
MyListBox.DataSource = fruit;
MyDropDownListBox.DataSource = fruit;
MyHTMLSelect.DataSource = fruit;
MyCheckBoxList.DataSource = fruit;
MyRadioButtonList.DataSource = fruit;
3. Activate the binding, eg.
this.DataBind(); // this refers to the current page.

Multiple Binding with hashtables:
1. Create hashtable with key,val pair
Hashtable fruit = new Hashtable();
fruit.Add(1, "Kiwi");
fruit.Add(2, "Pear");
2. Binding specific fields
MyListBox.DataTextField = "Value" -> put the Value of hastable
into the Text of the Control
MyListBox.DataValueField = "Key" -> put the Key of hastable into
the value of the Control
3. Define databinding and activate
MyListBox.DataSource = fruit;
4. The result is the following HTML will be rendered:
<select name="MyListBox" id="MyListBox">
<option value="1">Kiwi</option>
Databinding with databases:
1. Some possible namespaces (when using OleDB):
using System.Data;
using System.Data.OleDb;
2. Making data using dataset example:
DataSet ds = new DataSet();
ds.Tables.Add("Users");
ds.Tables["Users"].Columns.Add("Name");
ds.Tables["Users"].Columns.Add("Country");
DataRow dr = ds.Tables["Users"].NewRow();
dr["Name"] = "John";
dr["Country"] = "Uganda";
ds.Tables["Users"].Rows.Add(rd);
3. Bind table to data source:
lstUser.DataSource = ds.Tables["Users"];
lstUser.DataTextField = "Name";
or Bind whole DataSet to data source:
lstUser.DataSource = ds;
lstUser.DataMember = "Users";
lstUser.DataTextField = "Name";
4. Activate the Binding:
this.DataBind();
or to bind just the list box
lstItems.DataBind()
ADO.Net - Data Binding - DataList
=====================================
1. Code Behind:
public class BasicAuthorList: Page
{
protected DataList listAuthor;
// (Initialisation code omitted)
private string connectString ="Provider ......."
private void Page_Load(Object sender, EventArgs e)
{
string SQL = "SELECT * FROM AUTHORS";
OleDbConnection con = new OleDbConnection (connectString);
OleDbCommand cmd = new OleDbCommand(SQL, con);
OleDbAdapter adapt = new OleDbAdapter(cmd);
DataSet pubs = new DataSet();
con.Open();
adapter.Fill(pubs, "Authors");
con.Close();
//Bind the DataSet and activate the data bindings for the page
listAuthor.DataSource = pubs.Tables["Authors"];
this.DataBind();
2. ASPX DataList template
<asp:DataList id=listAuthor runat="server">
<ItemTemplate>
<font face="Verdana" size="2">
<b><%# DataBinder.Eval(Container.DataItem, "au_fname") %>
<%# DataBinder.Eval(Container.DataItem, "au_lname") %></b></font>
<br> Address: <%# DataBinder.Eval(Container.DataItem, "address") %>
<br> City: <%# DataBinder.Eval(Container.DataItem, "city") %>
</font>
</ItemTemplate>
</asp:DataList>
3. Formating Values - for DataBinder
eg DataBinder.Eval(Container.DataItem, "Price", "{0:C}")
{0:C} Currency
{0:E} Scientific (Exponential)
{0:P} Percentage
{0:F?} Fixed Decimal
see MSDN Help for more.
4. Adding different styles to Templates
a) Manual option - hand coding on aspx file
<HeaderTemplate>
<h2> title </h2>
</HeaderTemplate>
<ItemTemplate>
(Item style1)
</ItemTemplate>
<AlternatingItemTemplate>
(Item style2)
</AlternatingItemTemplate>
<SeparatorTemplate>
<h2> title </h2>
</SeparatorTemplate>
<FooterTemplate>
<h2> title </h2>
</FooterTemplate>
b) Using VS.Net right-click DataList properties
c) AutoFormat link from the DataList properties
d) To make columns and rows, check out the RepeatDirection and
RepeatColumns properties.

ADO.Net - Data Binding - DataGrid
=====================================
1) DataList may have columns and rows, but DataGrid has columns such
that the columns
correspond to certain fields of the data item; eg phone - city - zip
code as different
columns.
2) Features include: automatic paging, sorting, editing, selecting.
3) Examples that show the Columns tag and the use of styles:
<asp: DataGrid id=gridauthor runat="server" AutoGenerateColumns="false"
BorderColor="#..." BorderStyle="None" CellSpacing="2"
BackColor="#..." CellPadding="3" BorderWidth="1px">
<FooterStyle ForeColor="#..." BackColor="#..." ></FooterStyle>
<HeaderStyle ForeColor="#..." BackColor="#..." ></HeaderStyle>
<ItemStyle ForeColor="#..." BackColor="#..." ></ItemStyle>
<Columns>
<asp:TemplateColumn HeaderText="AuthorName">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "au_fname") %>
<%# DataBinder.Eval(Container.DataItem, "au_lname") %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
4) DataGrid has special columns including:
TemplateColumn - contents here include <ItemTemplate> and other stuff
that can go into
DataList.
BoundColumn - a particular field from database
ButtonColumn
EditCommandColumn
HyperlinkColumn
All these columns should exist within <Columns> ... </Columns>

ADO.Net - Data Binding - Repeater
=====================================
Repeater has not much formatting by itself. It depends on formatting provided
in the html. Example:
<asp:Repeater id=repeatauthor runat="server">
<HeaderTemplate> <table> </HeaderStyle>
<ItemTemplate><tr>
<%# DataBinder.Eval(Container.DataItem, "au_fname") %>
</ttr></ItemTemplate>
<FooterTemplate> </table> </FooterStyle>
</asp:DataGrid>
ADO.Net - Styles and Templates summary
=======================================
Styles
DataList DataGrid Repeater
-----------------------------------------------------------
AlternatingItemStyle AlternatingItemStyle None
EditItemStyle EditItemStyle
FooterStyle FooterStyle
HeaderStyle HeaderStyle
ItemStyle ItemStyle
SelectedItemStyle SelectedItemStyle
SeparatorStyle PagerStyle

Template
DataList DataGrid* Repeater
-----------------------------------------------------------
AlternatingItemTemplate FooterTemplate AlternatingItemTemplate
EditItemTemplate HeaderTemplate FooterTemplate
FooterTemplate ItemTemplate ItemTemplate
HeaderTemplate EditItemTemplate SeparatorTemplate
ItemTemplate
SelectedItemTemplate
SeparatorTemplate
* only supported by Template column
1) Do not bind the grid in the Page.Load event handler, otherwise info is
lost about which button user clicked or item selected.
private void Page_Load......
if(!this.PostBack) {
DataSet ds = GetDataSet();
BindGrid(ds);
.........
}
private DataSet GetDataSet(){
string SQL = "...."
OldDbConnection ...
OldDbCommand cmd =
OleDbAdapter = ...
DataSet dsPubs = ...
adapter.Fill(dsPubs, "Authors");
con.Close();
return dsPubs;
}
private void BindGrid(DataSet ds){
gridAuthor.DataSource = ds.Table["Authors"];
this.DataBind();
}

Windows Service Applications
=============================
1. Do not have any in/output to screen or Windows, or it will crash the app.
2. Error messages should be logged in the Windows event log rather
than raised in the user interface.
3. To control, use Services Control Manager, or Server Explorer, or
the ServiceController class (use this
to control the service from another app).
4. States of the service include: start, stop, pause, resume
Corresponding methods in code: OnStart, OnStop, OnPause,
OnContinue, OnShutdown, OnCustomCommand, OnPowerEvent.
5. Two types of services: Win32OwnProcess, Win32ShareProcess.
6. VisualStudio has installation components that can install
resources, register the service and let Services Controller
Manager know. Add these installers to the app and also create a
separate setup project.
7. Must inherit from System.ServiceProcess.ServiceBase class. The
project must contain installation components.
To create the Service:
- set ServiceName property
- create installers
- override methods for OnStart and OnStop.
8. System.ServiceProcess.ServiceProcessInstaller and
System.ServiceProcess.ServiceInstaller
—You use these classes to install and uninstall your service.
9. Execution Process:
Add Installers in project
Build
Install: installutil yourproject.exe / Uninstall: installutil
/u yourproject.exe
Start the Service
10. Debugging:
Install service
Start service
In VS, Debug->Process
Click Show System Processes
Attach process
add any break points
use Services Control Manager to control the service.
11. To add Installers:
-In Solution Explorer, go to Design View of the service.
-Click on background of designer and AddInstaller.
-A new class, ProjectInstaller, and two installation components,
ServiceProcessInstaller and ServiceInstaller,
are added to your project, and property values for the service are
copied to the components.
-Click the ServiceInstaller component and verify that the value
of the ServiceName property is set to the
same value as the ServiceName property on the service itself.
-To determine how your service will be started, click the
ServiceInstaller component and set the StartType property
to the appropriate value. { Manual, Automatic, Disabled }
- To determine the security context in which your service will
run, click the ServiceProcessInstaller
component and set the appropriate property values. For more
information, see How to: Specify the Security Context for Services.
- Override any methods for which you need to perform custom
processing. For more information, see How to: Override Default Methods
on Installation Components.
- Perform steps 1 through 7 for each additional service in your project.
Note: For each additional service in your project, you must
add an additional ServiceInstaller component
to the project's ProjectInstaller class. The ServiceProcessInstaller
component added in step
three works with all of the individual service installers in the project.
- Create your setup project and custom action to deploy and
install your service.
For more information on setup projects, see Setup Projects.
- After you add installers to your application, the next step is to
create a setup project that will install
the compiled project files and run the installers needed to install
your service. To create a complete
setup project, you must add the service project's output to the
setup project and
then add a custom action to have your service installed. For more
information on setup projects, see Setup Projects. For more
information on custom actions, see Walkthrough: Creating a Custom
Action.
(see VS Setup Projects for more details)

VS Setup Projects
=====================
1. Design, code, build your project in VS Studio say project ProjA in
solution SolnA.
2. Create the setup project SetupA, in SolnA: Add Project -> New
Project -> Other Project Types -> Setup and Deployment.
3. Right click setupA -> Install -> Add Project Output. Select ProjA
and choose "Primary Output".
4. Right click setupA -> View -> Custom Actions.
5. Right click on Custom Actions -> Add Custom Option. Select
Application Folder -> Primary output from ProjA.
6. Build.
7. The msi and exe file will be created.

Understanding ADO.Net - from AppDev video tutorial
====================================================
Object Model:
Connected Object (Specific to DB engine or provider)
-> .Net Data Provider (incl. MySql.Data.MySqlClient or
SystemData.ODBC|OleDB|SqlClient|OracleClient)
-> Connection: Transaction
-> Command: Parameters (eg to execute some command)
-> DataReader:
-> DataAdapter:
-> Fills DataTable: SelectComm
-> Updates Database: InsertComm, UpdateComm, DeleteComm
DisConnected Object (can work with data in a disconnected state)
-> DataSet (analogous to Database) <-> XML
-> DataTableCollection
-> DataTable:
-> DataRowCollection - storing the data
-> DataColumnCollection - names and properties of columns
-> ConstraintCollection - eg unique key or foreign key constraints.
-> DataRelationCollection
-> DataView
-> Row Filter
-> Sort
-> Extended support for Data Binnding
-> DataTableReader
-> A DataReader for DataTables and DataSets
-> Fast forward only reading
-> resilient to adding or deleting rows while reading

... to be continued at Data Caching Object
Using MySQL in Visual Studio
=============================
1. View -> Server Explorer
2. Look for database server and connect
Configuring MySQL with ASP.Net
===============================
It is easy to use MySQL with ASP.Net. becasue by default the local
ASP.Net enables you with FULL TRUST permission.
This section shows how to configure ASP.Net to work with MySQL where
the ASP.Net is stored in a ISP's server,
which usually uses MEDIUM TRUST, not FULL TRUST.
To the SQL administrator:
1. There are two options, one is to modify the web_mediumtrust.config;
the other option is to copy and rename the config file.
The web_mediumtrust.config is located typically in
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\
Add the SOCKPermission to this file.
<SecurityClass .............
<SecurityClass Name="SocketPermission"
Description="System.Net.SocketPermission, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
...
...
<IPermission
class="SocketPermission"
version="1"
Unrestricted="true"/>
2. If we choose the second option in step 1. to make a new file and
called web_mediumMySQLtrust.config, then we need
to register this in the
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config with
the following line:
<trustLevel name="Medium" policyFile="web_mediumtrust.config" />
.... already there
<trustLevel name="MediumMySQL"
policyFile="web_mediumMySQLtrust.config" /> .... add this new one
Also in the same file, add this within the <system.web>
<trust level="Medium" originUrl="" />
or
<trust level="MediumMySQL" originUrl="" />

To the Developer:
1. In the web application, in the web.config file, insert the line
about <trust> just before </system.web>
eg.
<system.web>
......
......
<trust level="Medium" originUrl="" />
</system.web>

DropDownList
============
To add first element, add a ListItem and the property
AppendDataBoundItems set to true.
Eg.
<asp:dropdownlist id="suburbDropList" AppendDataBoundItems="true"
AutoPostBack="True" runat="server" >
<asp:ListItem Text="(Select a Suburb)" Value="" />
</asp:dropdownlist>
DataGrid - Sorting
===================
To allow for sorting on the DataGrid, the following are needed.
1. Right click on the GUI design of the DataGrid and set
"AllowSorting" to "true".
2. Add the following in the aspx code file in the DataGrid item:
OnPageIndexChanging="PageChangeFunction" OnSorting="SortingFunction"
3. Set property AutoGenerateColumns to true,
i.e.TestMenu.AutoGenerateColumns = true;
GridView
==========
Namespace: System.Web.UI.WebControls
Assembly: System.Web (in system.web.dll)
Version: since .Net 2.0
Summary: Displays the values of a data source in a table where each
column represents a field and each row represents a record. The
GridView control allows you to select, sort, and edit these items.
Event: OnRowDataBound()
- can be used to set the width of the grid view once data is bound.
- Example:
<code>
protected void gvShop_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
GridView gv = (GridView)sender;
//e.Row.Cells[0].Width = 100; // Free Size
e.Row.Cells[1].Width = 100; //name
e.Row.Cells[2].Width = 300; //address
</code>

GridView - Sorting
===================
This describes how to implement the sorting event of a GridView object.
1. Sorting must be allowed in the GridView object. On the aspx page,
the GridView object must look something like:
<code>
<asp:GridView ID="gvShop" runat="server" AllowSorting="True"
OnRowDataBound="gvShop_RowDataBound"
OnPageIndexChanging="gvShop_PageIndexChanging"
OnSorting="gvShop_Sorting" >
</code>
The important properties are AllowSorting set to True and OnSorting
specified with the name of the method that performs the sorting. By
Default, the event name is given by the object ID (gvShop) combined
with the event (Sorting) hence the name gvShop_Sorting.
2. Before implementing the GridView sorting event, let us define two
strings at the start of the class.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
These specific strings ASC and DESC are required in the sorting
expressions later.
3. Define the property called gvSortDirection - to hold the state of
whether it is currently sorted in ascending or descending fashion.
<code>
public SortDirection gvSortDirection {
get {
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
</code>
4. Finally, the sorting event is implemented as below:
<code>
protected void gvShop_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
string strSort = null;
if (gvSortDirection == SortDirection.Ascending)
{
gvSortDirection = SortDirection.Descending;
strSort = sortExpression + " " + DESCENDING;
}
else
{
gvSortDirection = SortDirection.Ascending;
strSort = sortExpression + " " + ASCENDING;
}
DataTable dc1 = (DataTable)gvShop.DataSource;
dc1.DefaultView.Sort = strSort;
gvShop.DataBind();
}
</code>
A few things to note:
- when the user press on the header of the column, the data will be
sorted in ascending, then descending way alternately. This is possible
by the if loop which changes the direction of the sorting each time it
is sorted.
- the strSort is made up of the name of the column to be sorted, and
whether it is ascending or descending.
- The most important step is to assign the DefaultView.Sort = strSort.
Note that in this case, the GridView was originally sourced from a
DataTable, hence in this example, the DataSource is casted into a
DataTable dc1 object. Finally the GridView need to be binded.

GridView - Selecting Rows, Clickable Rows
==========================================
In ASP.Net, a simple GridView presents a table with rows of data, in
different columns. All the data are usually obtained from some
DataSource which may come from a database. This section shows how to
add an Extra column where all the entries in this column are clickable
and is linked to the row on which it is clicked. An example of a
Gridview with the Extra column as the first column:
clickable Col 1 Col 2
select John Smith
select Jane Doe
select Alice Wong
select Bob Chan
In the example, the first row are column names. Each of the "select"
words are clickable and can be used to launch an action, and identify
which row was clicked. The implement of this involves the following
steps:
1. On the aspx page, the code looks like:
<code>
<asp:GridView ID="gvShop" runat="server" AllowSorting="True"
OnRowDataBound="gvShop_RowDataBound"
OnPageIndexChanging="gvShop_PageIndexChanging"
OnSorting="gvShop_Sorting" >
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"
ForeColor="Navy" />
<Columns>
<asp:BoundField ReadOnly="True" >
<ItemStyle Width="0px" />
</asp:BoundField>
<asp:TemplateField HeaderText="clickable">
<ItemTemplate>
<asp:LinkButton ID="lnk_ShopName" runat="server" Text="select"
Tooltip="some tip"
CommandArgument='<%# Eval("Col 1") %>'
style="background-image: url(images/icon.gif);"
OnClick="lnk_ShopName_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code>
The important things to note are the following:
- The <asp:TemplateField> tag - see the word "clickable" as the name
of the column. The TemplateField can be generated from the GUI in the
Design mode of the aspx page, by right clicking the GridView rectangle
and right clicking the top right corner and select "edit columns".
- The <ItemTemplate> tag - this contain a LinkButton object whose Text
is "select". So the words "select" is displayed in the GridView
column.
- The CommandArgument is very important, the argument inside Eval,
must be exactly the same name as one of the column names. This means
that when a row is clicked, the CommandArgument will take the value at
that row of the specified column. In this example, Eval("Col 1") means
either John, Jane, Alice or Bob will be taken along the event.
- Instead of the words "select", an image or icon can be used, and
this is done by the background-image attribute in the LinkButton.
- For the event to do something it has to be linked. Here the
LinkButton is connected to the function called "lnk_ShopName" which is
called whenever an event occurs.
2. Implementing the event or action on the aspx.cs page. In this
example, the event triggers the method called "lnk_ShopName" to be
executed. The method can be something like:
<code>
protected void lnk_ShopName_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.LinkButton linkBut;
linkBut = (LinkButton)sender;
string sName = linkBut.CommandArgument;
// do something with sName
}
</code>
The information about which row is clicked can be extracted from the
sender object.
Since the Control was a LinkButton, the sender is cast into the LinkButton.
The CommandArgument will contain the data at the row that was clicked,
at the column specified in the Eval argument on the aspx page. In this
case, Col 1 was chosen as the column.

WebService in ASP.Net
======================
*.asmx - web service file
WSDL - Web Service Description Language, describes the methods
and parameters in a web service.
The elements of WSDL are: definitions, types, message,
portType, binding, service.
SOAP - way to encode info to pass to web service
HTTP - protocol through which SOAP messages are sent
DISCO - discovery standard that contains links to web services
UDDI - business registry that lists all info about companies
and web services they provide, with
URLs for their WSDL contracts and DISCO.
Data types: Basic / primitives, Enumerations, DataSets, XmlNode,
Custom Objects, Arrays

Testing the web service
------------------------
http://<domain>/<webservice>.asmx -> to view the web service directly
http://<domain>/<webservice>.asmx?WSDL -> to view the WSDL.
http://<domain>/<webservice>.asmx?op=<methodName> -> to access
the web service method directly
The use of web services in C# ASP.Net is illustrated with the example below:
----------------------------------
1.<%@ WebService Language="C#" Class="Util" %>
2. using System.Web.Services;
3. using System;
4. [WebService(Namespace="http://www.contoso.com/")]
5. public class Util: WebService
6. {
7. [ WebMethod]
8. public long Multiply(int a, int b)
9. {
10. return a * b;
11. }
12. }
----------------------------------
or
----------------------------------
in file: Util.asmx
1.«%@ WebService Language="C#" CodeBehind="Util.asmx.cs" Class="Util" %»
in file: Util.asmx.cs
2. using System.Web.Services;
3. using System;
4. [WebService(Namespace="http://www.contoso.com/", Description="test utility")]
5. public class Util: WebService
6. {
7. [WebMethod(Description=" test a method "]
8. public long Multiply(int a, int b)
9. {
10. return a * b;
11. }
12. }
----------------------------------
1. Declare the webservice using «%@ WebService....
Option 1: Place the above code inside *.asmx file with the C# code.
Option 2: Put only the <%@ WebService in the asmx class and put the C#
code somewhere else.
Then the declaration would be:
<%@ WebService Language="C#" Class="MyName.MyWebService,MyAssembly" %>
... where MyAssembly is the name of the assembly.
2. Deriving the WebService class - this is optional. Lines 2,5.
3. Apply WebService attribute and specify domain to avoid confusion
with other webservices.
see line 4.
4. Define the web service method using [ WebMethod ] - see line 7.
5. State Management for Web Services is achived by deriving from the
WebService class. It provides
access to ASP.NET objects such as:
Session - client specific state information
Application - used to store data globally and available to all clients
Server - utility functions
User - info about current client including authentication
Context - provides access to Request, Response and Cache
7. Storing and access state in a client session:
Declare: [ WebMethod(EnableSession=true) ]
Store: Session["MyServiceUsage"] = 1;
Access: Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;
8. Storing and access state in Web application hosting the Web service:
Declare: [ WebMethod ]
Store: Application["appMyServiceUsage"] = 1;
Access: Application["appMyServiceUsage"] = ((int)
Application["appMyServiceUsage"]) + 1;

ASP.Net Custom Control
=======================
The following describes Custom Control for web applications (*.aspx).
The Custom Control for console
applications are similar, but not exactly.
1. To add a user control, right click on the web application project
in the Solution Explorer. Click
New Item, then choose Web User Control, and name it WUC.

2. In Visual Studio, this will auto create 3 files:
- WUC.ascx - with Design and Code view
- WUC.ascx.cs - the code to be edited or added.
- WUC.ascx.designer.cs
3. Put the collection of controls in your custom control withing the
WUC.ascx file. For example,
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WUC.ascx.cs"
Inherits="ParentWebApp.WUC" %>
<asp:Label ID="lblFooter" runat="server" Height="87px" Text="Label"
Width="214px"></asp:Label>
4. The Label control above can be also created by using the WUC.ascx
design view. Just
drag the Label button from the toolbox onto the form.
5. In the code behind file WUC.ascx.cs, make the WUC class inherit
from System.Web.UI.UserControl. And
in the Page_Load, enter code for what the controls need to do. For example,
public partial class WebUserControlFooter : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
lblFooter.Text = "This page was served at ";
lblFooter.Text += DateTime.Now.ToString();
}
}
6. To use this custom control on any aspx web page:
a) Register the custom control on those aspx web pages, eg.
<%@ Register TagPrefix="cr" TagName="WUC" Src="~/WUC.ascx" %>
b) Add the custom control, eg.
<cr:WUC id=Footer1 runat="server" />
Note that the TagPrefix name is the alias for the custom control to be
used in the aspx web page.
Strings
========
\r\n - Carriage Return, then Newline - this is neeeded for
example in TextBox component.
How to Add Google Maps to your ASP.Net page
=============================================
1. In Visual Studio, go to the aspx page where you want to include the
Google Map.
For example, if the aspx page is called test.aspx, then in the
Solution Explorer there is at least 3 code files:
test.aspx
- test.aspx.cs
- test.aspx.designer.cs
For this example, choose the test.aspx. In the main editor panel, look
at the grey bar below the panel and ensure it is "Design" and not
"Source".
2. Add HTML components
Open the Toolbox. Either by View -> Toolbox or go to the right panel
and select the Toolbox tab.
Then in the Toolbox, go to the HTML section of components. Do not
remain at the Standard section of components.
Drag and drop the following onto the page:
- Input(Button) - for activating / drawing the map
- Input(Hidden) - for lattitude information
- Input(Hidden) - for longitude information
- Input(Hidden) - for other information to be printed on the map
- Div - actual area where map is displayed.
Click on each one of the components, and name them in the "id" field
with these names:
butMap,
hidLatitude,
hidLongitude,
hidDetails,
map
3. Make HTML components into ASP.NET components.
From the GUI editor page, click on the "Source" tab to edit the html
source code.
Go to the HTML section where the above 5 components are defined and
add the following for each 5 components: runat="server".
The final HTML code for the 5 components should look like:
<code>
Map Display
<input id="butMap" runat="server" type="button" value="Draw
Map" onclick="drawGmap()" />
<input id="hidLatitude" runat="server" type="hidden" />&nbsp;
<input id="hidLongitude" runat="server" type="hidden" />
<input id="hidShopDetails" runat="server" type="hidden" />
<div id="map" runat="server" style="width: 400px; height:
400px" visible="true"> </div>
</code>
At this stage just make sure the attributes of id, type and runat are correct.
By adding the runat="server" to the HTML code, then compile the code
in Visual Studio, this would make the HTML elements recognizable by
ASP.Net.
To check this, go to the test.aspx.designer.cs file and check the
following lines exist after compilation with runat="server":
protected global::System.Web.UI.HtmlControls.HtmlInputButton butMap;
protected global::System.Web.UI.HtmlControls.HtmlInputHidden
hidLatitude;
protected global::System.Web.UI.HtmlControls.HtmlInputHidden
hidLongitude;
protected global::System.Web.UI.HtmlControls.HtmlInputHidden
hidShopDetails;
protected global::System.Web.UI.HtmlControls.HtmlGenericControl map;
4. Ensure that somewhere in the test.aspx.cs code file, the html input
fields on the front end are filled with values. For example:
hidDetails.Value = "some details";
hidLatitude.Value = "20.312";
hidLongitude.Value = "132.12";

5. In between the header and the body section of the html code:
<script type="text/javascript"
src="http://www.google.com/jsapi?key=ABQIAAAAXg-1e7LbaB0NNB4KY0h0-BQWFt-7OBZKMPMlsVYvuUdvLO58RBSi6mMmr-RK5Y90BBnpyvt7UFoIfA"></script>
<script type="text/javascript"> google.load("maps", "2.x"); </script>
<script type="text/javascript">
function drawGmap() {
var dLat = document.getElementById("hidLatitude").value;
var dLong = document.getElementById("hidLongitude").value;
var sAddress = document.getElementById("hidDetails").value;
var map = new google.maps.Map2(document.getElementById("map"));
map.setUIToDefault();
var point = new GLatLng(dLat, dLong);
map.addOverlay(new GMarker(point));
map.setCenter(new google.maps.LatLng(dLat, dLong), 15);
var shtml = "100 <b>He</b>llo";
map.openInfoWindowHtml(map.getCenter(), sAddress);
//map.openInfoWindow(map.getCenter(),
document.createTextNode(hidText.value));
}
</script>
<body onunload="GUnload()">
In addition, ensure that the button or some other component call the
function drawGmap(). For example, from the above HTML Button :
<input id="butMap" runat="server" type="button" value="Draw
Map" onclick="drawGmap()" />

ASP.Net inline Tags <%...%>
==============================
These are tags that may be used on the aspx / html page, that enable
interaction with server side functions. The tags and a brief
explanation is given below:
<% ... %>
Allows C# code to be run within the tags.
Example:
<code>
<% string s = "test"; %>
</code>

<%= ... %>
Extracts values from server side objects.
Example:
<code>
<%= DateTime.Now.ToShortDateString() %>
</code>

<%# .. %>
Mostly used for binding expressions like Eval or Bind
Example: usage in Gridview in the example below where the Eval is used
to extract the value in the DB under the "name" column or field, for
each row in the Gridview.
<code>
<asp:GridView ID="GridView1"
runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="lnkname" runat="server"
Text='<%#Eval("Name") %>'
PostBackUrl='<%#"~/Details.aspx?ID="+Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</code>
<%$ ... %>
This is also called ASP.Net Expression and is used to extract
AppSettings, ConnectionsStrings or Resources
Example: using as connection string in DB
<code>
<asp:SqlDataSource ID="party" runat="server" ConnectionString="<%$
ConnectionStrings:myString %>" SelectCommand="SELECT * FROM [table]"
/>
</code>
<%@ ... %>
Specifying ASP.Net directives at the top of the aspx page.
Example:
<code>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs"
Inherits="_parent" Title="Test Page" %>
</code>

<%-- ... --%>
Comments are embedded here. These comments can be seen on the aspx
page, but after compilation into html page, the client would not be
able to see these parts.
Example:
<code>
<%-- Here are some comments --%>
</code>

ASP.Net calling Javascript client side
========================================
This section shows how to call a Javascript function defined on the
aspx page, from the C# code-behind aspx.cs code.
1. The javascript is defined in the aspx page between the head and
body tags, like:
<code>
<script type="text/javascript">
function drawGmap() { ......}
</script>
</code>
2. In the aspx.cs page, to call the javascript function drawGmap(...),
<code>
if (!Page.ClientScript.IsStartupScriptRegistered("alert")) {
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"drawGmap();", true);
}
</code>
The name of the function is simply placed at the third position.

Wednesday, May 18, 2011

How To Fix Your PC

This article provides a few tips in the form of a checklist on what to do to fix a computer when it is not behaving right.

- Check if there is firewall, antivirus and other security software.
- Run 'msconfig'
- Run web based virus scan, eg http://www.kaspersky.com/virusscanner or http://housecall.trendmicro.com
- Use the following tools:
   EasyCleaner - various tools like registry cleaning, removing programs, etc.
   PC Wizard - full info on PC
   Undelete Plus - recover deleted files
   Hijack This
- Windows Vista repair
       - Start - type Performance Information and Tools - click Advanced Tools - Generate System Health Report



Here are some links to other tips on fixing the PC

Common PC Problems Solved: The Ultimate FAQ
http://www.pcworld.idg.com.au/article/print/165794/common_pc_problems_solved_ultimate_faq/

Got XP Annoyances? Try These Four Smart Fixes for Windows Woes
http://www.pcworld.idg.com.au/article/199736/got_xp_annoyances_try_these_four_smart_fixes_windows_woes/

How Do I Get Malware Off My PC Once and for All?
http://www.pcworld.idg.com.au/article/199721/how_do_get_malware_off_my_pc_once_all_/

What Is the Best Way to Unstick My Frozen PC?
http://www.pcworld.idg.com.au/article/199798/what_best_way_unstick_my_frozen_pc_/

Protect Against Software Installation Nightmares
http://www.pcworld.idg.com.au/article/199810/answer_line_protect_against_software_installation_nightmares/

Make Windows start up faster
http://www.pcworld.idg.com.au/article/173412/make_windows_start_up_faster/?fp=2&fpid=2

Microsoft Standalone System Sweeper Beta 
 a recovery tool that can help you start an infected PC and perform an offline scan to help identify and remove rootkits and other advanced malware. In addition, Microsoft Standalone System Sweeper Beta can be used if you cannot install or start an antivirus solution on your PC, or if the installed solution can’t detect or remove malware on your PC.


Tools to fix PC

The Bootable Maintenance Flash Drive ( PDF ) - provides a small suite of tools very useful for troubleshooting.



Sunday, May 08, 2011

Notes Windows


NotesWindows  - Notes on Windows
=============

This includes NotesWinXP which is now made obsolete.
The content here is related to any version of Windows and will be specifically denoted.


Contents
=========
Roaming Profile - Encryption
Useful Registry Keys
Stop accidentally moving files or folders
Windows Update does not work anymore
Windows CMD commands
Application Location
MS Windows XP backup
Change Location of My Pictures, My Documents
Change Location of Libraries in Windows 7
Password Revealed on Windows
Known Folders can be Hidden - Windows 7
Boot Manager - Windows XP, Windows 7
How to Repair a Corrupt Windows 7 Installation
Windows Recovery Console Operations
Windows 7 Administrator account


Roaming Profile - Encryption - WinXP
=============================
Problem: When roaming profile cannot be saved - the reason could be due to some files are being encrypted.

Solution: Find and remove the encrypted file. Use the tool "cipher" provided by WinXP.

    cipher /S:directoryName
... to check encryption status of all subdirectories

Ref:
Roaming decrypt
http://www.microsoft.com/technet/prodtechnol/winxppro/reskit/c18621675.mspx

Search windows "roaming profile" decrypt
http://au.alpha.yahoo.com/search/web?p=windows+%22roaming+profile%22+decrypt
search http://au.alpha.yahoo.com/search/web?p=windows+%22roaming+profile%22+decrypt


 

Useful Registry Keys
================================
Append Path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
System Path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
User path:   HKEY_CURRENT_USER\Environment
Reserved Drives Letters: HKEY_LOCAL_MACHINE\SYSTEM\MOUNTEDDevices

Stop accidentally moving files or folders  - WinXP
===========================================
It is very easy to accidentally move folders in Windows Explorer, simply by careless movement of the mouse and accidentally releasing buttons. This problem is also very easy to occur with trackpads on laptops. There is a way of preventing this accidental motion by making Windows pop up a dialog box to ask for confirmation.

"Do You Want To Move Or Copy Files From This Zone?"

To enable this feature,
1. Click Start -> Control Panel -> Internet Options.
2. Click “Security” tab, mark the zone “Local intranet”, and click the “Sites” button.
3. Un-tick “Automatically detect intranet network”
4. Tick “Include all local (intranet) sites not listed in other zones”
   Tick “Include all sites that bypass the proxy server”
   Untick “Include all network paths (UNCs)”  

Windows Update does not work anymore  - WinXP
=====================================
For some reason, Windows files may corrupt such that the Windows Update will not work anymore. To solve this:
1. Open a Command Prompt Terminal: Start - Run, type: cmd.
2. To stop the current windows update service, in the Command Prompt, type:
    net stop wuauserv
3. Re-register the windows update dll for WinXP 32bit
    regsvr32 %windir%\system32\wups2.dll
Re-register the windows update dll for WinXP 64bit
    regsvr32 %windir%\syswow64\wups2.dll


Windows CMD commands
=====================
Ref: http://ss64.com/nt/

When in a CMD terminal, to launch another CMD terminal and execute a script (test.bat)
- start cmd /k test.bat    - new window remains open
- start cmd /c test.bat    - closes the new window when script finishes

Some commands related to Volume Shadow Copy Service (Vista)
vssadmin List Shadows
vssadmin List ShadowStorage


Application Location
=====================
WinXP:
Netscape Bookmarks (Netscape v 8.1)
D:\Program Files\Netscape\Netscape Browser\defaults\profile\bookmarks.html


MS Windows XP backup
======================
Below describes the process to take when backing up Windows. Some folder directory sizes given here may give an indication of their relative or typical sizes, but they will obviously vary in different systems.

- Login as each user and i) Empty Recycle Bin, ii) Clear all Cache, Cookies
- Login in as Administrator (so that can backup Registry and other System State)
- Goto Control Panel - Performance and Maintenance - "Free up space in your hard disk"
- c:\windows\system32 = 1GB
- c:\windows\ folders except system32 = 790MB
- c:\windows\system32\dllcache = 467MB
- c:\windows\$NTUninstall* = 245MB
- c:\windows\Driver Cache = 87MB
- c:\windows\fonts = 89MB
- c:\windows\help = 46MB
- c:\windows\ime = 86MB
- To backup Registry - go to the GUI windows Backup Utility and check the "System State"
- Do Normal and then Incremental backup.


Change Location of My Documents
=================================
WinXP:
Change My Documents.
- Right click My Documents - Properties - change the Target Location
- by default My Documents is in C:\Documents and Settings\<user>\My Documents

My Pictures, My Music.
- It appears that these folders are not changeable and are set under My Documents.
- When My Documents location is changed, then these folders should follow too.


Change Location of Libraries in Windows 7
===========================================
Libraries in Windows 7 can be assigned to various locations. Libraries will source the physial location of target directories and present the contents as if they all belong to the library. To change the location of Libraries in Windows 7:
- open Explorer
- in the left hand pane, right click on the library icons
- select Properties
- a list of location is presented, which can then be modified


Password Revealed on Windows
==============================
Windows 7:
- Passwords apparently can be revealed by System Information for Windows.
- the System Information (Start - All Programs - Accessories - System Tools - System Information) on Windows XP do not seem to reveal passwords.
- to remove the passwords in Windows 7, do:
    Control Panel - User Accounts and Family Safety - Windows Credential Manager.



Known Folders can be Hidden - Windows 7
==========================================
Windows default folders like Music, Pictures, Videos, Searches are part of the operating system and is not easy to remove. They may be hidden in a number of different ways.
1. Move them to another location by:
- Right click and select properties of the Known Folder
- Go to Location tab
- use the button Move to specify new location.
2. Merge them into Documents folder.
- Select the Known Folder to move.
- For the target to move to, select Documents.
3. Remove Known Folders
- Go to Start button and type, GPEDIT.MSC
- Under User Configuration, click Administrative Templates, double click Windows Components, then Windows Explorer.
- In the Disable Known Folders setting, double click and select Enabled.
- Click Show and enter names of any folders to be disabled.
- Go back to main Windows Explorer and delete any of the Known Folders, and it will be permanenet.

For a list of Known Folders, http://msdn.microsoft.com/en-us/library/bb882665.aspx


Boot Manager - Windows XP, Windows 7
======================================
Boot Loader for Windows XP: NTLDR
Sits on the Primary Partition of the Hard Disk
Configuration file: boot.ini
To edit, use Notepad

Boot Loader for Windows 7 / Vista : Windows Boot Manager (BOOTMGR)
Sits on the Primary Partition of the Hard Disk
Configuration file: BCD (Boot Configuration Data)
To edit, use BCDEDIT


How to Repair a Corrupt Windows 7 Installation
================================================
http://www.computerworld.com/s/article/9221540/How_to_Repair_a_Corrupt_Windows_7_Installation?taxonomyId=89&pageNumber=3


Windows Recovery Console Operations
====================================
Firstly to enter into recovery console, by booting from Windows CD/DVD. When 'Welcome to Setup' appears, then press 'R'. Here is a list of commands that may be helpful for repairing or trouble shooting in Recovery Console mode.

listsvc        - list the services running. Example display drivers agp440.sys is listed
disable agp440 - to disable a service that is running and listed under listsvc.


Windows 7 Administrator account
==================================
This section is specifically for Windows 7. In previous versions of Windows, there may appear the Administrator user on the login page. The Administrator account does not appear on Windows 7 by default.

By default, the Windows 7 installation usually
- allow you to create a new user, say FirstUser, during install and will set it up with Administrator password.
- there is a hidden Administrator user, but it is not active and has no password.

To manage the Administrator account, eg to activate it or give it a password, etc:
- click Start
- right click Computer - Manage
- Go to System Tools - Local User and Groups - User
- perform any task including Administrator account.

Alternative way to make Administrator appear on login screen.
- click Start and in the Search box, type CMD
- right click on the CMD icon that appears, choose Run As Administrator
- in the Command Prompt type:
  net user administrator /active:yes
      or
  net user administrator /active:no