Exclude specific sharedpreference key with Android 6.0 auto backup - android-6.0-marshmallow

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.

Related

Reading ?= arguments to dynamically set debug mode

I was wondering how to read the arguments from a url, ie. localhost:12345?debug=true and be able to set the debug mode. I originally wanted to use the same controller I use by default, however I got an error when I tried to set #define DEBUG because it wasn't at the start of the file, which means I need a separate controller to do this, but how do I check to see if ?debug=true is there, and to check if debug is set to true rather than false?
You are making too much work for yourself. In your web.config, you can set the compilation to be in debug mode (or not)
<compilation debug="true">
If this is set in your web.config, use the framework to tell you if you are in debug mode or not. If the above line (debug="true"), then the HttpContext.Current.IsDebuggingEnabled will return true.
if (HttpContext.Current.IsDebuggingEnabled)
{
DoSomethingDebuggy();
}
else
{
DoSomethingElseCompletely();
}
Now, you no longer need to append a random query string for debug mode (which I am sure will make your routes and links happier). However...if you really really want to keep that query string, then in your controller/action, you can use the following:
public ActionResult Home(){
var debugParam = Request.QueryString["debug"];
//be sure to check for null or empty string before casting to a bool
}
So because in my project, in the .cshtml file, I was using razor to check to see if the debugger was set, I just added an extra argument, || Request.QueryString["string"] == "value" and it solved my problem. A one line fix, where string is the name of the argument you want to look for.

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!

ResXResourceWriter deletes another entries in resource file

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.

Asp.net mvc - get full file name of uploaded file

Is it possible to get full file name of uploaded file in asp.net mvc?
UPDATE
The data contains only the file name, but doesn't the file path! See the attached image for details.
It depends on the browser.
Most browsers (FF, Chrome, Safari) do not send this information, primarily for security reasons. However, it appears as though some versions of IE do send the full client path.
This value will be stored in the FileName property of the HttpPostedFile.
The documentation for FileName should help. It says:
FileName: The name of the client's file, including the directory path.
In the following code, postedFile.FileName will vary based on the browser. Therefore, it's important to always extract just the filename, and you might also get lucky and get the clientPath too.
public ActionResult UploadFile(HttpPostedFile postedFile) {
var clientPath = IO.Path.GetDirectoryName(postedFile.FileName);
var filename = IO.Path.GetFileName(postedFile.FileName);
... Save the file, etc ...
}

how to check whether a file exists before creating it

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.

Resources