• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Sunday, 26 Feb 2012 18:22

Hi

Every one knows that when different threads write to the same data structure they need to be synced.

Lets assume we have a Service that exposed a single function Add which added the value received to a List.

1: public class ListWrapper

2: {

3: private readonly List<int> m_list =new List<int>();

4:

5: public void Add(int i)

6: {

7: m_list.Add(i);

8: }

9: }

In order to make it thread safe we would simply lock the List so if multiple thread try to access this function they will add their values to the list each at a time.

1: public void Add(int i)

2: {

3: lock (m_list)

4: {

5: m_list.Add(i);

6: }

7: }

For 99.9% of the applications this is a good solution.

Lets look at the following code:

1: private static object m_locker = new object();

2: static void Main(string[] args)

3: {

4: for (int i = 0; i < 50; i++)

5: {

6: int iLocal = i;

7: Task.Factory.StartNew(() =>

8: {

9: lock (m_locker)

10: {

11: Console.WriteLine(iLocal);

12: }

13: });

14: }

15: Console.ReadLine();

16: }

What do you think will be printed to the screen? If you though we are going to see the numbers 0-49 in order you are very wrong…

Here is one of the results of running this code:

Lock

Chaos!

Look at 3 its almost at the end! while 10-30 are neatly ordered.

This is due to the fact that lock() does not keep order, you never know which thread will get the priority to work.

Now that we know not to count on lock to keep our threads in line there is one more thing to notice here.

This test was with 50 calls. What if this was a web server that handles many calls a second 24/7? Since lock() does not offer any promise of order, there is a chance that some of the threads will stay “stuck” in that lock statement for a long time and possibly forever! In many applications this is not a problem but sometimes it means there is a desperate user on the other side trying to understand what went wrong…

So in conclusion :

  1. Don’t count on the lock() statement to keep your threads in order
  2. The lock() statement is not good enough for heavily multithreaded critical sections.

Did this ever cause any trouble to you? if so please comment.

Thanks

Amit


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Amit" Tags: ".Net, C#, lock, multithreading"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 23 Feb 2012 09:32

 

Hi

 

I you worked with the WebBrowser control you probably met the following popup:

 

script error

 

I have started to use the WPF WebBrowser control in some of my applications but when I tried to disable the script errors I had a small problem the property WebBrowser.ScriptErrorsSuppressed  was not there, bummer…

 

After some research I have come up with a new solution. It involves injecting each webpage we display a small piece of JavaScript which catches those errors and ignores them.

Here is how it is done:

This is the java script we are injecting:

   1: function noError() 

   2: {

   3:     return true;

   4: } 

   5: window.onerror = noError;

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

And now The way to inject the script to the WebBrowser control:

   1: private void InjectDisableErrorScript()

   2: {

   3:     var doc = Browser.Document as HTMLDocument;

   4:     if (doc != null)

   5:     {

   6:         //Create the sctipt element

   7:         var scriptErrorSuppressed = (IHTMLScriptElement)doc.createElement("SCRIPT");

   8:         scriptErrorSuppressed.type = "text/javascript";

   9:         scriptErrorSuppressed.text = m_disableScriptError;

  10:         //Inject it to the head of the page

  11:         IHTMLElementCollection nodes = doc.getElementsByTagName("head");

  12:         foreach (IHTMLElement elem in nodes)

  13:         {

  14:             var head = (HTMLHeadElement)elem;

  15:             head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);

  16:         }

  17:     }

  18: }

Don’t forget to do this every time before you navigate.

That’s it! Now you are script error free.

 

Enjoy

 

Amit


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Amit" Tags: ".Net, C#, WPF, Script Errors, ScriptElem..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 28 Jul 2009 16:11

Last week, I stumbled upon the following piece of code:

 

IList<double> doubles = new List<double> {22.123, 400.12, 100.22};
foreach (int number in doubles)
{
    Console.WriteLine("The Current Number Is : {0}", number);
}

Can you see the bug in that code? We convert all of the doubles in the list to integers, truncating them. I was very surprised that the compiler didn’t warn me about this issue, especially because the compiler would not let me write this code:

 

double someDouble = 22.523;
int someInt = someDouble;

An explicit conversion is necessary here:

 

int someInt = (int)someDouble;

What is the difference between those two cases? Can’t I expect a uniform behavior from the compiler? The reason is probably historic – before C# 2.0 which introduced us with Generics, all of the containers held their items as objects. If the foreach statement didn’t automatically do the conversion, the user would have to explicitly cast every item in the collection from object

 

 

ArrayList array = new ArrayList {"moshe", "levi"};
foreach (object obj in array)
{
    string str = obj as string;
    if (str != null)
       Console.WriteLine("The Current element is {0}", str);
}

In most cases, the collection items are of the same type so in order to reduce the explicit conversion effort, the C# developers decided to do an automatic conversion for us. If we test the MSIL which is generated for the foreach statement, we can clearly notice to the “injected” code which is responsible for the conversion:

 

clip_image002

Now that we understand what happens, here is a way to avoid those kinds of bugs. Using the var keyword, we can ask the compiler to define the type of the collection item according to its value. Here it is:

IList<double> doubles = new List<double> {22.123, 400.12, 100.22};
foreach (var number in doubles)
{
    Console.WriteLine("The Current Number Is : {0}", number);
}

By changing this code, the compiler is responsible for determining the type of “number”. In most cases, that is exactly what we want…


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "moshe" Tags: ".Net, C#, cast, casting, Explicit, forea..."
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 23 Jul 2009 15:30

Suppose you have several objects in your WPF application filled with similar Brushes which differ in brightness only. Like in this image:

red_rect

 

The nine rectangles use the same RadialGradienBrush but each rectangle is a little darker than previous. You can create these 9 different brushes in your favorite design tool (Expression Blend, etc.). But what if you need to change the base color later or you just need to make the brush user-configurable? Like in these samples:

 

 green_rect

 

blue_rect

 

The better approach would be to define the base brush once and then change it’s brightness in code. Unfortunately there’s no built-in way to change brightness of the Brush or Color in WPF. This is what we are going to address in this article.

 

Hue, Saturation, Brightness

System.Windows.Media.Color structure represents colors as 4 channels: alpha (opacity) channel and 3 channels for each core color (red, green and blue). aRGB color space is good for representing colors but it’s quite problematic to control such properties as brightness with these 4 channels. We will convert our colors to and from a HSB color space which is good at exactly what we need – controlling such perceptual color characteristics as hue, saturation and brightness. To do this we create a new class called HSBColor defined like this:

   1: public class HSBColor

   2: {

   3:     public double H { get; set; }

   4:     public double S { get; set; }

   5:     public double B { get; set; }

   6:     public byte A { get; set; }

   7: 

   8:     public static HSBColor FromColor(Color rgbColor)

   9:     {

  10:         HSBColor result = new HSBColor();

  11: 

  12:         // preserve alpha

  13:         result.A = rgbColor.A;

  14: 

  15:         // convert R, G, B to numbers from 0 to 1

  16:         double r = rgbColor.R / 255d;

  17:         double g = rgbColor.G / 255d;

  18:         double b = rgbColor.B / 255d;

  19: 

  20:         double max = Math.Max(r, Math.Max(g, b));

  21:         double min = Math.Min(r, Math.Min(g, b));

  22: 

  23:         // hue

  24:         if (max == min)

  25:             result.H = 0;

  26:         else if (max == r)

  27:             result.H = (60 * (g - b) / (max - min) + 360) % 360;

  28:         else if (max == g)

  29:             result.H = 60 * (b - r) / (max - min) + 120;

  30:         else

  31:             result.H = 60 * (r - g) / (max - min) + 240;

  32: 

  33:         // saturation

  34:         if (max == 0)

  35:             result.S = 0;

  36:         else

  37:             result.S = 1 - min / max;

  38: 

  39:         // brightness

  40:         result.B = max;

  41: 

  42:         return result;

  43:     }

  44: 

  45:     public Color ToColor()

  46:     {

  47:         Color result = new Color();

  48: 

  49:         result.A = this.A;

  50: 

  51:         int hi = (int)Math.Floor(this.H / 60) % 6;

  52:         double f = this.H / 60 - Math.Floor(this.H / 60);

  53: 

  54:         double p = this.B * (1 - this.S);

  55:         double q = this.B * (1 - f * this.S);

  56:         double t = this.B * (1 - (1 - f) * this.S);

  57: 

  58:         switch (hi)

  59:         {

  60:             case 0:

  61:                 result.R = (byte)(this.B * 255);

  62:                 result.G = (byte)(t * 255);

  63:                 result.B = (byte)(p * 255);

  64:                 break;

  65:             case 1:

  66:                 result.R = (byte)(q * 255);

  67:                 result.G = (byte)(this.B * 255);

  68:                 result.B = (byte)(p * 255);

  69:                 break;

  70:             case 2:

  71:                 result.R = (byte)(p * 255);

  72:                 result.G = (byte)(this.B * 255);

  73:                 result.B = (byte)(t * 255);

  74:                 break;

  75:             case 3:

  76:                 result.R = (byte)(p * 255);

  77:                 result.G = (byte)(q * 255);

  78:                 result.B = (byte)(this.B * 255);

  79:                 break;

  80:             case 4:

  81:                 result.R = (byte)(t * 255);

  82:                 result.G = (byte)(p * 255);

  83:                 result.B = (byte)(this.B * 255);

  84:                 break;

  85:             case 5:

  86:                 result.R = (byte)(this.B * 255);

  87:                 result.G = (byte)(p * 255);

  88:                 result.B = (byte)(q * 255);

  89:                 break;

  90:         }

  91: 

  92:         return result;

  93:     }

  94: }

The algorithm behind these conversions could be found in this Wikipedia article.

Now all we need to do is modify brightness of every color used in our brushes.

 

SetBrightness() Extension Method

We will create an extension method for Brush class which creates a new brush based on the original brush but with new brightness applied. Our method will support all Color based brushes such as SolidColorBrush, LinearGradientBrush and RadialGradientBrush. For all other brush types our method will just return the clone of the original brush.

With SolidColorBrush we are going to set brightness on the color set in it’s Color property and for GradientBrush(es) – on Color property of each GradientStop. So, enough talking – here’s the code:

   1: public static Brush SetBrightness(this Brush original, double brightness)

   2: {

   3:     if (brightness < 0 || brightness > 1)

   4:         throw new ArgumentOutOfRangeException("brightness",

              "brightness should be between 0 and 1");

   5: 

   6:     Brush result;

   7: 

   8:     if (original is SolidColorBrush)

   9:     {

  10:         HSBColor hsb = HSBColor.FromColor(((SolidColorBrush)original).Color);

  11:         hsb.B = brightness;

  12:         result = new SolidColorBrush(hsb.ToColor());

  13:     }

  14:     else if (original is GradientBrush)

  15:     {

  16:         result = original.Clone();

  17:         // change brightness of every gradient stop

  18:         foreach (GradientStop gs in ((GradientBrush)result).GradientStops)

  19:         {

  20:             HSBColor hsb = HSBColor.FromColor(gs.Color);

  21:             hsb.B = brightness;

  22:             gs.Color = hsb.ToColor();

  23:         }

  24:     }

  25:     else

  26:     {

  27:         result = original.Clone();

  28:     }

  29: 

  30:     return result;

  31: }

 

Using the Method

Let’s look at a simple usage scenario. We will create those 9 rectangles pictured above. The window’s XAML looks like this:

   1: <Window x:Class="Brightness.Window2"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     Title="Window2" Height="250" Width="300" Background="#333333"

   5:     Loaded="Window_Loaded">

   6:     <Window.Resources>

   7:         <Style x:Key="RectangleStyle" TargetType="Rectangle">

   8:             <Setter Property="RadiusX" Value="10" />

   9:             <Setter Property="RadiusY" Value="10" />

  10:             <Setter Property="Margin" Value="5" />

  11:         </Style>

  12:     </Window.Resources>

  13:     <UniformGrid x:Name="mainGrid" Margin="30">

  14:         <Rectangle Style="{StaticResource RectangleStyle}">

  15:             <Rectangle.Fill>

  16:                 <RadialGradientBrush GradientOrigin="-0.3 -0.3">

  17:                     <GradientStop Color="#ffffff" Offset="0" />

  18:                     <GradientStop Color="#0000FF" Offset="1" />

  19:                 </RadialGradientBrush>

  20:             </Rectangle.Fill>

  21:         </Rectangle>

  22:         <Rectangle Style="{StaticResource RectangleStyle}" />

  23:         <Rectangle Style="{StaticResource RectangleStyle}" />

  24:         <Rectangle Style="{StaticResource RectangleStyle}" />

  25:         <Rectangle Style="{StaticResource RectangleStyle}" />

  26:         <Rectangle Style="{StaticResource RectangleStyle}" />

  27:         <Rectangle Style="{StaticResource RectangleStyle}" />

  28:         <Rectangle Style="{StaticResource RectangleStyle}" />

  29:         <Rectangle Style="{StaticResource RectangleStyle}" />

  30:     </UniformGrid>

  31: </Window>

The first rectangle has it’s Fill property set to a RadialGradientBrush and all other rectangles have no fill at all. In the Window_Loaded event handler we just take the brush of the first rectangle and apply it to all other rectangles with different brightness.

   1: private void Window_Loaded(object sender, RoutedEventArgs e)

   2: {

   3:     Brush mainBrush = (mainGrid.Children[0] as Rectangle).Fill;

   4:     for (int i = 1; i < 9; i++)

   5:     {

   6:         (mainGrid.Children[i] as Rectangle).Fill = 

               mainBrush.SetBrightness(1 - i / 10d);

   7:     }

   8: }

And that’s it.

 

Final thoughts

Rather than creating an extension method it would be nice to create a custom Brush that would take another “standard” brush and apply specified brightness to it. This would allow animation of Brightness property resulting in nice fade-in and out effects (for example). Unfortunately Microsoft has implemented abstract Brush class in such a way that no 3rd party can inherit from it. Some of the abstract methods in the Brush class are also declared as internal so there’s no way we can implement them. I hope they had a good reason for doing this. Otherwise it doesn’t make much sense.


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "ailon" Tags: ".Net, C#, Silverlight, WPF, Brush Bright..."
Comments Send by mail Print  Save  Delicious 
Date: Friday, 17 Jul 2009 05:21

What is REST?

Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. As such, it is not just a method for building "web services." The terms "representational state transfer" and "REST" were introduced in 2000 in the doctoral dissertation of Roy Fielding,[1] one of the principal authors of the Hypertext Transfer Protocol (HTTP) specification.

REST is a method of managing resources over HTTP. There are a number of methods of interacting with resources via REST.

HTTP CRUD
POST Create
GET Read
PUT Update, Create
DELETE Delete

Systems which follow Fielding’s REST principles are often referred to as "RESTful".

 

Our Basic Service

For the purpose of this post we are going to create a service that returns a product based on the requested product id.

Start by adding a new WCF service to your project. We’ll call it Products.

Change the interface that is generated to look like this:

   1: [ServiceContract]

   2: public interface IProducts 

   3: {

   4:     [OperationContract]

   5:     [WebInvoke(Method = "GET",

   6:      ResponseFormat = WebMessageFormat.Json,

   7:      BodyStyle = WebMessageBodyStyle.Wrapped,

   8:      UriTemplate = "get/{id}")]

   9:     string Get(string id);

  10: }

In the above code we use the ServiceContract attribute to say that this interface is defining a service and makes the interface visible to WCF clients. We then define a method called Get. We mark this method with 2 attributes. First we use OperationContract. This just lets WCF know that this is a method of the service. Next we use WebInvoke. This means that the method is an invoke operation and maps it to an HTTP verb. In this case we have mapped it to the GET verb, specified we want our response to be JSON, and defined what to an URI will look like. The UriTemplate maps our id value to out method parameter.

   1: public class Products : IProducts 

   2: {

   3:     public string Get(string id) 

   4:     {

   5:         return "You requested product " + id;

   6:     }

   7: }

This next part is simple. We are just implementing our interface. Our method is pretty simple for demonstration purposes. We’ll just output the id value that we receive.

This next part that you need in your Web.config is important for your service to work. This maps the incoming requests to your services.

 

Calling Our API

So, now that our service is finished it is easy to call like http://yourdomain.com/Products.svc/get/123456. This is telling our service we want to use the Get method of the Products service and we are looking for product id 123456.

This will give us a response of:

{"GetResult":""You requested product 123456"}

 

Wrap Up

This is just a simple example of how to setup a RESTful web service quickly and easily by letting WCF take care of the plumbing and heavy lifting.

Stay tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Justin" Tags: "C#, REST, RESTful, Service, WCF"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 12 Jul 2009 16:17

Hey all

 

I am sorry for the long absence but I just got married and went on a great honeymoon, so I was not around!

 

I hope things will start to pick up from now.

 

Just wanted to let you all know that we are back online, and to tell you that we have updated the Write Articles for Dev102.com page with some new features.

  • Payment has gone up to 35$!
  • We now have a free submission option where you can share articles and still be able to publish them elsewhere.

So go ahead and check it out!

 

Talk soon

 

Amit.


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Amit" Tags: "C#"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 28 May 2009 12:32

Hi

 

When working with WPF I always found myself thinking how to handle Data formatting when a WPF control was bound to it. Let’s look at the following example of a window with a TextBlock that displays a DateTime:

   1: <Window x:Class="BindingFormat.Window1"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     Title="Window1" Height="300" Width="300">

   5:     <Grid>

   6:         <TextBlock Text="{Binding}"></TextBlock>

   7:     </Grid>

   8: </Window>

And the code behind:

   1: public Window1()

   2: {

   3:     InitializeComponent();

   4:     DateTime d = DateTime.Now;

   5:     this.DataContext = d;

   6: }

Very Simple.

 

The outcome is this:

 

Binding no Format

But what if we wanted to change the format of the DateTime? Before .NET 3.5 SP1 we had 2 options:

 

Adding a Property

That was the easiest and fastest way to make the data in the UI formatted in the way you wanted let’s say we wanted the DateTime to display like this: 11:49 2/5/2009, we would have done this:

   1: public Window1()

   2: {

   3:     InitializeComponent();

   4:     this.DataContext = this;

   5: }

   6: 

   7: public string Now

   8: {

   9:     get

  10:     {

  11:         return DateTime.Now.ToString("HH:MM d/M/yyyy");

  12:     }

  13: }

and have the UI bind to the Now property:

   1: <Window x:Class="BindingFormat.Window1"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     Title="Window1" Height="300" Width="300">

   5:     <Grid>

   6:         <TextBlock Text="{Binding Now}"></TextBlock>

   7:     </Grid>

   8: </Window>

The outcome is what we wanted:

Using Property to format

I don’t like this way of work for 2 reasons:

  1. It ads clutter to the code behind and mixes data and UI elements because the Now property is strictly UI but it resides in the Data of the application.
  2. There is no way to reuse it, we would have to duplicate the property anywhere we need to display this particular format.

Using a ValueConverter

This is a much better way of work because it solves the 2 problems I had with the Property method of formatting data. Using a converter keeps UI logic in the UI, removes the clutter from the code behind and is reusable.

 

Here is how we do it:

 

First we add the converter:

   1: public class DateTimeConverter : IValueConverter

   2: {

   3:     #region IValueConverter Members

   4: 

   5:     public object Convert(object value, Type targetType, object parameter

   6:                         , System.Globalization.CultureInfo culture)

   7:     {

   8:         if (value is DateTime)

   9:         {

  10:             DateTime d = (DateTime)value;

  11:             return d.ToString("HH:MM d/M/yyyy");

  12:         }

  13:         return string.Empty;

  14:     }

  15: 

  16:     public object ConvertBack(object value, Type targetType, object parameter

  17:                             , System.Globalization.CultureInfo culture)

  18:     {

  19:         throw new NotImplementedException();

  20:     }

  21: 

  22:     #endregion

  23: }

Use it with the binding:

   1: <Window x:Class="BindingFormat.Window1"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:         xmlns:local="clr-namespace:BindingFormat"

   5:     Title="Window1" Height="300" Width="300">

   6:     <Window.Resources>

   7:         <local:DateTimeConverter x:Key="BindingCVR"/>

   8:     </Window.Resources>

   9:     <Grid>

  10:         <TextBlock Text="{Binding Converter={StaticResource BindingCVR}}"/>

  11:     </Grid>

  12: </Window>

And have the DataContext be DateTime.Now:

   1: public Window1()

   2: {

   3:    InitializeComponent();

   4:    DateTime d = DateTime.Now;

   5:    this.DataContext = d;

   6: }

And the outcome? Just as before:

Using Property to format

The only drawback to this method is that it is takes more effort.

 

But we just got lucky..

 

Using Binding.StringFormat

In .NET 3.5 SP1 we got the StringFormat option in Binding!

 

This makes things so much easier All we have to do is have the Binding Expression look like this:

   1: <TextBlock Text="{Binding StringFormat='HH:MM d/M/yyyy'}"/>

And that’s it, no extra Properties and ValueConverters.

 

I could have copied the image again but trust me it gives the same outcome in a much more elegant way.

 

Do you have a different way of work? let me know.

 

Enjoy

 

Amit


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Amit" Tags: ".Net, WPF, .NET 3.5 SP1, Binding, proper..."
Comments Send by mail Print  Save  Delicious 
Date: Monday, 25 May 2009 18:25

This article was written by Alan Mendelevich

The Problem

Creating a shape with bullets on the joints of it’s segments sounds like a really trivial task at a first glance. Just plaster some bullets on top of the shape. And it is really something like this until you decide you want to have transparent outlined bullets or opaque bullets with transparent outline around them. Like the ones in this picture:

bulleted_path_samples

 

In raster scenarios this could be solved by simply deleting the pixels around the joint points but since we are talking about WPF or Silverlight (vector graphics) this is not an option.

If you have a simplistic figure like the first rectangle in the above picture you may think about just creating shorter lines for it’s sides. This is not a very complicated task. However in the second (triangle) example calculating the end points for the lines gets a little more complicated. And try doing this without a masters degree in mathematics for the third and fourth (bottom) examples utilizing arcs and Bezier curves.

The second option is to cheat a little. You can use background color for bullet’s fill or outline. This would work well on a solid color background. But what if you have a gradient background (like in our sample picture), image background or if your bullet falls on the edge of some object or the shape itself?

I have faced this issue when working on a line chart portion of amCharts for WPF and here’s how I solved it.

 

The Solution

The magic word for my solution is OpacityMask. To quote MSDN documentation what it does is:

Gets or sets an opacity mask, as a Brush implementation that is applied to any alpha-channel masking for the rendered content of this element.

In other words it lets you apply different levels of opacity to different portions of your element.

So, the general idea is to create an opacity mask which has zero opacity spots in place where we want to put our bullets and 100% opacity everywhere else. Below are the main parts of the implementation along with some small but very important details.

  • We derive our BulletedPath class from the abstract Shape class. Path could’ve been a better base class candidate, but unfortunately it’s sealed.
  • We add several bullet related dependency properties for controlling bullet shape, fill and outline.
  • We add a Data property which will store PathGeometry defining our shape.

With all this done (you can see the implementation by downloading the source code for the control linked at the end of the article) we override OnRender method of our shape.

Here’s the method in it’s entirety and we’ll examine what it does below:

   1: protected override void OnRender(DrawingContext drawingContext)

   2: {

   3:     Pen shapePen = new Pen(this.Stroke, this.StrokeThickness);

   4:     shapePen.StartLineCap = this.StrokeStartLineCap;

   5:     shapePen.EndLineCap = this.StrokeEndLineCap;

   6:     shapePen.DashCap = this.StrokeDashCap;

   7:     shapePen.LineJoin = this.StrokeLineJoin;

   8:     shapePen.MiterLimit = this.StrokeMiterLimit;

   9:     shapePen.DashStyle = 

  10:         new DashStyle(this.StrokeDashArray, this.StrokeDashOffset);

  11:     // a create temporary drawing to find out 

  12:     // real bounds of our shape using specified pen

  13:     GeometryDrawing maskBoundsDrawing = 

  14:         new GeometryDrawing(Brushes.Black, shapePen, this.Data);

  15:     Rect bounds = maskBoundsDrawing.Bounds;

  16:     // create opacity mask for bullet holes

  17:     GeometryGroup holes = this.GetHoles();

  18:     RectangleGeometry maskRect = new RectangleGeometry(bounds);

  19:     Geometry maskGeometry = 

  20:         Geometry.Combine(maskRect, holes, GeometryCombineMode.Exclude, null);

  21:     GeometryDrawing maskDrawing = 

  22:         new GeometryDrawing(Brushes.Black, null, maskGeometry);

  23:     DrawingBrush maskBrush = new DrawingBrush(maskDrawing);

  24:     maskBrush.Stretch = Stretch.None;

  25:     // apply opacity mask

  26:     drawingContext.PushOpacityMask(maskBrush);

  27:     // draw main shape

  28:     drawingContext.DrawGeometry(this.Fill, shapePen, this.Data);

  29:     drawingContext.Pop();

  30:     // draw bullets

  31:     RenderBullets(drawingContext);

  32: }

  33:  

First we construct a pen to use for drawing the outline of our shape. Oddly enough Shape class doesn’t provide one property for setting the Pen. This is justified by the fact that it’s easier to set (and animate) individual properties of the pen on the whole shape object in XAML rather than creating a dedicated object for the outline pen.

This is understandable, however it would be really nice of Microsoft to provide a method to get a real Pen out of all these individual properties. This is a good candidate for an extension method, but that’s another story and for now we just construct the pen manually.

   1: Pen shapePen = new Pen(this.Stroke, this.StrokeThickness);

   2: shapePen.StartLineCap = this.StrokeStartLineCap;

   3: shapePen.EndLineCap = this.StrokeEndLineCap;

   4: shapePen.DashCap = this.StrokeDashCap;

   5: shapePen.LineJoin = this.StrokeLineJoin;

   6: shapePen.MiterLimit = this.StrokeMiterLimit;

   7: shapePen.DashStyle = 

   8:         new DashStyle(this.StrokeDashArray, this.StrokeDashOffset);

Now comes a tricky part.

 

We need to construct our opacity mask. Opacity mask is a Brush and it gets applied to the whole drawing area of the element. The size of that area depends not only on the geometry of our shape but on the size of it’s stroke, it’s miter, etc. For example if you have a line from point (0, 0) to (0, 100) and the StrokeThickness is set to 100 you’d get a line that (at the very least) occupies space from -50 to 50 on the Y-axis and it could be more dependent on the caps of that line and other settings. So, in order to get the final bounds of our shape before we actually draw it we create a temporary drawing using our actual pen settings and use it’s bounds as a rectangle area for our mask:

   1: GeometryDrawing maskBoundsDrawing = 

   2:     new GeometryDrawing(Brushes.Black, shapePen, this.Data);

   3: Rect bounds = maskBoundsDrawing.Bounds;

Then we get the geometries for our bullet holes (see the source code for details) and exclude them from our rectangular area. This way we get a geometry which is a rectangle with a holes in it.

   1: RectangleGeometry maskRect = new RectangleGeometry(bounds);

   2: Geometry maskGeometry = 

   3:     Geometry.Combine(maskRect, holes, GeometryCombineMode.Exclude, null);

Now we need to create a brush for our opacity mask from this geometry.

We create a GeometryDrawing using any opaque brush for it’s fill (Brushes.Black for example) and create a DrawingBrush from this drawing. It’s important to set brush’s Stretch property to None so it’s not distorted in any way.

   1: GeometryDrawing maskDrawing = 

   2:     new GeometryDrawing(Brushes.Black, null, maskGeometry);

   3: DrawingBrush maskBrush = new DrawingBrush(maskDrawing);

   4: maskBrush.Stretch = Stretch.None;

And now all that’s left is to push our opacity mask on a DrawingContext, draw our shape (opacity mask will make sure that there are holes on the junction points), pop the mask and draw the bullets:

   1: // apply opacity mask

   2: drawingContext.PushOpacityMask(maskBrush);

   3: // draw main shape

   4: drawingContext.DrawGeometry(this.Fill, shapePen, this.Data);

   5: drawingContext.Pop();

   6: // draw bullets

   7: RenderBullets(drawingContext);

And that’s it.

 

I’ve omitted implementations of the other reasonably trivial tasks like drawing the bullets from the article but you can always take a look at the implementation by downloading the source code of BulletedPath control.

 

You can download the binary control, C# source code and class reference from download section of my blog. It’s released under the BSD license so feel free to use and improve it.

 

About the author: Alan Mendelevich is a software developer from Vilnius, Lithuania. He has more than 10 years of professional software development experience for both Web and Windows. Currently he works as a lead developer on amCharts for WPF project – a charting control suite for WPF platform and SPAW Editor – open source web based WYSIWYG HTML editor control.


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Amit" Tags: ".Net, Silverlight, WPF, BulletedPath, Bu..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 19 May 2009 10:34

Let me share you with one of the weirdest errors I ever encountered. Recently, I have been working on a distributed application which is built from a server and some clients. The clients are Windows Forms applications. Yesterday, I spent a whole day chasing a very weird and strange error – I was getting an exception at the main method (unhandled exception) of the client application. Here is what I got:

image

The error description was: “Parameters count mismatch“. Well, it didn’t help me a lot, but I thought that looking at the stack trace might be a good idea. So, here it is:

image

As you can see, there is nothing helpful here because the stack trace is full of .Net Framework methods, none of those methods are mine. Well after a whole day, trying to understand what happened, I figured out what was wrong. Take a look at the very simplified version of my code:

delegate void ChangeColorEventHandler(object sender, Color color);

private void ChangeColor(object sender, Color newColor)
{
    if(InvokeRequired)
    {
        BeginInvoke(new ChangeColorEventHandler(ChangeColor), newColor);
        return;
    }
    BackColor = newColor;
}

The ChangeColor method is changing the form back color on the UI thread. This method was called due to a server request, not because of a user action. Do you see what is wrong here? I didn’t set the sender as a parameter to the BeginInvoke method. That is it! It turns out that if you get this strange error, you probably called a BeginInvoke or Invoke methods with a wrong set of parameters. After changing my code to:

private void ChangeColor(object sender, Color newColor)
{
    if(InvokeRequired)
    {
        BeginInvoke(new ChangeColorEventHandler(ChangeColor), sender, newColor);
        return;
    }
    BackColor = newColor;
}

Everything was fine. Hope it would be helpful for some of you one day…


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Shahar Y" Tags: ".Net, C#, BeginInvoke, Error, exception,..."
Comments Send by mail Print  Save  Delicious 
Date: Monday, 04 May 2009 14:57

This article was written by Alan Mendelevich

 

Hi

 

Recently I’ve been working on a set of custom WPF controls.

There are numerous good books and articles about WPF in general and some basic information on custom control development but I have yet to find a good article (or book) with in-depth coverage of custom control development in general and design-time related issues in particular.

 

I’ve done my share of custom ASP.NET control development (see ASP.NET Controls for amCharts http://www.amcharts.com/aspnet, or SPAW Editor ASP.NET Edition http://spaweditor.com), and actually the basic principles are not that different. However some things should be implemented in a totally different manner and it wasn’t really obvious to me where those differences start and what to do about them. I’ve spent quite some time figuring these things out, so I decided to share my findings here hoping that it would save someone some time which could be better spent implementing new features.

 

This article covers several areas related to WPF Designer related features/issues which are implemented using different means than you would use while building ASP.NET/WinForms controls.

 

Metadata Store and Separate Metadata Assembly

Some design-time related attributes like CategoryAttribute (which specifies grouping category in property grid) could be set on a property the “old-fashioned” way, but general approach has switched toward the Metadata Store. Metadata store is a mechanism used by WPF Designer to decouple design-time metadata from implementation.

 

Design-time metadata is deployed in separate specialized assemblies which should follow specific naming conventions in order for design tools to find and use them. You create an assembly with “.Design” appended to the main assembly name for general design-time metadata.

 

For example if you have an implementation assembly called MyLibrary.dll then design-time metadata should reside in MyLibrary.Design.dll. Specialized Visual Studio or Expression Blend metadata could be placed in additional MyLibrary.VisualStudio.Design.dll and MyLibrary.Expression.Design.dll.

In addition to general good design principles, separation of design-time metadata into specialized assemblies has one very practical implication, most of the new attribute classes are defined in the Microsoft.Windows.Design.dll. If you add a reference to this DLL to your implementation project users of your control will most likely get an exception like “Unable to install or run the application. The application requires that the assembly Microsoft.Windows.Design Version 3.5.0.0 be installed in the Global Assembly Cache (GAC) first. Since it’s not a part of normal .NET deployment runtime.

To create a metadata store, you create a new project, add a reference to Microsoft.Windows.Design.dll to it and create a class that implements IRegisterMetadata interface like this:

   1: namespaceMyLibrary.Design

   2: {

   3:     internal classMyLibraryMetadata : IRegisterMetadata

   4:     {

   5:         public void Register()

   6:         {

   7:AttributeTableBuilder builder = newAttributeTableBuilder();

   8:builder.AddCustomAttributes(typeof(MyClass)

   9:                                       ,newToolboxBrowsableAttribute(false));

  10:MetadataStore.AddAttributeTable(builder.CreateTable());

  11:         }

  12:     }

  13: }

The IRegisterMetadata interface requires you to implement only one method – Register(). In this method you create an instance of AttributeTableBuilder and add attributes to your classes, properties, methods, etc. one-by-one using AddCustomAttributes() method. Then you add this table to the MetadataStore.

 

Toolbox visibility

When you create a control library you will most likely create some classes deriving from Control class (or one of it’s derivatives), you don’t want then to show up in the Visual Studio toolbox along your main controls. In ASP.NET/WinForms you would use the ToolboxItem(false) attribute to achieve that. However the WPF designer pays no attention to this attribute. For the WPF designer you should use ToolboxBrowsableAttributefrom the Microsoft.Windows.Design namespace. You attach it to your classes like this:

 

   1:builder.AddCustomAttributes(typeof(MyClass)

   2:         , newToolboxBrowsableAttribute(false));

 

Toolbox icon

You can add toolbox icon for your controls using ThumbnailAttribute class. However this attribute was only added in .NET 3.5 Service Pack 1. So, you have to make a choice here, supporting .NET 3.5 without SP1 and earlier versions of the .NET Framework, or specifying different thumbnails for Visual Studio and Expression Blend.

A simple and version agnostic method is to add images named according to the specific naming convention of your project. The convention is to name an image in a form of ClassName.Icon.ext. So, if you have a class named MyControl, then your icon should be named MyControl.Icon.png (for example).

 

Collection editors

In previous .NET designer technologies you had to create a class derived from System.ComponentModel.Design.CollectionEditor if you wanted to allow users to add objects of more than one type to collections through the collection editor in Visual Studio. The approach is demonstrated in this CodeProject article.

 

In WPF this no longer works.

 

But fortunately you can achieve the same result just by setting NewItemTypesAttribute on your property. This is how it’s done. Suppose you have a property defined as a collection of brushes like this:

   1:List<Brush> MyBrushes;

And you want users to be able to add SolidColorBrush and LinearGradientBrush objects to this collection via collection editor in Visual Studio. You do this by attaching NewItemTypesAttribute attribute in Register method of your metadata class like this:

   1:builder.AddCustomAttributes(typeof(MyClass), "MyBrushes",

   2:     newNewItemTypesAttribute(typeof(System.Windows.Media.SolidColorBrush),

   3:     typeof(System.Windows.Media.LinearGradientBrush)));

   4: 

 

Conclusion

This article touched only some of the issues which developers new to WPF control development may encounter. As WPF gains more and more popularity eventually someone will write a good book and/or tutorial on the subject. Maybe someone already did and I just wasn’t lucky to find it. If so, please, let me know by commenting.

However there’s pretty detailed coverage of WPF designer extensibility in this MSDN library section  even though it’s is not written in a very narrative tutorial-like style.

 

Alan.

As a bonus to this article Alan has included a 50% discount coupon for the WPF charting controls (http://wpf.amcharts.com) he has been working on lately. All you have to do is enter “dev102” (without quotes) when ordering it.


Copyright © 2008
This feed is for personal, non-commercial use only.
The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. (Digital Fingerprint:
)
Author: "Amit" Tags: ".Net, WPF, Attribute, Blend, Custom Cont..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 28 Apr 2009 08:12

JQuery has simplified a lot of my day to day coding. I think it is an amazing little framework and apparently a lot of people do too. Even Microsoft is bundling it with its ASP.NET MVC framework which , as far as I know, a first for open source software. Beyond even handling all the all of the cross browse mess, my favorite part of jQuery is the ability to easily extend the framework through plug-in. That brings us to the topic for this post. We are going to look at how easy it is to create a plug-in for jQuery.

What Will Our Plugin Do?

For this post I want to pick something that is fairly simple yet demonstrates the power of plugins. For this post I am going to show you how to create a plug-in that will highlight keywords in a given block of text. Many websites use something similar when performing searches.

 

The Anatomy Of A Plugin

A good guideline to follow when creating the file for your plug-in is use the following convention: jquery.pluginName.js. Keeping this in mind lets create a file called jquery.hightlight.js. Now in our main HTML file we should have something like the following.

   1: <html>

   2: <head>

   3:     <title>My jQuery Plugin</title>

   4: </head>

   5: <body>

   6:     <div class="mytext">

   7:         This is some text that contains some words that I want to

   8:         highlight using my jQuery plug-in. This plug-in will highlight

   9:         all instances of the one or more words it is

  10:         given.

  11:     </div>

  12:     <script type="text/javascript" src="jquery-1.3.2.js"></script>
   3:     <script type="text/javascript" src="jquery.plugin.js"></script>

   3:     <script type="text/javascript"></script>

  13: </body>

  14: </html>

In jquery.highlight.js we will create the shell of our plug-in.

   1: (function($)

   2: {

   3:     $.fn.highlight = function(words, options)

   4:     {

   5:         var defaults = { };

   6:         var options = $.extend(defaults, options);

   7:         if(typeof words == 'string')

   8:         {

   9:             words = [ words ];

  10:         }

  11:         return this.each(function() { });

  12:     };

  13: })(jQuery);

In the above code we are passing the jQuery object into our plug-in so we can extend it. It is recommend that you use jQuery instead of $ to avoid conflicts with other libraries.

 

Plugins always extend the fn object of jQuery as you can see where we created $.fn.highlight. Next we created a defaults object which we will fill out later on and then merge the defaults with the passed in options. On the next line we check to see of the words object is a string. If it is we turn it into an array. This way the plug-in will accept a single word as a string or an array of words to be highlighted. Finally, we return the this object which contains all the elements that jQuery found that met the selector we used. Before the plug-in returns it loops over each of the found elements so we can do our highlighting on them.

 

Completing Our Plugin

Using the shell we created above we can create the code that does the highlighting. First lets define our default values in case there aren’t any options passed into the plug-in.

   1: var defaults = { backcolor: 'yellow', forecolor: 'black' };

Now let’s highlight our words.

   1: return this.each(function()

   2: {

   3:     for(var i=0;i<words.length;i++)

   4:     {

   5:         var span = '' + words[i] + '';

   6:         this.innerHTML = this.innerHTML.replace(

   7:             new RegExp(words[i], 'gi'), span);

   8:     }

   9: });

This is pretty simple. We are looping through each of our words. We are wrapping the words in a span tag that uses CSS to define a background and foreground color. Then we simply do a find and replace on the elements innerHTML. It is that easy. You can see a demo of this plug-in our freebies page. Stay tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.


Author: "Justin" Tags: "Web Dev, ASP.NET MVC, JavaScript, jQuery..."
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 22 Apr 2009 04:39

Hey all,

 

a while back we had 2 great posts and one page about visual studio shortcuts. The first one had a list of 10 Visual Studio Shortcuts and the second one had 11 Visual Studio Shortcuts. We also have a Visual Studio CheatSheet with all the Keyboard shortcuts Visual Studio has.

 

Here is another list of 5 Shortcuts I have picked up along the way.

 


Author: "Amit" Tags: "Visual Studio, ALT, CTRL, SHIFT, Shortcu..."
Comments Send by mail Print  Save  Delicious 
Date: Friday, 17 Apr 2009 09:19

Hey all.

 

Nothing new for this month so apart from reminding you that if you want to make a quick 30$ all you have to do is to drop us a good unique article (you can get more information on our Make Money Writing Articles Page). I will move on to the stats.

 

Here are March’s Stats:

 

Traffic Stats

  • Visits: 37,663 (31,456)
  • Page Views: 49,908 (43,187)
  • Rss Readers: 1025 (994)
  • Twiter Followers: 55 (35)
  • Alexa Rank: 200,253 (225,471)
    1. 12,627 Israel
    2. 28,631 Sweden
    3. 47,156 Bulgaria
    4. 61,470 India
    5. 90,953 Turkey
    6. 120,277 United Kingdom
    7. 120,797 Italy
    8. 152,304 United States
    9. 156,169 Canada
    10. 157,090 China
    11. 168,691 Poland
    12. 189,156 Russia
    13. 282,951 Spain
    14. 368,151 Germany 

Top 5 Traffic Sources

  1. Google : 28,402 (23,550) Visits.
  2. Direct : 3,184 (2,705) Visits.
  3. DotNetKicks : 1,612 (1,052) Visits.
  4. StumbleUpon : 656 (550) Visits.
  5. Yahoo: 523 (558) Visits.

Top 10 KeyWords 

  1. linq to xml : 402 (321) Visits.
  2. visual studio shortcuts : 289 (340) Visits.
  3. nunit visual studio 2008  : 217 (135) Visits.
  4. wpf context menu : 175 (148) Visits.
  5. wpf contextmenu :142 (119) Visits.
  6. nunit visual studio : 125 (125) Visits.
  7. quake online : 119 (175) Visits.
  8. sortedlist : 98 (77) Visits.
  9. visual studio 2008 shortcuts : 96 (81) Visits.
  10. wpf binding converter : 87 (79) Visits.

Top 10 Articles

  1. 10 Visual Studio Shortcuts You Must Know : 2,099 (2,048) Visits.
  2. 3 Ways to Run NUnit From Visual Studio :  1,451 (1,263) Visits.
  3. Creating an Ajax Login Form With jQuery : 1,366 (New) Visits.
  4. How To Create a WPF Custom Context Menu : 1,333 (1133) Visits.
  5. LINQ to XML in 3 Easy Steps :  1289 (1,040) Visits.
  6. 11 More Visual Studio Shortcuts You Should Know : 1,093 (976) Visits.
  7. Measure String Size In Pixels (C#) : 1061 (831) Visits.
  8. When a Company Logo Doesn’t Come Out So Good : 970 (758) Visits.
  9. How to Create Interactive Form Validation Using Ajax : 913 (743) Visits.
  10. How to reset Identity Increment value in MS SQL : 911 (834) Visits.

That’s it.

If you are interested in Knowing anything else, Just ask

Amit


Author: "Amit" Tags: "Misc., Technology & Internet, create, NU..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 14 Apr 2009 07:02

Tab menus are a fairly common thing that I use in a lot of my applications. I like tabs because they help break up large chunks of, usually, related information.

 

At work we use RadControls for Telerik and they have a pretty nice tab menu control that is easy to use and looks good too. The only problem with these controls is that they only work in WebForms like even the default ASP.NET controls. So when I started playing with MVC I quickly realized I would need to spend some time building some of these controls myself.

Based on that realization, the idea for this post was formed and I set to work creating a fair simple control. This control is not meant to be compared with the control from Telerik. Mine is very basic and has very few features.

 

Again, I will be using the default MVC template project as my starting point. I did make a few minor changes to the MasterPage but I will include the finished Visual Studio project with this post so you can take a look for yourself.

The first step is to create the HtmlHelper extension method that will generate our control. This method will do most of the work we need.

   1: public static class MyHtmlHelper
   2: {
   3:     public static string TabbedMenu(this HtmlHelper helper, IEnumerable<MenuTab> tabs)
   4:     {
   5:         var route = helper.ViewContext.RequestContext.RouteData;
   6:         var controller = route.GetRequiredString("controller");
   7:         var action = route.GetRequiredString("action");
   8:         var menu = "\n\n<ul id=\"menu\">";
   9: 
  10:         foreach (var tab in tabs)
  11:         {
  12:             if (controller == tab.Controller && action == tab.Action)
  13:                 menu += "\n\t<li>" + helper.ActionLink(tab.Text, tab.Action,
  14:                 tab.Controller, new { @class = "selected" }) + "</li>";
  15:             else
  16:                 menu += "\n\t<li>" + helper.ActionLink(tab.Text,
  17:                 tab.Action, tab.Controller) + "</li>";
  18:         }
  19:         menu += "\n</ul>\n\n";
  20:         return menu;
  21:     }
  22: }

So what this method does is it accepts an IEnumberable collection of MenuTab. We’ll look at the MenuTab class in just a bit. Next the method gets the names of both the current controller and action. These will be used to determine which tab is currently selected. Then the method uses a foreach to loop through the collection and build out the HTML unordered list. Notice that during the loop we are checking to see if the MenuTab instance’s controller and action match the current controller and action. If they make we apply the selected CSS class to the anchor. Pretty simple stuff.

Note: All this method does is produce the required HTML markup. CSS is used to achieve the tab look.

Now let’s look at the MenuTab class.

   1: public class MenuTab
   2: {
   3:     private MenuTab(string text, string action, string controller)
   4:     {
   5:         Text = text;
   6:         Action = action;
   7:         Controller = controller;
   8:     }
   9: 
  10:     public static MenuTab Create(string text, string action, string controller)
  11:     {
  12:         return new MenuTab(text, action, controller);
  13:     }
  14: 
  15:     public string Text { get; private set; }
  16:     public string Action { get; private set; }
  17:     public string Controller { get; private set; }
  18: }

This class is very simple. It just stores the information we will need to build the links in our menu.

That covers off the extension method and any related code. As you can see I wasn’t kidding when I said it doesn’t have many features. This only meant to should how to get started.

In order to make the menu look like tabs a made a few minor tweaks to the existing Site.css file and added the below class definition to indicate which tab is selected.

   1: ul#menu li a.selected {
   2: background-color: #fff;
   3: color: #000;
   4: }

Now all that is left is to insert our menu into the Site.Master file of our application.

   1: <%= Html.TabbedMenu(new List<MenuTab> {
   2: MenuTab.Create("Home", "Index", "Home"),
   3: MenuTab.Create("About", "About", "Home"),
   4: MenuTab.Create("Services", "Services", "Home"),
   5: MenuTab.Create("Pricing", "Pricing", "Home"),
   6: MenuTab.Create("Contact", "Contact", "Home")
   7: }) %>

I replaced the menu code that was already in the demo with the above code that defines the links in our menu.

So as you can see it was pretty simple to build an extension method to add our own helper method for building a tab like menu. By encapsulating this into a helper method we can now easily reuse it in any application.

You can download a sample project from our Freebies Page

Stay tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.


Author: "Justin" Tags: "ASP.Net, C#, Web Development, action, AS..."
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 09 Apr 2009 07:30

Hi

 

I wanted to show the usage of these two very useful debugger attributes. If you don’t know them keep on reading, they are very useful.

 

DebuggerDisplay

This attribute allows you to customize the way an object is displayed. lets look at the following example:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         Client c = new Client() 
   6:         { 
   7:             Name = "John", 
   8:             HomeNumber = "555-0094", 
   9:             AccountBalance = -5000 
  10:         };
  11:     }
  12: }
  13:  
  14: class Client
  15: {
  16:     public string Name { get; set; }
  17:     public string HomeNumber { get; set; }
  18:     public double AccountBalance { get; set; }
  19: }

When we hover above the object c we get the following:

No Debugger Attribute

We can make this much more “appealing” by using the DebuggerDisplay attribute. By using the DebuggerDisplay you can create a string that will replace what Visual Studio shows by default. For example you can add the following attribute:

   1: [DebuggerDisplay(" This is a client Named {Name}, His Home Phone Number" +
   2:         "is {HomeNumber} and his Account Balance is {AccountBalance}")]

Now once we hover above the object c we get the following:

DebuggerDisplay Attribute

Pretty neat no?

You can customize the view in almost any way you want and you can even call method that belong to the class inside the marked {}.

 

DebuggerBrowsable

Lets add to the client class a list of strings that will represent SubAccounts he might have. Using DebuggerBrowsable we have 3 options to mark that list and one of them is extremely useful:

  1. DebuggerBrowsableState.Collapsed: This is the default value and keeps the view exactly the way you know.

    DebbugerBrowsable.Collapsed

  2. DebuggerBrowsableState.RootHidden: This makes the root of the List hidden and expands the list, so a 3 items list will look like this:

    DebuggerBrowsable.RootHidden

    As you can see the list is all expanded and the List Data is under the Raw View. If you ask me I don’t really see a real life use for this.

  3. DebuggerBrowsableState.Never: This makes the list go away! you cant see it in debug. I find this useful for people who write infrastructures in their company. Sometimes you don’t want to other users to see that list. This is your way of hiding it:

    DebuggerBrowsable.Never 
    How about that, No List!

More on other Debugger Attributes soon

 

Enjoy.

 

Amit


Author: "Amit" Tags: ".Net, C#, Visual Studio, Attribute, Coll..."
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 02 Apr 2009 16:52

Hi

 

Here is a problem that one of my colleagues who is just starting to use WPF got himself into. He was working on an application that displays items using an ItemsControl and uses a DataTemplate. Inside the DataTemplate he used an Image. Here is the Xaml code:

 

   1: <Window.Resources>
   2:         <Image Source="Creek.jpg" x:Key="IMG"></Image>
   3:     </Window.Resources>
   4:     <Grid>
   5:         <ItemsControl ItemsSource="{Binding}">
   6:             <ItemsControl.ItemTemplate>
   7:                 <DataTemplate>
   8:                     <Border BorderThickness="2" BorderBrush="Black" 
   9:                             CornerRadius="3" MinHeight="10">
  10:                         <ContentControl Content="{StaticResource IMG}"/>
  11:                     </Border>
  12:                 </DataTemplate>
  13:             </ItemsControl.ItemTemplate>
  14:         </ItemsControl>
  15:     </Grid>

This is a much simpler example, but the principal is the same.

 

Can you see what was he doing wrong?

 

In the code behind I will create a list and use it as the DataContext:

   1: public Window1()
   2: {
   3:    InitializeComponent();
   4:    List<int> data = new List<int> { 1, 2, 3, 4 };
   5:    this.DataContext = data;
   6: }

You will expect to see a window with 4 Images, but this is what you get:

Bad Resource Usage

Only one image shows up and all the other templates are empty.

 

Can you see the problem now?

 

It took me some time to see it because the code was much more complex, but then I noticed that he used the Image class as a resource for the Image.

 

Image is a WPF Control and can only have one parent! This is why it only displayed at the last item of the list. This is similar to doing the following:

   1: Image m = new Image();
   2: Border b1 = new Border();
   3: Border b2 = new Border();
   4: b1.Child = m;
   5: b2.Child = m;

What would happen here? The following:

Illegal child exception

I was actually surprised that my friend did not get an Exception, I will definitely have to check why no exception was thrown.

To correct the problem all you have to do is to use Bitmap Image which is a C# Class and not a WPF Control. You should use an Image in the template and use the BitmapImage as its source:

   1: <Window.Resources>
   2:    <!--<Image Source="Creek.jpg" x:Key="IMG"></Image>-->
   3:    <BitmapImage UriSource="Creek.jpg" x:Key="BMP"></BitmapImage>
   4: </Window.Resources>    
   5: <Grid>
   6:    <ItemsControl ItemsSource="{Binding}">
   7:        <ItemsControl.ItemTemplate>
   8:            <DataTemplate>
   9:                <Border BorderThickness="2" BorderBrush="Black" 
  10:                        CornerRadius="3" MinHeight="10">
  11:                    <!--<ContentControl Content="{StaticResource IMG}"/>-->
  12:                    <Image Source="{StaticResource BMP}"></Image>
  13:                </Border>
  14:            </DataTemplate>
  15:        </ItemsControl.ItemTemplate>
  16:    </ItemsControl>
  17: </Grid>

The result:

Good Resource Usage

 

Exactly what we wanted.

 

If any of you have an idea as to why we did not get an exception I will be happy to hear it.

 

Amit


Author: "Amit" Tags: ".Net, WPF, DataTemplate, image, ItemsCon..."
Comments Send by mail Print  Save  Delicious 
Date: Monday, 23 Mar 2009 14:01

In this post I want to show you how to use jQuery to create an AJAX login screen. I am going to use an ASP.NET MVC application for this demonstration. I will be modifying the small default application that is created when you create a new MVC application. So go ahead and create a new MVC application. I will be walking through the process step by step so when this article is done you will have a working application.

create-mvc-app

Step 1

Open LogOnUserControl.ascx. This is found in /Views/Shared/. What we want to do is modify the link to include an onclick attribute which will fire the login() event handler and assign an id to the link. The code should look like this:

 

   1: <%= Html.ActionLink("Log On", "LogOn", "Account", null,
   2: new { onclick = "return login();", id = "login_link" })%>

 

Step 2

Open the Site.Master master page, also located in /Views/Shared/, add  the links to our stylesheet, jQuery, and our JavaScript file in the head section of the document.

   1: <link type="text/css" rel="stylesheet" href="../../Content/login.css" />
   2: <script type="text/javascript" src="../../Scripts/jquery-1.2.6.min.js"></script>
   3: <script type="text/javascript" src="../../Scripts/login.js"></script>

Go ahead and create a login.css file in /Content/ and a login.js file in /Scripts/. Leave them empty for now.

 

Step 3

While still in Site.Master, add the following code at the bottom of the page, just before the closing body tag. This is our login form that we will use. The code contains a div element with the id lightbox that will cover the screen to make our login form act as a model dialog. The lightbox will be a transparent black color.

In addition to the form input elements there is also a div element called message that will server as an area for us to output messages.

<div id="lightbox"></div>
<div id="login_outer_container">
<div id="login_form">
<div id="message"></div>
<fieldset>
<legend>Login Information</legend>
<p>
<label for="username">Username:</label>
<%
   = Html.TextBox("username")

%>
<%

   = Html.ValidationMessage("username")

%>
</p>
<p>
<label for=”password”>Password:</label>
<%

   = Html.Password("password")

%>
<%

   = Html.ValidationMessage("password")

%>
</p>
<p>
<%

   = Html.CheckBox("rememberMe")

%> <label class=”inline” for=”rememberMe”>Remember me?</label>
</p>
<p>
<input type=”button” value=”Log On” onclick=”submitForm();” />
<input type=”button” value=”Cancel” onclick=”cancelLogin();” />
</p>
</fieldset>
</div>
</div>

 

Step 4

Add the following code to login.css. This will style our form elements.

   1: #lightbox {
   2: position: absolute;
   3: top: 0;
   4: left: 0;
   5: width: 100%;
   6: background: black;
   7: filter: alpha(opacity=60);
   8: opacity: 0.6;
   9: display: none;
  10: }
  11: 
  12: #login_outer_container {
  13: position: absolute;
  14: top: 50%;
  15: left: 50%;
  16: }
  17: 
  18: #login_form {
  19: position: relative;
  20: top: -125px;
  21: left: -200px;
  22: width: 400px;
  23: height: 250px;
  24: display: none;
  25: background: white;
  26: padding: 10px;
  27: border: 1px solid #424242;
  28: }
  29: #message {
  30: display: none;
  31: border: 1px solid #b8b8b8;
  32: background: #f6f3f6;
  33: padding: 5px;
  34: color: Red;
  35: }
  36: 

 

Step 5

Alright, this is where the real magic happens. We are going to add code to login.js. I will go slow and explain what each function is doing and why it matters to our application.

The first function we are going to add is the login() event handler we mentioned earlier in the post. In this function we are getting the lightbox element and assigning some stylesheet properties to it. Notice that we are setting the filter attribute even thought we did so in login.css. For some reason IE keep losing this setting so we had to add it again. We are also telling lightbox to fade in slowly.

Next we get the main login form element and tell it to also fade in slowly.

Finally, we return false to prevent the link from jumping to it’s href value. We don’t want to cause a page refresh.

   1: function login() {
   2: $('#lightbox')
   3: .css({
   4: 'height': $(document).height(),
   5: //reset opacity because IE loses it on open 
   6: 'filter': 'alpha(opacity=60)'
   7: })
   8: .fadeIn('slow');
   9: $('#login_form').fadeIn('slow');
  10: return false;
  11: }

Now when a user clicks the [ Log On ] link an impressive login form will fade into the center of the screen.

Notice how we set the height of the lightbox to the current height of the document. If the user resizes the browser window this will cause the lightbox to be too big and add scroll bars or cause the lightbox to be too small, all depending how the window is resized. To fix this this problem we will create a function that will set lightbox to the current height of the document and setup an event handler that will fire our function every time the window is resized.

   1: function adjustLightbox() {
   2: $('#lightbox').css({ 'height': $(document).height() });
   3: };
   4: 
   5: var resizeTimer = null;
   6: $(window).bind('resize', function() {
   7: if (resizeTimer) clearTimeout(resizeTimer);
   8: resizeTimer = setTimeout(adjustLightbox, 100);
   9: });
  10: 

When we created our login form markup we added an input button that had an onclick handler called cancelLogin(). If the user clicked this button we wanted to cancel the login form, clear an input, and restore the main screen. Let’s create that function.

This function first tells lightbox and the main login form to slowly fade out which will restore the main screen.

Next we clear the value of all input elements that are not buttons and make sure the remember me checkbox is not checked.

Lastly, we clear and messages that were output and hide the message element.

   1: function cancelLogin() {
   2: $('#lightbox').fadeOut('slow');
   3: $('#login_form').fadeOut('slow');
   4: $('#login_form input[type!=button]').val('');
   5: $('#login_form input[type=checkbox]').each(function(i) {
   6: this.checked = false;
   7: });
   8: $('#message').html('').css({ 'display' : 'none' });
   9: }

This brings us to out last function which will submit the form when the user clicks submit. First create the submitForm function. This function has been assigned to the submit button’s onclick handler in our HTML.

   1: function submitForm() {
   2: 
   3: }
   4: 

The first thing we need to do is get the values from our three form elements, username, password, and remember me.

   1: var username = $('#username').value;
   2: var password = $('#password').value;
   3: var rememberMe = $('#rememberMe').checked ? 'true' : 'false';

At this point you can do any form validation you want against the values. I am not going to include any validation in this demonstration.

Next we’ll build a data string out of our three values.

   1: var dataString = 'username=' + username + '&password=' + password + '&rememberMe='
   2:  + rememberMe;

Finally we will setup our AJAX call to the server to authenticate the user. We will use the data string we just setup as the data to pass to the request. We have also setup success and failure callbacks.

If the request succeeds we will call the cancelLogin() function to close the login form and change the Log On link to say Log Off.

If the request fails, we’ll show the user an error message.

   1: $.ajax({
   2: type: 'POST',
   3: url: '/Account/LogOn',
   4: data: dataString,
   5: success: function() {
   6: cancelLogin();
   7: $('#login_link').html('Log Off').href = '/Account/LogOff';
   8: },
   9: error: function() {
  10: $('#message').html('Failed to login')
  11: .css({ 'display': 'block' });
  12: }
  13: });

That pretty much finishes things off. you should now have a working login form. Stayed tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.


Author: "Justin" Tags: "ASP.Net, Web Development, AJAX, ASP.NET ..."
Comments Send by mail Print  Save  Delicious 
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader