DoUNo: Whadds up with the Background property of a control
This is weird !! Try to customize the control template of a button,
- Place a grid as the base panel (don’t add any Background property to it)
- Add an ellipse and a content presenter to this
- Add a Click event handler to the button
- Run it and try to click on the white space, the event will not be raised !!!
Go back to the template,
- Add a Background property to the grid and set the value to Blue (can be any color other than transparent)
- Run it and try to click on the Blue color, the event will be raised !!!
Go back to the template,
- Set the value of the Background Property to Transparent
- Run it and try to click on the white space, the event will still be raised !!! (WHY ?!?)
Looks weird to me thou’
ScrollBar control template in wpf
Won’t it be cool to have ones own scroll bar. Felling the same, I did a quick peek in to msdn and there was a sample scroll bar template. The example is really good, but it did not talk about the internals of a scroll bar. So i thought I will write about it.
The two arrows that you see at the ends are called RepeatButtons. The middle field (light grayish one) is called Track. The middle, movable portion in the track is called Thumb and the partitions to the left and the right of the thumb are two more repeat buttons.
I have named these controls with some number so that it can easily be related to the code.
<!-- We are going to alter the vertical scroll bar's template --> <ControlTemplate x:Key="VerticalScrollBar" TargetType="{x:Type ScrollBar}"> <!-- First up is the background panel for all the above mentioned controls --> <Grid Background="Transparent"> <Grid.RowDefinitions> <RowDefinition MaxHeight="50"/> <!-- Up arrow row --> <RowDefinition Height="0.00001*"/> <!-- Track row --> <RowDefinition MaxHeight="50"/> <!-- Down arrow row --> </Grid.RowDefinitions> <Border Grid.RowSpan="3" CornerRadius="2" Background="DarkGray" Opacity="1" /> <!-- Border for the scroll bar --> <RepeatButton Grid.Row="0" Command="ScrollBar.LineUpCommand" Width="30" Height="30">Up</RepeatButton> <!-- Repeat button 1 (up arrow) --> <Track Name="PART_Track" Grid.Row="1" IsDirectionReversed="true"> <!-- Track --> <Track.DecreaseRepeatButton> <RepeatButton Command="ScrollBar.PageUpCommand" Opacity="0" /> <!-- Repeat button 3 (left partition) --> </Track.DecreaseRepeatButton> <Track.Thumb> <Thumb Margin="1,0,1,0" Background="Transparent" Opacity="0.3" Width="20" /> <!-- Thumb --> </Track.Thumb> <Track.IncreaseRepeatButton> <RepeatButton Command="ScrollBar.PageDownCommand" Opacity="0" /> <!-- Repeat button 4 (right partition) --> </Track.IncreaseRepeatButton> </Track> <RepeatButton Grid.Row="2" Command="ScrollBar.LineDownCommand" Width="30" Height="30">Down</RepeatButton> <!-- Repeat button 2 (down arrow) --> </Grid> </ControlTemplate>
I hope the above snippet is self explanatory, still a bit of explanation.
- We start off altering the ControlTemplate of the ScrollBar.
- We place a grid as the base panel for the scroll bar and we divide it in to three rows, one for up arrow, one for track and one for down arrow.
- Then we add two repeat buttons to the top and the bottom most rows (up and down arrows).
- Now comes the middle row for the track. As mentioned earlier, a track is again composed of two repeat buttons (actually the partitions are made of buttons; really don’t know why) so we create those buttons and assign them the scroll bar related commands.
- We also add a thumb in the middle. Make sure that you don’t set any Height for the thumb as this is a vertical scroll bar (no width for the horizontal scroll bar). Don’t bother about the opacity that I have given for these controls. We are free to modify them.
After the control template creation modification, we need to assign this to our scroll bar.
<Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}"> <Setter Property="SnapsToDevicePixels" Value="True"/> <Setter Property="OverridesDefaultStyle" Value="true"/> <Style.Triggers> <Trigger Property="Orientation" Value="Vertical"> <!-- Our scroll bar is a vertical one. Thats why --> <Setter Property="Width" Value="18"/> <Setter Property="Height" Value="Auto" /> <Setter Property="Template" Value="{StaticResource VerticalScrollBar}" /> </Trigger> </Style.Triggers> </Style>
Thats it. You have successfully altered a scroll bar.
Update — Don’t try changing the PART_Track. Changing the name will lead to an incomplete scroll bar as that name has been used by .NET WPF framework.
DoUNo: XAML gets compiled in to a BAML
What does a xaml file gets compiled in to ? It gets compiled in to a baml (binary xaml). More @ wikipedia.
You can find the .baml file in the \obj\Debug folder.
Transparent background with opaque controls on top of it in wpf
Ever felt like having a transparent window background and still opaque controls inside the window? It can be easily done in wpf.
- Set the window’s AllowsTransparency to True
- Set the window’s Background to Transparent
- Add a Rectangle to the parent panel of the window
- Set the opacity of the rectangle to some value < 1 (0.7, …)
- Add your controls to the parent panel
- You are one step away form seeing a transparent background with opaque controls on top of it. Go ahead, run the application now
Sample window,
<Window x:Class=”BackgroundWindow.Transparent.Samples.WPF.Window1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Title=”Window1″ Height=”300″ Width=”300″ AllowsTransparency=”True” Background=”Transparent” WindowStyle=”None”>
<Grid>
<Rectangle Fill=”Gray” Opacity=”0.7″ />
<Button Width=”100″ Height=”100″>Click this on</Button>
</Grid>
</Window>
DoUNo: MDI in WPF
WPF, out of the box doesn’t have provision for MDI windows. The reason is quite simple, MDI windows are outdated and most of the applications have been using tabbed documents, proving they are really easy to use. Although the framework is flexible enough for you to make such a feature, its better to move to tab based interface.
Mashing Twitter and FSO
I really love Twitter and it didn’t make any sense to me to shell out a rupee for every tweet sent through my Airtel Mobile. Moreover, I am on one of those monthly booster packs which allows you to send 22000 text messages for free. I simply had to exploit this by setting up my own little ‘OC’ twitter forwarder written in python. (I know of smstweet.in service but I am still charged 1.50 for every tweet I send)
Its insanely simple to write such a ‘forwarder’ in python using the services provided by the FSO (freesmartphone.org) Framework,
- Send messages to your old/unused number whose SIM is in the Freerunner (or any other device supported by the FSO framework)
- Handle the incoming messages and use python-twitter API (or) raw urllib2 to post updates. Of course, the device should be connected to the internet, you can tether this device to an old unused computer. Simply put, the Freerunner should be able to access the internet.
I know this is dumb given cheap GPRS and all, but what the heck; Sundays _are_ reserved for dumb things and I wanted to show off how easy it is to develop and conjure up simple but powerful scripts using open hackable hardware like the Freerunner. So take off your pedantic hats ![]()
Here is the actual python code,
–
#!/usr/bin/env python # Written By Sudharshan S, http://sudharsh.wordpress.com import dbus import time import logging import twitter import gobject from gobject import MainLoop from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop (set_as_default = True) # Use OAUTH? USERNAME = "username" PASSWORD = "password" log = logging.getLogger("TweetForwarder") class TweetForwarder: """Process Incoming messages and update twitter status if the message startswith 'tweet' """ def __init__(self, username, password): log.warning("Starting up....") self.twitter_api = twitter.Api(username=username, password=password) # Get proxies and add signal handlers bus = dbus.SystemBus() _usage = bus.get_object("org.freesmartphone.ousaged", "/org/freesmartphone/Usage") _proxy = bus.get_object("org.freesmartphone.ogsmd", \ "/org/freesmartphone/GSM/Device") self.usage_iface = dbus.Interface(_usage, "org.freesmartphone.Usage") self.usage_iface.RequestResource('GSM') self.sms_iface = dbus.Interface (_proxy, "org.freesmartphone.GSM.SMS") self.sms_iface.connect_to_signal ("IncomingMessage", self.onIncomingMessage) def onIncomingMessage(self, sender, message, kwargs): log.warning("Received SMS from %s:%s" % (sender, message)) # We don't ALL messages to this number to be tweeted if message.strip().startswith("tweet "): log.warning("Trying to update status : %s" % message[6:].strip()) self.twitter_api.PostUpdate(message[6:]) log.warning("Updated Status") def run(self): loop = MainLoop() loop.run() if __name__ == "__main__": logging.basicConfig() server = TweetForwarder(USERNAME, PASSWORD) server.run() --
Make sure you have python-netclient and python-json installed on your Freerunner. These can be installed using the ‘opkg install’ command.
The script and the accompanying dependency can be downloaded from here. Just change the USERNAME and PASSWORD accordingly after scp’ing the tarball to your device.
Some useful links,
[2]: DBus Tutorial
DoUNo: Popup animation in wpf
Every time I try adding a default animation (Slide, Fade, …) to a pop up in WPF, I find it not to be working. Today, I went thru’ MSDN (breaking my laziness
) and found that the popup animation shall work only if the AllowsTransparency of the popup is set to true. Really weird !!
DoUNo: Setting expectations on nullable type, NMock2
Ever had a problem of setting an expectation for nullable objects?
If you wanna return false when .HasValue of a nullable object is called, then you cannot do it with the normal expect statement. Rather, try not returning any values, because NMock2 returns default value of HasValue (False) if nothing is set as return values in expect statements.
Here is a sample,
public interface IProduct //Interface that has a nullable member { int? ProductNo //Member that I wanna test and I wish to test the scenario in which this will be null { get; } }
IProduct aProduct= myMockery.NewMock<IProduct>(); //Stub.On(aProduct).GetProperty("ProductNo").Will(Return.Value(default(int?)); //this statement produces a runtime exception, so we have to use the following instead Stub.On(aProduct).GetProperty("ProductNo"); //no return value is set, nmock2 returns false when .HasValue is queries
Hope this helped you.
Sudarsan Srinivasan
- on behalf of my friends (they found this hack
)
Settings expectations in NMock2
One of our previous articles would have given an introduction to NMocks. In here, we will try out various methods of setting expectations when we do a unit test.
note — this article considers that you know the basics of unit testing. check out our previous article if you would like to know the basics of nmock2
In NMock2, you have a wide variety of setting expectations on mocked objects.
Stubs
Stubs are expectations whose occurrences are unknown. We use stubs when we are not sure the number of times it might be called. So generally Stubs are used when expectations needs to be set 0 or more times
Stub.On(myMockedObject).Method("GetName"); //Use this only when you are unaware of the occurrences, //otherwise you end up writing a bad UT
Expect
We use the Expect class when the number of calls to the method or property of the mock objects are known.
For example,
If number of occurrences are 7 on the method called, “GetName“, then use,
Expect.Exactly(7).On(myMockObject).Method("GetName")...
If the number of occurrence is 1 on the method called, “GetName“, then use,
Expect.Once.On(myMockObject).Method("GetName")...
or
Expect.Exactly(1).On(myMockObject).Method("GetName")...
You can even set negative expectations. For example,
If you are pretty sure that the method “GetName“, will not/should not be called in your unit test, then use,
Expect.Never.On(myMockObject).Method("GetName")...
Expectation With Parameters
If you are unit testing a method that makes a call to an interface which inturn takes two params and if you know the values of those params, you could set expectation on the mock object for the method with the known params.
For example,
If “GetName” method takes two params and if the param values are “foo” and “bar” according to the unit test case, then we can write an expectation as,
Expect.Once.On(myMockObject).Method("GetName").With("foo", "bar")...
Expectation On Events
You can add expectation on events of the mock object with the EventAdd method.
For example,
public class Foo { public event EventHandler ObjectChanged; ... }
public class FooBarBaz { private Foo myFoo; ... private void SomeMethod() { myFoo.ObjectChanged += new EventHandler(Foo__ObjectChanged); ... } }
If you are writing a unit test for the method SomeMethod, then you shall add an expectation of the following form,
Expect.Once.On(myMockObject).EventAdd("ObjectChanged", Is.Anything);
Expecting Exceptions
You could also expect exceprions by adding the attribute, ExpectedException on top of your unit test.
For example,
[Test(Description="Test case method that will test whether the ArgumentNullException is raised")] [ExpectedException(typeof(ArgumentNullException))] public void TestExceptionalScenario() { ... //call the method that is supposed to throw the ArgumentNullException }
These are the commonly used expectations. If you have used something really weird, I expect you share it with us
Accessing Command Prompt from C#
Recently, I wanted to write a program in c# that should start the command prompt in the background (it should not show the cmd window), give inputs from my C# program and get the results redirected back to my C# application. I was googling around a bit and then came up with a solution.
Its damn simple. Usually to start any process from C# applications, we use the Process object. The process object has two properties called StandardInput and StandardOutput. These properties will allow the C# application to get the input stream of the process that needs to be started. So to mock inputs and outputs, we need to do the following,
Process aProcess = new Process(); ProcessStartInfo aStartInfo = new ProcessStartInfo(); aStartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe"; aProcess.StartInfo = aStartInfo; aProcess.StandardInput.WriteLine("dir"); //will open a cmd process and feed the command "dir" to it
By this way you could give inputs to a process that you start from C#. What if you wanna see output of the cmd prompt in your own prompt ?? For this we use the StandardOutput property. But there is yet another simple way to get the output from the command prompt. This is done by subscribing for the event, OutputDataReceived.
aProcess.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { textBox1.AppendText(e.Data); textBox1.AppendText(Environment.NewLine); }
Note: These ways are possible only if,
aProcess.RedirectStandardOutput = true; aProcess.UseShellExecute = false; aProcess.BeginOutputReadLine();
are set to the mentioned values. BeginOutputReadLine method will start async read operations from the C# application stream instead of the standard input devices. So next time you wanna clone a command prompt, start the cmd process and give your own look and feel to it.


