Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Archive for the ‘Tips 'n' Tricks’ Category

Transparent background with opaque controls on top of it in wpf

without comments

Ever felt like having a transparent window background and still opaque controls inside the window? It can be easily done in wpf.

  1. Set the window’s AllowsTransparency to True
  2. Set the window’s Background to Transparent
  3. Add a Rectangle to the parent panel of the window
  4. Set the opacity of the rectangle to some value < 1 (0.7, …)
  5. Add your controls to the parent panel
  6. 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>

Written by sudarsanyes

January 13th, 2010 at 9:34 am

Posted in Tips 'n' Tricks, UI, WPF, xaml

Tagged with , , , ,

DoUNo: MDI in WPF

without comments

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.

Written by sudarsanyes

January 13th, 2010 at 9:07 am

Mashing Twitter and FSO

without comments

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,

  1. Send messages to your old/unused number whose SIM is in the Freerunner (or any other device supported by the FSO framework)
  2. 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,

[1]: The FSO API reference

[2]: DBus Tutorial

Written by sup3rkiddo

December 6th, 2009 at 8:16 pm

DoUNo: Popup animation in wpf

without comments

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 :P ) and found that the popup animation shall work only if the AllowsTransparency of the popup is set to true. Really weird !!

Written by sudarsanyes

December 3rd, 2009 at 10:28 am

DoUNo: Setting expectations on nullable type, NMock2

without comments

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&lt;IProduct&gt;();
//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 :P )

Written by sudarsanyes

November 6th, 2009 at 9:08 am

Accessing Command Prompt from C#

without comments

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.

Written by sudarsanyes

August 31st, 2009 at 5:44 pm

Give your boss the illusion of managing you… with pidgin and dbus

with 2 comments

Dilbert.com

Oh yeah!. With the power of DBus and libpurple APIs it is possible to give your boss the illusion of managing you. Just run the following script (under WTFPL). Tested with jabber accounts in a live office environment :P.

#!/usr/bin/env python
# By Sudharshan S, released under WTFPL
 
import dbus
import gobject
import time
 
class PointyHairedBoss:
 
    def __init__(self, boss_id, source, frequency=30):
        self.boss_id = boss_id
        self.source = source
        self.frequency = frequency
        bus = dbus.SessionBus()
        _pidgin_proxy = bus.get_object("im.pidgin.purple.PurpleService", \
                                                       "/im/pidgin/purple/PurpleObject")
        self.purple = dbus.Interface (_pidgin_proxy, "im.pidgin.purple.PurpleService")
        # FIXME:
        account_id = self.purple.PurpleAccountsGetAllActive()[0]
        self.boss_conversation = self.purple.PurpleConversationNew(1, account_id, self.boss_id)
        self.boss_im = self.purple.PurpleConvIm(self.boss_conversation)
        print self.boss_im
 
    def start_nonsense(self):
        question_list = open(self.source)
        for q in question_list:
            self.purple.PurpleConvImSend(self.boss_im, q)
            time.sleep(self.frequency)
 
if __name__ == "__main__":
   # Change the jabber id and the path to your questions, with an optional frequency
   o = PointyHairedBoss("foo@gmail.com", "questions")
   o.start_nonsense()

Written by sup3rkiddo

July 5th, 2009 at 11:37 am

WMI (Windows Management Instrumentation) in C#

without comments

In my previous post, I had written about ManagementEventWatcher with some WMI querries. In this post we will try to figure out what this WMI is.

WMI stands for Windows Management Instrumentation. Its a set of functionalities provided by the OS (Windows) for the applications to control / manage the administrative tasks (check this out for a formal definition).

For example, if you wanna retrieve information about the CDROM drive on a machine, you can write some simple queries in c# and get that job done.

Using WMI in C#

Its fairly simple  in C# to use WMI infrastructure services. C# comes with a class called, ManagementObjectSearcher with which we can query for any information. Lets take the fore mentioned example, the CDROM example. To get information about the CDROM,

  1. Create a WqlObjectQuery object with the query statement, SELECT * FROM Win32_CDROMDrive

    WqlObjectQuery aWMIQuery = new WqlObjectQuery("SELECT * FROM WIN32_CDROMDrive");
  2. Create an object of ManagementObjectSearcher and assign the created query to this object
    ManagementObjectSearcher aManagementObjectSearcher = new ManagementObjectSearcher();
    aManagementObjectSearcher.Query = aWMIQuery;
  3. Run the query by calling the Get method in the ManagementObjectSearcher
    aManagementObjectSearcher.Get();
  4. The Get() method returns a ManagementObjectCollection. Iterate thru’ it to get the reults of the query. Each ManagementObject’s Properties field (ManagementObject.Properties) will contain a PropertiesDataCollection. Iterate thru’ this for additional results on the query
    foreach (ManagementObject aObject in aObjectSearcher.Get())
    {
      Console.WriteLine(aObject.Properties.ToString());
      foreach (PropertyData aProperty in aObject.Properties)
      {
        Console.Write("\t");
        Console.WriteLine(aProperty.Name + "----->" + aProperty.Value);
      }
      Console.WriteLine();
    }
  5. Change the query according to your need. You can query USB Drive information, Hard Disks, Processes and so on. Check out the MSDN for the list of WMI classes

Written by sudarsanyes

June 25th, 2009 at 2:26 pm

ManagementEventWatcher and WqlEventQuery in c#

with one comment

Yesterday, I was searching for some kind of snippet that will throw some notification when the system starts / stops some processes, thats when I came to know about the ManagementEventWatcher in c#.

ManagementEventWatcher allows us to subscribe for specific events and notifies us when those events occur.

For example, in the fore mentioned example, we need to create a ManagementEventWatcher for the events related to the spawning of processes. This is done using the WqlEventQuery class.

So first we start off writing the WqlEventQuery. This class helps us in constructing WMI event queries. For getting a notification when a process is started or stopped, we shall write a query as follows,

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("SELECT * FROM
Win32_ProcessStartTrace");

or

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");

The above query shall be used to subscribe for WMI events for Win32 process creation.

Now that we have created a query, we need to use the ManagementEventWatcher to assign this query so that we can start listening for the subscribed events. So we create an object of the ManagementEventWatcher for the query that we formed earlier.

ManagementEventWatcher aWatcher = new ManagementEventWatcher(aProcessCreationQuery);

After creating an object of the ManagementEventWatcher, we need to subscribe for the events that willbe raised by the watcher. So we go for,

aWatcher.EventArrived += new EventArrivedEventHandler(ProcessStarted);

Thats it. All we have to do now is just trigger the watcher. We do this by calling,

aWatcher.Start();

This is an asynchronous call and the reply comes thru’ the event, EventArrived. So whenever the OS spawns a process, the event will be raised.

WqlEventQuery might have solved the fore mentioned problem, but I really don’t know how effective it is. If I get to know about them more, I will post it in here.

Written by sudarsanyes

June 25th, 2009 at 7:55 am

Creating a single instance application in C#, WPF

with 2 comments

Some time you might want the user to run only one instance of the application. Its pretty easy to do so in C#. This is acheived using a Mutex. A mutex is used to restrict the usage of common resources in concurrent proragmming. C# provides a class called System.Threading.Mutex with which we can control the number of instances of an application that should be running. Just add the following snippet to the App.xaml.cs file (code behind file of App.xaml)

class App : Application
{
private Mutex myMutex;
...
protected override void OnStartup(StartupEventArgs theArgs)
{
bool aIsNewInstance = false;
myMutex = new Mutex(true, "Foo.SingletonApp", out aIsNewInstance);  //Creates a mutex for the application
if(!aIsNewInstance)
{
App.Current.Shutdow();  //Shutdown when a new mutex with the same name is created
}
}
}

How this works

The creation of a mutex in here takes three parameters. First one is to give the ownership of this mutex to the calling thread. Second one is the unique name given for this mutex (remember this is a unique name). Third one is an out parameter that returns
true — if there are no mutex with this name and if the new mutex is successfully created
fase — if there is already a mutex with this name.
That why we check for !aIsNewInstance in the snippet. Here we override the Startup event of the Application class (refer to my previous post on Application Events) so that we can validate the mutex during the start of the application.

Written by sudarsanyes

May 24th, 2009 at 3:46 pm