Blog posts tagged: c-sharp
News and other things I find interesting
Windows Phone 7 development overview in 2 minutes
Last modified: Thursday, April 28, 2011
For fun I decided to look into Windows Phone 7 (WP7) Operating System (OS) development. Microsoft is definitely trying to reinvent its Mobile image with WP7 and they are spending over $400 million on marketing to do so. WP7 is a fresh platform for Microsoft and competes against iOS, Android, and Blackberry OS.
I currently own an Android HTC phone but I'm not so keen on developing for it since the primary development language is Java. Primarily I'm a Native C++ and .NET developer.
At first I didn't want to even look at WP7, but after spending a few hours reading about it I've changed my initial perception completely. I decided to write my equivalent to "Hello World" which is a Pi Memorize program that I made in MFC around 13 years ago. Pi Memorize is a small tool that helps you learn Pi to 10,000 digits.
WP7 is Microsoft's entirely new mobile OS and it is not compatible with the existing Windows Mobile which was based on Windows CE. WP7 is expected to be released in November of 2010 and unlike iOS and Blackberry OS, it is not a closed platform. Providers of the WP7 OS include HTC, Dell, Samsung, LG, and more. Apps made for Windows Mobile cannot be used directly on WP7.
WP7 development is based on Silverlight 3 (with some features from Silverlight 4), XNA Game Studio, and the .NET Compact Framework 4. I was a little disappointed to see that there is no native development with access to lower level things via writing a hypothetical native VC++ app. Windows Mobile had support for writing native apps with VC++ and also Windows Mobile had support for the .NET Compact Framework. Another missing feature that used to exist is multi-tasking, and finally cut, copy, and paste functionality.
Silverlight is the main way to make an app in WP7 and if you don't already know Silverlight is based on XAML and is similar but has a much nicer development stack (in my opinion) to Adobe's Flash. User interfaces in Silverlight are made in a declarative language called Extensible Application Markup Language (XAML). Silverlight is based on WPF and shares its XAML support.
XNA is familiar to game developers for Xbox and it is also based on the .NET Compact Framework.
To publish your application you need to buy a yearly renewable membership for $119 USD. The submission process works by submitting a .xap package which is just a renamed .zip with all of the application files. In order to successfully submit your app there is a known issue where you need to go to http://xbox.com/live and accept the agreement there first. Otherwise the "Submit a Windows Phone 7" button simply redirects you back to App Hub / create.msdn.com.
To get started in development you can download the WP7 development toolkit which includes an emulator, Visual Studio 2010 Express, XNA Game Studio, and the needed WP7 development tools. If you already have Visual Studio 2010 installed it will install the additional tools needed without installing Visual Studio 2010. From the Visual Studio New Project Window, you will notice you have additional tab pages for "XNA Game Studio 4.0 and "Silverlight for Windows Phone".
I developed only a small application, but from start to finish it only took me 5 hours, including downloading and installation, and I've never used Silverlight before; however, I have developed some apps with WPF.
Surprisingly the hardest part of the whole development was simply figuring out how to restrict a user to only be able to type numbers. To do this you can simply use a Textbox.InputScope element:
<TextBox Name="digitsText" TextWrapping="Wrap" Height="340" HorizontalAlignment="Left" Margin="-5,31,0,0" Text="" VerticalAlignment="Top" Width="460" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" DataContext="{Binding}" KeyDown="digitsKeyDown">
<TextBox.InputScope>
<InputScope>
<InputScopeName NameValue="TelephoneNumber"/>
</InputScope>
</TextBox.InputScope>
</TextBox>
This makes it so the textbox input consists of only the characters which are available to you when entering a phone number.
To restrict the keys in that input scope such as #, *, . and space I had to write some code behind via handling the KeyDown event:
private void digitsKeyDown(object sender, KeyEventArgs e)
{
bool isValid = e.Key >= Key.NumPad0
&& e.Key <= Key.NumPad9;
//Don't allow input if we have # or * or ...
e.Handled = !isValid;
//...
}
To embed the actual digits of Pi I simply added an embedded resource to the project called PiDigits.txt which contained Pi to 10,000 digits.
I loaded that resource at runtime with the following code into a string variable called correctPiDigits.
Assembly asm = this.GetType().Assembly;
Stream stream = asm.GetManifestResourceStream("PiMemorize.PiDigits.txt");
StreamReader reader = new StreamReader(stream);
correctPiDigits = reader.ReadToEnd();
//...
Here are some screenshots of the WP7 app that I made:
Tags: wp7 mobile c-sharp visual-studio windows
Add a new commentForward declaring enums in C++
Last modified: Friday, April 22, 2011
Forward declaring things in C++ is very useful because it dramatically speeds up compilation time. You can forward declare several things in C++ including: struct, class, function, etc...
But can you forward declare an enum in C++?
No you can't.
But why not allow it? If it were allowed you could define your enum type in your header file, and your enum values in your source file. Sounds like it should be allowed right?
Wrong.
In C++ there is no default type for enum like there is in C# (int). In C++ your enum type will be determined by the compiler to be any type that will fit the range of values you have for your enum.
What does that mean?
It means that your enum's underlying type cannot be fully determined until you have all of the values of the enum defined. Which mans you cannot separate the declaration and definition of your enum. And therefore you cannot forward declare an enum in C++.
The ISO C++ standard S7.2.5:
The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than
intunless the value of an enumerator cannot fit in anintorunsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value ofsizeof()applied to an enumeration type, an object of enumeration type, or an enumerator, is the value ofsizeof()applied to the underlying type.
You can determine the size of an enumerated type in C++ by using the sizeof operator. The size of the enumerated type is the size of its underlying type. In this way you can guess which type your compiler is using for your enum.
What if you specify the type of your enum explicitly like this:
enum Color : char { Red=0, Green=1, Blue=2};
assert(sizeof Color == 1);
Can you then forward declare your enum?
No. But why not?
Specifying the type of an enum is not actually part of the current C++ standard. It is a VC++ extension. It will be part of C++0x though.
Pure virtual function call errors and related behavior
Last modified: Friday, April 22, 2011
What are abstract functions?
Abstract functions, are functions who's implementation is not yet specified.
They are useful because:
- They allow you to define an interface without defining an implementation.
- A base class may not have a specific default definition for a function, but you know that derived types will.
In C++ both interfaces, and abstract classes are done via pure virtual functions. Pure virtual functions simply say that derived types must override the function. The base type can have a default implementation (that the derived types can use by calling the base function directly) but the base functions typically have no implementation at all.
In C# there are different constructs for interfaces (interface) and undefined base functions (abstract).
This post discusses what pure virtual function call errors are, and how they work across the following languages: C++, C#, and Python.
What is a pure virtual function call error?
Pure virtual function call errors could potentially happen, in a programming language that allows you to create partially implemented classes. Although not all programming languages can have pure virtual function call errors.
Pure virtual function call errors occur when a call is made to a pure virtual function. Since an abstract base type cannot be created in most languages, they will typically occur before a derived type is fully created, or after a derived type is already destroyed. The call is therefore usually called from the base type. Pure virtual function call errors could potentially also occur when using a pointer to call a function of an already deleted object.
Can C++ have pure virtual function errors?
Yes.
Consider the order of construction for the following C++ code:
class Animal
{
public:
virtual ~Animal() {}
virtual void Speak() = 0;
Animal() {}
};
class Dog : public Animal
{
public:
virtual void Speak() { }
};
//....
Dog leia;
When you create an instance of Dog the following happens:
- Construct
Animal - Construct
Dog
When the instance of Dog named leia falls out of scope, the following happens on destruction:
- Destruct
Dog - Destruct
Animal
If you happen to call Speak() in the destructor of Animal, or in the constructor of Animal, then a pure virtual function error will occur. Most C++ compilers will give you a compiling error; however, you can get around this compiling error by calling a function that calls a pure virtual function.
Here is a code sample that will produce a pure virtual function runtime error in g++, Visual Studio 2005, and Visual Studio 2008.
class Animal
{
public:
virtual ~Animal() {}
virtual void Speak() = 0;
void SpeakPlease()
{
Speak();
}
Animal()
{
SpeakPlease();
}
};
class Dog : public Animal
{
public:
virtual void Speak() { }
};
int main(int argc, char* argv[])
{
Dog leia;
return 0;
}
Can C# have pure virtual function errors?
No.
C# allows you to create pure virtual functions by using the abstract keyword on each of your abstract function/methods. And if you have even one abstract function/method in your class you must also use abstract before your class declaration.
C# gets around pure virtual function calls though, but arguably in a worse way.
public abstract class Animal
{
public Animal()
{
Speak();
}
~Animal()
{
Speak();
}
public abstract void Speak();
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof!");
}
~Dog()
{
}
}
Dog::Speak() will be called in the destructor of Animal even know Dog is already destructed. Obviously this can lead to many problems.
Can Python have pure virtual function errors?
Kind of, and only if you follow certain conventions.
Python can't define abstract functions directly, instead you simply raise an exception of type NotImplemented.
In Python all functions/methods are virtual.
This is to say pure virtual function support is defined in Python simply by convention instead of language constructs.
Therefore unlike C++ and C#, you can create objects of a class that have some of it's functions/methods as abstract. In that sence you can have pure virtual function errors (via NotImplementedError exceptions)
But Python works like C# in the sense that even before the derived type is constructed, it will call into it. The end result is that it throws an exception that can be caught.
class Animal(object):
def __init__(self):
print("Constructing animal")
self.Speak()
def Speak(self):
raise NotImplementedError
def __del__(self):
print("Destructing animal")
class Dog(Animal):
def __init__(self):
super(Dog, self).__init__()
print("Constructing Dog")
def Speak(self):
print("Woof!")
def __del__(self):
print("Destructing dog")
super(Dog, self).__del__()
def Test():
leia = Dog()
Next time you get an error like: "R6025 Pure virtual function call", perhaps you will wonder less about the source of the error.
2 books I'm reading...
Last modified: Friday, April 22, 2011
I'm currently reading:
- Gray Hat Python: Python Programming for hackers and reverse engineers by Justin Seitz
- C# in depth 2nd edition by John Skeet
I'm about half way through both books. They're both great books so far.