I have implemented the File Upload (upon reading Scott Hanselman's excellent post)
I have multiple files associated with various questions on the form though, and would like to associate each saved file with an internal ID.
How can I do this? For example, if question # 3 has a file uploaded abc.pdf, how can I associated that file with ID #3?
Any good ideas, or has someone done this before?
I would have an array or vector in one of files with a getter and setter. This way when question #3 has file abc.pdf uploaded you can send the information you want to save to the setter and save it at index 3. When you want to access it use the getter for index 3.
Depending what you want to save you create an array that holds what you want. I haven't used Asp.net but this site tells you how to sort an array, which we don't want, but it also shows how to make an array of structures. So if you want to save the name of the file only then you only need a string array. But if you need to save the name and something else then create the array of structures.
Private Structure FileInfo
Public Name As String
Public OtherInfo As String
End Structure
Then create the array with :
Dim FileInfoArray(NumOfPotentialUploadedFiles - 1) As FileInfo
Since it sounds like each of your input fields upload one file each you would just need to remember the id number of the fields and then you would easily "know which IDs the uploaded files were associated with" as if field 1 has an uploaded file then it would be in the array at the same position. You could create a boolean within the structure that is set to false when you first create the array. Then when you upload a file of index 1 you change the boolean to true. This way you easily know which files you have when you go through the array b/c only the positions with a true value have a file.
Ok, figured out an easy solution. I was struggling since the Request.Files[x] object did not have any reference to the fields, but the Request.Files (HttpFileCollectionWrapper) has an AllKeys property that holds the array of fields. My code now is:
for (int fileIndex = 0; fileIndex < Request.Files.Count; fileIndex++)
{
string fieldName = Request.Files.AllKeys[fileIndex]; <--- Here is where you can gleam an key to persist to the database, I have an ID in the fieldName
string savedFileName = Path.GetFileName(Request.Files[fileIndex].FileName);
var path = Path.Combine(<your server save path>, savedFileName);
Request.Files[fileIndex].SaveAs(path);
}
Easy enough!
Related
Long time lurker first time poster. Working with .Net / Linq for just a few years so I'm sure I'm missing something here. After countless hours of research I need help.
I based my code on a suggestion from https:http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3
The following code currently saves a chosen file (pdf, doc, png, etc) which is stored in an sql database to the C:\temp. Works great. I want to take it one step further. Instead of saving it automatically to the c:\temp can I have the browser prompt so they can save it to their desired location.
{
var getFile = new myDataClass();
//retrieve attachment id from selected row
int attachmentId = Convert.ToInt32((this.gvAttachments.SelectedRow.Cells[1].Text));
//retrieve attachment information from dataclass (sql attachment table)
var results = from file in getFile.AttachmentsContents
where file.Attachment_Id == attachmentId
select file;
string writePath = #"c:\temp";
var myFile = results.First();
File.WriteAllBytes(Path.Combine(writePath, myFile.attach_Name), myFile.attach_Data.ToArray());
}
So instead of using File.WriteAllBytes can I instead take the data returned from my linq Query (myFile) and pass it into something that would prompt for the user to save the file instead?). Can this returned object be used with response.transmitfile? Thanks so much.
Just use the BinaryWrite(myFile.attach_Data.ToArray()) method to send the data since it is already in memory.
But first set headers appropriately, for example:
"Content-Disposition", "attachment; filename="+myFile.attach_Name
"Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Content-type guides the receiving system on how it should handle the file. Here are more MS Office content types. If they are known at the point the data is stored, the content-type should be stored, too.
Also, since the file content is the only data you want in the response, call Clear before and End after BinaryWrite.
I have moved a newly built WordPress site from a sub directory in the remote server, to the root directory. I have a couple of custom post types with meta data associated with them, including images metadata (i.e. file & URL). Obviously I had to remove the sub directory from the URL. I did so with a replace SQL query.
Now wordpress doesn't recognize the meta data. When I write the following code:
$img = get_post_meta($post->ID,"mf_logo",true);
var_dump($img);
I get "bool(false)". I have tried to upload a new image, and it is showing. I then manually changed its URL through MySQL and again it wasn't recognized.
It is important to note that the problem only happens with meta data in the form of array, and not with 'normal' meta-data
Your kind help would be most appreciated.
When using meta data (update_post_meta, get_post_meta...) arrays will be automatically serialized in db :
http://codex.wordpress.org/Function_Reference/update_post_meta
A passed array will be serialized into a string.
And you cannot simply replace strings in a serialized array :
$data = array('key'=>'value');
echo serialize($data);
This will output : a:1:{s:3:"key";s:5:"value";}
If you simply replace key or value with a shorter/longer string, il will break the data :
a:1:{s:3:"key";s:5:"replace";} is incorrect
a:1:{s:3:"key";s:7:"replace";} is correct
You can make a batch to handle this.
But prior to this, do you know you can let wordpress in its own directory and make it accessible from root directory, without breaking links ?
Take a look here : http://codex.wordpress.org/Giving_WordPress_Its_Own_Directory#Using_a_pre-existing_subdirectory_install
I first came across a question similar to mine here at stack overflow: Loop through all Resources in ResourceManager - C#. It only solved part of what I need to do. When you request an entry in a resource file for a specific culture, if there is not one present it will default back on the neutral culture resource file.
I need to loop through each entry for a given resource file and GetResourceSet requires a culture. For example I have a neutral resource file with 3 entries in it and a culture specific resource file accompanying the neutral file with 1 entry.
My neutral resource example file is MyResource.resx and my culture specific resource example file is MyResource.en-gb.resx. The following code shows how I am currently trying to loop through and access all of the resource entries.
Dim cultInfo as New CultureInfo(culture)
For Each entry As System.Collections.DictionaryEntry In myResourceManager.GetResourceSet(cultInfo, True, True)
Next
Neutral Resource File Entries
FullName / Full Name
PhoneNumber / Phone Number
State / State
Culture Specific Resource File Entry
State / County
When I call GetResourceSet for the specific culture I only get back 1 entry. I was expecting (and want) to get back all 3 entries with the one culture specific entry overridden. Here is what I want returned:
FullName / Full Name
PhoneNumber / Phone Number
State / County
Is there anyway that I can do this? Thanks.
The GetString method of a ResourceManager object properly handles the traversing of resource files to locate the correct Value for a given key based on a culture. The base/neutral/default resource file can be obtained using the CultureInfo.InvariantCulture, which gives you all the possible keys for the resource file (assuming you setup your resource files this way).
Looping on the DictionaryEntry objects found in the GetResourceSet method of a ResourceManager, based on the Invariant Culture and then calling GetString for each Key using the specific culture passed in, you will get the correct Value for a given key based on the culture.
For Each entry As DictionaryEntry In myResourceManager.GetResourceSet(CultureInfo.InvariantCulture, True, True)
Dim strKey as String = entry.Key.ToString()
Dim strValue as String = myResourceManager.GetString(entry.Key.ToString(), cultInfo)
Next
Hope this helps!
I'm working on an ASP.NET app
I have a couple of resource files with the different languages I can support
example: Language.en.resx
Language.pt.resx
Is there any way to get, for example, a list with all the different languages dynamically?
If you are looking for a way which determine how many ( and what ) languages you localize for your application. There is no solution.
You have to write a parser which look in a series of sub directories in your application ( or given ) path. the read and store the name of Resx files into a list.
Finally you have to split the name of Resx file with Dot (split('.')) and seperate the language part of the Resx files like
string[] myString = new string[MyResxList.lenght];
for (int i=0; i<=MyResxList.lenght;i++)
myString[i] = MyResxList[i].toString().split('.')[3];
note that above code is a snippet and I wrote it here so you have to debugit if it's necessary
then you should remove the duplicates and return the List
I am creating an xml file. I need to check first if the file exists or not. If the file does not exist, create it and add the data cmg from a .cs file.
If the file exists, don't create the file just add the data cmg from a .cs file.
My code looks like this:
string filename="c:\\employee.xml";
XmlTextWriter tw=new XmlTextWriter(filename,null);//null represents
the Encoding Type//
tw.Formatting=Formatting.Indented; //for xml tags to be indented//
tw.WriteStartDocument(); //Indicates the starting of document (Required)//
tw.WriteStartElement("Employees");
tw.WriteStartElement("Employee","Genius");
tw.WriteStartElement("EmpID","1");
tw.WriteAttributeString("Name","krishnan");
tw.WriteElementString("Designation","Software Developer");
tw.WriteElementString("FullName","krishnan Lakshmipuram Narayanan");
tw.WriteEndElement();
tw.WriteEndElement();
tw.WriteEndDocument();
tw.Flush();
tw.Close();
so next time we add data to file we need to check if the file exits and add data to xml file
and as we have made empID as a primary key, if user tries to make duplicate entry we need to avoid
Is this possible to do?
if (!File.Exists(filename))
{
// create your file
}
or
if (File.Exists(filename))
{
File.Delete(filename);
}
// then create your file
File class is in System.IO namespace (add using System.IO; to your file)
You can't append records to an XML file, you have to read the file and then rewrite it.
So, just check if the file exists, and read the records from it. Then write the file including all previous records and the new record.
Have a look at the File.Exists method here
Testing for existance of a file before attempting to create it inherently is subject to a "things change after check" race condition. Who can guarantee you that your application isn't preempted and put to sleep for a moment after you checked, someone else creates/deletes that file, your app gets to run again and does exactly the opposite of what you intended ?
Windows (as well as all UN*X variants) supports file open/create modes that allow to perform that create-if-nonexistant/open-if-existant operation as a single call.
As far as .NET goes, this means for your task (create an XML file) you'd first create a System.IO.FileStream with the appropriate modes, see http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx and then pass that stream to the XmlWriter constructor. That's safer than simply performing an "exists" check and hoping for the best.