ResXResourceWriter deletes another entries in resource file - asp.net

everyone!
I try to update values in .resx file with ResXResourceWriter and the value which I updated with AddResource method call effected it well. But the other values were deleted. I didn't receive any errors.
Platform is ASP.NET 3.5, Windows 7-x64.
Here is a code of key method in writing-workflow:
void UpdateResourceValueOfKey(string resFileName, string key, string value)
{
using (ResXResourceWriter resourceWriter = new ResXResourceWriter(resFileName))
{
string resValue = contentEditor.InnerText;
resourceWriter.AddResource(key, value);
resourceWriter.Generate();
resourceWriter.Close();
}
}
Any ideas would be appreciated.

I ddin't find the reason of this strange behavior, but I solve it by copying all values from resx into dictionary, then made all changes in dictionary and save all pairs from it to the same resx file. I know, this is bad approach, but works for me.

Related

Exclude specific sharedpreference key with Android 6.0 auto backup

I have implemented the "old" GCM implementation where the sample code had the following:
public static final String PROPERTY_REG_ID = "registration_id";
private SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(SampleApp.class.getSimpleName(),
Context.MODE_PRIVATE);
}
...
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
With the new backup system in Android 6.0 it says you should exclude this key but the exclude format docs:
http://developer.android.com/training/backup/autosyncapi.html
doesn't really seem to indicate how you can exclude a sharedpreference except saying that:
sharedpref: Specifies a SharedPreferences object that the
getSharedPreferences() method returns.
There isn't a getSharedPreferences() with no parameters to my knowledge?
I tried:
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<exclude domain="sharedpref" path="registration_id"/>
</full-backup-content>
But that didn't seem to work naturally since I haven't indicated which sharedpreference file it should exclude from. Anyone successfully implemented this?
The exclusion is for a shared preferences file, not a single key within the file.
(In your example, your filename is got via SampleApp.class.getSimpleName().)
As the comment points out, you need to specify a full filename, so remember to include the ".xml" file extension when you put the name in the exclude instruction.

Key not valid for use in specified state error when using ProtectedData.Unprotect

I have a little problem in using a simple ProtectedData.Unprotect call, here's the code I'm sharing, maybe I'm missing something here.
public static byte[] SampleDecrypt(IEncrypted symmetricallyEncrypted, string base64DpapiLocalEncyrptedKey)
{
if (base64DpapiLocalEncryptedKey == null)
{
throw new ArgumentNullException("base64DpapiLocalEncryptedKey");
}
byte[] unprotectedKey =
ProtectedData.Unprotect(
base64DpapiLocalEncyrptedKey,
null,
DataProtectionScope.LocalMachine);
return unprotectedKey;
}
Where base64DpapiLocalEncyrptedKey is:
"ABCCENCMnd8CFdERjHoAVV/Pl+sMAAAA4q4wemrun5a67ohPku3cIAQCCCBAAAAKKKDZgAAqAAAABADDDCvGV5W6fCNcWbb9LPZp2U3AAAYYYSBBBCgDDDDEAAAANlpDcUbBvGqMyHXk8CPtUEoBBBBlB1TtMZRC05ASxGV1/c3U548eVSPUO4X307ZDjRYytjNC35Di92q9RQAAACN//xNkexvIrGULI9GG9MdyS9Lee=="
when I ran the above it gives me the "Key not valid for use in specified state"
Thank you so much in advance guys!
I've figured out the problem. DPAPI pairs the encrypted key with your machine (assuming it's encrypted using a machine scope) in my case, localmachine scope was used.
Thought it may help anyone out there having the same issues. Try the key onto different machines to see if one works and not on the other to verify that you have a wrong key.
I created a new key off of a different server and was able to use it.

Error when csv data contains comma

I am using ASP.NET VB.NET, CSV File upload and FileHelpers, ASP.NET control is File Upload
Code to read CSV File
Using sr As New StreamReader(FileUpload1.PostedFile.InputStream)
Dim engine As New FileHelperEngine(GetType([MyClass]))
For Each entry As [MyClass] In engine.ReadStream(sr)
Next
End Using
FileHelpers
<DelimitedRecord(",")> _
<IgnoreFirst(1)> _
<IgnoreEmptyLines> _
Class [MyClass]
<FieldTrim(TrimMode.Both)> _
Public Prop1 As String
<FieldTrim(TrimMode.Both)> _
Public Prop2 As String
End Class
Question
There is some comma in data and due to that It is crashing.
VB.net provides exactly what you are looking for in Microsoft.VisualBasic.FileIO. You can use it in C# however, as shown below:
TextFieldParser parser = new TextFieldParser(pFileName);
parser.SetDelimiters(",");
parser.TextFieldType = FieldType.Delimited;
while (!parser.EndOfData)
{
string current = parser.ReadFields();
}
Edit
Just noticed you are using VB - basic premise remains the same, but don't know enough about VB.net to rewrite it. It will work though, as I had the exact same problem and it fixed it.
If your CSV looks like:
value1,value2,valu,e3
it always will be 4 columns not 3
But if CSV looks like:
value1,value2,"valu,e3"
I recomended use regexp split like:
var result = Regex.Split(csvline, ",(?=(?:[^']*'[^']*')*[^']*$)");
In this case,the file has errors and it's pretty much impossible to know what's wrong with an individual line except to say "there are too many fields when split by comma". There is no sane way your code can fix this error, you have to throw it back to the user who is uploading the broken file.
You can set the FileHelper's ErrorMode setting to SaveAndContinue (see here) so that it doesn't throw on error, and after your loop check the Errors property and if it's not empty, report the problem to the user, listing out each ErrorInfo in the Errors collection.

servlets - choose a filename for uploaded files

I am interested in images but the question is quite general. I am doing it thusly :
private static final SecureRandom RANDOM = new SecureRandom();
private static final int FILENAMElENGTH = 73; // a guess
private static String nextId() { // synchronized ?
return new BigInteger(FILENAMElENGTH, RANDOM).toString(32);
} // https://stackoverflow.com/a/41156/281545
Questions :
Are there pros and cons in storing the files with the session id + a timestamp ? Pros as in use this info later and cons as in security
Are there any standard (see servlet API or Java) way of generating a name ? Any standard practices ? Any container specific tips (glassfish and tomcat)
I understand that keeping the original filename, the username etc can lead to security holes
Related :
File uploading : What should be the name of the file to save to?
JSP: Best practices uploading files to server
static File getImageFile() throws IOException {
return File.createTempFile("upload_", ".jpg", new File(upload_path));
}
// String filename = getImageFile().getName();
This is guaranteed to be unique (docs) - and it is not a tmp file at all (provided you have control to the upload_path, which must be a path to an existing directory (although the docs are not explicit about this)).
Obviously you should have a better way to specify the extension but this is another question.
No session ids, user input etc.
Got the idea from a BalusC blog post :
It is necessary to know the file upload location in the MultipartMap as well, because we can then make use of File#createTempFile() to create files with an unique filename to avoid them being overwritten by another file with a (by coincidence) same name. Once you have the uploaded file at hands in the servlet or bean, you can always make use of File#renameTo() to do a fast rename/move.
Notice that createTempFile used to be rather insecure before Java 6.11 (see here for an exposition and here for a general exposition of tmp files security). Also see this SO question - there is a window of vulnerability between file creation and opening. These issues however have nothing to do with filenames - still createTempFile is the only way to guarantee uniqueness (I hope you are using latest JDK, to avoid the predictable filenames createTempFile suffered from).
You may want to use a Universally Unique Identifier. They are nicely supported in Java 7. If you use the static method UUID.randomUUID(), you should have a reasonably unique identifier. Note that in theory you could run across a duplicate, but the chances of that are extremely small, so much so that it is considered a very strong solution for what you are trying to do (see the discussion on the Wikipedia link).
Mind you, the generated sequence of characters is not user-friendly at all, but from what I understand of your requirements, that is all right.
Good luck!

What is the most efficient way to perform the reverse of Server.MapPath in an ASP.Net Application

I am building an MVC application in which I am reading a list of files from the file system and I want to pass the relative URL to that file to the view, preferably prefixed with "~/" so that whatever view is selected cab render the URL appropriately.
To do this, I need to enumerate the files in the file system and convert their physical paths back to relative URLs. There are a few algorithms I've experimented with, but I am concerned about efficiency and minimal string operations. Also, I believe there's nothing in the .Net Framework that can perform this operation, but is there something in the latest MVC release that can?
At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:
We need to get the Application root, and replace it in our new path with ~
We need to convert the backslashes to slashes
public string ReverseMapPath(string path)
{
string appPath = HttpContext.Current.Server.MapPath("~");
string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));
return res;
}
Isn't this what UrlHelper.Content method does? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx
I did some digging, trying to get the UrlHelper class to work outside of a controller, then I remembered a old trick to do the same thing within an aspx page:
string ResolveUrl(string pathWithTilde)
Hope this helps!
See:
https://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl(v=vs.110).aspx

Resources