I almost migrated all tests to Robolectric 3.0. It was huge deal :)
I have last failing test because I can not access test database that I used for migration tests. Next code produces NPE:
String filePath = getClass().getResource( "/test.db" ).toURI().getPath();
Do you know a way how to get absolute path to this file in Robolectric 3.0? I want to avoid hardcoding since I want to have test working on all machines
Maybe will be helpful for someone. My code:
private void copyTestDatabase( String resourceDBName )
throws URISyntaxException, IOException
{
String filePath = RuntimeEnvironment.application.getPackageResourcePath() + "/src/test/res" + resourceDBName;
String destinationPath = RuntimeEnvironment.application.getDatabasePath( "<my-db-name>.db" ).getAbsolutePath();
File to = new File( destinationPath );
to.mkdirs();
to.delete();
Files.copy( new File( filePath ), to );
}
Let me know if you have more elegant solution. Post the answer I will accept it
Related
I am making a GUI file mover using Treeview, the only issue I am having is getting the absolute file path.
When I use this code:
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo sourceDir = new DirectoryInfo(textBox1.Text);
sourceDir.EnumerateFiles();
var fileToMovePath = Path.GetFullPath(treeView1.SelectedNode.FullPath);
var pathToMoveToo = textBox2.Text;
//File.Move(fileToMovePath, pathToMoveToo);
MessageBox.Show(fileToMovePath);
}
I get this file path:
Which obviously isn't what I want, as that file is actually stored on my desktop. Any ideas?
I was facing a similar problem and after some trial and error following solution worked for me.
Replace
var fileToMovePath = path.GetFullPath(treeView1.SelectedNode.FullPath);
With
var fileToMovePath = textBox1.Text + "\\" + treeView1.SelectedNode.Text;
I think the problem here was with path.GetFullPath(), that it was displaying the path to directory from where program is being executed and not the one we picked.
I need to deploy Sql Databases into an Azure Sql Server using to ways: the ARM template way, and a more custom way using C# code. There's a ARM template function called uniqueString(string) that generate a pseudo random hash of a given string. It's a deterministic pure function.
I need to find a way to exactly mimic the behaviour of this function from my C# code. ie I need to reproduce this function into my C# code.
Where can i find the algorithm used by the ARM Api ?
MSDN reference for uniqueString()
Update 2023-01-05 - As suggested by other answers, there's an easier way now - just reference the Azure.Deployments.Expression nuget package which contains all of the Arm functions and then use the following convenience wrapper:
using Azure.Deployments.Expression.Expressions;
using Newtonsoft.Json.Linq;
public static class ArmFunctions
{
public static string? UniqueString(params string[] values)
{
var parameters = values.Select(
arg => new FunctionArgument(
JToken.FromObject(arg)
)
).ToArray();
var result = ExpressionBuiltInFunctions.Functions
.EvaluateFunction("uniqueString", parameters, null);
return result.Value<string>();
}
}
// "zcztcwvu6iyg6"
var unique = ArmFunctions.UniqueString("tyeth");
Original answer for posterity:
I've been researching this myself on and off for a few years now, and I've finally hit paydirt...
// "zcztcwvu6iyg6"
var unique = ArmUniqueString("tyeth");
My ArmUniqueString function is a wrapper around some dlls that are distributed with the Azure Stack Hub Development Kit which is basically a virtual machine image that contains the Azure server-side platform that you can run locally...
private static string ArmUniqueString(string originalString)
{
var assembly = Assembly.GetAssembly(
typeof(Microsoft.WindowsAzure.ResourceStack.Frontdoor.Templates.Engines.TemplateEngine)
);
var functions = assembly.GetType(
"Microsoft.WindowsAzure.ResourceStack.Frontdoor.Templates.Expressions.TemplateExpressionBuiltInFunctions"
);
var uniqueString = functions.GetMethod(
"UniqueString",
BindingFlags.Static | BindingFlags.NonPublic
);
var parameters = new object[] {
"uniqueString",
new JToken[] {
(JToken)originalString
}
};
var result = uniqueString.Invoke(null, parameters).ToString();
return result;
}
You'll need to download the Azure Stack Hub Development Kit and unpack it to get the dlls:
Download the Azure Stack Hub Development Kit - warning: it's about 22Gb!
Run the installer to unpack a 55Gb *.vhdx
Mount the *.vhdx, or expand / unpack it locally
Inside the *.vhdx, find this file and unzip it somewhere:
CloudBuilder\CloudDeployment\NuGetStore\Microsoft.AzureStack.Setup.Services.ResourceManager.5.20.1335.300.nupkg
The content\Website\bin folder inside the *.nupkg contains the necessary dlls
To use them, add an assembly reference to Microsoft.WindowsAzure.ResourceStack.Frontdoor.Templates.dll (it has some dependencies on other files in the bin folder) and that contains the TemplateExpressionBuiltInFunctions class. The code above just uses reflection to invoke the private UniqueString function from that assembly, with a little bit of work to marshal the parameters into appropriate JToken types.
If you wanted to dig into the implementation details you could probably run a decompiler against the assembly to find out what it's doing under the covers...
Note - credits go to this blog article for pointing me in the right direction:
https://the.agilesql.club/2017/12/azure-arm-template-function-internals/
I found some PowerShell code to do this here: https://blogs.technet.microsoft.com/389thoughts/2017/12/23/get-uniquestring-generate-unique-id-for-azure-deployments/
I converted this code to C#:
public string GetUniqueString(string id, int length = 13)
{
string result = "";
var buffer = System.Text.Encoding.UTF8.GetBytes(id);
var hashArray = new System.Security.Cryptography.SHA512Managed().ComputeHash(buffer);
for(int i = 1; i <= length; i++)
{
var b = hashArray[i];
var c = Convert.ToChar((b % 26) + (byte)'a');
result = result + c;
}
return result;
}
This function is released in nuget: https://www.nuget.org/packages/Azure.Deployments.Expression/
The implementation:
https://msazure.visualstudio.com/One/_git/AzureUX-Deployments?path=%2Fsrc%2FExpressions%2FExpressions%2FExpressionBuiltInFunctions.cs&version=GBmaster&_a=contents
Example:
using Azure.Deployments.Expression.Expressions;
using Newtonsoft.Json.Linq;
var funcs = ExpressionBuiltInFunctions.Functions;
var jt = new JTokenExpression("test");
var output = funcs.EvaluateFunction("uniqueString", new JToken[] { jt.Value }).ToString();
Sam Cogan wrote a blog post on how to do this in C# here: https://samcogan.com/using-bicep-functions-in-c-if-you-really-want-to/
Inspired by Sam, I wrote a PowerShell module (for PowerShell 7) that does the same. You can install the module by running Install-Module -Name AzExpression which will give you command called New-AzUniqueString.
Here is an example on how to use it:
New-AzUniqueString -InputStrings 'test', 'value'
Which will output: bhxq2thzm5dym
I finally found a workaround. I used a very simple ARM template which goal is to only output the result of the uniqueStringcommand. Then I fetch this output in my C# code. This solution is not really the quickest one ;-), but it works as desired.
Here is a bicep template which will output a uniqueString for a resource group:
output unique string = uniqueString(resourceGroup().id)
My co-workers and I are working on a Coded UI project. We both have the same version of the project thanks to TFS, but on his computer all the test cases run, and on mine they don't. They used to run perfectly fine on my machine until one morning they decided to not work. I always keep getting the same error that the UI Test Controls are not found, even though the mappings are correct. Let me remind you that they work perfectly fine on my co-workers machine. We also have the same version of IE (11).
What could be the cause for this?
Thanks for the help in advance.
My co-worker seemed to resolve the situation, but we still don't understand why the previous version of the code worked for everyone but my machine. The problem occurred in our LaunchBrowser method which would use 2 different instantiations of the browser variable. He got rid of the unnecessary one and the playback commands and seemed to have fixed the problem.
Below are two versions of the code, the previous one and the newly written one:
Old:
public static void LaunchBrowser(string url)
{
GlobalVariable.browser = new BrowserWindow();
CloseAllBrowsers();
BrowserWindow.CurrentBrowser = GlobalVariable.BrowserType;
Playback.PlaybackSettings.WaitForReadyLevel = Microsoft.VisualStudio.TestTools.UITest.Extension.WaitForReadyLevel.Disabled;
GlobalVariable.browser = BrowserWindow.Launch();
System.Uri URI = new System.Uri(url);
GlobalVariable.browser.NavigateToUrl(URI);
Playback.PlaybackSettings.WaitForReadyLevel = Microsoft.VisualStudio.TestTools.UITest.Extension.WaitForReadyLevel.UIThreadOnly;
GlobalVariable.browser.Maximized = true;
if (BrowserWindow.CurrentBrowser == "Firefox")
{
Mouse.Click(_fireFoxAuthOK);
}
Logging.WriteLog("Browser was navigated to " + url + " in browser: <" + GlobalVariable.BrowserType + ">");
}
New:
public static void LaunchBrowser(string url)
{
CloseAllBrowsers();
BrowserWindow.CurrentBrowser = GlobalVariable.BrowserType;
GlobalVariable.browser = BrowserWindow.Launch(new Uri(url));
GlobalVariable.browser.Maximized = true;
if (BrowserWindow.CurrentBrowser == "Firefox")
{
Mouse.Click(_fireFoxAuthOK);
}
Logging.WriteLog("Browser was navigated to " + url + " in browser: <" + GlobalVariable.BrowserType + ">");
}
I think the problem is in this line :
Playback.PlaybackSettings.WaitForReadyLevel = Microsoft.VisualStudio.TestTools.UITest.Extension.WaitForReadyLevel.UIThreadOnly;
Because the browser's foreground thread is not ready to start the playback. you may try this
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.Disabled;
or different alternative ways in your pc.
Refer this link Mathew Aniyan's Blog for further information.
I want to open a text file programmatically using C#. I have used :
System.Diagnostics.Process.Start(test.txt);
but this code is causing OS command injection problem when scanning for threats.
Is there any way that i can open a text file programmatically?? or way to bypass that OS command injection?
Thank you
You should call a program, say notepad:
Process.Start("notepad.exe", fileName);
the argument is the file name:
Process.Start("notepad.exe", "Test.txt");
See the problem with your code in the comments of this post:
Open a file with Notepad in C#
Try:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
string _path = "c:/filepath";
startInfo.Arguments = string.Format("/C start {0}", _path);
process.StartInfo = startInfo;
process.Start();
I'm trying to iterate through all the files contained in the assets folder. To get the working directory I use: AAssetManager_openDir. However simply having this in my code causes a crash on startup - android_main doens't even get a look in. Has anybody had similar problems and/or know how to resolve this?
const char* filename = (const char*)NULL;
const char* dirName = "";
AAssetDir* dir = AAssetManager_openDir(assetManager, dirName);
while((filename = AAssetDir_getNextFileName(dir)) != NULL)
{
//action per file
}
AAssetDir_close(dir);
Well I didn't have any luck getting it to work so I tried a different approach.
I compiled a static library of Minizip and, combined with Zlib, opened the APK file (the path of which found via JNIEnv) and found the filenames nestled within, skipping over entries not contained in the assets folder.
Roundabout way to do it but since AAssetManager_openDir isn't working this seemed like the only option.
Still it would be nice if somebody does find the "correct" solution.
const char* dirName = "";
Is probably what is causing the crash.
Instead try:
while(1)
{
const char* filename = AAssetDir_getNextFileName(dir);
if(!filename)
break;
}