Thursday, November 30, 2006

Writing log message to file via Message Queue



using System;
using System.Configuration;
using System.Messaging;
using System.IO;

namespace Test
{
public class QSend
{
private System.Messaging.MessageQueue mq;
private string exQ;

public QSend()
{
try
{
mq = new System.Messaging.MessageQueue(
@".\Private$\MyQ");
LogItems inLogItems = new LogItems();
inLogItems.FileName = @"d:\mgslog\Log.txt";
inLogItems.Message = " my message";
mq.Send(inLogItems);
}
catch(MessageQueueException ex)
{
exQ = ex.Message;
}
}
}

public class QRecieve
{
private System.Messaging.MessageQueue mq;
private string exQ;

public QRecieve()
{
try
{
mq = new System.Messaging.MessageQueue (@".\Private$\MyQ");
mq.Formatter =
new System.Messaging.XmlMessageFormatter (
new Type[] {typeof (LogItems)}) ;
System.Messaging.Message msg = mq.Receive();
LogItems outLogItems = (LogItems) msg.Body;
using( StreamWriter sw =
new StreamWriter(outLogItems.FileName,true))
{
sw.WriteLine(DateTime.Now.ToString()
+ outLogItems.Message);
sw.Flush();
}
}
catch(MessageQueueException e)
{
exQ = e.Message;
}

}
}

public class LogItems
{
private string _fileName;
private string _message;
public string FileName
{
get {return _fileName;}
set {_fileName = value;}
}
public string Message
{
get {return _message;}
set {_message = value;}
}
}
}




kick it on DotNetKicks.com

Debugging and Tracing Your Website C# (Video)

Tuesday, November 21, 2006

Convert any possible type to T in .Net 2005

private T TryConvert <T>(object o, T defaultValue, bool isThrowException)
{
    T convertedValue = defaultValue;
    try
    {
     if (o != null)
      {
       convertedValue = (T)Convert.ChangeType(o, typeof(T));
      }
     else
      throw;
    }
    catch
    {
     if (isThrowException)
      {
       throw;
      }
    }
   return convertedValue;
}

How to use:


Let us suppose you have HttpRequest with some parameters:
ID , Name and Flag
Example 1. Simple using
private void Examle()
{
int id =
TryConvert<int>(Request["id"], -1,
true);
string name =
TryConvert<string>(Request["name"], string.Empty,
true);
bool flag =
TryConvert<bool>(Request["Flag"], default(bool),
true);
}


Example 2. Using in enum


 public enum Week
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

private void Examle2(Week w)
{
Week day = TryConvert<Week>(w, Week.Sunday, true);
}