Converting Guid to Cassandra UUID - cassandra

I want to convert a Guid to a UUID or a string version of the same so that the following CQL query will work.
if (cassandraDb.ExecuteQuery(string.Format("SELECT OrderGroupId FROM Order WHERE OrderGroupId={0}", orderGroupId)).Count() <= 0) {
The variable 'orderGroupId' is a Guid. Obviously this is using FluentCassandra in a C#/.NET environmnet. Any hints?
Thank you.

To convert System.Guid to FluentCassandra.Types.UUIDType you just need to assign one into the other.
Same goes for FluentCassandra.Types.TimeUUIDType.

Execute the CQL query directly as a string by using the .ToString() property.
string.Format("SELECT OrderGroupId FROM Order WHERE OrderGroupId={0}", orderGroupId.ToString())
Should work fine. If it does not... you may want to try this (which I found on a comment thread on one of the C# clients):
protected static string ToCqlString(Guid guid) {
var bytes = guid.ToByteArray();
StringBuilder sb = new StringBuilder(bytes.Length * 2);
for (int i = 0; i < 16; i++) {
if (i == 4 || i == 6 || i == 8 || i == 10) {
sb.Append("-");
}
var b = bytes[i];
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
Cheers,
Allison

Related

Duplicate result of Hazealcast Predicate while querying with "in"

I query Hazelcast data map using Predicate with "in" condition like below.
List<String> liveVideoSourceIdList=new ArrayList(){"my_filter"};
Predicate predicate=Predicates.in("myField",liveVideoSourceIdList.toArray(new String[0]));
When i filter map with the created predicate,all the values are duplicated.
If i use "like" instead of "in" like below,no duplication happens. Is there any thoughts about this problem ?
Predicate predicate=Predicates.like("myField",liveVideoSourceIdList.get(0));
I have been unable to reproduce your issue, using 3.9-SNAPSHOT
which version are you using ?
I am using
int min = random.nextInt( keyDomain - range );
int max = min+range;
String values = new String();
for (int i = min; i < max ; i++) {
values += i+", ";
}
SqlPredicate sqlPredicate = new SqlPredicate("personId IN ("+values+")");
Collection<Personable> res = map.values(sqlPredicate);
if(res.size()!=range){
throw new AssertionException(sqlPredicate+" on map "+map.getName()+" returned "+res.size()+" expected "+range);
}
Set<Personable> set = new HashSet<Personable>(res);
if(res.size()!=set.size()){
throw new AssertionException(sqlPredicate+" on map "+map.getName()+" returned Duplicates");
}
for (Personable person : res) {
if(person.getPersonId() < min || person.getPersonId() >= max ){
throw new AssertionException(map.getName()+" "+person+" != "+sqlPredicate);
}
}

Windows 10 get DeviceFamilyVersion

I'm working windows 10 10240 Univasal windows app, when i use Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion to get deivce version, it return a string "2814750438211605" instead of a version format (major.minor.revision.build).
Anyone can tell me what the string "2814750438211605" means?
The Windows 10 OS version value is located in this string property:
Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion
It returns string value like "2814750438211613".
To convert this long number to readable format use this:
string sv = AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
ulong v = ulong.Parse(sv);
ulong v1 = (v & 0xFFFF000000000000L) >> 48;
ulong v2 = (v & 0x0000FFFF00000000L) >> 32;
ulong v3 = (v & 0x00000000FFFF0000L) >> 16;
ulong v4 = v & 0x000000000000FFFFL;
string version = $"{v1}.{v2}.{v3}.{v4}"; // == 10.0.10240.16413
Your application should treat the as opaque data and just log it "as is". It's a 64-bit decimal value as a string.
Remember the intent of this API is to provide a log string from which you can reconstruct the OS version number for support/analytics. On your server-side analysis, you'd convert it if needed or just use it as a unique version identifier... If you are actually trying to parse it runtime, then you are using it incorrectly and quite likely to recreate same problems that resulted in GetVersionEx and VerifyVersionInfo being deprecated in the first place.
Do not parse the string at runtime in your app. Just store "as is" Remember that with Windows 10, a customer really has no idea what you mean if you ask "What version of Windows do you have?". The answer is "10" and will likely still be "10" for a long time to come.
If you found this question and like me you are looking for a way to do this in JavaScript, then you might find this useful.
getDeviceFamilyVersion() {
let deviceFamilyVersion = Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamilyVersion;
let deviceFamilyVersionDecimalFormat = parseInt(deviceFamilyVersion);
if (isNaN(deviceFamilyVersionDecimalFormat)) {
throw new Error('cannot parse device family version number');
}
let hexString = deviceFamilyVersionDecimalFormat.toString(16).toUpperCase();
while (hexString.length !== 16) { // this is needed because JavaScript trims the leading zeros when converting to hex string
hexString = '0' + hexString;
}
let hexStringIterator = 0;
let versionString = '';
while (hexStringIterator < hexString.length) {
let subHexString = hexString.substring(hexStringIterator, hexStringIterator + 4);
let decimalValue = parseInt(subHexString, 16);
versionString += decimalValue + '.';
hexStringIterator += 4;
}
return versionString.substring(0, versionString.length - 1);
}
Just a nifty way of doing this .. I Creadted a Enum that is used to match predefined device families
public enum DeviceFamily
{
Unknown,
Desktop,
Tablet,
Mobile,
SurfaceHub,
Xbox,
Iot
}
This method will check and parse it into the enum.
var q = ResourceContext.GetForCurrentView().QualifierValues;
if (q.ContainsKey("DeviceFamily"))
{
try
{
Enum.Parse(typeof(DeviceFamily) , q["DeviceFamily"]);
//send the user notification about the device family he is in.
}
catch (Exception ex) { }
}

c# string delimiter

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

Mapping umbraco node to strongtyped object

I am working with Umbraco 4.7.1 and I am trying to map the content-nodes to some autogenerated strong typed objects. I have tried using both valueinjecter and automapper, but OOTB neither of them map my properties. I guess it is because all properties on an Umbraco node (the cms document) are retrieved like this:
node.GetProperty("propertyName").Value;
And my strongly typed objects are in the format of MyObject.PropertyName. So how do I map the property on the node which is retrieved using a method and a string beginning with a lowercase character into a property on MyObject where the property begins with an uppercase character ?
UPDATE
I managed to create the following code which maps the umbraco node as intended, by digging around in the Umbraco sourcecode for some inspiration on how to cast string-properties to strongly typed properties:
public class UmbracoInjection : SmartConventionInjection
{
protected override bool Match(SmartConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name;
}
protected override void Inject(object source, object target)
{
if (source != null && target != null)
{
Node node = source as Node;
var props = target.GetProps();
var properties = node.Properties;
for (int i = 0; i < props.Count; i++)
{
var targetProperty = props[i];
var sourceProperty = properties[targetProperty.Name];
if (sourceProperty != null && !string.IsNullOrWhiteSpace(sourceProperty.Value))
{
var value = sourceProperty.Value;
var type = targetProperty.PropertyType;
if (targetProperty.PropertyType.IsValueType && targetProperty.PropertyType.GetGenericArguments().Length > 0 && typeof(Nullable<>).IsAssignableFrom(targetProperty.PropertyType.GetGenericTypeDefinition()))
{
type = type.GetGenericArguments()[0];
}
targetProperty.SetValue(target, Convert.ChangeType(value, type));
}
}
}
}
}
As you can see I use the SmartConventionInjection to speed things up.
It still takes approximately 20 seconds to map something like 16000 objects. Can this be done even faster ?
thanks
Thomas
with ValueInjecter you would do something like this:
public class Um : ValueInjection
{
protected override void Inject(object source, object target)
{
var node = target as Node;
var props = source.GetProps();
for (int i = 0; i < props.Count; i++)
{
var prop = props[i];
target.GetProperty(prop.Name).Value;
}
}
}

System.getProperty("line.separator") equivalent in j2me

I need to have a cross-platform newline reference to parse files, and I'm trying to find a way to do the equivalent of the usual
System.getProperty("line.separator");
but trying that in J2ME, I get a null String returned, so I'm guessing line.separator isn't included here. Are there any other direct ways to get a universal newline sequence in J2ME as string?
edit: clarified question a bit
Seems like I forgot to answer my question. I used a piece of code that allowed me to use "\r\n" as delimiter and actually considered \r and \n as well seperately:
public class Tokenizer {
public static String[] tokenize(String str, String delimiter) {
StringBuffer strtok = new StringBuffer();
Vector buftok = new Vector();
char[] ch = str.toCharArray(); //convert to char array
for (int i = 0; i < ch.length; i++) {
if (delimiter.indexOf(ch[i]) != -1) { //if i-th character is a delimiter
if (strtok.length() > 0) {
buftok.addElement(strtok.toString());
strtok.setLength(0);
}
}
else {
strtok.append(ch[i]);
}
}
if (strtok.length() > 0) {
buftok.addElement(strtok.toString());
}
String[] splitArray = new String[buftok.size()];
for (int i=0; i < splitArray.length; i++) {
splitArray[i] = (String)buftok.elementAt(i);
}
buftok = null;
return splitArray;
}
}
I don't think "line.separator" is a system property of JME. Take a look at this documentation at SDN FAQ for MIDP developers: What are the defined J2ME system property names?
Why do you need to get the line separator anyway? What I know is that you can use "\n" in JME.

Resources