MVC App pointing to wrong hive(Registry) - iis

In my MVC app i have the following code:
Private ipConecta As String = My.Computer.Registry.GetValue(
"HKEY_CURRENT_USER\Software\SPR4", "ConnString", Nothing)
But looking in the Process monitor, i see that is pointing to another hive:
How can i make it pointing to read the registry on HKEY_CURRENT_USER\Software\SPR4

Finally, i resolve my issue, pointing to HKEY_LOCAL_MACHINE:
Private reg As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\SPR4")
And giving permissions on that key to the user IUSR.

Related

ConnectionString is null when deploying Azure Function

I've been working with functions with Azure, I've built a very simple Http Function locally by following the example linked here, the only difference is I've defined a User table instead of a Todo table
Everything works as expected locally, I'm able to post and get.
However, when deploying the function and trying to make a POST request I see the following within the logs:
Executed 'User' (Failed, Id=5df9dffe-eedf-4b11-aa10-54fda00992b0, Duration=1ms)System.ArgumentNullException : Value cannot be null. (Parameter 'connectionString')
I've checked the SQL Server to ensure it's accessible by other Azure Services just encase that was causing a problem, but I can confirm it's set to allow.
I have found this question, I've gone through the steps and checked against mine and I can confirm my Function App configuration does have the AzureWebJobsStorage connection string.
I'm not 100% sure why this would be happening due to my lack of knowledge of functions at the moment, have anyone else experience this? if so how did you resolve it?
Update
After further testing, it seems the error is coming from my Startup class,
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
string connectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
builder.Services.AddDbContext<ApplicationDbContext>(
options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString));
}
}
Upon deployment, connectionString variable is null.... not sure why though.
Yes, you can not get it because you didn't set it in the configuration settings.
If you want to use the Connection Strings section.
Add the "ConnectionStrings":{} section to your local.settings.json file then add your connection string
{
...
"ConnectionStrings": {
"MyConnectionString": ""
}
}
Then you need to set the connection string in the Settings section of the Function App in the Azure Portal.
The scroll down to the Connection Section
And add a new connection string. Make sure it has the same name as you connection in the local.settings.json file.
Your question isn't 100% clear if this is happening locally (as you refer to local.settings.json) or when deploying. If this occurs when deploying, changing your local.settings.json file will not help, unfortunately.
You will need to add the Application Setting within the Azure Portal (located under Settings -> Configuration -> Application Settings -> New application setting).
You will need to save the application setting, and then restart the Azure Function instance for the changes to reflect.
Check out https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings?tabs=portal

Problems authenticating with MSAL and Azure B2C in a Xamarin.Forms app

I'm having some difficulty getting one of the sample Xamarin.Forms/Azure applications to work with my own Azure B2C tenant, specifically active-directory-b2c-xamarin-native.
I was able to get the sample to work out of the box, my only change being to update all the XF NuGet packages. At this point both the Android (on my Google Pixel) and UWP versions worked perfectly; on iOS I was able to log in/out and edit the profile (it still has the known issue that iPhoneSimulator doesn't properly save tokens in the keychain, so the API and caching doesn't work, but i'm ignoring that for now until i can get an actual iPhone). The problems started when I tried to set up and use my own B2C tenant, according to the instructions in the readme file. Since the original sample works, it's safe to assume that the code is ok; the only changes I made were to the magic strings at the top of App.cs, and the redirect URI's stored in AndroidManifest.xml and Info.plist. So the working theory is that I either entered one of those strings wrong, or the B2C setup is wrong. I've gone over this multiple times now and I can't find the issue. I'm willing to bet these are all caused by the same mistake on my part, though.
Problem 1 (solved). UWP app does not allow login. Instead when the embedded browser opens I get the message "We can't connect to the service you need right now. Check your network connection or try this again later", followed by an "MsalException: WAB authentication failed" dialog once I dismiss the browser.
This was the only issue I was able to fix so far, either by commenting out this line in the UWP.MainPage constructor:
UserDetailsClient.Core.App.PCA.RedirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
or by adding the value returned by that GetCurrentApplicationCallbackUri() call (which is something like "ms-app://s-1-15-2-900855338....") to the Custom Redirect URI list of the UI app in B2C. I would prefer simply removing the line of code, but that begs the question as to why that line of code was needed in the first place. Perhaps someone can suggest why using the ms-app:// redirect on the backend might be preferable to the msalXXXX://auth used by the other platforms. I have no idea why the original sample worked with the ms-app:// redirect; perhaps that string is actually constant across all apps and is already defined in the sample's B2C tenant.
Problem 2. Having gotten past the UWP login issue now everything works on that platform EXCEPT for the API call. I get a 401 Unauthorized.
The API code is taken straight from the tutorial Develop Cloud Connected Mobile Apps with Xamarin and Microsoft Azure; it's just the backend from Chapter 1, with the [Authorize] attribute added to the TodoItemController. (All of the Chapter 1 code works, btw) App Service Authentication is still turned off on the API itself (not the B2C tenant) in Azure. If I remove the Authorize attribute from the TodoItemController, it works, provided I also pass in the additional header ZUMO-API-VERSION=2.0.0. Adding the header does not help with the 401, though.
Since I'm able to login, I'm guessing I have a valid access token, it's just not what the backend is expecting. Again, this works on the sample, so I don't know how my app differs. I suspect this issue also affects iOS and Android, but I'm not sure because unable to complete the login on those platforms. Which brings me to...
Problem 3. On Android & iOS, on clicking SIGN IN the app opens the system browser and I'm able to login in, but the subsequent redirect doesn't happen and the app remains in it's initial state. When debugging, the line after the call to App.PCA.AcquireTokenAsync() is never reached. No exception is raised.
From what I understand this is generally due to either the redirect URI being improperly formed or forgetting to add the platform-specific redirect code (intent-filter on Android, or OpenUrl on iOS). I've double-checked the URI a half-dozen times, and the code has to be correct since the sample worked. I did notice the ActivityManager START entry in the Android logcat, so the browser is sending the redirect, but the app isn't responding to it for whatever reason. Note also that the UWP client DOES work using that same msalXXXX://auth URI (this is why I bothered to explain problem 1 above)
Visual Studio 2017 15.8.6
Xamarin.Forms 3.2.0.871581
Microsoft.Identity.Client 1.1.4-preview
Below is the list of strings from App.cs, as well as screenshots from my B2C setup. Any help would be greatly appreciated!
public static string Tenant = "myapp.onmicrosoft.com";
public static string ClientID = "d43c8xxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static string PolicySignUpSignIn = "B2C_1_emailPolicy";
public static string PolicyEditProfile = "B2C_1_profileEditPolicy";
public static string PolicyResetPassword = "B2C_1_passwordResetPolicy";
public static string[] Scopes = { "https://myapp.onmicrosoft.com/api/read" };
public static string ApiEndpoint = "https://myapp.azurewebsites.net/tables/todoItem";
public static string AuthorityBase = $"https://login.microsoftonline.com/tfp/{Tenant}/";
public static string Authority = $"{AuthorityBase}{PolicySignUpSignIn}";
public static string AuthorityEditProfile = $"{AuthorityBase}{PolicyEditProfile}";
public static string AuthorityPasswordReset = $"{AuthorityBase}{PolicyResetPassword}";

File.Exists from UNC using Azure Storage/Fileshare via IIS results in false.

Problem:
trying to get an image out of azure fileshare for manipulation. I need to read the file as an Drawing.Image for manipulation. I cannot create a valid FileInfo object or Image using uncpath (which I need to do in order to use over IIS)
Current Setup:
Attach a virtual directory called Photos in IIS website pointing to UNCPath of the Azure file share (e.g. \myshare.file.core.windows.net\sharename\pathtoimages)
This works as http://example.com/photos/img.jpg so I know it is not a permissions or authentication issue.
For some reason though I cannot get a reference to File.
var imgpath = Path.Combine(Server.MapPath("~/Photos"),"img.jpg")
\\resolves as \\myshare.file.core.windows.net\sharename\pathtoimages\img.jpg
var fi = new FileInto(imgpath);
if(fi.exists) //this returns false 100% of the time
var img = System.Drawing.Image.FromFile(fi.FullName);
The problem is that the file is never found to exist, even though I cant take that path and put it in an explorer window and return the img.jpg 100% of the time.
Does anyone have any idea why this would not be working?
Do I need to be using CloudFileShare object to just get a read of a file I know is there?
It turns out the issue is that I needed to wrap my code in an impersonation of the azure file share userid since the virtual directory is not really in play at all at this point.
using (new impersonation("UserName","azure","azure pass"))
{
//my IO.File code
}
I used this guys impersonation script found here.
Can you explain why DirectoryInfo.GetFiles produces this IOException?

Windows Azure Exception: "Access to the path XYZ.exe is denied."

I use local storage on Windows Azure to store temporary files. In there I call an .exe file to make a conversion of several other files in same local storage folder. Problem is I always get the exception "Access to the path XYZ.exe is denied.".
I should mention the following:
- I am using a worker role
- set in the service definition file
and tried to add permission to the folder I am accessing:
public static void AddPermission(string absoluteFolderPath)
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo(absoluteFolderPath);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(
"NETWORK SERVICE",
FileSystemRights.FullControl,
AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
UPDATE:
I tried with this code now:
public static void FixPermissions()
{
var tempDirectory = RoleEnvironment.GetLocalResource("localStorage").RootPath;
Helper.addPermission(tempDirectory);
var dir = new DirectoryInfo(tempDirectory);
foreach (var d in dir.GetDirectories())
Helper.addPermission(d.FullName);
}
private static void addPermission(string path)
{
FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone",
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.AddAccessRule(everyoneFileSystemAccessRule);
directoryInfo.SetAccessControl(directorySecurity);
}
I get a really strange behaviour of the page. I still get the errors but sometimes some files gets converted by the ffmpeg.exe file.
Can someone help me out here??
Thanks a lot.
SOLUTION:
So seems the problem was that I ran the .exe file within local storage and therefore had the given security issues. Putting the .exe into the application and referring directly solved my issue.
Thx for your help.
By default your worker role will most likely not be running with sufficient privilege to allow changes to the access control lists on Azure folders.
There's two possible options:
Best: run a script at startup to set the permissions. Details are on MSDN here: http://msdn.microsoft.com/en-us/library/gg456327.aspx. You'll want to set executionContext="elevated".
The best way to write the script itself is through Powershell. An example is here: http://weblogs.thinktecture.com/cweyer/2011/01/fixing-windows-azure-sdk-13-full-iis-diagnostics-and-tracing-bug-with-a-startup-task-a-grain-of-salt.html. Alternatively, write a console application to do the same thing.
Easiest, but much less secure: set the security in your OnStart method, and run your whole worker role elevated: in your service definition file include
<WebRole name="WebApplication2">
<Runtime executionContext="elevated" />
<Sites>
However, I'd really not recommend that as it's a terrible security hole for something that's running in the public cloud.

Environment.GetEnvironmentVariable("RoleRoot") returning null when called in a WebRole

I have a method (in a separated class library) which is called by a WebRole and a WorkerRole. This method contains the path of a file, which is returned using Environment.GetEnvironmentVariable("RoleRoot"), as follows:
private string FooPath()
{
string appRoot = Environment.GetEnvironmentVariable("RoleRoot");
return Path.Combine(appRoot + #"\", #"approot\file.foo");
}
When I call this method from a WorkerRole the path is returned normally. But when I call it from a WebRole I get null.
Any ideas?
EDIT: I am using APNS-Sharp to send push messages to iOS and it requires a .p12 certificate in order to work. Currently I have the .p12 in the root of my class library (which is called by both WebRole and WorkerRole). But the point is: Why RoleRoot returns null when I call it from a WebRole but returns the path when I call from a WorkerRole?
RoleRoot returns false for WebRole because the WebRole uses IIS, just like a normal website. That's why it's difficult to get Environment Variables from a WebRole.
In order to get the path properly I had to use the classic Server.MapPath and reference the bin folder, instead of approot:
private string FooPathWebRole()
{
string appRoot = HttpContext.Current.Server.MapPath(#"~\");
return Path.Combine(appRoot + #"\", #"bin\file.foo");
}
For the WorkerRole nothing has changed:
private string FooPathWorkerRole()
{
string appRoot = Environment.GetEnvironmentVariable("RoleRoot");
return Path.Combine(appRoot + #"\", #"approot\file.foo");
}
In addition, I found out that Azure doesn't import p12 certificates. I would have to transform it into another format, which I don't believe would work for me. So, the best option is to place them on the root of the application and mark its Build Action to Content.
I tried from webrole and it works for me. I place it at the OnStart() code of the web role, which is called by WaIISHost
If you want to load a certificate, you could try the advice in http://blogs.msdn.com/b/jnak/archive/2010/01/29/installing-certificates-in-windows-azure-vms.aspx
Linked from How do I import a public certificate to Windows Azure?

Resources