My datasource creates the JSON representing an array of integers as "1,2,3,4,5". I can't do anything about this (Like changing it to [1,2,3,4,5]), it is an enterprise CMS that we have to just deal with.
I'm trying to read up on how the newtonsoft ToObject method handles the following code:
JValue theValue = new JValue("1,2,3")
List<int> x = theValue.ToObject<List<int>>();
I get a Newtonsoft.Json.JsonSerializationException. Could not cast or convert from System.String to System.Collections.Generic.List`1[System.String]. I understand this fully, but I'd like to know if the Newtonsoft JSON libraries have a built in way to convert from a comma delimited string to a List.
I'd like to think there's a better way than trying to check if the variable is a comma delimited list or not and then converting it to a List<> manually, or maybe a JArray, but I've been wrong before !
EDIT
I wanted to share my solution:
dynamic theValue = new JValue("1,2,3,4"); /// This is just passed in, i'm not doing this on purpose. Its to demo.
if (info.PropertyType == typeof (List<int>))
{
if (info.CanWrite)
{
if (theValue.GetType() == typeof (JValue) && theValue.Value is string)
{
theValue = JArray.Parse("[" + theValue.Value + "]");
}
info.SetValue(this, theValue.ToObject<List<int>>());
}
} else {
// do other things
You have three problems from what I can see:
You should be using JArray not JValue. You are intending this to be an array of things, so you need to use the equivalent class in Newtonsoft to represent an array. (A JValue, as best I can tell, represents a simple type--e.g. string, number, Date, etc.)
You should use the Parse method versus using the constructor. Parse will read the content of the string as an array, however...
...in order for it to do that, you will need to surround the data that you get with the square brackets or JArray can't correctly the parse the data. There is no need to fiddle with the CMS; just do a string concat before you parse.
e.g.
JArray theValue = JArray.Parse("[" + "1,2,3" + "]");
Related
I'm having to create my own custom sink because none of the ones currently available give me what I need.
Issue I have is when fetching the key/value pair Value from the logEvent message in the Emit Method, the value is wrapped with quotation marks & backslashes.
I've tried converting the out value from the dictionary into a string and then removing the unwanted attributes but nothing is working for me.
Method in my Custom Sink Class:
public void Emit(LogEvent logEvent)
{
var properties = logEvent.Properties;
Serilog.Events.LogEventPropertyValue value;
if (properties.TryGetValue("logEventCategory", out value))
{
// Regex.Replace((value.ToString() ?? "").Replace("'", #"\'").Trim(), #"[\r\n]+", " "); // Not working
var notWorking = value.ToString();
var formattedValueNotWorking = value.ToString().Replace("\r\n", "\\r\\n");
}
}
It just seems that any attempted formatting of the key/value pair Value is ignored: You see that the example string value System is wrapped with a \"System\"
All I want is the actual string, not the backslashes or quotation marks that is wrapped around the string.
Creating my own sink is a hard enough task and I just want to keep things simple, have spent two days trying to understand the wider picture in message formatting but with custom sinks it gets too complicated and bloated coding for what I need. All the other standard message structure attributes are rendering OK, such as message / level / timestamp etc, it's just fine tuning the rendering of the propertie values I require in order to save these values into their own columns in my DB.
You need to unwrap the string from the enclosing ScalarValue:
// using Serilog.Events;
public void Emit(LogEvent logEvent)
{
var properties = logEvent.Properties;
Serilog.Events.LogEventPropertyValue value;
if (properties.TryGetValue("logEventCategory", out value) &&
value is ScalarValue sv &&
sv.Value is string rawValue)
{
// `rawValue` is what you're looking for
Looks like I just needed to use the correct syntax for string replace:
public void Emit(LogEvent logEvent)
{
var properties = logEvent.Properties;
Serilog.Events.LogEventPropertyValue value;
if (properties.TryGetValue("logEventCategory", out value))
{
var formattedValueWorking = value.ToString().Replace("\"", "");
var test = formattedValueWorking;
}
}
Suppose We are on the page www.abc.com/apple-store
then how to get string apple-store in asp C# code.
to store into another variable.
You can use string.last() to extract it.
string lastPartUrl =HttpContext.Current.Request.Url.AbsoluteUri.Split('/').Last();
You should use the Request.RawUrl property. See more details here.
Alternatelly you can also use the Request.Url (see here) property to get different parts of the current URL. For example you will get the same result using Request.Url.LocalPath.
You can get the url in a string variable. Further you can implement the below logic which will save the value in a variable.
string str = "www.abc.com/apple-store";
string result = "";
int i= 0;
int len = str.Length;
//Get the index of the character
i = str.IndexOf('/');
//store the result in the variable
result = str.Substring(i+1,len-i-1);
Console.WriteLine("Resultant:- {0}", result);`
Hope this helps a bit.
If I have the following code:
var value : String = StringUtil.substitute("The value {0} requested is {1}", user, value);
How can I use the variable name instead of using {0} and {1} in the code.
Please advice. Thanks.
Edit:
The above code is quoted from http://www.rialvalue.com/blog/2010/05/10/string-templating-in-flex/.
It says that "Also note that we’re substituting the parameters using the order, it’d would fairly easy to do a named-parameter subsitution instead (i.e. using tokens like ${var1})". Therefore, I think it may be very easy to do that, but I don't know how to do.
Looks like it's not possible. And kind of makes sense that it allows zero based ints only, since you're passing a variable number of parameters that you're not identifying (except for their relative position in the params list).
Here's a piece of code that will replace tokens by name:
public static function replacePlaceholders(input:String,replacementMap:Object):String {
// '${', followed by any char except '}', ended by '}'
return input.replace(/\${([^}]*)}/g,function():String {
return replaceEntities(arguments,replacementMap);
});
}
private static function replaceEntities(regExpArgs:Array,map:Object):String {
var entity:String = String(regExpArgs[0]);
var entityBody:String = String(regExpArgs[1]);
return (map[entityBody]) ? map[entityBody] : entity;
}
Use:
var test:String = "Hello there ${name}, how is the ${noun} today?";
var replacementMap:Object = {
name : "YOUR_NAME_HERE",
noun : "YOUR_NOUN_HERE"
};
trace(StringUtils.replacePlaceholders(test,replacementMap));
The format I'm using for the placeholders is ${placeholdername}, since it's safer, I think. But if you want to remove the dollar sign, change the regexp accordingly.
Does anyone know of an algorithm (or external library) that I could call to convert an arbitrary string (i.e. outside my control) to be CLS compliant?
I am generating a dynamic RDLC (Client Report Definition) for an ASP.Net Report Viewer control and some of the field names need to be based on strings entered by the user.
Unfortunately I have little control over the entry of the field names by the client (through a 3rd party CMS). But I am quite flexible around substitutions required to create the compliant string.
I have a reactive hack algorithm for now along the lines of:
public static string FormatForDynamicRdlc(this string s)
{
//We need to change this string to be CLS compliant.
return s.Replace(Environment.NewLine, string.Empty)
.Replace("\t", string.Empty)
.Replace(",", string.Empty)
.Replace("-", "_")
.Replace(" ", "_");
}
But I would love something more comprehensive. Any ideas?
NOTE: If it is of any help, the algorithm I am using to create the dynamic RDLC is based on the BuildRDLC method found here: http://csharpshooter.blogspot.com/2007/08/revised-dynamic-rdlc-generation.html
Here's the algorithm I use to create C/C++ identifiers from arbitrary strings (translated to C#):
static void Main(string[] args)
{
string input = "9\ttotally no # # way!!!!";
string safe = string.Concat("_", Regex.Replace(input, "[^a-z0-9_]+", "_"));
Console.WriteLine(safe);
}
The leading underscore is unnecessary if the first character of the regex result is not numeric.
Here is a regex which I found could be useful for splitting CLS-compliant string part and non-CLS-compliant string part. Below implementation in C#:
string strRegex = #"^(?<nonCLSCompliantPart>[^A-Za-z]*)(?<CLSCompliantPart>.*)";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
string strTargetString = #" _aaaaaa[5]RoundingHeader";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
I am using the JSON2 script in an asp page to parse JSON post data.
After parsing the data, I have an object in VBScript that allows for notations such as:
jsonData.key
I wish to parse through all the keys, however, I have no knowledge of the key names.
How would I go about doing this?
Example JSON:
{ "dbtable":"TABLE1", "dbcommand": "INSERT", "dbfilter": "ID" }
Thanks
You need to enumerate the property names of the object however this is a very alien thing to do in VBScript. You will need to build some other Jscript functions to assist converting the object into something more easily consumed in VBScript.
If the data is really as simplistic as the example in the question then you could use this function:-
function toDictionary(o)
{
var result = Server.CreateObject("Scripting.Dictionary");
for (var key in o)
result.Add(key, o[key]);
return result;
}
Now in VBScript:-
Dim myData: Set myData = toDictionary(jsonData);
For Each Key In myData
'' // Each Key is a property for jsonData
Next