Save file dialog for local machine in mvc - asp.net-mvc

wondering, if someone can help. I've written this code, which will generate an CSV file spreadsheet and save it to a specified location. I want to display a "Save as" dialogue box by reading the file from the stored location and then asking user, where they want to store it. The excel file is not generated and after click on "Export To CSV" in next window, it will show undefined as a massege! However my problem is the code i've written seems to be outputting the file directly to my browser, so i get all the contents of the CSV file on my browser screen, not displaying the save as dialogue box as expected!
Here is my Code
public ActionResult ExportToCSSReport(List<CEPMobility.CEPServiceProxy.CSSReport> Report)
{
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, System.Text.Encoding.UTF8);
writer.WriteLine("PROJECT NAME,CSS ID,CSS Name,Customer Reprentative Name,CSS Recived Date,CSI,TOP 3 STRENGTH,TOP 3 OFI,Any Other COMMENT");
foreach (CEPMobility.CEPServiceProxy.CSSReport objreport in Report)
{
writer.WriteLine("\"" + objreport.PROJECT_NAME + "\",\"" + objreport.CSS_ID + "\",\"" + objreport.CSS_NAME + "\",\"" + objreport.CUST_REP_NAME + "\",\"" + objreport.CSS_RECIEVED_DT + "\",\"" + objreport.CSI + "\",\"" + objreport.TOP_3_STRENGTH + "\",\"" + objreport.TOP_3_OFI + "\",\"" + objreport.COMMENT + "\"");
}
writer.Flush();
output.Seek(0, SeekOrigin.Begin);
return File(output, "text/csv", "CSSReport.csv");
}
In response to gor, it would show the same undefined message at the top:
public ActionResult ExportToCSSReport(List<CEPMobility.CEPServiceProxy.CSSReport> Report)
{
CEPServiceProxy.CEPDataServiceClient client = null;
client = new CEPServiceProxy.CEPDataServiceClient();
lstCSSReport = client.GetCSSReport(cSS_NAME, in_Cust_ID).ToList();
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, System.Text.Encoding.UTF8);
writer.WriteLine("PROJECT NAME,CSS ID,CSS Name,Customer Reprentative Name,CSS Recived Date,CSI,TOP 3 STRENGTH,TOP 3 OFI,Any Other COMMENT");
foreach (CEPMobility.CEPServiceProxy.CSSReport objreport in Report)
{
writer.WriteLine("\"" + objreport.PROJECT_NAME + "\",\"" + objreport.CSS_ID + "\",\"" + objreport.CSS_NAME + "\",\"" + objreport.CUST_REP_NAME + "\",\"" + objreport.CSS_RECIEVED_DT + "\",\"" + objreport.CSI + "\",\"" + objreport.TOP_3_STRENGTH + "\",\"" + objreport.TOP_3_OFI + "\",\"" + objreport.COMMENT + "\"");
}
writer.Flush();
output.Seek(0, SeekOrigin.Begin);
Response.AddHeader("Content-Disposition", "attachment;filename=CSSReport.csv");
return File(output, "text/csv", "CSSReport.csv");
}

You shoud add Content-Disposition header to your response. Like this:
Response.AddHeader("Content-Disposition", "attachment;filename=CSSReport.csv");

Related

How to convert all types (audio*) to mp3 ? Using FFMPEG

It is possible to convert all audio to mp3?
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = #"""C:\ffmpeg\bin\ffmpeg.exe""";
proc.StartInfo.Arguments = "-i C:\\Matheus\\Matheus_Project\\Matheus_Project\\App_Data\\" + User.Identity.Name + "\\" + fileNameAndType + " -acodec libmp3lame -ab 128k C:\\Matheus\\Matheus_Project\\Matheus_Project\\App_Data\\" + User.Identity.Name + "\\" + fileName + ".mp3"; /* use /y to overwrite if there it exists already or will fail */
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
var output = proc.StandardOutput.ReadToEnd();
string output_error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
proc.Close();
Example:
audio/x-m4a to mp3
audio/mp4 to mp3
audio/basic to mp3
audio/L24 to mp3
audio/mid to mp3
audio/x-aiff to mp3
audio/x-mpegurl to mp3
audio/vnd.rn-realaudio to mp3
audio/ogg to mp3
audio/vorbis to mp3
audio/vnd.wav to mp3
Any idea ?
public void ConvertWavToMp3(string filename)
{
try
{
string Flacfilename = AppDomain.CurrentDomain.BaseDirectory + "FlacRecording";
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = AppDomain.CurrentDomain.BaseDirectory + #"lame.exe";
psi.Arguments = "-b" + "128" + " --resample " + "22.05" + " -m j " +
"\"" + filename + "\"" + " " +
"\"" + Flacfilename + "\\" + Path.GetFileNameWithoutExtension(filename) + ".mp3" + "\"";
Process p = Process.Start(psi);
p.WaitForExit();
p.Close();
p.Dispose();
}
catch (Exception ae)
{
}
}
download lame.exe and put it in your application and call abover function with passing fullpath with wav file name.

how to insert multiple dynamic row value into the database

public void create(account_detail c, int jobcard_id)
{
SqlConnection con = new SqlConnection(#"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
foreach (var details in c.Data)
{
cmd.CommandText = "insert into child_detail values ('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "');";
cmd.ExecuteNonQuery();
}
}
I am using this code but it only taking single value but I want to save the multiple values into the database ?
Try something like:
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
additionalText += ", ";
else
needComma = true;
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
Basic idea - prepare the string of teh command in the foreach loop, then execute the command once.

Twitter API link parser

I am having an issue and tried to do everything regarding this!! even HttpUtility.ParseQueryString won't help!
I am trying to parse twitter links coming from the API in the form of http://t.co/oEVQbihMWu. I need the fully resolved URL.
My code:
richTextBox1.Clear();
richTextBox1.Visible = true;
SearchOptions SO = new SearchOptions();
SO.GeoCode = richTextBox3.Text + "," + richTextBox2.Text + "mi";
TwitterResponse<TwitterSearchResultCollection> TweetSearchResult = TwitterSearch.Search(tokens, "#blogger", SO);
if (TweetSearchResult.Result != RequestResult.Success) richTextBox1.Text = "connection Error";
else
{
string a = null;
foreach (var tweet in TweetSearchResult.ResponseObject)
{
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, tweet.User.Website, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + tweet.User.Website + "\n" + tweet.Text + "\n\n\n");
}
links being represented by tweet.user.website.
any help? :)
In the API response, there is entities.urls which contains an array of url and expanded_url mappings. Check your library's documentation for equivalent.
Alternatively, if you inspect the response for t.co links, you will find this:
<noscript><META http-equiv="refresh" content="0;URL=http://www.fitnessbydanielle.com"></noscript><title>http://www.fitnessbydanielle.com</title><script>window.opener = null; location.replace("http:\/\/www.fitnessbydanielle.com")</script>
Parse it to get the url.
I managed to crack it.
What I did:
foreach (var tweet in TweetSearchResult.ResponseObject)
{
if(tweet.User.Website != null)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tweet.User.Website);
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, realUrl, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + realUrl + "\n" + tweet.Text + "\n\n\n");
}
}
File.AppendAllText(#".\BloggerTable.csv", a, Encoding.UTF8);
}
Wrapped it inside a condition so no users without website will show and used a webrequest to get the link. stored the location inside the httprequest header for each and every tweet.

ASP.NET MVC PartialView gives an error some times?

I use partialview like
<td style="vertical-align: top;">#Html.Action("_HavaDurumuPartial")
And It is working on server now. But sometimes It gives error. Erros is below:
This error not occur allways.
I cant find any reason for this problem.And I cant understand why does it sometimes give this error.
If it is neccesary, I write the content of partialview and controller action.
action
public ActionResult _HavaDurumuPartial(string il)
{
il = "Izmir";
HttpWebRequest GoogleRequest;
HttpWebResponse GoogleResponse = null;
XmlDocument GoogleXMLdoc = null;
try
{
GoogleRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api?weather=" + il + "&hl=tr&ie=utf-8&oe=utf-8");
GoogleResponse = (HttpWebResponse)GoogleRequest.GetResponse();
GoogleXMLdoc = new XmlDocument();
GoogleXMLdoc.Load(GoogleResponse.GetResponseStream());
XmlNode root = GoogleXMLdoc.DocumentElement;
XmlNodeList nodeList1 = root.SelectNodes("weather/forecast_information");
//ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<b>Şehir : " + nodeList1.Item(0).SelectSingleNode("city").Attributes["data"].InnerText + "</b>";
XmlNodeList nodeList = root.SelectNodes("weather/current_conditions");
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<table cellpadding=\"5\"><tbody><tr><td style=\"width:50%;\"><b><big><nobr>" + nodeList.Item(0).SelectSingleNode("temp_c").Attributes["data"].InnerText + " °C | " + nodeList.Item(0).SelectSingleNode("temp_f").Attributes["data"].InnerText + " °F</nobr></big></b></br>";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<b>Şuan:</b> " + nodeList.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText + "";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + " " + nodeList.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerText + "</br>" + "";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + " " + nodeList.Item(0).SelectSingleNode("humidity").Attributes["data"].InnerText;
nodeList = root.SelectNodes("descendant::weather/forecast_conditions");
int i = 0;
foreach (XmlNode nod in nodeList)
{
if (i == 0)
{
i++;
continue;
}
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "</td><td align=\"center\">" + nod.SelectSingleNode("day_of_week").Attributes["data"].InnerText + "</br>" + "";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "<img src=\"http://www.google.com" + nod.SelectSingleNode("icon").Attributes["data"].InnerText + "\" alt=\"" + nod.SelectSingleNode("condition").Attributes["data"].InnerText + "\">" + "</br>";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + nod.SelectSingleNode("low").Attributes["data"].InnerText + "°C" + "</br>";
ViewBag.HavaDurumu = ViewBag.HavaDurumu + nod.SelectSingleNode("high").Attributes["data"].InnerText + "°C" + "</br>";
}
ViewBag.HavaDurumu = ViewBag.HavaDurumu + "</td></tr></tbody></table>";
}
catch (System.Exception ex)
{
ViewBag.HavaDurumu = ex.Message;
}
finally
{
GoogleResponse.Close();
}
return PartialView();
}
I get the weather for specific location from google with this action.
Thanks.
There is currently an intermittent 403 Forbidden response to the Google Weather API that you are using. See Google Weather API 403 Error
The reason for the intermittent 403 response is not known but has been a problem since the 7th of August 2012.
Add a null reference check in your finally. Initializing GoogleResponse could fail, so it would still be null. Then you'll hit your finally block and get a null reference exception since GoogleResponse is null when you try to call .Close().
finally
{
if (GoogleResponse != null)
{
GoogleResponse.Close();
}
}

How to use gettext placeholders?

I'm not a programmer, but I want to help translating a project written in vala (http://live.gnome.org/Vala/Tutorial) using gettext. I encountered a problem when I had to rearrange parts of a sentence using placeholders.
Example:
public void show_retrieving_similars() {
if(hint != ViewWrapper.Hint.SIMILAR || lm.media_info.media == null)
return;
errorBox.show_icon = false;
errorBox.setWarning("<span weight=\"bold\" size=\"larger\">" + _("Loading similar songs") + "</span>\n\n" + _("BeatBox is loading songs similar to") + " <b>" + lm.media_info.media.title.replace("&", "&") + "</b> by <b>" + lm.media_info.media.artist.replace("&", "&") + "</b> " + _("..."), null);
errorBox.show();
list.hide();
albumView.hide();
similarsFetched = false;
}
What do I need to do?
I haven't used vala and I haven't tested this, it looks like you need to replace
errorBox.setWarning("<span weight=\"bold\" size=\"larger\">" + _("Loading similar songs") + "</span>\n\n" + _("BeatBox is loading songs similar to") + " <b>" + lm.media_info.media.title.replace("&", "&") + "</b> by <b>" + lm.media_info.media.artist.replace("&", "&") + "</b> " + _("..."), null);
with
string title = lm.media_info.media.title.replace("&", "&");
string artist = lm.media_info.media.artist.replace("&", "&");
errorBox.setWarning(#"<span weight=\"bold\" size=\"larger\">Loading similar songs</span>\n\n BeatBox is loading songs similar to<b> $title </b>by<b> $artist </b>...", null);

Resources