Lower case all those hundread files in a folder – in one minute.
Today, I was hit by an eclipse (Android) requirement, that all resource files should be in lower case. Powershell came to rescue.
Start the powershell, by typing powershell in command window.
change to resource directory
$files= dir
dir $files| Rename-Item -NewName {$_.Name.ToLower()}
Windows Phone deployment error 0×81030110.
Native Apps which are not signed by MS will not work on Mango. Check your WMAppManifest.xml file and comment ID_CAP_INTEROPSERVICES line and try again.
Excel Automation
I wanted to redesign couple of REST API’s which have data returned in Atom format. First thing I wanted to know what are the elements returned in response. I wanted to have an excel sheet, with URL heading on top row and underneath all other attributes returned from the API. Something like this
Manually this seems a lot of work, so here a small code which will do exactly that:
namespace ExcellAutomation
{
using System;
using System.Xml;
using System.Reflection;
using System.Net;
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
const string NEWLINE = "\n\r" ;
static void Main(string[] args)
{
string[] URL = new string[] {
"Movie", @"http://rafatsarosh.com:80/v3.2/en-us/movie",
"MovieDetail", @"http://rafatsarosh.com:80/v3.2/en-us/movie/99f96de9-9a4c-42de-84be-0a0c9d959657",
"Tracks", @"http://rafatsarosh.com:80/v3.2/en-us/music/track",
"TrackDetails", @"http://rafatsarosh.com:80/v3.2/en-us/music/track/1b120f00-0100-11db-89ca-0019b92a3933",
};
string sline = "";
string sTab = "";
Dictionary d = new Dictionary();
MyExcel.StartExcel();
int row = 1; int col = 0;
foreach (string url in URL)
{
if (!url.StartsWith("http") )
{
row = 1;
col++;
MyExcel.WriteValue(col, row, url);
row++;
continue;
}
sline = url + "\n\r";
WebClient wc = new WebClient();
d.Clear();
XmlReader reader = XmlReader.Create(wc.OpenRead(url));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name != "a:link")
sTab += " ";
if (!d.ContainsKey(reader.Name))
{
d.Add(reader.Name, reader.Name);
sline += sTab + reader.Name + "\n\r";
MyExcel.WriteValue(col, row++, reader.Name);
}
}
if (reader.NodeType == XmlNodeType.EndElement)
sTab = sTab.Substring(0, sTab.Length - 2);
}
Console.WriteLine(sline);
}
Console.Read();
MyExcel.Save();
}
}
static public class MyExcel
{
static Excel.Application oXL;
static Excel._Workbook oWB;
static Excel._Worksheet oSheet;
public static void StartExcel ()
{
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
} catch ( Exception ex )
{
Console.WriteLine ( ex.Message );
}
}
public static void WriteValue(int col, int row, string value)
{
oSheet.Cells[row, col] = value;
//Come customization
if (value == "a:entry")
{
Excel.Range r = oSheet.Cells[row, col];
r.Font.Color = ConsoleColor.Blue;
r.Font.Bold = true;
}
if (value.EndsWith("s"))
{
Excel.Range r = oSheet.Cells[row, col];
r.Font.Bold = true;
}
}
public static void Save()
{
oXL.Quit();
}
}
}
Disclaimer: This is not a production code, a throw away code, just to show you the Excel automation.
WCF REST Template and 500.19
In VS2010, using WCF REST template and running your web service in IIS, you may get the following error:
HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
The error is misleading.
Fix it by making sure your site Application Pool is running under ASP.NET 4.0.
Atom and Syndication
I wanted to write a program to read tweets. There are easy to use REST based API to give you JSON or ATOM feed. There are many ways to read XML, using XMLReader, XML Serialization etc. However, I was not knowing how easy it is to read any atom feed using the syndication API of .NET. So here it is …
using System;
using System.Linq;
using System.Xml;
using System.ServiceModel.Syndication;
namespace ReadTwitter
{
class Program
{
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(@http://api.twitter.com/1/statuses/user_timeline.atom?screen_name=rafatsarosh);
SyndicationFeed feed = SyndicationFeed.Load(reader);
var tweetItems = from item in feed.Items
select new
{
item.Title.Text,
item.PublishDate
};
foreach (var o in tweetItems)
{
Console.WriteLine(o.Text );
Console.WriteLine(o.PublishDate);
}
Console.Read();
}
}
}
Here is another alternative for windows phone, as we don’t have SyndicationFeed object yet in windows phone.
WebClient wc = new WebClient();
XmlReader reader = XmlReader.Create ( wc.OpenRead(@"http://api.twitter.com/1/statuses/user_timeline.atom?screen_name=rafatsarosh"));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "content")
{
Console.WriteLine(reader.ReadInnerXml());
}
}
};
Format numbers in money format with commas – SQL
Wanted to convert the number in money format with all commas and decimal, did not find very easily and clear information in SQL BOL, so here it is:
convert the number to Money and then convert back to VarChar.
select CONVERT( varchar(16), cast (COUNT(*) as Money ), 1 ) from Table
Good resources to learn LINQ
Check some videos here.
Version checker
We often found code where we are trying to compare version of assembly or OS. Most of the time it is done wrong way with string comparison or string conversion to number etc. The correct way is to use the Version Class of .NET.
Retrieving the current application’s version:
<code>// Get the version of the executing assembly (that is, this assembly).
Assembly assem = Assembly.GetEntryAssembly();
AssemblyName assemName = assem.GetName();
Version ver = assemName.Version;
Console.WriteLine("Application {0}, Version {1}", assemName.Name, ver.ToString());</code>
Here is a code to compare two version:
<code>Version v1 = new Version(2, 0);
Version v2 = new Version("2.1");
Console.Write("Version {0} is ", v1);
switch(v1.CompareTo(v2))
{
case 0:
Console.Write("the same as");
break;
case 1:
Console.Write("later than");
break;
case -1:
Console.Write("earlier than");
break;
}
Console.WriteLine(" Version {0}.", v2);
// The example displays the following output:
// Version 2.0 is earlier than Version 2.1.</code>
<code>
Read more about it on MSDN.
Read remote computer Netstat value
On MSDN get more information on NetStat tool, which is a tool that displays statistical information about network traffic. Depending on the arguments supplied at the command line, NetStatTool collects and displays information about network connections, listening ports, and packets sent and received by the local computer. The tool uses classes in the System.Net and System.Net.NetworkInformation namespaces to gather and display information about network protocols and current TCP/IP network connections. However, MSDN sample shows how to get the information from the local computer not the remote computer.
To get the remote computer NetStat values I have to fall back on PsExec. Here is a code to read remote computer NetStat values.
static void Main(string[] args)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = @"\\LocalComputer\temp\pstools\psexec.exe";
proc.StartInfo.Arguments = @"\\RemoteComputer netstat -n -o -a -p tcp ";
//proc.StartInfo.Domain = "YourDomainName";
//proc.StartInfo.UserName = "UserName";
//string pwd = "Password";
//System.Security.SecureString secret = new System.Security.SecureString();
//foreach (char c in pwd)
// secret.AppendChar(c);
//proc.StartInfo.Password = secret;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true ;
proc.Start();
string s = proc.StandardOutput.ReadToEnd();
/* Clean the string */
s = s.Substring(s.IndexOf("Proto"), s.Length - s.IndexOf("Proto"));
s = s.Replace("Local Address", "LocalAddress");
s = s.Replace("Foreign Address", "ForeignAddress");
s = s.Replace (@"\r\n"," ");
/* Get all the details */
string[] values = s.Split( new string [] {" "}, StringSplitOptions.RemoveEmptyEntries);
proc.Close();
}
Now if you want to find out how many connections were established from a given local address, you can change your code as follows:
System.Text.RegularExpressions.MatchCollection established = System.Text.RegularExpressions.Regex.Matches(s, @”:22731[0-9. :]+ESTABLISHED”);
var i = established.Count;
In my case I don’t have to use the userId and Password, but you may need it.
I am sure, you can do the same thing with WMI, which i will leave for next time.
Browser compatibility table
HTML5, CSS, DOM v/s different Browser compatibility.


