Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Saturday, December 29, 2007

Web User Control shortcut

I just discovered a Web User Control shortcut for using your controls in apsx pages.
As per the reference link's example, add your implementation of this example:


<add tagPrefix="scottgu" src="~/Controls/Footer.ascx" tagName="footer"/>
<add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
All in the Web.config file in the elements.

Then you can reference it in aspx as

Reference: Link

Thursday, December 20, 2007

Microsoft Visual Web, CSS, and Images link bug

Here's a clue to avoid a bug with Microsoft Visual Web, CSS, and Images. I used the CSS style tool to add an image to an element, but the image would not show. The cause was a faulty link to the image.

Here is an example. I edit my StyleSheet.css in the css folder. I add an image from the brother folder named images. The link will say images/mypic.gif, but it is actually ../images/mypic.gif. Problem solved.

Friday, December 14, 2007

C# string is null or empty

Here's another shortcut method to make sure the string is not null and not empty. What I find interesting is that using myString.length>0 is supposedly more efficient than myString != string.empty.

if (!String.IsNullOrEmpty(myString))
{
myString = "myString != null && myString != string.Empty";
}

C# string extract tag method

This extracts a tagged string. For example, string findTagValue = extractTag ("Foo", "", ""); This would fetch Foo.

private string extractTag(string original, string beginTag, string endTag)
{
string retVal = string.Empty;
int begin = original.IndexOf(beginTag);
int end = -1;
if (begin > 0)
{
end = original.IndexOf(endTag, begin);
}
if ((begin > 0))
{
if ((end > begin))
{
retVal = original.Substring((begin+beginTag.Length), (end - begin-endTag.Length));
}
}
return retVal;
}

Thursday, December 13, 2007

Handy C# tricks

Here are some handy C# tricks to increase productivity.
First, the code:

        //

        // Summary:

        //     Gets or sets a value that indicates whether the System.Web.UI.WebControls.MenuItem

        //     object is enabled, allowing the item to display a pop-out image and any child

        //     menu items.

        //

        // Returns:

        //     true if the menu item is enabled; otherwise, false.

        [Browsable(true)]

        [DefaultValue(true)]

        public bool Enabled { get; set; }

  • The [Browsable(true)] allows the properties window to display the property or event.
  • Default value does as you would expect if the variable is not directly set
  • Short cut get and sets! Simple.

Thursday, December 6, 2007

C# ASP.NET using JavaScript

For ASP.NET, use the ClientScriptManager to register client scripts.

For example, in the Page_Load code behind I'll use:


ClientScript.RegisterClientScriptBlock(typeof(string), "MyScriptShow", "<script language=javascript>function showIt() { alert('showed it'); }</script>");

If the javascript was in a js file register it in the code behind with:

ClientScript.RegisterClientScriptBlock(typeof(string), "myScripts", "<script language='javascript' src='scripts/myScripts.js'></script>");

In the ASPX page I'll use;

<asp:Button ID="Button1" runat="server" OnClientClick="showIt()" Text="Button" />
Resource links: link, link

Note: Use the ClientScript.RegisterClientScriptBlock or ClientScript.Register_x methods (since Page.Register_x methods are version 1.1)

Setting the path environmental variable in XP and Vista

Setting the path environmental variable in XP and Vista.

It is often convenient to set the path environmental variable to call commands. For example, the "javac MyClass.java" command would use the javac command located in the path to compile the MyClass.java file to an executable. Here is how to set it up:


For Windows XP:
Start-> Control Panel -> System -> Advance Tab -> Environmental Variables.
Select Path -> Edit.
Append ";myPath" to environment variable, where myPath is the directory that contains your resources..
OK

For Windows Vista:
Start -> Control Panel -> System and Maintenance -> System -> Advanced system settings
click Continue
Select Environmental Variables
Select Path -> Edit.
Append ";myPath" to environment variable, where myPath is the directory that contains your resources..
OK

Using Google Web Toolkit gwt on Windows

Here's a quick start to using Google's Web Toolkit or gwt.

1. Download latest gwt release at link.
2. Unzip gwt_x to target directory. I used C:/Program Files/Google.

Now to create Eclipse projects do the following:
1. Append to the path environmental variable the target directory such as ";C:/Program Files/Google/gwt_x" , where gwt_x is the gwt version installed.

To create an Eclipse project called "MyProject":
1. use the command prompt and navigate (cd) to the Eclipse workspace. Mine was "C:\work\workspace\".
2. Create a folder via "mkdir MyProject".
3. "cd MyProject"
4. Create project via "projectCreator -eclipse MyProject"
5. Create application via "applicationCreator -eclipse MyProject com.mycompany.client.MyApplication"

To open the Eclipse Project:
1. In Eclipse: File->Import->General->Existing Projects into workspace
2. Select the MyProject directory that you originally created.

Other References:
link, link

Tuesday, December 4, 2007

Creating a Web User Control

Creating a Custom Web Control.
Within Visual Studio:
To keep organized, I create a company/website/user folder. Within the folder I create another folder named Controls. For example I'll have this directory structure: FooInc/Controls.

Within that folder, rt. click and Add New Item. Select the WebUserControl option. I'll name this one WebUserControl_DatePanel.ascx.

Switch to design view. Add a Panel (named Panel1 by default). Add a Label (named Label1 by default) within Panel1. Set Panel1's background to cyan for a custom feel.

In the load Event of WebUserControl_DatePanel.ascx, add the following:
Label1.Text = DateTime.Now.ToString();

Now save and close those files.

In your project, create a new Web Form named WebUser.aspx. Switch to design view.

From the Solution Explorer, drag the WebUserControl_DatePanel.ascx onto the page (much like adding a CSS file). Switch to Source View.

You will notice the following header:

<%@ Register Src="FooInc/Controls/WebUserControl_DatePanel.ascx" TagName="WebUserControl_DatePanel"
TagPrefix="uc1" %>
You will also notice the following web user control in the body:

<uc1:WebUserControl_DatePanel ID="WebUserControl_DatePanel1" runat="server" />

There it is. You can add custom functions at the web user control source if you want additional functionality.

Thursday, November 29, 2007

How to implement Ajaxified details view hide on PageIndexChanging

Previously I showed how to enable DetailsView with a Select button (link). But here is how to get rid of the DetailsView if Paging is enabled by using the PageIndexChanging method.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// get rid of the details view
DetailsView1.DataSource = null;
DetailsView1.DataBind();

GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
To Ajaxify it within an update panel, add a Trigger for the Gridview1 object and the PageIndexChanging event.

Generate Random numbers

Here's a quick one on how to generate random numbers. link

Random rnd = new Random();
int myRandom = rnd.Next();

Implementing Dynamic Hyperlink of Current Page

Here's how to implement a dynamic HyperLink of the current page based on the current pages title and current URL without the query string parameters. This is located in the Master Page.


protected void Page_Load(object sender, EventArgs e)
{
hlPageTitle.Text = Page.Title.ToString();
// old way would fetch query string paramaters
//hlPageTitle.NavigateUrl = Request.Url.AbsoluteUri.ToString();
hlPageTitle.NavigateUrl = Request.Url.GetLeftPart(UriPartial.Path);
}
Reference link.

Monday, November 26, 2007

Fixing WebForms.PageRequestManagerServerErrorException Status code 500

Here's a fix for the error WebForms.PageRequestManagerServerErrorException Status code 500.
I modified the MasterPage's ScriptManager as follows:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="false">
</asp:ScriptManager>


UPDATE: This might fix the error, but it limits the functionality by not allowing Partial Page Rendering. This may not be acceptable. Here is a hint to avoid breaking the AJAX:

Hint: Be careful when changing Control names. The IDE won't catch the name change in the Extenders section of the TargetControlID.

Sunday, November 25, 2007

How to implement Select on a GridView1 with Paging enabled.

How to implement Select on a GridView1 with Paging enabled based on a DataTable.

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
// e.NewSelectedIndex -> 0 to n
// GridView1.PageCount -> (n-1) always
// GridView1.PageIndex -> 0 to Page#
int rowN = 1 + ((GridView1.PageCount-1) * GridView1.PageIndex + e.NewSelectedIndex);
DetailsView1.HeaderText = "Details View of Row "+ rowN.ToString();
DetailsView1.PageIndex = rowN - 1;
GridView1.SelectedIndex = rowN - 1;
DetailsView1.DataSource = Cache["dt"];
DetailsView1.DataBind();
}

How to enable paging on a GridView that is bound to a DataTable.

How to enable paging on a GridView that is bound to a DataTable. On the GridView, simply

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = Cache["dt"];
GridView1.DataBind();
}


link

Saturday, November 17, 2007

Using Yahoo Mail Web Service hints

This should help you use Yahoo Mail Web Service for C# .NET.
First, go to link and download code sample for C#.
Second, use the APIs at link. I prefer the html link.
Third, get an application id at link. Be sure that this is the destination page where you will acquire the credentials using Request.QueryString[xTag].
Fourth, the above doesn't really explain a detail that will let the Web Service actually return Messages. Make sure that the xTagIsSpecified boolean is set before the request!
NOTE: The code sample below only works with premium accounts. Accounts link.


// <ListMessages>
// ListMessages, lists the messages in a given folder.
ListMessages listRequest = new ListMessages();
listRequest.fid = "Inbox";
listRequest.startMid = 0;
listRequest.startInfo = 0;
listRequest.numMid = 10;
listRequest.numInfo = 1;
listRequest.startMidSpecified = true;
listRequest.startInfoSpecified = true;
listRequest.numMidSpecified = true;
listRequest.numInfoSpecified = true;
ListMessagesResponse listResponse = ymwsInstance.ListMessages(listRequest);
retVal += string.Format("<br />Listed folder <b>{0}</b>, found <b>{1}</b> message IDs.<br />",
listResponse.folder.folderInfo.name, listResponse.mid.Length);
string[] listedMed = ymwsInstance.ListMessages(listRequest).mid;
// </ListMessages>

Wednesday, November 14, 2007

Well documented C# code sample

Well documented C# code sample demonstrates region, summary, and parameter documentation.


#region well documented sample method sample
/// <summary>
/// Saves the form size when it is resized.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SampleBrowser_SizeChanged(object sender, EventArgs e)
{
Properties.Settings.Default.FormClientSize = this.ClientSize;
}

/// <summary>
/// Saves all settings when form is closed.
/// </summary>
#endregion

Note: In addition to "param", one can use:

/// <returns>State of log in</returns>

Also: The #endregion must be on a new line!

Tuesday, November 13, 2007

Caching Methods in ASP.NET 2.0

How To Cache



























Method Implementation Sample uses

Programatic Caching


Set:


Cache.Insert("UniqueKey", myData,
null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);



Get:

Cache["UniqueKey"].ToString();


Session State Caching


Set:


Session.Add("UniqueKey", myData);





Get:


Session["UniqueKey"];


Caching to Disk

Application Cache Block


Caching to Database

CodeProject
Article


link

Monday, November 12, 2007

Modifying labels in MasterPage From MasterPage user Page

First, here is how to modify a label in the MasterPage from the MasterPage user Page:


Label mpLabel = (Label)Master.FindControl("lblPageTitle");
if (mpLabel != null)
{
mpLabel.Text = this.Title.ToString();
}

link

Monday, November 5, 2007

Setup an email form for .NET 2.0

Here is how I setup the email action for .NET 2.0. I included "using System.Net.Mail;" and "using System.Net;"


string sTo = "foo@foo.com";
string sFrom = txtFrom.Text.Trim();
string sSubject = "inforequest message" + DateTime.Now.ToLongDateString();
string sBody = txtContent.Text.Trim();
lblStatus.Text = "Sending... please wait";
MailMessage msg = new MailMessage(sFrom, sTo, sSubject, sBody);
msg.IsBodyHtml = false;
SmtpClient mailObj = new SmtpClient("mail.foo.com");
mailObj.Credentials = new NetworkCredential("user", "secret");
mailObj.Send(msg);
lblStatus.Text = "Sent " + msg.Subject + " to " + msg.To;

references: link
Note: I used "localHost" instead of "mail.foo.com".

Thursday, October 25, 2007

Adding a Checkbox Column to a GridView and checking if it is checked.

In my project I bind a DataTable to a Gridview. I have two fields in my DataTable: (bool) isChecked and (string) Value. Below I bind the data to those fields in the first two columns. The last Column I used a TemplateField and ItemTemplate to create a CheckBox row that is editable.



<asp:GridView ID="GridView1" runat="server"
OnDataBound="GridView1_DataBound"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
AutoGenerateColumns="False" >
<Columns>
<asp:CheckBoxField DataField="isChecked" HeaderText="Select" />
<asp:BoundField DataField="Value" HeaderText="Value" />
<asp:TemplateField HeaderText="Custom Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


Once the user edits the Custom Select checkboxes and pushes the button (btnSumbit), I read which fields are checked. If checked, I read from a Hashtable the value associated with the key.


protected void btnSubmit_Click(object sender, EventArgs e)
{
string sQueryString = "http://foo?";
// load hashtable with key values
Hashtable vhtTags = (Hashtable)Cache["htTags"];
bool isChecked;
// parse through to see what values are selected in gridview
foreach (GridViewRow vRow in GridView1.Rows)
{
isChecked = ((CheckBox)vRow.FindControl("chkSelect")).Checked;
if (isChecked)
{
string skey = vRow.Cells[1].Text.Trim();
sQueryString += vhtTags[skey].ToString();
}
}
lblResult.Text = sQueryString;
}
}

Notes: Since the first check column is only for demonstration and the last column is not bound because the default values are false. For the sake of brevity, error checking is left out.
Reference: link

Wednesday, October 24, 2007

Reversing the Keys and Values in a Hashtable

Here's how to reverse the Keys and Values in a Hashtable. I use the results and overwrite the original ht.Adds.
The results are output into the TextBox txtReversed.Text


protected void btnReverseHash_Click(object sender, EventArgs e)
{
Hashtable ht = new Hashtable();
ht.Add("a1", "Ask");
ht.Add("a2", "Ask what your country can do for you");
ht.Add("a3", "Ask what you can do for your country");
IDictionaryEnumerator _enum = ht.GetEnumerator();
string sOut = "";
const string _FRONT = "ht.Add(";
const string _END = ");\n";
const string _Q = "\"";
const string _CS = ", ";
while (_enum.MoveNext())
{
sOut += _FRONT + _Q + _enum.Value.ToString() + _Q + _CS
+ _Q + _enum.Key.ToString() + _Q + _END;
}
txtReversed.Text = sOut;
}

Wednesday, October 17, 2007

Sorting a GridView that is detached from database and put in a cache

First, the GridView needs to have sorting enabled and a sorting method:


<asp:GridView ID="GridView2" runat="server"
OnSorting="GridView2_Sorting" AllowSorting="True">
</asp:GridView>

Next, the page load and sorting method need to be implemented. I loaded my data from another GridView at the load. There is a Label that is also used. This code is similar to this reference link.


protected void Page_Load(object sender, EventArgs e)
{
DataView myDataView;

// Retrieve the DataView object from Cache. If not exist, then add DataView object to the Cache.

myDataView = (DataView)Cache["MyDataSet"];

if (myDataView == null)
{
myDataView = getTable().DefaultView;
Cache["MyDataSet"] = myDataView;
myDataView.Sort = myDataView.Table.Columns[0].ToString() + " ASC";
lblCacheMsg.Text = "Dataset created explicitly";
}
else
{
lblCacheMsg.Text = "Dataset retrieved from cache";
}
GridView2.DataSource = myDataView;
GridView2.DataBind();
}

// Verbose sort version
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataView Source = (DataView)Cache["MyDataSet"];
string direction = " DESC";
string curDirecton = Source.Sort.ToString().ToUpper();
if (curDirecton.Contains(direction))
{
direction = ASC;
}
else
{
direction = DESC;
}
Source.Sort = e.SortExpression + " " + direction;
Cache["MyDataSet"] = Source;
GridView2.DataSource = Source;
GridView2.DataBind();
lblE.Text = direction;
}
private DataTable getTable()
{
DataTable retVal;
DataTableHelper dth = new DataTableHelper(GridView1);
retVal = dth.getDataTable();
return retVal;
}

Monday, October 8, 2007

Modifying display of your GridView with CSS

If you manage multiple GridViews that you want to have the same format, use CSS classes. In the Styles section of the GridView properties there are:
  • AlternatingRowStyle
  • EditRowStyle
  • EmptyDataRowStyle
  • FooterStyle
  • HeaderStyle
  • PagerStyle
  • RowStyle
  • SelectedRowStyle
In this example I'll create classes in my CSS file as such:


.tableAnalysisRow {
border-right:#000 thin solid;
border-bottom:#000 thin solid;
background:#fff;
color:#000;
border-top:#000 thin solid;
border-left:#000 thin solid;
padding:2px 2px 3px 4px;
}
.tableAnalysisAlternatingRow {
border-right:#000 thin solid;
border-bottom:#000 thin solid;
background:#DCDCDC;
color:#000;
border-top:#000 thin solid;
border-left:#000 thin solid;
padding:2px 2px 3px 4px;
}
.tableAnalysisHeader {
border-right:#000 thick solid;
border-bottom:#000 thick solid;
background:#DCDCDC;
color:#000;
border-top:#000 thick solid;
border-left:#000 thick solid;
font-weight:700;
border-collapse:separate;
border-color:#000;
padding: 2px 2px 3px 4px;
}

Now just modify the Class property in the appropriate Gridview Style property like the following:


<asp:GridView ID="GridView1" runat="server" >
<RowStyle CssClass="tableAnalysisRow" />
<HeaderStyle CssClass="tableAnalysisHeader" />
<AlternatingRowStyle CssClass="tableAnalysisAlternatingRow" />
</asp:GridView>

The result GridView is here.

Saturday, October 6, 2007

Swapping GridView DataSourceID from DataSource

Here's the simple code for swapping the GridView back to DataSourceID from DataSource:


protected void DropDownListListsInUser_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewStocksInList.DataSource = null;
GridViewStocksInList.DataSourceID = SqlDataSourceGetStocksInList.ID;
GridViewStocksInList.DataBind();
}

The solution came from here.
It suggested studying this.

Friday, October 5, 2007

Help user redirect to secure target page after login and avoid extra navigation

Here's a solution for when the user needs to log in before accessing a secure page. This allows the user to avoid going through the menu system to go to the original page desired. I avoid some kind of error by using the false parameter in the redirect. The querystring of note is ReturnUrl.


protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated == false)
{
Response.Redirect("Login.aspx?ReturnUrl=DesiredPage.aspx", false);
}
else
{
MembershipUser user = Membership.GetUser().ProviderUserKey.ToString();
}
}

RedirectFromLoginPage Method

Thursday, October 4, 2007

Using a GridView to make calculations and avoid Database changes by merging DataTables and using PrimaryKey.

Merging DataTables named dt and dt2.

Before I show the diffences, here are the contents of dt (Figure 1) and dt2 (Figure 2):

Symbol Name Exchange
FRE Freddie Mac NYSE
FRE/PB Freddie Mac NYSE
FRE/PF Freddie Mac NYSE
FRE/PG Freddie Mac NYSE
FRE/PH Freddie Mac NYSE
Figure 1. dt

Symbol EPS Growth Lower Price Target Lower % Target Upper Price Target Upper % Target
FRE FRE FRE FRE FRE FRE
FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB
FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF
FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG
FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH
Figure 2. dt2

In my project I want to use a GridView and append calculated data without changing the database.
My solution is to read the GridView into a DataTable, dt. Then, I make calculations from a PrimaryKey of dt and use the same PrimaryKey for dt2 while adding actual calculations (EPS Growth, Lower Price Target, ... in production version). The final step is to Merge the datatables with dt.Merge(dt2). The result is shown in Figure 3.

Symbol Name Exchange EPS Growth Lower Price Target Lower % Target Upper Price Target Upper % Target
FRE Freddie Mac NYSE FRE FRE FRE FRE FRE
FRE/PB Freddie Mac NYSE FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB
FRE/PF Freddie Mac NYSE FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF
FRE/PG Freddie Mac NYSE FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG
FRE/PH Freddie Mac NYSE FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH
Figure 3.

If you simply Merge with dt.Merge(dt2), you would get the same result as long as the PrimaryKey is set in dt. However, without setting the PrimaryKey you get the result in Figure 4.

Symbol Name Exchange EPS Growth Lower Price Target Lower % Target Upper Price Target Upper % Target
FRE Freddie Mac NYSE
FRE/PB Freddie Mac NYSE
FRE/PF Freddie Mac NYSE
FRE/PG Freddie Mac NYSE
FRE/PH Freddie Mac NYSE
FRE FRE FRE FRE FRE FRE
FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB
FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF
FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG
FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH
Figure 4.

In my implementation I use:
dt.Merge(dt2, false, MissingSchemaAction.Ignore);
This will avoid preserving changes and ignore taking action when there is a missing schema.

Wednesday, October 3, 2007

Loading a GridView into a DataTable and then back to another GridView

First, Loading a GridView into a DataTable, dt:


private void initDataTable()
{

int i = 0;
int j = 0;
int totRow = GridView1.Rows.Count;
int totCol = GridView1.Rows[0].Cells.Count;
// Set the table headers
string[] arrHeaders = {"Symbol","Name","Exchange" };
// Get the table headers
for (j = 0; j < totCol; j++)
{
// The commented line would work if the Gridview had Column HeaderText
//dt.Columns.Add(new DataColumn(GridView1.Columns[col].HeaderText, typeof(string)));

// Instead I use the Headers array, arrHeaders
dt.Columns.Add(new DataColumn(arrHeaders[j].ToString(), typeof(string)));
}
DataRow dr;
for (i = 0; i < totRow; i++)
{
dr = this.dt.NewRow();
for (j = 0; j < totCol; j++)
{
dr[j] = GridView1.Rows[i].Cells[j].Text;
}
this.dt.Rows.Add(dr);
}
}

Then back to another GridView:


private void fillGridView2()
{
if (dt.Rows.Count > 0)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
else
{
dt.Rows.Add(dt.NewRow());
GridView2.DataSource = dt;
GridView2.DataBind();

int TotalColumns = GridView2.Rows[0].Cells.Count;
GridView2.Rows[0].Cells.Clear();
GridView2.Rows[0].Cells.Add(new TableCell());
GridView2.Rows[0].Cells[0].ColumnSpan = TotalColumns;
GridView2.Rows[0].Cells[0].Text = "No Record Found";
}
}

The no record found code was from this link.

Thursday, September 27, 2007

Connecting to Kensoft.net SQL Server 2005 database

The side note for this is that the database name in Kensoft has an '_' in it, not a '.'.


<connectionStrings>
<!--<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True; User Instance=True" providerName="System.Data.SqlClient"/>
-->
<add name="ConnectionString" connectionString="Data Source=mssql2005.kensoft.net;Database=myDatabase;uid=myUserId;pwd=myPassword" providerName="System.Data.SqlClient" />
</connectionStrings>

Copying a MDF SQLExpress Database file to SQL Server 2005 Server

Copying a MDF SQLExpress Database objects to SQL Server 2005:



  1. First make sure myDatabase.mdf is on your local machine unless you already
    have remote access enabled.


  2. Open Microsoft SQL Server Management Studio Express. Hint: Run as Administrator on Vista.


  3. Make sure myDatabase is listed as a Database in the Object Explorer,
    otherwise attach it.


  4. Right click myDatabase -> Tasks -> Generate Scripts -> [select]
    myDatabase -> Select All ... ->Script to new Query Window -> Finish


Next



  1. In the Object Explorer open the remote database where you want the copied
    tables and views.


  2. Right click myTargetDatabase ->Tasks -> New Query


  3. Paste in copied script from step 4 from above.


  4. Run



link to download Microsoft SQL Server Management Studio Express
Note: Be careful with constraint options. I also had to copy and paste the data from the source to target data tables in Microsoft SQL Server Management Studio Express like an Excel copy and paste.

Tuesday, September 25, 2007

Building an AJAX Slide Show in ASP.net

This was almost simple, but then the image paths made plug and chug necessary until the path problem was resolved. The key is to use image paths in the web service without ~/ and without /. Instead just type the directory name and the file name.



using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// <summary>
/// Summary description for WebServiceSlideShow
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class WebServiceSlideShow : System.Web.Services.WebService {

public WebServiceSlideShow () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public AjaxControlToolkit.Slide[] GetSlides() {
AjaxControlToolkit.Slide[] slides;
System.Collections.ArrayList alSlideUrls = new ArrayList();
alSlideUrls.Add("_imgLibrary/photo1.jpg");
alSlideUrls.Add("_imgLibrary/photo2.jpg");
alSlideUrls.Add("_imgLibrary/photo3.jpg");
slides = new AjaxControlToolkit.Slide[alSlideUrls.Count];
int i = 0;
foreach (string str in alSlideUrls)
{
slides[i] = new AjaxControlToolkit.Slide(str, str, str);
i++;
}
return slides;
}
}

Here is the ASPX code:


<div style="text-align: center">
<table style="vertical-align: text-top">
<tr>
<td style="width: 278px" nowrap="noWrap" align="center">
<asp:Image ID="ImagePlayer" runat="server" />
</td>
</tr>
<tr>
<td nowrap="nowrap" style="width: 278px" align="center">
<asp:Button ID="btnBack" runat="server" Text="Back" />
<asp:Button ID="btnPlay" runat="server" Text="Play" />
<asp:Button ID="btnNext" runat="server" Text="Next" />&nbsp;
</td>
</tr>
</table>
</div>
<cc1:SlideShowExtender ID="SlideShowExtender1" runat="server" TargetControlID="ImagePlayer" AutoPlay="True" Loop="True" NextButtonID="btnNext" PlayButtonID="btnPlay" PlayButtonText="Play" PreviousButtonID="btnBack" SlideShowServiceMethod="GetSlides" SlideShowServicePath="WebServiceSlideShow.asmx" StopButtonText="Pause">
</cc1:SlideShowExtender>

Saturday, September 22, 2007

Proper ViewState use and the coalescing operator

Here is a quick lesson the ViewState object for viewing an object's state. I found the use of the coalescing operator helpful for future use instead of wordy if then else statments.
  • public int CompanyID

    {

    get { return (int)(ViewState["CompanyID"] ?? 0); }

    set { ViewState["CompanyID"] = value; }

    }
The coalescing operator is a brother of if-then-else and
the more succinct: if (isX ? doA() : elseDoB).
I would describe coalescing as shorthand for: if (isX!=null) then getX() else getB().

Monday, September 17, 2007

GridView table headers and iterating over a GridView cells in the row and columns.

Here is a function to get the GridView's table header columns:


protected string getTableHeaders()
{
string retVal = "";
int TotalColumns = GridView1.Columns.Count;
int col = 0;
for (col = 0; col < TotalColumns; col++)
{
retVal += GridView1.Columns[col].HeaderText;
if ((col + 1) < TotalColumns) retVal += ", ";
}
return retVal;
}


Here is how to iterate over the GridView cells to extract row and column data into a string. The cells can be custom delimited. Notice how this does not include Column.HeaderText :


protected string getDataCells()
{
string retVal = "";
int TotalColumns = GridView1.Columns.Count;
int TotalRows = GridView1.Rows.Count;
int col = 0;
int row = 0;
if (TotalColumns > 0 && TotalRows > 0)
{
for (row =0; row<TotalRows; row++)
{
for (col = 0; col < TotalColumns; col++)
{ // uses arbitrary ',' between column cells
retVal += GridView1.Rows[row].Cells[col].Text;
if ((col + 1) < TotalColumns) retVal += ", ";
}
// uses arbitrary ';' for end of row
retVal += ";";
}
}
return retVal;
}

Sunday, September 16, 2007

DataGridView cell contents and header contents




// How do I get the contents of a GridView cell?
GridView1.Rows[0].Cells[0].Text;
// Note: This will only get the result data and not the table headers a.k.a. column names.

// How do I get the contents of a GridView table header (<th>) a.k.a. column name?
GridView1.Columns[0].HeaderText;

Friday, September 14, 2007

HTML Table header accessibility standards

This fascinating piece of law regarding federal accessibility standards on HTML table headers requires data tables that contain two more rows or columns to identify row and column headers. The header fields that you create render as , and the columns reference the headers. . The bottom line: Use TH for table headers.

ILLEGAL:


<TABLE>
<TR><TD>Stock</TD><TD>Price</TD></TR>
<TR><TD>AAPL</TD><TD>133.33</TD></TR>
</TABLE>


LEGAL


<TABLE>
<TR><TH SCOPE="COL">Stock</TH> <TH SCOPE="COL">Price</TH></TR>
<TR><TD>AAPL</TD> <TD>133.33</TD></TR>
</TABLE>


Microsoft Article: from excerpt
To better understand the DataGrid's rendering machinery, it's useful to review how the DataGrid's implementation has changed after the hotfix discussed in Knowledge Base article 823030 ("FIX: DataGrid Made Compliant with Section 508 of the Rehabilitation Act Amendments of 1998"). In ASP.NET 1.1, the DataGrid's markup is not compliant with Section 508 of the Rehabilitation Act Amendments of 1998, a U.S. law regarding accessibility standards. To resolve this problem, Microsoft made a hotfix rollup package available, as explained in the aforementioned article. In short, the act states that data tables that contain two or more rows or columns must clearly identify row and column headers. This means that, at the very minimum, the header row(s) of an HTML table must define its cells through the TH tag instead of the ordinary TD tag.

C# switch statement for DropDownList to update Image url.

Simple control-flow statement to reference C# switch statement, which is similar to other language's case statement.


switch (DropDownList1.SelectedValue)
{
case "Image 1":
imgFoo.ImageUrl = "images/photo1.jpg";
break;
case "Image 2":
imgFoo.ImageUrl = "images/photo2.jpg";
break;
case "Image 3":
imgFoo.ImageUrl = "images/photo3.jpg";
break;
default:
imgFoo.ImageUrl = "images/photo_blank.jpg";
break;
}

Using XPath for reading attribute and content of XML

I used this type of XPath functionality for creating a rotating image based on an XML file.


<-- First the XML -->
<images>
<image href="img1">1</image>
<image href="img2">2</image>
</images>

<-- Next the XPath for C# -->
<-- get all image hrefs (and other attributes) -->
images//image

<-- get image value at image position 1 -->
images//image[position()=1]

<-- get href attribute at images/image position 1 -->
images//image[position()=1][@href]

Nested GridView with subtotals, totals, and counts

This complicated example shows a nested GridView with subtotals, totals, and counts. The actual process of modifying the GridView ItemTemplates is not explained here. Note: The SQL should be replaced with a stored procedure for production.
NestedGridView example


<script runat="server">
Decimal masterTotal = 0;
Decimal masterCount = 0;
Decimal priceTotal = 0;
int priceCount = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlDataSource s = (SqlDataSource)e.Row.FindControl("SqlDataSource2");
String str = e.Row.Cells[0].Text;
s.SelectParameters[0].DefaultValue = e.Row.Cells[0].Text;

}
}

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
// add the UnitPrice and QuantityTotal to the running total variables
priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "contribution_amount"));
priceCount++;
masterCount++;
}
else if ((e.Row.RowType == DataControlRowType.Footer) )
{
masterTotal += priceTotal;
if (priceCount > 1)
{
e.Row.Cells[0].Text = "Subtotal:";
// for the Footer, display the running totals
e.Row.Cells[2].Text = priceCount.ToString();
e.Row.Cells[3].Text = priceTotal.ToString("c");
e.Row.Cells[3].HorizontalAlign = e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
e.Row.Font.Bold = true;
{
GridView1.FooterRow.Cells[0].Text = "Total:";
// for the Footer, display the running totals
GridView1.FooterRow.Cells[1].Text = masterCount.ToString();
GridView1.FooterRow.Cells[1].Text += "&nbsp&nbsp&nbsp&nbsp" + masterTotal.ToString("c");
GridView1.FooterRow.Cells[1].HorizontalAlign = GridView1.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
GridView1.FooterRow.Font.Bold = true;
}
}
else if (priceCount == 1)
{// blank out borders and background color for 1 row footers

e.Row.Visible = false;
}
else
{
e.Row.Visible = false;
}
priceTotal = 0;
priceCount = 0;
}
}


</script>

Here is the html part of the aspx:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Campaign Finance Contributions By Date</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td align="center" nowrap="nowrap" style="width: 253px; height: 92px">
<asp:Image ID="TelWebImage" runat="server" ImageAlign="Middle" ImageUrl="~/tel-web.gif"
Style="z-index: 101; left: 7px; position: relative; top: 9px" /></td>
</tr>
<tr>
<td align="center" nowrap="nowrap" style="width: 253px; height: 42px">
<asp:Label ID="TitleLabel" runat="server" Font-Size="Larger" Style="z-index: 100;
left: 4px; position: relative; top: 0px"
Text="Campaign Finance Contributions"
Width="206px"></asp:Label></td>
</tr>
<tr>
<td align="center" nowrap="nowrap" style="width: 253px">
<asp:Label ID="ByDateLabel" runat="server" Style="z-index: 102; left: 16px; position: relative;
top: 0px"
Text="BY CONTRIBUTION DATE"></asp:Label></td>
</tr>
<tr>
<td align="center" nowrap="nowrap" style="width: 253px; height: 19px">
<asp:Label ID="DateTimeLab" runat="server" Style="left: 0px; position: relative;
top: 2px"
Text="Date and Time"></asp:Label></td>
</tr>
</table>
</div>
&nbsp;&nbsp;
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT contribution_date FROM ContributionCandidateview WHERE (contribution_number LIKE @contribution_number)">
<SelectParameters>
<asp:Parameter DefaultValue="%" Name="contribution_number" />
</SelectParameters>
</asp:SqlDataSource>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" ShowFooter="True">
<Columns>
<asp:BoundField DataField="contribution_date" HeaderText="contribution_date" SortExpression="contribution_date" />
<asp:TemplateField HeaderText="Contributions">
<ItemTemplate>
&nbsp;
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [candidate_name], [contribution_date], [contribution_name1], [contribution_amount] FROM [ContributionCandidateview] WHERE ([contribution_date] = @contribution_date)">
<SelectParameters>
<asp:Parameter Name="contribution_date" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView2" runat="server" DataSourceID="SqlDataSource2" OnRowDataBound="GridView2_RowDataBound" ShowFooter="True" Width="500px">
<AlternatingRowStyle BorderColor="White" BackColor="#E0E0E0" />
<FooterStyle BackColor="#DFFFDF" />
<HeaderStyle BackColor="#DFDFFF" />
</asp:GridView>
</ItemTemplate>
<ItemStyle VerticalAlign="Bottom" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#DFDFFF" />
</asp:GridView>
</form>
</body>
</html>

Modifying the contents of a GridView after DataBinding

This is more than bare functionality, but it can be simplified by eliminating the contents in foreach brackets.


protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow dgrow in GridView1.Rows)
{
String myString, myPattern;
Boolean result;
myPattern = txtSearch.Text;
myString = dgrow.Cells[0].Text;
result = true;

if (isEndsWith == true)
{
if (myPattern.Length > 0)
{
result = myString.EndsWith(myPattern);
dgrow.Cells[0].Text = myString.Substring(0, myString.LastIndexOf(myPattern))
+ HighlightText(myPattern, myString.Substring(myString.LastIndexOf(myPattern)));
}
else result = false;
if (result == false)
dgrow.Cells[0].Visible = false;
}
else
{
if (isStartsWith)
{
if (myPattern.Length > 0)
{
result = myString.StartsWith(myPattern);
dgrow.Cells[0].Text = HighlightText(myPattern, myString.Substring(0,myPattern.Length)) + myString.Substring(myPattern.Length, myString.Length-myPattern.Length);
dgrow.Cells[0].Visible = true;
}
}
else
{
dgrow.Cells[0].Text = HighlightText(myPattern, myString);
dgrow.Cells[0].Visible = true;
}
}
}
}

Highlight search text functions using css tags and regex



protected string HighlightText(string searchWord, string inputText)
{

Regex expression = new Regex(searchWord.Replace(" ", "|"));
// Regex.ignorecase

return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(Match m)
{
return "<span class='highlight'>" + m.Value + "</span>";
}

Thursday, September 13, 2007

C# to run stored procedure after parsing text



char[] sSeparators = { ',', ' ' };
string[] sStocks = txtStocks.Text.Split(sSeparators);
SqlConnection conn = new SqlConnection("AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;User Instance=True;Data Source=.\\SQLEXPRESS;Integrated Security=True;");
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("sproc_aspnet_CreateStockInList", conn);
command.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
foreach (string _stock in sStocks)
{
command.Parameters.AddWithValue("@ListId", txtListId.Text.Trim());
command.Parameters.AddWithValue("@Symbol", _stock.Trim());
command.ExecuteNonQuery();
command.Parameters.Clear();
}
conn.Close();

Blog Archive