戰地連結︰ Home My Flickr NBA.com About

2008年8月27日星期三

Silverlight Get-started tutorial

Overview

To get started with Silverlight, I search for tutorial on web and found this blog by Scott Guthrie giving out a tutorial on building a complete Silverlight application with VS 2008.

Reference

  1. First Look at Silverlight 2
  2. Microsoft Silverlight Tools Beta 2 for Visual Studio 2008
  3. First Look at Using Expression Blend with Silverlight 2

Really Simple steps

  1. Install Silverlight 2 (if you don't have one)
  2. Install VS 2008
  3. Install Silverlight Tools Beta 2 for VS 2008 (download from reference 2)
  4. Create a Silverlight Application in VS 2008
  5. Happy coding!

2008年8月21日星期四

Sending test email through Telnet

Overview

How to test if a SMTP server function properly in sending email? The simplest way is to send a test email. In this blog I will talk about how to send a simple test email by Telnet to the SMTP server.

Reference

How Simple is SMTP?

Steps

  1. Start a Telnet connection to the SMTP server by using the following command in command prompt:
    telnet $smtp_server_ip$ $port$
    Note that the ip & port is separated by a "space" but not "colon", For SMTP server, the port is "25"
  2. Once the connection is established, type in "HELO" or "EHLO" before enter other commands
  3. After saying hello, we can use the following command to specify the email sender:
    MAIL FROM: sender@domain.com
  4. Next we can specify the receiver by the following command:
    RCPT TO: receiver@domain.com
  5. Now the last thing to do is entering the mail body, you can enter your mail after sending this command:
    DATA
  6. After you enter command "DATA", the server will tell you to enter mail and indicate how to end the mail body. Follow it and the server will reply that your email is on its way!
  7. After all is done, enter "QUIT" to close the connection.

2008年8月20日星期三

Globalization of ASP.NET with Resources File

Overview

Resources files can be used to provide multi-languages support in ASP.NET web applications. The web app can be set to display different languages based on the settings of client browser. Following shows how to use resources files in a web application project.

Reference

  1. ASP.NET Web Page Resources Overview
  2. Resource Files in ASP.NET 2.0
  3. CultureInfo Class
  4. globalization Element (ASP.NET Settings Schema)

Example

In the following example I will create a web application project in Visual Studio 2008 and add English & Traditional Chinese support for a simple page containing only one Label.

Create the Web Application Project

Note: In order to make the resources files editable even after the application is published, we have to use "ASP.NET Web Application" as the project template.

  1. In VS 2008, select "File" -> "New" -> "Project"
  2. In "Project types", select "Visual C#" -> "Web".
  3. In "Template", select "ASP.NET Web Application". Enter the Name of the web and the solution

Add Global Resources files (for default language: English) to the application

  1. Right-click on the web application project
  2. In the appeared menu, select "Add" -> "Add ASP.NET Folder" -> "App_GlobalResources", a folder named "App_GlobalResources" created
  3. Right-click on folder "App_GlobalResources"
  4. In the appeared menu, select "Add" -> "New Item..."
  5. In "Add New Item" window, select "Resources File", name it as "Resource.resx"
  6. Open "Resource.resx" and add a row with
    Name: TestString
    Value: Test

Add another Global Resources files for Trad. Chinese

  1. Right-click on folder "App_GlobalResources"
  2. In the appeared menu, select "Add" -> "New Item..."
  3. In "Add New Item" window, select "Resources File" under "Visual C#" category, name it as "Resource.zh-Hant.resx"
    Note: The phase between "Resource" & "resx" indicate the culture represented by this resources file. In this case, "zh-Hant" is the culture for "Traditional Chinese" which includes Locales for "Hong Kong", "Taiwan" etc.
  4. Open "Resource.zh-Hant.resx" and add a row with
    Name: TestString
    Value: 測試

Configure "web.config" to change Language based on client browser's setting

  1. Open file "web.config"
  2. Add the following code under "system.web" tab

<globalization enableClientBasedCulture="true" uiCulture="auto" culture="auto"/>

Add an ASP.NET page with a Label to see the result

  1. Right-click on the web application project
  2. In the appeared menu, select "Add" -> "New Item..."
  3. In "Add New Item" window, select "Web Form", name it as "Test.aspx"
  4. Open "Test.aspx", add a Web Control Label to it with the following code:

<asp:Label ID="Label1" runat="server" Text="<%$ Resources: Resources, TestString %>" />

Debug the project to see the result

If your browser (take IE 7 in this case) don't have any language preference setting, then the page should shows "Test". You can change the Language setting by:

  1. Select "Tools" -> "Internet Options"
  2. In "General" Tab, select "Languages"
  3. Click "Add" to add more preferred Languages, you can also change the priority of preferred Languages

2008年8月12日星期二

Multiple Delete in GridView

Overview

By default GridView allows us to delete only a record (a row) at a time, it will be better if we can select multiple rows with check boxes and delete them in a batch.

Reference

  1. Deleting Multiple Rows in a GridView
  2. delete multiple rows from gridview

Reference 1 shows a example of multiple delete in GridView with SqlDataSource. Reference 2 demonstrates the same thing and add a simple JavaScript asking user to confirm deleting.

I'm using ObjectDataSource in my code, which is very similar to what Reference 1 shows.

2008年8月8日星期五

Connecting NHibernate to Oracle Database

Overview

In my previous blog - NHibernate Setup, I shared my experience on setting up NHibernate with ASP.NET and SQL Server 2005 Database. Now I would like to talk about my experience on connecting NHibernate to Oracle Database.

Reference

  1. As long as ODP.NET is under the hood - NHibernate
  2. NHibernate & Spring.NET with Oracle
  3. NHibernate and Oracle Part 1 - using an external configuration file

About the Oracle Client Driver

There are two types of commonly used Oracle Client Driver: Microsoft's .NET driver & Oracle's own .NET driver. Using Microsoft's .NET driver in NHibernate is very very simple, but according to Reference 2 talking about NHibernate documentation, this driver does not handle long character strings correctly.
In the following blog, I will show the configuration for BOTH Drivers.

Steps - Microsoft's .NET driver

  1. Install "Oracle Client", you can download it at "http://www.oracle.com/technology/software/index.html" but registration required. I use Client 10g.
  2. Replace the original "hibernate-configuration" section in "web.config" with the following XML:

    <session-factory>

          <property name="dialect">NHibernate.Dialect.Oracle9Dialect</property>

          <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>

          <property name="hibernate.connection.driver_class">NHibernate.Driver.OracleClientDriver</property>

          <property name="connection.connection_string">Data source=DATASOURCE;User Id=ID;Password=PASS;</property>

        </session-factory>

  3. That's it!!! One thing to note is that in the connection string "Data source" is defined in "Net Manager" of Oracle Client. You can also find that in "$ORACLE_HOME\NETWORK\ADMIN\tnsnames.ora". $ORACLE_HOME is the installation folder of your Oracle Client, mine is "C:\oracle\product\10.2.0\client_1".

Steps - Oracle's .NET driver

  1. Install "Oracle Client", you can download it at "http://www.oracle.com/technology/software/index.html" but registration required. I use Client 10g.
  2. Set Environment Variable "ORACLE_HOME" to installation folder of your Oracle Client, mine is "C:\oracle\product\10.2.0\client_1".
  3. Make sure that "Oracle.DataAccess" is available in your Global Assembly Cache (GAC). You can view your GAC at "Administrative Tools" => ".NET Framework 2.0"
  4. In "web.config", add reference to "Oracle.DataAccess" by adding "qualifyAssembly" section in "assemblyBinding" section:

    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

         <qualifyAssembly partialName="Oracle.DataAccess" fullName="Oracle.DataAccess, Version=10.2.0.100, Culture=neutral, PublicKeyToken=89b483f429c47342" />

        </assemblyBinding>

  5. Replace the original "hibernate-configuration" section in "web.config" with the following XML:

    <session-factory>

          <property name="dialect">NHibernate.Dialect.Oracle9Dialect</property>

          <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>

          <property name="hibernate.connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property>

          <property name="connection.connection_string">Data source=DATASOURCE;User Id=ID;Password=PASS;</property>

        </session-factory>


    Note that the "driver_class" is "OracleDataClientDriver" instead of "OracleClientDriver".

2008年8月5日星期二

Convert NHibernate result iList to DataSet

Overview

Just like Hibernate, NHibernate returns query result in List of Objects (that's the idea of O/R mapping). It is very good, but some ASP.NET tools only work with DataSet, so we have to explicitly convert the iList returned by NHibernate to DataSet. The following simple code snippet mainly copied from Ayende's Blog can server this purpose.

Reference

Converting an object collection to a DataSet

Code Snippet

public static IList<Company> ShowCompanies()

        {

            // Get the List of Companies

            ICriteria criteria = NHibernateHttpModule.CurrentSession.CreateCriteria(typeof(Company));

            IList<Company> companies = criteria.List<Company>();

 

            // Convert the List into DataSet & return it

            DataTable dt = new DataTable();

            dt.Columns.Add("Name", typeof(string));

            dt.Columns.Add("CompanyCode", typeof(string));

            foreach (Company comp in companies)

            {

                DataRow row = dt.NewRow();

                row["Name"] = comp.Name;

                row["CompanyCode"] = comp.CompanyCode;

                dt.Rows.Add(row);

            }

            DataSet ds = new DataSet();

            ds.Tables.Add(dt);

            return ds;

            return companies;

        }

2008年8月4日星期一

Using CopySourceAsHtml in VS 2008

Overview

CopySourceAsHtml (CSAH) is a very useful tools for us "Programming Oriented Blogger". But after I switched to VS 2008, I soon found that there is no CSAH officially supporting it. Luckily with a little bit of googling, I was able to find a couple of Blogs of how to use CSAH in VS 2008.

Reference

Using CopySourceAsHtml with Visual Studio 2008 (beta 2 and yes, also RTM)

CopySourceAsHtml VS2008

Hibernate for .NET - NHibernate Setup

Overview

Hibernate offers O/R mappings between Database and Java persistence classes. Many Java programmers get used to Hibernate would like to use the same technology (and syntax!) on their .NET projects too~ The answer to this is called NHibernate.
Below I will share my experience on how to set up NHibernate with C#, it should be similar for other .NET languages.

Reference

  1. NHibernate Tutorial (1) - and ASP.NET
  2. Installation And Running NHibernate
  3. Your first NHibernate based application

Environment

  • Database: SQL Server 2005
  • NHibernate: 1.2.1 GA
  • .NET Language: C#

Steps

Setup SQL Server Database

  1. It is assumed that your Database is setup properly, so I will skip this step.

Download and install NHibernate

  1. Download NHibernate at Here (I downloaded 1.2.1 GA-bin.zip)
  2. Extract the zip file and navigate to folder "net-2.0"
  3. We are going to use "NHibernate.dll" as reference in our project

Create Web Site and do NHibernate Configuration in VS

  1. Add a Web Site to your Solution, and a C# class library project with name "Solution.Domain".
  2. There are two ways to do configuration for NHibernate, one is by "System.Configuration.NameValueSectionHandler", the other is by "NHibernate.Cfg.ConfigurationSectionHandler". I choose to use method 2 because it is supported in NHibernate 2.0
  3. Open "web.config" file and add "hibernate-configuration" section with the following code snippet:

    <configuration>

      <configSections>

            <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>

      </configSections>

      <!--

            NHibernate configuration

        -->

      <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

        <session-factory>

          <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>

          <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>

          <property name="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

          <property name="connection.connection_string">Server=(local);Initial Catalog=Test;Integrated Security=SSPI;</property>

          <mapping assembly="Solution.Domain" />

        </session-factory>

      </hibernate-configuration>

    </configuration>

  4. Now we have the "web.config" ready, we still have to add two helper classes for handling NHibernate sessions. I extracted This zip file attached to Reference 1 and used the "NHibernateHttpModule.cs" and "SessionHelper.cs" files.
    However, I modified "SessionFactory" method in "SessionHelper.cs" as my configuration method is different from that of Reference 1.

    My modified "SessionFactory" method:

    private static ISessionFactory SessionFactory

            {

                get

                {

                    if (_sessionFactory == null)

                    {

                        Configuration config = new Configuration();

                        config.Configure();

                        _sessionFactory = config.BuildSessionFactory();

                        if (_sessionFactory == null)

                            throw new InvalidOperationException("Could not build SessionFactory");

                    }

                    return _sessionFactory;

                }

            }

Defines Mapping and the persistence class

  1. The NHibernate mapping file is just like that of Hibernate: A XML file with extension ".hbm.xml". Here is my mapping file:

    <?xml version="1.0" encoding="utf-8" ?>

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Solution.Domain" assembly="Solution.Domain">

     

      <class name="User" table="app_user">

        <id name="Username" column="username" type="String">

          <generator  class="assigned"/>

        </id>

        <property name="Name" column="name" type="String"/>

        <property name="Password" column="password" type="String"/>

      </class>

       

    </hibernate-mapping>

  2. This XML mapping file must be included in the assembly with the name "Solution.Domain". To do this, right-click on the XML mapping file and select "properties", then choose "Embedded Resource" for "Build Action".
  3. Next, let's move on to the persistence class.

    namespace Solution.Domain

    {

        public class User

        {

            public User()

            {

            }

     

            public virtual string Username

            {

                get;

                set;

            }

            public virtual string Name

            {

                get;

                set;

            }

            public virtual string Password

            {

                get;

                set;

            }

        }

    }

Show the result in ASP.NET page

  1. Add a aspx page to the Web Site and then add the following code snippet to the aspx page:

    protected void Page_Load(object sender, EventArgs e)

        {

            ISession session = NHibernateHttpModule.CurrentSession;

            IQuery query = session.CreateQuery("FROM User");

            IList result = query.List();

     

            GridView1.DataSource = result;

            GridView1.DataBind();

        }

  2. If everything works fine (and you have some Data in your SQL Server Table!), then you should see the data is retrieved and displayed on the aspx page~

2008年8月1日星期五

Changing the default browser used in VS 2005/2008

Overview

I always use Firefox except browsing SharePoint sites (or sites with Active-X). However when I was debugging my projects with VS 2005/2008, I don't want it to use Firefox to open aspx pages. With a little bit of searching, I found below page showing how to set default aspx browser in VS (it can be either FF or IE or other Browsers)

Reference

Changing the default browser used in VS 2005 and Visual Web Developer - ScottGu's Blog

Steps (Copied from reference link)

  1. Right click on a .aspx page in your solution explorer
  2. Select the "browse with" context menu option
  3. In the dialog you can select or add a browser.  If you want Firefox in the list, click "add" and point to the firefox.exe filename
  4. Click the "Set as Default" button to make this the default browser when you run any page on the site.