.Net-Core get HttpBrowserCapabilities from httpContext - asp.net-core

I want to use the HttpBrowserCapabilities in .net-core. I tried it following way:
var userAgent = httpContext.Request.Headers["user-agent"];
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
var mobileString = userBrowser.IsMobileDevice ? "(mobil)" : string.Empty;
var browserString = $"{userBrowser.Browser} version {userBrowser.Version} {mobileString} OS: {userBrowser.Platform}";
But an InvalidCastException is thrown. How ca i get this code retun the right values?

Got it!
userAgent is of the type Microsoft.Extensions.Primitives.StringValues.
But HttpBrowserCapabilities expects a string as input parameter.
Therefore i had to check if userAgent contains a value (userAgent.Any()) and use the following code
var userBrowser = new HttpBrowserCapabilities {Capabilities = new Hashtable {{string.Empty, userAgent.First()}}};

Related

Simple serialize ODataQueryOptions

I'm trying to:
[EnableQuery]
[HttpGet]
[ODataRoute("")]
public IHttpActionResult Get(ODataQueryOptions<UserODataModel> options)
{
var users = _repository.RetrieveOData();
var serialQuery = JsonConvert.SerializeObject(options, jsonOptions);
//save serialQuery somewhere
return Ok(users);
}
But got
Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'ReadTimeout' on 'Microsoft.Owin.Host.SystemWeb.CallStreams.InputStream'.'
"Timeouts are not supported on this stream."
I know there is already a question about serialize Stream:
Newtonsoft Json.net - how to serialize content of a stream?
But in this case i can't "extract stream value" from ODataQueryOptions, or can I?
Some ideia?
Since we work on the same company, if anyone is interested, we found a way, maybe not the pretty way, to serialize an ODataQueryOptions:
public static ODataQueryOptions DeserializeQueryOptions(SerializedQueryOptions options)
{
var uri = new Uri(teste.OriginalUri);
var model = ODataConfig.Model; //GetEdmModel
var segment = model.EntityContainer.FindEntitySet(options.EdmType);
var newPath = new Microsoft.AspNet.OData.Routing.ODataPath(new EntitySetSegment(segment));
var httpConfiguration = new HttpConfiguration();
httpConfiguration.EnableDependencyInjection();
var request = new HttpRequestMessage(HttpMethod.Get, uri)
{
Properties =
{
{ HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },
}
};
var context = new ODataQueryContext(model, options.EntityType, newPath);
var oDataQueryOptions = new ODataQueryOptions(context, request);
return oDataQueryOptions;
}
public static SerializedQueryOptions SerializeQueryOptions(ODataQueryOptions options)
{
return new SerializedQueryOptions
{
OriginalUri = options.Request.RequestUri.AbsoluteUri,
EdmType = options.Context.NavigationSource.Name,
EntityType = options.Context.ElementClrType
};
}
After you serialize it to an object you can serialize it to a JSON string:
var queryOptionsSerialized = new SerializedQueryOptions()
{
OriginalUri = "http://localhost:25723/odata/users?$skip=0&$top=2&$orderby=fullName&$count=true",
EdmType = "users",
EntityType = typeof(UserODataModel)
};
var json = JsonConvert.SerializeObject(queryOptionsSerialized);
var deserialized = JsonConvert.DeserializeObject<SerializedQueryOptions>(json);
var options = ODataQueryOptionsHelper.DeserializeQueryOptions(deserialized);
In case One is not using OData routing or using an ApiController (not ODataController),
modify the way of Obtaining ODataPath to:
ODataUriParser parser = new ODataUriParser(model, serviceRoot, requestUri);
ODataPath path = parser.ParsePath();
//var newPath = new Microsoft.AspNet.OData.Routing.ODataPath(new EntitySetSegment(segment));
Microsoft.AspNet.OData.Routing.ODataPath newPath = new Microsoft.AspNet.OData.Routing.ODataPath(path.FirstOrDefault());
where the serviceRoot is the Url part other that the path defined in the model.

string Concatenate in yml file and use with aspnetcore 2.1

yml string concatenate does not work with .NET applications.I have tried by removing '$' sign, but it is still not working(Java application uses $ sign - Working fine with Java apps). It is working fine for a single value, but not with concatenation.
yml-01
cicd:
dbname: 172.10.10.110
port: 5432
yml-02
datasource:
url: jdbc:postgresql://${cicd:dbname}:${cicd:port}/sample-db
A solution for placeholder resolution in .NET Configuration (similar to that provided by spring) is available in Steeltoe.Common. We haven't added WebHostBuilder or IConfigurationBuilder extensions just yet, but if you add a recent reference to Steeltoe.Common from the Steeltoe Dev feed you should be able to do something like this:
public static IWebHostBuilder ResolveConfigurationPlaceholders(this IWebHostBuilder hostBuilder, LoggerFactory loggerFactory = null)
{
return hostBuilder.ConfigureAppConfiguration((builderContext, config) =>
{
config.AddInMemoryCollection(PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(config.Build(), loggerFactory?.CreateLogger("Steeltoe.Configuration.PropertyPlaceholderHelper")));
});
}
The code above is used in the Steeltoe fork of eShopOnContainers
You should take a look at YamlDotNet.
Here's an example of how to solve your problem using that lib
using YamlDotNet.RepresentationModel;
using YamlDotNet.Core;
Then in your method
var dbname = "172.10.10.110";
var port = "5432";
string content;
using (var reader = new StreamReader("your yml file"))
{
content = reader.ReadToEnd();
}
var doc = new StringReader(content);
var yaml = new YamlStream();
yaml.Load(doc);
// Add the url where you use string interpolation to replace the values
var ymlFile = (YamlMappingNode)yaml.Documents[0].RootNode;
ymlFile.Children["datasource"] = new YamlMappingNode
{
{ "url", $"jdbc:postgresql://{dbname}:{port}/sample-db" }
};
yaml.Save(File.CreateText("C:\\yourNewFile.yml"), assignAnchors: false);
Here's a link to the NetCore package
I've solved this by writing an extension method to the IConfiguration interface.
public static string ReadFromConfigRepo(this IConfiguration configuration, string key)
{
var pattern = #"\{(.*?)\}";
var query = configuration[key];
if (query.Contains('{'))
{
var matches = Regex.Matches(query, pattern);
string value;
foreach (Match m in matches)
{
value = configuration[m.Value.Substring(1, m.Value.Length - 2)];
query = query.Replace(m.Value, value);
}
}
return query.Trim();
}

CodeDom referencing System.Management

No matter what I try I am unable to reference System.Management in to my codedom project, I have tried
Dim assemblyReferences = New String() {"System.Drawing.dll",
"System.Data.dll",
"System.Data.DataSetExtensions.dll",
"System.Deployment.dll",
"System.Management.dll",
"System.Net.dll",
"System.Net.Http.dll",
"System.dll",
"System.Core.dll",
"mscorlib.dll",
"System.Windows.Forms.dll",
"System.Xml.dll",
"System.Xml.Linq.dll"}
param.ReferencedAssemblies.AddRange(assemblyReferences)
Among other methods such as using it implicitly and importing it at the top of the class
I have found it to work using both...
var compileUnit = new CodeCompileUnit();
compileUnit.ReferencedAssemblies.Add("System.dll");
compileUnit.ReferencedAssemblies.Add("System.Management.dll");
...and...
var parameters = new CompilerParameters(new string[] {"System.dll", "System.Management.dll" }, "TestAssembly.dll", true);
var results = provider.CompileAssemblyFromDom(parameters, compileUnit);
System.dll is required by System.Management.dll
The code snippet I used was:
var compileUnit = new CodeCompileUnit();
compileUnit.ReferencedAssemblies.Add("System.dll");
compileUnit.ReferencedAssemblies.Add("System.Management.dll");
var codeNamespace = new CodeNamespace("ClassLibrary1");
compileUnit.Namespaces.Add(codeNamespace);
var testClass = new CodeTypeDeclaration("TestClass");
var declaration = new CodeMemberField(typeof(System.Management.ManagementClass), "managementClass");
testClass.Members.Add(declaration);
codeNamespace.Types.Add(testClass);
I compiled it with:
using (var provider = CodeDomProvider.CreateProvider("VisualBasic"))
{
var parameters = new CompilerParameters(new string[] {"System.dll", "System.Management.dll" }, "TestAssembly.dll", true);
var results = provider.CompileAssemblyFromDom(parameters, compileUnit);
return results;
}
Sorry the example is in C#.

namespace is use like a type using nest elasticclient

I am using NEST to connect to the elasticsearch server:
var searchBoxUri = new Uri("xxx");
var elasticSettings = new ConnectionSettings(searchBoxUri).SetDefaultIndex("xxx");
var client = new ElasticClient(elasticSettings);
I got this error:
'ElasticClient' is a 'namespace' but is used like a 'type'
Try this one:
var client = new Nest.ElasticClient(elasticSettings);
You should use full qualified class name.
You can use something like this :
private ElasticClient _Instance;
var elasticSearchURI = ConfigurationManager.AppSettings["elasticSearchURI"];
var node = new Uri(elasticSearchURI);
var connectionPool = new SniffingConnectionPool(new[] { node });
var config = new ConnectionSettings(connectionPool, defaultIndex)
.SniffOnConnectionFault(false)
.SniffOnStartup(false)
.DisablePing();
_Instance = new ElasticClient(config);
Where defaultIndex is a string with the name of the index .

how can I query for releases / iterations via rally c# api?

I am trying to query on both Release and Iteration so I can fill out a drop down list with these various values. I'm not quite sure how to do this, however. What are the members of the object that come back via the query if we are able to do this? (Name, FormattedID, CreationDate, etc). Do we just create a new request of type "Release" and "Iteration" ?
Thanks!
Here is a code that queries on releases based on a project reference. If this project is not in a default workspace of the user that runs the code we either need to hardcode the workspace reference or get it from the project.
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "TopSecret1984", "https://rally1.rallydev.com", "1.40");
var projectRef = "/project/22222222"; //use your project OID
DynamicJsonObject itemWorkspace = restApi.GetByReference(projectRef, "Workspace");
var workspaceRef = itemWorkspace["Workspace"]["_ref"];
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
Request request = new Request("Release");
request.ProjectScopeDown = false;
request.ProjectScopeUp = false;
request.Workspace = workspaceRef;
request.Fetch = new List<string>()
{
"Name"
};
// request.Query = new Query("Project.ObjectID", Query.Operator.Equals, "22222222"); //also works
request.Query = new Query("Project", Query.Operator.Equals, projectRef);
QueryResult queryResult = restApi.Query(request);
foreach (var r in queryResult.Results)
{
Console.WriteLine("Name: " + r["Name"]);
}
}
catch
{
Console.WriteLine("problem!");
}
}
}
}