System.Web.HttpContext.Current.Response parses a field - export-to-csv

This is a weird one... I have a CSV file on the server and make it available to users via the code below. Typically, the results set is correct, except that it always omits the last field of the last record:
Co Name,Process Date,Employee Id,Last Name,First Name,Cust Auth,ENTERED_HRS,Labor Type
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,131137057134,5,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1411310002,8,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1411320015,6.69,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1413500001105,6
Notice there is no ",0" at the end of the last record? In Visual Studios, it works fine, but on my development server, it omits that last part.
I verified that the source CSV file has all the data fields. I tried different path locations for the CSV file, but no change. Can't understand why it works on Visual Studios and not on the server.
addendum: I don't know if it matters, but the source file is located on a virtual directory(not physical) on the server. Any Ideas???
// Causes Save As Dialog box to appear for user.
String FileName = fileName;
String FilePath = strFilePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/csv";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.WriteFile(FilePath + FileName);
response.Flush();
response.Close();
// response.End(); // Same as response.TransmitFile(), but causes an exception because it raises the EndRequest event.

After a lot of trial and error, I found that I can get it to work if I use the Content type:
response.ContentType = "application/csv";
Not sure why this is different from text/csv, but its working now.
Also, You could use
response.ContentType = "application/vnd.ms-excel";
As well, but its going to prompt the user that the file is not in the proper format, do you want
to open anyway.
Eric

Related

How to properly close Word documents after Documents.Open

I have the following code for a C# console app. It parses a Word document for textboxes and inserts the same text into the document at the textbox anchor point with markup. This is so I can convert to Markdown using pandoc, including textbox content which is not available due to https://github.com/jgm/pandoc/issues/3086. I can then replace my custom markup with markdown after conversion.
The console app is called in a PowerShell loop for all documents in a target list.
When I first run the Powershell script, all documents are opened and saved (with a new name) without error. But the next time I run it, I get an occasional popup error:
The last time you opened '' it caused a serious error. Do you still want to open it?
I can get through this by selecting yes on every popup, but this requires intervention and is tedious and slow. I want to know why this code results in this problem?
string path = args[0];
Console.WriteLine($"Parsing {path}");
Application word = new Application();
Document doc = word.Documents.Open(path);
try
{
foreach (Shape shp in doc.Shapes)
{
if (shp.TextFrame.HasText != 0)
{
string text = shp.TextFrame.TextRange.Text;
int page = shp.Anchor.Information[WdInformation.wdActiveEndPageNumber];
string summary = Regex.Replace(text, #"\r\n?|\n", " ");
Console.WriteLine($"++++textbox++++ Page {page}: {summary.Substring(0, Math.Min(summary.Length, 40))}");
string newtext = #$"{Environment.NewLine}TEXTBOX START%%%{text}%%%TEXTBOX END{Environment.NewLine}";
var range = shp.Anchor;
range.InsertBefore(Environment.NewLine);
range.Collapse();
range.Text = newtext;
range.set_Style(WdBuiltinStyle.wdStyleNormal);
}
}
string newFile = Path.GetFullPath(path) + ".notb.docx";
doc.SaveAs2(newFile);
}
finally
{
doc.Close();
word.Quit();
}
The console app is called in a PowerShell loop for all documents in a target list.
You can automate Word from your PowerShell script directly without involving any other dependencies. At least that will allow you to keep a single Word instance without creating each time a new Word Application instance for each document:
Application word = new Application();
Document doc = word.Documents.Open(path);
In the loop you could just open documents for processing and then closing them. It should improve the overall performance of your solution.
When you are done processing a document you need to close it by using the Close method which closes the specified document.
Also when a new Word Application instance is created, don't forget to close it as well by calling the Quit method which quits Microsoft Word and optionally saves or routes the open documents.
Application.Quit SaveChanges:=wdSaveChanges, OriginalFormat:=wdWordDocument

Use Google Scripts to Attach PDF to email

I am trying to have google Scripts send a PDF as an attachment to an email. I have a doc template that uses form data that is copied and then filled out. The code works, but the program keeps sending the template as a pdf and not the filled out copy. Can anyone help me with this?
Here is some of my code:
newDoc = autoWriteNewIEPForm(templateDocId, newDocName, fieldArray, NewEntryArray, submitTeacherName);
newDocId = newDoc.getId();
newDocURL = newDoc.getUrl();
var sender = newEntryArray[0][3];
var subSubject = newDocName;
var subEmailBody = "Thank you for submitting this information. This receipt confirms that we have received your information." + "<br><br>";
var file = DriveApp.getFileById(newDocId).getAs(MimeType.PDF);
MailApp.sendEmail(sender, subSubject, "", {cc:emailCC, htmlBody:subEmailBody, attachments:[file], name: newDocName});
Well the last line of your code is correctly attaching the newDoc as an attachment. The first line confuses me a bit; autoWriteNewIEPForm is not a Google scripts function, and I don't know where you're getting it from or if you're using it correctly. My guess is that you're using it incorrectly, or that for some reason it's not editing any of the text in the newDoc, so you have a document that is technically a copy of the template but looks exactly the same.
In the Body class of the Google Scripts DocumentApp you can find a number of methods for editing text in a document's body. I suggest you use one of those instead.

Unity Patcher. Name has invalid chars Error

I have written a patcher for my game but I am stuck at the actual saving of the files part. I keep on getting the following error from unity:
System.ArgumentException: Name has invalid chars
at System.IO.FileStream..ctor....
Here is the code that is in charge of saving my files:
function downloadFile(file:String){
var download:WWW = WWW(rawDataFolder+""+file); //download file from platforms raw folder
yield download; // wait for download to finish
// var saveLoc = Application.persistentDataPath; //Location where the files will go
var saveLoc = "C:\\games";
try{
Debug.Log(saveLoc+"\\"+file);
File.WriteAllBytes (saveLoc+"\\"+file+".FILE", download.bytes); //<----PROBLEM HERE.
}
catch(error){
updateMsg ="Update Failed with error message:\n\n"+error.ToString();
errorOccured = true;
Debug.Log(error);
}
}
I am trying to download a file called "level0". It doesn't have a file extension... in windows explorer it says it is simply 'FILE'. So I was thinking it was a binary file. Am I wrong? What might be causing my null character problem? This missing extension? Any help on this would be amazing.
I found out that my problem originated in the text file that I was reading. The text file must have had spaces in it. Using the ".Trim()" command I was able to remove the invalid char error. Once that was removed it worked perfectly reading files without extensions (Binary Files).

Is it possible to retrieve connection string inside DDL generation template in VS2010?

I am playing around with creating a T4 template for the "DDL Generation Template option" (model first) process in Visual Studio 2010 RC. Is it possible to retrieve the connection string that is associated with that process? If I right click on the .edmx file and choose "Generate Database from Model..." I have the option of choosing a data connection. That connection string is saved to the app.config (assuming that the option is checked). So I am wondering if it is possible to retrieve that connection string inside the T4 template. I would like to generate different information from the template based on the connection string.
More generally, is it possible to get any context information in this situation? So far, the only thing I have successfully retrieved is the .NET data provider name.
Note - I have studied the ideas provided by Craig but am only getting the name of the IDE (devenv.exe), which quite possibly means I am just doing something wrong.
In case this helps anyone else, here is a snippet I created to read the Entity Framework connection string from inside T4. You pass it the model name (which is also the name of the connection string). It finds and parses just the connection bit I need. It also throws helpful errors when it does not succeed.
To use:
A. Paste this at the top of your template if you aren't already referencing these assemblies:
<## assembly name="EnvDTE" #>
<## assembly name="System.Configuration" #>
B. Paste this ugly (but compact) code at the end of your template:
<#+
string GetEFConnectionString(string modelName)
{
string file = null, key = "provider connection string=\"";
foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
file = item.get_FileNames(0); break;
}
if (file == null) throw new Exception("config file could not be found");
var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
var cn = config.ConnectionStrings.ConnectionStrings[modelName];
if (cn == null) throw new Exception(modelName + " connection string could not be found");
string s = cn.ConnectionString;
int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);
if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
pos += key.Length;
int pos2=s.IndexOf('"',pos);
if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
return s.Substring(pos,pos2-pos);
}
#>
C. Use it like such:
using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
..
}
I posted my question on one of the MSDN forums and got a response from Lingzhi Sun who pointed me in the direction of a couple of links at skysanders.net. The second of these links has a very nice example of getting to the app/web.config file and, specifically the part I wanted, the connection strings. It doesn't give any information on the specific connection string for the scenario I described in the original question, but this gets me close enough.
Accessing app.config/web.config from T4 template
Accessing app.config/web.config from T4 template - Take 2
Well, the EF connection string will always have the same name as the model, right? The DB connection string will be embedded in the EF connection string. So I'd say you should be able to get it, at least indirectly, via the EF connection string.
Because you're not running in the assembly, have to specify the config file name.
So it would be something like:
var config = ConfigurationManager.OpenExeConfiguration(name);
var cs = config.ConnectoinStrings[modelName];
Note that name, here, is supposed to be an EXE name. But in the IDE, your config fine is going to be called App.config rather than MyApp.dll.config. So you may have to play around with this to get it to work -- try using "App" as the EXE name!
Worst case is open it as a file and then use the config manager.

Mirth: How to get source file directory from file reader channel

I have a file reader channel picking up an xml document. By default, a file reader channel populates the 'originalFilename' in the channel map, which ony gives me the name of the file, not the full path. Is there any way to get the full path, withouth having to hard code something?
You can get any of the Source reader properties like this:
var sourceFolder = Packages.com.mirth.connect.server.controllers.ChannelController.getInstance().getDeployedChannelById(channelId).getSourceConnector().getProperties().getProperty('host');
I put it up in the Mirth forums with a list of the other properties you can access
http://www.mirthcorp.com/community/forums/showthread.php?t=2210
You could put the directory in a channel deploy script:
globalChannelMap.put("pickupDirectory", "/Mirth/inbox");
then use that map in both your source connector:
${pickupDirectory}
and in another channel script:
function getFileLastModified(fileName) {
var directory = globalChannelMap.get("pickupDirectory").toString();
var fullPath = directory + "/" + fileName;
var file = Packages.java.io.File(fullPath);
var formatter = new Packages.java.text.SimpleDateFormat("yyyyMMddhhmmss");
formatter.setTimeZone(Packages.java.util.TimeZone.getTimeZone("UTC"));
return formatter.format(file.lastModified());
};
Unfortunately, there is no variable or method for retrieving the file's full path. Of course, you probably already know the path, since you would have had to provide it in the Directory field. I experimented with using the preprocessor to store the path in a channel variable, but the Directory field is unable to reference variables. Thus, you're stuck having to hard code the full path everywhere you need it.