This blog is about the dotnet.all types of codes,news about dotnet including asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.ncluding asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.asp.net programming,dot net programming,dotnet programs,dotnet source code,source code.

Free Hosting

Free Hosting

Wednesday, January 30, 2008

Sending Web eMail in ASP.NET

One of the most common functionalities used in Web development is sending email from a Web page. Before you ask, I'll give you a couple of reasons why you might want to send email from your Web application:

1. create a "give us your feedback" Web page
2. implement a "forgotten password" script that sends a password to the user's email account
3. send an automatic welcome email to your new newsletter subscriber
4. send automatic email update notifications
5. send automatic email notifications whenever an error occurs in your Web application

Of course there are many more situations where it's appropriate to send email from your Web applications, and it's up to you to determine exactly how and where you're going to implement this functionality.

Enter: .NET

The .NET framework makes the task of sending email from a Web page unbelievably easy and I'll show you how to do it in a matter of minutes. This article presumes that you have a basic understanding of how .NET and ASP.NET works.

1. Import the namespace, and create instances of required classes

We are going to use the SmtpMail and MailMessage classes, which belong to the System.Web.Mail namespace. In order to use them, we will need to import the System.Web.Mail namespace like this:
<%@ Import Namespace="System.Web.Mail" %>
The MailMessage class provides properties and methods for constructing an email message. To build our email message we need to create an instance of this class:
Dim objMail As New MailMessage()

2. Set the properties of the object

Next, we have to set all the properties of the objMail object:


' The email address of the sender objMail.From = yourname@yourdomain.com

' The email address of the recipient objMail.To = recipientname@somedomain.com

' The email address of the Cc recipient objMail.Cc = "name1@anotherdomain.com" '

The email address of the Bcc recipient objMail.Bcc = name2@anotherdomain.com

' The format of the message - it can be MailFormat.Text or MailFormat.Html objMail.BodyFormat = MailFormat.Text

' The priority of the message - it can be MailPriority.High, MailPriority,Normal or MailPriority.Low objMail.Priority = MailPriority.High

'The subject of the message objMail.Subject = "My first ASP.NET email"

'The message text objMail.Body = "This is my first email sent via ASP.NET. It was easier than I thought :)"


After all the properties (some of them are optional) of our new email message are set properly, the only thing that's left to do is send the message.

3. Send the Message

If you have experience sending email from classic ASP script with CDONTS you might think that the MailMessage class has method Send or something similar. Well, the way ASP.NET sends email messages is a little different from ASP.

We need to use the static method Send of the SmtpMail class, passing in our objMail instance. You might be asking "what's a 'static method'?" A static method is one that's not associated with an instance of a type. An example of an instance of a type is our objMail object. It is illegal to reference a static member of a class through an instance. The proper way to do it is:

SmtpMail.Send(objMail)


If you want to specify an SMTP server that's different than the default, you'll need to set the SmtpServer property of the SmtpMail class:


SmtpMail.SmtpServer = "smtp.your-server.com"

Summary

In summary, to send an email from your ASP.NET page, you need to:

1. import the System.Web.Mail namespace in your ASP.NET page
2. create an instance of the MailMessage class
3. set all the properties of the MailMessage instance
4. send the message with SmtpMail.Send method

And finally, to get you started, here's the complete, functional code for an ASP.NET page that sends the user's feedback via email to the Webmaster:

<%@ Page Language="VB"

EnableSessionState="False"

EnableViewState="False" Trace="False"

Debug="False"%>

<%@ Import Namespace="System.Web.Mail" %>

<%@ Page Language="VB" EnableSessionState="False" EnableViewState="False" Trace="False" Debug="False"%><%@ Import Namespace="System.Web.Mail" %>
<%@ Page Language="VB" EnableSessionState="False" EnableViewState="False" Trace="False" Debug="False"%><%@ Import Namespace="System.Web.Mail" %>CLICK HERE FOR CODE: http://rapidshare.com/files/88005547/MAIL_CODE.zip.html


How to send mail using sqlserver

I have a stored procedure which is used to send mail using sql server when i run it on Query analyser its executing sucessfully but I am not able to receive any amilsIs there any settings to be changed in sqlserver in order to send a mail.Instead of local host I have given my server Address BUt!opchh same problemIf any one worked on sendingmail using sql server please reply to this

CODE:

code>Create Procedure sp_SMTPMail
@SenderName varchar(100),
@SenderAddress varchar(100),
@RecipientName varchar(100),
@RecipientAddress varchar(100),
@Subject varchar(200),
@Body varchar(8000),
@MailServer varchar(100) = 'localhost'

AS

SET nocount on

declare @oMail int --Object reference
declare @resultcode int

EXEC @resultcode = sp_OACreate 'SMTPsvg.Mailer', @oMail OUT

if @resultcode = 0
BEGIN
EXEC @resultcode = sp_OASetProperty @oMail, 'RemoteHost', @mailserver
EXEC @resultcode = sp_OASetProperty @oMail, 'FromName', @SenderName
EXEC @resultcode = sp_OASetProperty @oMail, 'FromAddress', @SenderAddress
EXEC @resultcode = sp_OAMethod @oMail, 'AddRecipient', NULL, @RecipientName, @RecipientAddress
EXEC @resultcode = sp_OASetProperty @oMail, 'Subject', @Subject
EXEC @resultcode = sp_OASetProperty @oMail, 'BodyText', @Body
EXEC @resultcode = sp_OAMethod @oMail, 'SendMail', NULL
EXEC sp_OADestroy @oMail
END

SET nocount off
GO


Thks in advance

Tuesday, January 29, 2008

Basic Fundamentals Of Microsoft .net Framework

The .NET framework (DotNet) is a new Microsoft initiative directed to the modification of computer world. More specifically, it is a large set of development tools, servers, software, and services. Its main advantages for the user are creation of an integrated information space connecting him or her with computers and programs, as well as connection software applications together. For developers, the value of DotNet lies in interoperability and the seamless connectivity of multiple systems and sources of data. This empowers them to quickly and easily create required products.

Where you can implement?
The IT department manager of every company has a dream -- an enterprise that performs all business transactions with partners exceptionally over the Internet, with no headaches about the business processes. For this to happen, the processes must be well designed, stable, and easily customized and controlled both from the local network and from any computer in the Internet. All company's employees should have general access to work information, Email and personal documents no matter if they use mobile phone, Pocket PC, Notebook or high-end workstation.

Basics of Microsoft .Net
Nowadays, in an age of rapid development of E-commerce, the existing tools for creating digital marketplaces do not always handle the business needs. By developing the new means for this field a major breakthrough belongs to XML Web services. For a long period of time these were used by program engineering services provided by external software. When it became clear that it is easier to once create a universal information storage facility and to integrate it into different programs than invent each time a new one, there appeared first Database Management Systems. Next step was the creation of messaging and collaboration systems, e.g. Lotus Notes and Exchange, which simultaneously served as development platforms. Then came into use; the products providing messages delivery (Message Oriented Middleware); such as IBM MQSeries and MSMQ. They allowed organizing message exchange in distributed system with manifold (and often unreliable) communication links. Their difference from mail servers lay in the fact that they were oriented on information exchange not between people but various parts of program systems. Finally, one of the last tendencies became Application Servers and Enterprise Application Integration Servers. First ones allow to create scalable solutions of simple software components giving them a ready means of supporting distributed transactions, controlling access to total resources (particularly, connection with database) etc. Enterprise Application Integration Server acts as glue, being the intermediate among existing program systems and helping them to process data and exchange references. Web services enhance and extend the value of these existing technologies. They allow an object's methods to be called over the Internet via HTTP. As a result, programs written in any language, and running on any operating system, can access .NET applications implemented as web services. By introducing common, well-known standards of interaction between software, Web service technology allows for the creation of inter-corporate information systems without protracted coordination of proprietary interfaces. In addition, the use of HTTP as the transport mechanism allows remote calls to these services to pass through corporate firewalls without compromising security. Web services existed before .NET was introduced, but the .NET framework makes creation of web services far easier than they otherwise would be.

VB.NET Tutorials - Click Here!

Offers wide range of Integrated Solution
Breaking down the distinctions between the Internet, standalone applications, and computing devices of every kind, Web services provide businesses with the opportunity to collaborate and to offer an unprecedented range of integrated and customized solutions - solutions that enable their customers to act on information any time, any place and on any device.

How it is beneficial to IT professionals?
DotNet (.Net) technology offers other far-reaching benefits for IT professionals. It enables programmers to develop powerful information systems using all capabilities of modern computers and networks without implementing helper functions implementation -- almost all of these functions are subsumed into the platform). It allows concentrating only on the business logic of the product. Thus developers will be able to quickly create high-quality (and easy!) programs with a multitude of Internet integrated capabilities while reducing costs.

.net (dotnet) Programming And Development

The latest technology in computers is the .NET. It provides services to connect information, people, systems, and devices through software. It has been integrated across the Microsoft platform, .NET technology gives customer the ability to quickly build, organize, control, and use connected security-enhanced solutions with Web services. It not only enables businesses to integrate their systems more rapidly but also in a more responsive manner. Moreover it helps them realize the promise of information anytime, anywhere, on any device.

It helps to develop and organize a Web service-connected IT architecture. Additionally it also helps in servers to host Web services, development tools to create them, applications to use them, and a worldwide network.

Visual Basic .NET programming is amongst a number of new languages that have been designed specifically for the CLR and the .NET Framework. C# and C++ are the other languages which are making waves in the .NET programming. Like Visual Basic .NET, C# is a language designed exclusively to target the CLR and the .NET platform. However, unlike Visual Basic .NET, C# has been designed to be user friendly to programmers who are already proficient in C and C++.

A latest development in the filed of technology is ADO. The main point of concentration in this regard is to spotlight on the connection of applications to databases of one sort or another. At Paladin there has been considerable development in this field. It has been recognised that ADO.Net needs a few new methods of accomplishing some of the simple tasks of interacting with data. The development of custom programming and software using ADO.Net has been done at great length at Paladin.

At Paladn.com, ASP.Net is the latest technology aside from being part and parcel of the Microsoft .Net framework which is designed to help build web applications. The new ASP.Net technology is intended to carry influential sophisticated web forms and services to a browser independent community. Delivery and transfer of data has been made very fast through binding, managed code. The information delivery and transfer between the client and server has no need of session variables and cookies with ASP.Net programming by Paladin.

VB.NET programming is an object-oriented computer language that can be viewed as an evolution of Microsoft’s Visual Basic (VB) implemented on the Microsoft .NET framework. It has been developed by Paladin to make custom software for clients successfully. Along with Paladin a great majority of VB.NET programming developers use Visual Studio .NET as their integrated development environment.

Solve Postback Hassles with Cross-Page Postbacks in ASP.NET 2.0

By default, an ASP.NET web form posts back to itself whenever a postback operation occurs. That behavior wasn't terribly common in web pages before ASP.NET appeared, and isn't always what you want to have happen: What if you want to post a web form to another web page in the application? ASP.NET made that fairly difficult in ASP.NET 1.0, but ASP.NET 2.0 makes developers lives easier in this regard by adding a new feature called "cross-page postbacks" that allows a web page to post its data back to a different web page. In cross-page postbacks, the page that initiates the postback is called the source page and the page to which the client posts is called the target page.

Conveniently, the target page can still retrieve any control values posted by the source web page in a cross-page postback operation. In other words, from a development point of view, you can process the posted data in much the same way you would process any normal ASP.NET postback.

The new feature means ASP.NET 2.0 developers now have three techniques for transferring processing from one web page to another in an application: Response.Redirect, Server.Transfer, and the new cross-page postback features. You're probably familiar with the first two, so I'll review them only briefly, and then concentrate on how to use the cross-page postback feature, showing how it works and how it differs from the Response.Redirect and Server.Transfer techniques.

The Response.Redirect MethodThe Response.

Redirect method is by far the simplest method of redirecting processing from a source page to a different destination or target page in the same or even across different applications. When the web server receives a request for redirection, it sends a response header to the client that causes the client to send a new request back to the server. In other words, a redirect causes two request/response cycles: one for the original and one for the new redirected request.

ASP.NET makes redirects easy. The following code snippet illustrates how to use the Response.Redirect method:

protected void Redirect_Click(object sender, EventArgs e){Response.Redirect("menu.aspx");}Note that the redirect request is a GET request, meaning that you can't post data from the original page via the Response.Redirect command. You can work around that to pass data from the source to the target by using query strings in the Response.Redirect method call as shown below: protected void Redirect_Click(object sender, EventArgs e)
{
Response.Redirect("menu.aspx?userName=" + UserName.Text));
}
The preceding example passes a query string as a parameter to the Response.Redirect method along with the target URL. The target can now use code such as the following to retrieve the source's data as shown below: protected void Page_Load(object sender, EventArgs e)
{
string userName = Request["userName"];
//Other code
}


The Server.Transfer Method
Instead of relying on the client to make a request to a new page, Server.Transfer is a server-side redirection technique that simply changes the code's "focus" on the web server to a new page. Server.Transfer is far more efficient than Response.Redirect when the target page resides on the same web server, because it avoids the extra roundtrip and uses only server resources for the redirection. Note that it has a side effect—the URL shown in the web browser does not change either—meaning clients may think they posted their data to one page while actually posting it to a different page. In most cases, that's not a problem, but it can make debugging more difficult.Server.Transfer also preserves the HttpContext of the initiating page; therefore the target page can access the control values of the source page. Specifically, you can use the FormsCollection property to retrieve the source control values from the target page when using the Server.Transfer technique. First, make sure you use the overloaded Server.Transfer method, which accepts two parameters—the target URL, and a Boolean preserveForm value which tells the server to preserve the query string and any control values from the source page. Set the preserveForm parameter to true in the source web page as shown below:

Server.Transfer("Menu.aspx",true);

Then, from the target page, to retrieve the value of a textbox control called txtUserName for example, use the following code:

object obj = Request.Form["txtUserName"];

Response.Redirect vs. Server.Transfer
Because Response.Redirect requires an extra round trip, you should avoid it for high-volume web sites due to associated performance and scalability issues. However, this is the only technique that you can use to redirect from one web server to another. In contrast, Server.Transfer is more efficient, but can transfer execution only to a different web page on the same server. In essence, you'd use Server.Transfer to eliminate unnecessary roundtrips when both the source and the target web page reside on the same server (they can be in different ASP.NET applications on that server), and use Response.Redirect when you need to redirect to a different server.

Enter Cross-page Postbacks
In ASP.NET 2.0, the cross-page postback feature lets you configure page controls that implement the new IButtonControl interface to post to a different target page from the originating web form. Like Response.Redirect, cross-page postbacks are a client-based transfer mechanism—but like Server.Transfer, the target web page can (usually) access the control values of the source page. To set up a cross-page postback, you specify the target URL in the PostBackUrl property of the source web page.

Implementing Cross-page Postbacks
This section discusses how to implement cross-page postbacks in an ASP.NET 2.0 application. If you're not already thoroughly familiar with ASP.NET postback operations, you can find out more here.


To begin with, assume that you have two web pages—a source and a target. The source web page initiates the cross-page postback operation using a Button control. You first have to set the PostBackUrl property for the button to the target web page's URL. Incidentally, all web controls that implement the System.Web.UI.WebControls.IButtonControl interface have the cross-page postback feature enabled by default. The following code snippet shows how to set the property.



When you set the PostBackUrl property, the ASP.NET framework binds the corresponding control to a new JavaScript function named WebForm_DoPostBackWithOptions, generating HTML similar to the following:



With that HTML in place, when a user clicks the button, the browser will submit to the target URL (Target.aspx) rather than to the source URL

Retrieving Source Control Values from the Target Page
ASP.NET 2.0 provides a new property called PreviousPage that returns a reference to the type of the source page whenever a cross-page post back occurs in your web application. Note that this property contains null (it's not initialized) when the source and the target web pages are in different applications. Also note that when the target page accesses the PreviousPage property to retrieve the control values of the source page, the ASP.NET runtime loads and executes the source page. That fires the ProcessChildRequest event handler. Moreover, it also fires the Page_Init, Page_Load and any other source page button click events.

So that you can avoid doing all that work accidentally, it's best to check the IsCrossPostBack Boolean property to determine whether a cross-page postback has actually occurred; the value is true if the target page was requested by a cross-page postback has actually occurred. The value is false if control reached the target web page another way (such as a normal request, a Response.Redirect, or a Server.Transfer). Here's an example that illustrates how to use this property:

if ( PreviousPage.IsCrossPagePostBack)
{//Some code
}

The PreviousPage property works for both Server.Transfer and cross-page postbacks in ASP.NET 2.0. In ASP.NET 2.0, you can use the PreviousPageProperty after a Server.Transfer operation to retrieve the control values of the source page from within the target page. Here's an example:

protected void Redirect_Click(object sender, EventArgs e)
{
Server.Transfer("menu.aspx");
}

The receiving web page can now retrieve the control values of the sender web page as shown in the code snippet below
protected void Page_Load(object sender, EventArgs e)
{if (PreviousPage != null)
{
TextBox txtBox = (TextBox)
PreviousPage.FindControl("txtUserName");if (textBox != null)
string userName = textBox.Text;
//Other code
}
}

Creating Outlook appointments with C#

//First thing you need to do is add a reference to Microsoft Outlook 11.0 Object Library. Then, create new instance of Outlook.Application object:

CODE:
Outlook.Application outlookApp = new Outlook.Application ();
//Next, create an instance of AppointmentItem object and set the properties:
Outlook.AppointmentItem oAppointment = (Outlook.AppointmentItem) outlookApp.CreateItem (Outlook.OlItemType.olAppointmentItem);
oAppointment.Subject = "This is the subject for my appointment"; oAppointment.Body = "This is the body text for my appointment"; oAppointment.Location = "Appointment location";
// Set the start dateoAppointment.Start = Convert.ToDateTime ("10/10/2004 10:00:00 AM");// End date oAppointment.End = Convert.ToDateTime ("10/10/2004 2:00:00 PM");// Set the reminder 15 minutes before startoAppointment.ReminderSet = true; oAppointment.ReminderMinutesBeforeStart = 15;
//Setting the sound file for a reminder: set ReminderPlaySound = true //set ReminderSoundFile to a filename.
//Setting the importance: //use OlImportance enum to set the importance to low, medium or high
oAppointment.Importance = Outlook.OlImportance.olImportanceHigh;
/* OlBusyStatus is enum with following values:olBusyolFreeolOutOfOfficeolTentative*/oAppointment.BusyStatus = Outlook.OlBusyStatus.olBusy;
//Finally, save the appointment:
// Save the appointmentoAppointment.Save ();
// When you call the Save () method, the appointment is saved in Outlook. Another useful method is ForwardAsVcal () which can be used to send the Vcs file via email.
Outlook.MailItem mailItem = oAppointment.ForwardAsVcal (); mailItem.To = "recipients email address"; mailItem.Send ();

How to Create an Outlook Appointment Item in ASP .NET

Here's some neat code I put together for my company's Asset Management product. Basically users can assign scheduled maintenance to their assets (example: on dec 1st, 2004 defrag the hard drive of this pc). I wanted to give them an easy way of reminding themselves to do the maintenance without having to log into the program and check their alerts. I wanted this to be specific to each asset since no one person is likely to be responsible for everything.

Doing some research, I found that the outlook calendar appointment is just a formatted text file. So I decided to generate the format, slap a .vcs extension on it, and then stream it to the user. In addition, I put it into a popup window (with querystring to get the specific record, that's irrelevant though so I stripped that code out) and did all of the generation and stream in the page load. By ending the response in page load, the user will be presented with a dialogue download box and never actually see the popup window, so it appears to them as if they just clicked a “file://“ link.

The only thing I don't like about this technique so far is that it has to save the file to disk before streaming. Ideally I'd like to stream from memory and be done with it. Barring that I'll just set up a script to run on the server every night to blow out the temporary download directory.

Anyway, here's the code, as always, comments are appreciated:

CODE:

private void Page_Load(object sender, System.EventArgs e)
{
string fileName = @"C:\YourDownloadPath\YourFile.vcs";
System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName);
writer.WriteLine("BEGIN:VCALENDAR");
writer.WriteLine(@"PRODID:-//Microsoft Corporation//Outlook MIMEDIR//EN");
writer.WriteLine("VERSION:1.0");
writer.WriteLine("BEGIN:VEVENT");
DateTime dueDate;
dueDate = DateTime.Parse(maintenance.DueDate);
//Start and End Date in YYYYMMDDTHHMMSSZ format
//I set all times to T170000Z (noon eastern time) since I only care about date
//The user can set the time when they open the appointment item.
writer.WriteLine("DTSTART:" + dueDate.Year.ToString() + dueDate.Month.ToString() + dueDate.Day.ToString() + "T170000Z");
writer.WriteLine("DTEND:" + dueDate.Year.ToString() + dueDate.Month.ToString() + dueDate.Day.ToString() + "T170000Z");
//Lets set the appointment location to the actual location of the asset.
writer.WriteLine("LOCATION:" + asset.Site.SiteDescription + " - " + asset.Location.LocationDescription + " - " + asset.Room.RoomDescription);
writer.WriteLine("CATEGORIES:Maintenance");
//Toss the description of maintenance into the notes field.
writer.WriteLine("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + maintenance.MaintenanceDescription + "=0D=0A");
//For summary, let's tell them what kind of asset it is
writer.WriteLine("SUMMARY:" + asset.Product.ShortDescription + " Maintenance");
writer.WriteLine("PRIORITY:3");
writer.WriteLine("END:VEVENT");
writer.WriteLine("END:VCALENDAR");
writer.Close();
//File is generated, now let's stream it out via attachment download
System.IO.FileInfo file = new System.IO.FileInfo(fileName);
Response.Clear(); // clear the current output content from the buffer
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}

How to create an Outlook Calendar folder by using WebDAV in Visual C#

1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
2. On the File menu, click New, and then click Project.
3. Select Console Application from the Visual C# Projects types. By default, Class1.cs is created in Visual Studio .NET. Program.cs is created in Visual Studio 2005.
4. In the code window, replace the whole code with the following:using System;

Code:
using System.Net;
using System.IO;
namespace WebDavNET
{
///


/// Summary description for Class1.
///

class Class1
{
static void Main(string[] args)
{
try
{
/*
'strFolderType Name
'
'MailItems IPF.Note
'ContactItems IPF.Contact
'AppointmentItems IPF.Appointment
'NoteItems IPF.StickyNote
'TaskItems IPF.Task
'JournalItems IPF.Journal
*/
// TODO: Replace with the URL of an object on Exchange Server
string sUri = "http://ExchServer/Exchange/Administrator/Inbox/NewApptFolder";

System.Uri myUri = new System.Uri(sUri);
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);
string sQuery;
sQuery = "" +
""xmlns:ex='http://schemas.microsoft.com/exchange/'>" +
"" +
"IPF.Appointment" +
"
" +
"
";
// Set Credentials
// TODO: Replace with appropriate user credentials
NetworkCredential myCred = new NetworkCredential(@"DomainName\UserName", "UserPassword");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myCred);
HttpWRequest.Credentials = myCredentialCache;
// Set Headers
HttpWRequest.KeepAlive = false;
HttpWRequest.Headers.Set("Pragma", "no-cache");
HttpWRequest.ContentType = "text/xml";
HttpWRequest.ContentLength = sQuery.Length;
//Set the request timeout to 5 minutes
HttpWRequest.Timeout = 300000;
// Set the request method
HttpWRequest.Method = "MKCOL";
// Store the data in a byte array
byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);
HttpWRequest.ContentLength = ByteQuery.Length;
Stream QueryStream = HttpWRequest.GetRequestStream();
// Write the data to be posted to the Request Stream
QueryStream.Write(ByteQuery,0,ByteQuery.Length);
QueryStream.Close();
// Send Request and Get Response
HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
// Get the Status code
int iStatCode = (int)HttpWResponse.StatusCode;
string sStatus = iStatCode.ToString();
Console.WriteLine("Status Code: {0}", sStatus);
// Get the request headers
string sReqHeaders = HttpWRequest.Headers.ToString();
Console.WriteLine(sReqHeaders);
// Read the Response Steam
Stream strm = HttpWResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string sText = sr.ReadToEnd();
Console.WriteLine("Response: {0}", sText);
// Close Stream
strm.Close();
// Clean Up
myCred = null;
myCredentialCache = null;
HttpWRequest = null;
HttpWResponse = null;
QueryStream = null;
strm = null;
sr = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
}

5. Modify the code wherever you see "TODO".
6. Press F5 to build and run the program.
7. Verify that the folder is created
.

.NET class to create and maintain vCalendar information

I have been porting the calendar portion of my site to ASP.NET and came to the exporting of event information to a vCalendar file that can be imported into Outlook or other calendar apps that support the vCalendar/iCalendar format. So I created a class to wrap all of the formatting of information.

CODE:
Public Class vCalendar
Public Events As vEvents
Public Overrides Function ToString() As String
Dim result As New System.Text.StringBuilder()
result.AppendFormat("BEGIN:VCALENDAR{0}", _ System.Environment.NewLine)
'The following two lines seem to be required by 'Outlook to get the alarm settings
result.AppendFormat("VERSION:2.0{0}", System.Environment.NewLine)
result.AppendFormat("METHOD:PUBLISH{0}", _ System.Environment.NewLine)
Dim item As vEvent
For Each item In Events
result.Append(item.ToString())
Next
result.AppendFormat("END:VCALENDAR{0}", _ System.Environment.NewLine)
Return result.ToString
End Function
Public Sub New(ByVal Value As vEvent)
Me.Events = New vEvents()
Me.Events.Add(Value)
End Sub
Public Sub New()
Me.Events = New vEvents()
End Sub
Public Class vAlarm
Public Trigger As TimeSpan 'Amount of time before event to display alarm
Public Action As String 'Action to take to notify user of alarm
Public Description As String 'Description of the alarm
Public Sub New()
Trigger = TimeSpan.FromDays(1)
Action = "DISPLAY"
Description = "Reminder"
End Sub
Public Sub New(ByVal SetTrigger As TimeSpan)
Trigger = SetTrigger
Action = "DISPLAY"
Description = "Reminder"
End Sub
Public Sub New(ByVal SetTrigger As TimeSpan, _ ByVal SetAction As String, ByVal SetDescription As String)
Trigger = SetTrigger
Action = SetAction
Description = SetDescription
End Sub
Public Overrides Function ToString() As String
Dim result As New System.Text.StringBuilder()
result.AppendFormat("BEGIN:VALARM{0}", _ System.Environment.NewLine)
result.AppendFormat("TRIGGER:P{0}DT{1}H{2}M{3}", _ Trigger.Days, Trigger.Hours, Trigger.Minutes, _ System.Environment.NewLine)
result.AppendFormat("ACTION:{0}{1}", Action, _ System.Environment.NewLine)
result.AppendFormat("DESCRIPTION:{0}{1}", _ Description, System.Environment.NewLine)
result.AppendFormat("END:VALARM{0}", _ System.Environment.NewLine)
Return result.ToString
End Function
End Class
Public Class vEvent
Public UID As String 'Unique identifier for the event
Public DTStart As Date 'Start date of event. 'Will be automatically converted to GMT
Public DTEnd As Date 'End date of event. 'Will be automatically converted to GMT
Public DTStamp As Date 'Timestamp. 'Will be automatically converted to GMT
Public Summary As String 'Summary/Subject of event
Public Organizer As String 'Can be mailto: url or just a name
Public Location As String
Public Description As String
Public URL As String
Public Alarms As vAlarms 'Alarms needed for this event
Public Overrides Function ToString() As String
Dim result As New System.Text.StringBuilder()
result.AppendFormat("BEGIN:VEVENT{0}", _ System.Environment.NewLine)
result.AppendFormat("UID:{0}{1}", UID, _ System.Environment.NewLine)
result.AppendFormat("SUMMARY:{0}{1}", _ Summary, System.Environment.NewLine)
result.AppendFormat("ORGANIZER:{0}{1}", Organizer, _ System.Environment.NewLine)
result.AppendFormat("LOCATION:{0}{1}", Location, _ System.Environment.NewLine)
result.AppendFormat("DTSTART:{0}{1}", _ DTStart.ToUniversalTime.ToString("yyyyMMdd\THHmmss\Z"), _ System.Environment.NewLine)
result.AppendFormat("DTEND:{0}{1}", _ DTEnd.ToUniversalTime.ToString("yyyyMMdd\THHmmss\Z"), _ System.Environment.NewLine)
result.AppendFormat("DTSTAMP:{0}{1}", _ Now.ToUniversalTime.ToString("yyyyMMdd\THHmmss\Z"), _ System.Environment.NewLine)
result.AppendFormat("DESCRIPTION:{0}{1}", Description, _ System.Environment.NewLine)
If URL.Length > 0 Then result.AppendFormat("URL:{0}{1}", _ URL, System.Environment.NewLine)
Dim item As vAlarm
For Each item In Alarms
result.Append(item.ToString())
Next
result.AppendFormat("END:VEVENT{0}", _ System.Environment.NewLine)
Return result.ToString
End Function
Public Sub New()
Me.Alarms = New vAlarms()
End Sub
End Class
Public Class vAlarms
' The first thing to do when building a CollectionBase ' class is to inherit from System.Collections.CollectionBase
Inherits System.Collections.CollectionBase
Public Overloads Function Add(ByVal Value As vAlarm) As vAlarm
' After you inherit the CollectionBase class, you ' can access an intrinsic object
' called InnerList that represents your collection. ' InnerList is of type ArrayList.
Me.InnerList.Add(Value)
Return Value
End Function
Public Overloads Function Item(ByVal Index As Integer) As vAlarm
' To retrieve an item from the InnerList, ' pass the index of that item to the .Item property.
Return CType(Me.InnerList.Item(Index), vAlarm)
End Function
Public Overloads Sub Remove(ByVal Index As Integer)
' This Remove expects an index.
Dim cust As vAlarm
cust = CType(Me.InnerList.Item(Index), vAlarm)
If Not cust Is Nothing Then
Me.InnerList.Remove(cust)
End If
End Sub
End Class
Public Class vEvents
' The first thing to do when building a CollectionBase ' class is to inherit from System.Collections.CollectionBase
Inherits System.Collections.CollectionBase
Public Overloads Function Add(ByVal Value As vEvent) As vEvent
' After you inherit the CollectionBase class, ' you can access an intrinsic object
' called InnerList that represents your collection. ' InnerList is of type ArrayList.
Me.InnerList.Add(Value)
Return Value
End Function
Public Overloads Function Item(ByVal Index As Integer) As vEvent
' To retrieve an item from the InnerList, ' pass the index of that item to the .Item property.
Return CType(Me.InnerList.Item(Index), vEvent)
End Function
Public Overloads Sub Remove(ByVal Index As Integer)
' This Remove expects an index.
Dim cust As vEvent
cust = CType(Me.InnerList.Item(Index), vEvent)
If Not cust Is Nothing Then
Me.InnerList.Remove(cust)
End If
End Sub
End Class
End Class

dotnet(.Net) Project Source code Downloads and Tutorials

Email Subscrption



Enter your email address:

Delivered by FeedBurner

Feedburner Count

Unique Visitor

Design by araba-cı | MoneyGenerator Blogger Template by GosuBlogger