How to update data in hypertable - c#

I have written some C# code to store data into hypertable database. However I don't know how to update the data.
Below is what I have done:
Hypertable b = new Hypertable();
b.Write("1", "value1");//this line is for writing to database
b.Write("1", "value111");//this line is for updating the value whose key = "1"
and my Write function is:
public override bool Write(string key, string value)
{
try
{
using (IContext context = Context.Create(connectionString))
using (IClient client = context.CreateClient())
{
using (INamespace ns = client.OpenNamespace("Test", OpenDispositions.OpenAlways | OpenDispositions.CreateIntermediate))
{
using (ITable table = ns.OpenTable(tableName))
{
using (ITableMutator mutator = table.CreateMutator())
{
Key _key = new Key { Row = key, ColumnFamily = "vvalue" };
mutator.Set(_key, Encoding.UTF8.GetBytes(value));
}
}
}
}
return true;
}
catch (Exception e)
{
Console.WriteLine("Hypertable--Write--{0}", e.Message);
return false;
}
}
So my update is simply write again with the same key but different value. However after updating I do a read of that key and value, it is supposed to show the new key and value (key = "1" and value = "value111") but it doesn't, it just shows the old key and value (key = "1" and value = "value1")
I don't know why this happens. Any tips will be appreciated. Thanks.

You can try adding mutator.Flush() to your innermost using block, although it should be called automatically when mutator goes out of scope...

Related

Update the data from the instance SQL its state is unchangued and its not saving its a big Obj

public string UpdateCateter(string json)
{
try
{
jss.MaxJsonLength = 900000000;
conexion.Configuration.ValidateOnSaveEnabled = false;
conexion.Configuration.AutoDetectChangesEnabled = false;
conexion.Configuration.LazyLoadingEnabled = false;
conexion.Configuration.ProxyCreationEnabled = false;
dynamic newValues = jss.DeserializeObject(json);
int codigo = Convert.ToInt32(newValues["id"]);
cateter_mahurka_web data = conexion.cateter_mahurka_web.Find(codigo);
if (data != null)
{
foreach (var property in data.GetType().GetProperties())
{
var newValue = newValues[property.Name];
if (newValue != null)
{
var rspre3 = property.SetValue(data, Convert.ChangeType(newValue, property.PropertyType));
var rspre1 = conexion.Entry(data).State;
}
}
var rspre = conexion.Entry(data).State;
var rs = conexion.SaveChanges();
return jss.Serialize(rs > 0);
}
return jss.Serialize("No se encontro ningun registro");
}
#region catch...
}
I hope u can help me, Im trying to update a database record using Entity Framework. The New Values are being stored into an object called "newValues". Then, it finds a record in the database with the specified "id" value and stores it in the "data" object.
Next, the code loops through each property in the "data" object and compares it to the corresponding property in the "newValues" object. If the property in "newValues" is not null, the code sets the value of the corresponding property in the "data" object to the value in "newValues".
Finally, the code saves the changes to the database by calling the "SaveChanges" method on the database context. The result of this method call is then serialized and returned as a string, indicating whether the update was successful or not.
It is expected that the code would update the database record with the new values provided in the "newValues" object and return a string indicating whether the update was successful or not.
But in the line var rspre = conexion.Entry(data).State; im getting unchanged so it is not updating can u help me pls.
Although I am making modifications to a database instance, I am encountering an issue where the changes are not being detected by the system. However, I have found a solution to this problem by adding the following line of code to my implementation: "conexion.Entry(data).State = EntityState.Modified;". By setting the State property of the Entry object to EntityState.Modified, the system will recognize that the entity has been modified and persist the changes to the database accordingly.

CreateObject PKCS#11 fail

I tried to comment on this link https://stackoverflow.com/a/39798597/448266, but could not due to the reputation #.
I have tried the sample and run well, but when I changed to arbitrary value it returns exception Message: Net.Pkcs11Interop.Common.Pkcs11Exception : Method C_CreateObject returned 2147483968
I am using safenet HSM SW.
plainKeyValue = Common.HelperFunctions.StringToByteArray("112233445566778899001122334455665566998844335511");
Below is the snapshot of the code, I changed slightly on the key value (as above).
public static string generateAndCreateKeyObj()
{
using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Configurations.Pkcs11LibraryPath, Settings.AppType))
{
// Find first slot with token present
ISlot slot = Helpers.GetUsableSlot(pkcs11, Configurations.default_slot);
// Open RW session
using (Net.Pkcs11Interop.HighLevelAPI.ISession session = slot.OpenSession(SessionType.ReadWrite))
{
// Login as normal user
session.Login(Configurations.user_type, "1234");
// Prepare attribute template of new key
List<IObjectAttribute> objectAttributes = new List<IObjectAttribute>();
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_TOKEN, false)); //not stored in token
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ENCRYPT, true));
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DECRYPT, true));
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_WRAP, true));
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_UNWRAP, true));
objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_EXTRACTABLE, true));
// Specify key generation mechanism
IMechanism mechanism = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_DES3_KEY_GEN);
// Generate key
IObjectHandle secret_key = session.GenerateKey(mechanism, objectAttributes);
////////////////////////////////////////////////////////////////////////////////////////
// Export the key
byte[] plainKeyValue = null;
List<IObjectAttribute> readAttrs = session.GetAttributeValue(secret_key, new List<CKA>() { CKA.CKA_VALUE });
if (readAttrs[0].CannotBeRead)
throw new Exception("Key cannot be exported");
else
plainKeyValue = readAttrs[0].GetValueAsByteArray();
plainKeyValue = Common.HelperFunctions.StringToByteArray("112233445566778899001122334455665566998844335511");
// Prepare attribute template of new key
List<IObjectAttribute> oa = new List<IObjectAttribute>();
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_LABEL, "Imported key"));
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_TOKEN, true));
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ENCRYPT, true));
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DECRYPT, true));
oa.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_VALUE, plainKeyValue));
IObjectHandle importedKey = session.CreateObject(oa);
// Test encryption with generated key and decryption with imported key
using (IMechanism mechanismx = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_DES3_CBC, session.GenerateRandom(8)))
{
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
byte[] encryptedData = session.Encrypt(mechanismx, secret_key, sourceData);
byte[] decryptedData = session.Decrypt(mechanismx, importedKey, encryptedData);
if (Convert.ToBase64String(sourceData) != Convert.ToBase64String(decryptedData))
throw new Exception("Encryption test failed");
}
// Destroy object
session.DestroyObject(importedKey);
session.DestroyObject(secret_key);
session.Logout();
return HelperFunctions.ByteArrayToString(plainKeyValue);
}
}
}
// convert from string to array
public static byte[] StringToByteArray(string hex)
{
byte[] result;
try
{
result = Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
return result;
}
catch (Exception e)
{
throw new Exception(e.Message); ;
}
}
Exception you are getting says that low level PKCS#11 function C_CreateObject returned vendor specific error 0x80000140. You will need to discuss documentation provided by the device vendor or contact vendor support to get better understanding how to handle or avoid this specific error.
Thanks #jariq for your response.
I found out that in safenet hsm when creating a key object, the key plain value must be with odd parity bit, if not then the error mentioned above will occur.
Hope this will help anyone who stumbled the same error.

Error throw exception when insert data with thread

I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.

RegistryKey.GetValue(..) returns null

I'm trying to retrieve the value of a (REG_SZ) registry key and write it to a string. However this code seems to think the key is null or doesn't exist and won't allow me to GetValue() it. Here's the code I'm using to retrieve the value.
string s64BasePath = "SOFTWARE\\Wow6432Node\\Xactware\\";
private void versionSelectorBox_SelectedIndexChanged(object sender, EventArgs e)
{
showForms();
sVersionSelected = versionServerBox.Text;
if (b64Bit == true)
{
string sRKey = s64BasePath + sVersionSelected + "\\"; //Reads as SOFTWARE\\Wow6432Node\\Xactware\\Xactimate28\\
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(sRKey))
{
if (key != null)
{
//label1.Text = "Test."; //Reaches this point just fine
Object o = key.GetValue("Location");
if (o != null)
{
//label1.Text = "Test."; //Does not reach this point, o = null?
sLocationKey = Convert.ToString(o);
}
}
}
//label1.Text = sLocationKey;
}
Here is what the registry looks like. As you can see the Location key exists in the path provided. However the code isn't dropping into the inner most if statement, acting like the o object is null.
Thanks in Advance.
I will be honest, without having Xactimate installed, I do not have the same registry entry you do so I used Skype as my key.
I changed one thing, I changed it from \ to using the literal string flag.
FYI, I ran in this in LINQPad so ignore the 'dump' commands
var test = #"SOFTWARE\Wow6432Node\Skype\Phone";
var reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(test);
reg.Dump("OpenSubKey: ");
var result = reg.GetValue("SkypeFolder");
result.Dump("GetValue: ");
Here are the results from the two dumps

Field Value change not being saved

I am trying to change a field value dynamically from back-end, but looks like the changes are not being saved.
Code
item is fetched from the master database.
using (new EditContext(item))
{
item.Editing.BeginEdit();
try
{
//Value is updated here from "" to Test
item.Fields["Content"].Value = "Test";
}
finally
{
//item.Fields["Content"].Value is "" again.
item.Editing.AcceptChanges();
item.Editing.EndEdit();
}
}
UPDATE
As #sitecore climber said, I did change my code back to use -
new Sitecore.SecurityModel.SecurityDisabler()
However, the issue was caching. The updated value was displayed in the content editor, only after I had cleared the cache and restarted the browser.
To get around that, I disabled caching before making the edit and turned it back on once the editing was done.
CacheManager.Enabled = false;
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Editing.BeginEdit();
try
{
item.Fields["Content"].Value = "Test";
}
finally
{
item.Editing.EndEdit();
}
}
CacheManager.Enabled = true;
Please add : (new Sitecore.SecurityModel.SecurityDisabler())
EditContext containts next lines of code :
public EditContext(Item item)
{
Assert.ArgumentNotNull((object) item, "item");
this._item = item;
this._item.Editing.BeginEdit();
}
so you don't need here if you have in your code
item.Editing.BeginEdit();
your code must be :
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Editing.BeginEdit();
try
{
//Value is updated here from "" to Test
item.Fields["Content"].Value = "Test";
}
finally
{
//item.Fields["Content"].Value is "" again.
// Remove AcceptChanges I never use it , for editing .
// item.Editing.AcceptChanges();
item.Editing.EndEdit();
}
}
I updated my answer, did you check on content editor if are any changes ?
Can you clear cache, and check again. It's really strange why is not working I guess can be a caching problem .
Try using SecurityDisabler if it helps..
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Editing.BeginEdit();
try
{
//Value is updated here from "" to Test
item.Fields["Content"].Value = "Test";
}
finally
{
//item.Fields["Content"].Value is "" again.
item.Editing.AcceptChanges();
item.Editing.EndEdit();
}
}

Categories