Saturday, August 28, 2010

Posted by SAMAJ SHEKHAR

4

Introduction to using WP7 Accelerometer


This post is about introducing you Windows Phones Accelerometer (I have taken following contents from Charles Petzold's book "Programming Windows Phone 7 - Special Excerpt 2". The contents are Copyright of Microsoft and is used only for informational purpose). You can get more detailed information about using Accelerometer from above mentioned book, complete book is still to be released later this year.

Windows Phones contain an accelerometer — a small hardware device that essentially measures force, which elementary physics tells us is proportional to acceleration. When the phone is held still, the accelerometer responds to the force of gravity, so the accelerometer can tell your application the direction of the Earth relative to the phone. It is convenient to represent the accelerometer output as a vector in three-dimensional space. Vectors are commonly written in boldface, so the acceleration vector can be symbolized as (x, y, z). XNA defines a three-dimensional vector type; Silverlight does not.

While a three-dimensional point (x, y, z) indicates a particular location in space, the vector (x, y, z) encapsulates instead a direction and a magnitude. Obviously the point and the vector are related: The direction of the vector (x, y, z) is the direction from the point (0, 0, 0) to the point(x, y, z). But the vector (x, y, z) is definitely not the line from (0, 0, 0) to (x, y, z). It’s only the direction of that line. The magnitude of the vector (x, y, z) is calculable from the three-dimensional form of the Pythagorean Theorem:

Magnitude = Math.sqrt( Math.pow(x,2), Math.pow(y,2), Math.pow(z,2) )
where:
Math.sqrt() function returns the square root of a number
Math.pow() function returns a number raised to a power
For working with the accelerometer, you can imagine the phone as defining a threedimensional coordinate system. No matter how the phone is oriented, the positive Y axis points from the bottom of the phone (with the buttons) to the top, the positive X axis points from left to right.



When the phone is still, the accelerometer vector points towards the Earth. The magnitude is 1, meaning 1 g, which is the force of gravity on the earth's surface. When holding your phone in the upright position, the acceleration vector is (0, –1, 0), that is, straight down.

So lets start, To use the accelerometer, you’ll need a reference to the Microsoft.Devices.Sensors library, and a using directive for the Microsoft.Devices.Sensors namespace. In WMAppManifest.xml, you need
<Capability Name="ID_CAP_SENSORS">

You create an instance of the Accelerometer class, set an event handler for the
ReadingChanging event, and call Start. And then it gets a little tricky. Let’s take a look at a project named SilverlightAccelerometer project that simply displays the current reading in its content grid. A centered TextBlock is defined in the XAML.

<Grid x:Name="ContentGrid" Grid.Row="1">
    <TextBlock Name="txtblk"
     HorizontalAlignment="Center"
     VerticalAlignment="Center" />
</Grid>

This is a program that will display the accelerometer vector throughout its lifetime, so it creates the Accelerometer class in its constructor and calls Start:

public MainPage()
{
    InitializeComponent();
    Accelerometer acc = new Accelerometer();
    acc.ReadingChanged += OnAccelerometerReadingChanged;
    try
    {
        acc.Start();
    }
    catch (Exception exc)
    {
        txtblk.Text = exc.Message;
    }
}

The documentation warns that calling Start might raise an exception, so the program protects itself against that eventuality. These user-interface objects are not thread safe; they are not built to be accessed simultaneously from multiple threads. For this reason, Silverlight will not allow you to access a user-interface object from a non-UI thread.

This means that the OnAccelerometerReadingChanged method cannot directly access the TextBlock element to set a new value to its Text property. Fortunately, there’s a solution involving a class named Dispatcher defined in the System.Windows.Threading namespace. Through the Dispatcher class, you can post jobs from
a non-UI thread on a queue where they are later executed by the UI thread.

The Dispatcher class defines a method named CheckAccess that returns true if you can access a particular user interface object from the current thread. (The CheckAccess method is also duplicated by DependencyObject itself.) If an object can’t be accessed from the current thread, then Dispatcher provides two versions of a method named Invoke that you use to post the job to the UI thread.

The verbose version requires a delegate and a method defined in accordance with that delegate. The delegate (and method) should have no return value, but as many arguments as you need to do the job, in this case setting a string to the Text property of a TextBlock:
delegate void SetTextBlockTextDelegate(TextBlock txtblk, string text);
void SetTextBlockText(TextBlock txtblk, string text)
{
    txtblk.Text = text;
}
The OnAccelerometerReadingChanged is responsible for calling SetTextBlockText. It first makes use of CheckAccess to see if it can just call the SetTextBlockText method directly. If not, then the handler calls the BeginInvoke method. The first argument is an instantiation of the delegate with the SetTextBlockText method; this is followed by all the arguments that SetTextBlockText requires:
void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
{
    string str = String.Format("X = {0:F2}\n" +
    "Y = {1:F2}\n" +
    "Z = {2:F2}\n\n" +
    "Magnitude = {3:F2}\n\n" +
    "{4}",
    args.X, args.Y, args.Z,
    Math.Sqrt(args.X * args.X + args.Y * args.Y +
    args.Z * args.Z),
    args.Timestamp);
    if (txtblk.CheckAccess())
    {
        SetTextBlockText(txtblk, str);
    }
    else
    {
        txtblk.Dispatcher.BeginInvoke(new
        SetTextBlockTextDelegate(SetTextBlockText),
        txtblk, str);
    }
}
This is not too bad, but the need for the code to jump across threads has necessitated an additional method and a delegate. Is there a way to do the whole job right in the event handler?
Yes! The BeginInvoke method has an overload that accepts an Action delegate, which defines a method that has no return value and no arguments. You can create an anonymous method right in the BeginInvoke call. The complete code following the creation of the string object looks like this:
if (txtblk.CheckAccess())
{
    txtblk.Text = str;
}
else
{
    txtblk.Dispatcher.BeginInvoke(delegate()
        {
            txtblk.Text = str;
        });
}
The anonymous method begins with the keyword delegate and concludes with the curly
brace following the method body. The empty parentheses following the delegate keyword are not required.



The Windows Phone 7 emulator doesn’t contain any actual accelerometer, so it always reports a value of (0, 0, –1), which indicates the phone is lying on a flat surface:



READ MORE - Introduction to using WP7 Accelerometer

Tuesday, August 10, 2010

Posted by SAMAJ SHEKHAR

0

Invoking C# Compiler from your Code



Imagine you have just generated some code using a code generation technique, wouldn’t it be really cool to then programmatically call the C# language compiler and generate assemblies from the generated code?
Let’s imagine we used an Xslt transformation to generate some code:
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("Program.xslt");
transform.Transform("Program.xml", "Program.cs");
Using the CSharpCodeProvider class we can now programmatically call the C# compiler to generate the executable assembly. We’ll begin by advising the compiler of some options we’d like it to use when compiling our code using the CompilerParameters class.
CompilerParameters parameters = new CompilerParameters();
We’ll specify that the assembly to be created should be an executable and we’ll also specify such things as whether debug information should be included, the warning level, whether warnings should be treated as errors etc.
parameters.GenerateExecutable = true;
parameters.IncludeDebugInformation = true;
parameters.GenerateInMemory = false;
parameters.TreatWarningsAsErrors = true;
parameters.WarningLevel = 3;
parameters.CompilerOptions = "/optimize";
parameters.OutputAssembly = "Program.exe";
Using the compiler parameters we can now compile the C# code using the CSharpCodeProvider class and get the results of the compilation as an instance of the CompilerResults class.
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, new string[] { "Program.cs" });
While the code you generated is unlikely to have any compiler warnings or errors, other developers may be less fortunate and therefore they can access the Errors property of the CompilerResults class to determine what went wrong. Actually the Errors property contains both compiler errors and warnings although the following simple LINQ queries allow you to examine the warnings and errors in isolation.
var warnings = from e in results.Errors.Cast()
      where e.IsWarning
      select e;
var errors = from e in results.Errors.Cast()
    where !e.IsWarning
    select e;
While code generation is very cool, we generate code to ultimately create assemblies that we can either execute or reference from other code. If you’re programmatically generating code why not next time also programmatically generate the assemblies too!

Post originally taken from Here
READ MORE - Invoking C# Compiler from your Code

Wednesday, August 4, 2010

Posted by SAMAJ SHEKHAR

0

Enable Built-in Administrator Account in Windows 7



Hi everybody, recently I was exploring features of windows 7 when I found that administrator account can be enabled and listed among other accounts in the logon screen. We all know in XP we could do so by pressing “Ctrl+Alt+Delete” at the logon screen and entering Administrator as the username and entering required password you entered while installing XP (Most people don’t enter anything, and I used to use this a lot to logon as administrator at Cyber cafes). But in Windows 7 by default you don’t have administrator account listed among other accounts. When you need to elevate the permissions for an application, you usually right click an application and select “Run as Administrator”. Windows do this to prevent any application from running with admin permissions until you want or need so. The account in which you are logged in is a Member of Administrator Group, it is not the Built-in account for administering the computer/domain
(Warning: It is not recommended to enable Administrator account and logging in as Administrator)

So to enable admin account you need to follow following steps (you need administrative rights to perform these steps):

1: Switch to Desktop (if not already) and Right click on “My computer” and click on “Manage”.



















2: In Computer Management window that will open, select “Local Users and Groups” under “Computer management \ System Tools”.

3: In the right pane two folders will be visible, Double Click on “Users”



















4: Then double click on “Administrator”.

5: In the “Administrator Properties” dialogue box there is a check box labeled “Account is disabled”, uncheck that check box and click on apply.




















Close that window and any other open window, now to check that it worked, Logoff or Lock your computer (By pressing Windows Key + L) and click on “Switch user”. You will see Administrator account, you can log into it and enjoy full access to computer with complete admin rights. You can also set a  password for this built in Administrator Account (I would strongly recommend doing so).
READ MORE - Enable Built-in Administrator Account in Windows 7