Category Archives: C#

14 C# Tips that improve code efficiency and productivity

C# is a wonderful programming language; I’ve been writing windows apps and working with C# since C# 2.0 and I like it. The C# syntax in general is very straight forward and simple, in addition, I also like the fact that despite the constantly expanding code library, things are still kept readable. Below I have listed 14 tips that you can use to improve code efficiency, make your code more compact and achieve productivity. I have no doubt that you know or use one or more already.

1. Ternary Operator (?:)

I first time read about the ternary operator while I was browsing the list of operators in C# back in 2006, it’s an interesting operator and I still use it today in programming tasks. The ternary operator is very straight forward and simple to understand—I’ll give you a few examples to clear up things and make sure you understand this.

1.1 string IsEligibleToPurchaseAlcohol(int age)
I’ve written a function which prints out a string, based on the age value the user enters. I’ve followed the alcohol laws of the United States, this means that there is a law for alcohol minimum purchase age; you have to be 21 or over to be eligible to buy alcohol. Here’s the code written with If-then-else:

string IsEligibleToPurchaseAlcohol(int age)
{
   string message = null;

   if (age >= 21)
   {
        message = "Congratulations! You are eligible to buy alcohol.";
   }
   else
   {
        message = "Sorry! You're not eligible to buy alcohol.";
   }
   
   return message; 
}

And here is the code written in one single return line using the ternary operator, notice that both functions complete the same check.

string IsEligibleToPurchaseAlcohol(int age)
{
    return age >= 21 ? "Congratulations! You are eligible to buy alcohol." : 
                       "Sorry! You're not eligible to buy alcohol.";
} 

1.2 string PMorAM()
In this second example, I am using the ternary operator to determine if it is PM or AM, and return that in a string with current time + “PM” or “AM”.

string PMorAM()
{
    return string.Format("{0}:{1} {2}", DateTime.Now.Hour, 
         DateTime.Now.Minute, DateTime.Now.Hour >= 12 ? "PM" : "AM"); 
}

1.3 bool Is18(int age)
In this third example, I am using the ternary operator to determine if the user is 18 years old or younger, and return true or false.

bool Is18(int age)
{
    return age == 18 ? true : false; 
}

2. Null-Coalesce Operator (??)

Every time we need to test for null values in our code, the null-coalesce operator (??) becomes handy to use. I’ve created 3 code-snippets below, just to demonstrate code efficiency and to show how much shorter the code can become.

2.1 The regular newbie way of testing for null value

object a = null;
object b = new object();
object c;

if (a != null)
    c = a;
else
    c = b; 

It is very obvious that a C# developer that has just learned to use the ternary operator will rewrite this to a single line.

2.2 Using the ternary operator to test null

object a = null;
object b = new object();
object c = (a != null) ? a : b; 

With the null-coalescing operator we can make this shorter. If the left-hand side equals null, the right-hand side will be assigned, in this context object b.

2.3 Using the null-coalescing operator to test null

object a = null;
object b = new object();
object c = a ?? b;

3. Boolean

The Boolean (a.k.a. bool) is a data type that supports two states, true/false. The bool data type is commonly used to determine whether a return value is true or false, as we saw with the third example in the examples that use the ternary operator. To explain what code efficiency one can gain by just using bool in if-statements and return values, I’ve written some examples below.

3.1 If-else statement
To be more correct, and more efficient one does not need to fix check whether a method will be true or false, only invoke the method name inside the if-statement, and the rest of the check will occur automatically.

if (IndividualsNormalAge() == true)
{
    System.Diagnostics.Debug.Print("Yes!"); 
}
else
{
    System.Diagnostics.Debug.Print("No!"); 
}

To make this more efficient, simply remove == true, and it will be determined autormatically.

if (IndividualsNormalAge())
{
    System.Diagnostics.Debug.Print("Yes!"); 
}
else
{
    System.Diagnostics.Debug.Print("No!"); 
}

3.2 Return
In some cases one does not need to use the ternary operator to return true/false, that’s how simple it is, below I have a few code-snippets:

bool IndividualsNormalAge()
{
    Random r = new Random(); 
    int age = r.Next(1, 113); 
    return (age < 111) ? true : false; 
}

The ? true : false can be removed, and it will still return true/false.

bool IndividualsNormalAge()
{
    Random r = new Random(); 
    int age = r.Next(1, 113); 
    return (age < 111); 
}

It is very easy to understand this, to clarify further, I've added two more code-snippets below:

return (i == 1) ? true : false;

and even shorter:

return (i == 1); // Returns true only if i equals 1

4. Is String Null?

The string.IsNullOrEmpty tests strings by checking for string references that are null, or empty strings. In short, the static method IsNullOrEmpty enables you to simultaneously test whether a String is null or its value is Empty—as tested in the code-snippet below:

if (string.IsNullOrEmpty(s))
    return "This string is null or empty.";
else
    return string.Format("This string is not null or empty, it equals to \"{0}\" ", s);

5. Data Type Conversion

It's very common that we sometimes or very often have to convert data types for various of reasons, for instance, if the we have a decimal variable with a set value, and we want to convert it into an Integer or int an explicit conversion will be performed to achieve this.

int j = 0;
decimal money = 9500.34m;

j = (int)money; // An explicit conversion using cast operator.

The better option is to use the Convert class which supports full Data Type conversion between all data types.

int money = 0; 
string uservalue = null;

uservalue = Console.ReadLine();
money = Convert.ToInt32(uservalue); 

In the first code-snippet we do explicit conversion using a cast operator, and in the second code-snippet we use the Convert class and invoke the ToInt32() method to convert a string to an int. Is there any difference? Yes, of course there's a difference between the first code-snippet and the second code-snippet—I'll explain, explicit conversions strictly requires a cast operator, and that the source and destination variables are compatible. Conversion using a helper class such as Convert allows us to convert between non-compatible types and does not require the use of cast operator, thus, providing a safe conversion method with performance benefits.

6. Using Statement

Allocation of memory is as important as freeing memory. However, in C# we have the Garbage Collector (GC) which takes care of a lot, but some classes in the .NET library implement the IDisposable interface,
and these require manual object disposal. In the code-snippet below, we make a new instance of the SHA1 class, and in the finally code-block we dispose the object.

SHA1 sha1 = SHA1.Create(); 
            
try
{
   StringBuilder sb = new StringBuilder();
   byte[] data = Encoding.UTF8.GetBytes(text);
   byte[] hash = sha1.ComputeHash(data);

   foreach (byte b in hash)
   {
       sb.Append(b.ToString("x2").ToLower());
   }

   hashed = sb.ToString();
}
finally
{
    if (sha1 != null)
        ((IDisposable)sha1).Dispose();
}

A better way is to use the using statement once, as shown below:

// Allocate
using (System.Security.Cryptography.SHA1 sha1 
    = System.Security.Cryptography.SHA1.Create())
{
     //Use the sha1 to computer the hash.
     //sha1 can only be used inside this code-block
}
//Automatically Disposed

In the second code-snippet, using (...) { ... } will only allow the usage of an object once within the curly braces ("{}"), and disposal will happen automatically after the last curly brace. This approach is much better, especially, if we only need to use one class once.

7. Properties

Prior to C# 2.0, programmers used to solve things very differently, see the first code-snippet:

class Child
{
    public Child() { }

    private int age = 0;

    public int GetAge() { return age; }
    public void SetAge(int _age) { age = _age; }
}

In the first code-snippet, a programmer in C# 1.0 was required to write two methods to be able to set and get a value, in this context, the age of a child. However, that's a lot of code, and it quickly gets messy and it's not elegant enough. However, this issue was solved in C# 2.0 with the introduction of Properties. The code-snippet below demonstrates Properties.

class Child
{
    public Child() { }
      
    private int _age = 0;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    } 
}

The Properties are really useful, especially when we need to protect internal variables and not expose them to the outside world. The second code-snippet above clearly protects our internal variable, _age. However, even the second code-snippet isn't elegant enough, what's elegant is the last code-snippet below. Yes, only get; set; —this is an auto-implemented property (called auto-implemented properties) introduced in C# 3.0.

class Child
{
    public Child() { }
    public int Age { get; set; }
}

The last code-snippet is cleaner, safer and more concise since no additional logic is required in the property accessors, in short, more code efficiency benefits.

8. Namespace Alias Qualifier

The Namespace Alias Qualifier (a.k.a. Aliases) in C# lets developers use the alias name instead of the complete namespace. This is very useful, since namespaces in general can become quite long, an alias becomes very handy. In the code-snippet below, Excel is an alias of the Microsoft.Office.Interop.Excel namespace, yeah the default namespace is long, but we've shorten it.

using Excel = Microsoft.Office.Interop.Excel;

...

var excelapp = new Excel.Application();
excelapp.Visible = true;

9. Object Initializers

The old way, to initialize property values from outside of the class, we would have to write either use a constructor or initialize the properties separately as shown in the first code-snippet:

Child child = new Child();
child.Age = 10;
child.Name = "Bryan";
child.StreetAddress = "Seattle, WA 98124";

The code-snippet above, can be written as:

Child child = new Child() { Age = 10, Name = "Bryan", StreetAddress = "Seattle, WA 98124" };

This language feature exists in C# 3.0 and newer versions, but is not supported in C# 1.0 and C# 2.0. In short, this provides a more elegant way to achieve the same thing, in addition, it's a useful shorthand and provides good code productivity.

10. Nullable Types

Every C# developer in the world knows how to work with value types like int, double, bool, char, and so one. They're really useful, but they have one flaw: they simply cannot be set to null, except string which can be set to null. For example, a bool variable can only hold the values true or false, however, putting the question symbol ("?") or as shown below, Nullable it is possible to assign null i.e. undefined.

Nullable<bool> status = null;
int? i = null;

11. Type Inference

C# 3.0 introduces the concept of type inference with the var keyword. The var keyword was added to support anonymous types which is another new feature in C# 3.0. Without this keyword, we would not be able to create a variable of an anonymous type if we always needed to specify the type. The best part is that the compiler determines the type automatically.

string[] Elementaryschools = {"Adams Elementary", "Hyde Elementary School", 
                              "Brookland Elementary", "Meyer Elementary School", 
                              "Thomas Elementary School", "Young Elementary School"};
var school = from name in Elementaryschools
             where name[0] == 'T'
             select name;
foreach (string n in school)
    Console.WriteLine(n);

The output in the console application will be:

Thomas Elementary School

The main reason "Thomas Elementary School" is printed out, is because we say: where name[0] == 'T', we select only the name if it begins with a 'T'. I just wanted to give some code explanation, in case it becomes complicated. The following two declarations of i are functionally equivalent:

int i = 25; //Explicitly typed
var i = 25; //Implicitly typed

12. Lambda Expressions

Lambda expressions were introduced in C# 3.0, and they use the lambda operator =>. Lambda expressions provide a more concise, functional syntax for writing anonymous methods (note: anonymous methods were introduced in C# 2.0). Since functional programming requires a more declarative style of writing code, lambda expressions are handy, in short, lambda expressions are simply functions/methods.

The following code-snippet shows the definition of a delegate and a method that can be used to initialize the delegate:

public delegate int DoubleInteger(int x);

...

class DelegateSample {
    static public int DoubleNow(int x) { return x * 2; }
}

Create and initialize an instance of the delegate, and then call it:

DoubleInteger dint = new DoubleInteger(DelegateSample.DoubleNow); 
Console.WriteLine("{0}", dint(16));

Using lambda expressions, the syntax gets even terser:

DoubleInteger dint = x => x * 2; 
Console.WriteLine("{0}", dint(16));

Lambda expressions provide a powerful shorthand that can be used to significantly speed up C# development. In short, lambda expressions allow C# developers to shorten their code significantly and make it more compact form, isn't this good huh? Of course it is good especially if we want to achieve productivity.

13. Optional and Named Parameters in C# 4.0

C# 4.0 introduces optional and named parameters. Named parameters free us from the need to remember or to look up the order of parameters in the parameter lists of invoked methods. Optional parameters enable us to omit arguments for some parameters. These two language features can be used with Microsoft Office Automation APIs—this is what the second code-snippet demonstrates below.

Word.Application wordapp = new Word.Application() { Visible = true };
object MissingValue = System.Reflection.Missing.Value;
object Filename = @"C:\sampledocument.docx"; 
object ReadOnly = true; 

wordapp.Documents.Open(ref Filename, ref MissingValue, ref ReadOnly, ref MissingValue, 
    ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,ref MissingValue, 
    ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, 
    ref MissingValue, ref MissingValue); 

With the support of optional and named parameters this becomes even shorter:

Word.Application wordapp = new Word.Application() { Visible = true };
wordapp.Documents.Open(@"C:\sampledocument.docx", ReadOnly: true);

The Microsoft.Office.Interop.Word has a method, Documents.Open this method has one required parameter, and 15 optional paramters, that's a lot huh? Thanks to named paramters we're able to omit a few or all the optional paramters by using their names and passing the argument value for each—as already demonstrated in the second code-snippet above, ReadOnly: true.

14. Asynchronous Programming with Async and Await in C# 5.0

Finally, as a bonus I've decided to demonstrate the usage of async and await in C# 5.0. Asynchronous and Synchronous programming has always been useful, especially when we want our application to be able to perform multiple operations at the same time i.e. multitasking. However, the traditional way of writing asynchronous applications is usually complicated, resulting in applications that become difficult to—write, debug, and maintain.

14.1 The traditional way

public delegate int GetValueAsync(int callDuration);

class ProgramA
{
    public ProgramA() { }

    public int GetValueMethod(int callDuration)
    {
        Thread.Sleep(callDuration); 
        int i = ReturnRandomNumber();
        return i; 
    }

    private int ReturnRandomNumber()
    {
        return new Random().Next(1, 1000);
    }
}

C# 5.0 introduces two new keywords, async and await—these help C# developers build asynchronous applications that are capable of achieving multitasking without performance issues.

14.2 The New Modern way

class ProgramB
{
    public ProgramB() { }

    public async void PrintAsync()
    {
        int a = await GetValueAsync(); 
        Console.WriteLine("The Multiplication of one" + 
            " random number with itself is: {0}", a * a);
    }

    private async Task<int> GetValueAsync()
    { 
        int i = ReturnRandomNumber();
        return await Task.FromResult<int>(i); 
    }

    private int ReturnRandomNumber()
    {
        return new Random().Next(1, 1000);
    }
}

Create and initialize one instance of each, and then invoke their methods:

static void Main(string[] args)
{
    ProgramA prgm = new ProgramA();
    GetValueAsync gasync = new GetValueAsync(prgm.GetValueMethod);
    IAsyncResult result = gasync.BeginInvoke(2000, null, null); 
            
    Console.WriteLine("Test method GetValueAsync() from ProgramA begins.");
    Thread.Sleep(300);
    int a = gasync.EndInvoke(result); 
    Console.WriteLine("The Multiplication of one random numbers is: {0}", a * a);
    Console.WriteLine("\n\n");

    ProgramB prgmB = new ProgramB();
    Console.WriteLine("Test method PrintAsync() from ProgramB begins.\n");
    prgmB.PrintAsync();

    Console.WriteLine("\n");
    Console.ReadKey(); 
}

In conclusion, we can easily avoid performance bottlenecks and enhance the overall responsiveness of our C# applications by using asynchronous programming. The new Visual Studio 2012 and .NET Framework 4.5 leverages asynchronous support via a simplified approach, async programming. In Windows 8 the support for asynchronous programming is much more extended thanks to the Windows Runtime (WinRT).

More to Explore

That's a few tips, and I hope you found them helpful. We've now just briefly had a look on 14 different approaches that help C# developers achieve code efficiency, write more compact code, and achieve productivity. However, there is more to explore—for example, in terms code efficiency, using fewer loops to achieve the same result—this is something I did not cover in this article. We'll tackle that next month. In the meantime, explore other methods and approaches that allow you to become a better C# developer, and be sure to drop me an e-mail with suggestions for future articles.
 
Happy coding!
 

C#: Format a String as Currency

As the title of this short article states, this topic is about “Currency formatting”, and I will show some examples on how to do this with C#. When producing a string for output to a customer, it is useful to format any currency value in a more human friendly money format. This is extremely easy in C#.

The standard numeric format specifier I am going to use is the Currency (“C”) Format Specifier, which is formatted like this: {0:C}

decimal price = 9565.50m;
string total = string.Format("{0:C}", price); 
Console.WriteLine(total + "\n\n"); 
Console.ReadKey();

Another way to achieve the same result is by using ToString(),

decimal price = 9565.50m;
Console.WriteLine(price.ToString("C") + "\n\n"); 
Console.ReadKey();

Result:

In addition, one can add more checks, for example, to output the value with a different currency symbol (e.g. $ £ € Lek Kr).

Using CultureInfo.CreateSpecificCulture() one can set the culture information, and thereby adjust to the country and print out the price with the proper money currency symbol.

decimal price = 9565.50m; 
string total = string.Format(CultureInfo.CreateSpecificCulture("en-GB"), "{0:C}", price);
Console.WriteLine(total + "\n\n"); 
Console.ReadKey();  

Result:

To once again show that this works, lets try with the Albanian currency format, “sq-AL”,

string total = string.Format(CultureInfo.CreateSpecificCulture("sq-AL"), "{0:C}", price);

Result:

As I said one can add more checks, I made a method which checks the culturename with a switch statement, and then formats the price string for output:

static string FormatPrice(decimal price, string cultureName)
{
   string formatted = null;
   CultureInfo info = new CultureInfo(cultureName); 
   switch (info.Name)
   { 
       case "en-US":
             formatted = string.Format(CultureInfo.CreateSpecificCulture("en-US"), 
                 "{0:C}", price);
             break; 
       case "en-GB":
             formatted = string.Format(CultureInfo.CreateSpecificCulture("en-GB"), 
                 "{0:C}", price);
             break;
       case "sq-AL":
            formatted = string.Format(CultureInfo.CreateSpecificCulture("sq-AL"), 
                "{0:C}", price);
            break;
       case "se-SE":
            formatted = string.Format(CultureInfo.CreateSpecificCulture("se-SE"), 
                "{0:C}", price);
            break; 
   }

   return formatted; 
}

This method can easily be invoked inside the Console.WriteLine() method,

decimal price = 9565.50m; 
Console.WriteLine(FormatPrice(price, "se-SE") + "\n\n"); 
Console.ReadKey(); 

Result:

Wrapping up

I’m not quite done with this, what’s really missing is real currency conversion support—for example, the ability to convert between American (USD) and European Euro (€) and vice versa. While, this tutorial and its examples are really covered to a level, this means that there’s probably more that can be added.

But for now, happy coding!

C# Detect Windows OS Version

Software developers sometimes have to add additional lines of code to check the Windows Operating System (OS) version numbers. There are a few ways this can be achieved, and I’ll cover them in this tutorial.

There are three traditional methods or ways to do this:

      1. Read information from the Windows Registry, this is very easy; you only have to use the Registry class in .NET.

      2. Use Environment variables. However, it doesn’t give you the additional details you might want. For example: There is no way to detect Windows® 7 editions.

      3. Use the Windows Management Instrumentation (WMI) query, WMI gives you everything you possibly might need in one single shot, and just a few lines of code. However, WMI is not supported in older versions of the Windows® NT Kernel (but this is becoming less of a problem nowadays).

The Code

There’s in fact, a fourth method, which is to use the OSVersion property in .NET found under the Environment class. We will look a this one as well, but first, CPU Architecture. Using the environment variable “PROCESSOR_ARCHITECTURE”.

bool Isx86()
{
   string cpu = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
   return cpu == "x86" ? true : false; 
}

The way we use this code is simple:

if (Isx86())
    Debug.Print("Your CPU architecture is = x86");
else
    Debug.Print("Your CPU architecture is = x64");

However, another method that is more recommended way to check CPU and OS bits is by checking the IntPtr.Size. If IntPtr.Size == 4 it means x86 and if it return IntPtr.Size == 8 it means x64. To save some lines of code, and code a fewer lines, I recommend this.

bool Is64() { return IntPtr.Size == 8 ? true : false; }  

Another solution that is also available, is Environment.Is64BitOperatingSystem, however, this works only in .NET Framework 4.0 and apps made with .NET Framework 4.

Now time to check Windows OS versions. I made a basic class which I named WinOperatingSystem in C#, the code snippet for using is by making a new instance of the class via the constructor.

WinOperatingSystem os = new WinOperatingSystem();  

Usage:

if (os.IsWindows7())
      Debug.Print("Yes this is Windows 7");

if (os.IsWindowsVista() || os.IsWindowsVistaSP2())
      Debug.Print("Yes this is Windows Vista");

if (os.IsWindowsXP() || os.IsWindowsXP64())
      Debug.Print("Yes this is Windows XP"); 

See the image below for the first line of code execution.

Attachment:
File: WinOperatingSystem.cs

For now, happy coding!

Windows Phone 7: Using GeoLocation API and Consuming Web-Service with C#

Hey! I am back with a third post on WP7 Development with C#. This time we’ll be making a Windows Phone 7.1 application that uses the GeoCoordinateWatcher class and consumes one web-service.

 

  1. Begin by launching Microsoft Visual Studio 2010 on your computer, click File, next New and select Project.
  2. From the Installed Templates Pane, expand Visual C# and select Silverlight for Windows Phone.
  3. From the Project Templates List in the middle select Windows Phone Application. Name the project whatever you want I named mine “geolocationsample” and click OK.

 

Microsoft Visual Studio 2010 will now generate all the project files for us to use. Before we continue, start by dropping two UI components from the Toolbox, one Textbox and one Button. For the button1 set the text to “Find Me” and save. Make sure it looks as shown in the screenshot below:

 


(Click to view larger)

 

Next, right-click button1 and select Properties, from the Properties panel, select Events and locate the Click, once located double-click it so that Microsoft Visual Studio adds button1_Click event to our code. Leave it for now; we’re going to write code for that later.

 

To be able to use the GeoCoordinateWatcher class we need to add another assembly reference to our code, you do this from the Solution Explorer, by right-clicking References and selecting Add Reference. Find the System.Device reference and click OK.

 

 

Don’t forget to add the namespace inside the code as well.

 


Time to write code for the button1_Click event, you can just copy the code I’ve written below:

//Setup two variables
double latitude, longitude = 0.0;  
//Create an instance of the GeoCoordinateWatcher class
GeoCoordinateWatcher gwatcher = new GeoCoordinateWatcher();
//Store all the Position information inside PositionNow 
var PositionNow = gwatcher.Position;

/* 
   New York, United States
*/
latitude = 74.0064;
longitude = 40.7142;


/* 
  If the location is NOT unknown 
  then retrieve Latitude and Longitude 
  dynamically.
*/
if (!PositionNow.Location.IsUnknown)
{
     latitude = PositionNow.Location.Latitude;
     longitude = PositionNow.Location.Longitude;
}

The above code will compile fine without syntax errors and/or other errors. However, for us to retrieve location information i.e. for example New York, United States latitude = 74.0064, and longitude = 40.7142, we have to consume some web-service that does this for us.

I’ve decided that I will use the Microsoft Research Maps (http://msrmaps.com/webservices.aspx), the TerraService (http://msrmaps.com/TerraService2.asmx), which provides an *.wsdl for Microsoft Visual Studio to read from XML, http://msrmaps.com/terraservice2.asmx?wsdl.

Copy this url = http://msrmaps.com/terraservice2.asmx. In Microsoft Visual Studio, right-click the project (In my case geolocationsample), and from the context-menu select Add Service Reference.


(Click to view larger)

In my project, I left the namespace name ServiceReference1 and clicked OK.

Note: If Microsoft Visual Studio reports Error: Cannot import wsdl:binding, then you’ll have to reconfigure the Service Reference to fix this, else IntelliSense will not find the namespace of the service.

To fix this, simply right-click the Service Reference, ServiceReference1 and from the context-menu select Configure Service Reference.

Uncheck Reuse types in referenced assemblies and click OK.


(Click to view larger)

Now, let us go back to the button1_Click and consume the Web-Service we’ve referenced, copy the code below and paste it before the closing curly bracket (}) in the button1_Click event.

//Create an instance of the TerraServiceSoapClient class 
ServiceReference1.TerraServiceSoapClient tsclient = new ServiceReference1.TerraServiceSoapClient();

//Add an event handler
tsclient.ConvertLonLatPtToNearestPlaceCompleted += new EventHandler(tsclient_ConvertLonLatPtToNearestPlaceCompleted);

//Pass latitude and longitude and consume           
tsclient.ConvertLonLatPtToNearestPlaceAsync(new ServiceReference1.LonLatPt { Lat = latitude, Lon = longitude }); 

Since we’ve added another event handler (tsclient_ConvertLonLatPtToNearestPlaceCompleted), we need to write some code within it as well, copy the line below:

textBox1.Text = e.Result;


If you have done everything correctly, then you’re good to go, hit F5 to build and run in debug mode inside the Windows Phone Emulator.

In my Textbox it says: “7807 km NE of New York, New York, United States”, so it worked slightly with a fraction of error I guess, anyway.

To find more latitudes and longitudes, simply use Google.com, new york latitude longitude or Redmond, Washington, United States, Note: Redmond, Washington, United States, latitude = 47.674 and longitude = -122.12, anyway, good luck hope this worked for you.

(Click image to view larger)

If you have problems with this code sample, simply do this, from the Solution Explorer right-click the ReferenceService1 and from the context-menu select Update Service Reference, this will re-download all the necessary information, code and more for your app to consume the web-service.

Download attached C# code sample:
Geolocationsample.zip

Windows Phone 7: Install Windows Phone 7.1 SDK

Welcome, to a Windows Phone 7.1 (WP7) Apps Development Series, I’ll be covering quite a lot about the WP7 and building different samples with C#.
 
However, before you begin make sure you have:
 

  • Microsoft Visual Studio 2010 SP1 Installed.
  • Windows Phone SDK 7.1 Installed.

 

Download: Service Pack 1 for Microsoft Visual Studio 2010
Download: Windows Phone SDK 7.1
 
Install everything. :)
 
Step 1: SP1 for Microsoft Visual Studio 2010
 

 
Step 2: Complete the Windows Phone SDK 7.1 installation, and check your Start Menu for new tools installed by the SDK
 

 
Step 3: Launch Microsoft Visual Studio 2010, and you’ll see new project templates added
 

 
Step 4: Create one sample, and hit F5 to launch it inside the Windows Phone Emulator
 

 
That’s it for this time…enjoy!
 

Math Is Fun: Geometric Sequences and Sums with C# and (Native) C++

Mathematics is really fun sometimes; however, what makes it difficult is that it is a fundamentally different way of thinking—for example, learning languages can be much easier than learning math.

 

Since I’ve been playing with geometrical sums and sequences I decided to try this out with some computer programming, so I wrote two methods in two different languages, one in C++ and the other one in C#.
 

I’ll be using the following geometric sum formula:

 

C#:

static double CalcGeoSum(double a1, double a2, int n)
{
   double k, sum = 0;
   k = a2 / a1;

   if (k <= 1)
       sum = 0; 
   else
       sum = (a1 * (Math.Pow(k, n) - 1)) / (k - 1);

   return sum; 
}

 

C++:

float CalcGeoSum(float a1, float a2, int n){
   float k, sum = 0.0;
   k = a2/a1; 
   
   if(k <= 1)
       sum = 0.0; 
   else 
       sum = (a1 * (pow(k, n)-1))/(k-1);
   
   return sum; 
}

 
It's simple to invoke this function in any of the programming languages, just invoke it and pass it the required arguments. See the example below:
 
Invoke in C#:

static void Main(string[] args)
{
    Console.WriteLine(Convert.ToString(CalcGeoSum(3, 18, 6)) + "\n\n");
    Console.ReadKey(); 
}

 
Invoke in C++:

void main(){
    float result = CalcGeoSum(3, 18, 6); 
    cout << result << endl; 
	
    system("pause"); 
}

 
The output when you compile an run one of these code snippets in debug mode will be:

Output in C#: 27993
Output in C++: 27993

 
For further reading, I recommend MathWorld,
http://mathworld.wolfram.com/GeometricSeries.html