Windows Phone 7 development

Posts tagged ‘C#’

Drawin cool simple text in XNA

I was wondering how to use some cool font in my XNA game. I came up with an idea to draw white and black text with an offset to give it “3d” look.

Here is the result:

Image

I made extension methods for SpriteBatch  that write this kind of text

public static class ExtensionMethods   
{       /// <summary>
        /// Draws white text with a black stroke
        /// </summary>
        public static void DrawStringBlackAndWhite(this SpriteBatch spriteBatch, SpriteFont smallFont, String text, Vector2 position)
        {
            spriteBatch.DrawStringWithStroke(smallFont, text, position, Color.White, Color.Black);
        }

        /// <summary>
        /// Draws white text with a black stroke
        /// </summary>
        public static void DrawStringBlackAndWhite(this SpriteBatch spriteBatch, SpriteFont smallFont, StringBuilder text, Vector2 position)
        {
            spriteBatch.DrawStringWithStroke(smallFont, text, position, Color.White, Color.Black);
        }

		/// <summary>
		/// Draws string with a stroke on up and right side of text
		/// </summary>
		public static void DrawStringWithStroke(this SpriteBatch spriteBatch, SpriteFont smallFont, String text, Vector2 position, Color color, Color stroke)
		{
			spriteBatch.DrawString(smallFont, text, position, stroke);
			spriteBatch.DrawString(smallFont, text, new Vector2(position.X - 1, position.Y + 1), color);
		}

		/// <summary>
		/// Draws string with a stroke on up and right side of text
		/// </summary>
		public static void DrawStringWithStroke(this SpriteBatch spriteBatch, SpriteFont smallFont, StringBuilder text, Vector2 position, Color color, Color stroke)
		{
			spriteBatch.DrawString(smallFont, text, position, stroke);
			spriteBatch.DrawString(smallFont, text, new Vector2(position.X - 1, position.Y + 1), color);
		}
	}

Meaning of “this” keyword in C#

Recently, I’ve been looking for all usages of “this” in C#. I couldn’t find any good article, so I’ve “grepped” the spec.
Surprisingly, I had wrong idea of “this” that is the same as in Java.

What is “this”? It is a keyword used in many object-oriented programming languages to refer to the current object. It can be implemented as a pointer (f.e. C++) or reference (f.e. Java), but in C# it has a few different meanings.

Classes

We can use “this” in 3 different context

-call other contructors

-refer to instance fields or methods

-pass current object

public class Person
{
    private string name;
    public Person()
    {
       name = "John";
    }

    public Person(string name)
    : this() // call other constructor
    {
        // this is used to qualify the field
        // “name” is hidden by parameter
        this.name = name;
    }

    public string Name
    {
        get { return name; }
    }

    private void sayHi()
    {
        Console.WriteLine("Hi");
        Foo.SayName(this); //use this to pass current object
    }

    public void Speak()
    {
        this.sayHi(); // use this to refer to an instance method
         Console.WriteLine("Want to come up and see my etchings? ");
    }
}

class Foo
{
public static void SayName(Person person)
{
Console.WriteLine("My name is  {0}", person.Name);
}
}

 

Indexers

Define an indexer for the type to have array-like semantics.

public int this[int index]
{
    get { return array[index]; }
    set { array[index] = value; }
}

Extension methods

class Foo
{
     // with “this” modifiler we can use it like instance method of Person
     public static void SayName(this Person person)
     {
          Console.WriteLine(“My name is  {0}”, person.Name);
     }
}
 

Structures

struct MyVeryOwnInteger
{
    private int x;
    public int Gimme()
    {
    // inside struct this is treated as a variable
    // not reference to current structure
    return this.x;
    }
}
 

From the spe:

1.51.7This access

A this-access consists of the reserved word this.

this-access:
this

A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor. It has one of the following meanings:

When this is used in a primary-expression within an instance constructor of a class, it is classified as a value. The type of the value is the instance type (§1.89.1) of the class within which the usage occurs, and the value is a reference to the object being constructed.

When this is used in a primary-expression within an instance method or instance accessor of a class, it is classified as a value. The type of the value is the instance type (§1.89.1) of the class within which the usage occurs, and the value is a reference to the object for which the method or accessor was invoked.

When this is used in a primary-expression within an instance constructor of a struct, it is classified as a variable. The type of the variable is the instance type (§1.89.1) of the struct within which the usage occurs, and the variable represents the struct being constructed. The this variable of an instance constructor of a struct behaves exactly the same as an out parameter of the struct type—in particular, this means that the variable must be definitely assigned in every execution path of the instance constructor.

When this is used in a primary-expression within an instance method or instance accessor of a struct, it is classified as a variable. The type of the variable is the instance type (§1.89.1) of the struct within which the usage occurs.

If the method or accessor is not an iterator (§1.100), the this variable represents the struct for which the method or accessor was invoked, and behaves exactly the same as a ref parameter of the struct type.

If the method or accessor is an iterator, the this variable represents a copy of the struct for which the method or accessor was invoked, and behaves exactly the same as a value parameter of the struct type.

Use of this in a primary-expression in a context other than the ones listed above is a compile-time error. In particular, it is not possible to refer to this in a static method, a static property accessor, or in a variable-initializer of a field declaration.

Yet another example that C# is not Java.

Usefull helper

The default parsing method for C# using current culture, which sucks really badly. ( I wrote about it on SO)

Here a lil helper  that I use

public static class Helper
{
public static bool TryParseDouble(this TextBox textbox, out double value)
{
if (double.TryParse(textbox.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
textbox.Foreground = Brushes.Black;
return true;
}
else
{
textbox.Foreground = Brushes.Red;
return false;
}
}

public static bool TryParseDouble(this string text, out double value)
{
return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
}
}

Does malloc allocate a block of memory on the heap or should it be called Virtual Adress Space?

To answer this question, we need to know what kind of Operating System and architecture we are dealing with,  the Standard and articles refers to “storage” or “space”. These are the most general terms and the only valid ones, unless we make a bunch of assumptions.

For example:

malloc allocates a block of Virtual Address Space on the heap

This is not correct for many embedded systems. Many of them do not use Virtual Memory, because there is no need (no multitasking etc.) or for performance reasons. What is more, it is possible that some exotic device does not have the idea of heap – doubt that malloc would be used, but fairly that is one of the reasons why the Standard refers to “storage” – it is implementation-specific.

On the other hand, the example is correct for Window and Linux in our PCs. Let’s analyze it to answer the question.

First off, we need to define what is Virtual Address Space.

Virtual Address Space (VAS) is a memory mapping mechanism that helps with managing multiple processes.

  • isolate processes – each of them has his own address space
  • allow to allocate memory that 32-bit architecture is limited to.
  • provides one concise model of memory

Back to question, ”Does malloc allocate a block of memory on the heap or should it be called Virtual Adress Space ?”

Both statements are correct. I would rather say VAP instead of memory – it is more explicit. There is a common myth that malloc = RAM memory. Back in old day, DOS memory allocation was very simple. Whenever we ask for memory it was always RAM, but in modern Oses it may vary.

Changing namespaces in WP7 project

It seems that VS 2010 screws the project properties when namespaces are changed.

I posted it on SO.

And the solution is:

Check the “Startup Object” in the project properties page. The sometimes requires manually being set/corrected when the namespace of the app is changed.

Thx Matt 😉

How to play music across pages.

Silverlight for Windows Phone 7 is based on the page  navigation system. Key point is the lifetime of pages – each page is deleted while you navigate to another. To have an object(singleton f.e.) during the whole application life it could be placed in App class (App.xaml.cs file). MediaElement is definitely an object that should be one (there must be only one music player). The best and simple solution is place the MediaElement in XAML(it needs to be a part of visual tree), I have used application resources:


<!--Application Resources-->
<Application.Resources>
   <MediaElement x:Name="mediaPlayer" Source="/Sound/horrorSong.mp3" AutoPlay="False"  />
</Application.Resources>

Then you can get it from any page:

MediaElement player = null; // get the media element from App resources
if (App.Current.Resources.Contains("mediaPlayer"))
{
   player = App.Current.Resources["mediaPlayer"] as MediaElement;
}
if (player != null)
{
   player.Play();
}

MediaElement can’t play the music while Zune is connect, it is good to prompt the user about it.

if (NetworkInterface.GetIsNetworkAvailable())
{
   if (NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
      zuneTextBlock.Visibility = System.Windows.Visibility.Visible;
      return;
   }
}
zuneTextBlock.Visibility = System.Windows.Visibility.Collapsed;

This code does not guarantee if Zune is on (User sill can have the plugged phone) but is very likely that Zune is running(Zune starts while you connect the phone).

Simple center zoom

To add simple pinch zoom (that I used in my Spirit Level) use the Silverlight Toolkit for WP7 and add the pinch GetureListener to a grid

<toolkit:GestureService.GestureListener>
  <toolkit:GestureListener PinchDelta="GestureListener_PinchDelta" />
 </toolkit:GestureService.GestureListener>

and code in event

 private void GestureListener_PinchDelta(object sender, PinchGestureEventArgs e)
 {
    if (e.DistanceRatio < 1.0 || e.DistanceRatio > 1.4)
    {
      return;
    }
 // Create the animation for pinch
   Storyboard storyboard = new Storyboard();
   DoubleAnimation pinchXAnimation = new DoubleAnimation();
   pinchXAnimation.To = e.DistanceRatio;
   pinchXAnimation.Duration = TimeSpan.FromSeconds(0.3);
   storyboard.Children.Add(pinchXAnimation);
   Storyboard.SetTargetProperty(pinchXAnimation, new PropertyPath("GridScaling.ScaleX"));
   Storyboard.SetTarget(pinchXAnimation, GridScaling);

   DoubleAnimation pinchYAnimation = new DoubleAnimation();
   pinchYAnimation.To = e.DistanceRatio;
   pinchYAnimation.Duration = TimeSpan.FromSeconds(0.3);
   storyboard.Children.Add(pinchYAnimation);
   Storyboard.SetTargetProperty(pinchYAnimation, new PropertyPath("GridScaling.ScaleY"));
   Storyboard.SetTarget(pinchYAnimation, GridScaling);

   storyboard.Begin();

}
%d bloggers like this: