Monday, April 26, 2010

Customizing Fiddler for Omniture scripts

 

 

One of the best ways to investigate your Omniture implementation is to watch the actual traffic that is being sent by your site. To assist with this, Omniture provides a JavaScript debugger (search “Debugger” in the SiteCatalyst Knowledge Base). But sometimes, you need to break out the good ol’ packet sniffer to watch the actual traffic being sent.

The trouble with Fiddler is that it will watch all of your requests, making it difficult to isolate the Omniture requests that you’re looking for.

Fortunately, you can configure a custom filter in Fiddler, which will exclude non-Omniture calls. This makes is more convenient to use Fiddler to look at server requests sent to Omniture. Creating the filter is a little bit geeky, but very easy to do. Here’s how you do it:

1. Open Fiddler


2. From the Main Menu, select Rules > Customize Rules…

 

3. Add the following code to the class handlers. This adds the menu item, and turns it on by default.

public static RulesOption("&Omniture Only")
var m_OmnitureOnly: boolean = true;

4. Add the following code to the static function OnBeforeRequest. This is the logic for the filter. It tells Fiddler to only include requests that match the pattern 2o7.net. You can change the filter value by changing the value of var re.

if (m_OmnitureOnly){
  var re = /2o7.net/;
    if (!re.test(oSession.host)){ 
         }
}

5. Fiddler will now show you only Omniture requests, as long as the “Omniture Only” rule is selected in the Rules menu.

Once you have configured Fiddler to show you the Omniture server requests, be sure to check out the Debugger white paper in the SiteCatalyst knowledge base for more information on what the different parameters mean.

Thursday, April 22, 2010

Cool Fire Fox Addons:

 

Web Developer

The Web Developer extension adds a menu and a toolbar to the browser with various web developer tools

https://addons.mozilla.org/en-US/firefox/addon/60

 

Firebug

  • Inspect HTML and modify style and layout in real-time
  • Use the most advanced JavaScript debugger available for any browser
  • Accurately analyze network usage and performance
  • Extend Firebug and add features to make Firebug even more powerful
  • Get the information you need to get it done with Firebug.

https://addons.mozilla.org/en-US/firefox/addon/1843

DOM Inspector

Inspects the structure and properties of a window and its contents with a variety of views.

https://addons.mozilla.org/en-US/firefox/addon/6622

Monday, April 19, 2010

Auto-Implemented Properties in VB.Net

 

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. When you write code for an auto-implemented property, the Visual Basic compiler automatically creates a private field to store the property variable in addition to creating the associated Get and Set procedures.

With auto-implemented properties, a property, including a default value, can be declared in a single line. The following example shows three property declarations.

 

Public Property Name As String
Public Property Owner As String = "DefaultName"
Public Property Items As New List(Of String) From {"M", "T", "W"}
Public Property ID As New Guid()

An auto-implemented property is equivalent to a property for which the property value is stored in a private field. The following code example shows an auto-implemented property.

 

Property Prop2 As String = "Empty"

The following code example shows the equivalent code for the previous auto-implemented property example.

 

Private _Prop2 As String = "Empty"
Property Prop2 As String
Get
Return _Prop2
End Get
Set(ByVal value As String)
_Prop2 = value
End Set
End Property

Backing Field






When you declare an auto-implemented property, Visual Basic automatically creates a hidden private field called the backing field to contain the property value. The backing field name is the auto-implemented property name preceded by an underscore (_). For example, if you declare an auto-implemented property named ID, the backing field is named _ID. If you include a member of your class that is also named _ID, you produce a naming conflict and Visual Basic reports a compiler error.

The backing field also has the following characteristics:



  • The access modifier for the backing field is always Private, even when the property itself has a different access level, such as Public.



  • If the property is marked as Shared, the backing field also is shared.



  • Attributes specified for the property do not apply to the backing field.



  • The backing field can be accessed from code within the class and from debugging tools such as the Watch window. However, the backing field does not show in an IntelliSense word completion list.


Initializing an Auto-Implemented Property






Any expression that can be used to initialize a field is valid for initializing an auto-implemented property. When you initialize an auto-implemented property, the expression is evaluated and passed to the Set procedure for the property. The following code examples show some auto-implemented properties that include initial values.

 

Property FirstName As String = "James"
Property PartNo As Integer = 44302
Property Orders As New List(Of Order)(500)

You cannot initialize an auto-implemented property that is a member of an Interface, or one that is marked MustOverride.

When you declare an auto-implemented property as a member of a Structure, you can only initialize the auto-implemented property if it is marked as Shared.

When you declare an auto-implemented property as an array, you cannot specify explicit array bounds. However, you can supply a value by using an array initializer, as shown in the following examples.

 

Property Grades As Integer() = {90, 73}
Property Temperatures As Integer() = New Integer() {68, 54, 71}

Friday, April 16, 2010

Pagination Query with SQL Server 2005

 
Pagination can be done more easier through SQL queries.

CREATE Procedure Paging  @startIndex int , @endIndex int
AS
Begin
-- create the Common Table Expression, which is a table called "pagination"
with pagination as
(
    -- your normal query goes here, but you put your ORDER BY clause in the rowNo declaration
    select
        row_number() over (order by department, employee) as rowNo,
        -- a list of the column you want to retrieve
        employeeId, employee, department
    from
        Employee
    where
        disabled = 0
)
-- we now query the CTE table
select
    -- add an additional column which contains the total number of records in the query
    *, (select count(*) from pagination) as totalResults
from
    pagination
where
    RowNo between @startIndex and @endIndex
order by
    rowNo

End

If we want to see 50 to 60 records using paging query , just execute exec Paging  5,6 --> will return rows from 50 to 60.

Advantages : we doesn’t need to keep all records in memory by means of datasources , we can hold records corresponding to a particular page.

Silverlight 4.0 released with a bunch of new features

New features:

* XAP Signing : User cannot unpack zap files any more !!
* Custom window chrome for trusted applications
* Pinned full-screen mode : can view application in full screen mode , even if it is hosted in a browser.
* WCF RIA Services Toolkit
* ContextMenu control : right click and do the thing you want :-)
* SLLauncher silent installs

Enhanced features:
* RichTextBox improvements
* WebBrowser control
* Printing API enhancements
* Native automation (COM interop)
* Language/Script support
* Networking and Sockets
* User consent dialog on webcam/clipboard/etc.

more information available @ http://www.microsoft.com/silverlight/

Monday, April 12, 2010

Data Caching in ASP.Net

Cached Data Reference Pattern

Whenever an attempt is made to access data from the cache, it should be with the assumption that the data might not be there any more. Thus, the following pattern should be universally applied to your access of cached data. In this case, we're going to assume the object that has been cached is a DataTable.

public DataTable GetCustomers(bool BypassCache)
{
string cacheKey = "CustomersDataTable";
object cacheItem = Cache[cacheKey] as DataTable;
if((BypassCache) || (cacheItem == null))
{
cacheItem = GetCustomersFromDataSource();
Cache.Insert(cacheKey, cacheItem, null,
DateTime.Now.AddSeconds(GetCacheSecondsFromConfig(cacheKey),
TimeSpan.Zero);
}
return (DataTable)cacheItem;
}

There are several points I'd like to make about this pattern:

  • Values, like cacheKey, cacheItem and the cache duration, are defined once and only once.
  • The cache can be bypassed as needed—for example, after registering a new customer and redirecting to a list of customers, it would probably be best to bypass the cache and repopulate it with the latest data, which would include the newly inserted customer.
  • Cache is only accessed once. This has performance benefits and ensures that NullReferenceExceptions don't occur because the item was present the first time it was checked but had expired before the second check.
  • The pattern uses strong type checking. The "as" operator in C# will attempt to cast an object to a type and will simply return null if it fails or if the object is null.
  • The duration is stored in a configuration file. All cache dependencies, whether file-based, time-based, or otherwise, should ideally be stored in a configuration file so that changes can be made and performance measured easily. I also recommend that a default cache duration be specified, and that the GetCacheSecondsFromConfig() method uses the default if no duration is specified for the cacheKey being used.

Monday, November 16, 2009

Behaviours and Triggers in Silverlight 3.0

Recently i read a excellent blog form Silverlight Show , this article is based on the above blog. Link


Prerequisite

In order to write behaviors and triggers you need to have installed the Microsoft Expression Blend SDK on your machine. After that you need to add a reference to the System.Windows.Interactivity.dll assembly which is located in:{Program Files}\Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\Silverlight

Behavior types

Currently you can use three types of bevahors: Behavour, TriggerAction and TargetedTriggerAction.


the Behavior class

For simple scenarios the generic Behavior class is excellent choice. This class has only two overridable methods which notify the current behavior when an object is attached and detached from it. For my post I will create two behaviors: the first one just inverts the color of an image, when the image is clicked, and the second is little more complicated – it adds an animation and creates a magnifier when the mouse is over the image.

The first thing you should do when creating behaviors is to create a new class which inherits from the generic class Behavior, where T is a dependency object. In the most cases you will inherit from the Behavior or Behavior.

public class InverseColorClickBehavior : 
    Behavior
{
    public InverseColorClickBehavior() :
        base()
    {
    }
}

For that particular case I am interested in the mouse click event. That’s why in the OnAttached method I will attach to the MouseLeftButtonDown event of the associated with that behavior object. And respectively in the OnDetaching method I will detach from that event.

protected override void OnAttached()
{
    base.OnAttached();
    this.AssociatedObject.MouseLeftButtonDown += 
        new MouseButtonEventHandler( AssociatedObject_MouseLeftButtonDown );
}
 
protected override void OnDetaching()
{
    base.OnDetaching();
    this.AssociatedObject.MouseLeftButtonDown -= 
        new MouseButtonEventHandler( AssociatedObject_MouseLeftButtonDown );
}

The only thing that's left is to add an inverse color effect to the associated object in the mouse Click event handler.

private void AssociatedObject_MouseLeftButtonDown( 
    object sender, MouseButtonEventArgs e )
{
    this.AssociatedObject.Effect = 
        this.AssociatedObject.Effect == null ?
            this.AssociatedObject.Effect = this.inverseColor :
            this.AssociatedObject.Effect = null;
}

Once we have created the bahavior we should attach it to a particular object.

<Image Stretch="Fill"
       Source="/Photos/Image1.jpg">
    <interactivity:Interaction.Behaviors>
        <local:InverseColorClickBehavior/>
    interactivity:Interaction.Behaviors>
Image>

"Get " width="100%" height="100%"> My second behavior is little more complicated. It hits more common scenario where you want to add an animation for example on the mouse over event. Again as the first example I will create a new class which inherits from the generic Behavior where T will be a FrameworkElement.

I want when the mouse is over the element to add a magnifier shader effect on the element and when the mouse leaves the element area to remove the effect. That’s why I want to handle the MouseEnter and MouseLeave events in order to enable and disable the effect. On the analogy of the previous case in the OnAttached method I will attach to the MouseEnter and MouseLeave events of the associated with that behavior object. And respectively in the OnDetaching method I will detach from that events. When the mouse is over the element I want to track the mouse move event. That’s why I will attach also to the mouse move event on entering and will detach from it on leaving the element area.

protected override void OnAttached()
{
    base.OnAttached();
 
    this.AssociatedObject.MouseEnter += 
        new MouseEventHandler( AssociatedObject_MouseEnter );
    this.AssociatedObject.MouseLeave += 
        new MouseEventHandler( AssociatedObject_MouseLeave );
}
 
protected override void OnDetaching()
{
    base.OnDetaching();
 
    this.AssociatedObject.MouseEnter -= 
        new MouseEventHandler( AssociatedObject_MouseEnter );
    this.AssociatedObject.MouseLeave -= 
        new MouseEventHandler( AssociatedObject_MouseLeave );
}
 
private void AssociatedObject_MouseLeave( object sender, MouseEventArgs e )
{
    this.AssociatedObject.MouseMove -= 
        new MouseEventHandler( AssociatedObject_MouseMove );
    this.AssociatedObject.Effect = null;
}
 
private void AssociatedObject_MouseEnter( object sender, MouseEventArgs e )
{
    this.AssociatedObject.MouseMove += 
        new MouseEventHandler( AssociatedObject_MouseMove );
    this.AssociatedObject.Effect = this.magnifier;
}

The whole work is done in the mouse move event handler.

private void AssociatedObject_MouseMove( object sender, MouseEventArgs e )
{
    ( this.AssociatedObject.Effect as Magnifier ).Center =
        e.GetPosition( this.AssociatedObject );
 
    Point mousePosition = e.GetPosition( this.AssociatedObject );
    mousePosition.X /= this.AssociatedObject.ActualWidth;
    mousePosition.Y /= this.AssociatedObject.ActualHeight;
    this.magnifier.Center = mousePosition;
 
    Storyboard zoomInStoryboard = new Storyboard();
    DoubleAnimation zoomInAnimation = new DoubleAnimation();
    zoomInAnimation.To = this.magnifier.Magnification;
    zoomInAnimation.Duration = TimeSpan.FromSeconds( 0.5 );
    Storyboard.SetTarget( zoomInAnimation, this.AssociatedObject.Effect );
    Storyboard.SetTargetProperty( zoomInAnimation, 
        new PropertyPath( Magnifier.MagnificationProperty ) );
    zoomInAnimation.FillBehavior = FillBehavior.HoldEnd;
    zoomInStoryboard.Children.Add( zoomInAnimation );
    zoomInStoryboard.Begin();
}

You can add this behavior in XAML the same way as the first one. And here is the demo for the second behavior (which covers maybe the most commonly used events for animations, effects, etc.). Just move your mouse cursor over the image.

"Get " width="100%" height="100%"> To summarize before continuing with the triggers, in my opinion the behaviors is very similar to the extension methods in C#. The only difference is that the behavior is a component. It encapsulates some functionality and can be attached to another component to extend its built-in functionality.

Using the TriggerAction class

In simple cases the Behavior class is perfect. The TriggerAction class is useful in much more common cases than the simple Behavior. The TriggerAction offers invoke method which is fired once an event trigger happens. When you use the Behavior class you require that the behavior is responsible for the attaching and detaching of the item events. In comparison when using the TriggerAction you specify which event triggers the action in the XAML,.

I will create a trigger that will apply an animation on the click event. The first step is to create a new class which inherits from the generic TriggerAction class.

public class WaveTrigger : TriggerAction
{
    protected override void Invoke( object parameter )
    {
        this.waveStoryboard.Begin();
    }
}

As you can see the Invoke method is the only required method that you need to have in your trigger. But often in the practice you will need to override several other methods of the class. In the constructor of our trigger I need to configure the animation and the storyboard.

public WaveTrigger() :
   base()
{
   this.waveAnimation = new DoubleAnimation();
   this.waveStoryboard = new Storyboard();
   this.waveEffect = new WaveEffect();
   this.InitializeTrigger();
   this.waveAnimation.AutoReverse = false;
   this.waveStoryboard.Children.Add( this.waveAnimation );
}
private void InitializeTrigger()
{
    this.waveAnimation.From = -this.WaveFrequency;
    this.waveAnimation.To = this.WaveFrequency;
    this.waveAnimation.Duration = this.WaveDuration;
}

In order to set the animated object as well as the animated property I need to override that the OnAttached method. If you try to do that, for example, in the constructor you won’t succeed due to the fact that the associated object is still unknown.

protected override void OnAttached()
{
    base.OnAttached();
    
    this.AssociatedObject.Effect = this.waveEffect;
    Storyboard.SetTarget( this.waveAnimation, 
        this.AssociatedObject.Effect );
    Storyboard.SetTargetProperty( this.waveAnimation, 
        new PropertyPath( WaveEffect.WavinessProperty ) );
}

The only required method you need to do in the Invoke method is to start the animation.

protected override void Invoke( object parameter )
{
    this.waveStoryboard.Begin();
}

In order to make my WaveTrigger configurable I will add several dependency properties (for the duration and for the frequency). This is pretty straightforward. Once we have our trigger the final step is to use it in the XAML.

<Image Stretch="Fill"
       Source="/Photos/Image3.jpg">
    <interactivity:Interaction.Triggers>
        <interactivity:EventTrigger 
                EventName="MouseLeftButtonUp">
            <local:WaveTrigger WaveFrequency="1.9" 
                WaveDuration="00:00:05"/>
        interactivity:EventTrigger>
    interactivity:Interaction.Triggers>
Image>


"Get " width="100%" height="100%"> 6. Using the TargetedTriggerAction class

The third type behavior is offered by the generic TargetedTriggerAction class. It represents an action that can be targeted to affect a totally different object rather than its associated object. I can’t remember any practical solution for that type of triggers, but in a few words it allows you to associate the trigger with an object, but to manipulate totally different element. Again as a first step I will create a new class which inherits from the TargetedTriggerAction class.

public class TurnImageTargetedTrigger : 
    TargetedTriggerAction
{
    protected override void Invoke( object parameter )
    {
    }
 
    protected override void OnAttached()
    {
        base.OnAttached(); 
        ( this.AssociatedObject as FrameworkElement ).Loaded += 
            new RoutedEventHandler( TurnImageTargetedTrigger_Loaded );
    }
 
    protected override void OnDetaching()
    {
        base.OnDetaching();
        ( this.AssociatedObject as FrameworkElement ).Loaded -= 
            new RoutedEventHandler( TurnImageTargetedTrigger_Loaded );
    }
 
    private void TurnImageTargetedTrigger_Loaded( object sender, RoutedEventArgs e )
    {
    }
}

The trick here is that the target object can be access only when the associated object is loaded. That’s why I need to attach to the Loaded event of the associated object. An Invoke method must also be defined with the only purpose to start the animation. After the trigger is ready we need to use it in the XAML. You can see how this can be done in the next code snippet.

<Image x:Name="imgToFlip" Stretch="Fill"
    Source="/Photos/Image4.jpg"/>
<Button Content="TurnImage">
    <interactivity:Interaction.Triggers>
        <interactivity:EventTrigger 
                EventName="Click">
            <local:TurnImageTargetedTrigger 
                TargetName="imgToFlip"/>
        interactivity:EventTrigger>
    interactivity:Interaction.Triggers>
Button>


"Get " width="100%" height="100%"> Behaviors and Expression Blend 3


The Properties pane you may adjust the behavior (setting properties, which event will fire it, etc.).

If you note in the Assets library except our behaviors created for the current solution there are several other behaviors which are listed in all Expression Blend projects. If you want your own custom behaviors also to be listed for all Blend project you need to register your assembly in the registry. You need to use the following path in the Registry Editor:

HKEY_CURRENT_USER(or HKEY_LOCAL_MACHINE) \Software\Microsoft\Expression\Blend\v3.0\Toolbox\Silverlight\v3.0

Using the DefaultTriggerAttribute

By default when you create a new TriggerAction, Expression Blend will associate it with the MouseLeftButtonDown event where it can, or with the Loaded event if the MouseLeftButtonDown is not available. However sometimes you may want a custom Action to be connected with a different default event. In order to do this you should use the DefaultTriggerAttibute:

public DefaultTriggerAttribute(Type targetType, Type triggerType, 
    params object[] parameters)

The first parameter is the type for which to create this Trigger, the second is the type of Trigger to create and the final is a list of constructor arguments to the Trigger when it is created. If you specify more than one attribute, the most derived targetType that is applicable when the user create the behavior will be used.

[DefaultTrigger(typeof(UIElement), typeof(EventTrigger), 
    "MouseLeftButtonDown")] 
[DefaultTrigger(typeof(ButtonBase), typeof(EventTrigger), 
    "Click")] 
public class WaveAction : TriggerAction 
{ 
}

If the WaveAction is dragged onto a Button, the Action will be created under a Click EventTrigger. However, if the WaveAction is dragged onto any other UIElement, a MouseLeftButtonDown trigger will be created.

Using the TypeConstraintAttribute

You can use the TypeConstraintAttribute to specify type constraints on the AssociatedObjectTargetedTriggerAction and EventTriggerBase. of

10. Final words

The motivation for adding behaviors in Silverlight 3 is twofold. First, the behaviors are somehow work-around for the missing triggers in Silverlight. They allow closing the gap between WPF and Silverlight. Second, they allow designers to add interactivity without needing to write any code. I like the behaviors and definitely will use them in any future projects. This post covers quite a bit ground. I hope it was useful for you. In the official siteReferences of Expression Blend you can find a lot of ready for use behaviors. Also see the section for more information.

11. References