Saturday, September 19, 2009

File Upload In silverlight using Web service (.asmx)

In My Article File Handling in Silverlight I have discussed that we can use file upload in tow ways one using the Isolated storage of the silerlight and the other is using the classic (.asmx) Web services or WCF. Here I am discussing about
the classic .asmx web services. To upload files in the silverlight applications.

Steps :

  1. 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.
  2. Make these important changes in the properties of FileUploadASMX.Web project
    1. Right click on FileUploadASMX.Web.
    2. Select Properties
    3. 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.
    4. Save The Properties Page and close it.
  3. Add a new Web service to the FileUploadASMX.Web project and name it as uploadService.asmx
  4. Include the name space "System.IO"
    using System.IO;
  5. 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 "";
    }
    }
  6. Save the Service Leaving other settings as it is. or you want then you can delete the Helloworld example web method.
  7. Coming back to the FileUploadASMX project.
  8. Create A class FilesClasspublic 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;
    }
    }
    }
  9. Create Two Buttons in the Mainpage.xaml.
    1. To Chosse File
    2. To upload File At the specifed folder in the Web Service
    The Code Will look like
    <Grid x:Name="LayoutRoot" Background="White" Width="400" Height="50">
    <Button Content="Choose" Height="20" Width="150" Click="Button_Click" Margin="10,0,10,10" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Left" Background="#FF2770AF"></Button>
    <Button Content="Upload" Height="20" Width="150" Click="Button_Click_1" Margin="20,0,10,10" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Right" Background="#FF2770AF"></Button>
    </Grid>

  10. Add the service refernce to the silverlight project name it "uploadService"
  11. Navigating to the event for choose buttonprivate 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");
    }
    }
  12. Now Lets code for the upload event Navigate to the eventprivate 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");
    }
    }
The Code Is Attached you can Download the files and enjoy file handling


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 :
  1. Creating Files
  2. Reading Files
  3. Getting List of Files
  4. Uploading The Existing Files to the Isolated Area.
  5. Deleing Files

Steps :

  1. Create a new Silverlight Application I am naming it as "FileUploadSLApp". And leave the other settings as it is.
  2. 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>
  3. The Page will Look like Create File
  4. 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");
    }
    }
  5. Reading Files

  6. 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 thereprivate 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();
    }
    }
    }
    }
  7. Getting List of Files from the Isolated Storage

  8. 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 handlerprivate 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;
    }
    }
    }
  9. Uploading File

  10. 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";
    }
    }
    }
  11. Delete File

  12. 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 Handlerprivate 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;
    }
    }
The Code Is Attached you can Download the files and enjoy file handling


Thanks and Regards
Meetu Choudhary
MVP.
My Blog || My Web || My Forums

Saturday, September 12, 2009

Creating A setup For a Windows Application

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

I am Sending a Mail with attachemts for this I have Made A WCF Which works fine when I give the Network path of the file. but I need to host It And when I try to give a URL path It Says. URI format not supported please Help My Code in WCF

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);
}

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.

<!-- 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/

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com