Miscellaneous Topics and Tips
- Check Whether or Not an IP Is Valid in C#
- Split a Concatenated String with a Delimiter
- Convert a String to a Byte Array
- Format the Currency for a Culture in C#
- Convert Hex to RGB in C#
- Change Date to ISO8601 Date Format in C#
- Get a Special Folder Path in C#
- Enumerate All the Values in an Enum
- Quickly View All TODOs in Visual Studio
- Get the Path to the Temporary Folder in the Operating System
- How to Create a Hash String for a String Input
- Get the Path to the Temporary Folder in the Operating System
- How to Filter an Exception with a Condition in C# 6.0
- Chaining Null Comparisons with the ?? Operator
- Quickly Surround a Block of Code in Visual Studio
- Find the Sign of a Number in C#
- Dealing with DateTimeOffset Serialization to Strings
- Determine if the Current Request Is from a Crawler in ASP.NET
- Format the Console.Write Responses
- How to Restrict Input Text to Characters in a Text Box
- Sort a List in C# by Date
- Easily Create a String of Repeated Characters
- Case Insensitive Comparison of Two Strings
- How to Find the Size of the HTTP Resource Being Fetched
- Set Multiple Projects as Startup Projects in Visual Studio
- Quick Way to Disable Copy-Paste in a Textbox in a WinForms Application
- Using SendKeys in C#
- Use the Math.Absoute Function to Return the Absolute Value for Numbers
- Quick and Efficient Way to Get to the Parent Control
- Serialize an Object to a JSON String
- Use the Math.BigMul Method to Find Multiple Large Integers
- Get DNS Name from an HttpRequest in C#
- Quick Way to Create Class Diagrams for a Project
- Block and Unblock Internet Access on a User's Computer Using C#
- Using Aliases for Namespaces in C#
- Get the Size of a File in FTP with C#
- Can't use the "Between" Keyword in a LINQ Query
- Working with an SQL Output Parameter in C#
- Retrieving Multiple Record Sets Through a DataReader
- Getting Text from any External Window in C#
- Check if an HttpRequest is an Ajax Request
- Displaying the Euro Sign in a Textbox
- Generate Random Passwords
- Left, Right and Mid String Functions for C#
- List all Environment Variables
- Strip HTML Content from a String
- Create Quick Documentation for your Code in Visual Studio
- Quick Way to Escape Special Characters in an XML Document
- Converting JSON Results in Camel Case
- Encrypting and Decrypting a Database Connection String
- Encrypt a Config Section Using .NET's Configuration Providers
- Break the Data Links in an Excel Workbook
Check Whether or Not an IP Is Valid in C#
See below for a short function that validates a given IP address:
public static Boolean ValidateIP(string inputIP)
{
var ipParts = inputIP.Split('.');
return Int32.Parse(ipParts [0]) < 256 &&
Int32.Parse(ipParts [1]) < 256&
Int32.Parse(ipParts [2]) < 256 &
Int32.Parse(ipParts [3]) < 256;
}
Split a Concatenated String with a Delimiter
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
string s = "You win some. You lose some.";
string[] subs = s.Split(' ', '.');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
he periods are gone from the substrings, but now two extra empty substrings have been included. These empty substring represent the substring between a word and the period that follows it. To omit empty substrings from the resulting array, you can call the Split(Char[], StringSplitOptions) overload and specify StringSplitOptions.RemoveEmptyEntries for the options parameter.
string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
Here is how to split a concatenated string with a delimiter and remove empty entries.
public static void Test()
{
string concatenatedString = ",ONE,,TWO,,,THREE,,";
char[] charSeparator = new char[] {','};
string[] splitArray= concatenatedString.Split(charSeparator, StringSplitOptions.RemoveEmptyEntries);
}
===
Convert a String to a Byte Array
Explore how to convert a string to a byte array.
String stringToBeConverted = " … " ;
int stringLength = stringToBeConverted.Length;
byte[] bytes = new byte[stringLength / 2];
for (int counter = 0; counter < stringLength; counter += 2)
bytes[counter / 2] = Convert.ToByte(stringToBeConverted.Substring(counter, 2), 16);
===
Format the Currency for a Culture in C#
Use the CultureInfo class of System.Globalization namespace to format values based on a culture.
Example:
using System;
using System.Globalization;
namespace ConsoleTests
{
class Program
{
static void Main(string[] args)
{
decimal inputValue = 123456;
CultureInfo currentCulture = new CultureInfo("en-US");
string formattedString = string.Format(currentCulture, "{0:C}", inputValue);
Console.WriteLine(formattedString);
Console.ReadKey();
}
}
}
output: $123,456.00
===
Convert Hex to RGB in C#
The .NET System.Globalizaton's NumberStyles has a parameter called AllowHexSpecifier that helps us to replace a hexString with RGB color.
using System;
using System.Drawing;
using System.Globalization;
namespace ConsoleTests
{
class Program
{
static void Main(string[] args)
{
Color color = HexToColor("#812dd3");
Console.WriteLine(color.ToString());
Console.ReadKey();
}
public static Color HexToColor(string hexString)
{
//replace # occurences
if (hexString.IndexOf('#') != -1)
hexString = hexString.Replace("#", "");
int r, g, b = 0;
r = int.Parse(hexString.Substring(0, 2), NumberStyles.AllowHexSpecifier);
g = int.Parse(hexString.Substring(2, 2), NumberStyles.AllowHexSpecifier);
b = int.Parse(hexString.Substring(4, 2), NumberStyles.AllowHexSpecifier);
return Color.FromArgb(r, g, b);
}
}
}
output: Color [A=255, R=129, G=45, B=211]
NumberStyles Enum
Namespace:
System.Globalization
Assemblies:
mscorlib.dll, System.Runtime.dll
Determines the styles permitted in numeric string arguments that are passed to the Parse and TryParse methods of the integral and floating-point numeric types.
===
Change Date to ISO8601 Date Format in C#
To change the date format in C#, just use the ToUniverstalTime and the overload formatting as below:
String isoFormat = inputDateTime.ToUniversalTime().ToString("s") + "Z";
===
Get a Special Folder Path in C#
Use the System.Environment namespace's GetFolderPath method to retrieve the path of a special folder. It can also create the folder if it does not exist.
System.Environment.GetFolderPath(Environment.SpecialFolder.Recent, Environment.SpecialFolderOption.None))
===
Enumerate All the Values in an Enum
See an easy way to enumerate all the values.
public enum WorkTypes
{
Remote = 0,
Office = 1,
Exempted = 2
}
foreach (WorkTypes workType in Enum.GetValues(typeof(WorkTypes)))
Console.WriteLine(workType);
===
Quickly View All TODOs in Visual Studio
TODOs are a quick way to jot down action items while coding. It can also sometimes become cumbersome to locate all TODOs for further action. Visual Studio provides a way to get them.
Select View - Show Tasks option. This lists all TODOs in the code.
==
Get the Path to the Temporary Folder in the Operating System
Use the GetTempPath method to retrieve the temp file path in a machine.
Please note that it also varies from one operating system to other.
string tempFilePath = System.IO.Path.GetTempPath();
===
Using the String.join Method to Concatenate Strings
To join the objects in a collection, such as a string array, with a common delimiter like a comma or another character, is quite easy with the string.join method. See below for an example:
List<string> stringList = new List<String>() { "John", "Doe"m "Fischer" };
var combinedString = String,Join(",", stringList);
===
How to Create a Hash String for a String Input
You can use the SHA1Managed class and compute hash for an input string as shown below.
It is done in two steps. First, is to get the byte array after computation, and second is converting the bytes into string and append them.
Using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(inputstring));
var hashSB = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
hashSB.Append(b.ToString(???x2???));
}
return sb.ToString();
}
===
Get the Path to the Temporary Folder in the Operating System
Use the GetTempPath method to retrieve the temp file path in a machine.
Please note that it also varies from one operating system to other.
string tempFilePath = System.IO.Path.GetTempPath();
===
How to Filter an Exception with a Condition in C# 6.0
There are cases in which we want to ignore errors even if they are genuine. For example, there could be a feed running on all days except for some fixed holidays. You could work with the exception as shown below.
The following code catches the null reference exception only when it is not a pre-defined holiday (through the IsHoliday method).
try
{
//code
}
catch(System.NullReferenceException ex) if (!IsHoliday(DateTime.Now))
{
//log this error
}
===
Chaining Null Comparisons with the ?? Operator
Did you know you can chain null comparisons to any level on an object with ?? operator? See below for an example:
string inputString;
//set some value.
var multiEvaluationResult = inputString?? secondaryString ?? someOtherString;
===
Escape Characters with the "@" Symbol in C#
Use the "@" symbol to prefix a string that has characters. You do not have to escape the characters in the string. For example, instead of:
Var filePathString = "C:\\mydocs\\share\\audit.docx";
We could write it as:
Var filePathString = @"C:\mydocs\share\audit.docx";
===
Quickly Surround a Block of Code in Visual Studio
Visual Studio has the surround with code snippets that are handy and help save time to write code. A couple of the inbuilt code snippets include the if condition, for loop and so on.
Just select the code, and press ctrl + K + S : you will be presented with the surround with menu and choose an option there.
===
Find the Sign of a Number in C#
System.Math class has a Sign method that will help you determine if a number has a negative sign or positive sign.
//returns -1
int negativeNumber = System.Math.Sign(-2);
// returns 1
int postiveNumber = System.Math.Sign(1);
//returns 0
int neutralNumber = Math.Sign(0);
===
Dealing with Datetimeoffset Serialization to Strings
DateTimeOffSet values are often converted to strings for display or some other purpose. But these representations often fail when they are used to convert them back to valid date/time values.
We need to use the ToString method's overload and pass the "u" or "s" formats as they are culture-invariant.
For example:
DateTimeOffSet d = DateTimeOffSet.Now;
Console.WriteLine(d.ToString("u"));
===
Check Whether a String Contains Another String
Often, we have to do a string comparison by ignoring the case, or the results end up being wrong. The StringComparison enum provides the "ordinalignorecase" member that allows you to do this. See below for an example.
string searchString = "John";
string completeString = "johnDoe";
bool exists = completeString.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) = 0;
===
Determine if the Current Request Is from a Crawler in ASP.NET
The System.Web.HttpBroswerCapabilities has an important property called "Crawler" that enables us to handle requests from crawlers. Please check out the example below:
Var isCrawler = ((System.Web.Configuration.HttpCapabilitiesBase)Request.Browser).Crawler;
===
Format the Console.Write Responses
We use string.format to format the data written to the console using the console.write or console.writeline commands. However, it isn't indented well to make it readable. C# allows you to bridge this gap by supporting the addition of spaces and thus providing the formatted and indented output.
for (int counter=0 ; counter {
Console.WriteLine(string.Format("Collection Key: {0,-5} Value: {1,5}"), collection[counter].key, collection[counter].value);
}
As you already know, the numbers 0 and 1 are used to position the value of the variables in the formatted response string. The numbers -5 and 5 allow you to left align and right align the text within 5 spaces.
===
How to Restrict Input Text to Characters in a Text Box
Use the KeyPress event to check for the keys pressed. See below for an example:
private void textFirstName_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ( !( char.IsLetter(e.KeyChar) ) )
{
e.Handled = true;
}
}
===
Sort a List in C# by Date
We can use the Sort Method of LINQ, and use the CompareTo delegate.
If your List contains collection of objects, where each object has a date identifier, you could use the following code to sort:
myObject.Sort((a, b) = a.dateFieldName.CompareTo(b.dateFieldName));
===
Easily Create a String of Repeated Characters
Use the string class's constructor to specify the character and the number of times you want it to be repeated.
Listing 1. Repeat String Characters
String repeatedCharacterString = new String('*',50);
The sample code will create a string of 50 repeated '*' characters.
===
Use the Let Keyword to Create Variables in a LINQ Query
There are cases in which you will find the need to have variables inside a LINQ query to hold an evaluation result. The Let keyword helps in this case. See below for an example:
var oldTeens = from kidAge in kidsAges
let age = kidAge 14
where age
select kidAge;
var result = oldTeens.ToList();
===
Case Insensitive Comparison of Two Strings
We often compare two strings to the same case and then compare them to see if they are the same. Instead, we can use the StringComparison class's InvariantCultureIgnoreCase property.
String.Equals('stringOne', 'Stringone', StringComparison.InvariantCultureIgnoreCase)
===
Merge Two Data Tables in C#
If you have two data tables with the same data columns, you can merge them quite easily.
Merge Data Tables
dataTableEuropeanCities and dataTableAsianCities are two datatables with same schema. They can be merged with one line of code.
DataTable dataTableEuropeanCities = new DataTable();
DataTable dataTableAsianCities = new DataTable();
dataTableEuropeanCities.Merge(dataTableAsianCities);
===
How to Find the Size of the HTTP Resource Being Fetched
There are cases in which we might want to warn the user before an attempt is made to download a large file, or we might simply be interested to know its size before downloading.
In C#, we use the HttpWebRequest class to download objects from an URL. We can set the request method to be of "Head" type and examine the response header "Content-Length" to determine the size of the object.
string url = "http://mydomain.com/FileStore/bigfile.zip";
var urlRequest = (HttpWebRequest)WebRequest.Create(url);
//Set the request.method to ???HEAD???
urlRequest.Method = "HEAD";
var urlResponse = urlRequest.GetResponse();
string contentLength = urlResponse.Headers.Get("Content-Length");
Messagebox.Show(int.Parse(contentLength).ToString());
===
Set Multiple Projects as Startup Projects in Visual Studio
Yes, you can set multiple projects to be startup projects in Visual Studio.
Right click on a solution file in Visual Studio. Choose "Set startup projects." In the dialog that appears, choose common properties — Multiple startup projects.
Select the multiple projects that you want to start simultaneously and set their action to "Start."
===
Quick Way to Disable Copy-Paste in a Textbox in a WinForms Application
In the old versions of .NET, we needed to override the default context menu and override the ProcessCmdKeyfunction to return True to disable Copy-Paste of content into textboxes through keys such as Ctrl+C, Ctrl+V, Shift+Insert, etc.
In the newer versions of .NET, we can just disable the "ShortcutsEnabled" property to False. This will do the trick. You can no longer copy/paste or perform any other actions through shortcuts on the textbox.
===
Using SendKeys in C#
SendKeys is very powerful. You can use SendKeys to send a different keycode from the one that was pressed. For example:
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
SendKeys.Send("{TAB}");
}
if (e.KeyCode == Keys.Left)
{
SendKeys.Send("+{TAB}");
}
}
"Presses" tab when the Left or Right arrow keys are pressed.
===
Use the Math.Absoute Function to Return the Absolute Value for Numbers
There are cases in our math calculations where we would need absolute values of negative numbers. System.Math class's Abs method helps in such cases. It returns the absolute value of the number.
Int i = -10;
Console.WriteLine(System.Math.Abs(i).ToString());
//will output 10
===
Quick and Efficient Way to Get to the Parent Control
Many times, it is tough to traverse up the control tree to reach the parent control. The best example is of a control in a template column of a grid.
The most common way would be go reverse, traversing all the parents, until you find the real one. But this isn't efficient. For example, a TextBox control in a TableRow, would use the following code to reach its Row Item.
//1st Parent is the Cell, and 2nd is the TableRow
DataGridItem grdPrntItem = (DataGridItem) txtBox1.Parent.Parent;
Efficient way of doing this is like this,
//this would work always, no matter how deep in the control tree the actual control is.
DataGridItem grdPrntItem = (DataGridItem) txtBox1.Container;
===
Serialize an Object to a JSON String
Newtomsonft.json has helper methods that help to serialize objects to JSON. See below for a code snippet that uses the library and helps convert an object to JSON format.
public string SerializeToJSon(object o)
{
var jsonSerializer = new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Ignore
};
var jsonString = string.Empty;
using (var stringWriter = new StringWriter())
{
using (var jsonTextWriter = new JsonTextWriter(stringWriter))
{
//use quotename to surround names in quotes.
jsonTextWriter.QuoteName = true;
jsonSerializer.Serialize(jsonTextWriter, o);
jsonTextWriter.Close();
}
jsonString = stringWriter.ToString();
}
return jsonString;
}
===
Use the Math.BigMul Method to Find Multiple Large Integers
System.Math provides the BigMul method for cases where you have to find the product of two large integer numerals that may result in a value that would cause an System.Overflow Exception. The BigMul method returns a long number, which avoids the overflow.
System.Int32 i = 245525352;
System.Int32 j = 245552352;
System.Int32 k = 0;
//This one will work
var result = System.Math.BigMul(i, j);
//This one will throw Arithmetic overflow exception
k = i * j;
===
Get DNS Name from an HttpRequest in C#
Use the GetLeftPart method on the HttpRequest's URI with Authority as the UriPartial's value to retrieve the DNS Name.
string dnsName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
===
Quick Way to Create Class Diagrams for a Project
Class diagrams help you to understand code a lot more quickly through visual representation. Visual Studio, by default, provides you with a one-step process to generate self-updating Class diagrams.
Right-click on "Project" in solution explorer and choose View - View class diagram. It will generate a class diagram for you. Go ahead and add new methods to the existing class and make some changes to the class. This will be reflected in the class diagram in real time.
===
Block and Unblock Internet Access on a User's Computer Using C#
Use the following code to block and unblock Internet connectivity on a user's PC:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace BlockInternet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//ADDED A REFERENCE TO SYSTEM.SERVICEPROCESS VIA PROJECT->ADD REFERENCE, .NET tab
System.ServiceProcess.ServiceController scPAServ = new System.ServiceProcess.ServiceController("PolicyAgent"); //IPSec
if (scPAServ.Status != System.ServiceProcess.ServiceControllerStatus.Running)
{
scPAServ.Start(); //Start If Not Running
}
string[] strCommands = { @"-w REG -p ""Firewall"" -r ""Block All"" -f *:*:*+*:*:* -n BLOCK -x" ,
@"-w REG -p ""Firewall"" -r ""Allow LAN"" -f 0:*:*+192.168.10.*:*:* -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""DNS"" -f 0:*:UDP+223.211.190.23:53:UDP 0:*:UDP+223.211.190.24:53:UDP 0:*:TCP+223.211.190.23:53:TCP 0:*:TCP+223.211.190.24:53:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""POP3"" -f 0:*:TCP+*:110:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""POP3S"" -f 0:*:TCP+*:995:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""FTP Control"" -f 0:*:TCP+*:21:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""FTP Data"" -f 0:*:TCP+*:20:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""IMAP"" -f 0:*:TCP+*:143:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""HTTP"" -f 0:*:TCP+*:80:TCP -n PASS -x" ,
@"-w REG -p ""Firewall"" -r ""HTTPS"" -f 0:*:TCP+*:443:TCP -n BLOCK -x" ,
@"-w REG -p ""Firewall"" -r ""PROXY"" -f 0:*:TCP+*:8080:TCP 0:*:TCP+*:3128:TCP 0:*:TCP+*:8081:*:TCP 0:*:TCP+*:8000:TCP -n BLOCK -x"};
for (int i = 0; i < strCommands.Length; i++) //Loop through each Command String
{
ProcessStartInfo psiStart = new ProcessStartInfo(); //Process To Start
psiStart.CreateNoWindow = true; //Invisible
psiStart.FileName = Directory.GetParent(Assembly.GetExecutingAssembly().Location) + "\\ipseccmd.exe"; //IPSEC
psiStart.Arguments = strCommands[i]; //Break Command Strings Apart
psiStart.WindowStyle = ProcessWindowStyle.Hidden; //Invisible
Process p = System.Diagnostics.Process.Start(psiStart); //Start Process To Block Internet Connection
}
}
private void button2_Click(object sender, EventArgs e)
{
System.ServiceProcess.ServiceController scPAServ = new System.ServiceProcess.ServiceController("PolicyAgent"); //IPSec
if (scPAServ.Status != System.ServiceProcess.ServiceControllerStatus.Running) //If Not Running
{
scPAServ.Start();
}
string strCommands = @"-w REG -p ""Firewall"" -r ""Block All"" -f *:*:*+*:*:* -n BLOCK -y"; //Commands To Send
ProcessStartInfo psiStart = new ProcessStartInfo(); //Process To Start
psiStart.CreateNoWindow = true; //Invisible
psiStart.FileName = Directory.GetParent(Assembly.GetExecutingAssembly().Location) + "\\ipseccmd.exe"; //IPSEC
psiStart.Arguments = strCommands; //Give Command String As Argument
psiStart.WindowStyle = ProcessWindowStyle.Hidden; //Invisible
Process p = System.Diagnostics.Process.Start(psiStart); //Start Process To Stop Internet Connection
}
}
}
===
Using Aliases for Namespaces in C#
We can use an alias for long namespaces and use it further down in the code. For an example, see below:
//InteropExcel is the alias
using InteropExcel = Microsoft.Office.Interop.Excel;
public class SpreadSheetInteropHelper
{
public void InitializeApplication()
{
var excelApplication = new InteropExcel.Application();
}
}
===
Get the Size of a File in FTP with C#
Using the System.Net.WebRequestMethods.FTP class, we can use the "SIZE" FTP Protocol method to get the size of the file in FTP. Below is an example in C#:
var request = (FtpWebRequest)FtpWebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential("username", "password");
request.KeepAlive = false;
//Use the GetFileSize FILE SIZE Protocol method
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
fileSize = response.ContentLength;
response.Close();
request.Abort();
===
Can't use the "Between" Keyword in a LINQ Query
You can't use the "Between" keyword in a LINQ query.
The sample snippet below shows how you translate between two date fields.
DateTime fromDate = DateTime.Now.AddMonths(-3);
DateTime endDate = DateTime.Now;
//linq query
var result = from te in datatable.AsEnumerable()
where (te.Field("Month") = fromDate)
&& (te.Field("Month")
Can't use the "Between" Keyword in a LINQ Query
You can't use the "Between" keyword in a LINQ query.
The sample snippet below shows how you translate between two date fields.
DateTime fromDate = DateTime.Now.AddMonths(-3);
DateTime endDate = DateTime.Now;
//linq query
var result = from te in datatable.AsEnumerable()
where (te.Field("Month") = fromDate)
&& (te.Field("Month")
===
Can't use the "Between" Keyword in a LINQ Query
You can't use the "Between" keyword in a LINQ query.
The sample snippet below shows how you translate between two date fields.
DateTime fromDate = DateTime.Now.AddMonths(-3);
DateTime endDate = DateTime.Now;
//linq query
var result = from te in datatable.AsEnumerable()
where (te.Field("Month") = fromDate)
&& (te.Field("Month")
======
Working with an SQL Output Parameter in C#
When working with an SQL Output parameters, you need to specify the parameter's Direction property once you have created it. Here is a nice little example method:
private float checkValue()
{
SqlConnection con = new SqlConnection("Provider=PROVIDER;Server=SERVER;Database=DATABASE;");
SqlCommand com = new SqlCommand("getValue", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter par = new SqlParameter("@WB", SqlDbType.Float);
par.Direction = ParameterDirection.Output;
com.Parameters.Add(par);
con.Open();
com.ExecuteNonQuery();
float i = float.Parse(par.Value.ToString());
return i;
}
Implementation
float val = checkvalue();
======
Retrieving Multiple Record Sets Through a DataReader
If a stored procedure returns multiple record sets, and if you are using the DataReader to retrieve the results, you can use the NextResult method of the DataReader to iterate through the Record Sets. Sample shown below:
SqlConnection conn = new SqlConnection("connectionStringValue"));
conn.Open();
using (conn)
{
using (SqlCommand command = new SqlCommand(" SELECT col1 FROM Table1; SELECT col2 FROM Table2", conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.HasRows)
{ while (reader.Read())
{
//
}
reader.NextResult();
}
}
}
}
======
Getting Text from any External Window in C#
To get the text of an external window you could use the GetForegroundWindow and the GetWindowTextAPI functions. Here is a small example of its usage:
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(int hWnd, StringBuilder text, int count);
//Use SetWindowPos to make app alwaysontop
public Form1()
{
InitializeComponent();
}
private void GetActiveWindow()
{
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) 0)
{
this.captionWindowLabel.Text = Buff.ToString();
this.IDWindowLabel.Text = handle.ToString();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
GetActiveWindow();
}
}
======
Check if an HttpRequest is an Ajax Request
A quick way to check if an HTTP Request is an Ajax request is by examining the X-Requested-With Header value.
Please see below:
bool isAjaxRequest = request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest";
======
Displaying the Euro Sign in a Textbox
Don't you just hate it that the Euro monetary symbol is not present on all computers?
With this simple trick you can add the Euro sign to a textbox.
Put a Textbox on your form. In its Text Property use the shortcut Alt 0128. Then add this code to make use of it properly:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += Convert.ToDecimal(txtEuros.Text);
//OR If your regional settings are set up correctly
textBox1.Text = Convert.ToDecimal(txtEuros.Text).ToString("C");
}
======
Generate Random Passwords
Use the following method to generate random passwords.
private string GenerateRandomPassword(int minLength, int maxLength)
{
StringBuilder randomPassword = new StringBuilder();
Random rand = new Random((int)DateTime.Now.Ticks);
int randLength = rand.Next(minLength, maxLength);
for (int i = 0; i {
int charint = 0;
while (charint == 0)
charint = rand.Next(48, 58);
randomPassword.Append((char)charint); } return randomPassword.ToString();
}
}
======
Left, Right and Mid String Functions for C#
Unlike Visual Basic, C# doesn't have built-in string methods to extract parts of string from the Left, Right or a location specified through Mid. Unfortunately you have to create the logic yourself.
Here are examples of Left, Right and Mid in C# with the use of the Substring method present in C# (and VB):
class LeftRightMid
{
[STAThread]
static void Main(string[] args)
{
string myString = "This is a string";
//Get 4 characters starting from the left
Console.WriteLine(Left(myString,4));
//Get 6 characters starting from the right
Console.WriteLine(Right(myString,6));
//Get 4 characters starting at index 5 of the string
Console.WriteLine(Mid(myString,5,4));
Console.ReadLine();
}
public static string Left(string param, int length)
{
string result = param.Substring(0, length);
return result;
}
public static string Right(string param, int length)
{
string result = param.Substring(param.Length - length, length);
return result;
}
public static string Mid(string param,int startIndex, int length)
{
string result = param.Substring(startIndex, length);
return result;
}
}
}
======
List all Environment Variables
The system variables are exposed through the GetEnvironmentVariables method in the System.Environment class.
var environmentVariables = System.Environment.GetEnvironmentVariables();
foreach (var ev in environmentVariables)
{
DictionaryEntry de = (DictionaryEntry) ev;
Console.WriteLine(string.Format("Key: {0}, Value: {1}", de.Key, de.Value));
Console.WriteLine();
}
======
Strip HTML Content from a String
To string HTML tags, use HttpUtility???s HTMLDecode method with a RegEx expression. HTMLDecode is available in System.Web assembly.
string htmlText = @"Decision Making Techniques: Why should you be prepared";
string plainText = string.Empty;
if (!string.IsNullOrWhiteSpace(htmlText))
{
plainText = Regex.Replace(HttpUtility.HtmlDecode(htmlText), @"", string.Empty).Trim();
}
======
Create Quick Documentation for your Code in Visual Studio
In order to create quick documentation for your code in Visual Studio, install GhostDoc--a Visual Studio extension that allows you to quickly create XML documentation for Classes, Methods, Properties, Parameters, etc.
======
Quick Way to Escape Special Characters in an XML Document
We can use the SecurityElement's Escape method of the System.Security namespace to escape all the special characters in an XML file. Code snippet below:
string escapedstring = System.Security.SecurityElement.Escape(inputXMLString);
...inputXMLString contains the XML with special characters.
======
Converting JSON Results in Camel Case
Use the CamelCasePropertyNamesContractResolver class of the Newtonsoft.Json assembly to return the JSON serialized string in camel case.
var responseObject = employeeProxy.GetAllEmployees();
var serializedObjectInCamelCase = JsonConvert.SerializeObject(responseObject,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
======
Encrypting and Decrypting a Database Connection String
You can encrypt your connection string to a database. Let me rephrase that: you should encrypt data connections. Here is an example of encrypting a connection string and decryprting a connection string.
Create the Connection String in your App.Config:
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source???;DatabaseName;"
providerName="System.Data.OleDb" /
Form Code:
private void EncryptConnectionString()
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string provider = "DataProtectionConfigurationProvider";
ConfigurationSection connstrings = config.ConnectionStrings;
connstrings.SectionInformation.ProtectSection(provider);
connstrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
private void DecryptConnectionString()
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection connstrings = config.ConnectionStrings;
connstrings.SectionInformation.UnprotectSection();
connstrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
private void EncryptButton_Click(object sender, EventArgs e)
{
EncryptConnectionString();
}
private void DecryptButton_Click(object sender, EventArgs e)
{
DecryptConnectionString();
}
======
Encrypt a Config Section Using .NET's Configuration Providers
var configFilePath = @"C:\Code\Classified\Configurations\app.config";
var sectionName = "appSettings";
EncryptConfigSection(configFilePath, sectionName);
private void EncryptConfigSection(string configFilePath, string sectionName)
{
var configurationFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);
var configSection = configuration.GetSection(sectionName);
var configurationProvider = new RsaProtectedConfigurationProvider();
if (!configSection.SectionInformation.IsLocked)
{
configSection.SectionInformation.ProtectSection(configurationProvider.CspProviderName);
}
configuration.Save();
}
======
Break the Data Links in an Excel Workbook
Use this function to break the data links in an Excel workbook. It shows a message asking the user to confirm to break.
private void BreakDataLinks(Excel._Workbook wb)
{
if (DialogResult.Yes == MessageBox.Show(this,"Do you want to break the links to Data Sources ?", "Links",
MessageBoxButtons.YesNo))
{
Array links = (Array)wb.LinkSources(Excel.XlLink.xlExcelLinks);
if (links != null) {
for (int i = 1; i {
wb.BreakLink((string)links.GetValue(i),
Excel.XlLinkType.xlLinkTypeExcelLinks);
}
}
======
using System;
using System.Globalization;
namespace ConsoleTests
{
class Program
{
static void Main(string[] args)
{
DateTime datetime = new DateTime(); //0001-01-01 12:00:00 AM
Console.WriteLine(datetime.ToString()); //0001-01-01 12:00:00 AM
Console.WriteLine(datetime.Date);//1001-01-01 12:00:00 AM
Console.WriteLine(datetime.AddYears(1000));//0009-05-01 12:00:00 AM
Console.WriteLine(datetime.AddMonths(100));//0001-04-11 12:00:00 AM
Console.WriteLine(datetime.AddDays(100));//2021-06-28 7:57:10 PM
Console.WriteLine(DateTime.Now);//2021-06-28 2:27:10 PM
Console.WriteLine(DateTime.UtcNow);//
Console.WriteLine(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern); //yyyy-MM-dd
bool flag = DateTime.TryParse("2021/2/21", out DateTime result);
if (flag)
{
Console.WriteLine(result); //2021-02-21 12:00:00 AM
}
Console.ReadKey();
}
}
}
No comments:
Post a Comment