Friday, November 7, 2008

ASP .NET Connection Strings in Web.config File

ASP .NET offers an elegant way to store data source connection creditentials. Connection strings should be stored in a .config file, commonly and by default the Web.config file.

Firstly, what are connection strings? Connection strings are strings of text that contain information about a data source used in the code for data access. Information contained in a connection string includes the data source name, data source address, security mode, login creditentials, and the data source type.

There are a couple reasons why the Web.config file is a good place to store connection. One, ASP .NET is automatically configured to never display a file with a .config extension. So you can assume a level of security when storing login information in the Web.config. In addition, ASP .NET can be configured to encrypt the Web.config file, which would add more security. Nonetheless, you can be assured that any web request to a .config file would result in an error. Secondly, using Web.config allows a central way to manage information without requiring digging into the code nor code modification.

Below are examples of how connection strings would be used:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <connectionStrings>
  <add name="connectionName" connectionString="Data Source=serverName;
  Initial Catalog=databaseName;User Id=username;Password=password;"
  providerName="System.Data.SqlClient"/>
</connectionStrings>
...
</configuration>



To retrieve the above connection string in C# code:

string connStr = ConfigurationManager.ConnectionStrings["connectionName"];



To use the connection string directly in an ASP .NET page:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:connectionName %>"
  SelectCommand="SELECT * FROM [Employees]" />

Thursday, November 6, 2008

Reading/Writing Data with ADO .NET in C#

In .NET coding there are two main methods of handling database data using ADO.NET. The two methods are distinguished by the classes used to access and manipulate the data. The classes are DataReader and DataSet. I will briefly go over each class and major differences between the two in addition to some examples.

DataReader


The DataReader is the core class for retrieving data from a database in ADO.NET. When using ADO.NET to read data from a database, a DataReader is always used although sometimes implicitly. Even in the case of using a DataSet, the DataAdapter that is used to populate the DataSet uses a DataReader internally.
Now a few things about the DataReader. A DataReader object can merely provide read-only access to a database and only in a forward direction. The DataReader is connection based, meaning the connection to database is maintained while data is read by the DataReader. The DataReader class is efficient and has a relatively small memory fingerprint. If no data writing is required, a DataReader is usually the best choice.

Example



using (SqlConnection conn = new SqlConnection(connectionString))
{
   SqlCommand command = new SqlCommand("SELECT * FROM Categories");
   command.Connection = conn;
   conn.Open();
   SqlDataReader dr = command.ExecuteReader();
}


DataSet


As we have seen above, the DataSet aproach also uses a DataReader. However, the difference is that the DataReader is used to read the data into a DataSet object which retains the data in memory. Once in memory, the data can be manipulated as the programmer wishes. After the data is modified inside the DataSet, it can be written back to a database.
The DataSet is a connectionless object. Once the data is read into the DataSet, the connection to the database is halted. Clearly, using a DataSet to hold records has a memory cost. While in memory, the data can be modified multiple times and when finalized written once to the database. If data memory retention or modification is needed, a DataSet is usually the solution.

Example



using (SqlConnection conn = new SqlConnection(connectionString))
{
   SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Categories",conn);
   DataSet ds = new DataSet();
   ad.Fill(ds);
}

Wednesday, September 10, 2008

TS 70-630: Microsoft Office SharePoint Server 2007, Application Development

Best way to prepare for this exam is by taking one of the available practice tests. One good one I have tried is the practice test from MeasureUP.com. One thing I like about the MeasureUP exams that cannot be done with Transcender is that you can review your answer as you go through the questions. You don’t have to wait until the exam is completed. Relative to the WSS 3.0 Application Development exam this exam is not hard to pass. From my experience, the one subject to focus on the most is the Business Data Catalog (BDC). You have to be familiar with BDC Application Definitions. Make sure you understand all the questions about the BDC.

Monday, July 14, 2008

Sharepoint Server and WSS Certificates

I have posted before general Sharepoint resources that are relevant to certain Microsoft certificates. However, in the next few posts I want to talk specifically about four Sharepoint exams that I passed not long ago and give some pointers.

Before I get into that, I want to mention what happened with the 2 beta exams I was supposed to take and then my testing center canceled. Essentially, I ended up getting 2 free exams from Prometric to make up for them. But since the day I was scheduled was the last day for the beta exams I couldn't register for them then. So I took a couple Sharepoint exams instead. Here it is.

In general, a very good resource for all four exams and especially the Windows Sharepoint Services (WSS) ones is the Inside Microsoft® Windows® SharePoint® Services 3.0 book from the Microsoft Press by Ted Pattison and Daniel Larson. If you have access to books24x7.com, an online version of it is available there. Today I am going to talk about the 70-630 exam.

Inside Microsoft® Windows® SharePoint® Services 3.0 book


TS 70-630: Microsoft Office SharePoint Server 2007, Configuring


The fastest way to learn the material for this exam is to take a practice test and study its answer explanations. The following test providers have practice tests for this exam, Transcender, MeasureUp, and Self Test Software.
The test should not have any development questions so focus on configuration, things you can do by moving and clicking the mouse around with very little typing. Here are more specific tips:
  • Familiarize yourself with the administrative console features.

  • Get familiar with the site and other settings pages.

  • Know how to do simple settings tasks like adding an item to a menu and changing the site logo.

  • Understand Groups and Audiences.

  • Know the basics of using the STSADM and Prescan tools.

  • Understand the different connection files, UDC and ODC.

  • Know what Restrictive Read is.

  • Know how to see the servers running in a web farm and what services they are running.

  • Understand Quiescing.

For more information visit the Microsoft page for the exam.

Please leave a comment and let me know what you think!

Monday, June 16, 2008

HTML/Div Layering over Flash and Transparent Background with Windowless Mode

To lay HTML elements such as a DIV over a Flash object, the Flash object must be embedded with windowless mode. Setting the mode to windowless also allows the web page to show an image or a background through the Flash object embedded on the page. The only drawback with using windowless mode is performance. Most of the time the difference in performance would not be noticeable. However, if performance was a top concern then alternate designs should be considered.

To set the mode to windowless or transparent, the "wmode" parameter should be set to "transparent" as follows. The way the mode is changed depends on the browser. On IE the OBJECT tag is used. On Firefox the EMBED tag is used instead. To accommodate for all browsers use SWFObject or put the EMBED tag inside the OBJECT tag right before "</OBJECT>".

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"
WIDTH="550" HEIGHT="400" id="objectId">
<PARAM NAME=movie VALUE="flashfile.swf">
<PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#FFFFFF>
<param name="wmode" value="transparent">
</OBJECT>


<EMBED src="/support/flash/ts/documents/myFlashMovie.swf"
quality=high bgcolor=#FFFFFF WIDTH="550" HEIGHT="400"
NAME="embedId" ALIGN="" TYPE="application/x-shockwave-flash"
PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"
wmode="transparent"></EMBED>


Using my favorite way of embedding flash, SWFObject:
<script type="text/javascript">
var so = new SWFObject("flashfile.swf", "objectId", "400", "100%", "8", "#336699");
so.addParam("quality", "high");
so.addParam("wmode", "transparent");
so.write("flashelement");
</script>

For more information there is a TechNote about this from Adobe.

Monday, June 2, 2008

Internet Explorer (IE) Conditional Comments

It's rather common that the same CSS styles are rendered differently among different browsers. Many times there is a difference between the way Netscape/Mozilla/Firefox browsers interpret CSS code and the way IE does. Opera seems to fall on either side depending on the property. Another problem that often arises is that different Javascript code must be written for different browsers.

Now with Javascript, unlike CSS, it's easy to check the type of browser and execute different code accordingly as I've explained before. However, it's sometimes more desirable to include different Javascript files depending on the browser especially when there is code that is specific to only IE. One viable solution for this is using the IE conditional comments.

Using IE conditional comments, one can include Javascript, CSS, and HTML that is only parsed if the user browser is IE or if it's not IE. If it is IE, you check even further and include the code if browser is a specific version of IE.

There are two types of conditional comments. One is called "downlevel-hidden," which is only parsed by IE because it uses special IE syntax. The second is called "downlevel-revealed," which is ignored by IE and parsed by everything else because it's not a standard HTML comment.

The downlevel-hidden syntax is as follows:
<!--[if IE]> Javascript/CSS/HTML <![endif]-->

As you can see the downlevel-hidden syntax uses standard "<!-- ... -->" HTML comment syntax.

Now the downlevel-revealed syntax is:
<![if !IE]> Javascript/CSS/HTML <![endif]>

Here we don't have the two dashes "--" after the "!" and before the ">".

The difference between downlevel-hidden and downlevel-revealed is that downlevel-hidden is parsed by IE when the condition is true and is never parsed by other browsers. Downlevel-revealed is always parsed by other browsers and is parsed by IE only when the condition is satisfied. So in both cases IE selectively executes but in downlevel-hidden other browsers never see the code and in downlevel-revealed they always parse it.

Here are some examples of what can be done with conditional comments from MSDN
<!--[if IE]><p>You are using Internet Explorer.</p><![endif]-->
<![if !IE]><p>You are not using Internet Explorer.</p><![endif]>

<!--[if IE 7]><p>Welcome to Internet Explorer 7!</p><![endif]-->
<!--[if !(IE 7)]><p>You are not using version 7.</p><![endif]-->

<!--[if gte IE 7]><p>You are using IE 7 or greater.</p><![endif]-->
<!--[if (IE 5)]><p>You are using IE 5 (any version).</p><![endif]-->
<!--[if (gte IE 5.5)&(lt IE 7)]><p>You are using IE 5.5 or IE 6.</p><![endif]-->
<!--[if lt IE 5.5]><p>Please upgrade your version of Internet Explorer.</p><![endif]-->

<!--[if true]>You are using an <em>uplevel</em> browser.<![endif]-->
<![if false]>You are using a <em>downlevel</em> browser.<![endif]>

<!--[if true]><![if IE 7]><p>This nested comment is displayed in IE 7.</p><![endif]><![endif]-->

Some of the CSS differences I've noticed is that the opacity property has no effect in IE but it works in Firefox and Opera. When word-wrap property with value of "break-word" is applied to hyperlinks (anchors) in Firefox, it does nothing but it works on IE and Opera.

Saturday, May 24, 2008

Don't Abuse Anchors -- Use CSS

Many web developers use anchors "<a...>" to suround texts and images simply to change the cursor. This usually involves setting the href property to "#" and possibly using the onclick event to execute some JavaScript code and then adding "return false;" at the end so that the page doesn't jump to top every time a user clicks the link.

This might have been the right way to do things at some point. However, after introducing the CSS element "cursor," there is no reason to use all that mess. Simply set the cursor property of the HTML element in question to "pointer" and add the onclick event code to the element itself if needed.

So for example:

.button {
cursor: pointer;
}


This makes code look so much cleaner and it would prevent the URL in the browser from changing to something with an "#" at the end. Moreover, it would also prevent the status of the window shown usually at the bottom of the browser from changing when hovering over the element.

Sunday, May 4, 2008

Creating and Customizing Document Information Panels Using MOSS 2007

Part 1:




Part 2:




This video does a good job of showing how Document Information Panels integrates with Office 2007 applications. Ted demonstrates creating custom content types and using Document Information Panels with InfoPath 2007 to add custom metadata to Office files.
The video is courtesy of Ted Pattison of www.tedpattison.net

ASP .NET 3.5 and ADO .NET 3.5 Beta Exams Canceled


I just got off the phone with the manager of the Prometric testing center I usually go to to cancel both of my beta exams scheduled for today. He said he had an emergency and has to close the center by 10am to go pick up some people from LAX airport. The people he's receiving were supposed to come on Monday but for some reason came a day early.

I don't really care but I am curious if I can actually reschedule them. He gave me a ticket number to use to reschedule and said that I would be able to reschedule them even though today was the last day to take them. I think he didn't know what he was talking about but it's worth trying. I am going to call tomorrow and see what happens. Anyway today was the last day to take the beta ASP .NET 3.5 70-562 and the ADO .NET 3.5 70-561 exams.

Saturday, April 12, 2008

Blackle - Make Google Black

Google recently dimmed its lights observing the Earth Hour. Whether using a black background conserves energy or not is debatable and depends on the type of monitor that is used. One attempt at saving energy by dimming the background on one of the most popular pages online is Blackle. Blackle was developed by Heap Media, a company based in Sydney, Australia and founded in 2005. Heap Media "is committed to developing and growing leading online services with global reach."

Search Google in Black
www.blackle.com

Wednesday, April 9, 2008

Microsoft Office Sharepoint Server Resources


I was looking online for Sharepoint information and training material and here are some excellent resources I found:


Free Sharepoint 2007 Server Courses by Microsoft
http://office.microsoft.com/en-us/training/CR102146081033.aspx
Some of these course are very basic and are meant for general users not developers. For example, some of them teach the user how to upload or save a file directly from Word/Excel/Powerpoint to a Sharepoint server.



Sharepoint desktop training download.
http://www.microsoft.com/downloads/details.aspx?FamilyId=7BB3A2A3-6A9F-49F4-84E8-FF3FB71046DF&displaylang=en



Sharepoint standalone and server training download
http://office.microsoft.com/en-us/sharepointserver/HA102488011033.aspx



Sharepoing server home page
http://office.microsoft.com/en-us/sharepointserver/default.aspx



Sharepoint 2007 Server help page
http://office.microsoft.com/en-us/sharepointserver/FX101211721033.aspx



Sharepoint Server 2007 Virtual PC Harddrive Image
http://www.microsoft.com/downloads/details.aspx?FamilyID=67f93dcb-ada8-4db5-a47b-df17e14b2c74&DisplayLang=en
This image runs a Windows Server 2003 R2 Enterprise Edition machine. The virtual machine is for evaluation purposes and will expire after 30 days. You can login to the image using the following creditentials:
Username: Administrator
Password: pass@word1



Sharepoint Server 2007 Virtual PC Harddrive Image with Instructions and Walkthrough
https://connect.microsoft.com/Downloads/DownloadDetails.aspx?SiteID=428&DownloadID=7004
This image has been expired but can still be used for an hour each time the virtual machine is started.



Let me know if you find this of help.

Sunday, March 30, 2008

Checking OS and Browser with Javascript


I've ran into cases where different browsers and even the same browsers but on different OS's respond differently to CSS attributes. So in some cases it's best to check for the type of OS and browser and apply attributes accordingly. I recently had to deal with this issue for the Firefox browser on Mac.




It turns out that having an HTML element with a CSS opacity attribute interferes with Flash graphics on the web page if it lays over it. As far as I noticed this only happens currently when using Firefox on Mac. Since opacity wasn't a requirement and wasn't of importance I decided to take it out on that browser/OS combination. This is done by code like the following:





function checkOSBrowser() {
if(navigator.platform.indexOf("Mac") || navigator.userAgent.indexOf("Firefox"))
document.getElementById("myElem").style.opacity = "0.8";
}




To review, navigator.platform returns the current OS and navigator.userAgent returns the running browser name. It is generally better to use indexOf() or search() to look for the desired OS or browser than to use an exact match because if anything slightly changed with an exact match the match would fail. Take "Mac" for example. If you run navigator.platform on a Mac machine with Intel processors, the output would be "MacIntel" not "Mac." So if you don't care exactly what kind of Mac is running you should just use the indexOf() or search() functions provided by the Javascript String.

Thursday, February 21, 2008

Google JavaScript Trick

Here is a cool browser JavaScript trick. Go to www.google.com then in the address bar of the browser paste the following and press Enter:

"javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++}setInterval('A()',5 ); void(0);"

without the quotes. The Google logo should start dancing. You can still use the Google search while the logo is bouncing around the page though. Like it?

Friday, February 15, 2008

Javascript Naming for CSS Float Property

Typically, you can access a CSS property of an element in Javascript using something similar to:


elem.style.propertyName = "value";


Where the propertyName is the property name in CSS with no dashes and written in camel format. For example text-align becomes textAlign. However, for the CSS float property this is a problem because float a keyword in Javascript. Therefore instead you have to use cssFloat.

Monday, February 11, 2008

State Management with ASP .NET 2.0 - 2

In the previous post about state management I talked about the ViewState collection. Today I will write about the Application collection.

2. Application State Collection

The Application collection is an object collection that maps strings to objects. The unique aspect of the Application collection is that it is a global variable such that it is shared throughout the entire ASP .NET application. The Application collection has the same life span as the ASP .NET process and dies or is cleared when the process is killed or restarted.

The use of the Application collection is to store variables that need to be retained across different pages and shared amongst different users and sessions. An example of something that might be stored in the Application collection would be a counter of some sort that is shared amongst pages and sessions.

The Application collection is used like any collection in .NET. To store something (in code behind):

int n = 0;
Application["keyID"] = n;


To retrieve a variable from the collection:

int x = (int)Application["keyID"];

Saturday, February 9, 2008

Make Google Black and White


Have you ever dreamed about seeing how the Google logo looks in black and white (or grey scale). Well, there is a chance for you. Just go to google.com and type "make google black and white" then press "I am feeling lucky." And if today is your lucky day, the Google logo will switch to black and white :). Actually it should switch anyway.



Google log in black and white


So how does that work? It turns out that there is a web site that totally mimicks the Google web site look in a signed off state. But it has a logo in black and white. More importantly, this site happens to be the first result on Google search when you search for "make google black and white." Pressing the "I am feeling lucky" button has the same effect as going to the first link in the search results. So when you press the button you are actually going a new site but since everything looks the same except for the logo, it looks like as if Google understood what you wanted and changed its logo like magic. But sorry not this time. No magic there.

Monday, February 4, 2008

Submitting a Form upon Pressing the Enter Key


It is very common on web forms that a page is desired to submit its form when a user presses the Enter key while the focus in a certain or any text box. This is typically done using JavaScript. I want to share how it's done as it can be very useful. In essence all that is done is that every time a user presses a key, a JavaScript code checks if the key pressed is the Enter key. If so it submits the form to the server, otherwise it does nothing. The following is a snippet of the code would look like:




On the JavaScript side


function enter_submit(pevent)
{
if(window.event) //Internet Explorer
{
if(myEvent.keyCode == 13) //check enter was pressed
{
document.formname.submit();
//or __doPostBack("",'');
return;
}
}
else if(pevent.which) // Netscape/Firefox/Opera
{
var pressed = pevent.which;
if(pressed == 13)
document.formname.submit();
//or __doPostBack('','');
}
}



On the HTML or ASP .NET side



<asp:Textbox ID="txtPassword" runat="server" onkeypress="javascript:enter_submit(event);/>

<input id="inPassword" type="password" onkeypress="enter_submit(event);"/>

Tuesday, January 22, 2008

asp:Button and Javascript

It is useful many times to decide the behavior of a button based on some client side code result. For example, when a button is pressed a web page might need to execute Javascript code to validate some user input or to have the user confirm a certain action and based on the output of the client code either post back to the web server or ignore the click or execute more client side code.

Let's take the scenario of asking the user to confirm a certain action as this scenario has actually come up with me at a client. The web page has a button that deletes an object permanently. Upon a user click on the button, the page executes Javascript code to open a confirmation box with an OK and a Cancel button. The confirmation box should at the least minimize accidental deletions. If the user clicks OK the page posts back and the object is deleted. However, if the user clicks Cancel the button click is ignored and nothing happens. Let's take a look at the code behind this:

Javascript part:

<script type="text/javascript">
function confirmDelete() {
return window.confirm("You really want to delete all your work?");
}
</script>


ASPX side:

<asp:button id="btnDelete" onclick="btnDelete_Click" runat="server" text="Delete" tooltip="Permanetly remove this item" onclientclick="javascript:return confirmDelete();" />


That's it.

Free Online Silverlight Training Resources

I wanted to share some free online resources for the new Microsoft web technology Silverlight.

Microsoft Press E-Book: Introducing Silverlight 1.0
http://csna01.libredigital.com/?urvs5cn3s8

visitmix.com Firestarter:
http://www.visitmix.com/University/silverlight/firestarter/

Lynda.com Training:
http://movielibrary.lynda.com/html/modPage.asp?ID=473

On another note, Microsoft has extended the deadlines for 3 beta exams.
From: Trika msdn blog

The dates for the following three betas have been extended and you are welcome to spread the word. taking a beta exam is free. If you pass it, you have passed that exam (and earned the related certification, if applicable)--you do not need to take the live version of the exam. if you've never taken a beta exam before, read this. If you have questions, check out Gerry's Blog, I'm sure he'll be posting this info too and he knows more about it than YT.


Link to registration: http://www.register.prometric.com/ClientInformation.asp

· Not available in China, India, Pakistan
· Need to stress there’s no guarantee of a seat

Sunday, January 6, 2008

Submitting Files to Multiple Sites

An issue came up recently at my client where the client wanted to keep a backup copy of every file submitted by a user to a third-party site. The backup copy was going to be saved a separate server. The solution I implemented was some simple JavaScript code. Essentially, the code submits the form to one site then changes the "action" and "target" properties of the form and submits it again to the other site. The new target could be an HTML iframe or a new window. In my case it was a small popup window. Here is a sample of the code:


function submitForms() {
window.open("", "smallPopup", "location=1, status=1, scrollbars=1, width=100, height=100");
var theForm = document.myForm;
theForm.action = "http://firstSite.com/backup";
theForm.target = "smallPopup";
theForm.submit();

theForm.action = "http://2ndSite.com/receive";
theForm.target = "_self";
theForm.submit();
}

Now you might wonder why I didn't just create another form and have two forms, one for each server. The problem with that is the user would have to select the file twice, once for each form. This is because for security reasons, it is not possible to programmatically set the file path in an HTML input of type file. So a programmer is prevented from assigning the path of one input tag to be the same as another input tag of type file. A programmer only has read access to the file path. Of course this makes a lot of sense too because if it were possible then any malicious site would be able to upload any file its owner wishes from your computer to his server.