Wednesday, October 7, 2009

LINQ / Lambda Examples : Aggregate collection


///////////////////////////////////////////////////////////////////////////////
//
// Copyright © Schakra Inc. 2009. All rights reserved.
//

///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Schakra.Samples.DotNet.Linq
{
///
/// Sample demonstrating aggregating content of a Collection.
///

public class LinqSample_02
{
public void AggregateRequestParameters()
{
// Generate Data.
Random random = new Random();
List uids = new List();
for (int i = 0; i < 10; i++)
{
uids.Add(random.Next(1, int.MaxValue));
}

// Had to use similar code snippet while working with Facebook APIs.
string uidString = uids.Aggregate(
string.Empty,
(s, uid) => string.Format("{0},{1}", s, uid.ToString())
// (s, uid) => s + "," + uid.ToString())
).Substring(1);

// Had to use similar code while working with OAuth signature creation.
SortedList oauthParams = new SortedList();

// Append all parameters in sorted order.
string sigBaseString = oauthParams.Aggregate(
string.Empty,
(s, kvp) => string.Format(
"{0}&{1}={2}", s, UrlEncode(kvp.Key), UrlEncode(kvp.Value))
).Substring(1);
}

private static Regex hexCharsExp = new Regex("%.{2}", RegexOptions.Compiled);

// Custom encoding in upper case for OAuth String.
private static string UrlEncode(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}

return hexCharsExp.Replace(
HttpUtility.UrlEncode(input), m => m.Value.ToUpper());
}
}
}

Tuesday, September 29, 2009

LINQ / Lambda Examples : Convert list of one type to another


///////////////////////////////////////////////////////////////////////////////
//
// Copyright © Schakra Inc. 2009. All rights reserved.
//

///////////////////////////////////////////////////////////////////////////////

using System.Collections.Generic;
using System.Linq;

namespace Schakra.Samples.DotNet.Linq
{
public class LinqSample_01
{
List OutlookContacts { get; set; }

public void ConvertListFromOneTypeToAnother()
{
List winLiveContacts =
OutlookContacts.ConvertAll(
contact => contact.ToWindowsLiveContact());

List outlookContacts =
winLiveContacts.ConvertAll(
contact => new OutlookContact()
{
Name = contact.DisplayName,
Phone = contact.MobilePhone
});

List outlookContacts2 =
(from contact in winLiveContacts
select new OutlookContact()
{
Name = contact.DisplayName,
Phone = contact.MobilePhone
}).ToList();
}
}

public class OutlookContact
{
public string Name { get; set; }

public string Phone { get; set; }

public WindowsLiveContact ToWindowsLiveContact()
{
return
new WindowsLiveContact()
{
DisplayName = this.Name,
MobilePhone = this.Phone
};
}
}

public class WindowsLiveContact
{
public string DisplayName { get; set; }

public string MobilePhone { get; set; }
}
}

Wednesday, July 22, 2009

BlackBerry File Explorer

As part of work, we had to generate code coverage report for the application on BlackBerry. We have used Cobertura for J2ME for generating the code coverage results. However, we had to develop a quick tool to transfer the coverage result file generated on the simulator to desktop. For this purpose, we have developed the file explorer / transfer tool for BlackBerry, which works on USB connection.

We would make this tool available tool for public download soon.

Sunday, July 12, 2009

Overriding ServerCertificateValidation

I found the following code very useful, when trying to debug https calls through fiddler. During this proxying, fiddler creates its own certificates, which will be failed by the programs. In order to override the behavior, while doing debugging, the following code could be used.


//using System.Net;
//using System.Security.Cryptography.X509Certificates;
//using System.Net.Security;

ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};

Monday, May 18, 2009

Msbuild throwing exception for v3.5 target code

As part of my current project, I had to build solution which contained both C++ and C# projects. C# project was written for target version of .NET 3.5. Whenever, I tried msbuild from command prompt, it complained ‘must declare a body because it is not marked abstract or extern’ for the property declarations in my C# classes. I have done a lot of research (Thanks to Google) to find a solution for this.

1. I ensured that the csproj file contains the target framework version of 3.5

         <targetframeworkversion>v3.5</targetframeworkversion>

2. Tried to override version through msbuild parameters

         /p:Configuration=Debug;TargetFrameworkVersion=v3.5 /toolsversion:3.5 /property:TargetFrameworkVersion=v3.5 

3. Enabled diagnostic log information for msbuild and identified that csc.exe file from v2.0.50727 is picked up during the build (event though Microsoft.Common.targets is picked up from v3.5)

        /v:diag

4. Did some more search and found out this thread from msdn. So the problem was in my environment COMPLUS_VERSION was set to v2.0.50727

I fixed the problem by setting environment variable 'COMPLUS_VERSION' value to empty. (Since my project file was already set for v3.5, clearing the environment variable helped me. Otherwise, you will need to set it to v3.5)

Thursday, March 26, 2009

Live Messenger IM Control on Blogger

I was reading Mix’09 update from Angus Logan’s blog and noticed Live Messenger IM Control on the side. I found it cool and wanted to add it to my blogger blog as well. Here are the steps that I have followed to get this up and working on my blog.

  1. Get html code for Live Messenger IM Control as specified at Delegated Authentication with the Windows Live Messenger IM Control
  2. Go to Customize > Layout > ‘Page Elements’ on your blogger site
  3. Click on ‘Add a Gadget’ link
  4. Select HTML/JavaScript gadget from Basics collection
  5. Insert the html code generated in step 1 to the ‘Content’ area and give an apt title.
    • Note: You will have to adjust the height and width of iframe to fit correctly with your blogger page template
  6. Save and view your blog. You are all set. :)

Thanks to Rajendra for helping me with this. :)

Wednesday, March 25, 2009

Writing blogs using Live Writer

Windows Live Essentials come with a set of goodies. Out of which Live Writer is a tool which can be used to write blogs and publish to most of the popular blog sites. I am also trying out the same. And this blog is written and posted to my blogger site using Windows Live Writer.

I am listing down, what I liked about Live Writer.

  • Preview of blog is much much better from Live Writer. I love it.
  • Switching between Edit, Preview and Source is faster.
  • I don’t need to do an explicit spell checker
  • I have better control while inserting hyperlinks
  • Tables, alignments, picture, formatting etc looks good. (Haven’t used it really)

What did I not like about Writer?

  • While showing the preview, the labels shown do not seem to be correct. This could be a bug with Writer.
  • With Live Writer also, I am not able to see the code block, custom edit of the template that I made is not coming proper in the preview mode. Yea, I understand that it is difficult for both Blogger and Writer to do it, as it need to sort of invoke the runtime page execution to run the custom script and generate the html output. This is something which I would really like to have. (Either auto execution of script in preview mode, or code style inbuilt in the blogger theme).

Disclaimer: I haven’t used blogger for long time. So I am not really sure about all the features of blogger create page. These are my initial impressions. :)

Debugging using Fiddler

I have been using Fiddler for a long time. I use fiddler to trace http/https calls to see what is the actual http messages (request - response).

From C#, I typically use the following configuration.


<system.net>
<defaultproxy>
<proxy bypassonlocal="False" usesystemdefault="True" />
</defaultproxy>
</system.net>

Sunday, March 22, 2009

Customizing Blogger Template

When I started blogging, one of the main requirements I had was to enable code block on my blog. I have enabled syntax highlighting on my blog by taking help from Using SyntaxHighlighter on BLOGGER and How to get syntax highlighting in Blogger with SyntaxHighlighter.

Also, by default the template that I was using was having smaller width for the main post area. To increase this I have followed Rounders 2 with a wider post area.

APM pattern with Anonymous methods

Jeffrey Ritcher has explained the APM pattern with anonymous methods in one of the concurrent affairs article in msdn magazine. Here, one of the key things to notice is that anonymous delegate method could be executed on another thread at a later point of time (after executing the statements below the BeginXYZ method).

Consider the following APM code.

static void Main(string[] args)
{
// Create instnace of LongTask that is executed asynchronously
// Ref: http://msdn.microsoft.com/en-us/magazine/cc163467.aspx
LongTask task = new LongTask(15); // Task should run for 15 seconds
Console.WriteLine(
string.Format("Thread-{0} : {1}",
Thread.CurrentThread.ManagedThreadId, "Starting Task"));

// APM pattern with anonymous method
task.BeginDoTask(
delegate(IAsyncResult ar)
{
Console.WriteLine(
string.Format("Thread-{0} : {1}",
Thread.CurrentThread.ManagedThreadId, "Delegate called"));
},
null);

Console.WriteLine(
string.Format("Thread-{0} : {1}",
Thread.CurrentThread.ManagedThreadId, "Control came back after BeginDoTask"));

Thread.Sleep(25 * 1000); // Sleep for 25 seconds
}
When I run the above code, output is coming as given below.

Thread-1 : Starting Task
Thread-1 : Control came back after BeginDoTask
Thread-3 : Delegate called
This means that the anonymous method could be called from another thread at a later point of time. So the below given code is very very wrong.

// Following code is very very wrong.
// Never use this approach
int returnData = 0;
asyncObj.BeginXYZ(
delegate(IAsyncResult ar)
{
returnData = asyncObj.EndXYZ(ar);
},
null);

// It is most likely that returnData is 0
return returnData;

Hello World

Hello everyone.. :)

Disclaimer: I have created this blog to share my thoughts, learning, experience and knowledge around various technical areas that I come across. All the information posted here in this blog are solely my own personal opinions and are not related to the company that I work for or anybody else.