I have written a piece of code to get a value from a currency converter like below:
WebClient n = new WebClient();
var JsonData = n.DownloadString("http://currencyconverterapi.com/api/v6/convert?q=USD_NRI&compact=ultra&apiKey=");
JsonData = {"USD_INR":69.657026} // Got value result from JsonData
dynamic JObj = JObject.Parse(JsonData);
dynamic JOresult = JObject.Parse(Convert.ToString(JObj.USD_INR)); //Got Error here (Error reading JObject from JsonReader. Current JsonReader item is not an object: Float. Path '', line 1, position 9.)
string JOFilter_Val = Convert.ToString(JOresult.val);
decimal Total = 230 * Convert.ToDecimal(JOFilter_Val);
return Total;
I want to get the value '69.657026' from multiplying with the decimal 230, and return the final result. Can anybody tell me what I'm doing wrong and if possible please correct it?
It's not really clear why you're trying to parse 69.657026 as a JObject - it's not an object.
I suspect you don't need to do that at all - just use JObj.USD_INR as a decimal:
decimal value = JObj.USD_INR; // Use the dynamic conversion to handle this
In general you seem to be converting back and forth far more than you need to. Here's a complete example of what I think you're trying to do:
using Newtonsoft.Json.Linq;
using System;
class Test
{
static void Main()
{
string json = "{ \"USD_INR\": 69.657026 }";
dynamic obj = JObject.Parse(json);
decimal rate = obj.USD_INR;
decimal total = 230 * rate;
Console.WriteLine(total); // 16021.115980
}
}
Alternatively, without dynamic typing:
using Newtonsoft.Json.Linq;
using System;
class Test
{
static void Main()
{
string json = "{ \"USD_INR\": 69.657026 }";
JObject obj = JObject.Parse(json);
decimal rate = (decimal) obj["USD_INR"];
decimal total = 230 * rate;
Console.WriteLine(total);
}
}
I have a library which has a function like this:
int get_user_name(const char **buffer);
in swift, should call like this:
var name:CMutablePointer<CString> = nil
get_user_name(name)
I want make use this function more comfortable so I wrapped this up:
func get_username() -> String {
var name:CMutablePointer<CString> = nil
get_user_name(name)
// how to convert name to String
}
I question is how to convert name to String
It goes something like:
var stringValue :CString = ""
name.withUnsafePointer {p in
stringValue = p.memory
}
return NSString(CString: stringValue)
You can do:
return NSString(UTF8String: name[0])
I have recently worked on AS3 project with a module that works like this:
I have 50 strings and I am picking one randomly of them at a given time. When I am done with the picked one I choose another one of the 49 left again randomly and so on.
I managed to solve this problem using helper arrays, for cycles, mapping index numbers with the strings. Although every thing works just fine I found my code very messed and hard to understand.
Is there a much more easy and cleaner way to solve this problem in AS3?
Maybe there is a library for getting random string out of strings?
Something simple like this class:
public class StringList
{
private var _items:Array = [];
public function StringList(items:Array)
{
_items = items.slice();
}
public function get random():String
{
var index:int = Math.random() * _items.length;
return _items.splice(index, 1);
}
public function get remaining():int{ return _items.length; }
}
And its usage:
var list:StringList = new StringList(['a', 'b', 'c', 'd']);
while(list.remaining > 0)
{
trace(list.random);
}
I'm not sure what do you want to do with that procedure, but here's one proposal:
var stringArray:Array = new Array("string1", "string2", "string2"); //your array with strings
var xlen:uint = stringArray.length-1; //we get number of iterations
for (var x:int = xlen; x >= 0; x--){ //we iterate backwards
var randomKey:Number = Math.floor(Math.random()*stringArray.length); //gives you whole numbers from 0 to (number of items in array - 1)
stringArray.splice(randomKey,1); //remove item from array with randomKey index key
var str:String = stringArray[randomKey]; //output item into new string variable or do whatever
}
I have string value like this:
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
I just need to retrieve role to string array. I wonder if there is the best way to split the string in C# 4.0
string[] arrStrRole = strRole.Split('|').Select .. ??
Basically, I need brandUK, brandUsa, brandAu to string[] arrStrRole.
Thanks.
string[] arrStrRole = strRole.Split('|').Select(r => r.Split(new []{"role="}, StringSplitOptions.None)[1]).ToArray()
results in an string array with three strings:
branduk
brankdusa
brandAu
you can use string[] arrStrRole = strRole.Split('|',','); and this will split according to | and , characters
You can use String.Split in this LINQ query:
var roles = from token in strRole.Split('|')
from part in token.Split(',')
where part.Split('=')[0] == "role"
select part.Split('=')[1];
Note that this is yet prone to error and requires the data always to have this format. I mention it because you've started with Split('|').Select.... You can also use nested loops.
If you need it as String[] you just need to call ToArray:
String[] result = roles.ToArray();
I would go with Regex rather than splitting string. In combination with your intended Select solution, it could look like this:
var roles = Regex.Matches(strRole, #"role=(\w+)")
.Cast<Match>()
.Select(x => x.Groups[1].Value).ToArray();
You could use an extension like this which would allow you to test it easily.
public static string[] ParseRolesIntoList(this string csvGiven)
{
var list = new List<string>();
if (csvGiven == null) return null;
var csv = csvGiven.Split(',');
foreach (var s in csv)
{
if (string.IsNullOrEmpty(s)) continue;
if(!s.StartsWith("role")) continue;
var upperBound = s.IndexOf("|");
if (upperBound <= 0) upperBound = s.Length;
var role = s.Substring(s.IndexOf("=") + 1,
upperBound - s.IndexOf("=") - 1);
list.Add(role);
}
return list.ToArray();
}
Test below found brankdusa typo in your example. Some of the other answers would not deal with brandAu as it matches slightly differently. Try running this test against them if you like
[Test]
public void Should_parse_into_roles()
{
//GIVEN
const string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
//WHEN
var roles = strRole.ParseRolesIntoList();
//THEN
Assert.That(roles.Length, Is.EqualTo(3));
Assert.That(roles[0], Is.EqualTo("branduk"));
Assert.That(roles[1], Is.EqualTo("brankdusa"));
Assert.That(roles[2], Is.EqualTo("brandAu"));
}
This gives an array of the 3 values.
void Main()
{
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
var arrStrRole = strRole.Split('|',',')
.Where(a => a.Split('=')[0] == "role")
.Select(b => b.Split('=')[1]);
arrStrRole.Dump();
}
For some reason I need to save some big strings into user profiles. Because a property with type string has a limit to 400 caracters I decited to try with binary type (PropertyDataType.Binary) that allow a length of 7500. My ideea is to convert the string that I have into binary and save to property.
I create the property using the code :
context = ServerContext.GetContext(elevatedSite);
profileManager = new UserProfileManager(context);
profile = profileManager.GetUserProfile(userLoginName);
Property newProperty = profileManager.Properties.Create(false);
newProperty.Name = "aaa";
newProperty.DisplayName = "aaa";
newProperty.Type = PropertyDataType.Binary;
newProperty.Length = 7500;
newProperty.PrivacyPolicy = PrivacyPolicy.OptIn;
newProperty.DefaultPrivacy = Privacy.Organization;
profileManager.Properties.Add(newProperty);
myProperty = profile["aaa"];
profile.Commit();
The problem is that when I try to provide the value of byte[] type to the property I receive the error "Unable to cast object of type 'System.Byte' to type 'System.String'.". If I try to provide a string value I receive "Invalid Binary Value: Input must match binary byte[] data type."
Then my question is how to use this binary type ?
The code that I have :
SPUser user = elevatedWeb.CurrentUser;
ServerContext context = ServerContext.GetContext(HttpContext.Current);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile profile = GetUserProfile(elevatedSite, currentUserLoginName);
UserProfileValueCollection myProperty= profile[PropertyName];
myProperty.Value = StringToBinary(GenerateBigString());
and the functions for test :
private static string GenerateBigString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 750; i++) sb.Append("0123456789");
return sb.ToString();
}
private static byte[] StringToBinary(string theSource)
{
byte[] thebytes = new byte[7500];
thebytes = System.Text.Encoding.ASCII.GetBytes(theSource);
return thebytes;
}
Have you tried with smaller strings? Going max on the first test might hide other behaviors. When you inspect the generated string in the debugger, it fits the requirements? (7500 byte[])
For those, who are looking for answer. You must use Add method instead:
var context = ServerContext.GetContext(elevatedSite);
var profileManager = new UserProfileManager(context);
var profile = profileManager.GetUserProfile(userLoginName);
profile["MyPropertyName"].Add(StringToBinary("your cool string"));
profile.Commit();