by Malav
19. August 2010 21:18
Event-driven applications play crucial role in usability as it allows an end-user to run multiple tasks simultaneously and receive notifications of progress on each of those tasks. Often, developers run into scenario where they have a class (call it classA) that utilizes BackgroundWorker (a class that executes an operation on a separate thread) and this class also collects and reports progress of this supposedly long running task. Now, in order for another class (call it classB) to receive progress notifications from classA, the classA needs to expose event properties. See example below for more details, note that the example is collecting data synchronization progress between a client and server:
Code:
|
Public Class clsSyncManager Implements ISyncManager
'define event(s) Public Event SyncProgressChanged(ByVal sender As Object, _ ByVal e As ProgressChangedEventArgs) Public Event SyncProgressCompleted(ByVal sender As Object, _ ByVal e As RunWorkerCompletedEventArgs)
Private Sub BackgroundWorker_ProgressChanged(ByVal sender As System.Object, _ ByVal e As System.ComponentModel.ProgressChangedEventArgs)
'raise an event when progress changes RaiseEvent SyncProgressChanged(sender, e) End Sub
Private Sub BackgroundWorker_RunWorkerCompleted(ByVal sender As System.Object, _ ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) 'raise this event since sync process is appears to have been completed. RaiseEvent SyncProgressCompleted(sender, e)
'do other operation(s) below
End Sub End Class
Partial Public Class ucStatusBar
'declare variables Private WithEvents _startSync As New clsSyncManager
Private Sub Window_Loaded()
AddHandler _startSync.SyncProgressChanged, AddressOf ProgressBar_Update AddHandler _startSync.SyncProgressCompleted, AddressOf ProgressBar_Reset End Sub
Private Sub ProgressBar_Update(ByVal sender As Object, _ ByVal e As ProgressChangedEventArgs) _ Handles _startSync.SyncProgressChanged 'update the value of our progress bar syncProgress.Value = e.ProgressPercentage End Sub
Private Sub ProgressBar_Reset() 'reset the value of our progress bar syncProgress.Value = 0 End Sub End Class
|
Now, the above example is fairly straightforward in terms of implementation, you instantiate two events (one for progress changed, and the other for progress completed) in clsSyncManager (this would be classA). When a BackgroundWorker progress changes, you raise an event on SyncProgressChanged. And when the BackgroundWorker completes, you raise an event on SyncProgressCompleted. Also note that these two events are made public so another ucStatusBar class (this would be classB) can access and collect and update the progressbar accordingly.
For more information on this subject, please read Event-based Asynchronous Pattern Overview, Best Practices for Implementing the Event-based Asynchronous Pattern, and Implementing the Event-based Asynchronous Pattern
by Malav
3. August 2010 22:37
Being a developer, one ought to know the basics of security as it relates to business requirements and the application your are developing. Some applications require connection strings that points to specific services like SQL Server, Web address, or even a RSS feed url. Again, some of these services may or may not be protected but that is not the scope of this post, it is to bring this topic to your attention as you are developing applications. For example, if you are using SQLCE like myself, you will notice that initially it creates and stores connection string information directly to My.Settings (in VB.NET) or Properties.Settings (in C#), and many of the tutorials and articles follow the same way. However, as you are ready to begin publishing your application out or shall I say going in production, you may realize that this is definitely not secure in any form whatsoever as a perpetrator may get access to the deployed application on the client machine and use MSIL disassembler tool to retrieve connection string information (see Figure 1).
An easiest approach to solving this problem is to encrypt the connection string using ConnectionStringsSection class. I have attached the code for your review, please feel free to post comments or thoughts on this matter. I have written this in .NET Framework 4.0 but you can easily downgrade it to v3.x if you like.
For additional information on this topic see: Securing Connection Strings, Securing ADO.NET Applications, Encrypting Configuration Information Using Protected Configuration in ASP.NET
|

|
| Figure 1 - Unsecure Connection String |
Secure_ConnectingString.zip (32.72 kb)
by Malav
8. June 2010 21:04
In WPF, the most basic yet also the most important fundamental you will learn is laying out UI controls using different types of panels. As you may know, there are many types of panels that a developer/designer can utilize and understanding when to utilize which types is crucial as it can have a dramatic impact on overall performance of the application. For example, a canvas panel which uses XY coordinates to layout control(s) is the simplest and has very minimal impact on performance as the control(s) are fixed; however, a grid or wrappanel would be described as complex and intensive as it has functionalities such as redrawing UI elements in relation to resolution, and available space. And as more child elements are added to these complex panels, the impact on overall performance is quite noticeable. If you would like to learn in more detail on how layout system functions, head over to MSDN article that goes in-depth on this matter.
by Malav
3. June 2010 23:29
With all the sophisticated concepts and technologies we work on day to day basis as a programmer, sometimes we forget the most basic idea, and that is properly commenting on your code. I came across an article on MSDN the other day and wanted to bring this up to share with you folks on how you can use the commenting section of your code to develop comprehensive code documentation at the same time! Just to give you an example, I have a shared function that checks whether an internet connection is available by pinging a web address in specified amount of time, as you can see below...just above the function method the XML tags are automatically generated by typing three single-quotation marks (''') just above the definition. By filling in comments within those tags, and using Sandcastle tool provided by Microsoft, you can generate a nice looking documentation.
Code:
|
''' <summary> ''' Checks whether an internet connection is available. ''' </summary> ''' <param name="url">Enter a web address (ex: www.google.com).</param> ''' <param name="timeout">Enter a timeout value in milliseconds.</param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function isInternetAvailable(ByVal url As String, ByVal timeout As Integer) As Boolean
'check to see if we can ping a web address or not Try If (isNetworkAvailable()) Then If (My.Computer.Network.Ping(url.ToString, timeout)) Then Return True Else Return False End If Else Return False End If Catch ex As Exception 'something unexpected happened... Return False End Try End Function
|
by Malav
29. April 2010 09:27
In this post, I am going to talk about how to retrieve an image from a DataTable. Now, for those who don't know what DataTable is used for, it is in simplest terminalogy a single table stored in a memory. It is derived from ADO.NET libraries and provides easy to use data structure for mapping data objects.
If your project requires retriving an image from a SQL Database then your application need to extract binary data off of that database and convert it to a Bitmap object using MemoryStream. In order to get an image from a specified row, you need to provide a DataTable, column name, and an index of row where the image is located. See code below for more details...
Code:
#Region "Import Declaration(s)" Imports System.Data Imports System.IO #End Region
Module modGetImage
Public Function GetImage(ByVal dataTable As DataTable, ByVal columnName As String, _ ByVal i As Integer)
'create a bitmap object Dim bmp As New BitmapImage
Try 'get the image data stored in the datatable Dim row As DataRow = dataTable.Columns(columnName.ToString).Table.Rows.Item(i - 1)
'get the raw bytes of the image 'only if the row is NOT null If Not (CType(row(columnName.ToString), Byte()).GetType() Is GetType(System.DBNull)) Then Dim photoSource() As Byte = CType(row(columnName.ToString), Byte()) If (photoSource.Length <> 0) Then 'read the image into the bitmap object bmp.BeginInit() bmp.CacheOption = BitmapCacheOption.OnLoad bmp.StreamSource = New MemoryStream(photoSource) bmp.EndInit() bmp.Freeze() End If Else bmp = Nothing End If Catch ex As Exception bmp = Nothing End Try
Return bmp 'return the image End Function End Module
|
by Malav
9. April 2010 20:15
It amazes me everytime about the flexibilities that are allowed within WPF when I am working on small to large scale project(s). For instance, regardless of the scalibility or complexity of your project, you will definitely end up using resources (icons, data templates, themes, etc.) within WPF environment. And you know what that means, as the level of complexity of your project goes up, the need to implement a design that organizes these resources becomes rather high-priority on your to-do list. But with WPF, you have that capability in place and it is quite amazing I must say. Just to give you an example, you have a listview control that provides sorting capabilities and has header template arrows (see pic below) for visual representation to end-user of sorting direction.
One very simple method of achieving this is to include a data template within each window's resource path like the following:
<Window.Resources>
<!--DataTemplate for HeaderTemplate Arrows-->
<DataTemplate x:Key="HeaderTemplateArrowUp" >
<DockPanel>
<TextBlock HorizontalAlignment="Center" Text="{Binding}" />
<Path x:Name="arrow" StrokeThickness="1" Fill="Gray"
Data="M 5,10 L 15,10 L 10,5 L 5,10" />
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowDown" >
<DockPanel>
<TextBlock HorizontalAlignment="Center" Text="{Binding}" />
<Path x:Name="arrow" StrokeThickness="1" Fill="Gray"
Data="M 5,5 L 10,10 L 15,5 L 5,5" />
</DockPanel>
</DataTemplate>
</Window.Resources>
The above method certainly works but what if you have 10+ windows and user controls on a large project that make use of this resource all the time? This is where the second approach comes into play, it provides a much more easier and cleaner way of organizing your code. You would need to move the data template in a ResourceDictionary file (see attached) and set it's build action to Resource. Once you have done that you need to merge this ResourceDictionary you just created under the Application.xaml file under MergedDictionaries (see code below).
<Application.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/ResourceDictionaries/ExpanderStyle.xaml" />
<ResourceDictionary Source="/Resources/ResourceDictionaries/ListViewStyle.xaml" />
<ResourceDictionary Source="/Resources/ResourceDictionaries/TextBlockStyle.xaml" />
<ResourceDictionary Source="/Resources/ResourceDictionaries/TextBoxStyle.xaml" />
<ResourceDictionary Source="/Resources/ResourceDictionaries/StackPanelStyle.xaml" />
<ResourceDictionary Source="/Resources/ResourceDictionaries/HeaderTemplateArrows.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
It's not over just yet, we are very close, in this scenario, we still need to specify (this time behind-the-code) to use this data template like this:
headerClicked.Column.HeaderTemplate = Application.Current.Resources("HeaderTemplateArrowUp")
So when a user clicks a header, the above code tries to locate "HeaderTemplateArrowUp" resource key and off it goes!
|

|
HeaderTemplateArrows.xaml (861.00 bytes)
by Malav
22. March 2010 20:51
Recently I have been doing quite a bit of research on the FeedSync that has recently been integrated within MSF v2.0. As the name suggests, FeedSync allows you to synchronize data (Atom/RSS format) across any device or network, you can read up more on this at Live Services website. When I first stumbled upon FeedSync, I decided to do more digging around on the web to find more informative articles on this subject and it surprised me how little had been published. If you are a developer, you can check out the sample code for both the client and server side, especially the NotePad example which illustrates the use of technology more in-depth. I will be posting an example on this subject soon, so check back soon!
by Malav
8. March 2010 22:49
For those of you who have experiemented with Visual Studio 2010 Beta release may already know about some of the features that lies within the new WPF-based IDE. Specifically, abilities to monitor each and every thread and provide visual representation to the developer to assess the overall performance of application. On the March 2010 issue of MSDN, Hazim Shafi wrote an article on this specific topic and how a developer can utilize Visual Studio 2010 to quickly monitor and track down bottlenecks. Check out the article for more in-depth information on this topic.
by Malav
4. November 2009 22:53
From the past year, I've been working on an n-tier project that involves synchronizing data from number of devices that are connected only limited amount of time (a.k.a occasionally connected devices). Depending on project requirements, you may possibly need to implement both database and file level synchronization capabilties into your application. Initially, the framework itself is fairly easy to understand and use; however, once you move further ahead from proof-of-concept to production-level application, it takes considerable amount of time to research, implement, and at the same time follow best practices.
Below you will find an example of SyncManager class that I wrote to perform database synchronization. You could certainly add more functionalities to this class, for example, you could write up methods to support not just database but also file/folder synchronization. If you have had prior experience working with BackgroundWorker class (executes time-consuming operations asynchronously on a separate thread), you will notice that this entire class runs on its own thread to process sync requests along with reporting synchronization progress. Feel free to post your thoughts/comments on this matter, I will be posting more material soon!
To use the provided class, you will need to create a new instance of SyncManager and set the worker by passing in the required parameters (see setWorker method).
Code:
|
'create a new instance of SyncManager Dim doSync As New SyncManager
'provide required parameters doSync.setWorker(bkgWorker, syncProg, True, True)
If (doSync.isBusy() = False) Then Me.syncProg.Value = 0 doSync.runAsync() End If
|
SyncManager.vb (5.41 kb)
by Malav
26. October 2009 21:43
Back when I was in college, I took a course in emerging network technologies and software applications and one of the most intriguing part of the course material was analyzing behavioral patterns of network(s) and how they react based on conditions (e.g. time, # of users connected at any give time, and type of protocol(s) used). During labs, we would make use of multiple software applications to conduct our studies and gather data. One of the software applications we used in our research was extraordinary in creating a live discrete simulated network flow which in turn provided us with valuable data to analyze later. The tool is called NS (Network Simulator) and is freely available and works both under linux and windows environment. The application provides support for TCP/UDP, routing, and wide variety of protocols used both over wired and wireless networks. If you are interested in learning more, head over to Worcester Polytechnic Institute's page which goes more in-depth into the application's functionality, and while you are there don't forget to check out some really cool examples of its capabilities and features.

