Entries in ASP.NET (41)

Silverlight 2.0 Video Tutorials

Silverlight 2.0 provides a new and exciting framework for building rich applications using C#, VB.NET or other languages that are capable of running on multiple operating systems and in multiple browsers.  Scott Guthrie recently posted a great set of tutorials on Silverlight 2.0 that are an excellent resource for getting started building Silverlight 2.0 applications. 

Scott recently approved converting the tutorials into video so I've been busy the past few days putting together video tutorials that cover Silverlight 2.0 and the Digg.com application Scott wrote about.  Links to the written tutorials and video tutorials are shown below.

Silverlight 2.0 Video Tutorials

Part 1: Creating "Hello World" with Silverlight 2 and VS 2008TutorialVideo Tutorial
Part 2: Using Layout ManagementTutorialVideo Tutorial
Part 3: Using Networking to Retrieve Data and Populate a DataGridTutorialVideo Tutorial
Part 4: Using Style Elements to Better Encapsulate Look and FeelTutorialVideo Tutorial
Part 5: Using the ListBox and DataBinding to Display List DataTutorialVideo Tutorial
Part 6: Using User Controls to Implement Master/Details ScenariosTutorialVideo Tutorial
Part 7: Using Templates to Customize Control Look and FeelTutorialVideo Tutorial
Part 8: Creating a Digg Desktop Version of our Application using WPFTutorialVideo Tutorial


View other cool videos on Silverlight 2.0 and additional .NET technologies from the Mix 08 conference:

Joshua Allen's Mix 08 Blog


del.icio.us Tags: ,,,,
Posted on Saturday, March 8, 2008 at 10:12PM by Registered CommenterDan Wahlin in , , , , , , , | CommentsPost a Comment | EmailEmail | PrintPrint

Building an N-Layer ASP.NET Application with LINQ, Lambdas and Stored Procedures (Updated)

Update:  I refactored some of the code and also did a better job ensuring Dispose() is called everywhere so that the DataContext object gets cleaned up properly.

Download the Application Here

.NET 3.5 has a lot of great new features that can significantly enhance developer productivity.  I've been spending some time lately working on a little sample application that demonstrates how an N-Layer ASP.NET 3.5 application can be built using LINQ, lambdas and LINQ with stored procedures.  The application is for a talk I'll be giving at DevConnections in April discussing how LINQ technologies can be used in an N-Layer architecture.  In a previous post comparing different LINQ options I mentioned that I'd be posting the code download as soon as it was ready.

The application provides a presentation layer, business layer, data layer and model layer through separate projects as shown next:

image

It also demonstrates how the new ListView control can be used to display data, perform insert, update and delete operations and nest other controls such as the GridView.  Databinding on the presentation layer is mainly done using the ObjectDataSource control.

Application Example

All of the queries performed in the application go against an object model created using the Visual Studio 2008 LINQ to SQL Designer. 

Note:  The included Northwind SQL Express database has been modified slightly to add a TimeStamp field into the Customer and Orders tables.  Doing so simplifies updates so be aware that if you change the connection string to point to a standard Northwind database you'll get an error since the TimeStamp fields will be missing.


3 Options for Data Access

Rather than focusing solely on LINQ, I wanted to show different options for data access that .NET 3.5 offers so that developers can get a feel for what's available in addition to standard LINQ queries that seem to get most of the attention these days.  I ended up creating six main data layer classes as shown next:

Customer Query Classes:

  • CustomerDBLINQ - Executes customer related queries using inline LINQ
  • CustomerDBLambda - Executes customer related queries using lambda expressions
  • CustomerDBSprocs - Executes customer related queries using stored procedures and LINQ

Order Query Classes:

  • OrderDBLINQ - Executes order related queries using inline LINQ
  • OrderDBLambda - Executes order related queries using lambda expressions
  • OrderDBSprocs - Executes order related queries using stored procedures and LINQ

I still lean toward using stored procedures due to the security and maintenance benefits they offer in more enterprise environments, but for small queries I actually prefer lambda expressions over LINQ (not sure why...just feels more object oriented I guess).  If you currently use stored procedures in your applications and haven't checked out the new LINQ to SQL Designer you'll be impressed with how easy it is to call stored procedures and pass parameters.  You never have to see or create another SqlCommand or SqlParameter object again (well...in many cases anyway).


Switching Between Data Access Classes

By changing a value in web.config you can switch between the different data layer classes and see which option you prefer (LINQ, lambdas or LINQ with sprocs).  All of the data access classes perform the same overall tasks, they just use different techniques to do it.

<appSettings>
  <!-- 
    Used to define which DB layer class should be loaded and used. 
    Valid customer values include:  Data.CustomerDBSprocs, Data.CustomerLINQ, Data.CustomerLambda
    Valid order values include: Data.OrderDBSprocs, Data.OrderLINQ, Data.OrderLambda
  -->
  <add key="CustomerDBType" value="Data.CustomerDBLINQ" />
  <add key="OrderDBType" value="Data.OrderDBLINQ" />
  <!-- When the following key is set to "true" ensure that 
EnablePartialRendering is set to false on the Default.aspx ScriptManager control --> <add key="EnableDataContextLogging" value="false" /> </appSettings>

Over the next few weeks I'm hoping to make some time to walk through the application pieces.  I may create some video tutorials about it as well....we'll see how time goes.

 

Posted on Monday, February 18, 2008 at 06:27PM by Registered CommenterDan Wahlin in , , , , | CommentsPost a Comment | EmailEmail | PrintPrint

Simplifying ASP.NET ListView Control Templates

I've been working with the new ListView control in ASP.NET 3.5 combining it with LINQ and Lambda expressions and was finding myself duplicating a lot of code between ItemTemplate and AlternatingItemTemplate templates (I'll be posting the sample application that demonstrates using LINQ, Lambdas and Stored Procedures soon).  The AlternatingItemTemplate contained the same code as the ItemTemplate except for a CSS class added to the first <tr> element to change the background color.  Here's an example of both templates that were used initially:

<ItemTemplate>
    <tr class="even">
        <td class="tdControls">
            <asp:LinkButton ID="EditButton" CommandName="Edit" runat="server" 
Text="Edit"></asp:LinkButton> <asp:LinkButton ID="DeleteButton"
OnClientClick="return confirm('Delete Record?');"
CommandName="Delete" CommandArgument='<%# Eval("CustomerID")%>'
runat="server" Text="Delete"></asp:LinkButton> </td> <td> <%# Eval("CustomerID") %> </td> <td> <%# Eval("CompanyName") %> </td> <td> <%# Eval("ContactName") %> </td> <td> <%# Eval("ContactTitle") %> </td> <td> <%# Eval("Address") %> </td> <td> <%# Eval("City") %> </td> <td> <%# Eval("Country") %> </td> <td> <asp:LinkButton ID="lbOrders" runat="server" Text="Orders"
CommandName="ViewOrders"
CommandArgument='<%# Eval("CustomerID") %>' /> </td> </tr> <tr id="trOrders" runat="server" visible="false"> <td>&nbsp;</td> <td colspan="8"> <asp:GridView id="gvOrders" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid"
BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Width="500px" EnableViewState="false"> <FooterStyle BackColor="#CCCCCC" /> <Columns> <asp:BoundField DataField="OrderID" HeaderText="OrderID" SortExpression="OrderID" /> <asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" HtmlEncode="false"
DataFormatString="{0:d}" /> <asp:BoundField DataField="RequiredDate"
HeaderText="RequiredDate" SortExpression="RequiredDate" HtmlEncode="false"
DataFormatString="{0:d}" /> <asp:BoundField DataField="ShippedDate"
HeaderText="ShippedDate" SortExpression="ShippedDate" HtmlEncode="false"
DataFormatString="{0:d}" /> </Columns> <AlternatingRowStyle BackColor="#eaeaea" /> </asp:GridView> </td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr class="odd"> <td class="tdControls"> <asp:LinkButton ID="EditButton" CommandName="Edit" runat="server"
Text="Edit"></asp:LinkButton> <asp:LinkButton ID="DeleteButton"
OnClientClick="return confirm('Delete Record?');"
CommandName="Delete" CommandArgument='<%# Eval("CustomerID")%>'
runat="server" Text="Delete"></asp:LinkButton> </td> <td> <%# Eval("CustomerID") %> </td> <td> <%# Eval("CompanyName") %> </td> <td> <%# Eval("ContactName") %> </td> <td> <%# Eval("ContactTitle") %> </td> <td> <%# Eval("Address") %> </td> <td> <%# Eval("City") %> </td> <td> <%# Eval("Country") %> </td> <td> <asp:LinkButton ID="lbOrders" runat="server" Text="Orders"
CommandName="ViewOrders"
CommandArgument='<%# Eval("CustomerID") %>' /> </td> </tr> <tr id="trOrders" runat="server" visible="false"> <td>&nbsp;</td> <td colspan="8"> <asp:GridView id="gvOrders" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid"
BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Width="500px" EnableViewState="false"> <FooterStyle BackColor="#CCCCCC" /> <Columns> <asp:BoundField DataField="OrderID" HeaderText="OrderID" SortExpression="OrderID" /> <asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" HtmlEncode="false"
DataFormatString="{0:d}" /> <asp:BoundField DataField="RequiredDate"
HeaderText="RequiredDate" SortExpression="RequiredDate" HtmlEncode="false"
DataFormatString="{0:d}" /> <asp:BoundField DataField="ShippedDate"
HeaderText="ShippedDate" SortExpression="ShippedDate" HtmlEncode="false"
DataFormatString="{0:d}" /> </Columns> <AlternatingRowStyle BackColor="#eaeaea" /> </asp:GridView> </td> </tr> </AlternatingItemTemplate>


It seemed like a waste (and a maintenance headache) to have both templates duplicating the same code while only needing background color changes so I decided to adjust it by adding a little code into the first <tr> tag to dynamically assign the CSS class based upon odd or even rows. It calls the ListViewDataItem class's DataItemIndex property and applies a modulus operation to it.  This isn't anything new of course (I've done the same type of thing for years with GridView and DataGrid controls), but it's a nice trick that can save a lot of duplicated code if you haven't seen it.


<ItemTemplate>
    <tr class='<%# (Container.DataItemIndex % 2 == 0)?"even":"odd" %>'>    
<td>
<asp:LinkButton ID="EditButton" CommandName="Edit" runat="server"
Text="Edit"></asp:LinkButton> <asp:LinkButton ID="DeleteButton"
OnClientClick="return confirm('Delete Record?');"
CommandName="Delete" CommandArgument='<%# Eval("CustomerID")%>'
runat="server" Text="Delete"></asp:LinkButton> </td> <td> <%# Eval("CustomerID") %> </td> <td> <%# Eval("CompanyName") %> </td> <td> <%# Eval("ContactName") %> </td> <td> <%# Eval("ContactTitle") %> </td> <td> <%# Eval("Address") %> </td> <td> <%# Eval("City") %> </td> <td> <%# Eval("Country") %> </td> <td> <asp:LinkButton ID="lbOrders" runat="server" Text="Orders"
CommandName="ViewOrders"
CommandArgument='<%# Eval("CustomerID") %>' /> </td> </tr> <tr id="trOrders" runat="server" visible="false"> <td>&nbsp;</td> <td colspan="8"> <asp:GridView id="gvOrders" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid"
BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Width="500px" EnableViewState="false"> <FooterStyle BackColor="#CCCCCC" /> <Columns> <asp:BoundField DataField="OrderID" HeaderText="OrderID" SortExpression="OrderID" /> <asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" HtmlEncode="false"
DataFormatString="{0:d}" /> <asp:BoundField DataField="RequiredDate"
HeaderText="RequiredDate" SortExpression="RequiredDate" HtmlEncode="false"
DataFormatString="{0:d}" /> <asp:BoundField DataField="ShippedDate"
HeaderText="ShippedDate" SortExpression="ShippedDate" HtmlEncode="false"
DataFormatString="{0:d}" /> </Columns> <AlternatingRowStyle BackColor="#eaeaea" /> </asp:GridView> </td> </tr> </ItemTemplate>
del.icio.us Tags: ,,

 

Posted on Friday, February 15, 2008 at 11:02PM by Registered CommenterDan Wahlin in | CommentsPost a Comment | EmailEmail | PrintPrint

New Video: Integrating Silverlight and ASP.NET AJAX

I gave a talk at Desert Code Camp toward the end of 2007 that discussed how Microsoft's Silverlight product could be integrated with ASP.NET AJAX to dynamically display albums obtained from an Amazon.com Web Service.  It's taken awhile to get the video posted, but it's now available.  The audio in the room wasn't great since no microphone was used so you may need to crank it up a bit. 

Slides and code shown in the video can be downloaded below:

  • PowerPoint Slides Download

    Integrating Silverlight and ASP.NET AJAX (57 minutes)

    Click here to view in Windows Media Player (right-click and you can save the file)

     

    Posted on Sunday, January 20, 2008 at 11:48AM by Registered CommenterDan Wahlin in , , , , , | CommentsPost a Comment | EmailEmail | PrintPrint
  • Upcoming .NET Courses in 2008



    I've had several people here in the Phoenix area and others I've met at ASP.NET Connections conferences ask when I'll be teaching specific .NET classes in 2008 and my standard reply has been "I'm not sure at this point".  We have things scheduled out past June now so here's the information for those who are interested.  Most of the classes listed are 5 days aside from the First Look at Visual Studio 2008 (1 day) and ASP.NET AJAX Programming (3 days).

    The schedule is of course subject to change, but it's what I have at this point.  If you have any questions about any of the courses feel free to contact me through my blog.

    Posted on Thursday, January 10, 2008 at 09:49PM by Registered CommenterDan Wahlin in , , , , , , , | CommentsPost a Comment | EmailEmail | PrintPrint

    ASP.NET 3.5 Extensions Preview Released

    For those of you that like to stay on top of the latest technologies, Microsoft just released the ASP.NET 3.5 Extensions Preview today which provides the following new functionality (quoted from the http://www.asp.net Website):

    ASP.NET MVC

    ASP.NET MVC provides model-view-controller (MVC) support to the existing ASP.NET 3.5 runtime, which enables developers to more easily take advantage of this design pattern. Benefits include the ability to achieve and maintain a clear separation of concerns, as well as facilitate test driven development (TDD).

    The ASP.NET MVC Toolkit provides HTML rendering helpers and dynamic data support for MVC.

    ASP.NET Dynamic Data

    ASP.NET Dynamic Data helps developers build a fully customizable, data-driven app quickly. It provides a rich scaffolding framework that allows rapid data driven development without writing code, yet it is easily extendible using the traditional ASP.NET programming model.

    ASP.NET AJAX

    New additions to ASP.NET AJAX include support for managing browser history (Back button support).

    ADO.NET Entity Framework

    ADO.NET Entity Framework is a new modeling framework that enables developers to define a conceptual model of a database schema that closely aligns to a real world view of the information. Benefits include easier to understand and easier to maintain application code that is shielded from underlying database schema changes.

    ADO.NET Data Services

    ADO.NET Data Services provide new services that find, manipulate and deliver data over the web using simple URIs. Benefits include an easy and flexible way to access data over the web, while enabling the separation of presentation and data access code.

    Silverlight Controls for ASP.NET

    You can integrate the rich behavior of Microsoft Silverlight into your Web application by using two new ASP.NET server controls: a MediaPlayer server control that enables easy integration of media sources such as audio (WMA) and video (WMV) into your Web application, and a Silverlight server control that allows an ASP.NET page to reference both XAML objects and their event handlers.

    If you're still trying to get your head around new features released in Visual Studio 2008 and .NET 3.5 (and who isn't since they just came out) then this new preview release may really make your head swim.  We're all in that boat though. :-)  There's a lot of new things to look into and get to know that can significantly enhance developer productivity which is the ultimate goal.

    Posted on Sunday, December 9, 2007 at 11:20PM by Registered CommenterDan Wahlin in , , | CommentsPost a Comment | EmailEmail | PrintPrint

    Speaking at the ASP.NET Connections Conference in Vegas

    I'll be speaking at the ASP.NET Connections conference next week in Las Vegas and always like to post the slides and content for those that come (and those who can't come).  If you've never been it's a great conference that has a ton of in-depth content.  It's definitely my favorite conference.

    I'll be giving a pre-conference workshop on Silverlight and two other regular talks:

    I'll post the slides and demos here after I give each talk so check back.

    Posted on Wednesday, October 31, 2007 at 10:21AM by Registered CommenterDan Wahlin in , , | Comments Off | EmailEmail | PrintPrint

    Speaking on Silverlight and Web Services in Los Angeles Area

    I'm going to be speaking on behalf of Interface Technical Training and INETA this week at two Los Angeles area user groups.  The first talk is at Manhattan Beach, CA on October 2nd and will cover calling Web Services asynchronously in .NET 2.0.  The next talk is at Buena Park, CA on October 3rd and will cover building Silverlight applications. More details about the talks are shown next. 

    Synchronous and Asynchronous Web Services in .NET 2.0

    The advent of Web services has started a revolution that allows applications to communicate regardless of language or platform. This talk will discuss how synchronous and asynchronous calls can be made to Web services using features in .NET 2.0. The discussion will explain synchronous and asynchronous pros and cons and show the code necessary to use each technique in .NET applications.

    Slides and Code

    Integrating Silverlight with ASP.NET AJAX and Web Services

    This talk will discuss Microsoft’s new Silverlight 1.0 technology and explore how you can use it to build rich Web-based applications.  Throughout the talk you’ll see the role that XAML plays, different XAML animation and transformation techniques, how JavaScript can be used to communicate with Silverlight objects, and how you can display data from different data sources including Amazon.com's Web Service using  ASP.NET AJAX integration techniques.

    If you're new to Silverlight and are looking to get a jump-start on the technology I'll start out by covering fundamental concepts and provide a step-by-step approach to building Silverlight applications.  I'll then dive into a Silverlight application and discuss how it was created so that you can learn about several different Silverlight concepts by example.

    Slides and Code

    Posted on Sunday, September 30, 2007 at 06:17PM by Registered CommenterDan Wahlin in , , | CommentsPost a Comment | EmailEmail | PrintPrint

    JavaScript Beautifier Tool

    I was working on a new article on Silverlight tonight and needed to "beautify" the Silverlight.js code so that I could read through it more easily.  I came across a nice JavaScript beautifier tool that did a great job converting the unformatted file into an easy to read format.  I'm sure there are several of these tools out there on the Web, but this was the first one that popped up while searching and it worked quite well in case anyone needs that type of functionality.

     http://elfz.laacz.lv/beautify/

    Posted on Wednesday, September 26, 2007 at 11:03PM by Registered CommenterDan Wahlin in | CommentsPost a Comment | EmailEmail | PrintPrint

    Integrate Windows Live ID Authentication Into Your Website

    Microsoft recently released an SDK that allows you to integrate Windows Live ID authentication into your Website (ASP.NET or any other).  To get started you'll need to register your application and get an application ID.  From there it's quite straightforward especially since a sample application that uses Windows Live ID is available to download.  Sample code is available for ASP.NET, Java, Perl, PHP, Python, and Ruby.

    Once you've registered your site and obtained an application ID you can embed an iframe into the page where users need to sign-in.  The iframe points to the windows Live ID authentication page and passes it your application ID:

    <iframe 
       id="WebAuthControl" 
       name="WebAuthControl"
       src="http://login.live.com/controls/WebAuth.htm?appid=<%=AppId%>&style=font-size%3A+10pt%3B+font-family%
    3A+verdana%3B+background%3A+white%3B"
    width="80px" height="20px" marginwidth="0" marginheight="0" align="middle" frameborder="0" scrolling="no"> </iframe>

    Once the end user signs-in they'll be redirected to the landing page you specified when you registered the application with WIndows Live ID services.  This page needs to process the response and set a cookie if the user successfully signed-in to Windows Live ID.  The following code (from the SDK sample) shows how you can check what action is being performed and then log the user into or out of your site as appropriate through cookies.  The code relies upon a class named WindowsLiveLogin that is available in the SDK sample code mentioned above.

    public partial class HandlerPage : System.Web.UI.Page
    {
        const string LoginPage = "default.aspx";
        const string LogoutPage = LoginPage;
        const string LoginCookie = "webauthtoken";
        static DateTime ExpireCookie = DateTime.Now.AddYears(-10);
        static DateTime PersistCookie = DateTime.Now.AddYears(10);
    
        // Initialize the WindowsLiveLogin module.
        static WindowsLiveLogin wll = new WindowsLiveLogin(true);
    
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpRequest req = HttpContext.Current.Request;
            HttpResponse res = HttpContext.Current.Response;
    
            // Extract the 'action' parameter from the request, if any.
            string action = req.QueryString.Get("action");
    
            /*
              If action is 'logout', clear the login cookie and redirect
              to the logout page.
    
              If action is 'clearcookie', clear the login cookie and
              return a GIF as response to signify success.
    
              By default, try to process a login. If login was
              successful, cache the user token in a cookie and redirect
              to the site's main page.  If login failed, clear the cookie
              and redirect to the main page.
            */
    
            if (action == "logout")
            {
                HttpCookie loginCookie = new HttpCookie(LoginCookie);
                loginCookie.Expires = ExpireCookie;
                res.Cookies.Add(loginCookie);
                res.Redirect(LogoutPage);
                res.End();
            } 
            else if (action == "clearcookie")
            {
                HttpCookie loginCookie = new HttpCookie(LoginCookie);
                loginCookie.Expires = ExpireCookie;
                res.Cookies.Add(loginCookie);
    
                string type;
                byte[] content;
                wll.GetClearCookieResponse(out type, out content);
                res.ContentType = type;
                res.OutputStream.Write(content, 0, content.Length);
    
                res.End();
            } 
            else 
            {
                WindowsLiveLogin.User user = wll.ProcessLogin(req.Form);
    
                HttpCookie loginCookie = new HttpCookie(LoginCookie);
                if (user != null)
                {
                    loginCookie.Value = user.Token;
    
                    if (user.UsePersistentCookie)
                    {
                        loginCookie.Expires = PersistCookie;
                    }
                } 
                else 
                {
                    loginCookie.Expires = ExpireCookie;
                }   
    
                res.Cookies.Add(loginCookie);
                res.Redirect(LogoutPage);
                res.End();
            }
        }
    }

    You can also integrate other Windows Live controls into your pages.  An example of integrating the Windows Live Contacts Control into a page is available here.  More information about integrating Windows Live ID services into your applications can be found here.
    Posted on Friday, August 17, 2007 at 09:14AM by Registered CommenterDan Wahlin in | CommentsPost a Comment | EmailEmail | PrintPrint

    Video: Using the New ASP.NET ListView Control

    ASP.NET 3.5 introduces a new control called the ListView that allows developers to have 100% control over the HTML markup that is generated while still providing paging, inserting, updating, and deleting support. To me the ListView control is a nice blend between the GridView and Repeater controls with new features added.

    In this video I walk through the fundamentals of using the ListView control and show how you can use the new CSS tools in VS.NET 2008 to create a scrollable ListView control with a frozen header. See my previous blog post if you're interested in learning how to freeze GridView control headers in IE and FireFox.

     

    Posted on Wednesday, August 1, 2007 at 10:15PM by Registered CommenterDan Wahlin in | Comments8 Comments | References2 References | EmailEmail | PrintPrint

    Tracing in ASP.NET Application Classes

    I'm a big fan of tracing in .NET and use it in every project I work on since it's a great way to find out why things aren't working properly.  Tracing is especially useful when an application works in a test environment but not in production.  My good buddy Michael Palermo recently wrote a nice post on how to dynamically grab the name of a method when using tracing which is a great idea.  Mike's post made me think about a question I'm often asked: "How do you perform tracing in classes that don't have direct access to the ASP.NET TraceContext object?".

    There are several potential answers to this question.  Some or good and some are bad.  You could pass a Page object instance to business object methods that need to write to the ASP.NET trace log but this would break some fundamental architecture principles so it's not something I'd recommend.  You could also perform a trace operation in a business or data layer class by using the HttpContext class as shown next (you could used Michael's suggested technique to dynamically add the target method name into the message text):

    HttpContext.Current.Trace.Warn("Category","Message text");

    While this works, using HttpContext ties the class where it's defined to the Web and makes it less useful in desktop or other non-Web applications (without checking to see if an HTTP context exists anyway).  I'll admit that I use the HttpContext technique for demos since it's quick and easy, but for more enterprise applications there's a better technique that you might want to consider.  

    The System.Diagnostics namespace provides a Trace class that can be used to route data to the ASP.NET trace log exposed by viewing Trace.axd in the browser.  You'll have to add some minor configuration code into web.config to get it to work, but it's quite simple.  Here's an example of using the System.Diagnostics.Trace class's Write() method:

    Trace.Write("Category","Message text");

    To enable trace messages created by classes used in an ASP.NET application to be written to the ASP.NET trace log, you can add the following code to web.config (add it outside of the system.web tag) which listens for trace operations and uses the System.Web.WebPageTraceListener class to write them to the trace log:

    <system.diagnostics>
        
    <trace>
            
    <listeners>
                
    <add name="WebPageTraceListener" 
                  type
    ="System.Web.WebPageTraceListener, System.Web, 
                            Version=2.0.3600.0, Culture=neutral, 
                            PublicKeyToken=b03f5f7f11d50a3a"/>
            </
    listeners>
        
    </trace>
    </system.diagnostics>

    The value supplied to the type attribute should be placed on a single line in web.config of course.

    By using the System.Diagnostics.Trace class (and related configuration code) with custom business or data classes you can use these classes with Web or desktop applications since the trace operations aren't tied to HttpContext any longer.  Desktop applications would simply need to change the listener class in app.config to have trace operations written to a log file or other location.  A class such as System.Diagnostics.TextWriterTraceListener could be used in this situation.

     

    Posted on Monday, July 9, 2007 at 08:41PM by Registered CommenterDan Wahlin in | CommentsPost a Comment | EmailEmail | PrintPrint

    Article: Master Pages Tips and Tricks

     

    I recently finished a new article on Master Pages tips and tricks that covers different things you can do with Master Pages such as using the MasterType directive, working with base classes, and handling nested Master Page design issues in VS.NET 2005.  The article also discusses a technique published awhile back on my blog for sharing Master Pages across IIS applications.  The article is available on the Simple-Talk.com Website. 

    Additional code covering different tips and tricks for Master Pages can be found here.

     

    Posted on Thursday, June 14, 2007 at 04:23PM by Registered CommenterDan Wahlin in | CommentsPost a Comment | EmailEmail | PrintPrint

    New Column on ASP.NET AJAX, Web Services/WCF and Silverlight

    Over the past month I've been writing articles for a new column in the .NET Insight and Web Design and Development Insight newsletters published by 1105 Media (a parent company for several media groups) that covers ASP.NET AJAX, XML Web Services/WCF, and Silverlight.  The articles are designed to be very focused so that you learn things quickly without having to scroll through pages and pages of text to learn a single concept.  The first 3 articles have been published and are available at the links below.  Four more articles are on the way.

    Upcoming articles will cover various aspects of the UpdatePanel, Timer and UpdateProgress controls and explore how the client-side PageRequestManager can be used to provide visual feedback to end users.  As the articles progress I'll discuss ASP.NET AJAX and Web Services as well as Silverlight.  If you have specific topics you're interested in seeing related to AJAX, Web Services or Silverlight let me know by adding a comment. 

    You can subscribe to these newsletters here if you're interested. 

     

    Posted on Saturday, June 9, 2007 at 02:33PM by Registered CommenterDan Wahlin in , , | CommentsPost a Comment | EmailEmail | PrintPrint

    DinnerNow.net Sample Application Available

    Microsoft's .NET & Connected Systems Evangelism team recently released all of the source code for their DinnerNow.net application.  If you're interested in learning .NET 3.0 technologies as well as the new 3.5 stuff coming out, this is a great application to run and explore.  James Conrad's team put together a great set of sample code that shows how "you can develop a connected application using several new Microsoft technologies, including: IIS7, ASP.NET Ajax Extensions, Linq, Windows Communication Foundation, Windows Workflow Foundation, Windows Presentation Foundation, Windows Powershell, and the .NET Compact Framework".

    There's no better way to learn how these technologies can be used together than by walking through a real application and picking it apart.  In addition to the DinnerNow.net application, they've also released several labs that target VS.NET Orcas Beta 1 covering the following topics. 

    • JSON with ASP.NET AJAX and WCF
    • Developing Dynamic Data-Driven Websites
    • Using DLinq (Linq to SQL) with the .Net 3.5
    • Syndication using WCF
    • Workflow Services using WCF

    They'll also be releasing videos about the application.  I'll more than likely make some videos of my own that walk through the application as well in the near future.

    Posted on Sunday, June 3, 2007 at 01:24PM by Registered CommenterDan Wahlin in , , , , , , | CommentsPost a Comment | EmailEmail | PrintPrint