Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, December 18, 2013

Read Mails From Exchange Server - Send Mail - Move Mail

Just finished struggling around with a console application that reads mail for a particular account with a particular subject from Exchange server and re sends it to some other id with the same content.

Not much blah blah..here is the whole code.. Let you guys be saved atleast...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
using Microsoft.Exchange.WebServices.Data;

namespace BTROutlookConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            MessageBody messageBody = new Microsoft.Exchange.WebServices.Data.MessageBody();
            service.Credentials = new System.Net.NetworkCredential("username", "pwd", "domain.com");
            service.AutodiscoverUrl("username@domain.com");
            object o = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            FolderView view = new FolderView(100);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            view.Traversal = FolderTraversal.Deep;
            FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Inbox, view);
            foreach (Item item in findResults.Items)
            {
                Console.WriteLine(item.Subject);
                if (item.Subject.ToString().ToLower() == "SUBJECT1".ToLower())
                {
                    item.Load();
                    messageBody = item.Body.ToString();
                    Console.WriteLine("IsNew: " + item.IsNew);
                    Console.WriteLine("To: " + item.DisplayTo);
                    Console.WriteLine("Subject: " + item.Subject);
                    Console.WriteLine("Message Body: " + item.Body.ToString());
                    Console.WriteLine("Date & Time Received: " + item.DateTimeReceived);
                    Console.WriteLine("HasAttachments: " + item.HasAttachments);
                    string mailBody = item.Body.ToString();
                    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                    message.To.Add("salini.haridas@uniquegroup.com");
                    message.Subject = "From YesFolder";
                    message.From = new System.Net.Mail.MailAddress("username@domain.com", "Test Subject");
                    message.Body = mailBody;
                    message.IsBodyHtml = true;
                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("exname.domain.com");
                    smtp.Send(message);
                    item.Move(findFolderResults.Folders[0].Id);
                }
            }
        }
    }
}

This program assumes the Microsoft.Exchange.WebServices is added as reference to the project.

Happy programming guys..So good to c you after so long...Hey n between nowadays I am trying my luck in AX 2012 too.. So may be next time I can give you something from that.. :)

Sunday, April 21, 2013

clr20r3 P9 system.componentmodel.win32 : Handling unhandled exceptions

The problem : An Application that doesn't start


Happened to come across an older (read dot net 2.0) application which , due to some reason started to misbehave. whenever it is started it said "App has encountered a problem and needs to close. We are sorry for the inconvenience". There are no other details and the only point of hope was the windows log which said.

EventType clr20r3, P1 app_name.exe, P2 1.1.2.0, P3 4f1ea58b, P4 system, P5 2.0.0.0, P6 4889de7a, P7 3839, P8 131, P9 system.componentmodel.win32, P10 NIL.

I was also told by the dev guys that the application is having its own error log which does not show any entry of this error and also the infamous excuse of "It worked yesterday."   and "It is working fine on my machine."


The source


Going through the source code , found that all the methods had try catch blocks with exception logging configured to log everything including stack trace. Even all the line of codes inside the static Main() were enclosed in a try catch.


The Solution


Since there was no handler for unhandledexception written, the same was added just inside the Main()

           AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(delegate(object sender, UnhandledExceptionEventArgs e)
                {
                  if (e.IsTerminating)
                  {
                      object o = e.ExceptionObject;
                      MessageBox.Show(o.ToString()); // use EventLog instead
                  }
                }
            );



This snippet makes sure that no exceptions are unhandled from your side. [On a lighter note, the root cause here in this case was revealed to be an error log which grew out of size]
I suggest the usage of this handler for trapping any exception that stays unhandled.


Understanding the error log [Watson buckets]



For Breaking up the windows error log entry
EventType clr20r3, P1 app_name.exe, P2 1.1.2.0, P3 4f1ea58b, P4 system, P5 2.0.0.0, P6 4889de7a, P7 3839, P8 131, P9 system.componentmodel.win32, P10 NIL.
The entries P1 ,P2 ,P3 etc are the details collected by the system regarding the exception that went unhandled. They are known as Watson buckets. They include the following information


  1. Executable
  2. Assembly version number
  3. File Stamp
  4. Full assembly name
  5. Faulting assembly version
  6. Faulting assembly timestamp
  7. Faulting assembly method def
  8. IL Offset within the faulting method
  9. Exception type




Hopes this helps someone, someday, some time...
Happy Programming...



Thursday, December 8, 2011

Map Network Drive using C# / Vb.net code

This post will show you an easier way to map a network drive using dot net code. you are free to use any .net language of your choice. I will be mostly sticking to C# though.

We will be relying on COM Interop for this and we will be referencing the Windows Script Host Object Model for this task. Lets get going....

  • Step 1.
Open your choice of application project. In this case I am opening a new Windows Forms Application in C#. And you are there on the default form :Form1.

  • Step 2.
Add a new reference.
In Solution Explorer, right click on References and Click on Add reference.

Select the COM tab.

Scroll down and select Windows Script Host Object Model
Now the solution explorer will look like this with an IWshRuntimeLibrary added.

Now you are ready to go.

  • Step 3.
Write Code.
Go to the code window. select your required event [button click or form load or just anything].
Create an instance of the class IWshNetwork_Class
Call the MapNetworkDrive method and you are done.

  • Sample Code
IWshNetwork_Class network = new IWshNetwork_Class();
network.MapNetworkDrive("k:",@"\\192.168.20.35\MyShare", Type.Missing, "user1", "password1");

you can use the following code to UnMap or remove the mapping.

network.RemoveNetworkDrive("k:");

Hope this saves some time for you....
Happy Programming...

Monday, June 8, 2009

Coolite : ExtJS + ASP.Net

Every one agrees that using Ajax in ASP.Net is cool. And even cooler if you can use third party javascript/Ajax frameworks. A number of people had asked me whether there is an easy solution to use extJs framework in ASP.Net. So I thought of writing something about that here.

ExtJS is an excellent framework by itself , But a cooler way to integrate it with ASP.Net exists. Enter Coolite Toolkit. Coolite toolkit is A suite of professional ASP.NET AJAX Web Controls
built on the ExtJS JavaScript Framework. The project is in development phase and the current release [as of June 2009] is version 0.8. The control kit is dual licensed and is available in GPL and also with a commercial license.

The Library consists of a vast collection of UI components starting from buttons and datepickers to treeviews, Grid panels , Messageboxes and a Desktop control. You can see them live at Coolite Example Explorer. The controls are easy to use [you need to have a look at their examples to know how to use them and better if you can find time to read the documentation] and intuitive and they offer community help through their forum also.

Another interesting thing that i found with the library is the use of [AjaxMethod] Attribute . By using it you can call any server side method from a javascript function without any flicker/postback and the same is done using Ajax and JSON.

Do find some time to explore this toolkit.


Sunday, March 9, 2008

Send and Receive Mail from C# (SMTP and POP)


Today we shall see both sending of mails from a domain and reading mails from a domain.

Some domains wont allow mails to be send from them from an application if no mail is popped from it,ie;read from it. That means , to send a mail we first need to get pop access to the domain.Once we authenticate that we can start sending mails from that domain.

Include the following code bit in any page.

public class Pop3Exception : System.ApplicationException
{
public Pop3Exception(string str)

: base(str)
{

}
};

public class Pop3Message
{

public long number;

public long bytes;

public bool retrieved;

public string message;

};
public class Pop3 : System.Net.Sockets.TcpClient
{
public void Connect(string server, string username, string password)
{
string message;
string response;

Connect(server, 110);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

message = "USER " + username + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

message = "PASS " + password + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}
}

private void Write(string message)
{
System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding();
byte[] WriteBuffer = new byte[1024];
WriteBuffer = en.GetBytes(message);
NetworkStream stream = GetStream();
stream.Write(WriteBuffer, 0, WriteBuffer.Length);
Debug.WriteLine("WRITE:" + message);
}

private string Response()
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
NetworkStream stream = GetStream();
int count = 0;
while (true)
{
byte[] buff = new Byte[2];
int bytes = stream.Read(buff, 0, 1);
if (bytes == 1)
{
serverbuff[count] = buff[0];
count++;
if (buff[0] == '\n')
{
break;
}
}
else
{
break;
};
};
string retval = enc.GetString(serverbuff, 0, count);
Debug.WriteLine("READ:" + retval);
return retval;
}

public void Disconnect()
{
string message;
string response;
message = "QUIT\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}
}

public ArrayList List()
{
string message;
string response;

ArrayList retval = new ArrayList();
message = "LIST\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

while (true)
{
response = Response();
if (response == ".\r\n")
{
return retval;
}
else
{
Pop3Message msg = new Pop3Message();
char[] seps = { ' ' };
string[] values = response.Split(seps);
msg.number = Int32.Parse(values[0]);
msg.bytes = Int32.Parse(values[1]);
msg.retrieved = false;
retval.Add(msg);
continue;
}
}
}
public Pop3Message Retrieve(Pop3Message rhs)
{
string message;
string response;

Pop3Message msg = new Pop3Message();
msg.bytes = rhs.bytes;
msg.number = rhs.number;

message = "RETR " + rhs.number + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

msg.retrieved = true;
while (true)
{
response = Response();
if (response == ".\r\n")
{
break;
}
else
{
msg.message += response;
}
}

return msg;
}
}

Now calling PopMail(),

private static void PopMail()
{
try
{
Pop3 obj = new Pop3();
obj.Connect("pop.rediffmailpro.com", "full@email.address", "password");
ArrayList list = obj.List();
foreach (Pop3Message msg in list)
{
Pop3Message msg2 = obj.Retrieve(msg);
System.Console.WriteLine("Message {0}: {1}",
msg2.number, msg2.message);
break;
}
obj.Disconnect();
}
catch (Pop3Exception pe)
{
System.Console.WriteLine(pe.ToString());
}
catch (System.Exception ee)
{
System.Console.WriteLine(ee.ToString());
}
}

will do the tricks.

No we'll see the sending of mails.For that we use a button click event on our application.

private void _sendButton_Click(object sender, EventArgs e)
{
System.Data.Odbc.OdbcConnection connect = new System.Data.Odbc.OdbcConnection();
...
{
..
}
foreach (DataGridViewRow row in grid.Rows)
{
count++;
if (row.Cells[0].Value != null)
{
if (row.Cells[0].Value.ToString() == "True")
{
..
if (count % 300 == 0)
PopMail();
sendMail(row);
..
}
}
}
MessageBox.Show("Mails sent Successfully");
}

bool sendMail(DataGridViewRow row)
{
MailMessage message = new MailMessage();

string getToAddress = row.Cells[4].Value.ToString();
try
{
if (getToAddress == "")
message.To.Add("default@email.id");
else
message.To.Add(row.Cells[4].Value.ToString());
}
catch (Exception ex)
{
message.To.Add("default@email.id");
}
try
{
message.From = new MailAddress("emailid", "domain");
message.IsBodyHtml = true;
string messageBody = GetMessageBody(row);
message.Body = messageBody;
message.Subject = "Hi";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.rediffmailpro.com");
System.Net.NetworkCredential smtpAuthen =
new System.Net.NetworkCredential("emailid", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = smtpAuthen;
smtp.Send(message);
return true;
}
catch (SmtpException se)
{
Console.WriteLine(se.Message);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return true;
}
}

In the code you might have noticed that,the PopMail() is called in a loop during limited time interval.That is because,the authentication time expires after sending a couple of mails.So the PopMail is called after sending every 300 mails.

Hope this is useful..

Friday, March 7, 2008

Strongly Typed Dataset C#

Have you ever struggled to generate a Strongly Typed Dataset from an xml File.

Most of you guys might be knowing this technique.

This post is for my friends who dont know how to implement that.I shall explain that to you with the help of two batch files.

One for converting and xml file to its corresponding schema file,ie;xsd and next to generate its class file.

Before that..just a slight introduction.

There are generally two types of dataset.

1.Untyped Dataset
2.Typed Dataset

In an untyped dataset we access a table as,

dataSet.Tables[0]

But in a Typed Dataset it can be accessed by giving,

dataSet.TableName

ie; direct access.

There are many other features.This was just to give a slight idea.

Now we shall see the batch file to convert xml file into xsd.

Type the following code in notepad

c:
cd %VS2003DIR%\SDK\v1.1\Bin
xsd C:\xmlConverter\abc.xml /out:K:\dotnet\csharp\dialogs
pause

and
save this file as xmlToSchema.bat

Now run this batch file.

A new file called abc.xsd will be now available in K:\dotnet\csharp\dialogs

Now create the next batch file.

c:
cd %VS2003DIR%\SDK\v1.1\Bin
xsd K:\dotnet\csharp\dialogs\abc.xsd /c /out:K:\dotnet\csharp\dialogs
pause

Save this file as schemaToCS.bat

On running this file the corresponding class file for the xsd will be generated.Now if we read the xml file to a dataset, the dataset will be a typed dataset.

Very simple right? Hope this is of use to somebody or the other.

Cheers...

Sunday, March 2, 2008

Excel To SQL

Transferring Excel sheet cell values to SQL server is never a tough job now.

Here is how we can transfer all the cell contents from an excel file to a database in a single click.

private void button1_Click(object sender, EventArgs e)
{
System.Data.Odbc.OdbcConnection con = new System.Data.Odbc.OdbcConnection();
string strConnString;
strConnString = "Driver={Microsoft Excel Driver
(*.xls)};DriverId=790;Dbq=c:\\test1.xls;DefaultDir=c:\\";
con.ConnectionString = strConnString;
con.Open();
string select = "select a,x from [sheet1$]";
System.Data.Odbc.OdbcDataAdapter odbcdataAdapter = new
System.Data.Odbc.OdbcDataAdapter(select, con);
DataSet excelDataset = new DataSet();
try
{
odbcdataAdapter.Fill(excelDataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "server=abc;database=test1;uid=user;pwd=passwd;Connection Timeout=200;";
try
{
cnn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCommand cmm = new SqlCommand();
cmm.Connection = cnn;

foreach (DataRow row in excelDataset.Tables[0].Rows)
{
cmm.CommandText = "insert into testWriteTable values('" + row[0].ToString() + "','" +
row[1].ToString() + "')";
cmm.ExecuteNonQuery();
}
cnn.Close();
}

Hope this helps somebody out there.

Cheers....

Thursday, February 14, 2008

Datagridview Checkbox Select All

Though .Net allows to include Checkboxes in a datagridview,selection of all the checkboxes in a single column at once is always a tough task.I found it very tough initially.

Today I shall help you include a top Checkbox,clicking on which selection of all the checkboxes under that is possible.

public delegate void CheckBoxClickedHandler(bool state);
public class DataGridViewCheckBoxHeaderCellEventArgs : EventArgs
{
bool _bChecked;
public DataGridViewCheckBoxHeaderCellEventArgs(bool bChecked)
{
_bChecked = bChecked;
}
public bool Checked
{
get { return _bChecked; }
}
}
class DatagridViewCheckBoxHeaderCell : DataGridViewColumnHeaderCell
{
Point checkBoxLocation;
Size checkBoxSize;
bool _checked = false;
Point _cellLocation = new Point();
System.Windows.Forms.VisualStyles.CheckBoxState _cbState =
System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;
public event CheckBoxClickedHandler OnCheckBoxClicked;

public DatagridViewCheckBoxHeaderCell()
{
}

protected override void Paint(System.Drawing.Graphics graphics,
System.Drawing.Rectangle clipBounds,
System.Drawing.Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates dataGridViewElementState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex,
dataGridViewElementState, value,
formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts);
Point p = new Point();
Size s = CheckBoxRenderer.GetGlyphSize(graphics,
System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
p.X = cellBounds.Location.X +
(cellBounds.Width / 2) - (s.Width / 2);
p.Y = cellBounds.Location.Y +
(cellBounds.Height / 2) - (s.Height / 2);
_cellLocation = cellBounds.Location;
checkBoxLocation = p;
checkBoxSize = s;
if (_checked)
_cbState = System.Windows.Forms.VisualStyles.
CheckBoxState.CheckedNormal;
else
_cbState = System.Windows.Forms.VisualStyles.
CheckBoxState.UncheckedNormal;
CheckBoxRenderer.DrawCheckBox
(graphics, checkBoxLocation, _cbState);
}

protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
Point p = new Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y);
if (p.X >= checkBoxLocation.X && p.X <=
checkBoxLocation.X + checkBoxSize.Width
&& p.Y >= checkBoxLocation.Y && p.Y <=
checkBoxLocation.Y + checkBoxSize.Height)
{
_checked = !_checked;
if (OnCheckBoxClicked != null)
{
OnCheckBoxClicked(_checked);
this.DataGridView.InvalidateCell(this);
}
}
base.OnMouseClick(e);
}
}

This class needs to be included to the project to get the Header Checkbox feature.

Then the checkbox need to be added to the datagridview as a DatagridViewCheckBoxColumn.
Then we assign the header to it.
The header is assigned an event with the help of which we can uncheck or check all the checkboxes.

The code to add the checkbox to header and the corresponding event code is given below.

private void FormatGrid()
{
DataView dv = new DataView();
dv.Table = _loginDs.Tables[0];

DataGridViewCheckBoxColumn chkbox = new DataGridViewCheckBoxColumn();
DatagridViewCheckBoxHeaderCell chkHeader = new DatagridViewCheckBoxHeaderCell();
chkbox.HeaderCell = chkHeader;
chkHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(chkHeader_OnCheckBoxClicked);
_chkBoxGrid.Columns.Add(chkbox);

DataGridViewTextBoxColumn uname = new DataGridViewTextBoxColumn();
uname.HeaderText = "user";
uname.Name = "username";
uname.DataPropertyName = "username";
_chkBoxGrid.Columns.Add(uname);

_chkBoxGrid.DataSource = dv;
}

void chkHeader_OnCheckBoxClicked(bool state)
{
foreach (DataGridViewRow row in _chkBoxGrid.Rows)
row.Cells[0].Value = state;
}

In the checkbox header clicked event,any conditions might be added to select only the needed rows..

I hope you'll have a good time working with the new header for checkboxes. :)

Monday, February 11, 2008

Creating Windows Service



This example was created soon after I made a windows service as I got to have several doubts myself when creating one. Thought this might be of help to someone or the other.

I have included necessary images for all the stages. Hope that helps.

Starting off. Take new project.


Take windows service and give proper name to it.

Initially service page looks like

Take properties of service page.

Change name and service name to project name

Add eventlog to service page by taking the toolbox and adding eventlog to it.

Now take code and add the following lines of code to the service1.cs page.

now right click on the service design page and add installer to it

Take serviceprocessInstaller1 properties

Change account type to local system or local service

I’ve changed type to local system here.

Now right click on service installer and take properties

Change start type to automatic.

Now the properties page look like,

Now build the project.

On successful build add a setup to the project.

Right click on the setup project and add the project output to it

and click ok.

Now right click on the setup project and take view-> custom actions

Now right click on custom actions and select add custom action.

Double click on application folder and Add primary output.

Click ok.

Now the installer custom actions look like

Now build setup

Now right click on setup and install

Now take services from administrative tools to start the service

From services select our project name and right click that to select start of the service.

Once the dialog box closes the service will be started. To track the service details take server explorer from vs.net

In that take the corresponding source from event logs.It will show our message “Service Started”.

If you right click on the WindowsServiceExample in services and stop it.Then the corresponding message will be shown there in server explorer.

Hope I was clear.So happy programming.