I have a WPF application which is messaging with my server using ASP. net webmethod. I have also file uploading functionality on it. But when I uploading a file to asp .net webmethod, my wpf application being locked. I used the standart Async method which generated automatically by asp. net webmethod, but it gives me only method result. I want to implement Progress bar about uploading status to server
Attaching my asp.net and WPF upload codes here.
WPF upload code:
private async void Upload_Button_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.DefaultExt = ".jpg"; // Required file extension
fileDialog.Filter = "Image files|*.jpg;*.jpeg;*.png;*.jfif|PDF Files|*pdf|Outlook file|*.msg"; // Optional file extensions
if (FilesGrid.Items.Count > 4)
{
MessageBox.Show("Maximum allowed file count is 5\n" +
"Please delete File to upload other Files.");
return;
}
if (fileDialog.ShowDialog() == true)
{
var size = new FileInfo(fileDialog.FileName).Length;
if (size > 2000000)
{
MessageBox.Show("File Size cannot be more than 2 MB");
return;
}
System.IO.StreamReader sr = new
System.IO.StreamReader(fileDialog.FileName);
//Get the name of the File.
string fileName = Path.GetFileName(fileDialog.FileName);
//Get the content type of the File.
string contentType = "Image";
//Read the file data into Byte Array.
//BinaryReader br = new BinaryReader(sr.InputStream);
//byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
byte[] bytes = File.ReadAllBytes(fileDialog.FileName);
//Call the Web Service and pass the File data for upload.
var s = await service.UploadFileAsync(fileName, contentType, bytes, ldap_mapping_id);
string uplo = s.Body.UploadFileResult;
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(uplo);
string id = "";
string name = "";
foreach (XmlNode item in xmlDocument.ChildNodes)
{
foreach (XmlNode child in item.ChildNodes)
{
if (child.Name == "id")
{
id = child.InnerText;
}
if (child.Name == "name")
{
name = child.InnerText;
}
}
}
var newAllFiles = new myGridClass
{
id = id,
name = name
};
//allFiles.Add(newAllFiles);
FilesGrid.Items.Add(newAllFiles);
sr.Close();
}
}
catch (Exception)
{
MessageBox.Show("File cannot be uploaded. Please contact to your support team");
return;
}
}
ASP.net WebMethod code:
[WebMethod]
public string UploadFile(string fileName, string contentType, byte[] bytes, int ldap_mapping_id)
{
try
{
string todayPath = HttpContext.Current.Request.PhysicalApplicationPath + "\\Uploads\\" + DateTime.Today.Year + "\\" + DateTime.Today.Month + "\\" + DateTime.Today.Day + "\\";
if (!Directory.Exists(todayPath))
{
Directory.CreateDirectory(todayPath);
}
//Save the Byte Array as File.
string filePath = todayPath + fileName;
File.WriteAllBytes(filePath, bytes);
string UrlScheme = HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://";
string fileUrl = UrlScheme + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port.ToString() + "/Uploads/" + DateTime.Today.Year + "/" + DateTime.Today.Month + "/" + DateTime.Today.Day + "/" + fileName;
var attEntities = new attachment
{
file_src = fileUrl,
ldap_mapping_id = ldap_mapping_id,
file_path = filePath
};
StringBuilder builder = new StringBuilder();
string resultXML = "<Result>";
var context = new HOCEntities();
var newHoc = context.attachments.Add(attEntities);
context.SaveChanges();
resultXML += "<id>" + attEntities.id.ToString() + "</id>";
resultXML += "<name>" + fileName + "</name>";
resultXML += "</Result>";
return resultXML;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}