Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

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...

Sunday, October 17, 2010

Multiline Textbox Character Limit

Giving character limit to a multiline textbox can be done using a regular expression validator. Add a regular expression validator to theaspx page and set the control to validate as the multiline text box. Then in the validation expression give

^[\s\S]{0,2000}$
This solution limits the character length to 2000 characters including blank spaces and tabs.

Cheers

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...