Stream file from ftp in localhost working in azure no - asp.net-mvc

Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}

Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.

Related

Not able to use the updated value -- Flutter

I'm updating the totalPayable value in else if, but I'm not able to use the updated value anywhere in the code when I call getOrder(). Is it an API problem or what can anyone help me with the code?
else if (isOrderInitiated == false){
getCleintOrderFromApi();
debugPrint("ifelse" + totalPayable.toString());
}
getClientOrderFromApi() {
orders.clear();
totalPayable = 0.0;
api.getCleintOrder().then((list) {
list.forEach((order) {
if(order.is_placed) {
order.status = ORDER_STATUS[0];
} else if(!order.is_placed) {
order.status = ORDER_STATUS[2];
}
debugPrint("ORDER_STATUS from remote" + order.status);
for (var j = 0; j < order.items.length; j++) {
FoodItemOrder item = order.items[j];
totalPayable = totalPayable + item.unitPrice * item.quantity;
debugPrint(" total payable in order "+ totalPayable.toString());
}
orders.add(order);
debugPrint("itemsin order"+orders.last.items.length.toString());
});
currentOrderList.clear();
currentOrderList.addAll(orders);
orderItemsSink.add(orders);
});
}
}
The debugPrint in getClientOrderFromApi() is showing the updated result, but in else if debugPrint(" ifelse "+ totalPayable.toString()); it is not showing the updated value which is why wherever I use totalPayable it is not showing the desired value.
Future<List<Order>> getCleintOrder() async {
MakeOrder clientOrderRequest = MakeOrder(); //currentCafe;
clientOrderRequest.caffeID = currentCafe.caffeId;
clientOrderRequest.tableidtimestamp = currentUser.tableIdTimestamp;
// offset = 160;
String url = BASE_URL + BASE_URL_GET_CLIENT_ORDER;
debugPrint("requesting getCleintOrder --- \n" +
url +
"\n " +
clientOrderRequest.toClietnOrderJson().toString());
var response = await http
.post(
url,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
// HttpHeaders.authorizationHeader : ''
},
body: json.encode(clientOrderRequest.toClietnOrderJson()),
)
.catchError(
(error) {
////debugPrint(error.toString());
return false;
},
);
var jsonObj = json.decode(response.body);
////debugPrint(jsonObj.toString());
List<Order> orders = [];
try {
jsonObj.forEach((newJson) {
List<Order> orderList = (newJson["orders"] as List)
.map((neworderJson) => Order.fromJSON(neworderJson))
.toList().cast<Order>();
orders.addAll(orderList);
});
} catch (e) {
////debugPrint(e.toString());
}
// debugPrint("total client orders " + orders.length.toString());
return orders;
}
This is my api call for refernece.

Multiple Excel upload error in ExcelPackage EPPlus

public ActionResult ExcelFile(IEnumerable < HttpPostedFileBase > excelFile) {
try {
if (excelFile != null) {
foreach(var singleExcel in excelFile) {
string path = "~/ExcelFolder/";
singleExcel.SaveAs(Server.MapPath(path + singleExcel.FileName));
using(FileStream fs = new FileStream(Server.MapPath(path + singleExcel.FileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using(ExcelPackage package = new ExcelPackage(fs)) {
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int startRowNumber = sheet.Dimension.Start.Row;
int endRowNumber = sheet.Dimension.End.Row;
int startColumnNumber = sheet.Dimension.Start.Column;
int endColumnNumber = sheet.Dimension.End.Column;
if (endColumnNumber > 26) {
for (int currentColumnNumber = endColumnNumber; startColumnNumber < currentColumnNumber; currentColumnNumber--) {
var cellValue = sheet.Cells[startRowNumber, currentColumnNumber].Value ? .ToString();
if (!string.IsNullOrWhiteSpace(cellValue)) {
if (cellValue == "延人公里小計") {
sheet.DeleteColumn(currentColumnNumber);
sheet.Cells[1, currentColumnNumber].Value = "小計";
//return fsr;
package.SaveAs(
new FileInfo(# "C:\Users\leon0944\Desktop\123\" + singleExcel.FileName));
break;
}
}
}
}
}
}
}
Hello,when I upload many Excel to the file then read every single Excel to do someting.then i got error in ExcelPackage package = new ExcelPackage(fs) this row
error message :System.Runtime.InteropServices.COMException: HRESULT:
0x8003001D (STG_E_WRITEFAULT)
sometime is working normally sometime I got error,Please tell me How Can I fix this. The problem existed for several days.

through exception in mvc on send email

I want to send email from an excel file.
When It get wrong email address it stop sending.
I want it send all email and at last show me wrong email that isn't able to send.
This my code for read Excel file:
if (!string.IsNullOrWhiteSpace(excel))
{
var src = excel;
DataSet ds = new DataSet();
string fileExtension = System.IO.Path.GetExtension(Server.MapPath("~/") + src);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/") + src;
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/") + src;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
And this is code for send email:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string excelname = "";
if (lang == "1")
{
excelname = "<div style='text-align:right;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
else
{
excelname = "<div style='text-align:left;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
exceltotal = excelname + text + newslink + attach;
//sender
message = string.Format(body, img, exceltotal, title, prehead, senderemail);
MailMessage email = new MailMessage();
email.To.Add(ds.Tables[0].Rows[i][2].ToString());
email.From = new MailAddress(senderemail);
email.Subject = maintitle;
email.Body = message + makedelivey(ds.Tables[0].Rows[i][2].ToString(), maintitle);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.IsBodyHtml = true;
SmtpClient ssmtp = new SmtpClient();
ssmtp.Host = server;
ssmtp.Port = port;
ssmtp.UseDefaultCredentials = false;
ssmtp.Credentials = new System.Net.NetworkCredential(senderemail, senderpassword);
ssmtp.EnableSsl = false;
ssmtp.Send(email);
exceltotal = "";
message = "";
}
It read a text file and add some value from excel or database base on user selection.
I couldn't find line of code which sends email. But wherever you are sending the email inside the loop, make sure you enclose that code in try catch block. This ensures even if a mail send operation is failed, the error is handled and goes on with other mails. You can include your consolidate and formatting of failures issues in catch block.
var consolidateErrors = string.Empty;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Try
{
//Mail sending logic here
}
Catch(Exception ex)
{
consolidateErrors += YourErrorDetails;
}
}

BlackBerry java.io.IOException: null

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

Silverlight 3 File Dialog Box

Ok - I have a WCF Service which reads an excel file from a certain location and strips the data into an object. What I need is the ability to allow users of my program to Upload an excel sheet to the file location that my Service uses.
Alternitivley I could pass the Uploaded excel sheet to the service directly.
Can anyone help with this. My service code is:
public List<ImportFile> ImportExcelData(string FileName)
{
//string dataSource = Location + FileName;
string dataSource = Location;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
var data = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheetName = data.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "] WHERE Status = '4'", con);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
DataTable dt = ds.Tables[0];
var _impFiles = new List<ImportFile>();
foreach (DataRow row in dt.Rows)
{
var _import = new ImportFile();
_import.PurchaseOrder = row[4].ToString();
try
{
var ord = row[8].ToString();
DateTime dati = Convert.ToDateTime(ord);
_import.ShipDate = dati;
}
catch (Exception)
{
_import.ShipDate = null;
}
ImportFile additionalData = new ImportFile();
additionalData = GetAdditionalData(_import.PurchaseOrder);
_import.NavOrderNo = additionalData.NavOrderNo;
_import.IsInstall = additionalData.IsInstall;
_import.SalesOrderId = additionalData.SalesOrderId;
_import.ActivityID = additionalData.ActivityID;
_import.Subject = additionalData.Subject ;
_import.IsMatched = (_import.ShipDate != null & _import.NavOrderNo != "" & _import.NavOrderNo != null & _import.ShipDate > DateTime.Parse("01/01/1999") ? true : false);
_import.UpdatedShipToField = false;
_import.UpdatedShipToFieldFailed = false;
_import.CreateNote = false;
_import.CreateNoteFailed = false;
_import.CompleteTask = false;
_import.CompleteTaskFailed = false;
_import.FullyCompleted = 0;
_import.NotCompleted = false;
_impFiles.Add(_import);
}
oleda.Dispose();
con.Close();
//File.Delete(dataSource);
return _impFiles;
}
You will want to modify your service to accept a Stream instead of a filename, then you can save if off to a file (or parse it directly from the Stream, although I don't know how to do that).
Then in your Silverlight app you could do something like this:
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var fileStream = dialog.File.OpenRead();
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// don't forget to close the stream
fileStream.Close();
};
proxy.ImportExcelDataAsync(fileStream);
}
}
You could also have your WCF service accept a byte[] and do something like this.
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var length = dialog.File.Length;
var fileContents = new byte[length];
using (var fileStream = dialog.File.OpenRead())
{
if (length > Int32.MaxValue)
{
throw new Exception("Are you sure you want to load > 2GB into memory. There may be better options");
}
fileStream.Read(fileContents, 0, (int)length);
}
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// no need to close any streams this way
};
proxy.ImportExcelDataAsync(fileContents);
}
}
Update
Your service could look like this:
public List<ImportFile> ImportExcelData(Stream uploadedFile)
{
var tempFile = HttpContext.Current.Server.MapPath("~/uploadedFiles/" + Path.GetRandomFileName());
try
{
using (var tempStream = File.OpenWrite(tempFile))
{
uploadedFile.CopyTo(tempStream);
}
//string dataSource = Location + FileName;
string dataSource = tempFile;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() +
";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
Thanks Bendewey that was great. Had to amend it slightly -
My Service:
var tempFile = #"c:\temp\" + Path.GetRandomFileName();
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(tempFile, FileMode.Create))
{
do
{
bytesRead = uploadedFile.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
uploadedFile.Dispose();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
Thanks Again for your help

Resources