How do I programmatically access the Settings.bundle? - swift2

Scenario:
Settings.bundle within the host application.
Goal:
To access the data within the settings.bundle.
Modus Operandi:
To dump the settings data into a dictionary for in-program access.
Here's my first attempt. I tried accessing the path, then the bundle. Both didn't work:
let path = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle")
let myBundle = NSBundle(path: path!)
let myData = NSDictionary(contentsOfFile:path!)
What's the correct syntax of collecting data from the Settings.bundle (which contains the root.plist)?

You can access the saved values via NSUserDefaults.
For example if you want to get the previously set value ("bar") from the setting named as "foo", then the code to get it is:
let valueOfFoo = NSUserDefaults.standardUserDefaults().valueForKey("foo")
In this case the content of valueOfFoo variable will be "bar".
Note: this returns an Optional

Related

Access the Android Special Folder Path by using Environment

I want to save my logs to a folder which I can access with windows explorer. For example I want to create my log in the following path
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So I tried to use Environment variables... I get such as
/data/user/...
But here i cannot see the file what I created (using code I can access the path but I want to see in the explorer).
how I can create a path like above with code?
When I tried this code
var finalPath2 = Android.OS.Environment.GetExternalStoragePublicDirectory
(Android.OS.Environment.DataDirectory.AbsolutePath);
I get the path "/storage/emulated/0/data"
and
If i use the code
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.ApplicationData),"logs");
I get the following path like:
/data/user/0/MyApp/files/.config/logs
and
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments),"logs");
"/data/user/0/IM.OneApp.Presentation.Android/files/logs"
but unfortunately I cannot access this folder by explorer....
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So how to find out this path in c# by using environments?
Update:
when I give the following path hardcoded, it creates the file where I want..
logDirectory = "/storage/emulated/0/Android/data/MyApp/files/logs";
is there any environment to create this path? I can combine 2 environments and do some string processing in order to create this path. But maybe there is an easier way?
You are looking for the root of GetExternalFilesDir, just pass a null:
Example:
var externalAppPathNoSec = GetExternalFilesDir(string.Empty).Path;
Note: This is a Context-based instance method, you can access it via the Android application context, an Activity, etc... (see the link below to the Android Context docs)
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using Environment.getExternalStorageState(File).
There is no security enforced with these files. For example, any application holding Manifest.permission.WRITE_EXTERNAL_STORAGE can write to these files.
re: https://developer.android.com/reference/android/content/Context#getExternalFilesDir(java.lang.String)
string docFolder = Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments), "logs");
string libFolder = Path.Combine(docFolder, "/storage/emulated/0/Android/data/MyApp/files/logs");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
string destinationDatabasePath = Path.Combine(libFolder, "temp.db3");
db.Backup( destinationDatabasePath, "main");

TestComplete_JavaScripting_how to hide web url path while performing any operation for any object in script

I'm new to use Testcomplete , i'm using javascripts to automate my code, below are sample script ( converted one recorded first then converted into jscript) and in this scripts what i observe that TestComplete identified and captured the object element by using complete web url path not on only object specific .
efunction Test_Login {var UserName, Password, TestEnv;UserName = "XYZ";Pwd = "XYZXYZ";TestEnv = "https://test.Env.com/";Browsers.Item(btChrome).Run("TestEnv",1);Aliases.browser.pageTestenvCom.formFrmlogincomponent.textboxUsername.SetText("UserName");Aliases.browser.pageTestenvCom.formFrmlogincomponent.passwordboxPassword.SetText("Pwd");Aliases.browser.pageTestenvCom.formFrmlogincomponent.buttonLogin.ClickButton();}e
what i means lets see below example of login page
thank you
Whenever we record any Test case in Test-Complete, it stores all the object in the Naming Repository and then access the same.
This helps test-complete in easily recognisation of object and can improve the speed of test-case, in case there are multiple objects visible on screen
You can go through following link for more info on Name Mapping.
https://support.smartbear.com/testcomplete/docs/testing-with/object-identification/name-mapping/overview.html

Manually populate an ImageField

I have a models.ImageField which I sometimes populate with the corresponding forms.ImageField. Sometimes, instead of using a form, I want to update the image field with an ajax POST. I am passing both the image filename, and the image content (base64 encoded), so that in my api view I have everything I need. But I do not really know how to do this manually, since I have always relied in form processing, which automatically populates the models.ImageField.
How can I manually populate the models.ImageField having the filename and the file contents?
EDIT
I have reached the following status:
instance.image.save(file_name, File(StringIO(data)))
instance.save()
And this is updating the file reference, using the right value configured in upload_to in the ImageField.
But it is not saving the image. I would have imagined that the first .save call would:
Generate a file name in the configured storage
Save the file contents to the selected file, including handling of any kind of storage configured for this ImageField (local FS, Amazon S3, or whatever)
Update the reference to the file in the ImageField
And the second .save would actually save the updated instance to the database.
What am I doing wrong? How can I make sure that the new image content is actually written to disk, in the automatically generated file name?
EDIT2
I have a very unsatisfactory workaround, which is working but is very limited. This illustrates the problems that using the ImageField directly would solve:
# TODO: workaround because I do not yet know how to correctly populate the ImageField
# This is very limited because:
# - only uses local filesystem (no AWS S3, ...)
# - does not provide the advance splitting provided by upload_to
local_file = os.path.join(settings.MEDIA_ROOT, file_name)
with open(local_file, 'wb') as f:
f.write(data)
instance.image = file_name
instance.save()
EDIT3
So, after some more playing around I have discovered that my first implementation is doing the right thing, but silently failing if the passed data has the wrong format (I was mistakingly passing the base64 instead of the decoded data). I'll post this as a solution
Just save the file and the instance:
instance.image.save(file_name, File(StringIO(data)))
instance.save()
No idea where the docs for this usecase are.
You can use InMemoryUploadedFile directly to save data:
file = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = InMemoryUploadedFile(file,
field_name='file',
name=request.POST['name'],
content_type="image/jpeg",
size=sys.getsizeof(file),
charset=None)
instance.image = image
instance.save()

trouble accessing files loaded into project

I've added a bunch of files to my swift project folder like so:
I need to access these files at a certain point in the project for two purposes:
Use the name of each file to populate Categories (ie. Age, Alone, Amazing...)
Access the data within the files to populate each Category items page
I've implemented this code in the viewDidLoad of my class to access and iterate through the files
//get categories
let fileManager = NSFileManager.defaultManager()
let directoryPath = NSHomeDirectory() + "/Categories"
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!
while let element = enumerator.nextObject() as? String {
println(String(element))
}
This does not work and produces the error fatal error: unexpectedly found nil while unwrapping an Optional value on the line let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!. I suspect (and correct me if I'm wrong), that it is accessing the applications internal file structure and as a result cannot find the files specified. As I am new to IOS development, my general understanding of how this works is nebulous at best.
So How exactly do I access files I've added the project in the way I've shown in the image, so as to iterate through and get the data I'm looking for
EDIT
So I've changed the structure to make the Categories folder an actual folder like so:
I'm currently trying to use NSBundle to access the application route, however I am not sure how to do that. Any guidance would be appreciated.
The problem is that xcode's project navigator folders are not actual folders in the disk. So this:
let directoryPath = NSHomeDirectory() + "/Categories"
does not exist in your hdd. If you want this folder you have to navigate to your projects folder on your hdd, create it manually and add the files you want in it.
You can refer to a file and read it like this:
let htmFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "html")
let htmlString = NSString(contentsOfFile: htmFile!, encoding: NSUTF8StringEncoding, error: nil)
for json you can get a dictionary with
let jsonFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "json")
let dict = NSDictionary(contentsOfFile: jsonFile)

System.IO.File.Exists() returns false

I have a page where I need to display an image which is stored on the server. To find that image, I use the following code:
if (System.IO.File.Exists(Server.MapPath(filepath)))
When I use this, I get a proper result as the file is present.
But when I give an absolute path like below:
if (System.IO.File.Exists("http://myserever.address/filepath"))
It returns false.
The file is physically present there, but I don't know why it's not found.
The path parameter for the System.IO.File.Exists is the path to an actual file in the file system.
The call to Server.MapPath() changes the URI into an actual file path.
So it is working as intended.
You can't use HTTP paths in File.Exists. It supports network shares and local file systems. If you want to do this in a web application on the server side. First use Server.MapPath() first to find the physical location and then use File.Exists.
Read about Server.MapPath here: http://msdn.microsoft.com/en-us/library/ms524632%28v=vs.90%29.aspx
Eg.
string filePath = ResolveUrl("~/filepath/something.jpg");
if (File.Exists(Server.MapPath(filePath)))
{
//Do something.
}

Resources