Lowercase Property Names - azure-cosmosdb

I am adding a document to Cosmos DB with following line:
client.CreateDocumentAsync(collectionLink, report).Wait();
My c# classes are uppercase however standard json you lowercase properties. Is it possible somehow to ensure this when saving the document?

Some of the DocumentClient constructors accept an object called JsonSerializerSettings.
You can provide a different contract resolver there. In your case it's the CamelCasePropertyNamesContractResolver.
var client = new DocumentClient(new Uri(""), "", serializerSettings: new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});

Related

Read AzureDevOps Pipeline Variables in C#

I need develop a C# .NetCore Console Application to access my DevOps account, select a release and read all variables in Pipeline Variables[
Anybody can give me an example?
Found a solution do read variables from Azure DevOps with REST API.
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-6.1
Here I have a rough draft to read the variables from a release definition. You can create the .NET helper objects by creating helper classes from the JSON. There are sites on the internet for this.
Main() {
var pat = Environment.GetEnvironmentVariable("????");
var baseUrl = "https://dev.azure.com/{organization}";
var apiversion = "api-version=6.0";
var project = "????";
var search = "Releasename";
var actUrl = string.Format("{0}/{1}/_apis/release/definitions?searchText={2}&{3}",baseUrl,project,search,apiversion);
var json = await GetJsonFromUrlPAT(actUrl, pat);
cReleases varReleases = JsonConvert.DeserializeObject<cReleases>(json);
int ReleaseId=0;
if (varReleases.count == 1)
{
ReleaseId = varReleases.values[0].id;
actUrl = string.Format("{0}/{1}/_apis/release/definitions/{2}?{3}",baseUrl,project,ReleaseId,apiversion);
var json2 = await GetJsonFromUrlPAT(actUrl, pat);
cReleasedefinition varReleaseDef = JsonConvert.DeserializeObject<cReleasedefinition>(json2);
string jsonstring = JsonConvert.SerializeObject(varReleaseDef);
foreach (KeyValuePair<String,JToken> element in varReleaseDef.variables)
{
string varname = element.Key;
string varvalue = ((JObject)(element.Value)).GetValue("value").ToString();
}
foreach (var element in varReleaseDef.environments)
{
string environmentname = element.name;
foreach (KeyValuePair<String, JToken> item in element.variables)
{
string varname = item.Key;
string varvalue = ((JObject)(item.Value)).GetValue("value").ToString();
}
}
}
}
No worries!
To get your pipeline variables applied to your application configuration, you're going to want to use the File Transform task within your pipeline and configure it to point to your configuration JSON file within the Target Files
File Transform Task: https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/file-transform?view=azure-devops
What this task is going to do is use the variables you've associated with your pipeline to replace values within your JSON configuration.
Some things to note when using File Transform:
It can only perform replace operations, it cannot add to your configuration. So, be sure to have placeholders for every value you are looking to replace within your JSON file.
To access a nested value within JSON, you want to use a period within your naming conventions. In your case for example, you'll want to change ConnectionStrings:StorageAccountLogs to **ConnectionStrings.StorageAccountLogs" ** in order to correctly perform the variable substitution.

documentDB .net Rest Create Docs with auto gen id

I am trying to create a new document in documentDB via the rest API. I would use the SDK, but im running the project from asp.net core and the SDK isn't compatible yet.
I would like to have documentDB auto generate the id for the document, but I am having problems with my request.
What should I set the ids value to when creating the document via the documentDB rest api (using id based routing)?
Right now I am getting hit with the 400 bad request error.
Ive tried posting it with the following variations on the id:
No id property
id: null
id: ""
The code i am using is basically what was in the github .net rest examples, i have the replace call, get calls working fine.
Here is my code making the request:
//Create a document
verb = "POST";
resourceType = "docs";
resourceLink = string.Format("dbs/{0}/colls/{1}/docs", databaseId, collectionId);
resourceId =string.Format("dbs/{0}/colls/{1}", databaseId, collectionId);
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
string content = JsonConvert.SerializeObject(document);
StringContent contentMessage = new StringContent(content, System.Text.Encoding.UTF8, "application/json");
contentMessage.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
contentMessage.Headers.ContentType.CharSet = null;
var r = client.PostAsync(baseUri + resourceLink, contentMessage).Result;
System.Diagnostics.Debug.WriteLine(r.Content.ReadAsStringAsync().Result);
return r.Content.ReadAsStringAsync().Result;
You should supply a string value for the "id" property. The auto-id functionality (like Larry mentions) is a client-side feature, not part of the REST API. So when consuming directly from REST, you must generate a Guid (or any unique string) and set the "id" property with that value.

Json format of data which is having HTML tags in Web API in C#

I have an object Example
Class Event
{
string country{get;set}
}
Events test = new Evnts();
test.country="<P>India<P>"
How i need to Json format for the above.
I used the method
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
StringContent sc = new StringContent(oSerializer.Serialize(list));
sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return sc;
But this is giving output result as "City": "\u003cp\u003eIndia\u003cp\u003e",
Please comment on this .
Thank you
That's encoded <> tag representation. You shouldn't return specific html element in JSON response. Also, no need to use JavaScriptSerializer class. You can simply return your "Event" class as a result of your svc web api service.
Actually I am fetching Rich text from Sitecore Item,
I used Regex to remove the HTML tags and Replace Method to replace the "’" and Replace(" ",""). I am directly sending the List of events not using JavaScriptSerializer class.
((Regex.Replace(eve["text"].ToString(), "<[^>]*>", "").Replace("’", "'")).Replace(" ","")).Replace("\n","");
Thank you Pravin and Ivan Sivak

Get type of metadata fields of a Metadata schema

I want to get the all fields along with type/datatype of the metadata fields of a Metadata schema.
I have written below sample code to achieve the functionality and I am able to get Name, Description etc but could not find any property with type/dataType. If anyone of you have any idea, please suggest...
var client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
if (client.State == System.ServiceModel.CommunicationState.Opened)
{
var schemaUri = "tcm:1-47-8";
var fields= client.ReadSchemaFields(schemaUri, true, new ReadOptions());
var fieldName = fields.MetadataFields[0].Name;
}
To know the type of a field, you only need to examine the .NET type of the field.
I typically use an "is" check, but you can also call GetType if you want.
For example:
var client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
if (client.State == System.ServiceModel.CommunicationState.Opened)
{
var schemaUri = "tcm:1-47-8";
var fields= client.ReadSchemaFields(schemaUri, true, new ReadOptions());
foreach (var field in fields.MetadataFields)
{
if (field is SingleLineTextFieldDefinitionData)
{
// Do something specifically for single-line text fields
}
}
}
The ReadSchemaFields method exposes only the definition of the fields. So it is essentially a wrapper around the properties you enter while you define the field in a schema.
The Content and Metadata are exposed by ComponentData.Content and ComponentData.Metadata respectively. But those are exposed as XML strings, so you will have to do your own parsing of them.
If you (understandably) don't feel like that, have a look at this helper class: http://code.google.com/p/tridion-practice/wiki/ChangeContentOrMetadata
You might also want to read my answer to this question: Updating Components using the Core Service in SDL Tridion 2011

NVelocity not finding the template

I'm having some difficulty with using NVelocity in an ASP.NET MVC application. I'm using it as a way of generating emails.
As far as I can make out the details I'm passing are all correct, but it fails to load the template.
Here is the code:
private const string defaultTemplatePath = "Views\\EmailTemplates\\";
...
velocityEngine = new VelocityEngine();
basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, defaultTemplatePath);
ExtendedProperties properties = new ExtendedProperties();
properties.Add(RuntimeConstants.RESOURCE_LOADER, "file");
properties.Add(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, basePath);
velocityEngine.Init(properties);
The basePath is the correct directory, I've pasted the value into explorer to ensure it is correct.
if (!velocityEngine.TemplateExists(name))
throw new InvalidOperationException(string.Format("Could not find a template named '{0}'", name));
Template result = velocityEngine.GetTemplate(name);
'name' above is a valid filename in the folder defined as basePath above. However, TemplateExists returns false. If I comment that conditional out and let it fail on the GetTemplate method call the stack trace looks like this:
at NVelocity.Runtime.Resource.ResourceManagerImpl.LoadResource(String resourceName, ResourceType resourceType, String encoding)
at NVelocity.Runtime.Resource.ResourceManagerImpl.GetResource(String resourceName, ResourceType resourceType, String encoding)
at NVelocity.Runtime.RuntimeInstance.GetTemplate(String name, String encoding)
at NVelocity.Runtime.RuntimeInstance.GetTemplate(String name)
at NVelocity.App.VelocityEngine.GetTemplate(String name)
...
I'm now at a bit of an impasse. I feel that the answer is blindingly obvious, but I just can't seem to see it at the moment.
Have you considered using Castle's NVelocityTemplateEngine?
Download from the "TemplateEngine Component 1.1 - September 29th, 2009" section and reference the following assemblies:
using Castle.Components.Common.TemplateEngine.NVelocityTemplateEngine;
using Castle.Components.Common.TemplateEngine;
Then you can simply call:
using (var writer = new StringWriter())
{
_templateEngine.Process(data, string.Empty, writer, _templateContents);
return writer.ToString();
}
Where:
_templateEngine is your NVelocityTemplateEngine
data is your Dictionary of information (I'm using a Dictionary to enable me to access objects by a key ($objectKeyName) in my template.
_templateContents is the actual template string itself.
I hope this is of help to you!
Just to add, you'll want to put that into a static method returning a string of course!
Had this issue recently - NVelocity needs to be initialised with the location of the template files. In this case mergeValues is an anonymous type so in my template I can just refer to $Values.SomeItem:
private string Merge(Object mergeValues)
{
var velocity = new VelocityEngine();
var props = new ExtendedProperties();
props.AddProperty("file.resource.loader.path", #"D:\Path\To\Templates");
velocity.Init(props);
var template = velocity.GetTemplate("MailTemplate.vm");
var context = new VelocityContext();
context.Put("Values", mergeValues);
using (var writer = new StringWriter())
{
template.Merge(context, writer);
return writer.ToString();
}
}
Try setting the file.resource.loader.path
http://weblogs.asp.net/george_v_reilly/archive/2007/03/06/img-srchttpwwwcodegenerationnetlogosnveloc.aspx
Okay - So I'm managed to get something working but it is a bit of a hack and isn't anywhere near a solution that I want, but it got something working.
Basically, I manually load in the template into a string then pass that string to the velocityEngine.Evaluate() method which writes the result into the the given StringWriter. The side effect of this is that the #parse instructions in the template don't work because it still cannot find the files.
using (StringWriter writer = new StringWriter())
{
velocityEngine.Evaluate(context, writer, templateName, template);
return writer.ToString();
}
In the code above templateName is irrelevant as it isn't used. template is the string that contains the entire template that has been pre-loaded from disk.
I'd still appreciate any better solutions as I really don't like this.
The tests are the ultimate authority:
http://fisheye2.atlassian.com/browse/castleproject/NVelocity/trunk/src/NVelocity.Tests/Test/ParserTest.cs?r=6005#l122
Or you could use the TemplateEngine component which is a thin wrapper around NVelocity that makes things easier.

Resources