I have a hjson file like this that I want to deserialize and work with:
{
"TestConfig": {
"SecondConfig": {
"ConnectionString": "Integrated Security = true; Data Source = dataPseudo; Initial Catalog = catalogPseudo; Connect Timeout = 180",
"SpecificationPseudo": "pseudo",
"NumberOfHintsPseudo": 300
},
"ThirdConfig": "pseudo"
}... // more hjson coming here.
I load it with the HjsonValue.Load method like this:
private static Foo convertJson()
{
var loadedValue = HjsonValue.Load("hjsonFile.hjson").ToString();
return new JsonSerializer<Foo>().DeserializeFromString(loadedValue);
// another failed method: return JsonConvert.DeserializeObject<Foo>(loadedValue);
// A third failed method: return JsonConvert.DeserializeObject<Dictionary<string, Foo>>(loadedValue);
}
I think my problem is in the 2 c#-coded lines, but can't figure what. Am I deserializing wrong or what seems to be the problem? I suspect that it's because it is a nested json, but can't find a way to deserialize it. Trying to use dictionary as it is a answer in a other stack-question, but it didn't work for me.
Note: The first and second tried return method don't return any errors, but they just return a nullreferenceexception since "SecondConfig" and "ThirdConfig" both are null..
Update (with help from er-sho): removed the "root"-element from the hjson (TestConfig), which solved the problem.
Removing "TestConfig" from the hjson fixed it, since it's root and the class I am working with.
Related
I am trying to read back from the GPU a compute buffer inside of which there is an array of structs that I have defined and previously set.
var req = AsyncGPUReadback.Request(myBuffer);
if(req.hasError == false)
{
var readback = req.GetData<myStruct>();
print(readback);
}
When I put this in the code I get this error: InvalidOperationException: Cannot access the data as it is not available. The problem is that the data should be available because when I use the normal GetData method everything works just fine.
myBuffer.GetData(data);
Does anyone have an idea where I should be looking to get this error solved? Thanks!
------------------------Edit-------------------------------
I found a solution here https://github.com/keijiro/AsyncCaptureTest/blob/master/Assets/AsyncCapture.cs , but It's not very clear to me why it is working now and not before.
void Update()
{
AsyncGPUReadback.Request(myBuffer, OnCompleteReadBack);
}
void OnCompleteReadBack(AsyncGPUReadBackRequest request)
{
if(request.hasError == false)
{
var data = request.GetData<myStruct>();
}
}
I've been trying to pass a data array to c# web method with using jquery. I have a table which has selectable rows. And my function must pass the id's of selected data. But i can't pass the object array with PageMethods.
Here is my jquery function;
function DeleteQuestions()
{
var table = $('#questTable').DataTable();
var data = (table.rows('.selected').data()).map(function (d) { return d.q_id; });
PageMethods.Delete(data);
}
When i debug it with firebug, veriable data looks like : Object["543","544","546"] as i wanted.
And here is my Web Method:
[WebMethod]
public static void Delete(List<string> questId)
{
DB_UserControl carrier = new DB_UserControl(); //break pointed here
}//and looks it doesn't come here
It doesn't work, and the error is : Cannot serialize object with cyclic reference within child properties. I've searced for error but i couldn't figured it out. So need some help. Thanks in advance.
Note:Error throws at script function's last line: PageMethods.Delete(data);
And i think it might be about mapped data causes some kind of loop behavior.
Problem solved with changing syntax. I use
var data = $.map(table.rows('.selected').data(), function (d) {
return d.q_id;
});
instead of given line. I don't know what caused the error but this code works fine and i get data in c#. Thank you all
Using NopCommerce 3.8, Visual Studio 2015 proff.
I have created a plugin that is responsible for making restful calls to my Web API that exposes a different DB to that of Nop.
The process is run via a nop Task, it successfully pulls the data back and i can step through and manipulate as i see fit, no issues so far.
Issue comes when i try to update a record on the product table, i perform the update... but nothing happens no change, no error.
I believe this is due to the Context having no idea about my newly instantiated product object, however I'm drawing a blank on what i need to do in relation to my particular example.
Similar questions usually reference a "model" object that is part of the parameter of the method call, "model" has the method ToEntity which seems to be the answer in similar question in stack.
However my example doesn't have the ToEntity class/method possibly because my parameter is actually a list of products. To Clarify here my code.
Method in RestClient.cs
public async Task<List<T>> GetAsync()
{
try
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(ApiControllerURL);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
catch (Exception e)
{
return null;
}
}
Method in my Service Class
public async Task<List<MWProduct>> GetProductsAsync()
{
RestClient<MWProduct> restClient = new RestClient<MWProduct>(ApiConst.Products);
var productsList = await restClient.GetAsync();
InsertSyncProd(productsList.Select(x => x).ToList());
return productsList;
}
private void InsertSyncProd(List<MWProduct> inserted)
{
var model = inserted.Select(x =>
{
switch (x.AD_Action)
{
case "I":
//_productService.InsertProduct(row);
break;
case "U":
UpdateSyncProd(inserted);
.....
Then the method to bind and update
private void UpdateSyncProd(List<MWProduct> inserted)
{
var me = inserted.Select(x =>
{
var productEnt = _productRepos.Table.FirstOrDefault(ent => ent.Sku == x.Sku.ToString());
if(productEnt != null)
{
productEnt.Sku = x.Sku.ToString();
productEnt.ShortDescription = x.ShortDescription;
productEnt.FullDescription = x.FullDescription;
productEnt.Name = x.Name;
productEnt.Height = x.Pd_height != null ? Convert.ToDecimal(x.Pd_height) : 0;
productEnt.Width = x.Pd_width != null ? Convert.ToDecimal(x.Pd_width) : 0;
productEnt.Length = x.Pd_depth != null ? Convert.ToDecimal(x.Pd_depth) : 0;
productEnt.UpdatedOnUtc = DateTime.UtcNow;
}
//TODO: set to entity so context nows and can update
_productService.UpdateProduct(productEnt);
return productEnt;
});
}
So as you can see, I get the data and pass data through to certain method based on a result. From that list in the method I iterate over, and pull the the entity from the table, then update via the product service using that manipulated entity.
So what am I missing here, I'm sure its 1 step, and i think it may be either be because 1) The context still has no idea about the entity in question, or 2) Its Incorrect calls.
Summary
Update is not updating, possibly due to context having no knowledge OR my methodology is wrong. (probably both).
UPDATE:
I added some logger.inertlog all around my service, it runs through fine, all to the point of the call of update. But again I check the product and nothing has changed in the admin section.
plugin
I have provided the full source as i think maybe this has something to do with the rest of the code setup possibly?
UPDATE:
Added the following for testin on my execute method.
var myprod = _productRepos.GetById(4852);
myprod.ShortDescription = "db test";
productRepos.Update(myprod);
This successfully updates the product description. I moved my methods from my service into the task class but still no luck. The more i look at it the more im thinking that my async is killing off the db context somehow.
Turned of async and bound the getbyid to a new product, also removed the lambda for the switch and changed it to a foreach loop. Seems to finally update the results.
Cannot confirm if async is the culprit, currently the web api seems to be returning the same result even though the data has changed (some wierd caching by deafult in .net core? ) so im creating a new question for that.
UPDATE: It appears that the issue stems from poor debugging of async. Each instance I am trying to iterate over an await call, simply put im trying to iterate over a collection that technically may or may not be completed yet. And probably due to poor debugging, I was not aware.
So answer await your collection Then iterate after.
When I try to access my classic ASP application I get a random error of "Invalid Procedure Call or Argument". The line that causes this error calls a method from a C# component.
Here is the line that breaks in vbscript :
tmpArray2 = session.get(arrName) 'where arrName is a string
Also it cracks at this kind of line too :
if UBound(session.get("RTT_ID")) <> "-1" then
And here is the component code for the get method :
public object get(string key)
{
if (key == null || IsExpired)
{
return null;
}
if (!SessionData.ContainsKey(key))
{
var sessionData = GetDbSessionData(key);
var cachedValue = default(object);
if (sessionData == null || sessionData.Value == null || sessionData.ValueType == null)
{
LogManager.Instance.LogFormat(this, LogLevel.Warning, "Session data not found. SessionId: '{0}'; Key: '{1}'.", this.SessionInfo.Id, key);
cachedValue = null;
}
else
{
cachedValue = SessionDataSerializer.Instance.DeserializeSessionData(sessionData.Value, sessionData.ValueType);
}
var cachedSessionData = new CachedSessionData();
cachedSessionData.CachedValue = cachedValue;
cachedSessionData.DbEntity = sessionData;
SessionData.Add(key, cachedSessionData);
}
RefreshExpirationDate();
return SessionData[key].CachedValue;
}
Also, what I noticed and I do not know if it is relevant or not, this code cracks a lot on an environment that has 2 servers and makes a balancing between them when the first one is too busy. If I try it on a single server, I managed to broke it only once.
Any ideas?
Thank you for your answers. The problem was that because we wanted to increase our performance we had to serialize every object that was send to the component and deserialize it when we returned it to the vbscript. The issue was that we had one array that was containing other arrays and when we deserialize the array we could not return also the child arrays and that was causing the problem. We used for deserialization the MessageBox library.
Another thing to mention is that on our environment we had 2 servers and we are doing some balancing between them. When the application runs only on one server, the deserialization was ok and we had no problems, but when we switched to the other server we encountered this problem.
Maybe this answer will help others understand what could happen if you receive this type of error.
I have a DAL class library that is included in my program as a DLL. The below line is from the DAL to initialize the connection.
DataSet ds = new DataSet("table");
SqlConnection cnn = new SqlConnection(Settings.CMOSQLConn);
When I run this I get the below error:
An unhandled exception of type 'System.StackOverflowException' occurred in CMO.DAL.dll
The below is in the Settings.Designer.cs file and it is where it shows the error on the get call:
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=WWCSTAGE;Initial Catalog=CMO;Persist Security Info=True;User ID=CMOWe" +
"bService;Password=ecivreSbeWOMC")]
public static string CMOSQLConn {
get {
return (CMOSQLConn);
}
}
Anyone have any ideas of what to look for? Is it because the connection string is stored in the dll instead of my Main App? I am really stuck on this and will greatly appreciate any help!
EDIT 1
I tried Greg's suggestion below:
public static string CMOSQLConn {
get {
return (Settings.CMOSQLConn);
}
}
And I still get the same error... Any more thoughts? Thanks so far!
EDIT 2
So I followed the suggestion of regenerating the settings file below and now my setting file looks like this -->
public string CMOSQLConn {
get {
return ((string)(this["CMOSQLConn"]));
}
}
Unfortunately this won't compile now as wherever I have this statement -->
SqlConnection cnn = new SqlConnection(Settings.CMOSQLConn);
I now get this error -->
Error 1 An object reference is required for the non-static field, method, or property 'CMO.DAL.Properties.Settings.CMOSQLConn.get' B:\MyDocs\tmpPATRIOT\Projects\VS2008\DisConnectDAL\CMO.DAL\SupportWorker.cs 13 51 CMO.DAL
Is this what I should expect?
Thanks!
This is a classic c# properties mistake. Double check what you're returning in your property-- you're returning the property itself! Name resolution will prefer the local name over an external name. You're getting a stack overflow because you hit infinite recursion when CMOSQLConn.get calls CMOSQLConn.get.
Consider returning Settings.CMOSQLConn. The extra specification should clearly indicate the correct location of your connection string.
EDIT:
Whoops! I didn't notice that you pasted that from your Settings designer file. The infinite recursion is clearly happening, but I'm afraid you'll have to do some more investigation to track down why it's happening in this case.
It appears that your designer file was generated incorrectly (!!!). On VS2008, my settings designer getters look something like:
public bool Foo{
get {
return ((bool)(this["Foo"]));
}
// ...
}
You may need to do something similar. IE:
public string CMOSQLConn
get {
return ((string)(this["CMOSQLConn"]));
}
// ...
}
Try changing your code to this:
public static string CMOSQLConn {
get {
return ((string)(this["CMOSQLConn"]));
}
}
Hmm.. Good point in the comments. I just looked in my VS settings file and copied and pasted without thinking. Something isn't right with your settings file... It shouldn't be creating a static property for the settings.