TODO:
Have you ever wanted to get the elapsed seconds between 2 dates?
SOLUTION:
int elapsed_seconds = DateTime.Now.Subtract(MyDate).TotalSeconds;
NOTES:
There are no notes ont his topic
TODO: Have you ever had a "the specified @job_id does not exist" error when trying to start a replication job?
SOLUTION:
--STEP 1 : get the data to use for the new job id
select job_id, * From msdb.dbo.sysjobs where name like '%MY-JOB-NAME%'
--STEP 2 : now get the id to use for the update
select id, * From distribution.dbo.msmerge_agents where name like '%MY-JOB-NAME%'
--STEP 3 : use job_id obtained in STEP 1 as the GUID in this statement. Use Id from step 2 as the WHERE clause id in this statement
update distribution.dbo.MSmerge_agents set job_id=CONVERT(binary(16), cast('A08B3687-8D56-45D1-8FB3-252ACB81A104' as uniqueidentifier)) where id=61
NOTES:
No notes on this topic
TODO:
Have you ever wanted to search a document for nodes with a certain name, and get their associated value?
SOLUTION:
string productCode = "";
//get a node list of all products with a venue id of 278652
XmlNodeList events = myDocument.DocumentElement.SelectNodes("product[VenueID='278652']");
//go through each node and get the product code
foreach (XmlNode eventNode in events)
{
productCode = eventNode.SelectSingleNode("product_code").InnerText;
//do some other stuff here...
}
NOTES:
No notes on this topic.
TODO:
You try to Deserialize a string, and receive the error "There is no Unicode byte order mark, Cannot switch to Unicode"
SOLUTION:
//If there is no UTF8 encoding in the XML, do this
string xmlString = ""; //your XML string
using (TextReader reader = new StringReader(xmlString))
{
XmlSerializer xmlSerial = new XmlSerializer(typeof(myObject));
return (myObject)xmlSerial.Deserialize(reader);
}
NOTES:
There are no notes on this topic.
TODO:
Have you ever wanted to express an if-else more consicely and elegantly? The example below checks for a null string and sets to empty if found to be so.
SOLUTION:
string mystring = "";
..
//some code
..
mystring = (mystring == null ? "" : mystring);
NOTES:
No notes apply to this topic.
TODO:
Have you ever wanted to send an email in C#?
SOLUTION:
public bool sendEmail(string pstrTo, string Name, string bcc, string smtpServer, string smtpUser,
string pstrSubject, string strMessage, string attachFilePath)
{
string smtpServerPort = "25";
MailMessage mailMsg = null;
int port = 0;
try
{
//make sure we have an email address.....
if (String.IsNullOrEmpty(pstrTo))
throw new Exception("Email address was not supplied");
//get smtp user, and make sure its valid
if (String.IsNullOrEmpty(smtpServer))
throw new Exception("No SMTP Server specified");
port = System.Convert.ToInt32(smtpServerPort);
System.Net.Mail.SmtpClient smtp = new SmtpClient(smtpServer, port);
MailAddress from = new MailAddress(smtpUser, "Mail Admin");
MailAddress to = new MailAddress(pstrTo, Name);
mailMsg = new MailMessage(from, to);
mailMsg.Subject = pstrSubject;
mailMsg.Body = strMessage;
//add BCC if we have it
if (!String.IsNullOrEmpty(bcc))
{
mailMsg.Bcc.Add(bcc);
}
//attach file if we have one...
if (!String.IsNullOrEmpty(attachFilePath))
{
mailMsg.Attachments.Add(new Attachment(attachFilePath));
}
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Timeout = 5000;
smtp.Send(mailMsg);
return true;
}
catch (Exception x)
{
throw x;
}
finally
{
if (mailMsg != null)
mailMsg.Dispose();
}
}
NOTES:
I assumed port 25 was used. This was for simplicity only, your mail server may be different.
TODO:
Have you ever wanted to read a NTEXT column from a Table in SQL Server
SOULTION:
DECLARE @Length int
DECLARE @ptrval varbinary(16)
SELECT @ptrval = TEXTPTR(MyTextColumn), @Length = Datalength(MyTextColumn) / 2
FROM tbl_MyData where Id = 10023
READTEXT tbl_MyData.MyTextColumn @ptrval 0 @Length
NOTES:
You must divide the @Length by 2 in the select because NTEXT is a double-byte data type.
TODO:
Have you ever wanted to read an TEXT column from a Table in SQL Server
SOULTION:
DECLARE @Length int
DECLARE @ptrval varbinary(16)
SELECT @ptrval = TEXTPTR(MyTextColumn), @Length = Datalength(MyTextColumn)
FROM tbl_MyData where Id = 10023
READTEXT tbl_MyData.MyTextColumn @ptrval 0 @Length
NOTES:
There are no notes on this topic.
TODO:
Have you ever wanted to create and initialize a list on the fly?
SOLUTION:
List<int> MyNumberList = new List<int>(){ 6, 1, 3, 4 };
NOTES:
No notes on this topic.
TODO:
Have you ever wanted to detect or catch the user pressing CTRL+C, CTRL-BREAK, Window Close, or Logoff / Shutdown Event in your console application?
SOLUTION:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection;
namespace ConsoleApplication1
{
class ControlChecker
{
#region GLOBAL VARS
private static readonly Mutex mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetName().CodeBase);
private static bool _userRequestExit = false;
private static bool _doIStop = false;
static HandlerRoutine consoleHandler;
#endregion
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
/// <summary>
///
/// </summary>
/// <param name="ctrlType"></param>
/// <returns></returns>
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_C_EVENT:
_userRequestExit = true;
Console.WriteLine("CTRL+C received, shutting down");
break;
case CtrlTypes.CTRL_BREAK_EVENT:
_userRequestExit = true;
Console.WriteLine("CTRL+BREAK received, shutting down");
break;
case CtrlTypes.CTRL_CLOSE_EVENT:
_userRequestExit = true;
Console.WriteLine("Program being closed, shutting down");
break;
case CtrlTypes.CTRL_LOGOFF_EVENT:
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
_userRequestExit = true;
Console.WriteLine("User is logging off!, shutting down");
break;
}
return true;
}
/// <summary>
/// Main entry point
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
static int Main(string[] args)
{
try
{
//make sure we only have one....
if (!mutex.WaitOne(TimeSpan.Zero, true))
{
Console.WriteLine("Another instance already running");
Thread.Sleep(5000);
return 1;
}
//save a reference so it does not get GC'd
consoleHandler = new HandlerRoutine(ConsoleCtrlCheck);
//set our handler here that will trap exit
SetConsoleCtrlHandler(consoleHandler, true);
DoMyTask();
return 0;
}
catch (Exception x)
{
Console.WriteLine("Main Error [{0}]", x.Message);
return -1;
}
}
/// <summary>
/// Run the export
/// </summary>
/// <param name="pAuthority"></param>
/// <returns></returns>
private static void DoMyTask()
{
//execcute until we have no more records to process
while (!_doIStop)
{
//did user request exit?
if (_userRequestExit)
{
_doIStop = true; //set flag to exit loop. Other conditions could cause this too, which is why we use a seperate variable
Console.WriteLine("Shutting down, user requested exit");
break;
}
//do some other stuff here
Console.WriteLine(String.Format("{0}, no exit requested yet...", DateTime.Now));
//sleep 1 second
Thread.Sleep(1000);
}
}
}
}
NOTES:
Open up Visual Studio. Create a new Console Application Project. Copy the entire code above, and replace ALL of the code in your program.cs main file. Hit CTRL-F5, then test the break conditions above.