I am relatively new to C# and i have come across this error while working on a project to spin a VM (and support resources in MS Azure).
The code I am using is the one below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
namespace ConsoleApp1
{
class Program
{
private static void Main(string[] args)
{
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
Also I have an "azureauth.properties.txt" file i used to set a new Environmental path referenced in the code above as "AZURE_AUTH_LOCATION".
To set the path i used the simple PS command:
[Environment]::SetEnvironmentVariable("AZURE_AUTH_LOCATION", "C:\MY-PATH\azureauth.properties", "User")
The azureauth.properties file contains simple Tenant/application/key IDs in the format
subscription=<subscription-id>
client=<application-id>
key=<authentication-key>
tenant=<tenant-id>
managementURI=https://management.core.windows.net/
baseURL=https://management.azure.com/
authURL=https://login.windows.net/
graphURL=https://graph.windows.net/
Whenever I am trying to run the project i get an error saying:
System.ArgumentNullException: 'Value cannot be null.'
specifically for the line:
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
Any idea why?
Like luxun said, you have to define the environment variable.
For that open the cmd (on windows) and write:
set AZURE_AUTH_LOCATION
this will show the environment variable "AZURE_AUTH_LOCATION". If the result is "Environment variable AZURE_AUTH_LOCATION not defined" or if the path is wrong then write on the cmd:
SET AZURE_AUTH_LOCATION=PathOfTheAzureAuthLocationFile
This should do the trick.
Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION") must be returning null.
If this is the case you may want to check if that environment variable has actually been defined or whether the file exists.
Define a variable like:
var location = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION");
When you debug in VS you should be able to inspect the value of location by right clicking on it and clicking quickwatch.
Many thanks for your suggestions.
in the end the error was generated by a school-boy mistake in setting the Env Variable in the first place (relative path contained an error I didn't spot earlier).
I was able to run it in the end.
Made a change to define the path in the config file instead too.
thanks
Related
I am using VS 2022, .Net 6.0, and trying to build my first app using System.CommandLine.
Problem: when I build it, I get an error
The name 'CommandHandler' does not exist in the current context
The code I'm trying to build is the sample app from the GitHub site: https://github.com/dotnet/command-line-api/blob/main/docs/Your-first-app-with-System-CommandLine.md , without alteration (I think).
It looks like this:
using System;
using System.CommandLine;
using System.IO;
static int Main(string[] args)
{
// Create a root command with some options
var rootCommand = new RootCommand
{
new Option<int>(
"--int-option",
getDefaultValue: () => 42,
description: "An option whose argument is parsed as an int"),
new Option<bool>(
"--bool-option",
"An option whose argument is parsed as a bool"),
new Option<FileInfo>(
"--file-option",
"An option whose argument is parsed as a FileInfo")
};
rootCommand.Description = "My sample app";
// Note that the parameters of the handler method are matched according to the names of the options
rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
{
Console.WriteLine($"The value for --int-option is: {intOption}");
Console.WriteLine($"The value for --bool-option is: {boolOption}");
Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
});
// Parse the incoming args and invoke the handler
return rootCommand.InvokeAsync(args).Result;
}
I have installed the latest version of System.Commandline: 2.0.0-beta2.21617.1
SURELY I am just being a big fat idiot in some respect. But I don't see it.
Any insight would be welcomed.
This issue is caused by updating the CommandLine 2.0 Beta 2 package. Add the reference System.CommandLine.NamingConventionBinder to the references to fix the problem. Follow the announcements on command-line-api's GitHub account:
In your project, add a reference to System.CommandLine.NamingConventionBinder.
In your code, change references to the System.CommandLine.Invocation namespace to
use System.CommandLine.NamingConventionBinder, where the CommandHandler.Create
methods are now found. (There’s no longer a CommandHandler type in
System.CommandLine, so after you update you’ll get compilation errors until you
reference System.CommandLine.NamingConventionBinder.)
If you want to continue with the old habits, try using older versions of the System.CommandLine package.
References
Announcing System.CommandLine 2.0 Beta 2 and the road to GA
Think you are missing a using line:
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
I can't swear that's it, but it looks like CommandHandler is defined in a namespace not referenced by a using (in your current code), so System.CommandLine.Invocation may be the key!
I am trying to load a local json file into a string such that I can parse/deserialize it into an object.
However for some reason despite all the examples and the Xamarin support documentation suggesting I can use System.IO.File.ReadAllText(...) I get the following error:
c# error: 'File' type or namespace name not found
My code seems pretty simple, I can't get past loading the file, which seems like it should be so simple!
string jsonInput = System.IO.File.ReadAllText("example.json", Encoding.UTF8);
Quiz temp = JsonConvert.DeserializeObject<Quiz>(jsonInput);
My header includes System.IO amongst the rest too..
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel; //ObservableCollection
using Newtonsoft.Json;
using System.IO;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;`
I've also tried the following solution:
var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("example.json");
string jsonInput = "";
using (var reader = new System.IO.StreamReader(stream))
{
jsonInput = reader.ReadToEnd();
}
However in this case 'LoadResourceText' is not found and I can't work out what type should replace it.
Any help or suggestions would be greatly appreciated!
My first post on StackOverflow, hope I did it right..
If you are using this file as a local resource, make sure that it is available for each device, for example, in the Android project, select the file/properties/advanced/build action and set it to embedded resource.
Sometimes the code is fine, it's just that the file 'doesn't exist' for the device
^See above response as well^
I have solved this myself.
I found my answer hidden in a forum post by YkshLeo on the Xamarin Forums:
"...make sure the Build Action for your resource is set to "Embedded Resource"
I really wish Xamarin would make their documentation a little more thorough. Maybe it's my .Net noobness coming through.
This code works fine within a Kentico website:
var users = UserInfoProvider.GetUsers();
for (int x = 0; x < users.Count(); x++
{
UserInfo currentUser = users.ElementAt(x);
currentUser.SetValue("AcceptsAlerts", equivalentSubscriber.Status != SubscriberStatus.Unsubscribed);
UserInfoProvider.SetUserInfo(currentUser);
}
When I move the code to a console app, any calls to UserInfoProvider result in the error: "Object type 'cms.usersettings' not found"
For the initial call to get the users, I can do it like this in the console app:
DataSet usersds = new CMS.DataEngine.DataQuery("cms.user.selectall").Execute();
then loop through Table1 of the dataset using the user data:
UserInfo currentUser = new UserInfo(dtUsers.Rows[x]);
All is fine and working, until I come to write the updated user back to the database. I cannot find another way of writing the data apart from calling:
UserInfoProvider.SetUserInfo(currentUser);
Does anyone know another way to save the user data? or to resolve the error. The error is a runtime error and as far as I know, I have referenced everything I need to. The field I am editing is a custom field added to the cmsUser table.
using statements for info:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using CMS;
using CMS.CustomTables;
using CMS.DataEngine;
using CMS.Membership;
Before you start working with Kentico CMS API from an external application make sure you call the following lines:
CMS.DataEngine.ConnectionHelper.ConnectionString = "your connection string";
CMS.Base.SystemContext.WebApplicationPhysicalPath = Application.StartupPath;
CMS.DataEngine.CMSApplication.Init();
Then, you'll be also able to use UserInfoProvider.GetUsers() object query instead of using DataQuery.Execute().
Are you sure you are referencing all necessary assemblies?
Following scenario works on my machine with configuration: Kentico 8.x, Web Application project
Reference in your Console application these assemblies from lib folder
CMS.Base
CMS.DataEngine
CMS.DataProviderSQL
CMS.Membership
Then copy your Connection String from Web Application's web.config to Console Application's App.config.
After that you can use this code to set custom user properties
static void Main(string[] args)
{
var users = UserInfoProvider.GetUsers();
foreach (var user in users)
{
user.SetValue("myTestString", "test");
user.Generalized.SetObject();
}
}
For anyone looking to get a SiteID to use in API calls from an external app such as getting an email template, this might help you. In Kentico 8.1 you can go to Sites > General and get the code name for your site. Then you can do this:
int siteID = CMS.SiteProvider.SiteInfoProvider.GetSiteID("<your site code name>");
Hope it helps!
I'm trying to use the Process class but it gives me this compiler error every time I do
The name 'Process' does not exist in the current context
I've already added using System.Diagnostics; at the top of my code but I still get this error. Autocomplete wont even recognize the class.
Hear is the code. I've only included the Main method because the rest of the code has nothing to do with the error.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
public class MainClass
{
static void Main()
{
AIRuntime adam = new AIRuntime("Adam", false);
adam.AIUpdate();
Process.Start(adam.directory); //adam.directory is just a string
}
}
My IDE is Xamarin Studio if it matters.
After web searching and attempts, I found the problem.
To fix this, I manually add a reference to System in my project options instead of just typing using System;. I also need to keep using System.Diagnostics; at the top. It's all in the picture below
Thanks guys for trying to help
I'm new to C# and VS, and I have a bizarre problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ExampleApplication {
class Program {
static void Main(string[] args) {
FileInfo fi = new FileInfo("C:\\TEST.TXT");
fi.Create();
Console.WriteLine("File exists: {0}", fi.Exists);
}
}
}
This is my program, it creates a file TEST.TXT. When I run the program inside VS 2010 with the Debug -> Start Debugging command (F5), the program works fine and the file is created.
However if I build the solution then run the program from the .exe using cmd prompt:
C:\...\Visual Studio 2010\Projects\ExampleApplication\ExampleApplication\bin\Debug\ExampleApplication.exe
It runs outputting: File exists: true. But the file is not created. Anyone have any ideas?
Thanks
Perhaps file stream eventually was not released by OS so file system does not reflect recent changes? Just try explicitly closing a new file stream after creation:
FileInfo fi = new FileInfo("C:\\TEST.TXT");
using (var stream = fi.Create());
Please let us know whether it works or not since it is a bit crazy idea ;) I believe problem could be even simple
I suspect that User Account Control is redirecting the file creation to the shadow copy directory; under VS you're running as an administrator, so the file creation is not redirected.
Have a look for the file in the VirtualStore directory. That will be at
C:\Users\YourUserNameHere\AppData\Local\VirtualStore
The actual folder will be something like
C:\Users\YourUserNameHere\AppData\Local\VirtualStore\C
To solve this problem, you could change the program so that it writes the file to a location intended for user data; an obvious choice would be the Documents folder. You could also run the application with administrator privileges. There are at least three ways to do this:
Right-click the executable and choose "Run as Administrator"
Run the executable with a shortcut, after checking the "Run as Administrator" check box in the shortcut's properties dialogue
Use either method above to open an "Administrator" command prompt session; then run the application normally by entering its name at the command prompt.
Could be a permissions problem. If the user account running vS is different from the one running the command prompt, they may have different permissions for creating files. Look in your Windows event viewer to see if the error is reported there. Then, use try-catch, as Marc suggested.
Just a tip. When you work with files, always do it in a try catch. You never know what could happen like in your case.
Do you run the cmd as administrator? Maybe you don't have the rights to create the file.
Also add a try catch and return the error in the console. It would help you to figure out your problem if running as administrator doesn't work.
try
{
your code..
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
You need to call fi.Refresh(); in order to have the FileSystemInfo re-examine the base object, otherwise, it will always return false.
Try to close the file as follow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ExampleApplication {
class Program {
static void Main(string[] args) {
FileInfo fi = new FileInfo("C:\\TEST.TXT");
fi.Create();
fi.Close();
Console.WriteLine("File exists: {0}", fi.Exists);
}
}
}
I don't know the reason of this, but why won't you try this:
if(!File.Exists("C:\\TEST.TXT"))
{
File.Create("C:\\TEST.TXT");
Console.WriteLine("File exists");
}
You're doing this the wrong way. You have to dispose the file object after you're done with it. To create an empty file in .NET, I'd suggest you do it like this:
using (File.Create("C:\\TEST.TXT"));
or like this:
File.Create("C:\\TEST.TXT").Dispose();
Alternatively you could just modify your fi.Create() to:
fi.Create().Dispose();
It is likely that Visual Studio Debugger is automatically cleaning up your mess for you by properly disposing all objects when you stop the debugging.
use the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ExampleApplication {
class Program {
static void Main(string[] args) {
if(!File.Exists("C:\\TEST.TXT"))
{
GC.Collect();
GC.WaitForPendingFinalizers();
fi.Create();
fi.Close();
Console.WriteLine("File exists: {0}", fi.Exists);
}
}
}
}
This is a simple solution,
I ran you code and got a UnauthorizedAccessException which is a security exception
you do not have the right security to save a file in the root folder (C:\)
if you change it to FileInfo("TEXT.TXT"); instead of C:\TEXT.TXT
it will work
Btw, you cant use a using statement as FileInfo doesn't implement IDisposable interface.