sbyte arrays always coming back null - c#

I have a function to writes a bunch of "ImageSignatures" to a DbContext:
using (var db = new ImageContext())
{
foreach (var file in files)
{
var sig = new ImageSignature
{
FileName = file,
Signature = Signature(file),
};
Console.WriteLine("{0}: {1}", Path.GetFileName(sig.FileName), Sig2Str(sig.Signature));
if (sig.Signature != null)
{
db.Images.Add(sig);
}
}
try
{
records = db.SaveChanges(); // where the heck is this saving to!?
}
...
Where the Signature property is defined as
[MinLength(420)]
[MaxLength(420)]
[Required]
public sbyte[] Signature { get; set; }
If I put a breakpoint just before I Add the sig, I can see that it's not null, but a 420 byte array as I expect.
On a later run of the application I try to loop over the ImageSignatures I inserted,
foreach (var img1 in db.Images)
{
var set = new List<string> { img1.FileName };
foreach (var img2 in db.Images)
{
if (Distance(img1.Signature, img2.Signature) < 0.6)
{
set.Add(img2.FileName);
}
}
if (set.Count > 1)
{
dupeSets.Add(set);
}
}
But Signature is always coming back as null. What happened to it? How did it become null, when it wasn't null when I saved it?

Make sure you have saved the changes to your DbContext before disposing it which will ensure that those changes got persisted in the underlying data store:
using (var db = new ImageContext())
{
foreach (var file in files)
{
var sig = new ImageSignature
{
FileName = file,
Signature = Signature(file),
};
Console.WriteLine("{0}: {1}", Path.GetFileName(sig.FileName), Sig2Str(sig.Signature));
db.Images.Add(sig);
}
db.SaveChanges();
}

Related

Generating JSON-formatted data from Google Ads results

The code below is what I'm currently using to generate a JSON representation of the captured data. My question is, is the use of the Google.Protobuf.Reflection.MessageDescriptor and the use of Reflection. The code appears to work. However, is there a better way to do this?
The code is called by a ClearScript-enabled JavaScript instance, thus the strings rather than longs in the parameters.
public string GenerateHistoricalMetrics(GoogleAdsClient client, string customerIdString, string locationIdsList,string languageIdString, string keywordTextsList, string pageUrl, bool debug = true)
{
if (debug) Debugger.Launch();
long[] locationIds = (from id in locationIdsList.Split(',') select long.Parse(id)).ToArray();
string[] keywordTexts = keywordTextsList.Split(',');
long customerId = long.Parse(customerIdString);
long languageId = long.Parse(languageIdString);
KeywordPlanIdeaServiceClient keywordPlanIdeaService =
client.GetService(Services.V10.KeywordPlanIdeaService);
// Make sure that keywords and/or page URL were specified. The request must have
// exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set.
if (keywordTexts.Length == 0 && string.IsNullOrEmpty(pageUrl))
{
return JsonConvert.SerializeObject(new JSON() { Error = "At least one of keywords or page URL is required, but neither was specified." });
}
// Specify the optional arguments of the request as a keywordSeed, UrlSeed,
// or KeywordAndUrlSeed.
GenerateKeywordIdeasRequest request = new GenerateKeywordIdeasRequest()
{
CustomerId = customerId.ToString(),
};
if (keywordTexts.Length == 0)
{
// Only page URL was specified, so use a UrlSeed.
request.UrlSeed = new UrlSeed()
{
Url = pageUrl
};
}
else if (string.IsNullOrEmpty(pageUrl))
{
// Only keywords were specified, so use a KeywordSeed.
request.KeywordSeed = new KeywordSeed();
request.KeywordSeed.Keywords.AddRange(keywordTexts);
}
else
{
// Both page URL and keywords were specified, so use a KeywordAndUrlSeed.
request.KeywordAndUrlSeed = new KeywordAndUrlSeed
{
Url = pageUrl
};
request.KeywordAndUrlSeed.Keywords.AddRange(keywordTexts);
}
// Create a list of geo target constants based on the resource name of specified
// location IDs.
foreach (long locationId in locationIds)
{
request.GeoTargetConstants.Add(ResourceNames.GeoTargetConstant(locationId));
}
request.Language = ResourceNames.LanguageConstant(languageId);
// Set the network. To restrict to only Google Search, change the parameter below to
// KeywordPlanNetwork.GoogleSearch.
request.KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearch; //.GoogleSearchAndPartners;
var list = new List<Dictionary<string, object>>();
try
{
// Generate keyword ideas based on the specified parameters.
var response =
keywordPlanIdeaService.GenerateKeywordIdeas(request);
// Iterate over the results and print its detail.
foreach (GenerateKeywordIdeaResult result in response)
{
KeywordPlanHistoricalMetrics metrics = result.KeywordIdeaMetrics;
Google.Protobuf.Reflection.MessageDescriptor descriptor = GenerateKeywordIdeaResult.Descriptor;
foreach (var field in descriptor.Fields.InDeclarationOrder())
{
object value = field.Accessor.GetValue(result);
if (value != null)
{
var props = value.GetType().GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.GetField | BindingFlags.Instance);
var dict = new Dictionary<string, object>();
foreach (string key in from prop in props
let key = Title(field.JsonName) + "." + prop.Name
where key.StartsWith("Keyword")
select key
)
{
dict.Add(key, value);
}
if (dict.Count() > 0)
list.Add(dict);
}
}
}
}
catch (GoogleAdsException e)
{
return JsonConvert.SerializeObject(new JSON() { Error = $"Failure: Message: {e.Message}, Failure: {e.Failure}, Request ID: {e.RequestId}" });
}
return JsonConvert.SerializeObject(new JSON() { Cargo = list, Crew = resultList });
}

elastic search field update from csv file in c#

I am new to programming in C#
I want to read the csv file and update the fields in elastic search. I already have this function made by someone else and I want to call this function and update fields.
public static bool UpdateDocumentFields(dynamic updatedFields, IHit<ClientDocuments> metaData)
{
var settings = (SystemWideSettings)SystemSettings.Instance;
if (settings == null)
throw new SettingsNotFoundException("System settings have not been initialized.");
if (ElasticSearch.Connect(settings.ElasticAddressString(), null, out ElasticClient elasticClient, out string status))
{
return ElasticSearch.UpdateDocumentFields(updatedFields, metaData, elasticClient);
}
return false;
}
what I have done myself so far is :
private void btnToEs_Click(object sender, EventArgs e)
{
var manager = new StateOne.FileProcessing.DocumentManager.DocumentManager();
var path = "C:/Temp/MissingElasticSearchRecords.csv";
var lines = File.ReadLines(path);
foreach (string line in lines)
{
var item = ClientDocuments.GetClientDocumentFromFilename(line);
if (item != null)
{
var output = new List<ClientDocuments>();
manager.TryGetClientDocuments(item.AccountNumber.ToString(), 100, out output);
if (output!= null && output.Count <= 0)
{
var docs = new List<ClientDocuments>();
//var doc = docs.Add();
// var doc = docs.Add();
//docs.Add(doc);
foreach (var doc in output)
{
if (!item.FileExists)
{
//insert in elastic search
manager.UpdateDocumentFields(output, );
}
else
{
//ignore
}
}
My problem here is manager.updateDocumentFields() is a function. I am calling it but what I need to pass as a parameter? Thanks in advance.

Object multiple reference IEntityTracker error while saving audit table

first I know this question has been asked but I really couldn't find an answer nor find the root of the problem so maybe a someone points me in the right direction.
I'm having the An entity object cannot be referenced by multiple instances of IEntityChangeTracker. error when trying to save into the log tables.
for the log table, I'm using
https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.EntityFramework
so inside my DbContext class where I define the dbset, I have to override the onscopecreated function
the problem here is that when context.Savechanges run for the first audit record for each table it works but after first record, I get the multiple reference error.
so let's say I have the following tables
Languages table. with the following values
English,French,German
Countries Table with the following values
UK,France,Germany
for languages table, if I change English to English3 and save it works It records to the audit table but then for languages table, I can not do any changes at any records it's the same in every table
what am I missing?
private void SaveToLogTable(AuditScope auditScope)
{
foreach (var entry in ((AuditEventEntityFramework)auditScope.Event).EntityFrameworkEvent.Entries)
{
if(entry.Action is null) return;
if (TABLES.Any(x => x.T_TABLE_NAME.Equals(entry.Table)))
{
var newLog = new LOGS
{
LOG_ACTION = ACTIONS.FirstOrDefault(x => x.A_DESC == entry.Action)?.A_CODE,
LOG_DATE = DateTime.Now,
USERS = MyGlobalSettings.MyUser
};
if (entry.Changes != null)
{
foreach (var changes in entry.Changes)
{
var ch = new CHANGES
{
CH_COLUMN = changes.ColumnName,
CH_NEW_VALUE = changes.NewValue.ToString(),
CH_ORIGINAL_VALUE = changes.OriginalValue.ToString()
};
newLog.CHANGES.Add(ch);
}
}
if (entry.ColumnValues != null)
{
foreach (var kv in entry.ColumnValues)
{
var val = new VALUES
{
ColumnName = kv.Key,
ColumnValue = kv.Value.ToString()
};
newLog.VALUES.Add(val);
}
}
TABLES.First(x => x.T_TABLE_NAME.Equals(entry.Table)).LOGS.Add(newLog);
}
else
{
var table = new TABLES {T_TABLE_NAME = entry.Table};
var newLog = new LOGS
{
LOG_ACTION = ACTIONS.FirstOrDefault(x => x.A_DESC.Equals(entry.Action))?.A_CODE,
LOG_DATE = DateTime.Now,
LOG_USER_REFNO = MyGlobalSettings.MyUser.U_ROWID
//USERS = MyGlobalSettings.MyUser
};
if (entry.Changes != null)
{
foreach (var changes in entry.Changes)
{
var ch = new CHANGES
{
CH_COLUMN = changes.ColumnName,
CH_NEW_VALUE = changes.NewValue.ToString(),
CH_ORIGINAL_VALUE = changes.OriginalValue.ToString()
};
newLog.CHANGES.Add(ch);
}
}
if (entry.ColumnValues != null)
{
foreach (var kv in entry.ColumnValues)
{
var val = new VALUES
{
ColumnName = kv.Key,
ColumnValue = kv.Value is null? "": kv.Value.ToString()
};
newLog.VALUES.Add(val);
}
}
table.LOGS.Add(newLog);
//TABLES.Attach(table);
//TABLES.First(x => x.T_TABLE_NAME.Equals(entry.Table)).LOGS.Add(newLog);
TABLES.Add(table);
//TablesList.Add(table);
}
//entry.Entity
}
}

How can I pass a function with one parameter to an ICommand?

Here's my ICommand:
public ICommand ConfirmLotSavedCommand {
get
{
return new RelayCommand(ConfirmLotSaved);
}
}
The problem is I have deserialized data that I want to store into database after a user clicks confirm button. If the user does not click on confirm or the lot number already exists, then I don't want to save the deserialized string in db.
I had trouble calling a function with one parameter inside my ConfirmLotSaved() method because of scope.
So I created a set the deserialized lot as a field and put the code to save to db inside of ConfirmLotSaved(). However, the field is null for some strange reason... I'm not sure why.
Here's my attempt:
private LotInformation lot; //field that is supposed to contain all the deserialized info
private void ConfirmLotSaved()
{
using (var db = new DDataContext())
{
bool lotNumDbExists = db.LotInformation.Any(r => r.lot_number == DeserialLotNumber);
if (lotNumDbExists == false)
{
successWindow.Message = "Successfully Saved Lot";
dialogService.ShowDialog(successWindow.Message, successWindow);
LotInformation newLot = new LotInformation();
if (newLot != null)
{
newLot.Id = lot.Id;
newLot.lot_number = lot.lot_number;
newLot.exp_date = lot.exp_date;
LotNumber = Lot.lot_number;
ExpirationDate = Lot.exp_date.ToString();
foreach (Components comp in lot.Components)
{
newLot.Components.Add(comp);
}
ComponentsList = newLot.Components;
foreach (Families fam in lot.Families)
{
newLot.Families.Add(fam);
}
FamiliesList = newLot.Families;
try
{
db.LotInformation.Add(newLot);
db.SaveChanges();
//Grabs the lot_number column from db that is distinct
var lotNum = db.LotInformation.GroupBy(i => i.lot_number).Select(group => group.FirstOrDefault());
//Loops through the lot numbers column in db and converts to list
foreach (var item in lotNum)
{
Console.WriteLine(item.lot_number);
}
LotNumList = lotNum.ToList();
Console.WriteLine("successfully");
}
catch
{
//TODO: Add a Dialog Here
}
}
else if (lotNumDbExists == true)
{
// Inform user that the lot_number already exists
errorWindow.Message = LanguageResources.Resource.Lot_Exists_Already;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
logger.writeErrLog(LanguageResources.Resource.Lot_Exists_Already);
return;
}
}
}
}
Deserialization function to see where lot is grabbing data:
public void DeserializedStream(string filePath)
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "lot_information";
xRoot.IsNullable = false;
// Create an instance of lotinformation class.
LotInformation lot = new LotInformation();
// Create an instance of stream writer.
TextReader txtReader = new StreamReader(filePath);
// Create and instance of XmlSerializer class.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(LotInformation), xRoot);
// DeSerialize from the StreamReader
lot = (LotInformation)xmlSerializer.Deserialize(txtReader);
// Close the stream reader
txtReader.Close();
LotInformation newList = new LotInformation();
using (var db = new DDataContext())
{
bool isDuplicate = db.LotInformation.Any(r => r.lot_number == lot.lot_number);
if (newList != null && isDuplicate == false)
{
newList.Id = lot.Id;
newList.lot_number = lot.lot_number;
newList.exp_date = lot.exp_date;
DeserialLotNumber = newList.lot_number;
DeserialExpirationDate = newList.exp_date.ToString();
foreach (Component comp in lot.Components)
{
newList.Components.Add(comp);
}
DeserialComponentsList = newList.Components;
foreach (Families fam in lot.Families)
{
newList.Families.Add(fam);
}
DeserialFamiliesList = newList.Families;
}
else if (isDuplicate == true)
{
DeserialAnalytesList = null;
DeserialFamiliesList = null;
// Inform user that the lot_number already exists
errorWindow.Message = LanguageResources.Resource.Lot_Exists_Already;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
logger.writeErrLog(LanguageResources.Resource.Lot_Exists_Already);
return;
}
}
}
I figured out what was wrong:
After setting private LotInformation lot; field before constructor, I redeclared locally my mistake:
LotInformation lot = new LotInformation();
Changed it to:
lot = new LotInformation();
and it works.
I suggest you to use RelayCommand's generic edition http://www.kellydun.com/wpf-relaycommand-with-parameter/
It will allow you to pass lot to your command from view, all you need to store lot in current DataContext.

Get creation date for the file with SharpSvn

I'm playing with SharpSvn and have to analyze folder in repository
and I need to know when some file has be created there,
not last modification date, but when it was created,
Do you have any idea how to do that?
I started with the following:
Collection<SvnLogEventArgs> logitems;
var c = client.GetLog(new Uri(server_path), out logitems);
foreach (var i in logitems)
{
var properties = i.CustomProperties;
foreach (var p in properties)
{
Console.WriteLine(p.ToString());
Console.WriteLine(p.Key);
Console.WriteLine(p.StringValue);
}
}
But I don't see any creation date there.
Does someone know where to get it?
Looks like I can't do that. Here is how I solved this problem:
I'm getting the time if it was the SvnChangeAction.Add.
Here is the code (SvnFile is my own class, not from SharpSvn):
public static List<SvnFile> GetSvnFiles(this SvnClient client, string uri_path)
{
// get logitems
Collection<SvnLogEventArgs> logitems;
client.GetLog(new Uri(uri_path), out logitems);
var result = new List<SvnFile>();
// get craation date for each
foreach (var logitem in logitems.OrderBy(logitem => logitem.Time))
{
foreach (var changed_path in logitem.ChangedPaths)
{
string filename = Path.GetFileName(changed_path.Path);
if (changed_path.Action == SvnChangeAction.Add)
{
result.Add(new SvnFile() { Name = filename, Created = logitem.Time });
}
}
}
return result;
}
Slightly different code than the previous one:
private static DateTime findCreationDate(SvnClient client, SvnListEventArgs item)
{
Collection<SvnLogEventArgs> logList = new Collection<SvnLogEventArgs>();
if (item.BasePath != "/" + item.Name)
{
client.GetLog(new Uri(item.RepositoryRoot + item.BasePath + "/" + item.Name), out logList);
foreach (var logItem in logList)
{
foreach (var changed_path in logItem.ChangedPaths)
{
string filename = Path.GetFileName(changed_path.Path);
if (filename == item.Name && changed_path.Action == SvnChangeAction.Add)
{
return logItem.Time;
}
}
}
}
return new DateTime();
}

Categories