Error in adding properties my object Server OPC-UA - opc-ua

I am using the open62541 library [1.1.2-216-g50933d8].
Tell me how to add engineering units to my node?
Му Node create:
bool isOk = true;
UA_VariableAttributes valueAttr = UA_VariableAttributes_default;
UA_Variant_init(&valueAttr.value);
UA_Float valueVal = 0;
UA_Variant_setScalar(&valueAttr.value, &valueVal, &UA_TYPES[UA_TYPES_FLOAT]);
std::string description = "Value Params";
valueAttr.description = UA_LOCALIZEDTEXT(const_cast<char*>(lt), const_cast<char*>(description.c_str()));
valueAttr.displayName = UA_LOCALIZEDTEXT(const_cast<char*>(lt), const_cast<char*>("Value"));
if(UA_Server_addVariableNode(server, UA_NODEID_NULL,
getNodeId(),
UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
UA_QUALIFIEDNAME(nsIndexBrowser, const_cast<char*>("Value")),
UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE),
valueAttr, nullptr, &value_) != UA_STATUSCODE_GOOD)
{
return isOk;
}
I tried to do this:
UA_EUInformation eu;
eu.namespaceUri = UA_STRING("somecompany.com");
eu.unitId = -1;
eu.displayName = UA_LOCALIZEDTEXT(const_cast<char*>(lt), const_cast<char*>(typeSigne_->getEUid().c_str()));
eu.description = UA_LOCALIZEDTEXT(const_cast<char*>(lt), const_cast<char*>(typeSigne_->getEUid().c_str()));
UA_StatusCode status = UA_Server_writeObjectProperty_scalar(server,
value_,
UA_QUALIFIEDNAME(nsIndexBrowser, "EngineeringUnits"),
&eu,
&UA_TYPES[UA_TYPES_EUINFORMATION]);
if(status != UA_STATUSCODE_GOOD)
{
return isOk;
}
But I got the error code UA_STATUSCODE_BADNOMATCH
I tried to do this:
UA_EUInformation eu;
eu.namespaceUri = UA_STRING("somecompany.com");
eu.unitId = -1;
eu.displayName = UA_LOCALIZEDTEXT(const_cast<char*>(lt), const_cast<char*>(typeSigne_->getEUid().c_str()));
eu.description = UA_LOCALIZEDTEXT(const_cast<char*>(lt), const_cast<char*>(typeSigne_->getEUid().c_str()));
UA_VariableAttributes enAttr = UA_VariableAttributes_default;
UA_VariableAttributes_init(&enAttr);
enAttr.dataType = UA_TYPES[UA_TYPES_EUINFORMATION].typeId;
enAttr.userWriteMask = UA_ACCESSLEVELMASK_READ;
UA_Variant_setScalarCopy(&enAttr.value, &eu, &UA_TYPES[UA_TYPES_EUINFORMATION]);
UA_StatusCode status = UA_Server_addVariableNode(server, UA_NODEID_NULL,
value_,
UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
UA_QUALIFIEDNAME(nsIndexBrowser, "EngineeringUnits"),
UA_NODEID_NUMERIC(0, UA_NS0ID_PROPERTYTYPE),
enAttr,
nullptr, &enUnitNodeUnits_);
if(status != UA_STATUSCODE_GOOD)
{
return isOk;
}
But I got the error code UA_STATUSCODE_BADTYPEMISMATCH
I also tried these examples https://groups.google.com/g/open62541/c/90dpSO2Wu7E/m/mNUknnRSCAAJ . They don't work.
And in general, I tried to add any properties to my object, but it didn't work out either (UA_STATUSCODE_BADTYPEMISMATCH).
I don't understand why I can't do it?

Related

OnPhotonSerializeView Call only on specific condition

I am new in Photon Multiplayer With Unity. I am stuck with a OnPhotonSerializeView() function. This function call every time in second[With Serialization Rate], But I want it to call when a specific bool value change. Like state change of player. Any one have idea about it please help me.
Thanks
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
// Here I want to add condition
stream.SendNext(AppConfig.avatarObj.avtaarGender.ToString());
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.beard));
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.coat));
stream.SendNext(AppConfig.avatarObj.face);
stream.SendNext(AppConfig.avatarObj.hair);
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.hairColor));
stream.SendNext(AppConfig.avatarObj.isBeard);
stream.SendNext(AppConfig.avatarObj.isCoat);
stream.SendNext(AppConfig.avatarObj.isMoustache);
stream.SendNext(AppConfig.avatarObj.isSpecs);
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.moustache));
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.pant));
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.shirt));
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.shoes));
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.specs));
stream.SendNext(SerializeToXmlString(AppConfig.avatarObj.tie));
updateData = false;
print("Sending Data");
}
else if (stream.IsReading)
{
avtaarGenderStr = (string)stream.ReceiveNext();
beardStr = (string)stream.ReceiveNext();
coatStr = (string)stream.ReceiveNext();
faceIndex = (int)stream.ReceiveNext();
hairIndex = (int)stream.ReceiveNext();
hairColorStr = (string)stream.ReceiveNext();
beardValue = (bool)stream.ReceiveNext();
coatValue = (bool)stream.ReceiveNext();
moustacheValue = (bool)stream.ReceiveNext();
specsValue = (bool)stream.ReceiveNext();
moustacheStr = (string)stream.ReceiveNext();
pantStr = (string)stream.ReceiveNext();
shirtStr = (string)stream.ReceiveNext();
shoesStr = (string)stream.ReceiveNext();
specsStr = (string)stream.ReceiveNext();
tieStr = (string)stream.ReceiveNext();
if (info.photonView.ViewID == localPV.ViewID)
{
SetData();
}
print("Reciving Data");
}
}

get_value of a feature in IFeatureCursor

I'm trying to read the attribute "POSTCODE" of the features in IFeatureCursor. The FID was successful read but the "POSTCODE" was failed. The runtime error 'An expected Field was not found or could not be retrieved properly. Appreciate your advise. Paul
private void test2(IFeatureCursor pFeatc1)
{
IFeature feature = null;
IFields pFields;
int ctcur = 0;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indxid = pFields.FindField("FID");
int indxpost = pFields.FindField("POSTCODE");
object valu = feature.get_Value(indxid);
string valupost = feature.get_Value(indxpost);
string aValu = Convert.ToString(valu);
Debug.WriteLine("FID: " + aValu + " Postcode: " + valupost);
ctcur++;
feature = pFeatc1.NextFeature();
}
MessageBox.Show("count cursor = " + ctcur);
}
I have modified the program and successfully read the feature attribute 'POSTCODE'. I have added IFeatureClass.Search(queryFilter, true) to search the feature again by FID and save in a cursor then use the 'feature.get_Value' to read the attribute. Please see my updated code below. Thanks.
private void test2(IFeatureCursor pFeatc1)
{
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;
IMap map = mxdoc.FocusMap;
IFeatureLayer flayer;
IMaps pMaps = mxdoc.Maps;
for (int i = 0; i <= pMaps.Count - 1; i++)
{
map = pMaps.get_Item(i);
IEnumLayer pEnumLayer = map.get_Layers(null, true);
pEnumLayer.Reset();
ILayer pLayer = pEnumLayer.Next();
while (pLayer != null)
{
if (pLayer.Name == "AddrKey")
{
Debug.WriteLine("Layer: " + pLayer.Name);
flayer = (IFeatureLayer)pLayer;
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeature feature = null;
IFields pFields;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indx = pFields.FindField("FID");
object valu = feature.get_Value(indx);
string sFID = Convert.ToString(valu);
IQueryFilter queryFilter = new QueryFilter();
queryFilter.WhereClause = ("FID = " + sFID);
Debug.WriteLine("FID: " + sFID);
queryFilter.SubFields = "POSTCODE";
int fieldPosition = pFeatureClass.FindField("POSTCODE");
IFeatureCursor featureCursor = pFeatureClass.Search(queryFilter, true);
while ((feature = featureCursor.NextFeature()) != null)
{
MessageBox.Show(feature.get_Value(fieldPosition));
}
feature = pFeatc1.NextFeature();
}
}
pLayer = pEnumLayer.Next();
}
}
}

ADO.NET: ExecuteScalar() Connection problum

Here is my C# code
protected bool SaveItems(ObservableCollection<Model> Items, Int32 UserId)
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
foreach (Model Rate in Items)
{
SqlCommand sccmd = new SqlCommand("ItemsAdd", sqlcon);
sccmd.CommandType = CommandType.StoredProcedure;
sccmd.Parameters.Add("#ItemsId", SqlDbType.Int).Value = Rate.Id;
sccmd.Parameters.Add("#RMId", SqlDbType.Int).Value = Rate.HeadId;
sccmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Rate.Date;
sccmd.Parameters.Add("#Price", SqlDbType.Decimal).Value = Rate.Price;
sccmd.Parameters.Add("#UserId", SqlDbType.Int).Value = UserId;
if (Rate.Id == 0)
{
Rate.Id = Convert.ToInt32(sccmd.ExecuteScalar());
}
else
sccmd.ExecuteScalar();
}
sqlcon.Close();
return true;
}
Repeated clicking on add button, this is giving me this error
Additional information: ExecuteScalar requires an open and available
Connection. The connection's current state is closed.
What is causing this error and how can I fix it?
Try Like this:
protected bool SaveItems(ObservableCollection<Model> Items, Int32 UserId)
{
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
foreach (Model Rate in Items)
{
SqlCommand sccmd = new SqlCommand("ItemsAdd", sqlcon);
sccmd.CommandType = CommandType.StoredProcedure;
sccmd.Parameters.Add("#ItemsId", SqlDbType.Int).Value = Rate.Id;
sccmd.Parameters.Add("#RMId", SqlDbType.Int).Value = Rate.HeadId;
sccmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Rate.Date;
sccmd.Parameters.Add("#Price", SqlDbType.Decimal).Value = Rate.Price;
sccmd.Parameters.Add("#UserId", SqlDbType.Int).Value = UserId;
if (Rate.Id == 0)
{
Rate.Id = Convert.ToInt32(sccmd.ExecuteScalar());
}
else
sccmd.ExecuteScalar();
}
sqlcon.Close();
}
return true;
}

Entity Framework - how to save entity without saving related objects

In my Entity Framework, I have three related entities 'Client', 'ClientAddress' and 'LookupAddressType'. "LookupAddressType" is a master class specifying the type of available address type, like business address, residential address etc. ClientAddress depend on LookupAddresstype and Client. While saving a Client entity with relevant ClientAddress data, i'm getting following error.
"Violation of PRIMARY KEY constraint 'PK_LookupAddressType'. Cannot
insert duplicate key in object 'dbo.LookupAddressType'. The statement
has been terminated.
I do not need LookupAddressType to be inserted. Here I just need the relevant lookupAddressTypeId to be inserted in clientAddress entity.
The Saving code is like this:
Add(Client);
_objectContext.SaveChanges();
how can i do this?
The Load Code is below:
private void LoadClientDetails(EFEntities.Client _Client)
{
EFEntities.LookupClientStatu clientStatus;
var clientAddressList = new List<ClientAddress>();
if (_Client == null)
{
return;
}
//Assign data to client object
_Client.ClientName = rtxtName.Text;
_Client.Alias = rtxtAlias.Text;
_Client.ClientCode =Int32.Parse(rtxtClientCode.Text);
_Client.TaxPayerID = rtxtTaxPayerId.Text;
if (rcboStatus.SelectedIndex != 0)
{
clientStatus = new EFEntities.LookupClientStatu
{
ClientStatusID = (Guid) (rcboStatus.SelectedValue),
ClientStatusDescription = rcboStatus.Text
};
_Client.LookupClientStatu = clientStatus;
}
//_Client.Modified = EnvironmentClass.ModifiedUserInstance.Id;
_Client.EffectiveDate = rdtEffectiveDate.Value;
if (rdtExpDate.Value != rdtExpDate.MinDate)
{
_Client.ExpirationDate = rdtExpDate.Value;
}
else
{
_Client.ExpirationDate = null;
}
_Client.StartDate = DateTime.Now;
EFEntities.ClientAddress clientAddress = null;
// Iesi.Collections.Generic.ISet<ClientAddress> clientAddress = new HashedSet<ClientAddress>();
foreach (var cAddress in _clientController.client.ClientAddresses)
{
clientAddress = cAddress;
break;
}
if (clientAddress == null)
{
clientAddress = new EFEntities.ClientAddress();
}
clientAddress.Address1 = rtxtClientAdd1.Text;
clientAddress.Address2 = rtxtClientAdd2.Text;
clientAddress.Address3 = rtxtClientAdd3.Text;
// Address type details
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
clientAddress.City = rtxtClientCity.Text;
clientAddress.Client = _Client;
\
_Client.ClientAddresses.Add(clientAddress);
}
Well I did this to the following lines of code to make it work.
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
I changed the above code into this
if (rcboClientAddType.SelectedIndex != -1)
{
//clientAddress.LookupAddressType = new EFEntities.LookupAddressType
// {
// AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
// AddressTypeDescription = rcboClientAddType.Text
// };
clientAddress.AddressTypeID = (Guid)(rcboClientAddType.SelectedValue);
}

Entity Framework overwrites data when 2 two people save data simultaneously

In a function I pass a list of related values and loop over them to save changes in the database. All works well until 2 or more people use the same page to update different entities .Then only that data gets saved for which the changes were made more recently.
public bool UpdatePermanentDifferenceBL(List<PermanentDifferenceProperties> permDiffDetails)
{
try
{
int permanentDifferenceID=0;
int taxEntityID = 0;
int mapid = 0;
//using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
//{
Topaz.DAL.PermanentDifference permDiff;
for (int i = 0; i < permDiffDetails.Count; i++)
{
if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
{
using (var ctx = new TopazDbContainer())
{
try
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
catch (System.Data.OptimisticConcurrencyException ex)
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
ctx.Refresh(System.Data.Objects.RefreshMode.StoreWins, permDiff);
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
}
}
//ctx.ContextOptions.UseLegacyPreserveChangesBehavior = true;
}
//}
//using (UnitOfWork uow = new UnitOfWork())
//{
// for (int i = 0; i < permDiffDetails.Count; i++)
// {
// if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
// {
// Repository.PermanentDifferenceRepository pDiffRepo = new Repository.PermanentDifferenceRepository(uow);
// Topaz.DAL.PermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID);
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// else
// {
// int snapshotID = (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]);
// SnapShotPermanentDifferenceRepository pDiffRepo = new SnapShotPermanentDifferenceRepository(uow);
// SnapShotPermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID,snapshotID);
// permDiff.SnapshotID = snapshotID;
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// }
// uow.SaveChanges();
return true;
}
catch (Exception ex)
{
TopazErrorLogs.AddTopazErrorLogBL(ex, 1, 1);
throw new TopazCustomException(GlobalConstant.errorMessage);
}
}
Any urgent assistance is much appreciated.
The common way to solve this is adding additional column to every table where you want to handle concurrency. This column will have ROWVERSION or TIMESTAMP data type. Once you map tables in EDMX you will get a new computed property of type byte[] and set its Concurrency mode to fixed. This setting will force EF to add additional WHERE condition to every UPDATE or DELETE statement validating that row version is the same as it was when the record was loaded from the database. If the row version is not the same (another thread updated the record) the record from modification is not found and you will get exception.
Database will change the value every time you update the record automatically. You just need to ensure that your entity uses the value which was retrieved when the entity was loaded from the database.
Apologies all the viewstate and to some extent session was the culprit and not EntityFramework.