Archive
XML to strongly typed object in C#
Assume you have composite XML and you want read the XML field values in your C# project, the simplest way is to convert in to Strongly type object and read as parameters.
It involves two steps as mentioned below
Generate XML Wrapper Class
- “Fruits.xml” is your XML file.
- Copy the XML file content.
- Open a new Class file “FruitsWrapper.cs” in Visual Studio 2012
- Select “EDIT -> Paste Special -> Paste XML As Classes”
- Now you get XML wrapper class on your Class file
- Save the file
Convert XML to Class
- To test the Conversion and read the XML data
- Take a console application and paste below code
static void Main(string[] args){
const string fruitsXmlPath = @”c:\Fruits.xml”;
// Set your Root Element Name (i.e., <Fruits> is the root node of our XML)
var xRoot = new XmlRootAttribute { ElementName = “Fruits”, IsNullable = true };
var xmlSerializer = new XmlSerializer(typeof(Fruits), xRoot);
var fruits = (Fruits)xmlSerializer.Deserialize(new FileStream(fruitsXmlPath, FileMode.Open));
// Read XML node values as Object Properties
Console.WriteLine(“Fruit Name” + fruits.CitrusFruits.Fruit.Name);
Console.WriteLine(“Fruit Price” + fruits.CitrusFruits.Fruit.Price);
}
This approach is useful when you have your application’s configuration details provided in an XML file and if the file is complex and big.
Note – If you don’t have “Paste Special -> Paste XML As Classes” feature in your Visual Studio, you can use XSD.exe tool to generate wrapper class from XML.
Unable to uninstall windows service; Service status is disabled
I was trying to uninstall my windows service using cmd>installutil \u ‘sevice.exe’.
But the service is not uninstalling and showing status as ‘Disabled’ in ‘Service Manager’ (Run -> Services.msc).
Also when I try to install the same service again, I was getting “The specified service has been marked for deletion” message.
Fix –
- Make sure you close “Services Manager” (Services.msc) before Install or Uninstall your windows service.
🙂
Reflection with method overloading C#
I have a class with 3 overloaded methods and when try to invoke method’s using Reflection, I was getting “Avoiding an ambiguous match exception” exception.
Below is the way to invoke overload methods using Reflection, which solved my exception.
Let’s take a class with 3 overload methods.
Class Structure
namespace MyNamespace{
public class CallMe{
public string MyName(){
return “You don’t have name”;
}
public string MyName(string firstName){
return “Your name is ” + firstName;
}
public string MyName(string firstName, string lastName){
return “Your name is ” + firstName + lastName;
}
}
Here is the way to invoke methods using Reflection
C# Code to call the Generic Method
// Load .dll
Assembly assembly = Assembly.LoadFile(“{Physical path of }MyNamespace.dll”);
// Set the Class type as “Namespace.Classname”
Type classType = assembly.GetType(“ReflectionClass.CallMe”);
// One of my methods expects 1 string hence creating MethodInfo object with 1 Type[] parameter
MethodInfo methodWithOneParameter = classType.GetMethod(“MyName”, new Type[] { typeof(string) });
// One of my methods expect 2 string parameters hence creating MethodInfo object with 2 Type[] parameters.
MethodInfo methodWithTwoParameter = classType.GetMethod(“MyName”, new Type[] { typeof(string), typeof(string) });
// To invoke overload with no parameters, provide an empty Type array to GetMethod’s second parameter
MethodInfo methodWithNoParameter = classType.GetMethod(“MyName”, new Type[0]);
// Invoke Methods
var resultMethodWithOneParameter = InvokeMethod(classType, methodWithOneParameter, new string[] { “Rajeev” });
var resultMethodWithTwoParameter = InvokeMethod(classType, methodWithTwoParameter, new string[] { “Rajeev”, “Pentyala” });
var resultMethodWithNoParameter = InvokeMethod(classType, methodWithNoParameter, null);
// Display Results
Console.WriteLine(“ResultMethodWithOneParameter – ” + resultMethodWithOneParameter.ToString());
Console.WriteLine(“ResultMethodWithTwoParameter – ” + resultMethodWithTwoParameter.ToString());
Console.WriteLine(“ResultMethodWithNoParameter – ” + resultMethodWithNoParameter.ToString());
C# Generic Method to Invoke methods
// Generic method Invokes methods and return Result as Object
public static object InvokeMethod(Type classType, MethodInfo methodInfo, object[] parametersArray){
object result = null;
if (classType != null) {
if (methodInfo != null) {
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(classType, null);
if (parameters.Length == 0) {
//This works fine
result = methodInfo.Invoke(classInstance, null);
}
else {
//The invoke does NOT work it throws “Object does not match target type”
result = methodInfo.Invoke(classInstance, parametersArray);
}
}
}
return result;
}
We get the response as below
🙂
Separating alphabets and digits from Alphanumeric string– C#
We got a requirement to separate alphabets and digits from alphanumeric string as groups.
Let’s say my alphanumeric string is “Hel00Wor11DD” and I need to get
- Alphabet group as “Hel,Wor,DD”
- Digit group as “00,11”.
Below is the C# code which use Regular expressions and achieve the same
var digitGroup = newList<string>();
var alphabetGroup = newList<string>();
Match regexMatch = null;
string myString = “Hel00Wor11DD”;
while (myString.Length > 0){
if ((regexMatch = Regex.Match(myString, “\\d”)).Success){
// If myString is not starting with digit
if (regexMatch.Index > 0) {
alphabetGroup.Add(myString.Substring(0, regexMatch.Index));
}
// If myString is starting with digits but has subsequent alphabets
elseif ((regexMatch = Regex.Match(myString, “\\D”)).Success) {
digitGroup.Add(myString.Substring(0, regexMatch.Index));
}
// If myString only has digits, no more alphabets
else{
digitGroup.Add(myString.Substring(0));
// No more alphabets
break;
}
myString = myString.Substring(regexMatch.Index);
}
// There are no digits in myString
else{
alphabetGroup.Add(myString);
// No more digits
break;
}
}
When you run above code, you would get Alphabets & Digits separated as Lists.
🙂
SQL query to split a string separated by Comma (or any special character)
Assume that you have a String with Comma separated value and wanted to split and get the collection in SQL.
My string looks ‘A,B,C,D, ‘ and I want output as
Value
A
B
C
D
Approach
The approach I am following here is
- Declare a Temporary table
- Split the string
- Insert the split values in to Temporary table
Query
DECLARE @MyValuevarchar(100)
DECLARE @posINT
DECLARE @lenINT
DECLARE @valuevarchar(8000)
SET @pos= 0
SET @len= 0
— Set the Comma separated value
SET @MyValue=‘A,B,C,D,’
— Declare Temporary Table to store split values
DECLARE @MyTempTbl TABLE (
[Value] [nvarchar](100)
)
WHILE CHARINDEX(‘,’,@MyValue,@pos+1)>0
BEGIN
SET @len=CHARINDEX(‘,’,@MyValue,@pos+1)–@pos
SET @value=SUBSTRING(@MyValue,@pos,@len)
— Insert the splitter value in to Temporary Table
INSERT INTO @MyTempTbl Values(@value)
SET @pos=CHARINDEX(‘,’,@MyValue,@pos+@len)+1
END
— Get the resultset
SELECT * FROM @MyTempTbl
Output you get as below
Note –
- My requirement was to split the string and use in ‘IN’ condition, hence I created a Temporary table.
- Also you can replace ‘,’ with any of the character
🙂
GUID generator website
How many times you were in a situation, where you need a GUID to test your .Net application or fill a ‘uniqueidentifier’ column of SQL table.
I found this GUID generator site very helpful.
You just need to refresh the web page to get a new GUID every time.
Not only this, this site will give you as many as GUID’s you want at a time and also has GUID validation option.
Try it your self 🙂
CRM Developer Toolkit for Visual Studio 2013
There is no release of CRM Developer Toolkit for VS 2013.
However by hacking the CRM Developer toolkit for VS 2012 we can get Developer Toolkit work for VS 2013.
Refer steps mentioned in this article.
🙂