Saturday, October 10, 2009
Directive Syntax @ Control
The @Control directive is used in an Asp.Net user controls. The @Control directive helps us to define control-specific attributes to be used by the ASP.NET control parser and compiler Hence it can be used only with .ascx (User Control) files.
The attributes of @Control directives are
a. Language: This Attribute is same as we read in the Page directive.
Value: Is a valid string which can represent any .NET-supported language, including VB || C# || Pearl || Jscript || any other .NET
Purpose: Tell the compiler about the language being used in the code-behind file.
b. AutoEventWireup: This Attribute is same as we read in the Page directive.
Value: Can be true || False. By Default value is true.
Purpose: For every page in a .net website there is an automatic way to bind the events to their corresponding methods in the same .ascx file and code behind.
c. CodeFile: This Attribute is same as we read in the Page directive.
Value: Any string which specifies the name of the code-behind file.
Purpose: Specifies the associated code-behind file of the page.
d. EnableViewState: This Attribute is same as we read in the Page directive.
Value: True || False The default is true.
Purpose: Tells whether view state is maintained across page requests. true to maintain view state is; otherwise, false.
e. Inherits: This Attribute is same as we read in the Page directive.
Value: any string
Purpose: Specifies a code-behind class name which the page will inherit. It can be any class which inherits the Page class.
f. Debug:
Value: Can be true || false
Purpose: This value indicates that the page should compile with debug symbols or without debug symbols.
g. Src:
Value: Any Valid String
Purpose: Tells the source file of the class i.e the file used as the code behind file of this user control.
The other attributes which we rarely use are ClassName, CompilerOptions, ComplieWith, Description, EnableTheming, Explicit, LinePragmas, Strict and WarningLevel.
An example of how a @Control directive looks
For more details Visit MSDN
Directive Syntax Page
Directives are instructions used to specify settings (related to how a page should render and processed) used by the page and user control compilers when they process ASP.NET Web Forms page (.aspx) and user control (.ascx) files. These are the essential part of every ASP.NET Page or Control.
Directives can be located anywhere in an .aspx or .ascx file, but the standard practice is to include them at the beginning of the file (The advantage of using them at the top or the beginning of the file is that we need not to search them through out the file to make any minor change). Each directive can contain one or more attributes (paired with values, same as any HTML tag) that are specific to that directive.
Special Note:
The @ Page directive can be used only in .aspx files, and the @ Control directive can be used only in .ascx files.
The ASP.NET framework supports 11 types of directives and they are as follows.
@ Page: Can be included only in .aspx files. It defines page-specific attributes used by the ASP.NET page parser and compiler. Every .aspx files should include this @Page directive to execute. Throwing some light on important attributes of page directive
a. AspCompat:
Value: true || false. By Default even if we don’t specify the value for AspCompat, it is set to false.
Purpose: Setting it to true will allow to the page to be executed on a single-threaded scenario.
For Example: The main cause when we set it to true is when we intend to use a component which was developed in VB 6.0; we can set this value to True.
Caution: Setting this attribute to true can cause page’s performance to degrade.
b. Language:
Value: Is a valid string which can represent any .NET-supported language, including VB, C#, Pearl, Jscript any other .NET
Purpose: Tell the compiler about the language being used in the code-behind file.
c. AutoEventWireup:
Value: Can be true || False. By Default value is true.
Purpose: For every page in a .net website there is an automatic way to bind the events to their corresponding methods in the same .aspx file and code behind.
d. CodeFile:
Value: Any string which specifies the name of the code-behind file.
Purpose: Specifies the associated code-behind file of the page.
e. Title:
Value: Any String
Purpose: To set the page title, if it is different from what is specified in the master page.
f. Culture:
Value: string containing the culture value or auto.
Purpose: To specifies the culture setting of the page. If set to auto; it enables the page to automatically detect the culture required for the page.
g. ValidateRequest:
Value: True ||False The default is true.
Purpose: Indicates whether request validation should occur or not. In case of true, request validation checks all input data against a hard-coded list of potentially dangerous values. In case they match, an HttpRequestValidationException Class is thrown.
This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.
h. Theme:
Value: any string
Purpose: To specify the theme for the page. This feature is introduced in Asp.Net 2.0.
i. SmartNavigation:
Value: True ||False The default value is false
Purpose: Specifies that the page should use smart navigation feature or not. Smart Navigation Feature enables a page to save the position after a postback. i.e. the page will returns the postback to current position of the page.
j. MasterPageFile:
Value: any String
Purpose: Specifies the location of the MasterPage file to be used with the current Asp.Net (.aspx) page.
k. EnableViewState:
Value: True ||False The default is true.
Purpose: Tells whether view state is maintained across page requests. true to maintain view state is; otherwise, false.
l. ErrorPage:
Value: Any string in URL format
Purpose: Specifies a target URL for redirection in case of an unhandled page exception occurs.
m. Inherits:
Value: any string
Purpose: Specifies a code-behind class name which the page will inherit. It can be any class which inherits the Page class.
There are also other attributes which are of seldom use such as Buffer, CodePage, ClassName, EnableSessionState, Debug, Description, EnableTheming, EnableViewStateMac, TraceMode, WarningLevel, etc.
An example of how a @Page directive looks
<Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Sample Page Title">
For More details Visit MSDN
Saturday, September 19, 2009
File Upload In silverlight using Web service (.asmx)
the classic .asmx web services. To upload files in the silverlight applications.
Steps :
- Create a silverlight project in Visual Studio 2008 or beyond. As silverlight 3.0 is released so you can use that or go with Silverlight 2.0 hardly matters.
- Make these important changes in the properties of FileUploadASMX.Web project
- Right click on FileUploadASMX.Web.
- Select Properties
- Under Web tab Select Specific port and give the port number I am using port number 1366 Note: we are using specific port so that every time we need not to run the web service to use it and it wont change its address. Neither we ned it to host on IIS if you don't want to use specifc port then either host your web service on IIS or run the webservice every time and update the service refrence each time before running the application.
- Save The Properties Page and close it.
- Add a new Web service to the FileUploadASMX.Web project and name it as uploadService.asmx
- Include the name space "System.IO"
using System.IO;
- Create a new web method
//method for upload the files. This will be called from Silverlight code behind.
[WebMethod]
public string UploadFiles(string strFileName, byte[] byFile, string strFileNo)
{
try
{
if (byFile.Length > 0)
{
string strFilePath = "D:\\meet\\" + strFileName;
System.IO.FileStream fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write);
fs.Write(byFile, 0, byFile.Length);
fs.Close();
return strFileNo;
}
else
{
return "";
}
}
catch
{
return "";
}
} - Save the Service Leaving other settings as it is. or you want then you can delete the Helloworld example web method.
- Coming back to the FileUploadASMX project.
- Create A class FilesClass
public class FilesClass
{
public FilesClass()
{
//do nothing
}
string strStatus = "";
string strNo = "";
FileInfo strFileName = null;
public string PropNumber
{
get
{
return strNo;
}
set
{
strNo = value;
}
}
public FileInfo PropFileName
{
get
{
return strFileName;
}
set
{
strFileName = value;
}
}
public string PropStatus
{
get
{
return strStatus;
}
set
{
strStatus = value;
}
}
} - Create Two Buttons in the Mainpage.xaml.
- To Chosse File
- To upload File At the specifed folder in the Web Service
<Grid x:Name="LayoutRoot" Background="White" Width="400" Height="50">
- Add the service refernce to the silverlight project name it "uploadService"
- Navigating to the event for choose button
private void Button_Click(object sender, RoutedEventArgs e)
{
//create a oblect for file open dialog
OpenFileDialog op = new OpenFileDialog();
//show the file browser dialog to select file
op.ShowDialog();
//if any file is selected
if (op.File != null && op.File.Name != "")
{
//check the file size. It shoud be less than 1MB
if (op.File.Length < 1048576)
{
//create a new fill class object to maintain the file content
FilesClass obj = new FilesClass();
//assign file
obj.PropFileName = op.File;
//assing file number
obj.PropNumber = iFileCount.ToString();
//add the file object to files list collection
fl.Add(obj);
iFileCount++;
}
//IF size is greater then 1 MB show the message
else
{
MessageBox.Show("Max file size is 1 MB");
}
}
//display message to the user if no file is selected
else
{
MessageBox.Show("Select File");
}
} - Now Lets code for the upload event Navigate to the event
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (fl.Count > 0)
{
//loop through the files and upload the files by passing it to web service.
for (int count = 0; count < fl.Count; count++)
{
uploadService.uploadServiceSoapClient x = new uploadService.uploadServiceSoapClient();
//here is the event hadndler, whihc will be invoked for every file upload
x.UploadFilesCompleted += new EventHandler<uploadService.UploadFilesCompletedEventArgs>(UploadFileComplted);
//read the file from file class
FilesClass obj = (FilesClass)fl[count];
System.IO.FileStream str = obj.PropFileName.OpenRead();
byte[] by = new byte[str.Length];
str.Read(by, 0, by.Length);
str.Close();
//call the upload file methods async event, which will upload the files asynchronously
x.UploadFilesAsync(obj.PropFileName.Name, by, obj.PropNumber);
}
}
}
private void UploadFileComplted(object sender, uploadService.UploadFilesCompletedEventArgs e)
{
if (e.Result != "")
{
MessageBox.Show("File Uploaded");
}
}
Thanks and Regards
Meetu Choudhary
MVP.
My Blog || My Web || My Forums
File Handling in Silverlight
File Handling in Silverlight
In real time programming I haven't seen any application which do not need to work with files in one or the other way and every programming Language and techniques gives a way to handle files. So do our Silverlight. Here we are going to discuss about the techniques or I must say the methods we can follow for handling files.In My Previous Article we saw how we can increase our application's Isolated Area. How can we handle the files in the Isolated storage area. By File Handling I mean The Following :
- Creating Files
- Reading Files
- Getting List of Files
- Uploading The Existing Files to the Isolated Area.
- Deleing Files
Steps :
- Create a new Silverlight Application I am naming it as "FileUploadSLApp". And leave the other settings as it is.
- We can use MainPage.xaml or can create our own silverlight user control (.xaml). For this example I am going with the MainPage.xaml. The Usercontrol of the Mainpage.xaml will look like:
<UserControl x:Class="FileUploadSLApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Canvas.Left="10" Canvas.Top="10">
<Button Content="Upload" Height="20" Click="Button_Click_1" Margin="10,60,162,54" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Right" Background="#FF2770AF"></Button>
<TextBox Text="Write File Name with Extention" Margin="10,10,0,0" x:Name="txtFileName"></TextBox>
<Button Content="Read Eile" Height="20" Click="Button_Click" Margin="65,60,162,54" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Right" Background="#FF2770AF"></Button>
<Button Content="Get List" Height="20" Click="Button_Click_2" Margin="130,60,162,54" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Right" Background="#FF2770AF"></Button>
<Button x:Name="btnDelete" Height="20" Margin="190,60,251,8" Content="Delete File" Click="btnDelete_Click"/>
<Button x:Name="btnWrite" Height="20" Margin="270,60,36,8" Content="Write" Click="btnWrite_Click" />
<TextBlock Height="20" Margin="10,100,126,79" VerticalAlignment="Bottom" Text="Select File to uload" TextWrapping="Wrap" FontSize="16" x:Name="txtStatus"/>
<TextBox Text="Enter The File Contents here......" Margin="10,140,0,0" x:Name="txtContent"></TextBox>
</Canvas>
</Grid>
</UserControl>
The Page will Look like
Create File
- In this section we will create a text file in the isolated storage area with the name as given by the user in te textbox.First will check whether the file exist in the isolated storage area or not. If it does exist then we will create a new file with the name and if it exists then we will append the contents at the start of the file which user inputs in the textbox.Now let us create the event handler for the button and navigate to the event.
private void btnWrite_Click(object sender, RoutedEventArgs e)
{
using (var MyAppStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(MyAppStore.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist , we are creating one for you ");
IsolatedStorageFileStream file = MyAppStore.CreateFile(txtFileName.Text);
file.Close();
}
using (StreamWriter sw = new StreamWriter(MyAppStore.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = "";
txtFileName.Text = "";
MessageBox.Show("File Writen");
}
} - This section of the article shows that how can we read a text file from the Isolated storage area of the application. We have Already created a button and the event handler for this in the .xaml file so let us navigate to the event and code there
private void Button_Click(object sender, RoutedEventArgs e)
{
//craeing a new link to the Application store for reading file in IsolatedStorage
using (var MyAppStore = IsolatedStorageFile.GetUserStoreForApplication())
{
//checking the existance of the file
if (!(MyAppStore.FileExists(txtFileName.Text)))
{
//if doesnot exist prompt the user
MessageBox.Show("File does not exist ");
//Clear the text from the textbox
txtFileName.Text = string.Empty;
}
//if file does exist
else
{
//create a stream reader to read the file
using (StreamReader sr = new StreamReader(MyAppStore.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite)))
{
//read file till end and post the contenst in hte textblock
txtStatus.Text = sr.ReadToEnd();
}
}
}
} - In this section we will get the list file in the isolated storage area and Display it in the TextBlock. for Directory Handling please read next article Now navigating to the event handler
private void Button_Click_2(object sender, RoutedEventArgs e)
{
//clearing the textblockstatus to ensure that it is not having any text
txtStatus.Text = string.Empty;
//getting the handler for the isolated store
using (var MyAppStore = IsolatedStorageFile.GetUserStoreForApplication())
{
//holding the array (list) of file names into a string array
string[] str = MyAppStore.GetFileNames();
//creating a foreach loop to go through each elemen of the array
foreach (string s in str)
{
//printing the filename in the textblock with a new line.
txtStatus.Text = txtStatus.Text + Environment.NewLine + s;
}
}
} - In this section we will upload any file in the isolated storage area. and then access it from there for future use.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//creating the refrence for the dialog
OpenFileDialog dlg = new OpenFileDialog();
//creating the filter for the dialog
dlg.Filter = "All files (*.*)|*.*";
//Displaying the Dialog box remeber this should be user itnitated.
if (dlg.ShowDialog() == true)
{
txtStatus.Text = "Uploading Files ";
// Save all selected files into application's isolated storage
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
//holding the file name into a string variable for later use
string strname = dlg.File.Name;
//creating a filestream and reading the contents of the selected file
using (Stream fileStream = dlg.File.OpenRead())
{
//craeing a new IsolatedStorageFileStream for certaing new file in IsolatedStorage
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(strname, FileMode.Create, iso))
{
// Read and write the data block by block until finish
while (true)
{
//get the bytes to write in the file.
byte[] buffer = new byte[fileStream.Length];
// byte[] buffer = new byte[100001];
int count = fileStream.Read(buffer, 0, buffer.Length);
if (count > 0)
{
isoStream.Write(buffer, 0, count);
}
else
{
break;
}
}
}
txtStatus.Text = "Files Uploaded";
}
}
} - In this section we will delete any file from the isolated storage area with the name as given by the user in te textbox. Moving towards the event Handler
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
//getting the handler for the store
using (var MyAppStore = IsolatedStorageFile.GetUserStoreForApplication())
{
//Checking if file doesnot exist
if (!(MyAppStore.FileExists(txtFileName.Text)))
{
//prompt the user that file does not exist
MessageBox.Show("File does not exist ");
}
//if file does exist
else
{
//delete it from the store
MyAppStore.DeleteFile(txtFileName.Text);
//prompt the user that the file is deleted
MessageBox.Show("Deleted");
}
//clear the textbox containg the file name
txtFileName.Text = string.Empty;
}
}
Reading Files
Getting List of Files from the Isolated Storage
Uploading File
Delete File
Thanks and Regards
Meetu Choudhary
MVP.
My Blog || My Web || My Forums
Saturday, September 12, 2009
Creating A setup For a Windows Application
Some one has asked me today that how can I create a setup for a windows application in VB.Net so in order to answer the question I have prepared an article which I am sharing with you all hoping it will be of any help to others to running into the same problem.
The one thing I would like to clear is that creating setup for a windows application is not based on any language.
We need to follow the following Steps, in order to create a setup project for any windows application regardless of the language.
1. Open visual studio.
2. Select New Project from the File Menu.
3. Under The Other Project Types.
4. Select Setup Project.
5. Name it I am using Setup1 for the Example.
6. Once You Click Ok You will see the Screen Like This
7. Select Application Folder in Left Tab under File System on Target Machine.
8. Right Click on it.
9. Under Add option you will find the Folder, File, Assembly options. Choose the appropriate option I am Directly Creating an exe File you may also Create a folder and in that folder Cerate the exe file.
10. Now Browse for the EXE. For which you want to create setup
11. The Dependent DLL’s and the Exe will be copied
12. If you want to create Shortcut keys on the user Desktop and in the Program files Then Right Click On the Exe File
13. Choose Create shortcut. Rename It.
14. Now Drag and Drop This Shortcut To the Appropriate folder
15. Now Some Properties We Need to Change In order that they look like this is ours company Project.
16. Select The Project from the Solution Explorer and Press Select the Project from the Solution Explorer and Press to open the Properties.
17. Change The Author Name From The Default Company Name to the name of your choice.
18. And Manufactures Name
19. Choose Release Option Instead of Debug option
20. And Then Build Solution
21. Now Your Product is ready to distribute with the setups.You Can See That by Opening the Containing Folder
22. There In Setup setup Relase you will find two files To distribute.
Friday, September 11, 2009
Solution to: URI Formats Not Supported
public List funSendMail(Mailcls m)
{
List result = new List();
try
{
/* Create a new blank MailMessage with the from and to adreesses*/
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(m.Sender, m.Receiver);
/*Checking the condition that the cc is empty or not if not then
* include them
*/
if (m.Cc != null && m.Cc != string.Empty)
{
mailMessage.CC.Add(m.Cc);
}
/*Checking the condition that the Bcc is empty or not if not then
* include them
*/
if (m.Bcc != null && m.Bcc != string.Empty)
{
mailMessage.Bcc.Add(m.Bcc);
}
//Ading Subject to the Mail
mailMessage.Subject = m.Subject;
//Adding the Mail Body
mailMessage.Body = m.Body;
/* Set the properties of the MailMessage to the
values on the form as per the mail is HTML formatted */
mailMessage.IsBodyHtml = true;
/* Bigining of Attachment1 process &
Check the all file for a attachment */
if ((m.AttachfilesPath != null) && (m.AttachfilesPath.Count > 0))
{
foreach (string s in m.AttachfilesPath)
{
result.Add("Attaching File : " + s);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(s);
/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);
}
}
/* Set the SMTP server and send the email with attachment */
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
// smtpClient.Host = emailServerInfo.MailServerIP;
//this will be the host in case of gamil and it varies from the service provider
smtpClient.Host = m.Host;
//smtpClient.Port = Convert.ToInt32(emailServerInfo.MailServerPortNumber);
//this will be the port in case of gamil for dotnet and it varies from the service provider
smtpClient.Port = m.Port;
smtpClient.UseDefaultCredentials = true;
//smtpClient.Credentials = new System.Net.NetworkCredential(emailServerInfo.MailServerUserName, emailServerInfo.MailServerPassword);
smtpClient.Credentials = new System.Net.NetworkCredential(m.UserName, m.Password);
//this will be the true in case of gamil and it varies from the service provider
smtpClient.EnableSsl = m.SSL;
smtpClient.Send(mailMessage);
try
{
/* Delete the attachements if any */
foreach (string s in m.AttachfilesPath)
{
File.Delete(s);
}
}
catch { }
result.Add("1");
}
catch (Exception ex)
{
result.Add("-2 " + ex.Message);
}
return result;
}
and In Calling Appication (Which is a Silverlight Application)
ObservableCollection cv = new ObservableCollection();
//cv.Add(@"file://c6/Shared/Repo/a/Drafts/go.png%22);//This Works
cv.Add(@"http://www.msdotnetmentor.com/wp-content/uploads/2009/08/5.JPG%22);//This Doesnot Work
Mail.Bcc = txtBCC.Text;
Mail.Body = txtMailBody.Text;
Mail.Cc = txtCC.Text;
//Mail.AttachfilesPath = SendDraftAttachment;
Mail.AttachfilesPath = cv;
Mail.Host = EditDeleteEmailConfig.SMTPHost;
Mail.Password = EditDeleteEmailConfig.SMTPPassword;
Mail.Port = EditDeleteEmailConfig.SMTPPort;
Mail.Receiver = txtTo.Text;
Mail.Sender = txtFrom.Text;
Mail.SSL = EditDeleteEmailConfig.SMTPSSL;
Mail.Subject = txtSubject.Text;
Mail.UserName = EditDeleteEmailConfig.SMTPUserName;
SuccessMessage = "Mail Sent Successfully";
ErrorMessage = "Error In Sending Mail" + Environment.NewLine + "Try Sending Later";
if (EmailSettings)
{
SendClient.funSendMailAsync(Mail);
SendClient.funSendMailCompleted += new EventHandler(SendClient_funSendMailCompleted);
}
else
{
EditDeleteEmailConfig = new EmailConfig();
IsSendMail = true;
EmailSettingsClient.GetEamilConfigByClientIdAsync(userID);
}
1. URI is not a physical path so it can't be used for File Handling as we need the Physical path for that.
2. There is nothing in WCf like server.mappath()
3. we have to do some workaround to achive so and that work around is
add the following Namespaces :
using System.ServiceModel.Activation;
using System.Web;
now the class implementing the intervfce or the WCF class Use This Line of Code
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
Eg:
// NOTE: If you change the class name "SendMailWCF" here, you must also update the reference to "SendMailWCF" in App.config.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SendMailWCF : ISendMailWCF
{
and now you can access the file like
string RD = HttpContext.Current.Server.MapPath("Repo") + @"\" + filename;
And below is an excerpt from the web.config.
<!-- Added only the one line below -->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <!-- Everything else was left intact --> <behaviors> <!-- ... --> </behaviors> <services> <!-- ... --> </services>
Thanks and Regards
Meetu Choudhary
http://www.msdotnetheaven.com/forums/index.php
http://www.msdotnetmentor.com/
http://aspnetbymeetu.blogspot.com/
URI Format Not Supported.
public Listand In Calling Appication (Which is a Silverlight Application)funSendMail(Mailcls m) { List result = new List (); try { /* Create a new blank MailMessage with the from and to adreesses*/ System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(m.Sender, m.Receiver); /*Checking the condition that the cc is empty or not if not then * include them */ if (m.Cc != null && m.Cc != string.Empty) { mailMessage.CC.Add(m.Cc); } /*Checking the condition that the Bcc is empty or not if not then * include them */ if (m.Bcc != null && m.Bcc != string.Empty) { mailMessage.Bcc.Add(m.Bcc); } //Ading Subject to the Mail mailMessage.Subject = m.Subject; //Adding the Mail Body mailMessage.Body = m.Body; /* Set the properties of the MailMessage to the values on the form as per the mail is HTML formatted */ mailMessage.IsBodyHtml = true; /* Bigining of Attachment1 process & Check the all file for a attachment */ if ((m.AttachfilesPath != null) && (m.AttachfilesPath.Count > 0)) { foreach (string s in m.AttachfilesPath) { result.Add("Attaching File : " + s); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(s); /* Attach the newly created email attachment */ mailMessage.Attachments.Add(attach); } } /* Set the SMTP server and send the email with attachment */ System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); // smtpClient.Host = emailServerInfo.MailServerIP; //this will be the host in case of gamil and it varies from the service provider smtpClient.Host = m.Host; //smtpClient.Port = Convert.ToInt32(emailServerInfo.MailServerPortNumber); //this will be the port in case of gamil for dotnet and it varies from the service provider smtpClient.Port = m.Port; smtpClient.UseDefaultCredentials = true; //smtpClient.Credentials = new System.Net.NetworkCredential(emailServerInfo.MailServerUserName, emailServerInfo.MailServerPassword); smtpClient.Credentials = new System.Net.NetworkCredential(m.UserName, m.Password); //this will be the true in case of gamil and it varies from the service provider smtpClient.EnableSsl = m.SSL; smtpClient.Send(mailMessage); try { /* Delete the attachements if any */ foreach (string s in m.AttachfilesPath) { File.Delete(s); } } catch { } result.Add("1"); } catch (Exception ex) { result.Add("-2 " + ex.Message); } return result; }
ObservableCollectioncv = new ObservableCollection (); //cv.Add(@"\\C6\Shared\Repo\a\Drafts\go.png");//This Works cv.Add(@"www.msdotnetmentor.com/wp-content/uploads/2009/08/5.JPG");//This Doesnot Work Mail.Bcc = txtBCC.Text; Mail.Body = txtMailBody.Text; Mail.Cc = txtCC.Text; //Mail.AttachfilesPath = SendDraftAttachment; Mail.AttachfilesPath = cv; Mail.Host = EditDeleteEmailConfig.SMTPHost; Mail.Password = EditDeleteEmailConfig.SMTPPassword; Mail.Port = EditDeleteEmailConfig.SMTPPort; Mail.Receiver = txtTo.Text; Mail.Sender = txtFrom.Text; Mail.SSL = EditDeleteEmailConfig.SMTPSSL; Mail.Subject = txtSubject.Text; Mail.UserName = EditDeleteEmailConfig.SMTPUserName; SuccessMessage = "Mail Sent Successfully"; ErrorMessage = "Error In Sending Mail" + Environment.NewLine + "Try Sending Later"; if (EmailSettings) { SendClient.funSendMailAsync(Mail); SendClient.funSendMailCompleted += new EventHandler (SendClient_funSendMailCompleted); } else { EditDeleteEmailConfig = new EmailConfig(); IsSendMail = true; EmailSettingsClient.GetEamilConfigByClientIdAsync(userID); }
Now The Solution IS
Fine I got The Answer
Points:
1. URI is not a physical path so it can't be used for File Handling as we need the Physical path for that.
2. There is nothing in WCf like server.mappath()
3. we have to do some workaround to achive so and that work around is
add the following Namespaces :
using System.ServiceModel.Activation;
using System.Web;
now the class implementing the intervfce or the WCF class Use This Line of Code
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
Eg:
// NOTE: If you change the class name "SendMailWCF" here, you must also update the reference to "SendMailWCF" in App.config.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SendMailWCF : ISendMailWCF
{
and now you can access the file like
string RD = HttpContext.Current.Server.MapPath("Repo") + @"\" + filename;
And below is an excerpt from the web.config.
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <behaviors> </behaviors> <services> </services>
Saturday, August 29, 2009
Scour Friend Invite
Check out: http://scour.com/invite/meetu.choudhary/
I'm using a new search engine called Scour.com. It shows Google/Yahoo/MSN
results and user comments all on one page. Best of all we get rewarded for
using it by collecting points with every search, comment and vote. The
points are redeemable for Visa gift cards. Join through my invite link so we
can be friends and search socially!
I know you'll like it,
- MeetuChoudhary
This message was sent to you as a friend referral to join scour.com, please
feel free to review our http://scour.com/privacy page and our
http://scour.com/communityguidelines/antispam page.
If you prefer not to receive invitations from ANY scour members,
please click here - http://www.scour.com/unsub/e/bWVldHVjaG91ZGhhcnkubWVldEBibG9nZ2VyLmNvbQ==
Write to us at:
Scour, Inc., 15303 Ventura Blvd. Suite 220, Sherman Oaks, CA 91403, USA.
campaignid: scour200908290001
Scour.com
Saturday, August 22, 2009
Stop Searchprotocolhost.exe on WindowsXP
Thursday, August 20, 2009
Meetu At First Page of City Bhaskar, Jaipur
Sunday, August 16, 2009
Isolated Storage in the Silverlight Application
Isolated Storage
Isolated Storage in the Silverlight Application
Definition:
Isolated storage is a mechanism which, provide data storage isolation and safety by defining standardized ways of associating code with saved data. Standardization provides some more benefits as well.
Uses of tools from designing, reconfiguration storage, make security
policies apart from this remove unused data all are the tasks of
Administrators
Using isolated storage there no need to write unique paths in the file system, so, hard-coded things are immaterial. With this all is controlled by computer's security policy. The uses of this is appreciable in web applications where user/client must have to use some cautions while running these applications.
Security policy doe not allow to access the file system using I/O mechanism, by default all is granted to access isolated storage
For more information on Isolated Storage Visit here
How to increase the space of the issolatedStorage of the application
Steps To Test The Current Space for the application
- Run any Silverlight Application Right click on it it will show you the silverlight button. Click on it
- Now the Silverlight properties Dialog will appear
Now select the Application Storage Tab It will show you the Application storgae for all the silverlight application on the system
Steps - Create an application with the name "IsolatedStorageApp". You can name it as per your choice I will be using this in my example Application.
Add New silverlight control and name it as "IncreaseIsolatedStorage.xaml" - Right-click on the IsolatedStorageApp in the solution explorer
- Choose Add
- New Item
- Silverlight User Control. In the Name box rename it to IncreaseIsolatedStorage
- For our purpose we are only taking three textblocks to
display Space Used, Space Available, Current Quota and the textbox for the New Space request. Add The Following lines in the .xaml file
<Canvas Canvas.Left="10" Canvas.Top="10">
<TextBlock Canvas.Left="10" x:Name="SpacedUsed" >Current Spaced Used=</TextBlock>
<TextBlock Canvas.Left="10" x:Name="SpaceAvaiable" Canvas.Top="20">Current
Space Available=</TextBlock>
<TextBlock Canvas.Left="10" x:Name="CurrentQuota" Canvas.Top="40">Current
Quota=</TextBlock>
<TextBlock Canvas.Left="10" x:Name="NewSpace" Canvas.Top="70">New
space (in bytes) to request=</TextBlock>
<TextBox Canvas.Left="255" Canvas.Top="70" Width="100" x:Name="SpaceRequest"></TextBox>
<TextBlock Canvas.Left="365" Canvas.Top="70" Width="60">(1048576
= 1 MB)</TextBlock>
<Button Canvas.Left="10" Content="Increase Storage" Canvas.Top="100" Width="100" Height="50" Click="Button_Click"></Button>
<TextBlock Canvas.Left="10"
Canvas.Top="160" x:Name="Result"></TextBlock>
</Canvas> Now our page will look like: - To set The Values of the Three TextBlocks lets create a function GetStorageData and call it in the constructor.
private void GetStorageData()
{
//creating an object for the IsolatedStorageFile
using (IsolatedStorageFile MyAppStore = solatedStorageFile.GetUserStoreForApplication())
{
//calculating the space used
SpacedUsed.Text = "Current Spaced Used = " + (MyAppStore.Quota
- MyAppStore.AvailableFreeSpace).ToString() + " bytes";
//getting the AvailableFreeSpace
SpaceAvaiable.Text = "Current Space Available="
+ MyAppStore.AvailableFreeSpace.ToString() + " bytes";
//getting the Current Quota
CurrentQuota.Text = "Current Quota=" + MyAppStore.Quota.ToString() + " bytes";
}
}
Here we will be missing a namespace "System.IO.IsolatedStorage" So include it. - Now the function to increase the quota
/// <summary>
/// Increases the Isolated Storage Space of the current Application
/// </summary>
/// <param name="spaceRequest">
Total Space Requested to increase</param>
private void IncreaseStorage(long spaceRequest)
{
//creating an object for the IsolatedStorageFile for current Application
using (IsolatedStorageFile MyAppStore = solatedStorageFile.GetUserStoreForApplication())
{
//Calculating the new space
long newSpace = MyAppStore.Quota + spaceRequest;
try
{
//displays a message box for the increase request.
//if accepted by the user then displays the result as quota increased
//else unsuccessful.
if (true == MyAppStore.IncreaseQuotaTo(newSpace))
{
Result.Text = "Quota successfully increased.";
}
else
{
Result.Text = "Quota increase was unsuccessfull.";
}
}
catch (Exception e)
{
Result.Text = "An error occured: " + e.Message;
}
//recalculate the static
GetStorageData();
}
}
Handling the button event
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
//taking the space request in the long variable
long spaceRequest = Convert.ToInt64(SpaceRequest.Text);
//calling the function to increase the space
IncreaseStorage(spaceRequest);
}
catch
{
Result.Text = "Bad Data Entered by the user";
}
}
- Run the Application and click on the Button after filling the textbox with the desired space to increase.
A Dialog box will appear for the confirmation click yes to see the results.
Thanks and Regards
Meetu Choudhary
Friday, August 14, 2009
Sending Mails with attachments using Gmail
Sending Mails with attachments using Gmail
Many times I came across the question that how can we send mails with some files as attachments and in continuation do we reaky need to buy some domain of our's to send mail or there is a domain using which we can send mails using gmail or yahoo or hotmail accounts. so the answer. So I decided to write this article which will help in solving the above quest.
Let answer First the above questions and then we will code how to send mails with attachments.
Question : Do we need our own domain to send mails?
Answer : No we do not necessarily need our own domain to send mails. Gmail
provides us free pop service and yahoo, hotmail and other mail engines charge for the service. Rather if we have our own domain that would be a benefit.
Question : Can we send files as an attachment?
Answer : Yes we can and even any extension of file can be send as attachment if server allows that as Gmail do not allow to send exe files rest you can send pdf,html,doc etc. any.
Question : Some Times our code is perfectly fine still we are not able to send mails ether we get error failed to send or could not connect to the server what may be the reasons?
Answer : The Reasons is very simple that we have some firewalls or the anti
virus installed on the system which prevents us to do so Specially Mac Fee prevents us sending the mails by blocking the port. The
Remedies is just off the antivirus for some time and then try sending the mail.
Requirements:
Development Machine Requirements
- Dotnet installed on the system VS2005 or above The Downloadable version comes for VS2008
- Files to attach with the mails
- Anti-Virus off while debugging the application
Client Side Requirements
- Dotnet Framework 2.0 or above in which the application is made
- Browser to run the Application
- Anti-Virus off while executing the application
Now lets start developing the application
- Create a web application with the name "SendMailWithAttachment". You can even use any name of your choice I am using this for my example.
- Add The Following code in the body tag of the Default.aspx page to genrate an interface for the aplication.
<%@
Page Language="C#"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="SendMailWithAttachment._Default"
%>
<!DOCTYPE
html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml"
>
<head
runat="server">
<title>Send
Mail Using Gmail Account With Attachments</title> </head>
<body>
<form id="Form1" method="post" runat="server">
<table borderColor="#339933" cellSpacing="0" cellPadding="4" width="55%" align="center" border="1">
<tr>
<td>
<table cellPadding="4" width="70%" align="center" border="0"> <tr bgColor="#339933"> <td align="center" colSpan="2"><asp:label id="lblHeader" Runat="server"
Font-Bold="True">Gmail Account Details for Sending Mails</asp:label></td> </tr>
<tr>
<td vAlign="middle" align="right" width="40%">Username:</td> <td
vAlign="middle" width="60%"> <asp:TextBox
ID="txtUserName" runat="server" Font-Names="Verdana" Font-Size="X-Small" Width="350px"></asp:TextBox>
</td>
</tr>
<tr>
<td vAlign="middle" align="right" width="40%">Password</td> <td
vAlign="middle" width="60%"> <asp:TextBox
ID="txtPassword" Font-Names="Verdana" Font-Size="X-Small" Width="350px" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr bgColor="#339933"> <td align="center" colSpan="2"><asp:label id="Label1" Runat="server"
Font-Bold="True">SMTP
Mail with Attachment</asp:label></td>
</tr>
<tr>
<td vAlign="middle" align="right" width="40%">From :</td> <td vAlign="middle"
width="60%"><asp:textbox id="txtSender"
tabIndex="1" runat="server" Font-Names="Verdana" Font-Size="X-Small" Width="350px"></asp:textbox></td>
</tr>
<tr>
<td vAlign="middle" align="right">To :</td>
<td><asp:textbox id="txtReceiver" tabIndex="1"
runat="server" Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:textbox></td>
</tr>
<tr>
<td vAlign="middle" align="right">Cc :</td>
<td><asp:textbox id="txtCc" tabIndex="1" runat="server"
Font-Names="Verdana" Font-Size="X-Small" Width="350px"></asp:textbox></td>
</tr>
<tr>
<td vAlign="middle" align="right">Bcc :</td>
<td><asp:textbox id="txtBcc" tabIndex="1" runat="server"
Font-Names="Verdana" Font-Size="X-Small" Width="350px"></asp:textbox></td>
</tr> <tr>
<td vAlign="middle" align="right">Subject :</td>
<td><asp:textbox id="txtSubject" tabIndex="2" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:textbox></td>
</tr>
<tr>
<td vAlign="middle" align="right">Format :</td>
<td><asp:radiobuttonlist id="rblMailFormat" tabIndex="3"
runat="server" repeatcolumns="2" repeatdirection="Horizontal">
<asp:ListItem Value="Text" Selected="True">Text</asp:ListItem>
<asp:ListItem Value="HTML">HTML</asp:ListItem>
</asp:radiobuttonlist></td>
</tr>
<tr>
<td vAlign="middle" align="right">Message :</td>
<td height="84"> <p><asp:textbox id="txtBody"
tabIndex="4" runat="server" Font-Names="Verdana" Font-Size="X-Small" columns="40" rows="5" textmode="MultiLine" width="350px"></asp:textbox></p> </td>
</tr>
<tr>
<td vAlign="middle" align="right">Attachment :</td><td><input id="inpAttachment1" tabIndex="5" type="file" size="53" name="filMyFile" runat="server"></td> </tr>
<tr>
<td vAlign="middle" align="right">Attachment :</td>
<td><input id="inpAttachment2" tabIndex="6" type="file"
size="53" name="filMyFile" runat="server"></td>
</tr>
<tr>
<td vAlign="middle" align="right">Attachment :</td>
<td><input id="inpAttachment3" tabIndex="7" type="file"
size="53" name="filMyFile" runat="server"></td>
</tr>
<tr>
<td align="center" colSpan="2"><asp:button id="btnSend"
tabIndex="9" runat="server" width="100px" text="Send" onclick="btnSend_Click"></asp:button></td>
</tr>
<tr>
<td align="center" colSpan="2"><asp:Label ID="lblMessage"
Runat="server"></asp:Label>
</td>
</tr>
</table>
</td> </tr> </table>
</form>
</body>
</html>
- The Default.aspx will now look like:
- Now Let us code for the Functionality double Click on the button and the event handler is genrated for the buttonclick
Before we start the code for the event let us include some namespaces: - using System.Net.Mail;
- using System.IO;
- using System.Drawing;
Here is the code for the button event. The code is having inline commets to explain the meamning of each line.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.IO;
using System.Drawing;
namespace SendMailWithAttachment
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
/* Create a new blank MailMessage with the from and to
adreesses*/
MailMessage mailMessage = new MailMessage txtSender.Text,txtReceiver.Text);
/*Checking the condition that the cc is empty or not if
not then * include them
*/
if (txtCc.Text != null && txtCc.Text != string.Empty)
{
mailMessage.CC.Add(txtCc.Text);
}
/*Checking the condition that the Bcc is empty or not
if not then
* include them
*/
if (txtBcc.Text != null && txtBcc.Text != string.Empty)
{
mailMessage.Bcc.Add(txtBcc.Text);
}
//Ading Subject to the Mail
mailMessage.Subject = txtSubject.Text;
//Adding the Mail Body
mailMessage.Body = txtBody.Text;
/* Set the properties of the MailMessage to the
values on the form as per the mail is HTML formatted or plain text */
if (rblMailFormat.SelectedItem.Text ==
"Text")
mailMessage.IsBodyHtml = false;
else
mailMessage.IsBodyHtml = true;
/* We use the following variables to keep track of
attachments and after we can delete them */
string attach1 = null;
string attach2 = null;
string attach3 = null;
/*strFileName has a attachment file name for
attachment process. */
string strFileName = null;
/* Bigining of Attachment1 process & Check the first open file dialog for a attachment */
if (inpAttachment1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = inpAttachment1.PostedFile;
/* Get size of the file */
int attachFileLength = attFile.ContentLength;
/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(inpAttachment1.PostedFile.FileName);
/* Save the file on the server */
inpAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));
/* Create the email attachment with the uploaded file
*/
Attachment attach = new
Attachment(Server.MapPath(strFileName));
/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);
/* Store the attach filename so we can delete it later
*/
attach1 = strFileName;
}
}
/* Attachment-2 Repeat previous step defiend above*/
if (inpAttachment2.PostedFile != null)
{
HttpPostedFile attFile = inpAttachment2.PostedFile;
int attachFileLength = attFile.ContentLength;
if (attachFileLength > 0)
{
strFileName = Path.GetFileName(inpAttachment2.PostedFile.FileName); inpAttachment2.PostedFile.SaveAs(Server.MapPath(strFileName));
Attachment attach = new Attachment(Server.MapPath(strFileName));
mailMessage.Attachments.Add(attach);
attach2 = strFileName;
}
}
/* Attachment-3 Repeat previous steps step defiend above*/
if (inpAttachment3.PostedFile != null)
{
HttpPostedFile attFile = inpAttachment3.PostedFile;
int attachFileLength = attFile.ContentLength;
if (attachFileLength > 0)
{
strFileName = Path.GetFileName(inpAttachment3.PostedFile.FileName); inpAttachment3.PostedFile.SaveAs(Server.MapPath(strFileName));
Attachment attach = new Attachment(Server.MapPath(strFileName));
mailMessage.Attachments.Add(attach);
attach3 = strFileName;
}
}
/* Set the SMTP server and send the email with attachment */
SmtpClient smtpClient = new SmtpClient();
// smtpClient.Host = emailServerInfo.MailServerIP;
//this will be the host in case of gamil and it varies from the service provider
smtpClient.Host = "smtp.gmail.com";
//smtpClient.Port = Convert.ToInt32 emailServerInfo.MailServerPortNumber);
//this will be the port in case of gamil for dotnet and
it varies from the service provider
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
//smtpClient.Credentials = new
System.Net.NetworkCredential(emailServerInfo.MailServerUserName,
emailServerInfo.MailServerPassword);
smtpClient.Credentials = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);
//this will be the true in case of gamil and it varies
from the service provider
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
/* Delete the attachements if any */
try{
if (attach1 != null)
File.Delete(Server.MapPath(attach1));
if (attach2 != null)
File.Delete(Server.MapPath(attach2));
if (attach3 != null)
File.Delete(Server.MapPath(attach3));
}
catch{}
/* clear the controls */
txtSender.Text = string.Empty;
txtReceiver.Text = string.Empty;
txtCc.Text = string.Empty;
txtBcc.Text = string.Empty;
txtSubject.Text = string.Empty;
txtBody.Text = string.Empty;
txtUserName.Text = string.Empty;
/* Dispaly a confirmation message to the user. */
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Black;
lblMessage.Text = "Message sent.";
}
catch (Exception ex)
{
/* Print a message informing the user about the exception that was risen */
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Red;
lblMessage.Text = ex.ToString();
}
}
}
}