SitecoreTypeCreationContext throws exception after GlassMapper upgrade - glass-mapper

I'm getting exception:
Inner Exception: Object reference not set to an instance of an object.
at Glass.Mapper.AbstractService.InstantiateObject(AbstractTypeCreationContext abstractTypeCreationContext)
At InstantiateObject the creation context it's not null, the item it's populated.
If I add the typeOf(TItem) then it crashes there at TItem cast, if I comment then it crashes at instatinate.
I tried to remove ConstructorParameter but even on that case it's crashing
The code before upgrade:
var creationContext = new SitecoreTypeCreationContext
{
SitecoreService = sitecoreContext,
RequestedType = typeof(TItem),
ConstructorParameters = new object[0],
Item = item,
InferType = false,
IsLazy = true,
Parameters = new Dictionary<string, object>()
};
var result = sitecoreContext.InstantiateObject(creationContext) as TItem;
The code after upgrade
var creationContext = new SitecoreTypeCreationContext
{
SitecoreService = mvcContext.SitecoreService,
Item = item,
Parameters = new Dictionary<string, object>(),
Options = new GetOptions()
{
//Type = typeof(TItem),
InferType = false,
Lazy = LazyLoading.Enabled,
ConstructorParameters = new List<ConstructorParameter>()
}
};
var result= mvcContext.SitecoreService.InstantiateObject(creationContext) as TItem;
I missed maybe a configuration or RequestedType it's not equal Option.Type?

Related

Calling an Oracle GlInterface SOAP service in .net Core

Error : System.ServiceModel.FaultException`1[Service.ServiceErrorMessage]: JBO-GL:::GL_INVALID_LEDGER: GL-781535You have entered an invalid ledger value. (Fault Detail is equal to Service.ServiceErrorMessage).
only result when I search
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
EndpointAddress endpointAddress = new EndpointAddress(new Uri("https://fa-eosd-dev1-saasfaprod1.fa.ocs.oraclecloud.com:443/fscmService/JournalImportService?WSDL"));
ChannelFactory<JournalImportService> factory = new ChannelFactory<JournalImportService>(basicHttpBinding, endpointAddress);
factory.Credentials.UserName.UserName = "user";
factory.Credentials.UserName.Password = "pass";
JournalImportService serviceProxy = factory.CreateChannel();
((ICommunicationObject)serviceProxy).Open();
var opContext = new OperationContext((IClientChannel)serviceProxy);
var prevOpContext = OperationContext.Current; // Optional if there's no way this might already be set
OperationContext.Current = opContext;
importJournalsRequest importJournalsRequest = new importJournalsRequest();
GlInterfaceTransHeader glInterfaceTransHeader = new GlInterfaceTransHeader();
glInterfaceTransHeader.LedgerId = 300000001958365;
List<GlInterface> glInterface = new List<GlInterface>();
glInterface.Add(glInter);
glInterfaceTransHeader.GlInterface = glInterface.ToArray();
importJournalsRequest.interfaceRows = glInterfaceTransHeader;
try
{
var result = await serviceProxy.importJournalsAsync(importJournalsRequest);
//cleanup
factory.Close();
((ICommunicationObject)serviceProxy).Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// *** ENSURE CLEANUP *** \\
CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
OperationContext.Current = prevOpContext; // Or set to null if you didn't capture the previous context
}
}
glInterfaceTransHeader.AccountingDateSpecified = true;

'Argument expression is not valid' when creating anonymous types dynamically

I'm creating an expression tree builder to return custom anonymous types. I tried it first with discrete types and it works ok, but using TypeBuilder to build types at runtime and pass that type to the expression tree fail with this error
'Argument expression is not valid'
here is the code I use:
this method I use to create the anonymous type
private Type CreateAnonymousType(Dictionary<string, Type> properties)
{
AssemblyName dynamicAssemblyName = new AssemblyName("MyAssembly");
AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAssembly");
TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("ReturnType", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass);
foreach (var p in properties)
{
dynamicAnonymousType.DefineField(p.Key, p.Value, FieldAttributes.Public);
}
return dynamicAnonymousType.CreateType();
}
and here is how I create the expression tree
var cars = new List<Car>();
for (int i = 0; i < 10; i++)
{
cars.Add(new Car { Id = i, Name = "Car " + i, Age = 2010 + i });
}
IQueryable<Car> allCars = cars.AsQueryable();
var properties = new Dictionary<string, Type>
{
{ "Id", typeof(int) },
{ "Name", typeof(string) }
};
ParameterExpression x = Expression.Parameter(typeof(Car), "x");
var listMembers = properties.Select(p => Expression.Property(x, p.Key));
var returnType = CreateAnonymousType(properties);
object destObject = Activator.CreateInstance(returnType);
var listBind = listMembers.Select(p => Expression.Bind(returnType.GetField(p.Member.Name), p));
var result = Expression.New(returnType);
var initExp = Expression.MemberInit(result, listBind.ToArray());
var call = Expression.Call(typeof(Queryable), "Select",
new Type[] {
typeof(Car),
returnType
}
, Expression.Constant(allCars)
, Expression.Lambda(initExp, x));
var qResult = allCars.Provider.CreateQuery<IdName>(call);
foreach (var car in qResult)
{
Console.WriteLine(car.Id + " - " + car.Name);
}
the error happened while CreateQuery method executes
This is because call returns dynamically created ReturnType not IdName thus the exception. Additionally you cannot put such dynamic types like ReturnType as generic type parameters because compiler knows nothing about them so you should use dynamic instead so the type will be resolved at runtime:
var qResult = allCars.Provider.CreateQuery<dynamic>(call);

Must declare the scalar variable "#historyId" exception

I have a working raw Sql command execution
using (var cmd = SqlUtils.CreateSqlCommand(cmdText, sqlConn))
{
cmd.Parameters.Add(new SqlParameter("historyId", SqlDbType.Int)).Value = AAverage.CashFlowRelevantHistoryId;
cmd.Parameters.Add(new SqlParameter("nodeId", SqlDbType.Int)).Value = AAverage.CashNodeId;
cmd.Parameters.Add(new SqlParameter("denomId", SqlDbType.Int)).Value = AAverage.DenominationId;
cmd.Parameters.Add(new SqlParameter("dayId", SqlDbType.Int)).Value = AAverage.CashFlowDayCategoryId;
cmd.Parameters.Add(new SqlParameter("hour", SqlDbType.Int)).Value = AAverage.Hour;
cmd.Parameters.Add(new SqlParameter("type", SqlDbType.Int)).Value = AAverage.ValueType;
cmd.Parameters.Add(new SqlParameter("average", SqlDbType.Real)).Value = AAverage.AverageDerivative;
using (var reader = cmd.ExecuteReader())
if (reader.HasRows && reader.Read())
{
IDataRecord record = (IDataRecord)reader;
AAverage.Id = record.GetInt32ByName("Id");
}
}
but if I've changed it to use SqlQuery method, I get the error in the subject:
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT INTO CashFlowAverageDerivatives");
cmdText.AppendLine(" (CashFlowRelevantHistoryId, CashNodeId, DenominationId, CashFlowDayCategoryId, Hour, ValueType, AverageDerivative)");
cmdText.AppendLine("VALUES");
cmdText.AppendLine(" (#historyId, #nodeId, #denomId, #dayId, #hour, #type, #average)");
cmdText.AppendLine("SELECT Id FROM CashFlowAverageDerivatives WHERE ##ROWCOUNT > 0 and Id = scope_identity()");
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId,
new SqlParameter("nodeId", SqlDbType.Int).Value = AAverage.CashNodeId,
new SqlParameter("denomId", SqlDbType.Int).Value = AAverage.DenominationId,
new SqlParameter("dayId", SqlDbType.Int).Value = AAverage.CashFlowDayCategoryId,
new SqlParameter("hour", SqlDbType.Int).Value = AAverage.Hour,
new SqlParameter("type", SqlDbType.Int).Value = AAverage.ValueType,
new SqlParameter("average", SqlDbType.Real).Value = AAverage.AverageDerivative
).First<int>();
and I have no idea why. If I tried to rename "historyId" in Sql text to something else, exception reports this new name. It seems like parameter definition was missing or misspelled, but list of parameters has been copy&pasted, VS IDE search command finds it, prefix "#" does not matter...
Sure I can live with my working version, but I'm learning EF and it tease me I'm not able to solve this
You were sending the sql parameter as value directly.
When you did this
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId
You actually sent a value of AAverage.CashFlowRelevantHistoryId, not a SqlParameter.
Try changing it with this and see if it works.
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", AAverage.CashFlowRelevantHistoryId),
new SqlParameter("nodeId", AAverage.CashNodeId),
new SqlParameter("denomId", AAverage.DenominationId),
new SqlParameter("dayId", AAverage.CashFlowDayCategoryId),
new SqlParameter("hour", AAverage.Hour),
new SqlParameter("type", AAverage.ValueType),
new SqlParameter("average", AAverage.AverageDerivative)
).First<int>();
Or this
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", SqlDbType.Int) { Value = AAverage.CashFlowRelevantHistoryId },
new SqlParameter("nodeId", SqlDbType.Int) { Value = AAverage.CashNodeId },
new SqlParameter("denomId", SqlDbType.Int) { Value = AAverage.DenominationId },
new SqlParameter("dayId", SqlDbType.Int) { Value = AAverage.CashFlowDayCategoryId },
new SqlParameter("hour", SqlDbType.Int) { Value = AAverage.Hour },
new SqlParameter("type", SqlDbType.Int) { Value = AAverage.ValueType },
new SqlParameter("average", SqlDbType.Real) { Value = AAverage.AverageDerivative }
).First<int>();

How can I create a MetadataWorkspace using metadata loading delegates?

I followed this example Changing schema name on runtime - Entity Framework where I can create a new EntityConnection from a MetaDataWorkspace that I then use to construct a DbContext with a different schema, but I get compiler warnings saying that RegisterItemCollection method is obsolete and to "Construct MetadataWorkspace using constructor that accepts metadata loading delegates."
How do I do that? Here is the code that is working but gives the 3 warnings for the RegsiterItemCollection calls. I'm surprised it works since warning says obsolete not just deprecated.
public static EntityConnection CreateEntityConnection(string schema, string connString, string model)
{
XmlReader[] conceptualReader = new XmlReader[]
{
XmlReader.Create(
Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(model + ".csdl")
)
};
XmlReader[] mappingReader = new XmlReader[]
{
XmlReader.Create(
Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(model + ".msl")
)
};
var storageReader = XmlReader.Create(
Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(model + ".ssdl")
);
//XNamespace storageNS = "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"; // this would not work!!!
XNamespace storageNS = "http://schemas.microsoft.com/ado/2009/11/edm/ssdl";
var storageXml = XElement.Load(storageReader);
foreach (var entitySet in storageXml.Descendants(storageNS + "EntitySet"))
{
var schemaAttribute = entitySet.Attributes("Schema").FirstOrDefault();
if (schemaAttribute != null)
{
schemaAttribute.SetValue(schema);
}
}
storageXml.CreateReader();
StoreItemCollection storageCollection =
new StoreItemCollection(
new XmlReader[] { storageXml.CreateReader() }
);
EdmItemCollection conceptualCollection = new EdmItemCollection(conceptualReader);
StorageMappingItemCollection mappingCollection =
new StorageMappingItemCollection(
conceptualCollection, storageCollection, mappingReader
);
//var workspace2 = new MetadataWorkspace(conceptualCollection, storageCollection, mappingCollection);
var workspace = new MetadataWorkspace();
workspace.RegisterItemCollection(conceptualCollection);
workspace.RegisterItemCollection(storageCollection);
workspace.RegisterItemCollection(mappingCollection);
var connectionData = new EntityConnectionStringBuilder(connString);
var connection = DbProviderFactories
.GetFactory(connectionData.Provider)
.CreateConnection();
connection.ConnectionString = connectionData.ProviderConnectionString;
return new EntityConnection(workspace, connection);
}
I was able to get rid of the 3 warning messages. Basically it wants you to register the collections in the constructor of the MetadataWorkspace.
There are 3 different overloads for MetadataWorkspace, I chose to use the one which requires to to supply a path (array of strings) to the workspace metadata. To do this I saved readers to temp files and reloaded them.
This is working for me without any warnings.
public static EntityConnection CreateEntityConnection(string schema, string connString, string model) {
var conceptualReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".csdl"));
var mappingReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".msl"));
var storageReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".ssdl"));
XNamespace storageNS = "http://schemas.microsoft.com/ado/2009/11/edm/ssdl";
var storageXml = XElement.Load(storageReader);
var conceptualXml = XElement.Load(conceptualReader);
var mappingXml = XElement.Load(mappingReader);
foreach (var entitySet in storageXml.Descendants(storageNS + "EntitySet")) {
var schemaAttribute = entitySet.Attributes("Schema").FirstOrDefault();
if (schemaAttribute != null) {
schemaAttribute.SetValue(schema);
}
}
storageXml.Save("temp.ssdl");
conceptualXml.Save("temp.csdl");
mappingXml.Save("temp.msl");
MetadataWorkspace workspace = new MetadataWorkspace(new List<String>(){
#"temp.csdl",
#"temp.ssdl",
#"temp.msl"
}
, new List<Assembly>());
var connectionData = new EntityConnectionStringBuilder(connString);
var connection = DbProviderFactories.GetFactory(connectionData.Provider).CreateConnection();
connection.ConnectionString = connectionData.ProviderConnectionString;
return new EntityConnection(workspace, connection);
}
Not wanting to create temp files which slows the process down, I found an alternate answer to this is fairly simple. I replaced these lines of code -
//var workspace2 = new MetadataWorkspace(conceptualCollection, storageCollection, mappingCollection);
var workspace = new MetadataWorkspace();
workspace.RegisterItemCollection(conceptualCollection);
workspace.RegisterItemCollection(storageCollection);
workspace.RegisterItemCollection(mappingCollection);
with this one line of code -
var workspace = new MetadataWorkspace(() => conceptualCollection, () => storageCollection, () => mappingCollection);
and that works fine.

Create a store from Code Behind and filter its content and bind it to Combobox Ext.Net 2.2

I am creating combobox in a component Column in a GridPanel from codebehind. There is requirement to create a store and filter its content according to some condition and bind it to the created combobox. Store is getting bind to combo but filter is not working. Please help me to get the proper solution for this. My code snippet is given below.
List<object> storeDataProductClass= new List<object>();
storeDataProductClass.Add(new { text = "Class0", value = "Class0", productIndex = 0});
storeDataProductClass.Add(new { text = "Class1", value = "Class1", productIndex = 1});
storeDataProductClass.Add(new { text = "Class2", value = "Class2", productIndex = 2});
storeDataProductClass.Add(new { text = "Class3", value = "Class3", productIndex = 3});
storeDataProductClass.Add(new { text = "Class4", value = "Class4", productIndex = 4});
Ext.Net.ComboBox cmbClass = new ComboBox();
cmbClass.ID = "cmbClass_" + i;
Model classModel = new Model();
classModel.Fields.Add(new ModelField("text", ModelFieldType.String));
classModel.Fields.Add(new ModelField("value", ModelFieldType.String));
classModel.Fields.Add(new ModelField("productIndex", ModelFieldType.Int));
Ext.Net.Store storeClass = new Ext.Net.Store();
storeClass.ID = "storeClass_" + i;
storeClass.AutoDataBind = true;
storeClass.Model.Add(classModel);
storeClass.DataSource = storeDataProductClass;
storeClass.DataBind();
storeClass.Filter("productIndex", i.ToString());
cmbClass.Store.Add(storeClass);
cmbClass.DisplayField = "text";
cmbClass.ValueField = "value";
compColumn.Component.Add(cmbClass);

Resources