|
|
by Viper
4. May 2009 12:37
Every time somebody says Use WMI to do this or that, it gives me heebie-jeebies. I start talking to my self, now I will have to figure out what WMI class to use for this task, what properties and methods are exposed and how to write SQL like statement to accomplish what I am trying to do. Last week I was trying to create an automated tool to test load balancing on web servers. Part of the task is to switch to turn off network adapters at certain intervals and turn them on. All help on this task pointed to making use of WMI. There you go, something I really did not want to hear but I had to do.
During this process of creating my nifty tool for automated testing, I found out about WMI Code Creator. Even though it was publish 4 years ago, it is a very useful tool and must have if you are doing WMI programming. Not only it lists all the classes exposed for various tasks, it tells you the properties, methods etc. for each of those classes. And best part is that it generates some boiler plate code as well in C#, VB.Net and VB script. What more could one ask for. With click of few menu options, I was able to generate following code that lists all network adapters on server and spits out the properties of each device.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
namespace WebMonitor
{
class Program
{
static void Main(string[] args)
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_NetworkAdapter");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine
("----------------------------");
Console.WriteLine
("AdapterType: {0}", queryObj["AdapterType"]);
Console.WriteLine
("AdapterTypeId: {0}", queryObj["AdapterTypeId"]);
Console.WriteLine
("AutoSense: {0}", queryObj["AutoSense"]);
Console.WriteLine
("Availability: {0}", queryObj["Availability"]);
Console.WriteLine
("Caption: {0}", queryObj["Caption"]);
Console.WriteLine
("ConfigManagerErrorCode: {0}", queryObj["ConfigManagerErrorCode"]);
Console.WriteLine
("ConfigManagerUserConfig: {0}", queryObj["ConfigManagerUserConfig"]);
Console.WriteLine
("CreationClassName: {0}", queryObj["CreationClassName"]);
Console.WriteLine
("Description: {0}", queryObj["Description"]);
Console.WriteLine
("DeviceID: {0}", queryObj["DeviceID"]);
Console.WriteLine
("ErrorCleared: {0}", queryObj["ErrorCleared"]);
Console.WriteLine
("ErrorDescription: {0}", queryObj["ErrorDescription"]);
Console.WriteLine
("Index: {0}", queryObj["Index"]);
Console.WriteLine
("InstallDate: {0}", queryObj["InstallDate"]);
Console.WriteLine
("Installed: {0}", queryObj["Installed"]);
Console.WriteLine
("LastErrorCode: {0}", queryObj["LastErrorCode"]);
Console.WriteLine
("MACAddress: {0}", queryObj["MACAddress"]);
Console.WriteLine
("Manufacturer: {0}", queryObj["Manufacturer"]);
Console.WriteLine
("MaxNumberControlled: {0}", queryObj["MaxNumberControlled"]);
Console.WriteLine
("MaxSpeed: {0}", queryObj["MaxSpeed"]);
Console.WriteLine
("Name: {0}", queryObj["Name"]);
Console.WriteLine
("NetConnectionID: {0}", queryObj["NetConnectionID"]);
Console.WriteLine
("NetConnectionStatus: {0}", queryObj["NetConnectionStatus"]);
}
catch (ManagementException e)
{
Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
|
|
|
b3a3a3ab-052f-43e1-a014-3582088c9367|0|.0
Views: 792
Tags: wmi
.Net | WMI
by Viper
16. April 2009 19:14
Read, download samples, tutorials etc. for WinForms.
by Viper
7. April 2009 12:33
Some time back I discussed How to submit requests to web sites programatically using HttpWebRequest. As I discussed in that article that back bone of the whole process is to know the structure of the page along with FORM parameters that need to be passed to target URL. Well that works for most of the application. You run into problem when you are dealing with ASP.Net because of its event model that gets used ASP.Net framework. If you follow the procedure discussed in last article, you will notice that most of the time you are not able to login into the site programatically. There is nothing wrong with the method that I discussed. There is little quirk for ASP.Net and that requires little understanding of how ASP.Net event mechanism works. So I will give brief description, you can read details in microsoft documentations .
If you look at source of an ASP.Net page, you will notice a hidden input variable __EVENTTARGET. When you click on some control that triggers postback, this variable is used to store ID/Name of that control. And this variable gets passed on to server when FORM is submitted. ASP.Net framework looks at this variable to decide what event handler needs to be triggered.
Given that information, if you do not pass correct value of the control that triggers log in action, sending HttpWebRequest with just login credentials is not going to work at all. Because your request will go to server, and it will never reach the event handlers that handles click on that button. So when you are dealing with ASP.Net sites, check ID/Name of the button or control that user clicks to start login process. You will need to pass that ID/Name as additional FORM key-value pair in POST or GET request. Following code snippet shows that this is about.
reqAttribs.RequestParameters.Add("txtEmail", "xxxxxxxxx");
reqAttribs.RequestParameters.Add("txtPassword", "yyyyyyy");
reqAttribs.RequestParameters.Add("__EVENTTARGET", "btnSubmit");
Notice third request parameter that I added which is ID of input button control. Hope this information helps in understanding programatic login process for ASP.Net sites.
|
|
|
by Viper
21. March 2009 18:18
Long time ago I wrote an article Detect file type or mime type based on content. If you look at the XML file that contained magic signature of different file types, one of the type was MP3 files. And magic signature for MP3 files is that first 3 bytes of file content are ID3. The format of MP3 files is very well defined and explained at ID3.org. Although it is very well defined but it is not something very straight forward and not a job for faint heart to understand it.
For one of new development adventure I am tasked with digging little bit deep into file structure of MP3 files and find out some meta data. Things like Artist Name, Title, Track Number, Year Of Release etc. So I looked around the site and found reference to IDSharp library developed for .Net and is COM visible as well. So you can use it in any application that can invoke COM interfaces. The library is available on sourceforge. But there is no source code for the actual core library. It is only available as .Net assembly. I really needed source code for it because I was curious about implementation and I had to make some modifications as well for the kind of work I was doing.
So I fired up good old tool Reflector and dis-assembled the assembly to generate the source code for it. I had to fix few compile errors after disassembly. But finally I made it to work as expected. So I thought I will share the source code of IdSharp library with people who are interested in it.
Download Source Code For IdSharp Library
From the following code snippet you can see how you can load a MP3 file to get all information about the file. And then you can actually change ID3 tag information as well and save the file with new information. In the sample code, I changed the name of the artist as well as album name. You can see from the screen shot that it did work.
static void Main(string[] args)
{
var id3v2 = ID3v2Helper.CreateID3v2("Hello.mp3");
Console.WriteLine("Artist: {0}", id3v2.Artist);
Console.WriteLine("Title: {0}", id3v2.Title);
Console.WriteLine("Album: {0}", id3v2.Album);
Console.WriteLine("Genre: {0}", id3v2.Genre);
Console.WriteLine("Year: {0}", id3v2.Year);
Console.WriteLine("TrackNumber: {0}", id3v2.TrackNumber);
Console.WriteLine("Media Type: {0}", id3v2.MediaType);
Console.WriteLine("CD Identifier: {0}", id3v2.MusicCDIdentifier.TOC);
id3v2.Artist = "Byteblocks.com";
id3v2.Title = "ID3v2 Song";
id3v2.Save("Bytes.mp3");
}
|
|
|
by Viper
21. March 2009 05:45
Recently I was working on detection of MP3 file format when a user uploads a file to a web site. Part of the detection was to look for ID3 header and figuring out what flags were set in header. The format specification tells you at what bit locations to check for what flags. This meant that you will need some mechanism to figure out what bits are set with in a byte. If you are seasoned C/C++ developer, you pretty much know that this meant that doing some low level bit shift operations on that byte to rotate through them to check which bit is set and which is not set. So if you will write that code in C#, it will look like snippet below.
static void ConvertToBinaryFormat(byte n)
{
var flags = new BitArray(8);
var counter = 8;
var idx = 0;
while(counter > 0)
{
flags.Set(idx++, ((n & 1) == 1));
n >>= 1;
counter--;
}
PrintBitArray(flags);
}
static void PrintBitArray(BitArray ba)
{
Console.WriteLine();
for(int i = ba.Length-1; i >= 0; i--)
{
Console.Write("{0}", ba[i] ? 1 : 0);
}
}
Looking at the code, you are already saying that I have already used BitArray class object in this function. Then why am I doing all the low level operations. I intentionally introduced BitArray here to demonstrate that you really do not need to do all the low level operations to check what bits are set. BitArray class already does that for you. Following one line of code does the same thing that I did by doing some bit shifting.
var newFlags = new BitArray(new byte[] {20});
PrintBitArray(newFlags);
If you look at PrintBitArray method, you will notice that it is using reverse loop to print each bit. When bit shit operation is being done, bit array gets filled from right to left. This means that higher order bits get pushed low. And BitArray class does the same thing. So you will have to access the array from bottom.
|
|
|
1cd9fdea-05e6-4289-a9d4-7070e5d2585d|0|.0
Views: 3795
Tags: c#, bitarray
.Net | C#
by Viper
10. March 2009 15:07
Some time when you use Add Service Reference to add reference to your WCF service, you may run into error like:
The type 'ForExService.Service1', provided as the Service attribute value in the ServiceHost directive could not be found
This error is very self explanatory telling that some type could not be found. Well if that type is missing in my service, how did the tool know about it. Well this exactly is the cause of this error. The tool looks at .svc file. And it found the following line in markup.
ServiceHost Language="C#" Debug="true" Service="ForExService.Service1" CodeBehind="CurrencyService.svc.cs
You probably can see the problem in line above. The service type is set to "ForExService.Service1" where the code behind was modified to name the service classes differently. So if you run into this kind of error, make sure that you check mark up of your service file as well to make sure that it matches the implementation in code.
|
|
|
6e385778-ae79-4fa6-80bd-252047cd4893|0|.0
Views: 17004
Tags: wcf
.Net | WCF
by Viper
6. March 2009 06:05
Some time back I wrote an article on similar topic How to get IP address of a machine using C#. That article was written in days of .Net1.1. Since then .Net framework has come a long way. Some APIs were deprecated and a lot of new APIs were added. This post is an update on that old article. While I was working on a silverlight socket programming project, I had to deal with lot of Networking APIs. During that process I ended up writing a new method that returns me list of local IP addresses and presenting that to user to decide on what IP address they want to run socket server. Hope this post provides a quick coding tip on how you can get local IP address of your machine.
Private Function GetIPs() As StringCollection
Dim localIP = New StringCollection()
Dim localHostName = Dns.GetHostName()
Dim hostEntry = Dns.GetHostEntry(localHostName)
' Grab all ip addesses.
For Each ipAddr As IPAddress In hostEntry.AddressList
localIP.Add(ipAddr.ToString())
Next
GetIPs = localIP
End Function
Pardon my VB.Net code. I am not very intimate with this language. You can find C# code at old article location
|
|
|
by Viper
5. March 2009 12:10
Well this was some question that somebody asked in forums. Well I thought i will just do a quick implementation to show it is done. Here is the use case. You have a text string my leader is not here and leaders of leader1 are gone as well but sleaders not. And you need to find all instances in the string where word leader appears. Just finding if word leader appears or not is simple. You can use IndexOf method to quickly find it. But requirement is that you want to find all occurances with complete word. So for your search of leader should return me list leader,leaders,leader1,sleaders. I just extended the original problem statement to include sleaders meaning that I want to find word even if search word leader is not at the start of the word.
The solution is simple and requires use of RegularExpressions. See the following code snippet.
private static StringCollection FindText(string src, string keyword, bool atStart)
{
StringCollection results = new StringCollection();
string pattern = string.Empty;
if (atStart)
{
pattern = "(" + keyword + ")(?<1>\\w*)";
}
else
{
pattern = "(\\w*)" + "(" + keyword + ")(?<1>\\w*)";
}
MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(src, pattern);
foreach(Match m in matches)
{
results.Add(m.ToString());
Console.WriteLine(m.ToString());
foreach(Group gp in m.Groups)
{
Console.WriteLine(gp);
foreach(Capture c in gp.Captures)
{
Console.WriteLine(c.ToString());
}
}
}
return results;
}
There is lot of noise in the code with all Console.WriteLine statements.But that is all to show what matches, groups and captures are being done by the regular expression. Third parameter of this method controls the pattern. If you set to true, that would mean that you are only interested in result of the search string appears at start of the word. If you will set it to false, it will find the search string anywhere in a word.
|
|
|
by Viper
2. March 2009 06:02
Last week I received an email from one of my clients asking for latest help documentation for HTMLParser.Net library. Then I realized it has been couple of years since I updated documentation for that library. I used to use NDoc for generating help files. Since .Net2.0 that project has been abandoned. And then Microsoft introduced Sandcastle project. Initially it was buggy to the extent that it used to crash all the time when I generated documentation for my library. So I kind of abandoned it. Last night I went back to Sandcastle site and was glad that the project is still alive is being updated regularly. So I decided to give it a try. Well it still has some bugs and still crashed on my library. But this time I was able to follow the error stack trace and figure out what area may be giving it trouble. It turned out that my XML comments had some text that was colliding with some XML reserved keywords. After removed that, it worked like a charm. So if you are thinking of generating help file for your .Net class library, here are some simple steps that you can follow:
- Install Sandcastle. This is framework for generating help files.
- Install Sandcastle Help File Builder. This is GUI application that is very much like NDoc.
- Compile you .Net class library project with XML documentation option turned on.
- Launch Help File Builder application and add your assembly file and related XML file to documentation resources node.
- Build help file
If you have any questions about usage feel free to drop me a line.
|
|
|
by Viper
27. February 2009 20:51
If you are using some Content Management System (CMS) for your web site, then there is good chance that all your content along with meta tag content like Title, Description, Keywords etc. is stored in some data source and need to be added to the page dynamically. This all is doable from server side using HtmlMeta html server side control to Controls collection of Header of your page. You just need to add head element to your page and make sure that you have set runat=server for it and you are good to go. See the following snippet how it is done.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.Header.Title = "My Page Title";
HtmlMeta meta = new HtmlMeta();
meta.Content = "my description for this page";
meta.Name = "description";
this.Header.Controls.Add(meta);
}
}
And on the page I have defined the mark up like this.
<head runat="server">
<title></title>
</head>
bac6127f-edea-480a-985e-4971a845df94|0|.0
Views: 1652
Tags:
.Net | ASP.Net | SEO
by Viper
24. February 2009 06:38
Auto implemented properties are wonderful thins and save lot of coding and declaration in most of the situations. So a simple auto implemented property will look like as below.
public string Title
{get; set;}
No need to define a private variable to store the value. In some cases you want your property to be immutable meaning you don't want clients to be able to change the value and only allow private or internal access to the setter of this property. The specification of auto implemented properties says that you have to provide both get and set accessors. This does not mean that you have to provide public accessors for both. You can always provide private or inernal accessor for get.
public string Title
{get; internal set;}
9ef4827c-45dd-4d5d-abf3-779cbb4baba4|0|.0
Views: 828
Tags: c#, .net
.Net | CSharp
by Viper
20. February 2009 15:59
While working on a Silverlight project, I had to do JSON serialization and deserialization of my data objects. I was using DataContractJsonSerializer object to perform serialization. One thing I had to do consistently was to convert serialized objects in stream to string. So in that process I wrote a tiny method. So I thought I will share it here.
private string ConvertMemoryStreamToString(MemoryStream ms)
{
ms.Seek(0, SeekOrigin.Begin);
byte[] jsonBytes = new byte[ms.Length];
ms.Read(jsonBytes, 0, (int)ms.Length);
return Encoding.UTF8.GetString(jsonBytes);
}
by Viper
28. January 2009 12:26
While developing a custom control I discovered a very important thing related to how all key value pairs in FORM on a page get named and added. I had a hidden input field added to the page. I was only setting ID of the control but was not specifying the name attribute for it. On PostBack i was not getting my field back. May be I was but i did not see any key named as "name" that I specified for the control. Then I set "name" attribute for the control, and I was able to get the value set in that hidden input field back during post back.
HtmlGenericControl selectedObjField = new HtmlGenericControl("input");
selectedObjField .Attributes.Add("type", "hidden");
selectedObjField .Attributes.Add("id", "_selected_cms_list");
selectedObjField .Attributes.Add("name", "_selected_objs_list");
mainPanel.Controls.Add(selectedObjField );
if (this.Page.IsPostBack)
{
string selectedCMs = this.Page.Request["_selected_objs_list"];
if (!string.IsNullOrEmpty(selectedCMs))
{}
}
|
|
|
31ef03c9-076c-4275-9787-4ac1f57895bf|0|.0
Views: 1170
Tags:
.Net | ASP.Net
by Viper
22. January 2009 17:18
A lot of times when you working on some redistributable commercial libraries or applications, you like to strong name your assembly. The key to generating strong name assembly is signing your assembly with a strong name key. It is very easy to generate this key. I will outline simple steps to generate your key quickly.
|
|
|
243a2153-7a67-44e4-90ad-d293076c396b|0|.0
Views: 693
Tags: .net
.Net
Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli
|
|