jQuery and ASP.NET

August 31, 2010

Change WPF DataGrid Row Color on Mouse Over

1 comments


In this short code snippet, I will explain how to change the look of the WPF DataGrid row display on a Mouse action (in this example, on MouseOver). In WPF using Style, the display and the behavior of any element can be changed by defining user input actions. The WPF styling and templating model enables you to specify triggers within your Style - known as PropertyTriggers. In this demo I have used a WPF DataGrid.

I have created a WPF 4.0 Application with following two classes:

public class clsEmployee
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
public int DeptNo { get; set; }
}

public class EmployeeCollection :
ObservableCollection<clsEmployee>
{
public EmployeeCollection()
{
Add(new clsEmployee() { EmpNo = 101, EmpName = "Ajay",
Salary = 56000, DeptNo = 10 });
Add(new clsEmployee() { EmpNo = 102, EmpName = "Vijay",
Salary = 46000, DeptNo = 20 });
Add(new clsEmployee() { EmpNo = 103, EmpName = "Bijay",
Salary = 26000, DeptNo = 30 });
Add(new clsEmployee() { EmpNo = 104, EmpName = "Sujay",
Salary = 16000, DeptNo = 40 });
Add(new clsEmployee() { EmpNo = 1051, EmpName = "Sanjay",
Salary = 36000, DeptNo = 50 });
}
}


The EmployeeCollection class is registered in the MainPage.Xaml to instantiate bind with the Grid element. The XAML code is shown below:

<Window x:Class="WPF_DataGrid_Property_Triggers.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WPF_DataGrid_Property_Triggers"
Title="MainWindow" Height="350" Width="525">
<Window.Resources><src:EmployeeCollection

x:Key="EmpDs"></src:EmployeeCollection>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="FontWeight" Value="ExtraBold" />
<Setter Property="Height" Value="20" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource EmpDs}}">
<DataGrid AutoGenerateColumns="False" Height="237"
HorizontalAlignment="Left" Margin="18,66,0,0" Name="dgEmp"
VerticalAlignment="Top" Width="466" ColumnWidth="*"
ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding EmpNo}"
Header="EmpNo" />
<DataGridTextColumn Binding="{Binding EmpName}"
Header="EmpName" />
<DataGridTextColumn Binding="{Binding Salary}"
Header="Salary" />
<DataGridTextColumn Binding="{Binding DeptNo}"
Header="DeptNo" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

The style defines trigger elements which acts when the user does a MouseOver on the DataGridRow. When this actions is satisfied, the look of the DataGrid Row will change. Run the application and the following result will be displayed:

image

August 30, 2010

Developers, there are Better Ways to Maintain your Notes

13 comments


I have been developing applications over the past 10 years, and I admit I do not have a long term memory, especially not when it comes to remembering a piece of code or technique, I had used in my previous projects. My memory acts alien especially at times when I need to remember a code snippet for the 11th-hour kinda fixes, which I wish I had documented, instead of choosing to be lazy.

It's true hard work never killed anybody, but I figure, why take the chance? ~Ronald Reagan

Many would agree that a good old notebook best serves the purpose, as it can be carried anywhere and requires only a pen/pencil to jot down your notes. However with time, we realize that paper notes becomes almost impossible to maintain (search, store, carry). I have seen some extremely-fond-of-notebook developers use a Livescribe Echo Smartpen which is a smart option, but then not everyone has that pen right?

Here are some tips to keep your developer notes in a more organized manner and make your life easier.

Tip 1:

A blog can be used as a developer’s journal. Blogging is an ultimate tool to keep your programming notes and refer to them later. Almost all popular blogs (like blogger, wordpress etc) give you an option to set up your blog for free, and with the help of plug-ins, you can even save your code snippets with syntax highlighting. Depending on how you configure it, you can choose to keep these notes to yourself or rather share your experiences with thousands of developers across the world and receive feedback on it (and also earn some extra money).

I speak out of experience. Blogging may look like a tedious thing to do initially, but once you get into the habit of recording notes in your blog, it does wonders for you later. This blog DevCurry.com is one and a half years old and there are over 600 posts here, all containing bits and pieces of our experiences, which have helped us and hundreds and thousands of developers as a reference, and will continue to do so.

Tip 2:

If you want to save only random bits of code, use an online tool called Snipplr . Snipplr lets you store your code at one place and you can share access to your code with other guys/gals at work. Another tool is Snipt where you can share your collection of frequently used commands or code snippets. If you are a Visual Studio developer, Code Snippets is something you definitely want to check out.

Tip 3:

If you are a bunch of developers looking out for a free tool to record documentation online, use ‘Wikis’.

MediaWiki is a great piece of server-based software (wikipedia uses it), designed to be used between a large team of programmers, working on the same documentation. MediaWiki stores display data in a MySQL database. You can add notes, codes, faq’s, images etc. with revisions. Here’s a sandbox to try it out.

If you are a small developer team and want to store your documentation as text files (to be reused outside the wiki), you can use DokuWiki.

If you want a wiki solution for your own personal use, you can use TiddlyWiki which is a client-side reusable personal web notebook and a collaboration tool. It is like a one page personal blog designed like a wiki and can also be used as a personal productivity tool.

Tip 4:

You can use a free software like Evernote to records your random thoughts, ideas, things to do etc. You can even access it using your phone. It also gives an option to save webpage clippings and screenshots and you can write code snippets and search them later.

Tip 5:

Apart from the tips shared above, you can use an awesome professional tool like Microsoft OneNote to store, sync, organize, style, encrypt, backup and share your notes (to yourself, over a network or internet). Check a demo video.

I hope these tips will help you organize your notes, if you already haven’t been doing so. It’s never too late to start! If you have been using a tool that has worked wonders for you, feel free to share it using the comments section.

August 29, 2010

Loop through Master-Detail Records using LINQ

0 comments


Here’s an example of how to loop through Master-Detail Records using LINQ. I have taken the example of one Department containing multiple Employees. The example is taken only for the purpose of understanding and does not cover all scenarios.

class Program
{
static void Main(string[] args)
{


var lst = from d in dept
from e in dept.emp
select new { d, e };
foreach (var rec in lst)
{
Console.WriteLine("{0}, {1}", rec.d.DeptNm, rec.e.EmpNm);
}
Console.ReadLine();
}
}

class Department
{
public int DeptID { get; set; }
public string DeptNm { get; set; }
public IList<Employees> emp = new List<Employees>();
}

class Employees
{
public int EmpID { get; set; }
public string EmpNm { get; set; }
public string Address { get; set; }
}

As you can see, ‘dept’ is an object of class Department. The Department class contains a collection of Employees.

public IList<Employees> emp = new List<Employees>();


To loop through each Employees in a Department, we make use of the following LINQ Expression

var lst = from d in dept
from e in dept.emp
select new { d, e };
foreach (var rec in lst)
{
Console.WriteLine("{0}, {1}", rec.d.DeptNm, rec.e.EmpNm);
}


The list prints the Department Name and the Employees in it.

August 28, 2010

Run Silverlight Applications on Linux

0 comments


A number of users have asked me how to run Silverlight apps on Linux? The answer is using MoonLight.

MoonLight is an open source implementation of Microsoft Silverlight for Linux and Unix based systems, provided by Novell in collaboration with Microsoft. This framework integrates animations, multimedia, graphics and interactivity into a single runtime environment. The Moonlight project aims at running a Silverlight application without the need to recompile that application.

You can download Moonlight here. As of this writing, the last released version of Moonlight was Moonlight 3.0 Preview 8.

Check out the Moonlight and Silverlight samples. To learn what’s ahead, check the MoonlightRoadmap.

August 27, 2010

Free Bug Tracking Software for your Projects

5 comments


A couple of days ago, I had shared a collection of Free SVN Repositories to Host your Projects. Software contains bugs and this is the inevitable truth. This week, I will share some open source bug tracking software that will streamline the process of raising, managing and fixing these issues, as they arise. Here’s a list of some open source bug tracking softwares.


Bugzilla

Bugzilla is one of the well known open source Defect/Bug-Tracking System using which you can track bugs and code changes, customize workflows, submit and review patches, test plan integration, manage quality assurance (QA) over a multi-project environment. In comparison to other Bugtracking softwares, Bugzilla being a powerful tool, has a very ordinary UI, making it difficult for beginners to use the tool.

Bugzilla uses MySQL, PostgreSQL, Oracle as its backend and integrates well with Git, CVS, Subversion, Mercurial etc.

Download Link - Feature List - Documentation


Trac

Trac is an enhanced wiki and issue tracking system for software development projects . The installation is a breeze and I particularly found the search option to be very powerful. Trac allows wiki markup in issue descriptions and commit messages, creating links and seamless references between bugs, tasks, changesets, files and wiki page.

Trac uses SQLite, PostgreSQL, MySQL as its backend and integrates well with Subversion and other version control systems.

Download Link - Documentation - Demo


Jira

JIRA provides issue tracking and project tracking through a clean, easy to use interface for capturing and organizing issues with customizable workflows, dashboards, a pluggable framework to integrate with external frameworks like CruiseControl, Confluence etc. JIRA is free for use only for official non-profit organizations, charities and open source projects.

Jira can integrate well with Git, CVS, Subversion, Mercurial etc.

Download Link - Feature List - Documentation


Redmine

Redmine is an open source project management web application with a flexible issue tracking system. It contains a wiki, discussion forums, Gantt Charts, email integration, calendars, LDAP support, multi language support, export to PDF, Excel/CSV etc.

Redmine uses SQLite, PostgreSQL, MySQL as its backend and integrates well with Git, CVS, Subversion, Mercurial etc.

Download Link - Feature List - Documentation - Demo


Mantis

MantisBT is a free web-based bugtracking system.

Mantis can connect to MS SQL, PostgreSQL, MySQL and can integrate with Git, CVS and Subversion.

Download Link - Feature List - Documentation - Demo

Wikipedia contains a very good Comparison of Issue-Tracking systems that can help you out with some additional open source bug tracking systems.

Feel free to share feedback about the ones you have used.

August 26, 2010

.NET Micro Framework 4.1 SDK Released

0 comments


Microsoft released Version 4.1 of the .NET Micro Framework SDK for developing managed applications on small devices.

As quoted in the released “The .NET Micro Framework is a .NET implemenation for very small, resource constrained devices. With version 4.1, we have added VS 2010 compatibility with multi targeting to support development for NETMF versions 3.0, 4.0, and 4.1. We have also added support for Big Endian processors. In addition, we have included ports for the Following Renesas processors and development boards: SH7216 RSK, SH7264 M3A HS64, SH7264 RSK, SH7619 EVB. We have added new applications diagnostics and DPWS custom bindings and additional samples. Finally, we have added the Hashtable type and enhanced the SPI type.

Download Link

August 25, 2010

Get Selected Value of Radio Button using a Single line of jQuery code

0 comments


In this post, we will see how to retrieve the selected value of a RadioButton using a single line of jQuery code. This is yet another example to prove that the jQuery library is indeed “Write Less, Do More”

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Selected Radio Button (from DevCurry.com)</title>
<script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
    
   <script type="text/javascript">
    $(function () {
     $('#btnRadio').click(function () {
          var checkedradio = $('[name="gr"]:radio:checked').val();
          $("#sel").html("Selected Value: " + checkedradio);
      });
    });
</script>
</head>
<body>
<div>
<input type="radio" name="gr" value="Milk" /> Milk <br />
<input type="radio" name="gr" value="Butter"
checked="checked" /> Butter <br />
<input type="radio" name="gr" value="Cheese" /> Ch <br />
<hr />
<p id="sel"></p><br />
<input id="btnRadio" type="button" value="Get Selected Value" />
</div>
</body>
</html>

As you can see, the crux of the example lies in a single line of jQuery code
var checkedradio = $('[name="gr"]:radio:checked').val();

We first identify all elements with the name attribute ‘gr’ and then use :checked to filter these elements to only the one, which is in a checked state. We then use .val() to retrieve the value of the checked radio button. The final step is to display the selected value in the paragraph(sel).

image

See a Live Demo

August 24, 2010

Different Ways of using the C# Null Coalescing Operator

9 comments


The C# Null-Coalescing operator or the ?? operator is a binary operator that returns the left-hand operand if it is not null; otherwise it returns the right operand. It can be used with both nullable and reference types.

Here’s a simple example of using the Null-Coalescing operator

int? i = null;
int j = i ?? 2;
// here the resultant value of j is 2
Here are some additional ways of using the Null-Coalescing operator in your code.

Method 1

string address = homeAddress1 ?? homeAddress2 ?? officeAddress
?? "No Address";

returns the first non-null value in this long expression. This expression returns “No Address” if homeAddress1, homeAddress2 and officeAddress are Null.


Method 2

While converting a Nullable Type to Non-Nullable type, we do an explicit cast to avoid assigning null values to a non-nullable type, as shown below:

int? a = NullType(); // returns nullable int
int b = (int)a;
instead you can avoid the explicit cast using a null-coalescing operator and write:
int? a = NullType();
int b = a ?? 0;

Method 3

private IList<Person> person;
public IList<Person> PersonList
{
get
{
return person ?? (person = new List<Person>());
}
}
Typical usage of the null-coalescing operator in a lazy instantiated private variable.


Method 4

string conn = Connection["TestMachineStr1"]
?? AppConnection["ProdMachineStr2"]
?? DefaultConnection["DefaultConn"];

Accessing NameValueCollections and choosing the first non-null value.

Note: The Null-Coalescing operator is useful but may sometimes be an overkill, especially when developers use it to flaunt their coding skills. I sometimes choose ‘understandable code’ over ‘terse code’, focusing on the intent.

Feel free to use the comments section to demonstrate how you have used the null-coalescing operator in your projects.

August 23, 2010

Chain Extension Methods in .NET

0 comments


Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. You can even chain Extension Methods.

Here’s an example:

class Program
{
static void Main(string[] args)
{
decimal num = 233.53468M;
// chaining extension methods
decimal result = num.DoSquare().DoRound();
Console.WriteLine(result);
Console.ReadLine();
}
}



public static class MathEasy
{
public static decimal DoSquare(this decimal i) {
// square a number
return i * i;
}
public static decimal DoRound(this decimal d) {
// Round to three decimal places
return Math.Round(d, 3);
}
}


As you can see, we are chaining extension methods

decimal result = num.DoSquare().DoRound();


OUTPUT

image

August 22, 2010

F# August 2010 CTP Released

0 comments


Microsoft recently released the August 2010 CTP of F# (pronounced F-Sharp). F# is a functional as well as object-oriented programming language for the .NET Framework. It combines the succinct, expressive and compositional style of functional programming with the runtime, libraries, interoperability, and object model of .NET.

As quoted by Microsoft “The F# August 2010 CTP provides all the tools and resources needed to develop applications with the F# programming language. It is available as an MSI for use with .NET and Visual Studio, and as a ZIP for use with other CLI implementations and platforms, including .NET Compact Framework on Xbox 360, and Mono on Mac, Linux and other platforms

Download Link

August 21, 2010

Using GridSplitter in Windows Presentation Foundation (WPF)

0 comments


WPF provides various control for enhancing User experience (UX). One of the very useful category of controls is Panel controls viz Grid, WrapPanel, DockPanel, StackPanel etc. All these controls are used for effective layout. Along with these controls, to resize UI elements at runtime, the ‘GridSplitter’ is provided which splits the UI in horizontal and vertical direction i.e. across rows and columns. The XAML code snippet shown below provides an example of using the GridSplitter.

<Window x:Class="WPF40_GridSplitter.Window_GridSpiltter_Row_Column"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window_GridSpiltter_Row_Column" Height="363" Width="875">
<
Grid x:Name="grdMain">
<
Grid.RowDefinitions>
<
RowDefinition Height="147*" />
<
RowDefinition Height="18*" />
<
RowDefinition Height="159*" />
</
Grid.RowDefinitions>
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="246*" />
<
ColumnDefinition Width="12*" />
<
ColumnDefinition Width="595*" />
</
Grid.ColumnDefinitions>

<
Grid Background="Red" Grid.Column="0">
<
TextBox Height="92" HorizontalAlignment="Left"
Margin="38,14,0,0" Name="textBox1"
VerticalAlignment="Top" Width="141"
Text="Cell 0,0" FontSize="28" />
</
Grid>

<
GridSplitter Grid.Row="0" Grid.Column="1" Background="Yellow"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Width="Auto" Height="Auto"
Grid.RowSpan="3" ResizeDirection="Columns">
</
GridSplitter>
<
Grid Grid.Row="0" Grid.Column="2" Background="Blue">
<
TextBox FontSize="28" Height="92" HorizontalAlignment="Left"
Margin="157,14,0,0" Name="textBox2" Text="Cell 0,1"
VerticalAlignment="Top" Width="141" />
</
Grid>

<
GridSplitter Grid.Row="1" Grid.Column="0" Background="Yellow"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Width="Auto" Height="Auto" Grid.ColumnSpan="3"
ResizeDirection="Rows"></GridSplitter>
<
Grid Grid.Row="2" Grid.Column="0" Background="Brown">
<
TextBox FontSize="28" Height="92" HorizontalAlignment="Left"
Margin="38,14,0,0" Name="textBox3"
Text="Cell 1,0" VerticalAlignment="Top" Width="141" />
</
Grid>
<
Grid Grid.Row="2" Grid.Column="2" Background="Coral">
<
TextBox FontSize="28" Height="92" HorizontalAlignment="Left"
Margin="157,23,0,0" Name="textBox4"
Text="Cell 1,1" VerticalAlignment="Top" Width="141" />
</
Grid>
</
Grid>
</
Window>

If you observe the XAML code, the main grid ‘grdMain’ is divided into 3 rows and 3 columns. There are four Grid elements in various cells of grdMain. There are two GridSplitters used for resizing across columns and rows respectively. These are with ‘Yellow’ background and span across Column no. 2, for column resize and Row no. 2, for row resize. Both these GridSplitters are spanned across column and rows, so that they can divide the window across Columns and Rows. Run the application, and you will find the following output.

image

After resizing rows and columns at runtime

image

August 20, 2010

Convert RGB to Hexadecimal using JavaScript

4 comments


In one of my previous article, I showed you how to Generate Random RGB Colors using JavaScript. However not all old browsers support the RGB mode. For old browsers, you are safe using Hex values instead of RGB. If you have a RGB value and want to convert it into Hexadecimal mode, here’s how to do it using JavaScript.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Convert RGBtoHEX using JavaScript by DevCurry.com</title>
<script type="text/javascript">
   1:  
   2:         function Rgb() {
   3:             var red = returnHex(200);
   4:             var green = returnHex(255);
   5:             var blue = returnHex(155);
   6:             var hex = "#" + red + green + blue;
   7:                         
   8:             alert(hex);            
   9:         }
  10:  
  11:         // Convert to Hex
  12:         function returnHex(num) {
  13:             // Hex can store 16 different values in 1 character
  14:             if (num == null) return "00";
  15:             num = num.length < 2 ? "0" + num : num
  16:             return num.toString(16);
  17:         }       
  18:     
</script>
</head>
<body onload="randomRgb()">
<div>Demo from DevCurry.com</div>
</body>
</html>

Using the returnHex(num) function, we first check to see if the num is not null, else return 0. We are then using a ternary condition to check if the length of num is less than 2. If it is, prefix ‘0’ to the results, else use the original number. Finally we use toString(16) on the number, to convert it into hexadecimal mode. Remember Hex can store 16 different values in 1 character.

In the Rgb function(), I am passing a sample RBG value and then displaying the converted hex value using alert(). I have not done too many validation checks, in order to keep the example simple and to the point.

On passing 200,255,155 you get #c8ff9b

image

August 19, 2010

Generate Random Colors using JavaScript

0 comments


In this post, we will see how to generate random colors using JavaScript. We will generate a random color and change the color of the div contents, at regular intervals.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Generate Random Colors using JavaScript</title>
<
script type="text/javascript">
// after every second timer
setInterval(randomRgb, 1000);

function randomRgb() {
// create the rgb string
var col = "rgb("
+ randomColor(255) + ","
+ randomColor(255) + ","
+ randomColor(255) + ")";

//change the text color with the new random color
document.getElementById("divone").style.color = col;
}


function randomColor(num) {
return Math.floor(Math.random() * num);
}
</script>
</
head>
<
body>
<
div id="divone" style="font:bold 24px verdana">DevCurry.com</div>
</
body>
</
html>

As you can see, we are using Math.random() to generate a random rgb value between 0 and 255. The onesecond timer is set using setInterval() which makes a function call to randomRgb() and changes the color of text kept inside ‘divone’. If you are new to the setInterval() function, read my post Execute a Function at Regular Intervals using JavaScript

Note: This code should work on most of the modern browsers. For old browsers, you need to look at hexadecimal value instead of RGB. Check my post Convert RGB to Hexadecimal using JavaScript

OUTPUT

image

See a Live Demo

August 18, 2010

Free SVN Repositories to Host your Projects

12 comments


We are planning to start work on an open source project soon. As a result, we were looking out for a free SVN repository [what is SVN?] with the following main features:

  • reliable version control system
  • mailing lists, forums, issue tracker, pages, download area
  • web based administration

Here are some free SVN repositories we found and thought of sharing with you, in case you too are looking out for some. Note that some of the products listed here have both free and commercial options. I am highlighting only the Free plans.

Assembla - Unlimited Users. Unlimited Projects. 2 GB Storage. Ideal for consultants and small agile-development teams that want a safe, reliable version control solution.

Unfuddle – Free for 2 users, 200 MB of space. Unlimited Repositories Subversion & Git.

BeanStalk – Free for 3 users, 1 private repository (Git or SVN) and 100 MB of space.

ProjectLocker – Free for 5 Users, 500 MB space and unlimited projects

Origo - Origo is an open source software development and collaboration platform that provides an SVN repository (with web interface), project wiki page, issue tracker with tag support, releases area etc.

Google Code - Project Hosting on Google Code provides a free collaborative development environment for open source projects. Each project comes with its own member controls, Subversion/Mercurial repository, issue tracker, wiki pages, and downloads section.

Gna! - Gna! provides Source Code Repositories (CVS, GNU Arch, Subversion), Download Area, Web Pages, Mailing-Lists and Trackers (Bugs, Task, Support Requests, Patches).

BerliOS - BerliOS Developer is a free service to Open Source developers offering easy access to the best in CVS/SVN/Mercurial/GIT, mailing lists, bug tracking, message boards/forums, task management, site hosting, permanent file archival, full backups, and total web-based administration.

You may also want to take a look at CodePlex, GitHub, SourceForge and Freepository

August 17, 2010

Creating and Loading XAML dynamically in WPF

2 comments


In this post, we will see how to create a XAML file from the WPF element object and how to load this XAML file dynamically to generate UI. In WPF we have been provided with following classes:

  • XamlWriter - used to serialize the WPF UI Element objects in Xaml code.
  • XamlReader - used to read the Xaml file, parse it and generate WPF object graph from it.

In the following application, I have demoed the same. I have created a WPF application with the following design Xaml for MainWindow.Xaml:

<Grid>
<
Button Content="Create XAML" Height="51" HorizontalAlignment="Left"
Margin="22,26,0,0" Name="btnCreateXAML" VerticalAlignment="Top"
Width="250" Click="btnCreateXAML_Click" />
<
Button Content="Load XAML" Height="50" HorizontalAlignment="Left"
Margin="458,12,0,0" Name="btnLoadXAML" VerticalAlignment="Top"
Width="250" Click="btnLoadXAML_Click" />
<
Grid Height="296" HorizontalAlignment="Left" Margin="384,82,0,0"
Name="grdLoadXAML" VerticalAlignment="Top" Width="414" />
</
Grid>

Creating Xml or XAML File From WPF UI Element Objects

The ‘btnCreateXAML’ click event has the following code as shown below. The buttons dynamically creates the Grid UI object and adds a Button and TextBox UI object as a child of the Grid. Using XamlWriter class a .xml file is created which serialize all UI objects. This object is passed to the FileStram class. The code is as shown below:

private void btnCreateXAML_Click(object sender, RoutedEventArgs e)
{
try
{
Grid grd = new Grid();
grd.Height = 210;
grd.Width = 400;
Button btn = new Button();
btn.Height = 50;
btn.Width = 80;
btn.Content = "Dyn. Button";
btn.Background = new SolidColorBrush(Colors.Red);
btn.Margin = new Thickness(5, 5, 310, 120);
grd.Children.Add(btn);

TextBox txt = new TextBox();
txt.Height = 50;
txt.Width = 100;
txt.Text = "Dynamic TextBox";
txt.Foreground = new SolidColorBrush(Colors.Red);
txt.Margin = new Thickness(5, 60, 310, 80);
grd.Children.Add(txt);

//Store this Xaml in File

FileStream Fs = new FileStream(@"H:\GeneratedFiles\MyDesign.Xml",
FileMode.CreateNew);
System.Windows.Markup.XamlWriter.Save(grd, Fs);
Fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Note: The File extension can also be .XAML. There is no difference in the code, since XAML is logically based upon XML

The following XAML file will be generated:

image

Loading XML or XAML file dynamically to Generate WPF UI Element Graph

Let us quickly see the code first to load the XAML dynamically

private void btnLoadXAML_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog Fd = new OpenFileDialog();
Fd.ShowDialog();
string LoadedFileName = Fd.FileName;

//Load the file
FileStream Fs = new FileStream(@LoadedFileName, FileMode.Open);
Grid grdToLoad = new Grid();
grdToLoad.Height = 210;
grdToLoad.Width = 400;

grdToLoad = System.Windows.Markup.XamlReader.Load(Fs) as Grid;

grdLoadXAML.Children.Add(grdToLoad);

Fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

The code shown above loads the xml using ‘XamlReader’ class. This class provides the ‘Load’ method which parses the input xml / xaml document. One of the most important thing here is that the file is parsed from its root element. This has to match with a specific Panel control of WPF e.g. Grid, Canvas, etc. Based upon that, the Load() method is type casted using ‘as’ operator. If the root is matched with the panel, then all the XAML UI elements in the file will be constructed and the WPF Element object graph will be generated.

Run the application and click on the ‘Create XAML’ button. The file will be created in the specified path. Then click on ‘Load XAML’ button to open the ‘Open File Dialog’. Select the xml file generated earlier and you will see the following result:

image

August 16, 2010

Random File Names using .NET

1 comments


It helps to have knowledge of .NET classes. I was recently working on a requirement where some files were to be generated on the fly and stored on the disk. The requirement was that the files had to be generated with random characters and random extensions, to add extra security to the files. System.IO.Path.GetRandomFileName() returns a random folder name or file name which makes the task very simple, as shown below:

C#

static void Main(string[] args)
{
for (int i = 1; i < 10; i++)
Console.WriteLine(System.IO.Path.GetRandomFileName());
Console.ReadLine();
}

VB.NET

Shared Sub Main(ByVal args() As String)
For i As Integer = 1 To 9
Console.WriteLine(System.IO.Path.GetRandomFileName())
Next i
Console.ReadLine()
End Sub

Note: If you want to physically create some files on the disk, just pass these random names to a FileStream object inside the for loop. GetRandomFileName() does not create a physical file like GetTempFileName() does.

OUTPUT

image

August 15, 2010

Windows Azure AppFabric SDK V1.0 (July Update)

0 comments


Microsoft released the updated version of the Windows Azure AppFabric SDK to help developers build on top of Windows Azure AppFabric.

Windows Azure AppFabric is a key component of the Windows Azure Platform. It includes two services: AppFabric Access Control and AppFabric Service Bus.

As quoted by Microsoft

This SDK includes API libraries and samples for building connected applications with the .NET platform. It spans the entire spectrum of today’s Internet applications – from rich connected applications with advanced connectivity requirements to Web-style applications that use simple protocols such as HTTP to communicate with the broadest possible range of clients.

You can download the Windows Azure AppFabric SDK v1.0 here

You can also download the Windows Azure AppFabric Labs SDK – August Update which provides developers with the APIs, tools, documentation, and samples to help developers build applications that use Windows® Azure AppFabric in the Labs environment.

August 14, 2010

If you win an Ultimate Edition of Visual Studio 2010 MSDN Subscription, how do you plan to use it?

0 comments


I am doing a Visual Studio 2010 Ultimate with MSDN Subscription GiveAway on our FaceBook page. To enter a chance to win this subscription, all you have to do is click the link below and answer this simple question:

If you win an Ultimate Edition of Visual Studio 2010 MSDN Subscription, how do you plan to use it?

Please note that the question has to be answered ‘only’ on our FaceBook discussion page.

We have already announced our two winners - Boris Teterin and Jeff Klawiter who have won this subscription. The 3rd and final winner will be announced on the 16th of August, 2010 at 6:00 PM GMT i.e two days from now. So hurry up and submit your entry!

Check the original post for rules and benefit restrictions.

August 13, 2010

Selected Text and Value of ASP.NET DropDownList using jQuery

0 comments


I recently saw a question on StackOverflow where a user wanted to retrieve the selected value of an ASP.NET DropDownList using jQuery. I have observed a lot of developers confused on when to use text() vs val().

Here’s the solution taken from my EBook 51 Recipes with jQuery and ASP.NET Controls

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Get Selected Value and Text From ASP.NET DropDownList</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript">
$(function () {
$('select[id$=DDL]').bind("change keyup", function () {
$('#para').html(
"Value: " + $(this).val() +
"<br />" +
" Text: " + $('select[id$=DDL] :selected').text());
});
});
</script>

</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
h2>Select an Item from the DropDownList to display
it's text and value </h2>
<
asp:DropDownList ID="DDL" runat="server" >
<
asp:ListItem Text="Select an Item" Value="" />
<
asp:ListItem Text="Item3" Value="3"></asp:ListItem>
<
asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<
asp:ListItem Text="Item4" Value="4"></asp:ListItem>
<
asp:ListItem Text="Item5" Value="5"></asp:ListItem>
<
asp:ListItem Text="Item2" Value="2"></asp:ListItem>
</
asp:DropDownList>
<
br /><br />
<
p id="para"></p>
</
div>
</
form>
</
body>
</
html>

In this example, both the change and keyup event of the DropDownList is captured using bind(). According to the W3C specifications, the change event occurs when a control loses the input focus and its value has been modified since gaining focus. However IE triggers the ‘change’ event as soon as the option is selected, whereas Mozilla, Chrome and Safari do not. This behavior of triggering the change event by IE on keyboard scrolling is not according to the W3C specs. This is the reason that we use both the change and keyup event to capture selection, when the user uses the keyboard to scroll through the dropdownlist items.

Whenever the user selects a new item from the DropDownList, the ‘value’ is printed using $(this).val() and the ‘text’ is printed using $('select[id$=DDL] :selected').text().

The :selected selector matches selected <option> elements. The results are written to a paragraph using $('#para').html()

When the user selects an item from the DropDownList, the output looks similar to the one shown below:

image

See a Live Demo

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions