Missing end of data in created text file - c#

I am trying to save data from public Web API to a txt file. However, it seems that somwhere here
using (var fs = FileService.CreateFile("filename.txt"))
{
// Add some text to file
var title = new UTF8Encoding(true).GetBytes(strContent);
fs.WriteAsync(title, 0, strContent.Length);
}
I am making a mistakes as I am missing some data at the end.
public void GetData()
{
var path = "https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/denni_kurz.txt";
string strContent;
var webRequest = WebRequest.Create(path);
using (var response = webRequest.GetResponse())
using(var content = response.GetResponseStream())
using(var reader = new StreamReader(content))
{
strContent = reader.ReadToEnd();
}
using (var fs = FileService.CreateFile("filename.txt"))
{
// Add some text to file
var title = new UTF8Encoding(true).GetBytes(strContent);
fs.WriteAsync(title, 0, strContent.Length);
}
var file = File.ReadAllLines(FileService.ReturnBinLocation("filename.txt"));
var results = new List<string>();
for (var a = 0; a < file.Length; a++)
{
results.Add(file[a]);
File.WriteAllLines(data, results);
}
var sub2 = File.ReadAllText(data);
sub2 = sub2.Replace('\n', '|').TrimEnd('|');
var split = sub2.Split('|');
var list = new List<DailyCourse>();
var i= 0;
do
{
var model = new DailyCourse();
model.Country = split[i]; i++;
model.Currency = split[i]; i++;
model.Amount = split[i]; i++;
model.Code = split[i]; i++;
model.Course = split[i]; i++;
list.Add(model);
} while ( i < split.Length);
var json = JsonSerializer.Serialize(list);
}
public static class FileService
{
public static FileStream CreateFile(string fileName)
{
var wholePath = ReturnBinLocation(fileName);
if (File.Exists(wholePath))
{
File.Delete(wholePath);
}
return File.Create(wholePath);
}
public static string ReturnBinLocation( string fileName)
{
var binPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
var wholePath = Path.Combine(binPath, fileName);
int endIndex = wholePath. Length - 5;
var sub = wholePath.Substring(5, endIndex);
return sub;
}
}

I have actually found out that it was this "Encoding.UTF8.GetBytes"when I switched it to Encoding.ASCII.GetBytes. It worked

Related

How do I delete a blob after it has been read by my function

I have created a blob triggered Azure function App that takes data from a TSV file and splits it up and writes data to a SQL database.
after the file have been read I would like to delete it from the blob container.
I'm currently studying and this is my first C# code ever so I hope you can help me out and be specific.
I have looked at the documentation for
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(???????);
blob.DeleteIfExists();
but I can't seem to find out what to put here
here is my complete function. please if you could help me out where to insert the delete command as well I would appreciate it :)
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using System.Diagnostics;
using System;
using System.Data.SqlClient;
using System.Linq;
using Azure.Storage.Blobs;
using Microsoft.WindowsAzure.Storage.Blob;
namespace FileProcessor
{
public static class FileProcessorFn
{
[FunctionName("FileProcessorFn")]
public static async Task Run([BlobTrigger("import/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, TraceWriter log)
{
log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
if (myBlob.Length > 0)
{
using (var reader = new StreamReader(myBlob))
{
var lineNumber = 1;
var line = await reader.ReadLineAsync();
var raceID = 0;
while (line != null)
{
if (lineNumber == 1 )
{
var fileName = name.Substring(0, name.Length - 4);
var races = fileName.Split('-');
var item2 = new Race
{
Race_Name = races[0],
Race_Track = races[1],
Race_Sequence = races[2],
Race_Date = races[3]
};
using (var context = new GokartDbContext())
{
context.Races.Add(item2);
log.Info("new race added with the name: " + item2.Race_Name + " and the date: " + item2.Race_Date + " with Success!");
await context.SaveChangesAsync();
//context.GetValidationErrors();
//context.SaveChanges();
raceID = context.Races.Select(p => p.RaceId).Max();
}
}
if (raceID > 0 )
{
await ProcessLine(name, line, lineNumber, log, raceID);
line = await reader.ReadLineAsync();
}
lineNumber++;
}
}
}
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(image/{ name});
blob.DeleteIfExists();
}
private static async Task ProcessLine(string name, string line, int lineNumber, TraceWriter log, int raceID)
{
if (string.IsNullOrWhiteSpace(line))
{
log.Warning($"{name}: {lineNumber} is empty.");
return;
}
if (lineNumber == 1)
{
log.Warning($"File header detected! Skipping....");
return;
}
//var fileName = name.Substring(0, name.Length -4);
//var races = fileName.Split('-');
var x_GPS_Longitudinal_Acceleration = "";
var x_Gyroscope_Y_Axis = "";
var x_Accelerometer_X_Axis = "";
var x_GPS_Speed = "";
var x_Temperatur_1 = "";
var x_Retning = "";
var x_Vertikalt_DOP = "";
var x_GPS_Lateral_Acceleration = "";
var x_Temperatur_fra_Barometer = "";
var x_RPM = "";
var x_Humidity = "";
var x_Gyroscope_Z_Axis = "";
var x_Intern_Temperatur = "";
var x_Lufttryk = "";
var x_Laengdegrad = "";
var x_Acceleeerometer_Z_Akse = "";
var x_Rat_Vinkel = "";
var x_GPS_Afstand = "";
var x_Batteri_Voltage = "";
var x_Vertical_Acceleration = "";
var x_Positions_DOP = "";
var x_Height = "";
var x_Breddegrad = "";
var x_Horisontal_DOP = "";
var x_Gyroscope_X_Axis = "";
var x_Accelerometer_Y_Akse = "";
var parts = line.Split('\t');
if (parts.Length > 6)
{
x_GPS_Longitudinal_Acceleration = parts[5];
x_Gyroscope_Y_Axis = parts[6];
x_Accelerometer_X_Axis = parts[7];
x_GPS_Speed = parts[8];
x_Temperatur_1 = parts[9];
x_Retning = parts[10];
x_Vertikalt_DOP = parts[11];
x_GPS_Lateral_Acceleration = parts[12];
x_Temperatur_fra_Barometer = parts[13];
x_RPM = parts[14];
x_Humidity = parts[15];
x_Gyroscope_Z_Axis = parts[16];
x_Intern_Temperatur = parts[17];
x_Lufttryk = parts[18];
x_Laengdegrad = parts[19];
x_Acceleeerometer_Z_Akse = parts[20];
x_Rat_Vinkel = parts[21];
x_GPS_Afstand = parts[22];
x_Batteri_Voltage = parts[23];
x_Vertical_Acceleration = parts[24];
x_Positions_DOP = parts[25];
x_Height = parts[26];
x_Breddegrad = parts[27];
x_Horisontal_DOP = parts[28];
x_Gyroscope_X_Axis = parts[29];
x_Accelerometer_Y_Akse = parts[30];
}
//var item2 = new Race
//{
// Race_Name = races[0],
// Race_Track = races[1],
// Race_Sequence = races[2],
// Race_Date = races[3]
//};
var item = new RaceData
{
RaceForeignKey = raceID,
Start_Date = parts[0],
Start_Time = parts[1],
Lap_Number = parts[2],
Session_Time = parts[3],
Lap_Time = parts[4],
GPS_Longitudinal_Acceleration = x_GPS_Longitudinal_Acceleration,
Gyroscope_Y_Axis = x_Gyroscope_Y_Axis,
Accelerometer_X_Axis = x_Accelerometer_X_Axis,
GPS_Speed = x_GPS_Speed,
Temperatur_1 = x_Temperatur_1,
Retning = x_Retning,
Vertikalt_DOP = x_Vertikalt_DOP,
GPS_Lateral_Acceleration = x_GPS_Lateral_Acceleration,
Temperatur_fra_Barometer = x_Temperatur_fra_Barometer,
RPM = x_RPM,
Humidity = x_Humidity,
Gyroscope_Z_Axis = x_Gyroscope_Z_Axis,
Intern_Temperatur = x_Intern_Temperatur,
Lufttryk = x_Lufttryk,
Laengdegrad = x_Laengdegrad,
Acceleeerometer_Z_Akse = x_Acceleeerometer_Z_Akse,
Rat_Vinkel = x_Rat_Vinkel,
GPS_Afstand = x_GPS_Afstand,
Batteri_Voltage = x_Batteri_Voltage,
Vertical_Acceleration = x_Vertical_Acceleration,
Positions_DOP = x_Positions_DOP,
Height = x_Height,
Breddegrad = x_Breddegrad,
Horisontal_DOP = x_Horisontal_DOP,
Gyroscope_X_Axis = x_Gyroscope_X_Axis,
Accelerometer_Y_Akse = x_Accelerometer_Y_Akse
};
using (var context = new GokartDbContext())
{
//context.Races.Add(item2);
//log.Info("new race added with the name: " + item2.Race_Name + " and the date: " + item2.Race_Date + " with Success!");
context.RaceDatas.Add(item);
log.Info($"{name}: {lineNumber} inserted task: \"{item.Start_Date}\" with id: {item.Id}.");
await context.SaveChangesAsync();
}
}
}
}
the reason I want to delete the blob after is because the function reads the file more than once. when it does I get a timeout because it takes more than 5 mins to process data. may be that's why it starts more than once.
is there a way to write this so the process is quicker?
the TSV files can hold up to 100.000 lines sometime.
looking forward to some advise on this
Robin
If you look at the MSFT API for GetBlockBlobReference method it takes in a blobName as a parameter.
So ideally you already have the name from the param on your function. You can just do
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(name);
blob.DeleteIfExists();

I use ".net core" .i want to search any keyword in a pdf file but this code is not working

static void Main(string[] args) {
var file = File.Open(Directory.GetCurrentDirectory() + "/Net.pdf", FileMode.Open);
var pattern = new Regex("kullan", RegexOptions.IgnoreCase);
//this line is not working
TextExtractor textExtractor = new TextExtractor();
var dddd = ReadToEnd(file);
var textStrings = textExtractor.Extract(dddd);
var matches = pattern.Matches(textStrings.Text);
foreach (var item in matches)
{
Console.WriteLine(item);
}
}
You can try something like this:
File file = new File(myPDF);
//pattern
var pattern = new Regex("kullan", RegexOptions.IgnoreCase);
var textExtractor = new TextExtractor();
foreach (var page in file.Document.Pages)
{
var strings = textExtractor.Extract(page);
var matchingText = pattern.Matches(TextExtractor.ToString(strings));
}
Tika:
try
{
var result = new TextExtractor().Extract(yourPDF.pdf).Text;
Console.WriteLine(result.Text.Length);
foreach(var line in result)
{
if(line.contains("kullen"))
/** Do Something **/
}
}
catch(Exception e)
{
Console.WriteLine("Error occurred: " + e);
}
I did it like that, thank you your answer
namespace pro
{
class Program
{
static void Main(string[] args)
{
string b = pdfText(Directory.GetCurrentDirectory()+ "/Net.pdf");
string a= "kullan";
int sonuc;
sonuc = b.IndexOf(a,0, b.Length);
if(sonuc==-1)
{
Console.WriteLine("not found");
}
else
{
Console.WriteLine("found from " + sonuc.ToString() + ". character");
}
}
public static string pdfText(string path)
{
PdfReader reader = new PdfReader(path);
var dd = reader.GetPageContent(1);
string text = string.Empty;
for (int page = 1; page <= reader.NumberOfPages; page++)
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
text += PdfTextExtractor.GetTextFromPage(reader, page);
}
reader.Close();
return text;
}
}
}

How can i handle and how should i handle exception The remote server returned an error: (500) Internal Server Error?

The exception is happen most of the times but there are times it's working fine.
The exception is always the same
The remote server returned an error: (500) Internal Server Error.
Also the stacktrace is the same:
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadData(Uri address)
at System.Net.WebClient.DownloadData(String address)
at SatelliteImages.ExtractImages.ExtractDateAndTime(String baseAddress) in D:\C-Sharp\SatelliteImages\SatelliteImages\SatelliteImages\ExtractImages.cs:line 120
Line 120 is:
var temp = wc.DownloadData("/en");
The method:
public void ExtractDateAndTime(string baseAddress)
{
try
{
var wc = new WebClient();
wc.BaseAddress = baseAddress;
HtmlDocument doc = new HtmlDocument();
var temp = wc.DownloadData("/en");
doc.Load(new MemoryStream(temp));
var secTokenScript = doc.DocumentNode.Descendants()
.Where(e =>
String.Compare(e.Name, "script", true) == 0 &&
String.Compare(e.ParentNode.Name, "div", true) == 0 &&
e.InnerText.Length > 0 &&
e.InnerText.Trim().StartsWith("var region")
).FirstOrDefault().InnerText;
var securityToken = secTokenScript;
securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
foreach (var date in scriptDates)
{
DatesAndTimes.Add(date.DateString);
}
}
catch(WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
}
}
}
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
this.Init();
}
}
When I use a breakpoint on the line:
string error = reader.ReadToEnd();
I see html content and in the content I see the text:
error occurred while processing your request. Return to the homepage of Sat24.com
What I want to do is somehow when the exception happen to start over again and try the download try the method ExtractDateAndTime.
I think using a timer some how and count back showing the user something like 30 seconds and try again. Will 30 seconds try will be consider as spam/flooding in the server site ?
This is the full class code but the exception is on this method ExtractDateAndTime.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Xml;
using HtmlAgilityPack;
using System.ComponentModel;
namespace SatelliteImages
{
class ExtractImages
{
static WebClient client;
static string htmltoextract;
public static List<string> countriescodes = new List<string>();
public static List<string> countriesnames = new List<string>();
public static List<string> DatesAndTimes = new List<string>();
public static List<string> imagesUrls = new List<string>();
static string firstUrlPart = "http://www.sat24.com/image2.ashx?region=";
static string secondUrlPart = "&time=";
static string thirdUrlPart = "&ir=";
public class ProgressEventArgs : EventArgs
{
public int Percentage { get; set; }
public string StateText { get; set; }
}
public event EventHandler<ProgressEventArgs> ProgressChanged;
public void Init()
{
object obj = null;
int index = 0;
ExtractCountires();
foreach (string cc in countriescodes)
{
// raise event here
ProgressChanged?.Invoke(obj,new ProgressEventArgs{ Percentage = 100 * index / countriescodes.Count, StateText = cc });
ExtractDateAndTime("http://www.sat24.com/image2.ashx?region=" + cc);
index +=1;
}
ImagesLinks();
}
public void ExtractCountires()
{
try
{
htmltoextract = "http://sat24.com/en/?ir=true";//"http://sat24.com/en/";// + regions;
client = new WebClient();
client.DownloadFile(htmltoextract, #"c:\temp\sat24.html");
client.Dispose();
string tag1 = "<li><a href=\"/en/";
string tag2 = "</a></li>";
string s = System.IO.File.ReadAllText(#"c:\temp\sat24.html");
s = s.Substring(s.IndexOf(tag1));
s = s.Substring(0, s.LastIndexOf(tag2) + tag2.ToCharArray().Length);
s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
string[] parts = s.Split(new string[] { tag1, tag2 }, StringSplitOptions.RemoveEmptyEntries);
string tag3 = "<li><ahref=\"/en/";
for (int i = 0; i < parts.Length; i++)
{
if (i == 17)
{
//break;
}
string l = "";
if (parts[i].Contains(tag3))
l = parts[i].Replace(tag3, "");
string z1 = l.Substring(0, l.IndexOf('"'));
if (z1.Contains("</ul></li><liclass="))
{
z1 = z1.Replace("</ul></li><liclass=", "af");
}
countriescodes.Add(z1);
countriescodes.GroupBy(n => n).Any(c => c.Count() > 1);
string z2 = parts[i].Substring(parts[i].LastIndexOf('>') + 1);
if (z2.Contains("&"))
{
z2 = z2.Replace("&", " & ");
}
countriesnames.Add(z2);
countriesnames.GroupBy(n => n).Any(c => c.Count() > 1);
}
}
catch (Exception e)
{
if (countriescodes.Count == 0)
{
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
Init();
}
}
}
public void ExtractDateAndTime(string baseAddress)
{
try
{
var wc = new WebClient();
wc.BaseAddress = baseAddress;
HtmlDocument doc = new HtmlDocument();
var temp = wc.DownloadData("/en");
doc.Load(new MemoryStream(temp));
var secTokenScript = doc.DocumentNode.Descendants()
.Where(e =>
String.Compare(e.Name, "script", true) == 0 &&
String.Compare(e.ParentNode.Name, "div", true) == 0 &&
e.InnerText.Length > 0 &&
e.InnerText.Trim().StartsWith("var region")
).FirstOrDefault().InnerText;
var securityToken = secTokenScript;
securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
foreach (var date in scriptDates)
{
DatesAndTimes.Add(date.DateString);
}
}
catch(WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
}
}
}
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
this.Init();
}
}
public class ScriptDate
{
public string DateString { get; set; }
public int Year
{
get
{
return Convert.ToInt32(this.DateString.Substring(0, 4));
}
}
public int Month
{
get
{
return Convert.ToInt32(this.DateString.Substring(4, 2));
}
}
public int Day
{
get
{
return Convert.ToInt32(this.DateString.Substring(6, 2));
}
}
public int Hours
{
get
{
return Convert.ToInt32(this.DateString.Substring(8, 2));
}
}
public int Minutes
{
get
{
return Convert.ToInt32(this.DateString.Substring(10, 2));
}
}
}
public void ImagesLinks()
{
int cnt = 0;
foreach (string countryCode in countriescodes)
{
cnt++;
for (; cnt < DatesAndTimes.Count(); cnt++)
{
string imageUrl = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
imagesUrls.Add(imageUrl);
if (cnt % 10 == 0) break;
}
}
}
}
}
What i want is in case of the exception happen to start over clean over again the whole class operation.
In Form1 i start the class operation first time once:
In top:
ExtractImages ei = new ExtractImages();
Then in constructor:
ei.Init();
The problem is this exception that sometimes happen.
You could go with something like Polly or the Transient Fault Handling Application Block to apply a retry strategy to your code.
Both packages provide multiple out-of-the-box components for various scenarios and you can always develop you own. Some of the included retry policies:
Incremental
Fixed interval
Exponential back-off
Retry
Retry for ever
Retry and wait
Wait and retry for ever
...

how to add a new customer in list in c#?

I'm working this code for almost 10 hours but i can not find out where i'm doing wrong .If you could help me you are really making my day.The problem is that I'm trying to add a new customer and save it in my list but when i'm click in submit button .It does not work nothing is saving in my list and keeps looping my other customers .
private void Sub_Click(object sender, RoutedEventArgs e)
{
customer newCus = new customer();
account newAcc= new account();
try
{
newCus.NAME = Nameadd.Text;
newCus.pin = pinadd.Text;
newAcc.PIN = pinadd.Text;
newAcc.accountnumber = Accountnumadd.Text;
newAcc.accounttype = 'C';
for (int i = 0; i < acclist.Count; i++)
{
{
if(newAcc.accounttype == 'C')
{
newAcc.PIN = pinadd.Text;
newAcc.accountnumber = Accountnumadd.Text;
newAcc.accounttype = 'S';
}
}
cuslist.add(newCus);
acclist.add(newAcc);
savefile();
saveaccount();
}
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}
//save to customer file
public void savefile()
{
using (StreamWriter writer = new StreamWriter("account.txt"))
{
for (int i = 0; i < cuslist.Count; i++)
{
var info = new List<string>
{
acclist[i].accounttype.ToString(),
acclist[i].PIN,
acclist[i].accountnumber,
acclist[i].accountbalance.ToString()
};
var account = String.Join(";", info);
writer.WriteLine(account);
}
}
}
public void saveaccount()
{
using (StreamWriter writer = new StreamWriter("account.txt"))
{
for (int i = 0; i < acclist.Count; i++)
{
var info = new List<string>
{
acclist[i].accounttype.ToString(),
acclist[i].PIN,
acclist[i].accountnumber,
acclist[i].accountbalance.ToString()
};
var account = String.Join(";", info);
writer.WriteLine(account);
}
}
}
You have a problem in your "save" functions.
Here is what you have:
public void savefile()
{
using (StreamWriter writer = new StreamWriter("account.txt"))
{
for (int i = 0; i < cuslist.Count; i++)
{
var info = new List<string>
{
acclist[i].accounttype.ToString(),
acclist[i].PIN,
acclist[i].accountnumber,
acclist[i].accountbalance.ToString()
};
var account = String.Join(";", info);
writer.WriteLine(account);
}
}
}
public void saveaccount()
{
using (StreamWriter writer = new StreamWriter("account.txt"))
{
for (int i = 0; i < acclist.Count; i++)
{
var info = new List<string>
{
acclist[i].accounttype.ToString(),
acclist[i].PIN,
acclist[i].accountnumber,
acclist[i].accountbalance.ToString()
};
var account = String.Join(";", info);
writer.WriteLine(account);
}
}
}
If you look, the only difference is the for loops. You need to also update the inner portion to read from the correct collection, and also write to the correct output file.
Try the following:
public void savefile()
{
using (StreamWriter writer = new StreamWriter("customer.txt"))
{
for (int i = 0; i < cuslist.Count; i++)
{
var info = new List<string>
{
cuslist[i].accounttype.ToString(),
cuslist[i].PIN,
cuslist[i].accountnumber,
cuslist[i].accountbalance.ToString()
};
var customer = String.Join(";", info);
writer.WriteLine(customer);
}
}
}
public void saveaccount()
{
using (StreamWriter writer = new StreamWriter("account.txt"))
{
for (int i = 0; i < acclist.Count; i++)
{
var info = new List<string>
{
acclist[i].accounttype.ToString(),
acclist[i].PIN,
acclist[i].accountnumber,
acclist[i].accountbalance.ToString()
};
var account = String.Join(";", info);
writer.WriteLine(account);
}
}
}

How to return some values from an asynchronous Task

I'm uploading a file using multipart data form and I need to keep the file description of the uploaded file. I'm using the following code
FileDescription temp = new FileDescription();
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDescription>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
temp.AssociatedSchool = 1;
temp.FileName = info.Name;
temp.LocalFileName = i.LocalFileName;
temp.FileSize = info.Length / 1024;
temp.IsFileValid = true;
temp.NoOfRecords = 1;
temp.UploadedBy = 1;
return temp;
});
return fileInfo;
});
This code doesnt set the values to the temp object. Can anyone tell me an alternate way to get the values? task.Result is always null. How can i get the values out of the thread?
Try change your sample like this
var descriptions = Request.Content.ReadAsMultipartAsync(streamProvider)
.ContinueWith<IEnumerable<FileDescription>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new FileDescription(){
AssociatedSchool = 1;
FileName = info.Name;
LocalFileName = i.LocalFileName;
FileSize = info.Length / 1024;
IsFileValid = true;
NoOfRecords = 1;
UploadedBy = 1;
}
});
return fileInfo;
}).Result;
var temp = descriptions.First();//Possibly you need FirstOrDefault

Categories

Resources