I'm getting a RuntimeBinderException when attempting to read a property from a dynamic object. This is no doubt one of those issues where I've not got the syntax quite right, but I'm just not seeing it....
Using a simple LinqPad script, the following works fine:
void Main()
{
var response = new
{
DotNet = Environment.Version,
ServerName = Environment.MachineName,
};
dynamic d = response;
var x = d.DotNet as Version;
x.Major.Dump();
}
If I return it from a Web Method, then I'm running into issues. Here is my simple web method (.Net 5 WebAPI)
public IActionResult GetEnvironmentDetails()
{
var response = new
{
DotNet = Environment.Version,
ServerName = Environment.MachineName,
};
return this.Ok(response);
}
In my unit test, I can read the property using reflection, but not using dynamics:
var c = new MyController();
var response = c.GetEnvironmentDetails() as OkObjectResult;
// This next line gets me the property using reflection:
Version dotNet = response.Value.GetType().GetProperty("DotNet").GetValue(response.Value, null) as Version;
// But...using dynamics
dynamic d = response.Value;
// then the following fails for me
object x = d.DotNet;
If I put the variable d in my WATCH window, then the Value shows as { DotNet = {5.0.4}, ServerName = "MyComputerName" } and the Type is <Anonymous Type>.
Related
I've created a new .NET 5 AWS Lambda Function using Container Images via the Visual Studio Project Template:
And now I want to deploy the Lambda Function and an ApiGateway using the CDK.
I was able to get it deployed, but when I invoke the method, I get this error:
❯ iwr https://3l0xxxxxx.execute-api.us-west-2.amazonaws.com/prod/
Invoke-WebRequest: {"message": "Internal server error"}
This is what I have in my Stack:
public class Dotnet5LambdaStack : Stack
{
internal Dotnet5LambdaStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var dotnet5Lambda = new Amazon.CDK.AWS.Lambda.Function(this, "dotnet5Lambda", new FunctionProps
{
Runtime = Runtime.FROM_IMAGE,
// relative to the cdk.json file
Code = Code.FromAssetImage("src/lambdaNet5"),
Handler = Handler.FROM_IMAGE
});
new LambdaRestApi(this, "dotnet5ApiEndpoint", new LambdaRestApiProps
{
Handler = dotnet5Lambda
});
}
}
How do I fix my CDK Stack code so my Lambda + Api Gateway deploy correctly?
Realized I could mine my CloudWatch logs to get to the real problem - Lambda wants a function handler defined:
I was able to pass a AssetImageCodeProps, with my handler set in hte Cmd property, to the Code.FromAssetImage and that got it working.
internal Dotnet5LambdaStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var dotnet5Lambda = new Amazon.CDK.AWS.Lambda.Function(this, "dotnet5Lambda", new FunctionProps
{
Runtime = Runtime.FROM_IMAGE,
// relative to the cdk.json file
Code = Code.FromAssetImage("src/lambdaNet5", new AssetImageCodeProps
{
// !!Set Handler Here!! Assembly::Type::Method
Cmd = new string[]{"lambdaNet5::lambdaNet5.Functions::Get"}
}),
Handler = Handler.FROM_IMAGE
});
new LambdaRestApi(this, "dotnet5ApiEndpoint", new LambdaRestApiProps
{
Handler = dotnet5Lambda
});
}
After a deploy:
❯ iwr https://3l0xxxxxx.execute-api.us-west-2.amazonaws.com/prod/
StatusCode : 200
StatusDescription : OK
Like the title says, i need to get the members of a group from my Active directory.
Code:
using(var p_con = new PrincipalContext(ContextType.Machine))
{
var grps = GroupPrincipal.FindByIdentity(p_con, IdentityType.Sid, "S-1-5-21-205523278-2745993604-4001200492-1027");
var users = grps.GetMembers();
}
But my code throws the follwing error in the Membersproperty of the 'grps' var.
Members = 'grps.Members' threw an exception of type
'System.TypeLoadException'
If i try it the other way, searching for the groups of a member, i get the same error.
using (var p_con = new PrincipalContext(ContextType.Machine))
{
var up = new UserPrincipal(p_con);
using (var search = new PrincipalSearcher(up))
{
foreach (var user in search.FindAll())
{
var _grp = user.GetGroups();
}
}
}
The group/user it self is correctly loaded except the Users\Groups.
Am i missing something in the setup?
I am using ASP.NET Core 2 and the current Windows.Compatibility Pack (which includes the current verion of the DirectoryServices).
The authentication runs via Http.sys
I am using Google API for the first time and I want to use Natural Language API.
But I don't know how.
So I search the internet and found an example code.
But when it uses APIs, the program throws an exception.
problem source code and thrown exception:
using Google.Cloud.Language.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// The text to analyze.
string text = "Hello World!";
try
{
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
Console.WriteLine($"Score: {sentiment.Score}");
Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
The console output:
The Application Default Credentials are not available.
They are available if running on Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
See https://developers.google.com/accounts/docs/application-default-credentials for more information.
What should I do?
I had used NLP a year ago for entity analysis. I had used Google.Apis.CloudNaturalLanguage.v1. I put together my code with what you have written for sentiment analysis. You will need the API key for this:
var service = new CloudNaturalLanguageService(new CloudNaturalLanguageService.Initializer { ApiKey = ApiKey });
var req = new AnalyzeSentimentRequest {
Document = new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
},
EncodingType = "UTF8"
};
var output = service.Documents.AnalyzeSentiment(req);
var exe = output.Execute();
Hope this works.
The following code throws an exception on the session.Load<Employee>(order.Employee), but I have no problem querying an employee directly.
static void LoadRelatedData()
{
using (var session = mystore.OpenSession())
{
var employeeFromQuery = session.Query<Employee>().FirstOrDefault(); //works
var order = session.Include<Order>(o => o.Employee).Load("orders/819"); //works
var employeeRelatedToOrder = session.Load<Employee>(order.Employee); //EXCEPTION
var dynamicRelatedToOrder = session.Load<dynamic>(order.Employee); //works
}
}
private static IDocumentStore mystore = new DocumentStore()
{
Url = "http://localhost:4444/RavenDB",
DefaultDatabase = "Hello"
}.Initialize();
The exception I get is -
An unhandled exception of type 'System.InvalidCastException' occurred in Raven.Client.Lightweight.dll
Additional information: Unable to cast object of type 'Raven.Abstractions.Linq.DynamicJsonObject' to type 'RavenApp.Employee'
.
I'm basing my code on http://ravendb.net/docs/article-page/2.5/Csharp/client-api/querying/handling-document-relationships
The employee and order data are generated by the Raven Create Sample Data task.
As you've used Include, the order.Employee should be populated for you and not require a second load.
static void LoadRelatedData()
{
using (var session = mystore.OpenSession())
{
var employeeFromQuery = session.Query<Employee>().FirstOrDefault();
var order = session.Include<Order>(o => o.Employee).Load("orders/819");
// Access them directly, as they have been resolved
var employeeRelatedToOrder = order.Employee;
var dynamicRelatedToOrder = (dynamic)order.Employee;
}
}
I'm just getting to grips with the C# API for MSDeploy (Microsoft.Web.Deployment.dll), but I'm struggling to find a way that I can determine the dependencies for a given web server.
Basically, I'd like the C# equivalent of the following MSDeploy command line call:
msdeploy.exe -verb:getDependencies -source:webServer
I've tried the documentation, but I've had no luck. Can anybody point me in the right direction?
Having examined the MSDeploy executable in Reflector, it seems that the getDependencies operation is not exposed by the API (the method is internal).
So instead I've had to fall back on calling out to the command line, and processing the results:
static void Main()
{
var processStartInfo = new ProcessStartInfo("msdeploy.exe")
{
RedirectStandardOutput = true,
Arguments = "-verb:getDependencies -source:webServer -xml",
UseShellExecute = false
};
var process = new Process {StartInfo = processStartInfo};
process.Start();
var outputString = process.StandardOutput.ReadToEnd();
var dependencies = ParseGetDependenciesOutput(outputString);
}
public static GetDependenciesOutput ParseGetDependenciesOutput(string outputString)
{
var doc = XDocument.Parse(outputString);
var dependencyInfo = doc.Descendants().Single(x => x.Name == "dependencyInfo");
var result = new GetDependenciesOutput
{
Dependencies = dependencyInfo.Descendants().Where(descendant => descendant.Name == "dependency"),
AppPoolsInUse = dependencyInfo.Descendants().Where(descendant => descendant.Name == "apppoolInUse"),
NativeModules = dependencyInfo.Descendants().Where(descendant => descendant.Name == "nativeModule"),
ManagedTypes = dependencyInfo.Descendants().Where(descendant => descendant.Name == "managedType")
};
return result;
}
public class GetDependenciesOutput
{
public IEnumerable<XElement> Dependencies;
public IEnumerable<XElement> AppPoolsInUse;
public IEnumerable<XElement> NativeModules;
public IEnumerable<XElement> ManagedTypes;
}
Hopefully this is useful to anybody else that ever tries to do the same thing!
There actually is a way of getting there via the public API by using DeploymentObject.Invoke(string methodName, params object[] parameters).
When "getDependencies" is used for methodName, the method returns an XPathNavigator object:
DeploymentObject deplObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.WebServer, String.Empty);
var result = deplObj.Invoke("getDependencies") as XPathNavigator;
var xml = XDocument.Parse(result.InnerXml);