I like to share a website I frequently use to format any code (C#, XML or T-SQL) to HTML for using on my blog. Other possibilities are to format VB, HTML or msh, but I haven't used these myself yet.
You can also add things like line numbers, or use alternating backgrounds. And to modify the colors of the output, you'll just need to change the css style sheet.
Also because everytime I need it, I'll have to search the website again on google. So this way I'll save some time for me too :).
Here's the link: http://www.manoli.net/csharpformat/
Posts tonen met het label C#. Alle posts tonen
Posts tonen met het label C#. Alle posts tonen
woensdag 5 september 2012
Formatting code to HTML
Labels:
C#,
handy tool,
HTML,
Script,
SQL,
Tips/Tricks,
XML,
XSLT
vrijdag 31 augustus 2012
Using System Colors in C#
When choosing a color in the properties window in visual studio, there is the possibility to choose from so called System Colors. An example for this is the color 'Window', which is the default for a textbox.
Now, I tried to set the BackColor of a Textbox programmatically back to this system color 'Window'. Turned out not to be as easy as I thought it would be.
I tried things like Color.? ... I hoped to find the color in this namespace, or even a System subsection for the systemcolors. Nothing to be found however.
Nor was there any namespace like System.Color to be found.
But how can these system colors be set from C# code than?
Well, one way turned to be using this command:
System.Drawing.Color.FromKnownColor(KnownColor.Window)
And, as you'd expect, the KnownColor enumeration contains all of the other user-definable colors.
Or even an easier method to achieve this is
System.Drawing.SystemColors.Window
Now, I tried to set the BackColor of a Textbox programmatically back to this system color 'Window'. Turned out not to be as easy as I thought it would be.
I tried things like Color.? ... I hoped to find the color in this namespace, or even a System subsection for the systemcolors. Nothing to be found however.
Nor was there any namespace like System.Color to be found.
But how can these system colors be set from C# code than?
Well, one way turned to be using this command:
System.Drawing.Color.FromKnownColor(KnownColor.Window)
And, as you'd expect, the KnownColor enumeration contains all of the other user-definable colors.
Or even an easier method to achieve this is
System.Drawing.SystemColors.Window
donderdag 19 juli 2012
Difference between 2 dates in C#
I tried to do a simple DateTime calculation in C#. What I wanted to achieve is to know how many years, months and days where between 2 DateTime variables. Or at least I thought this would be easy. Turns out there is know real out-of-the-box functionality available to handle this in C#.
The only thing available out-of-the-box in C# is using TimeSpan. Unfortuanately the only calculations TimeSpan can return is the number of days, hours, minutes, seconds and milliseconds. But how about the years, months and days than?
Here's a simple method to show the possibilities of the TimeSpan:
I ended up using a freely available .NET library called 'Time Period'. The source code can be found here. There's also an on line demo and documentation available.
Here's a simple method to show some the possibilities of the TimeSpan:
There are much more possibilities in the DateDiff class of the Time Period library. There are even much more classes available in the library. To know more of the capabilities of this library I again refer to the documentation.
Source: http://www.itenso.com/en/
The only thing available out-of-the-box in C# is using TimeSpan. Unfortuanately the only calculations TimeSpan can return is the number of days, hours, minutes, seconds and milliseconds. But how about the years, months and days than?
Here's a simple method to show the possibilities of the TimeSpan:
public void PrintDateDiffUsingTimeSpan(DateTime begin, DateTime end) { TimeSpan span = end - begin; StringBuilder str = new StringBuilder(); str.Append("Total span: "); str.Append(span.Days + " days, "); str.Append(span.Hours + " hours, "); str.Append(span.Minutes + " minutes, "); str.Append(span.Seconds + " seconds, "); str.Append(span.Milliseconds + " milliseconds"); Console.WriteLine(str.ToString() + "\n"); Console.WriteLine("Total Days: " + span.TotalDays); Console.WriteLine("Total Hours: " + span.TotalHours); Console.WriteLine("Total Minutes: " + span.TotalMinutes); Console.WriteLine("Total Seconds: " + span.TotalSeconds); Console.WriteLine("Total Milliseconds: " + span.TotalMilliseconds); }
I ended up using a freely available .NET library called 'Time Period'. The source code can be found here. There's also an on line demo and documentation available.
Here's a simple method to show some the possibilities of the TimeSpan:
public void PrintDateDiff(DateTime begin, DateTime end)
{
DateDiff diff = new DateDiff(begin, end);
StringBuilder str = new StringBuilder();
str.Append("Total difference: ");
str.Append(diff.ElapsedYears + " years, ");
str.Append(diff.ElapsedMonths + " months, ");
str.Append(diff.ElapsedDays + " days");
Console.WriteLine(str.ToString() + "\n");
Console.WriteLine("Total Days: " + diff.Days);
Console.WriteLine("Total Weeks: " + diff.Weeks);
Console.WriteLine("Total Weekdays: " + diff.Weekdays);
Console.WriteLine("Total Quarters: " + diff.Quarters);
Console.WriteLine("Total Hours: " + diff.Hours);
}
There are much more possibilities in the DateDiff class of the Time Period library. There are even much more classes available in the library. To know more of the capabilities of this library I again refer to the documentation.
Source: http://www.itenso.com/en/
woensdag 9 november 2011
Some neat tools for Biztalk / .NET developers
I bundled some handy free tools to help you develop and / or debug your (BizTalk) applications.
soapUI
soapUI is a free and open source cross-platform Functional Testing solution, a tool for SOA testing.
soapUI allows you to easily and rapidly create and execute automated functional, regression, compliance, and load tests. In a single test environment, soapUI provides complete test coverage and supports all the standard protocols and technologies.
http://www.eviware.com/soapUI/soapui-products-overview.html
linqpad
LINQPad lets you interactively query databases in a modern query language: LINQ.
LINQPad supports everything in C# 4.0 and Framework 4.0:
http://www.linqpad.net/
testdriven.net
TestDriven.Net makes it easy to run unit tests with a single click, anywhere in your Visual Studio solutions. It supports all versions of Microsoft Visual Studio and it integrates with the best .NET development tools.
http://www.testdriven.net/
ssmstoolspack
SSMS Tools Pack is an add-in for Microsoft SQL Server Management Studio. It contains a few upgrades to the SSMS IDE
http://www.ssmstoolspack.com/
deployment framework for biztalk
The Deployment Framework for BizTalk eliminates the pain associated with BizTalk application deployments, and goes far beyond BizTalk’s out-of-the-box deployment functionality. It also includes additional tools to enhance developer productivity, such as binding file management.
http://biztalkdeployment.codeplex.com/
biztalkcop
A set of FxCop rules for enforcing coding standards on BizTalk projects. First release includes configurable naming rules based on Scott Colestock's published conventions.
http://biztalkcop.codeplex.com/
smsniff
SmartSniff is a network monitoring utility that allows you to capture TCP/IP packets that pass through your network adapter, and view the captured data as sequence of conversations between clients and servers.
http://www.nirsoft.net/utils/smsniff.html
bizunit
BizUnit is a flexible and extensible declarative test framework targeted that rapidly enables the automated testing of distributed systems, for example it is widely used to test BizTalk solutions. BizUnit is fully extensible. Its approach is to enable test cases to be constructed from generic reusable test steps, test cases are defined in XML which allows them to be auto-generated and also enables the ‘fixing up’ of Url’s for different environments, e.g. test, staging and production environments. Defining test cases in XML enables test cases to be auto-generated.
http://bizunit.codeplex.com/
resharper
ReSharper is a renowned productivity tool that makes Microsoft Visual Studio a much better IDE.
http://www.jetbrains.com/resharper/
dansharp xmlviewer
DanSharp XmlViewer is a lightweight XPath generation and testing tool, making it easy to generate and test XPath queries. It also allows for validation of Xml documents against schemas, display of Xml documents in tree-view format, and generation of BizUnit test cases.
http://dansharpxmlviewer.codeplex.com/
bts terminator
A tool which allows for common biztalk problems to be addressed by scripts provided by the biztalk team. Replaces terminate.vbs with more functionality including the ability to suspend, resume and terminate by date range. Powershell script functionality provided for performance tuning. Integration with mbvcleanupscripts.xml from the messagebox viewer utility
http://www.microsoft.com/download/en/details.aspx?id=2846
Guideline on biztalkadminsblogging.com
debugview
DebugView is an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It is capable of displaying both kernel-mode and Win32 debug output.
http://technet.microsoft.com/en-us/sysinternals/bb896647
msbuild explorer extension
The MSBuild Extension Pack provides a collection of over 400 MSBuild Tasks, MSBuild Loggers and MSBuild TaskFactories.
http://msbuildextensionpack.codeplex.com/
ilspy
ILSpy is the open-source .NET assembly browser and decompiler.
http://wiki.sharpdevelop.net/ILSpy.ashx
biztalk map documenter
The BizTalk Map Documenter stylesheet will transform a a BizTalk map into an HTML view containing the following information:
http://biztalkmapdoc.codeplex.com/
msxsl.exe
The msxsl.exe command line utility enables you to perform command line Extensible Stylesheet Language (XSL) transformations using the Microsoft XSL processor.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21714
Microsoft BizTalk LoadGen 2007
Microsoft LoadGen 2007 generates message transmission loads to run performance and stress tests for your Microsoft BizTalk Server applications, and provides performance counters to monitor the performance of the infrastructure running BizTalk Server.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=14925
BizTalk Server Best Practices Analyzer
he BizTalk Server Best Practices Analyzer V1.2 examines a BizTalk Server 2006, BizTalk Server 2006 R2, or BizTalk Server 2010 deployment and generates a list of issues pertaining to best practices standards for BizTalk Server deployments.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=15963
Performance Analysis of Logs (PAL)
The PAL (Performance Analysis of Logs) tool is a new and powerful tool that reads in a performance monitor counter log (any known format) and analyzes it using complex, but known thresholds (provided). The tool generates an HTML based report which graphically charts important performance counters and throws alerts when thresholds are exceeded.
http://pal.codeplex.com/
Log Parser 2.2
Log parser is a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows® operating system such as the Event Log, the Registry, the file system, and Active Directory.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=24659
Process Explorer
The unique capabilities of Process Explorer make it useful for tracking down DLL-version problems or handle leaks, and provide insight into the way Windows and applications work.
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Message Box Viewer
The goal of MBV is to retrieve the maximum amount of information from a BizTalk System in one click in the minimum amount of time, identify all possible issues which could be critical or need attention and present them in a user friendly format.
More info: http://blogs.technet.com/b/jpierauc/archive/2008/07/22/msgboxviewer-mbv-q-a.aspx%22
http://blogs.technet.com/b/jpierauc/archive/2007/12/18/msgboxviewer.aspx
TCP Trace
Used to monitor text based network traffic between client and server. Useful while using adapters like SOAP,HTTP,POP3 etc to see the message travelling via the wire.
http://www.pocketsoap.com/tcptrace/
DTCPing
This tool is designed to assist with troubleshooting Microsoft DTC Firewall Issues, which you'll often see in a multiserver BizTalk deployment.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=2868
BizTalk Message Decompressor
This tool enables you to decompress BizTalk messages/context from a screen that looks like SQL Query Analyzer.
http://btsdecompress.codeplex.com/
soapUI
soapUI is a free and open source cross-platform Functional Testing solution, a tool for SOA testing.
soapUI allows you to easily and rapidly create and execute automated functional, regression, compliance, and load tests. In a single test environment, soapUI provides complete test coverage and supports all the standard protocols and technologies.
http://www.eviware.com/soapUI/soapui-products-overview.html
linqpad
LINQPad lets you interactively query databases in a modern query language: LINQ.
LINQPad supports everything in C# 4.0 and Framework 4.0:
- LINQ to Objects
- LINQ to SQL and Entity Framework
- LINQ to XML
- Parallel LINQ
http://www.linqpad.net/
testdriven.net
TestDriven.Net makes it easy to run unit tests with a single click, anywhere in your Visual Studio solutions. It supports all versions of Microsoft Visual Studio and it integrates with the best .NET development tools.
http://www.testdriven.net/
ssmstoolspack
SSMS Tools Pack is an add-in for Microsoft SQL Server Management Studio. It contains a few upgrades to the SSMS IDE
http://www.ssmstoolspack.com/
deployment framework for biztalk
The Deployment Framework for BizTalk eliminates the pain associated with BizTalk application deployments, and goes far beyond BizTalk’s out-of-the-box deployment functionality. It also includes additional tools to enhance developer productivity, such as binding file management.
http://biztalkdeployment.codeplex.com/
biztalkcop
A set of FxCop rules for enforcing coding standards on BizTalk projects. First release includes configurable naming rules based on Scott Colestock's published conventions.
http://biztalkcop.codeplex.com/
smsniff
SmartSniff is a network monitoring utility that allows you to capture TCP/IP packets that pass through your network adapter, and view the captured data as sequence of conversations between clients and servers.
http://www.nirsoft.net/utils/smsniff.html
bizunit
BizUnit is a flexible and extensible declarative test framework targeted that rapidly enables the automated testing of distributed systems, for example it is widely used to test BizTalk solutions. BizUnit is fully extensible. Its approach is to enable test cases to be constructed from generic reusable test steps, test cases are defined in XML which allows them to be auto-generated and also enables the ‘fixing up’ of Url’s for different environments, e.g. test, staging and production environments. Defining test cases in XML enables test cases to be auto-generated.
http://bizunit.codeplex.com/
resharper
ReSharper is a renowned productivity tool that makes Microsoft Visual Studio a much better IDE.
http://www.jetbrains.com/resharper/
dansharp xmlviewer
DanSharp XmlViewer is a lightweight XPath generation and testing tool, making it easy to generate and test XPath queries. It also allows for validation of Xml documents against schemas, display of Xml documents in tree-view format, and generation of BizUnit test cases.
http://dansharpxmlviewer.codeplex.com/
bts terminator
A tool which allows for common biztalk problems to be addressed by scripts provided by the biztalk team. Replaces terminate.vbs with more functionality including the ability to suspend, resume and terminate by date range. Powershell script functionality provided for performance tuning. Integration with mbvcleanupscripts.xml from the messagebox viewer utility
http://www.microsoft.com/download/en/details.aspx?id=2846
Guideline on biztalkadminsblogging.com
debugview
DebugView is an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It is capable of displaying both kernel-mode and Win32 debug output.
http://technet.microsoft.com/en-us/sysinternals/bb896647
msbuild explorer extension
The MSBuild Extension Pack provides a collection of over 400 MSBuild Tasks, MSBuild Loggers and MSBuild TaskFactories.
http://msbuildextensionpack.codeplex.com/
ilspy
ILSpy is the open-source .NET assembly browser and decompiler.
http://wiki.sharpdevelop.net/ILSpy.ashx
biztalk map documenter
The BizTalk Map Documenter stylesheet will transform a a BizTalk map into an HTML view containing the following information:
- The node links between source and destination schemas.
- All functoids used in the map are displayed with their parameters.
- Chained functoids are displayed as nested “function” calls.
- Labels
- Constants
- For HL7 schemas where source and desitnation are the same message type, links between different nodes are highlighted.
http://biztalkmapdoc.codeplex.com/
msxsl.exe
The msxsl.exe command line utility enables you to perform command line Extensible Stylesheet Language (XSL) transformations using the Microsoft XSL processor.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21714
Microsoft BizTalk LoadGen 2007
Microsoft LoadGen 2007 generates message transmission loads to run performance and stress tests for your Microsoft BizTalk Server applications, and provides performance counters to monitor the performance of the infrastructure running BizTalk Server.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=14925
BizTalk Server Best Practices Analyzer
he BizTalk Server Best Practices Analyzer V1.2 examines a BizTalk Server 2006, BizTalk Server 2006 R2, or BizTalk Server 2010 deployment and generates a list of issues pertaining to best practices standards for BizTalk Server deployments.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=15963
Performance Analysis of Logs (PAL)
The PAL (Performance Analysis of Logs) tool is a new and powerful tool that reads in a performance monitor counter log (any known format) and analyzes it using complex, but known thresholds (provided). The tool generates an HTML based report which graphically charts important performance counters and throws alerts when thresholds are exceeded.
http://pal.codeplex.com/
Log Parser 2.2
Log parser is a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows® operating system such as the Event Log, the Registry, the file system, and Active Directory.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=24659
Process Explorer
The unique capabilities of Process Explorer make it useful for tracking down DLL-version problems or handle leaks, and provide insight into the way Windows and applications work.
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Message Box Viewer
The goal of MBV is to retrieve the maximum amount of information from a BizTalk System in one click in the minimum amount of time, identify all possible issues which could be critical or need attention and present them in a user friendly format.
More info: http://blogs.technet.com/b/jpierauc/archive/2008/07/22/msgboxviewer-mbv-q-a.aspx%22
http://blogs.technet.com/b/jpierauc/archive/2007/12/18/msgboxviewer.aspx
TCP Trace
Used to monitor text based network traffic between client and server. Useful while using adapters like SOAP,HTTP,POP3 etc to see the message travelling via the wire.
http://www.pocketsoap.com/tcptrace/
DTCPing
This tool is designed to assist with troubleshooting Microsoft DTC Firewall Issues, which you'll often see in a multiserver BizTalk deployment.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=2868
BizTalk Message Decompressor
This tool enables you to decompress BizTalk messages/context from a screen that looks like SQL Query Analyzer.
http://btsdecompress.codeplex.com/
Labels:
Biztalk,
Biztalk tool,
C#,
handy tool,
SQL,
Visual Studio,
XPATH,
XSD,
XSLT
donderdag 14 juli 2011
Microsoft Lightswitch coming on July 26
Microsoft’s LightSwitch to Launch on July 26. This program will give developers a simpler and faster way to create high-quality business applications for the desktop and the cloud. LightSwitch is a new addition to the Visual Studio family.
I've already been playing with Lightswitch some time ago + I've seen the presentation on Techdays 2011 in Belgium. The new Visual Studio addition definitely has some promising features, and is easy to use. It could get quite handy for some (smaller) projects.
Lightswitch makes sure you'll get a working program fast with pre-configured screen templates, prewritten code and other reusable components to handle routine application tasks, along with helpful step-by-step guidance.
And afterwards you can of course customize it all in Visual Basic .NET or C#. To finalize, you can deploy to the desktop, browser, or cloud to share your application with others more easily without the cumbersome installation processes.
More info: Lightswitch, a developers tool, will launch on July 26
Videos and tutorials: http://www.microsoft.com/visualstudio/en-us/lightswitch
maandag 14 maart 2011
BizTalk monitoring, PART 1: BTS services and configurations
For the monitoring of the BizTalk Server we've programmed a simple application that will send an email if a certain port or orchestration will be disabled... or even worse, when a BizTalk Service is stopped.
The configuration for the app is done in an external XML file.
Below is the code that is used to check the BTS status, the method will return a boolean that indicates if all is running or not.
the method to send an email is the following:
to read the configuration out of the XML file, we've programmed following in the constructor (all is read to private class variables:
and finally the created XML file:
Hope you enjoyed my post.
In my next blog I'll show you how to monitor the BizTalk Queue to receive an email with the error message of all suspended instances.
The configuration for the app is done in an external XML file.
Below is the code that is used to check the BTS status, the method will return a boolean that indicates if all is running or not.
1: /// <summary>
2: /// Checks the BizTalk Status for BTS Service, Orchestrations, Send Ports, Receive Locations
3: /// And send a mail on not running of any instance
4: /// </summary>
5: /// <returns>True if all is running</returns>
6: public Boolean CheckBTSStatus()
7: {8: //Constant Values
9: String ErrorMessage = " {0} '{1}' is {2}!<BR>";
10: String ErrorServicesHeader = "<FONT color=\"#C11B17\"><strong>CRITICAL ISSUE: BTS SERVICE IS STOPPED</strong></FONT><BR><BR>";
11: String ErrorReceiveLocationsHeader = "<BR><strong>WARNING: Receive Location issue(s)</strong><BR><BR>";
12: String ErrorSendportsHeader = "<BR><strong>WARNING: Send Port issue(s)</strong><BR><BR>";
13: String ErrorOrchestrationsHeader = "<BR><strong>WARNING: Orchestration issue(s)</strong><BR><BR>";
14: String MailSubject = "URGENT: BizTalk issue(s) on " + Dns.GetHostName();
15: 16: // separate ERROR StringBuilders
17: StringBuilder services = new StringBuilder();
18: StringBuilder sendports = new StringBuilder();
19: StringBuilder receiveLocations = new StringBuilder();
20: StringBuilder orchestrations = new StringBuilder();
21: Boolean allRunning = true;
22: 23: foreach (String service in BTSService)
24: {25: ServiceController sc = new ServiceController(service);
26: 27: if (sc.Status != ServiceControllerStatus.Running && sc.Status != ServiceControllerStatus.StartPending)
28: {29: services.AppendLine(String.Format(ErrorMessage, "Service", service, sc.Status));
30: allRunning = false;
31: } 32: } 33: 34: String connectionString = "Data Source=" + dBServer + ";Initial Catalog=" + dB + ";";
35: if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password))
36: connectionString += "User Id=" + userName + ";Password=" + password + ";";
37: else
38: connectionString += "Integrated Security=SSPI;";
39: 40: BtsCatalogExplorer catalog = new BtsCatalogExplorer();
41: catalog.ConnectionString = connectionString; 42: 43: foreach (Application app in catalog.Applications)
44: {45: if (app.Status != Status.Started && app.Status != Status.NotApplicable)
46: {47: foreach (SendPort send in app.SendPorts)
48: {49: if (send.Status != PortStatus.Started)
50: {51: sendports.AppendLine(String.Format(ErrorMessage, "Send Port", send.Name, send.Status == PortStatus.Bound ? "Unenlisted" : send.Status.ToString()));
52: allRunning = false;
53: } 54: }55: foreach (ReceivePort receive in app.ReceivePorts)
56: {57: foreach (ReceiveLocation location in receive.ReceiveLocations)
58: {59: if (!location.Enable)
60: {61: receiveLocations.AppendLine(String.Format(ErrorMessage, "Receive Location", location.Name, "Disabled"));
62: allRunning = false;
63: } 64: } 65: }66: foreach (BtsOrchestration orch in app.Orchestrations)
67: {68: if (orch.Status != OrchestrationStatus.Started)
69: {70: orchestrations.AppendLine(String.Format(ErrorMessage, "Orchestration", orch.FullName, orch.Status));
71: allRunning = false;
72: } 73: } 74: } 75: } 76: 77: if(!allRunning)
78: {79: if(!String.IsNullOrEmpty(services.ToString()))
80: services.Insert(0, ErrorServicesHeader);81: if (!String.IsNullOrEmpty(sendports.ToString()))
82: sendports.Insert(0, ErrorSendportsHeader);83: if (!String.IsNullOrEmpty(receiveLocations.ToString()))
84: receiveLocations.Insert(0, ErrorReceiveLocationsHeader);85: if (!String.IsNullOrEmpty(orchestrations.ToString()))
86: orchestrations.Insert(0, ErrorOrchestrationsHeader); 87: 88: String body = services.ToString() + receiveLocations.ToString() 89: + sendports.ToString() + orchestrations.ToString(); 90: 91: Helper.SendMail(body, MailSubject, sendMailAddress, receiveMailAddress, SMTP); 92: }93: return allRunning;
94: }the method to send an email is the following:
1: public static void SendMail(String body, String subject, String fromAddress, String toAddress, String SMTPAddress)
2: {3: MailMessage msg = new MailMessage(fromAddress, toAddress);
4: msg.IsBodyHtml = true;
5: msg.Body = body;6: //msg.From = new MailAddress(fromAddress);
7: msg.Subject = subject; 8: 9: System.Net.Mail.SmtpClient smtp = new SmtpClient(SMTPAddress);
10: smtp.Send(msg);11: //SmtpMail.SmtpServer = SMTPAddress;
12: //SmtpMail.Send(msg);
13: }to read the configuration out of the XML file, we've programmed following in the constructor (all is read to private class variables:
1: private string dBServer;
2: private string dB;
3: private string userName;
4: private string password;
5: 6: private List<string> BTSService;
7: 8: private string sendMailAddress;
9: private string receiveMailAddress;
10: private string SMTP;
11: 12: public Monitor()
13: {14: XmlDocument config = new XmlDocument();
15: config.Load(System.IO.Directory.GetCurrentDirectory() + "/BTSMonitorConfiguration.xml");
16: 17: try
18: {19: dBServer = config.SelectSingleNode("CONFIGURATION/DBSETTINGS/Server").InnerText;
20: dB = config.SelectSingleNode("CONFIGURATION/DBSETTINGS/DB").InnerText;
21: userName = config.SelectSingleNode("CONFIGURATION/DBSETTINGS/UserName") == null ?
22: "" : config.SelectSingleNode("CONFIGURATION/DBSETTINGS/UserName").InnerText;
23: password = config.SelectSingleNode("CONFIGURATION/DBSETTINGS/Password") == null ?
24: "" : config.SelectSingleNode("CONFIGURATION/DBSETTINGS/Password").InnerText;
25: 26: BTSService = new List<string>();
27: 28: foreach(XmlNode service in config.SelectNodes("CONFIGURATION/BTSSETTINGS/BTSSERVICES/BTSServiceName"))
29: { 30: BTSService.Add(service.InnerText); 31: } 32: 33: sendMailAddress = config.SelectSingleNode("CONFIGURATION/MAILSETTINGS/From").InnerText;
34: receiveMailAddress = config.SelectSingleNode("CONFIGURATION/MAILSETTINGS/To").InnerText;
35: SMTP = config.SelectSingleNode("CONFIGURATION/MAILSETTINGS/SMTP").InnerText;
36: }37: catch (Exception e)
38: {39: StringBuilder error = new StringBuilder();
40: error.AppendLine("not all necessary data to perform the action is provided.");
41: error.AppendLine("Make sure these fields are correctly filled in in the XML File:");
42: error.AppendLine("\tDBServer (server name)");
43: error.AppendLine("\tDB (Database)");
44: error.AppendLine("\tBTSServiceName (BTS Service Name)");
45: error.AppendLine("\tFrom (sending mail address)");
46: error.AppendLine("\tTo (receiveing mail address)");
47: error.AppendLine("\tSMTP (SMTP host address)");
48: throw (new Exception(error.ToString()));
49: } 50: }and finally the created XML file:
<?xml version="1.0" encoding="utf-8" ?> <CONFIGURATION> <DBSETTINGS> <Server>.</Server> <!-- Server Name --> <DB>BizTalkMgmtDb</DB> <!-- DataBase Name --> <!--<UserName>user</UserName>--> <!-- optional --> <!--<Password>password</Password>--> <!-- optional --> </DBSETTINGS> <BTSSETTINGS> <BTSSERVICES> <BTSServiceName>BizTalk Service BizTalk Group : BizTalkServerApplication</BTSServiceName> <!-- BTS Service Name --> <BTSServiceName>BizTalk Service BizTalk Group : BizTalkServerApplication2</BTSServiceName> <!-- BTS Service Name --> </BTSSERVICES> </BTSSETTINGS> <MAILSETTINGS> <From>from@company.com</From> <To>to@company.com</To> <SMTP>smtp.company.com</SMTP> </MAILSETTINGS> </CONFIGURATION>
Hope you enjoyed my post.
In my next blog I'll show you how to monitor the BizTalk Queue to receive an email with the error message of all suspended instances.
dinsdag 18 januari 2011
GAC assemblies with right-click
As a developer you'll often need to place an assembly into the GAC (Global Assemblie Cache).
There are several ways to do this. You can do it in command line with "gacutil -if 'assembly path'" or by dragging your assembly in explorer to "C:\Windows\assembly".
Well there is another even easier way to do this. By just adding a registry key, you can place an assembly into the GAC with a simple right-click, as you can see below.
br /> To achieve this you'll need to create the registry key.
This can be done by copying following code to notepad, and save it with the .reg extension. Now double-click the created .reg file to add the registry key.
That's it!
You can also change the shown text when you right-click by changing the 'GAC-It' (written in red) to the desired text.
*****************************************************************
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\dllfile\shell\GAC-It\command]
@="C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\NETFX 4.0 Tools\\gacutil.exe /if \"%1\""
*****************************************************************
By specifying the '/if', I choose to install an assembly into the global assembly cache. If an assembly with the same name already exists in the global assembly cache, the tool overwrites it.
(other possible parameters can be found here).
ATTENTION: the path to the gacutil.exe may be different on your pc. I've installed it on a 64-bit machine. you should verify the actual path of your gacutil.exe (may occur multiple times on your pc).
Source: http://biztalkia.blogspot.com/2005/12/easier-way-to-add-dll-to-gac.html
There are several ways to do this. You can do it in command line with "gacutil -if 'assembly path'" or by dragging your assembly in explorer to "C:\Windows\assembly".
Well there is another even easier way to do this. By just adding a registry key, you can place an assembly into the GAC with a simple right-click, as you can see below.
br /> To achieve this you'll need to create the registry key.
This can be done by copying following code to notepad, and save it with the .reg extension. Now double-click the created .reg file to add the registry key.
That's it!
You can also change the shown text when you right-click by changing the 'GAC-It' (written in red) to the desired text.
*****************************************************************
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\dllfile\shell\GAC-It\command]
@="C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\NETFX 4.0 Tools\\gacutil.exe /if \"%1\""
*****************************************************************
By specifying the '/if', I choose to install an assembly into the global assembly cache. If an assembly with the same name already exists in the global assembly cache, the tool overwrites it.
(other possible parameters can be found here).
ATTENTION: the path to the gacutil.exe may be different on your pc. I've installed it on a 64-bit machine. you should verify the actual path of your gacutil.exe (may occur multiple times on your pc).
Source: http://biztalkia.blogspot.com/2005/12/easier-way-to-add-dll-to-gac.html
vrijdag 7 januari 2011
Inserting / updating SQL from C#
Creating an SQL string in C# is a poor way to do it. It might give problems with some special characters, even the data retrieved from SQL to C# might not be the exact same anymore.
You really want to bind your parameters. It prevents SQL attacks, and makes the query run faster.
Here's a simple piece of code as an example:
You really want to bind your parameters. It prevents SQL attacks, and makes the query run faster.
Here's a simple piece of code as an example:
1: // we'll assume there's a connection set up in the instance
2: 3: // pass a value
4: public void updateLog(string msg) {
5: // create your command, not the @msg where the parameter will go
6: SqlCommand cmd = 7: new SqlCommand("insert into log(msg) values (@msg)", this.conn);
8: 9: // bind the value to the parameter reference
10: cmd.Parameters.AddWithValue("@msg", msg); 11: 12: // fire
13: try {
14: cmd.Connection.Open(); 15: cmd.ExecuteNonQuery();16: } finally {
17: cmd.Connection.Close(); 18: } 19: }Converting DatetTime from and to Custom String format
Converting from String to DateTime
Using Convert.ToDateTime method might give you the error 'String was not recognized as a valid DateTime'.
Following code for example will result in an error:
You can simply do the conversion by defining the dateTime format yourself as follows:
Converting from DateTime to String
To convert a DateTime to String is even easier, just use following code:
NOTE:
for an overview of all possible DateTime formats, I'll refer to http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
Using Convert.ToDateTime method might give you the error 'String was not recognized as a valid DateTime'.
Following code for example will result in an error:
DateTime dt = Convert.ToDateTime("20100228");You can simply do the conversion by defining the dateTime format yourself as follows:
DateTime dt = DateTime.ParseExact("20100228", "yyyyMMdd", new System.Globalization.DateTimeFormatInfo())
Converting from DateTime to String
To convert a DateTime to String is even easier, just use following code:
dt.ToString("yyyy-MM-dd HH:mm:ss.ss");NOTE:
for an overview of all possible DateTime formats, I'll refer to http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
dinsdag 4 januari 2011
Compress and Decompress Strings with C#
To reduce the data size in our SQL tables we compress the full received message for all messages older than 90 days.
To accomplish this I use a compression and a decompression function in C#.
I've come up with 2 different solutions.
One will use the System.IO.Compression namespace, while the other uses an external referenced library, namely SharpZipLib.
First I'll show you how you can do this by just using the build in .NET functions.
the function to decompress the String looks like this:
The Decompression will be done by following funtion:
Another way to solve this is by using the SharpZipLib Library, which can be found here.
This will result in following methods:
Conclusion:
The second method, with the SharpZipLib library, results in a better compression than the first solution. So by using SharpZipLib you'll get the lowest data size for the resulting compressed string.
To accomplish this I use a compression and a decompression function in C#.
I've come up with 2 different solutions.
One will use the System.IO.Compression namespace, while the other uses an external referenced library, namely SharpZipLib.
First I'll show you how you can do this by just using the build in .NET functions.
the function to decompress the String looks like this:
public static string Zip(string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } ms.Close(); sw.Dispose(); ms.Dispose(); return sB.ToString(); } |
The Decompression will be done by following funtion:
public static string DecompressData(string sData) { byte[] byteArray = new byte[sData.Length]; int indexBa = 0; foreach (char item in sData) byteArray[indexBa++] = (byte)item; MemoryStream memoryStream = new MemoryStream(byteArray); GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress); byteArray = new byte[1024]; StringBuilder stringBuilder = new StringBuilder(); ;int readBytes; while ((readBytes = gZipStream.Read(byteArray, 0,byteArray.Length)) != 0) { for (int i = 0; i < readBytes; i++) stringBuilder.Append((char)byteArray[i]); } gZipStream.Close(); memoryStream.Close(); gZipStream.Dispose(); memoryStream.Dispose(); return stringBuilder.ToString(); } |
Another way to solve this is by using the SharpZipLib Library, which can be found here.
This will result in following methods:
private static string Compress(string strInput) { try { byte[] bytData = System.Text.Encoding.UTF8.GetBytes(strInput); MemoryStream ms = new MemoryStream(); Stream s = new DeflaterOutputStream(ms); s.Write(bytData, 0, bytData.Length); s.Close(); byte[] compressedData = (byte[])ms.ToArray(); return ConvertByteToString(compressedData); } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } private static string DeCompress(string strInput) { byte[] bytInput = ConvertStringToByte(strInput); string strResult = ""; int totalLength = 0; byte[] writeData = new byte[4096]; Stream s2 = new InflaterInputStream(new MemoryStream(bytInput)); try { while (true) { int size = s2.Read(writeData, 0, writeData.Length); if (size > 0) { totalLength += size; strResult += System.Text.Encoding.ASCII.GetString(writeData, 0, size); } else { break; } } s2.Close(); return strResult; } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } } private static byte[] ConvertStringToByte(string strInput) { byte[] byteArray = new byte[strInput.Length]; int indexBa = 0; foreach (char item in strInput) byteArray[indexBa++] = (byte)item; return byteArray; } private static string ConvertByteToString(byte[] compressedData) { System.Text.StringBuilder sB = new System.Text.StringBuilder(compressedData.Length); foreach (byte item in compressedData) { sB.Append((char)item); } return sB.ToString(); } |
Conclusion:
The second method, with the SharpZipLib library, results in a better compression than the first solution. So by using SharpZipLib you'll get the lowest data size for the resulting compressed string.
dinsdag 14 december 2010
Replace multiple spaces by a single space
We had a problem with multiple spaces in the messages received from another party.
I'll provide you an answer to handle this problem in XSLT as well as for C#.
I'll start by explaining it for XSLT.
In this case it is really simple, there exists an XSLT function to do this for u. Simply make a call to the function 'normalize-space()', and that's it!
normalize-space will remove all leading and trailing spaces to the string you pass to it. And above this, it will also replace all multiple spaces with a single space. It is that easy.
for example:
<node>
<value-of select="normalize-space(RootNode/SubNode/AnotherSubNode)" />
</node>
In C# there is no build-in solution for this problem, at least none that I'm aware of.
I solved this by writing a simple function, as follows:
public String RemoveMultipleSpaces(String phrase)
{
phrase = phrase.Trim();
phrase = System.Text.RegularExpressions.Regex.Replace(phrase, "\\s+", " ");
return phrase;
}
This functions exists of 2 steps. First of all I'll remove all leading and trailing spaces in the string.
Then I replace all remaining multiple spaces by a single space. To do this I use the Regex.Replace(String, String, String) function. The first parameter is just the String that needs to be changed. The second parameter represents a regalur expression of the pattern that needs to be replaced, in this case its mulitple spaces. And finally, the last parameter is the single space that will replace all matching substrings inside the original string.
I'll provide you an answer to handle this problem in XSLT as well as for C#.
I'll start by explaining it for XSLT.
In this case it is really simple, there exists an XSLT function to do this for u. Simply make a call to the function 'normalize-space()', and that's it!
normalize-space will remove all leading and trailing spaces to the string you pass to it. And above this, it will also replace all multiple spaces with a single space. It is that easy.
for example:
<node>
<value-of select="normalize-space(RootNode/SubNode/AnotherSubNode)" />
</node>
In C# there is no build-in solution for this problem, at least none that I'm aware of.
I solved this by writing a simple function, as follows:
public String RemoveMultipleSpaces(String phrase)
{
phrase = phrase.Trim();
phrase = System.Text.RegularExpressions.Regex.Replace(phrase, "\\s+", " ");
return phrase;
}
This functions exists of 2 steps. First of all I'll remove all leading and trailing spaces in the string.
Then I replace all remaining multiple spaces by a single space. To do this I use the Regex.Replace(String, String, String) function. The first parameter is just the String that needs to be changed. The second parameter represents a regalur expression of the pattern that needs to be replaced, in this case its mulitple spaces. And finally, the last parameter is the single space that will replace all matching substrings inside the original string.
Abonneren op:
Posts (Atom)
