As most of you might know (I hope) it is unwise to call methods on a Control from a non-UI thread. This can cause all sorts of issues. Actually, I think in most cases .NET will throw and Exception. If you need to set a property on a Control this is how you would properly do it.

VB.NET

 Delegate Sub SetPropertyValueDelegate(ByVal obj As Object, ByVal val As Object, ByVal index As Object())

 

    Public Sub SetControlProperty(ByVal ctrl As Control, ByVal propName As String, ByVal val As Object)

        Dim propInfo As PropertyInfo = ctrl.[GetType]().GetProperty(propName)

        Dim propertyDelegate As [Delegate] = New SetPropertyValueDelegate(propInfo.SetValue)

        'index

        ctrl.Invoke(propertyDelegate, New Object(2) {ctrl, val, Nothing})

    End Sub

 

    Private Sub UpdateSent(ByVal item As String)

        _chat.AppendLine(item)

 

        If Me.SentTextBox.InvokeRequired Then

            ' This is a worker thread so delegate the task.

            SetControlProperty(SentTextBox, "Text", _chat.ToString())

        Else

            ' This is the UI thread so perform the task.

            Me.SentTextBox.Text = _chat.ToString()

        End If

 

 

    End Sub

C#

        delegate void SetPropertyValueDelegate(Object obj, Object val, Object[] index);

 

        public void SetControlProperty(Control ctrl, String propName, Object val)

        {

            PropertyInfo propInfo = ctrl.GetType().GetProperty(propName);

            Delegate propertyDelegate = new SetPropertyValueDelegate(propInfo.SetValue);

            ctrl.Invoke(propertyDelegate, new Object[3] { ctrl, val, /*index*/null });

        }

 

        private void UpdateSent(string item)

        {

            _chat.AppendLine(item);

 

            if (this.SentTextBox.InvokeRequired)

            {   // This is a worker thread so delegate the task.

                SetControlProperty(SentTextBox, "Text", _chat.ToString());

            }

            else

            {   // This is the UI thread so perform the task.      

                this.SentTextBox.Text = _chat.ToString();

            }

 

        }

UpdateSent is example code on how to use the code. Also, _chat is a StringBuilder object. This code is taken from a chat program I wrote at where I work.

Tip Submitted By: David McCarter


 
Categories: Csharp | VB.NET | WinForms

December 19, 2008
@ 02:31 PM

Deep Zoom Composer is a tool to allow the preparation of images for use with the Deep Zoom feature currently being previewed in Silverlight 2. The new Deep Zoom technology in Silverlight allows users to see images on the Web like they never have before. The smooth in-place zooming and panning that Deep Zoom allows is a true advancement and raises the bar on what image viewing should be. High resolution images need to be prepared for use with Deep Zoom and this tool allows the user to create Deep Zoom composition files that control the zooming experience and then export all the necessary files for deployment with Silverlight 2.

https://www.microsoft.com/downloads/details.aspx?FamilyID=457B17B7-52BF-4BDA-87A3-FA8A4673F8BF&displaylang=en


 
Categories: News | Silverlight

Did you know that with .NET you can use COM components without registering them? Well you can if you are using ClickOnce. Check out this article: http://msdn.microsoft.com/en-us/library/ms165432.aspx

 

 


 
Categories: .NET | Link | ClickOnce

December 8, 2008
@ 05:32 PM

Prepare images for use with the Deep Zoom feature in Silverlight 2.

http://www.microsoft.com/downloads/details.aspx?FamilyID=457B17B7-52BF-4BDA-87A3-FA8A4673F8BF&displaylang=en


 
Categories: News | Silverlight

December 1, 2008
@ 11:42 AM

If you live in the San Diego area, dotNetDave (a.k.a. David McCarter) will be teaching a 6 week Building Rich & Interactive Web Applications with ASP.NET AJAX course at the University of California, San Diego Extension beginning on Thursday 1/7/2009 from 5:30pm to 10pm. For more information and to enroll, please click here.


 
Categories: AJAX | ASP.NET | dotNetDave

November 19, 2008
@ 12:05 PM
The Visual Round Trip Analyzer tool helps web developers and testers visualize the download of their page, identify best practices and changes that improve web performance. The network Round-Trip between the client and server(s) is the single biggest impact to web page performance – much greater than server response time. VRTA examines the communications protocol, identifying the causes of excessive round-trips, and recommending solutions. Performance engineers, testers, developers, operations personnel should use VRTA to conduct their web performance analysis.
 

 
Categories: ASP.NET | News

Microsoft .NET Framework 3.5 Service Pack 1 is a full cumulative update that contains many new features building incrementally upon .NET Framework 2.0, 3.0, 3.5, and includes cumulative servicing updates to the .NET Framework 2.0 and .NET Framework 3.0 subcomponents.

http://www.microsoft.com/downloads/details.aspx?FamilyID=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en


 
Categories: .NET | News

October 29, 2008
@ 01:21 PM

Small Basic is a project that's aimed at bringing "fun" back to programming. By providing a small and easy to learn programming language in a friendly and inviting development environment, Small Basic makes programming a breeze. Ideal for kids and adults alike, Small Basic helps beginners take the first step into the wonderful world of programming.

Check it out by going to: http://msdn.microsoft.com/en-us/devlabs/cc950524.aspx


 
Categories: Link

October 29, 2008
@ 01:01 PM
Learn about the future of VB.NET!

http://code.msdn.microsoft.com/vbfuture

Here is some of what is new:

* sub lambdas, and multiline sub/function lambdas

* sub lambdas, and multiline sub/function lambdas

* AsParallel. (well, this was a plinq feature rather than a VB feature, but cool as heck)

* DLR interop: invoke DLR methods from VB; create dynamic objects from VB; pass .net objects to DLR code; pass DLR objects to VB code. Note: unfortunately, this feature wasn’t ready in time for inclusion in the CTP.

* array literals, including inference of array structure (e.g. {{1,0},{0,1}} and {({1,2,3,4}),({1,2})}

* collection initializers: “dim x as new dictionary(of string,integer) from {{“hello”,1},{“world”,2}}

* auto-implemented properties, including initializers for them

* generic co- and contra-variance. Note: the VB support for co- and contra-variance was in the CTP. Unfortunately the covariant version IEnumerable(Of Out T) wasn’t ready in time for inclusion in the CTP, nor any of the other BCL classes. Also the CTP has a crummy bug that’s my fault which crashes when you use variance as part of overload resolution.

* line continuations (also www.unemployedunderscores.com!)

* No-PIA
 
Categories: Link | VB.NET

October 29, 2008
@ 12:57 PM
Learn about the future of C#!

http://code.msdn.microsoft.com/csharpfuture


 
Categories: C# | Link

If you came to my talk at the OC .NET User group meeting today, below is a link to the presentation. Enjoy!

Why You Need .NET Coding Standards (2008)

Why You Need .NET Coding Standards-2008.pdf (941.06 KB)

Link to my book: http://www.cafepress.com/geekmusicart.165478704


 
Categories: Csharp | Defensive Programming | dotNetDave | VB.NET

Redmond, Wash. — Oct. 13, 2008 — Microsoft Corp. today announced the availability of Silverlight 2, one of the industry’s most comprehensive and powerful solutions for the creation and delivery of applications and media experiences through a Web browser. Silverlight 2 delivers a wide range of new features and tools that enable designers and developers to better collaborate while creating more accessible, more discoverable and more secure user experiences.

Microsoft also announced further support of open source communities by funding advanced Silverlight development capabilities with the Eclipse Foundation’s integrated development environment (IDE) and by providing new controls to developers with the Silverlight Control Pack (SCP) under the Microsoft Permissive License.

“We launched Silverlight just over a year ago, and already one in four consumers worldwide has access to a computer with Silverlight already installed,” said Scott Guthrie, corporate vice president of the .NET Developer Division at Microsoft. “Silverlight represents a radical improvement in the way developers and designers build applications on the Web. This release will further accelerate our efforts to make Silverlight, Visual Studio and Microsoft Expression Studio the preeminent solutions for the creation and delivery of media and rich Internet application experiences.”

Silverlight adoption continues to grow rapidly, with penetration in some countries approaching 50 percent and a growing ecosystem that includes more than 150 partners and tens of thousands of applications. During the 17 days of the 2008 Olympics Games in Beijing, NBCOlympics.com, powered by Silverlight, had more than 50 million unique visitors, resulting in 1.3 billion page views, 70 million video streams and 600 million minutes of video watched, increasing the average time on the site (from 3 minutes to 27 minutes) and Silverlight market penetration in the U.S. by more than 30 percent. Broadcasters in France (France Televisions SA), the Netherlands (NOS), Russia (Sportbox.ru) and Italy (RAI) also chose Silverlight to deliver Olympics coverage online. In addition, leading companies such as CBS College Sports, Blockbuster Inc., Hard Rock Cafe International Inc., Yahoo! Japan, AOL LLC, Toyota Motor Corp., HSN Inc. and Tencent Inc. are building their next-generation experiences using Silverlight.

“CBS College Sports Network streams more than 20,000 hours of live content annually for our 150-plus college and university official athletic partners, so we demand that our video player environment be both consumer friendly and robust,” said Tom Buffolano, general manager and vice president, Digital Programming and Subscription, CBS Interactive-Sports. “Silverlight was the perfect choice to help develop and power our new, exclusive online collegiate sports experience, as it features the best price and performance of any streaming media solution on the market today. Silverlight also gives us the most flexibility in expanding the product in the future as we develop embeddable players and mobile platforms and explore new advertising integration opportunities.”

Continued Commitment to Openness and Interoperability

Microsoft announced plans to support additional tools for developing Silverlight applications by providing funding to Soyatec, a France-based IT solutions provider and Eclipse Foundation member, to lead a project to integrate advanced Silverlight development capabilities into the Eclipse IDE. Soyatec plans to release the project under the Eclipse Public License Version 1.0 on SourceForge and submit it to the Eclipse Foundation as an open Eclipse project.

Microsoft also will release the Silverlight Control Pack and publish on MSDN the technical specification for the Silverlight Extensible Application Markup Language (XAML) vocabulary. The SCP, which will augment the powerful built-in control set in Silverlight, will be released under the Microsoft Permissive License, an Open Source Initiative-approved license, and includes controls such as DockPanel, ViewBox, TreeView, Accordion and AutoComplete. The Silverlight XAML vocabulary specification, released under the Open Specification Promise (OSP), will better enable third-party ISVs to create products that can read and write XAML for Silverlight.

“The Silverlight Control Pack under the Microsoft Permissive License really addresses the needs of developers by enabling them to learn how advanced controls are authored directly from the high-quality Microsoft implementation,” said Miguel de Icaza, vice president, Engineering, Novell. “By using the OSP for the Silverlight vocabulary, they further solidify their commitment to interoperability. I am impressed with the progress Microsoft continues to make, and we are extremely satisfied with the support for Moonlight and the open source community.”

Beyond funding development in the free Eclipse IDE, Microsoft currently delivers state-of-the-art tools for Silverlight with Visual Studio 2008 and Expression Studio 2. In addition, support is now extended to Visual Web Developer 2008 Express Edition, which is a free download.

“We wanted to build a cutting-edge, rich Internet application that enables our customers to search our vast database of content and metadata so they can access movie reviews, watch high-quality movie trailers, and either rent or buy movies from our new MovieLink application,” said Keith Morrow, chief information officer, Blockbuster. “Because Silverlight 2 now includes several new rich controls such as data grids and advanced skinning capabilities, as well as support for the .NET Framework, allowing us to access our existing Web services, we were able to easily maintain the high standards of the Blockbuster brand and bring the application to market in record time.”

Delivering Features for Next-Generation Web Experiences

Highlights of new Silverlight 2 features include the following:

.NET Framework support with a rich base class library. This is a compatible subset of the full .NET Framework.

Powerful built-in controls. These include DataGrid, ListBox, Slider, ScrollViewer, Calendar controls and more.

Advanced skinning and templating support. This makes it easy to customize the look and feel of an application.

Deep zoom. This enables unparalleled interactivity and navigation of ultrahigh resolution imagery.

Comprehensive networking support. Out-of-the-box support allows calling REST, WS*/SOAP, POX, RSS and standard HTTP services, enabling users to create applications that easily integrate with existing back-end systems.

Expanded .NET Framework language support. Unlike other runtimes, Silverlight 2 supports a variety of programming languages, including Visual Basic, C#, JavaScript, IronPython and IronRuby, making it easier for developers already familiar with one of these languages to repurpose their existing skill sets.

Advanced content protection. This now includes Silverlight DRM, powered by PlayReady, offering robust content protection for connected Silverlight experiences.

Improved server scalability and expanded advertiser support. This includes new streaming and progressive download capabilities, superior search engine optimization techniques, and next-generation in-stream advertising support.

Vibrant partner ecosystem. Visual Studio Industry Partners such as ComponentOne LLC, Infragistics Inc. and Telerik Inc. are providing products that further enhance developer capabilities when creating Silverlight applications using Visual Studio.

Cross-platform and cross-browser support. This includes support for Mac, Windows and Linux in Firefox, Safari and Windows Internet Explorer.

More information and details about Silverlight 2 are available by reading the Silverlight 2 fact sheet at http://www.microsoft.com/presspass/presskits/silverlight/default.mspx.

Get Silverlight 2

Silverlight 2 will be available for download on Tuesday, Oct. 14, at http://www.microsoft.com/silverlight. Customers already using a previous version of Silverlight will be automatically upgraded to Silverlight 2.


 
Categories: News | Silverlight

Two new technologies, the Entity Framework (EF) and ADO.NET Data Services were released with .NET 3.5 SP1 in August 2008. These two major editions to the framework finally provide true data modeling and an easy way to send the data across a WCF service. Making programming the data tier much easier (kind of). Since these technologies are so new there is not a lot of good information out there and a lot of what you can find is a lot of "fluff"... not much "real world" solutions. Since I have been actively been using this where I work since it came out in a "real" project, I thought I would share what I have learned. This will be a living blog post, meaning that as I find things I will update it. So check back often.

One thing I should mention is that the project I am working on is converting VB6 code to C#. We use SQL Server 2005 with most all of the data access going through stored procedures. Most of the sp's I have seen so far are simple selects and inserts or selects based on a parameter. So these are ideal candidates for just letting the EF create the SQL dynamically.

Entity Framework

Design Considerations

When starting this project I chose to create an assembly just for the Entity Data Model's. This way, down the road it could easily be shared with another applications. I chose the naming scheme for the assembly of: MyCompay.Project.Data.Entities.dll (of course replace "MyCompany" and "Project" with your company name and project name). This works great since by default entity type access is public.

There is one caveat with this, when you configure your entities, connections are created in the app.config file that look like this:

<configuration>

  <connectionStrings><add name="MyEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=MyServer;Initial Catalog=MyApplicationDB;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

</configuration>

This issue is when you reference this assembly in your WCF project (see more below), you will need to move the connection strings information to the web.config file under the <system.web> section.

Creating Your Entity Data Model

When I first started going though the VB6 project, I searched for sp calls or dynamic sql. As I saw these statements I added the appropriate tables to my data model. This worked great until I found the last table that was actually "root" table for the application. For example a Customer table that has a primary key that most if not all other tables rely on. While the designer correctly created the relationships, they never seemed to work correctly. I kept getting errors. So always add the "root" table first when creating your data model.

ADO.NET Data Services

Design Considerations

With the project I'm working on, there are multiple assemblies that will end up needing to connect to the Data Service to retrieve data. Because of this and the need to pass around the same "proxy" object, I decided to wrap the Data Service proxy in a separate assembly. The naming scheme I used for the assembly is: MyCompay.MyProduct.Data.ServiceProxy.dll  (of course replace "MyCompany" and "Project" with your company name and project name). By default the proxy object created to the Data Service is public so it's easily used by any other assembly. Also, configuration is easy since the location of the service is defined in one place in this assemblies app.config file.

LINQ

With the Data Services, LINQ can be used to call the service. This is great for the programmer since there is no need to master REST. Your LINQ statement will be automagically turned into REST. But be forewarned that at this point LINQ does not support all of REST. So you can write your LINQ statement, it will seem correct, but nothing will come back from the service. Most of the time there will be no warning or Exception either. So, if you are not getting data back, look at your LINQ query.

Loading Data

Retrieving data from a data service using LINQ is really simple. In my class I declare:

MyEntities _serviceProxy = new MyEntities();

Client _client;

Then to load, simply do the following LINQ statement:

_client = (from cl in _serviceProxy.Clients where cl.ClientId == this.ClientId select cl).Single<Client>();

This performs a call to the Data Service and returns a single Client object using a REST query simular to this:

http://localhost:4437/Services/MyDataService.svc/Clients('1')

To load child objects simply code the following:

_serviceProxy.LoadProperty(_client, "Accounts");

 

_serviceProxy.LoadProperty(_client, "Categories");

Each of the LoadProperty methods above will create a call to the Data Service. These calls can be batched to reduce network traffic, but you will basically have to write the REST queries manually... something I have not tackled yet.

Data Joins

Joins are not supported in Data Services because they are not supported in REST. But if you need to join data to display it in a grid etc, you can do it like you would do it in EF. For it to work the data will have to be preloaded into memory from the Data Service. The join would look similar to this:

var data = (from a in _client.Accounts

            join ac in _client.Categories on a.CatagoryId equals ac.Id into cat

            from c in cat.DefaultIfEmpty()

            orderby a.Type, a.Number

            select new

            {

                a.Id,

                a.Department,

                a.Number,

                a.Description,

                a.Type,

                a.IsTaxable,

                a.IsActive,

                Code = c == null ? string.Empty : c.Code

            }).Distinct();

 

accountGridView.DataSource = data.ToArray();

In the code above, cat.DefaultIfEmpty() is very important because if there is no match between Account and Category, then no data at all will be returned! Then in the last line of the select, it's also important to check for null, since "c" could be null and will throw an exception if you try to access one of its properties.

Now that you have your data into the grid control (DataGridView) you are going to run into another problem... retrieving the data from the DataSource! Since the data has been loaded as an anonymous type it can't be converted back. Also, since I chose not to show the Id property in the grid, I simply can not look at the first column.

So in my case, I only want the Id value of the row the user clicked on, from there I can use LINQ to look up the Account and what ever else I need to display more detailed data etc. For this we are going to have to use reflection.

private void accountGridView_SelectionChanged(object sender, EventArgs e)

{

     var data = accountGridView.Rows[accountGridView.SelectedRows[0].Index].DataBoundItem;

     var propInfo = data.GetType().GetProperty("Id");

     var propValue = (Int32)propInfo.GetValue(data, null);

 

     LoadAccountDetail((from acc in _client.Accounts where acc.Id == propValue select acc).Single());

}

As you can see in the code above we are using reflection and GetProperty to retrieve the value for Id from the grid DataBoundItem which I then use in the LINQ statement to retrieve the Account object.

Updating Data

One of the great things about the Entity Framework is the built in state tracking. This make is really simple to update, insert and delete object (data) with a single method call. Unfortunately, as soon as you serialize an EF object across the wire using any service including ADO.NET Data Service, this tracking is gone for the most part. Though Microsoft has promised to make this better in upcoming releases, for now we have to do it a little more manually, but still is pretty easy. You just need to remember this when using objects coming from a Data Service.

To update an object, simply change it's properties and then do the following:

_serviceProxy.UpdateObject(currentAccount);

 

_serviceProxy.SaveChanges();

Calling SaveChanges will make a call to the DataService. You can make as many calls to UpdateObject, AddObject and DeleteObject as needed before the SaveChanges call.

Service Methods

What's Not Supported
  • Enum parameters: I wanted to do this to send back different data based on an enum parameter (just like I do in normal programming). This is a perfect job for service methods. Unfortunately, I was told by Microsoft that it's not supported in "this release". They did not indicate if it will be supported in a future release.

"Good" Resources


 
Categories: ADO.NET | Csharp | Entity Framework | LINQ | WCF

If you are interested in using LINQ to read Xml instead of the older way of the XmlDocument and SelectNodes, the code below is a pretty good example. The code takes in the ISO standard file for country names and codes (see sample below) and turn it into a list of Country objects for use in an application including ComboBoxes.

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>

<ISO_3166-1_List_en xml:lang="en">

   <ISO_3166-1_Entry>

      <ISO_3166-1_Country_name>AFGHANISTAN</ISO_3166-1_Country_name>

      <ISO_3166-1_Alpha-2_Code_element>AF</ISO_3166-1_Alpha-2_Code_element>

   </ISO_3166-1_Entry>

   <ISO_3166-1_Entry>

      <ISO_3166-1_Country_name>ÅLAND ISLANDS</ISO_3166-1_Country_name>

      <ISO_3166-1_Alpha-2_Code_element>AX</ISO_3166-1_Alpha-2_Code_element>

   </ISO_3166-1_Entry>

</ISO_3166-1_List_en>

Before

Here is the original code that has been in use for a few years. It uses the "easy" way of loading and selecting nodes using the XmlDocument object.

Dim countriesXml As New System.Xml.XmlDocument

countriesXml.LoadXml(My.Resources.CountriesXML)

 

Dim list As New System.Collections.Generic.List(Of Country)

 

For Each country As System.Xml.XmlNode In countriesXml.SelectNodes("//ISO_3166-1_Entry")

 

   Dim tempCountry As New Country

 

   tempCountry.Name = country.SelectSingleNode("ISO_3166-1_Country_name").InnerText

   tempCountry.Code = country.SelectSingleNode("ISO_3166-1_Alpha-2_Code_element").InnerText

 

   list.Add(tempCountry)

 

Next

 

After

This code uses LINQ and the new XElement to make it easy to load the xml from the assemblies resources.

Dim reader = XElement.Parse(My.Resources.Countries)

 

Dim list As New System.Collections.Generic.List(Of Country)

 

Dim data = From c In reader.Elements(XName.Get("ISO_3166-1_Entry")) _

           Order By c.Element(XName.Get("ISO_3166-1_Country_name")).Value _

           Select New Country With {.Name = c.Element(XName.Get("ISO_3166-1_Country_name")).Value, _

                            .Code = c.Element(XName.Get("ISO_3166-1_Alpha-2_Code_element")).Value.ToUpper}

 

As you can see this is much cleaner, fewer lines of code and actually faster (1 millisecond). Also you can see in the Select line that I am actually filling the Country object during the query... pretty cool!

Tip Submitted By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


 
Categories: LINQ | VB.NET | XML

If you are going to attend tonights meeting of the ASP.NET user Group SIG, below is the presentation download. I hope to see everyone at the meeting!

Building Rich & Interactive Web Applications with ASP.NET AJAX Part 2 - 2008.pdf (877.42 KB)
 
Categories: AJAX | ASP.NET | dotNetDave | JavaScript

If you are coming to the San Diego .NET Developers Group meeting tonight I hope you will be their early for my talk titled "What’s New In VS 2008 SP1". Lots of new additions to this SP, not just bug fixes. Below is a link to the presentation.

VS2008Sp1.pdf (715.88 KB)
 
Categories: .NET | ADO.NET | AJAX | ASP.NET | Csharp | dotNetDave | Entity Framework | LINQ | MVC | Silverlight | VB.NET | VS.NET | WCF | WinForms | WPF

September 2, 2008
@ 11:36 AM
If you live in the San Diego area, dotNetDave (a.k.a. David McCarter) will be teaching a 6 week Fundamentals of the .NET Framework course at the University of California, San Diego Extension beginning on Thursday 9/24/2008 from 5:30pm to 9:15pm. For more information and to enroll, please click here.
 
Categories: .NET | C# | dotNetDave | VB.NET