Apr 13
VN:F [1.6.7_924]
Rating: 5.3/7 (3 votes cast)

This post is about a simple application that I’ve created to get my hands on Silverlight 2. It is simple Digital Clock which shows local time using custom fonts and updates itself every second. My few observations that I would like to share with you:

Demo Application

  1. Custom Font Embedding in Silverlight
  2. Data Binding Modes and using INotifyPropertyChanged
  3. Using Dispatcher.BeginInvoke()

Before we start digging each of above topics lets first have a look at the application in running condition. I have named it SilverTimer.


Download: SilverTimer Source (C#/VS 2008)


Custom Font Embedding in Silverlight

I have used custom fonts (courtesy: DS-DIGI.TTF) in my SilverTimer application. These fonts are first downloaded automatically by the Silverlight Runtime. Here is excerpt showing how to embedd custom fonts -


FontFamily is comprise of this format – FONT_FILE#FONT_NAME. Having said that font file is “DS-DIGI.TTF” and the font named “DS-Digital” and are separated by‘#’. The real beauty is that we need not write any single line of code for downloading the font-file. Just keep DS-DIGI.TTF file “ClientBin” folder where the XAP file is located. One thing to note here is that before you use custom font you need to change the Build Action for your Font file to ‘Resource’ as shown below. This will make it as an assembly resource.

Digital_prop

This is all you have to do to use the custom fonts. If you wish to know more about custom font embedding, you can watch this great video tutorial by Tim Heuer

Data Binding Modes and using INotifyPropertyChanged

I’d like to discuss it in three basic Steps

  1. Specifying DataBinding Mode
  2. Set the DataContext
  3. Implement INotifyPropertyChanged interface to the business object

Silverlight supports binding of Business Object properties with the UI Controls. The data flow between these can be controlled by specify the Data Binding Mode between source and target. Here source is the Business Object and target is the UI control. Modes supported are -

OneWay” – Binds source and target and update target subsequently as the source gets updated. (source -> target)
TwoWay” – It keeps source and target in sync. Source is updated when a target changed and vice versa. (source <-> target)
OneTime” – As the name suggest, it updates target with the data and never updates when a source get updated.

In application, I’ve used ‘OneWay’ Binding Mode to update the Time in application. Below is the excerpt from Page.xaml -


Here we are talking about this bit  “Text=”{Binding CurrentTime, Mode=OneWay}”, You can see the Text property is bind to the CurrentTime property and the mode is defined as ‘OneWay’.

Now, we need to specify which Object this property is associated with. We have to set the DataContext of target control to the Business Object. It goes like this -

txtTimer.DataContext = objTimer;

Specifying the Mode doesn’t do the job we need some mechanism/event which tells the UI controls (TextBlock) to update itself when a property of business object changed. This can be achieved by implementing the INotifyPropertyChanged interface to the business object. The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. In this case Timer.cs is the business object that implemented this interface and should raise a PropertyChanged event when “CrrentTime” is changed. -

        public string CurrentTime
        {
            get
            {
                return currentTime;
            }
            set
            {
                currentTime = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,new PropertyChangedEventArgs("CurrentTime"));
                }
            }
        }
  .. .. ..

Whenever the CurrentTime property changed it notify the clients and they will be updated accordingly. You can go through this excellent video tutorial by Jesse Liberty

Using Dispatcher.BeginInvoke()

Dispatcher.BeginInvoke is used to execute the delegate asynchronously. Dispatcher is associated with the thread which is UI thread in this case. Why we need to use this? Form controls should be accessed in a thread which they have been created. Doing otherwise may throw “Invalid Cross-thread access” exception.

So, as soon as “CurrentTime” property is changed, the binding controls will be notified which is trigger by the “PropertyChanged Event” of “INotifyPropertyChanged” interface. But as this happen in a new thread this cause “Invalid Cross-thread access” exception.

The key to resolve this error is to update the “CurrentTime” property using dispatcher which guarantees the code to be executed on UI thread.

         public void RunTimer(object oDispatch)
        {
            while (true)
            {
                // Making asynchronous call to update the Texblock using the UI Thread.
                ((Dispatcher)oDispatch).BeginInvoke(() =>
                   {
                       //Updating the property which inturn notify the clients to udpate.
                       this.CurrentTime = System.DateTime.Now.ToLongTimeString();
                   }
               );

                // New thread sleeps for one second.
                System.Threading.Thread.Sleep(1000);
            }
        }

I hope you may have find this information useful. I would like to hear your comments and queries on this.

Tagged with:
Mar 31
VN:F [1.6.7_924]
Rating: 7.0/7 (1 vote cast)

Asp.net configuration file, web.config (machine.config at server level)  applies to the directory in which it appears and all sub – directories. The configuration file hierarchy for a Asp.net site goes as shown below.

Asp.net Configuration File Hierarchy

Here is a link where you can read more about web.config inheritance. While settings are inherited from the higher level of configuration file, child configuration files are always permitted to override them. Inheritance downward is useful for applying a unique settings for all applications on server but in certain situation a higher config file may want to prevent inheritance in child applications. This can be achieved by using the <location> element as follows.

<location path="." inheritInChildApplications="false">
<system.web>
...
...
</system.web>
</location>

The above code can prevent inheriting the <system.web> element in this case, into the child web application. Please note that this piece of code should be placed in the parent’s web.config file.

Tagged with:
Sep 05
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

If you ever tried or try to bind an Repeater control with a data source that have a period or dot in its one/more data item’s name then you might receive a error while binding the property using DataBinder.Eval method.

For Example, I was trying to do a simple thing with Asp Repeater control (which is bind to a DataTable). Please see the following piece of code


<%# DataBinder.Eval(Container.DataItem, “alt.price”)%>

Here is a column name “alt.price” in the data source (DataTable) . But the above line was resulting an error as follows

DataBinding: ‘System.Data.DataRowView’ does not contain a property with the name ‘alt’

To resolve this issue I used a new Method ‘DataBinder.GetPropertyValue’ that simply retrieves property value without any evaluation on the expression while DataBinder.Eval method uses reflection to parse and evaluate a data-binding expression against an object at run-time.

Conclusion – If you don’t want that the expression to be evaluated at the run time, it’s a good practice to use GetProtperyValue method instead of Eval method.

Nov 22
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

Visual Studio 2008 with .Net 3.5 has been released on November 19, 2007 and available for download at Microsoft’s Website. It is not an ordinary release with some common updates and extensions. VS2008 comes up with lots of exciting features for developers. Some of the main features are:

VS 2008 Multi-Targeting Support.
ASP.NET AJAX and JavaScript Support.
VS 2008 Web Designer and CSS Support.
Language Improvements and LINQ.
Data Access Improvements with LINQ to SQL.
Browsing the .NET Framework Library Source using Visual Studio.

You can find the detail explanation of above features at ScottGu’s Blog.

Tagged with:
Nov 18
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

I’ve finished my first dasblog macro that was created by me. It’s an Ajax enabled Shout-box. Still it is under testing and enhancement. Let me tell you it took me two full weekends to get this done. It was quite a good work behind this. But I am happy that I am seeing it running and working perfectly. Initially, I have added it on my blog (see the right navigation) for testing purpose only. Some of the main features are:-

a) XML Database (All entries are stored in XML File. It can be kept under the content directory of blog)
b) Ajax Enabled – No Iframe or refreshing of whole page. Update shoutbox silently and regularly after specified interval.
c) Customizable CSS – I tried to make it very customizable. It can gel with any theme perfectly.
d) Support New dasBlog version 2.0 (with Asp.net 2.0)

I’d appreciate any feedback, comments or error from you. It will be available for download, once I make necessary changes on the basis of feedback received.

Tagged with:
Oct 30
VN:F [1.6.7_924]
Rating: 6.0/7 (1 vote cast)

If you install IIS after .Net 2.0 or Visual studio 2005, you may receive “Failed to access IIS metabase” error. To resolve this issue either you need to install .Net framework again after IIS or you can do the following…

You can use the aspnet_regiis utility comes with .Net framework 2.0. This is an administrator utility to install or uninstall Asp.Net on local server/machine. To run this utility through command prompt move to C:\Windows\Microsoft.Net\Framework\v2.0.50727 and type (without quotes)

“aspnet_regiis -i ”


This will install the ASP.Net and update and upgrade the scriptmaps at the IIS metabase root and in below the root. In certain cases, a particular user account doesn’t have access to IIS metabase. Such condition will result the same error. However, in this case you can simply grant access to user account using…

“aspnet_regiis –ga (user_account_name)”

Tagged with:
Oct 25
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

Recently, I have joined NIIT Technologies Ltd, New Delhi (http://www.niit-tech.com/). It’s well known around the world for its remarkable software services in Travel and Transport domain. It’s been few weeks since I have joined but no project allocated to me yet. So I decided to brush up my skills and drill down in State Management Techniques in ASP.Net. I have planned to cover it all gradually. I have started with ViewState, here are some important points about it.

View state is state management technique at the page level. (between the round-trips on same aspx page.)

Veiw state save the information by serializing it into base64 encoded strings.

View state can be saved in another location such as SQL server database by implementing the cusom PageStatePersister class

You can save the information in ViewState (is a dictonary containing key/values pair) between page round trips.

View state data is first converted in to XML and then encoded using base64 encoding.

View State can store following types of objects:
Strings
Integers
Boolean values
Array objects
ArrayList objects
Hash tables
Custom type converters (see the TypeConverter class for more information)
(To store other types of objects class must be compiled with Serializable attribute.)

MaxPageStateFieldLength (page attribute) specifies the amount of maximum data that can be stored in  viewstate. The page split viewstate into multiple hidden fields if the data exceed this limit.

Changes to view state can be made until the PreRenderComplete event. It means that once a page is rendered changes to viewstate will not be saved.

More about ViewState

Tagged with:
Sep 17
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

In .Net Package Class act as a container that holds multiple types of objects in the hierarchical manner. Each object in hierarchy of Package is known as its Part. Essentially, this Class eases the access of a package and its parts in more efficient and useful manner. .Net 3.0 introduced a new assembly named windowsbase.dll which contains the System.IO.Packaging Namespace. This assembly is required for accessing the functionality of Packaging Classes. You may need to reference the assembly in Visual Studio before adding the namespace in your Asp.Net page. The default location is C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0
Once reference is added you can use open method of Package class to open a package. Given below is the method to open a XLSX Document using the Package class open method.

Public Function

 

OpenPackage(ByVal XLSXPath As String) As Boolean

    Dim oXlPackage As Package

    If XLSXPath <> “” Then

        oXlPackage = Package.Open(oPath, FileMode.Open, FileAccess.ReadWrite)

    End If

End Function

Package is a abstract class, ZipPackage is derived from Package that is used by the open method by default. Its mean ZipPackage is default type of Package and this is used by open method.

Tagged with:
Aug 14
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

Points to remember about APP_CODE Directory

  • Asp.net handles the files in bin and app_code folder in a special way.
  • The compiled classes (dll) placed in bin folder are automatically available to all the pages in application. We don’t need to register the assemblies to use them. Asp.net automatically detects the new version of assembly and start using the new one.
  • Assemblies in the bin folder have application scope. They cannot access the resources outside the current web application.
  • The access levels of assemblies are determined by the trust level specified by the local computer.
  • By default code run in full trust under visual studio development environment.
  • We can store and create as many folder and files (class files) in app_code folder. But Asp.net still compile all in a single assembly.
  • As Asp.net compiles all the code (App_code) in a single assembly, all files must be of same programming language. Ex – App_Code folder cannot contain code in both VB.Net and C#. However we can make settings in web.config to configure the code subdirectories in different compliable units. The configuration is specified by creating a “codeSubDirectories” element in the compilation element of the Web.config file. Ex –

<compilation debug=”false”>
    <codeSubDirectories>
        <add directoryName=”VBCode” />
        <add directoryName=”CSCode” />
    </codeSubDirectories>
</compilation>

Tagged with:
Jul 17
VN:F [1.6.7_924]
Rating: 0.0/7 (0 votes cast)

This weekend I have added some Technical Interview questions in my site. This part is still in progress. I could have added them much earlier but there was some URL Rewriting problem. Anyway I have published them without using URL Rewrite module.
You can checkout that part here – .Net Interview Questions (removed)


ASP.Net Inverview Question

Vb.net Interview Questions

.Net Framework

Tagged with:
preload preload preload