namespace is use like a type using nest elasticclient - nest

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 .

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.

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#.

.Net-Core get HttpBrowserCapabilities from httpContext

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()}}};

Create memory index with Elasticsearch.net

I try to create memory index with following code but it creates regular index.
Any idea?
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node);
var client = new Elasticsearch.Net.ElasticsearchClient(settings);
var js = JsonConvert.SerializeObject("{settings: { index.store.type: memory}");
var index = client.IndicesCreate("sampleIndex", js);
Your second argument to the IndicesCreate method call is not correct. See the code below for a better way to achieve it. The first three lines are the same. In the fourth one, we properly create the settings for the index.
_body = new {
settings = new {
index = new {
store = new {
type = "memory"
}
}
}
};
var index = client.IndicesCreate("sampleIndex", _body);

JSON.Net serialize XML to JSON camel case

How do I get JSON.Net to serialize my XML to camel case JSON and without the "#"?
this is what I currently have but it prepends # to the properties and does not camel case...
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXmlString);
string jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(doc, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Make a model of your XML data
example
public class MyClass
{
[JsonProperty("#SomeXMLProperty")]
public string MyString{ get; set; }
}
then deserialize XML to your model
XDocument xmlDocument = XDocument.Parse(xmlData);
string jsonData = JsonConvert.SerializeXNode(xmlDocument);
var myClass = JsonConvert.DeserializeObject<MyClass>(jsonData);
then just use CamelCasePropertyNamesContractResolver and Formatting.Indented
string json = JsonConvert.SerializeObject(rootObject,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });
UPDATE:
The first solution is simple and clean (no need to write custom resolvers etc.) this is just for removing # sign
var xml = new XmlDocument();
xml.XmlResolver = null;
xml.Load("yourfilehere");
var json = JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented);
var withoutATSign = System.Text.RegularExpressions.Regex.Replace(json, "(?<=\")(#)(?!.*\":\\s )", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
If anybody knows a better solution for both cases then the first it would be nice to look at it.
WebAPI addition
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();