Rar and UnRar in DOS.cmd

To Rar all directories in the current folder and make a rar file using the folder name:

@echo off
@setlocal
REM
REM Unrar all .rar files on the current directory and use the full path
REM

set path="%ProgramFiles(x86)%WinRAR";%path%
for /F %%i in ('dir /b *.rar') do call :do_extract "%%i"

:eof
pause
exit 1

:do_extract
echo %1
REM x : Extract files with full path
REM -y : Assume Yes on all queries
unrar x -y %1

To Unrar all files in the current location using FullPath:


@echo off
@setlocal
REM
REM Unrar all .rar files on the current directory and use the full path
REM

set path="%ProgramFiles(x86)%WinRAR";%path%
for /F %%i in ('dir /b *.rar') do call :do_extract "%%i"

:eof
pause
exit 1

:do_extract
echo %1
REM x : Extract files with full path
REM -y : Assume Yes on all queries
unrar x -y %1

WCF Authenticate by APIKey

Following my previous note, I want each service have its own authentication mechanics, maybe some public services and some sharing the same authentication manager.

To do so, I will set up different behaviors in my web.config in the servicebehaviors section, and make sure each service points to the corresponding behavior:

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name=
"ProductionServiceBehavior">
<serviceAuthorization serviceAuthorizationManagerType=
"WCFWebHttp.APIKeyAuthorization, WCFWebHttp" />
</behavior>
<behavior name=
"PublicServiceBehavior">
<serviceMetadata httpGetEnabled=
"true"/>
<serviceDebug includeExceptionDetailInFaults=
"false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name=
"WCFWebHttp.ProductionService" behaviorConfiguration="ProductionServiceBehavior">
</service>
</services>

Now, all I need to do is to implement my APIKeyAuthorization class. This class inherits from ServiceAuthorizationManager and overrides CheckAccessCore to validate the request and send an Error response if not validated.
For detailed information about this class see the original article on:
MSDN.

Routing WCF services by code

When you want to route the requests to specific WCF service deppending on the url, you can add routers on the Application_Start method of the Global.asax.cs. In the following example I want my ProductionService handle the service calls on the path starting with /Production/ and my PublicService handle the requests with a path starting with /public/demo/

using System;
using System.Web.Routing;
using System.ServiceModel.Activation;

public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
#region Register Routes
var factory =
new WebServiceHostFactory();
RouteTable.Routes.Add(
new ServiceRoute("Production", factory, typeof(ProductionService)));
RouteTable.Routes.Add(
new ServiceRoute("Public/demo/", factory, typeof(PublicService)));
#endregion
}

Animate Image Left To Right

The basics of any animation is moving something from one location to the other. In this code snippet I use to Image elements to slide away previously selected image and slide in the newly selected one.

The Image elements need to sit in a Canvas in order to let the Left property make sence.
<Label x:Name="txtFile"  HorizontalAlignment="Stretch"  />
<Canvas HorizontalAlignment=
"Stretch" VerticalAlignment="Stretch">

<Image x:Name=
"newImage" Canvas.Left="0" Canvas.Top="0" />
<Image x:Name=
"oldImage" Canvas.Left="0" Canvas.Top="0" />

</Canvas>

assuming that I have already given the previously selected image, my new image file will be given through a function call like

AnimateLeftToRight(selectedFile);

This method will swap the images and create a storyboard to begin animating. I start the newImage from x-position that equals to minus Window.Width and the old one starts from 0 and moves to Window.Width:

/// <summary>
/// Begins a story which animates two images from left to right
/// the old image takes the source from te new image just before assigning the new one
/// and they move together in the distance of Window.Width
/// </summary>
/// <param name="path">the path of the new image</param>
private void AnimateLeftToRight(string path)
{
oldImage.Source = newImage.Source;
newImage.Source =
new BitmapImage(new Uri(path));

var myStoryboard =
new Storyboard();

myStoryboard.Children.Add(MakeAnimation(-
this.Width, 0, "newImage"));
myStoryboard.Children.Add(MakeAnimation(
0, this.Width, "oldImage"));

myStoryboard.Begin(
this);
}

Making animation can be done in different ways using different EasingFunction, But this one looked easy to understand and look nice on my example:

/// <summary>
/// Creates a DoubleAnimation that moves the target from left to right
/// </summary>
/// <param name="from">starting point X</param>
/// <param name="to">ending point X</param>
/// <param name="target">the target element to set the x to </param>
/// <returns>the created animation</returns>
private DoubleAnimation MakeAnimation(double from, double to, string target)
{
const double durationSeconds = 1;

var animation =
new DoubleAnimation
{
Duration =
new Duration(TimeSpan.FromSeconds(durationSeconds)),
AutoReverse =
false,
From = from,
To = to,
EasingFunction =
new PowerEase()
{
EasingMode = EasingMode.EaseInOut,
Power =
5
}
};

Storyboard.SetTargetName(animation, target);
Storyboard.SetTargetProperty(animation,
new PropertyPath(Canvas.LeftProperty));

return animation;
}

Geometry and Mini-Language

StreamGeometry is a light-weight alternative to the PathGeometry class for
creating complex geometric shapes. You can use StreamGeometry when you
need to describe a complex geometry but don’t want the overhead of supporting
data binding, animation, and modification.
There are two classes in WPF that provide the mini-language for describing
geometric paths: StreamGeometry, and PathFigureCollection. You need to use
the StreamGeometry mini-language when you set a property of the Geometry
type, such as the Data property of a Path element.

<path stroke="Blue" data="M 100 120 L 200 120 L 200 220 L 100 170">
</path>

This path uses a sequence of four commands. The first command, M, creates the
PathFigure and sets the starting point to (100, 120). The following three
commands (L) create line segments.

See also Mini-Language in MSDN

From the book of Practical WPF Graphics Programming

L endPoint : The end point of the line.
H x : The x-coordinate of the end point of the line.
V y : The y-coordinate of the end point of the line.

F0 specifies the EvenOdd fill rule.
F1 specifies the Nonzero fill rule.
An uppercase M indicates that startPoint is an absolute value; a lowercase m indicates that startPoint is an offset to the previous point

C controlPoint1 controlPoint2 endPoint : Cubic Bezier Curve Command
A size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint : Creates an elliptical arc between the current point and the specified end point.

Z : Ends the current figure and creates a line that connects the current point to the starting point of the figure.

Did i say “I’ve got memory leak”?

Dealing with memory leak is not as far as some might think it is. But it doesn’t get serious until it is very late to change the fundamentals of our software design.

In my recent project it happened to be caused by traditional event subscription pattern. Which is most likely not leaving any memory leak behind, but it could easily do so 🙁
I also looked into latest libraries of Microsoft and saw they are using a new way of subscribing event handler to GUI events in WPF. Further I saw that every Window, like any Visual object in WPF, is derrived from DispatcherObject and is also implementing IWeakEventListener; hummmmmm!
So I’ve decided to create my first WeakEventManager and followed the instructions by Reed Copsey Jr. in his blog
You can instanciate several instances of different event listeners and let the manager route the events to all of them. As long as they all implement IWeakEventListener.ReceiveWeakEvent

To demonstrate this I started a sample code about human body. Assume you have a heart class and a hand class. If you have an instance of them and you need to get events on your hand when the heart beats you might do something like:
hear.BeatEvent += right.BeatHandler
The idea is to change this aby using an event manager, in my sample I have called it Brain, to handle de notifications like
Brain.AddListener(heart, right);
And to unsubscribe to the event you do something like
Brain.RemoveListener(heart, right);

To make this possible, you need to make sure that your Hand class where the events need to be handled, you implement the IWeakEventListener interface which brings us to ReceiveWeakEvent method:

/// <summary> Receives events from the centralized event manager. </summary>
/// <returns> true if the listener handled the event. </returns>
/// <param name="managerType">The type of the <see cref="T:System.Windows.WeakEventManager"/> calling this method.</param>
/// <param name="sender">Object that originated the event.</param>
/// <param name="e">Event data.</param>
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(Brain))
{
var beat = e
as BeatArgs;
Trace.WriteLine(
string.Format("{0} hand is getting the beat from {1}", name, beat.TimeOfBeat.ToString("hh:mm:ss")));
return true;
}

return false;
}

The Brain class which has a Singleton implementation provides only two public methods i.e. AddListener and RemoveListener. They do this by calling the protected methods and passing the parameters:

/// <summary>Subscribe a body part to listen to heart beat </summary>
/// <param name="source">the heart to listen to</param>
/// <param name="listener">the body that subscribes</param>
public static void AddListener(Heart source, IWeakEventListener listener)
{
Neuron.ProtectedAddListener(source, listener);
}

/// <summary>Unsubscribe a body part to listen to heart beat </summary>
/// <param name="source">the heart to listen to</param>
/// <param name="listener">the body that subscribes</param>
public static void RemoveListener(Heart source, IWeakEventListener listener)
{
Neuron.ProtectedRemoveListener(source, listener);
}

That is not all what brain do internally. It is actually inheriting the abstract class WeakEventManager and in order to do that it overrides the StartListening and StopListening methods that are internally called when it should be.

/// <summary>Starts listening on the provided heart for the managed beat event.</summary>
/// <param name="source">The heart to disconnect beat event</param>
protected override void StartListening(object source)
{
var heart = source
as Heart;
if (heart == null) throw new ArgumentException("The brain suppose to listen to heart only");

heart.BeatEventHandler += DeliverEvent;
}

/// <summary>Stops listening on the provided heart for the managed beat event.</summary>
/// <param name="source">The heart to disconnect beat event</param>
protected override void StopListening(object source)
{
var heart = source
as Heart;
if (heart == null) throw new ArgumentException("The brain suppose to listen to heart only");

heart.BeatEventHandler -= DeliverEvent;
}

The last part is the Heart where the event is getting fired. That is nothing special and can be implemented as before.

/// <summary> Can beat and can e subscribed to the beat event handler </summary>
public partial class Heart
{
/// <summary>Hanldler for notifying a beat </summary>
public event EventHandler<BeatArgs> BeatEventHandler;

/// <summary>Sends the beat through the events </summary>
/// <param name="beatArgs"></param>
protected void OnSendBeat(BeatArgs beatArgs)
{
if (BeatEventHandler != null)
BeatEventHandler(
this, beatArgs);
}

/// <summary>Create a beat and send it </summary>
private void BeatOnce()
{
OnSendBeat(
new BeatArgs());
}
}

Behavior Driven Development

Dan North in his blog about Behavior Driven Development write the following:

If we could develop a consistent vocabulary for analysts, testers, developers, and the business, then we would be well on the way to eliminating some of the ambiguity and miscommunication that occur when technical people talk to business people.
He describes BDD as follows:
BDD is a second-generation, outside-in, pull-based, multiple-stakeholder, multiple-scale, high-automation, agile methodology. It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters.

The practices of BDD include:

  • Establishing the goals of different stakeholders required for a vision to be implemented
  • Drawing out features which will achieve those goals using feature injection
  • Involving stakeholders in the implementation process through outside-in software development
  • Using examples to describe the behavior of the application, or of units of code
  • Automating those examples to provide quick feedback and regression testing
  • Using ‘should’ when describing the behavior of software to help clarify responsibility and allow the software’s functionality to be questioned
  • Using ‘ensure’ when describing responsibilities of software to differentiate outcomes in the scope of the code in question from side-effects of other elements of code.
  • Using mocks to stand-in for collaborating modules of code which have not yet been written

Link to existing source file

Got a nice tip from PDSA.NET

Reuse Class Files in Different Projects (Add as Link)

All of us have class libraries that we developed for use in our projects. When you create a .NET Class Library project with many classes, you can use that DLL in ASP.NET, Windows Forms and WPF applications. However, for Silverlight and Windows Phone, these .NET Class Libraries cannot be used. The reason is Silverlight and Windows Phone both use a scaled down version of .NET and thus do not have access to the full .NET framework class library. However, there are many classes and functionality that will work in the full .NET and in the scaled down versions that Silverlight and Windows Phone use.

Let’s take an example of a class that you might want to use in all of the above mentioned projects. The code listing shown below might be something that you have in a Windows Form or an ASP.NET application.

public class StringCommon
{
public static bool IsAllLowerCase(string value)
{
return new Regex(@”^([^A-Z])+$”).IsMatch(value);
}

public static bool IsAllUpperCase(string value)
{
return new Regex(@”^([^a-z])+$”).IsMatch(value);
}
}

The StringCommon class is very simple with just two methods, but you know that the System.Text.RegularExpressions namespace is available in Silverlight and Windows Phone. Thus, you know that you may reuse this class in your Silverlight and Windows Phone projects. Here is the problem: if you create a Silverlight Class Library project and you right-click on that project in Solution Explorer and choose Add | Add Existing Item… from the menu, the class file StringCommon.cs will be copied from the original location and placed into the Silverlight Class Library project. You now have two files with the same code. If you want to change the code you will now need to change it in two places! This is a maintenance nightmare that you have just created. If you then add this to a Windows Phone Class Library project, you now have three places you need to modify the code!

Add as Link

Instead of creating three separate copies of the same class file, you want to leave the original class file in its original location and just create a link to that file from the Silverlight and Windows Phone class libraries. Visual Studio will allow you to do this, but you need to do one additional step in the Add Existing Item dialog. You will still right mouse click on the project and choose Add | Add Existing Item… from the menu. You will still highlight the file you want to add to your project, but DO NOT click on the Add button. Instead click on the drop down portion of the Add button and choose the “Add As Link” menu item. This will now create a link to the file on disk and will not copy the file into your new project.

When this linked file is added to your project, there will be a different icon next to that file in the Solution Explorer window. This icon signifies that this is a link to a file in another folder on your hard drive.

Of course, if you have code that will not work in Silverlight or Windows Phone — because the code has dependencies on features of .NET that are not supported on those platforms – you can always wrap conditional compilation code around the offending code so it will be removed when compiled in those class libraries.

Download Other Tips and Tricks

I hope you found this short tip useful. You can get many other tips, tricks and articles at my website. http://www.pdsa.com/downloads.

MVVM Basic Binding – reflecting multiple targets

I have a ViewModel implementing INotifyPropertyChanged interface and have at least two properties Value and IsChanged. When I bind two Textboxes to the Value on source and one check box to IsChanged property of the source I noticed that user changes to Value does not reflect the other target controls!
This behavior is due to the fact that my ViewModel was not provided as a field in my container ViewModel and rather it was created when needed.
public PandViewModel PandViewModel
{
get
{
return listIndex < 0
?
null
:
new PandViewModel(panden[listIndex]);
}
}

Moving the PandViewModel to a local field in this container class, or even putting it into an ObservableCollection will sort out the problem:

public PandViewModel PandViewModel
{
get
{
return listIndex < 0
?
null
: pandenVM[listIndex];
}
}

See also a nice article over Binding on MSDN.

MVVM Basic Principals

The very basic principals so far I understand from M-V-VM practice is the following which is understood from this article : http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090025

View is a Control or Window

public partial class CustomerView : System.Windows.Controls.UserControl
{
public CustomerView()
{
InitializeComponent();
}
}

And this is as far as the view might be written in code. In the most cases we don’t want to write more code in the View. The reason is that the View is supposed to be made loosely coupled from the data and the logic, probably done by creative designers.

The View gets DataContext

Some magic forces will get the data that is accessible through the ViewModel and set it to the DataContext property of the control:

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

var viewModel =
new MainWindowViewModel(path);
MainWindow window =
new MainWindow();
window.DataContext = viewModel;

window.Show();
}

In this example the magic happens in the Startup method of the application. Using MEF this magic is taken out to some sophisticated standard way.
Now the View and its elements are ready to consume the data.

View binds to ViewModel

Both data and actions are binded to public accessors of ViewModel:

 <TextBox
x:Name=
"firstNameTxt"
Grid.Row=
"2" Grid.Column="2"
Text=
"{Binding Path=FirstName, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
Validation.ErrorTemplate=
"{x:Null}"
/>


<Button
Command=
"{Binding Path=SaveCommand}"
Content=
"_Save"
/>

ViewModel is unaware of View

Unlike the Presenter in MVP, a ViewModel does not need a reference to a view. This makes it possible to attach any View at any time to consume the public data provided by ViewModel.

ViewModel exposes public properties to share data with any possible View:

public class CustomerViewModel : WorkspaceViewModel, IDataErrorInfo
{
public string FirstName
{
get { return _customer.FirstName; }
set
{
if (value == _customer.FirstName)
return;

_customer.FirstName = value;

base.OnPropertyChanged("FirstName");
}
}

ViewModel exposes public commands to share actions with any possible View:

/// <summary>
/// Returns a command that saves the customer.
/// </summary>
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand =
new RelayCommand(
param =>
this.Save(),
param =>
this.CanSave
);
}
return _saveCommand;
}
}

Some of these properties may be data coming from a model and some might be simply a state of the ViewModel to help out the View.

Data Manipulation

The ViewModel, never the View, performs all modifications made to the model data.
As I already mentioned the ViewModel is unaware of View but it is certainly aware of Model and can manipulate it when needed. When user interacts with the View, the binding manager will take care of both ways of data modifications in each binding.

The way a ViewModel is attached to a model, is an architectural decision and makes your application easier or hard to understand and maintain. But this is another important subject. For now, like MEF does the magic for coupling View and ViewModel, there needs to be some Factory or Controller mechanism to pull the data and assign it to the ViewModel.