private async Task <ExecValue> createObject(ExecutionContext ctx, bool onHeap, // false -> create regular value IEntityInstance typename, FunctionDefinition targetFunc, IEnumerable <IEntityInstance> templateArguments, params ObjectData[] arguments) { IEntityInstance outer_typename = typename; if (onHeap) { outer_typename = ctx.Env.Reference(typename, TypeMutability.None, viaPointer: true); } ObjectData this_object = await allocObjectAsync(ctx, typename, outer_typename, null).ConfigureAwait(false); // it is local variable so we need to inc ref count bool incremented = ctx.Heap.TryInc(ctx, this_object, RefCountIncReason.StoringLocalPointer, ""); ExecValue ret = await callNonVariadicFunctionDirectly(ctx, targetFunc, templateArguments, this_object, arguments).ConfigureAwait(false); if (incremented) { ctx.Heap.TryRelease(ctx, this_object, this_object, false, RefCountDecReason.DroppingLocalPointer, ""); } if (ret.IsThrow) { return(ret); } else { return(ExecValue.CreateExpression(this_object)); } }
public static bool LowestCommonAncestor(ComputationContext ctx, IEntityInstance anyTypeA, IEntityInstance anyTypeB, out IEntityInstance result) { bool a_dereferenced, b_dereferenced; bool via_pointer = false; TypeMutability mutability_override = TypeMutability.None; { a_dereferenced = ctx.Env.DereferencedOnce(anyTypeA, out IEntityInstance deref_a, out bool a_via_pointer); b_dereferenced = ctx.Env.DereferencedOnce(anyTypeA, out IEntityInstance deref_b, out bool b_via_pointer); if (a_dereferenced && b_dereferenced) { TypeMutability mutability_a = anyTypeA.SurfaceMutabilityOfType(ctx); TypeMutability mutability_b = anyTypeB.SurfaceMutabilityOfType(ctx); if (mutability_a == mutability_b) { mutability_override = mutability_a; } else { mutability_override = TypeMutability.ReadOnly; } anyTypeA = deref_a; anyTypeB = deref_b; via_pointer = a_via_pointer && b_via_pointer; } } var type_a = anyTypeA as EntityInstance; var type_b = anyTypeB as EntityInstance; if (type_a == null) { result = type_b; return(type_b != null); } else if (type_b == null) { result = type_a; return(type_a != null); } type_a.Evaluated(ctx); type_b.Evaluated(ctx); if (type_a.IsJoker) { result = type_b; return(true); } else if (type_b.IsJoker) { result = type_a; return(true); } HashSet <EntityInstance> set_a = type_a.Inheritance(ctx).OrderedAncestorsIncludingObject.Concat(type_a) .ToHashSet(EntityInstance.CoreComparer); result = selectFromLowestCommonAncestorPool(ctx, type_b, set_a); if (result != null && a_dereferenced && b_dereferenced) { // result = ctx.Env.Reference(result, TypeMutability.None, null, via_pointer); result = ctx.Env.Reference(result, mutability_override, via_pointer); } return(result != null); }
private static IEntityInstance GetEntityInstance(SPBusinessDataField dataField, string entityId, SPSite site, SPListItem item, string finderMethodName) { IEntityInstance entInstance = null; try { IEntity entity = GetEntity(site, dataField); ILobSystemInstance lobSystemInstance = entity.GetLobSystem().GetLobSystemInstances()[0].Value; // Get methods collection foreach (KeyValuePair <string, IMethod> method in entity.GetMethods()) { // Get current method's instance IMethodInstance methodInstance = method.Value.GetMethodInstances()[method.Key]; // Execute specific finder method if (methodInstance.MethodInstanceType == MethodInstanceType.SpecificFinder && methodInstance.Name == finderMethodName) { Identity id = null; if (EntityInstanceIdEncoder.IsEncodedIdentifier(entityId)) { object[] oIDList = EntityInstanceIdEncoder.DecodeEntityInstanceId(entityId); id = new Identity(oIDList[0]); // Execute specific finder method and get the entity instance entInstance = entity.FindSpecific(id, methodInstance.Name, entity.GetLobSystem().GetLobSystemInstances()[0].Value); item[dataField.RelatedField] = entityId.ToString(); } else { object oID = GetTypedIDValue(entityId, entity); id = new Identity(oID); string encodedIdentifier = EntityInstanceIdEncoder.EncodeEntityInstanceId(new object[] { oID }); // Execute specific finder method and get the entity instance entInstance = entity.FindSpecific(id, methodInstance.Name, entity.GetLobSystem().GetLobSystemInstances()[0].Value); item[dataField.RelatedField] = encodedIdentifier; } } } } catch (ObjectNotFoundException notFoundException) { LogError("GetEntityInstance errored with message " + notFoundException.Message + ". Adding item to Guidewire."); Console.WriteLine("GetEntityInstance errored with message " + notFoundException.Message + ". Adding item to Guidewire."); bool addDocumentToGuidewire = CallGuidewire(item, GuidewireOperationType.New); string outMessage = ""; if (addDocumentToGuidewire) { outMessage = string.Format("Item with ID {0} added to Guidewire", item.ID); } else { outMessage = string.Format("Item with ID {0} could not be added to Guidewire", item.ID); if (Settings.Default.DeleteFailures) { try { // Recycle the item if it can't be added to guidewire and it's older than 30 days if (DateTime.Now.AddDays(-30) > (DateTime)item[SPBuiltInFieldId.Modified]) { item.Recycle(); } } catch { // Swallow this error. The item doesn't exist in Guidewire and can't be deleted in SharePoint. It has problems } } LogError(outMessage); } Console.WriteLine(outMessage); } catch (Exception ex) { // Swallow this error LogError("GetEntityInstance errored with message " + ex.Message); Console.WriteLine("GetEntityInstance errored with message " + ex.Message); } return(entInstance); }
internal static Task <ObjectData> CreateTypeAsync(ExecutionContext ctx, IEntityInstance typeInstance) { TypeDefinition type_def = typeInstance.Cast <EntityInstance>().TargetType; return(constructorAsync(ctx, type_def.Modifier.HasNative, null, typeInstance, isStatic: true)); }
public static bool IsDerivedOf(ComputationContext ctx, FunctionDefinition derivedFunc, FunctionDefinition baseFunc, EntityInstance baseTemplate) { if (derivedFunc.IsPropertyAccessor(out Property derived_prop)) { if (baseFunc.IsPropertyAccessor(out Property base_prop)) { // properties have to much and name (kind) of the accessor if (!EntityNameArityComparer.Instance.Equals(derived_prop.Name, base_prop.Name) || !EntityNameArityComparer.Instance.Equals(derivedFunc.Name, baseFunc.Name)) { return(false); } } // property-getters can override regular methods else if (derived_prop.Getter != derivedFunc || !EntityNameArityComparer.Instance.Equals(derived_prop.Name, baseFunc.Name)) { return(false); } } // todo: we have to check constraints as well else if (!EntityNameArityComparer.Instance.Equals(derivedFunc.Name, baseFunc.Name)) { return(false); } foreach (Tuple <TemplateParameter, TemplateParameter> param_pair in derivedFunc.Name.Parameters .SyncZip(baseFunc.Name.Parameters)) { if (!TemplateParameterExtension.IsSame(param_pair.Item1, param_pair.Item2, baseTemplate)) { return(false); } } { IEntityInstance base_result_type = baseFunc.ResultTypeName.Evaluation.Components.TranslateThrough(baseTemplate); TypeMatch match = derivedFunc.ResultTypeName.Evaluation.Components.MatchesTarget(ctx, base_result_type, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)); if (match != TypeMatch.Same && match != TypeMatch.Substitute) { return(false); } } if (derivedFunc.Parameters.Count != baseFunc.Parameters.Count) { return(false); } foreach (Tuple <FunctionParameter, FunctionParameter> param_pair in derivedFunc.Parameters.SyncZip(baseFunc.Parameters)) { if (!FunctionParameterExtension.IsDerivedOf(ctx, param_pair.Item1, param_pair.Item2, baseTemplate)) { return(false); } } return(true); }
public static IEntityInstance Rebuild(this IEntityInstance instance, ComputationContext ctx, TypeMutability mutability, bool deep = true) { return(instance.Map(elem => elem.Rebuild(ctx, mutability, deep))); }
private async Task <ExecValue> executeNativeFileFunctionAsync(ExecutionContext ctx, FunctionDefinition func) { if (func == ctx.Env.FileReadLines) { ObjectData filepath_obj = ctx.GetArgument(func, NameFactory.FileFilePathParameter); if (!filepath_obj.TryDereferenceAnyOnce(ctx.Env, out ObjectData filepath_val)) { throw new Exception($"{ExceptionCode.SourceInfo()}"); } string filepath = filepath_val.PlainValue.Cast <string>(); string[] lines = null; try { // todo: change it to ReadLines once we have deferred execution lines = System.IO.File.ReadAllLines(filepath); } #pragma warning disable 0168 catch (Exception ex) // we would use it when debugging #pragma warning restore 0168 { } Option <ObjectData> opt_lines_obj; ObjectData chunk_ptr; if (lines == null) { chunk_ptr = null; opt_lines_obj = new Option <ObjectData>(); } else { IEntityInstance string_ptr_instance; { IEntityInstance ptr_iterable_instance = func.ResultTypeName.Evaluation.Components.Cast <EntityInstance>().TemplateArguments.Single(); IEntityInstance iterable_str_ptr_instance = ptr_iterable_instance.Cast <EntityInstance>().TemplateArguments.Single(); string_ptr_instance = iterable_str_ptr_instance.Cast <EntityInstance>().TemplateArguments.Single(); } var lines_obj = new ObjectData[lines.Length]; int i = 0; foreach (string s in lines) { ObjectData s_ptr = await createStringAsync(ctx, s).ConfigureAwait(false); if (!ctx.Heap.TryInc(ctx, s_ptr, RefCountIncReason.FileLine, $"{filepath}")) { throw new Exception($"{ExceptionCode.SourceInfo()}"); } lines_obj[i] = s_ptr; ++i; } chunk_ptr = await createChunkOnHeap(ctx, string_ptr_instance, lines_obj).ConfigureAwait(false); opt_lines_obj = new Option <ObjectData>(chunk_ptr); } ExecValue opt_exec = await createOption(ctx, func.ResultTypeName.Evaluation.Components, opt_lines_obj).ConfigureAwait(false); if (chunk_ptr != null) { ctx.Heap.TryRelease(ctx, chunk_ptr, null, false, RefCountDecReason.DroppingLocalPointer, ""); } if (opt_exec.IsThrow) { return(opt_exec); } ObjectData result = opt_exec.ExprValue; return(ExecValue.CreateReturn(result)); } else if (func == ctx.Env.FileExists) { ObjectData filepath_obj = ctx.GetArgument(func, NameFactory.FileFilePathParameter); if (!filepath_obj.TryDereferenceAnyOnce(ctx.Env, out ObjectData filepath_val)) { throw new Exception($"{ExceptionCode.SourceInfo()}"); } string filepath = filepath_val.PlainValue.Cast <string>(); bool exists = System.IO.File.Exists(filepath); ExecValue result = ExecValue.CreateReturn(await ObjectData.CreateInstanceAsync(ctx, func.ResultTypeName.Evaluation.Components, exists).ConfigureAwait(false)); return(result); } else { throw new NotImplementedException($"{ExceptionCode.SourceInfo()}"); } }
public IEnumerable<ILayer> GetLayersForEntity(IEntityInstance instance) { return from layer in Layers where instance.IsPartOfLayer(layer) select layer; }
/// <summary> /// /// </summary> public Uri GetDisplayUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance) { throw new NotImplementedException(); }
// // This region contains methods for generating access and display URLs for child items that are enumerated from // BCS metadata objects that we don't expect to crawl (e.g. LobSystem, LobSystemInstance, Entity). As a result, // they all throw NotImplementedException. If you were to change the crawl strategy of this connector to crawl // different BCS metadata objects you would need to implement the GetAccessUri and GetDisplayUri for those // metadata object types. // #region Unused URL translation methods /// <summary> /// Generate the access URL for an EntityInstance. This method is called when the instance is being enumerated /// from the finder method of an entity (i.e., the RootFinder). /// </summary> public Uri GetAccessUri(IEntityInstance entityInstance) { throw new NotImplementedException(); }
// // This region contains methods that generate access URL and display URL for EntityInstance data objects that // are enumerated using association navigators. This is the only type of enumeration that the MyFileConnector // sample does. // #region URL translation methods we need /// <summary> /// Generate the access URL for an entity instance. This method is used when the instance is being enumerated /// by an association navigator (and will therefore have a "parent" entity instance). /// </summary> /// <param name="entityInstance"> /// Supplies the entity instance. /// </param> /// <param name="parentEntityInstance"> /// Supplies the entity instance that contained the entity instance in whose access URL we're interested. /// </param> /// <returns> /// Returns a Uri containing the access Url. /// </returns> public Uri GetAccessUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance) { // // The identifier of an Entity instance is defined in the model file at the Entity level: // // <Entity Name="MyFolder" Namespace="MyFileConnector" Version="1.0.0.1"> // <Identifiers> // <Identifier Name="PathID" TypeName="System.String" /> // </Identifiers> // ... // // And every method defined for that Entity must mark the field or fields in the return type descriptor that // contain the identifier(s). In the MyFileConnector example, the identifier is just the path to the file, // which is a field in the return type descriptor of every method defined in the model file for the MyFolder // Entity. Here is an example of how it's marked as an 'Identifier' in the return type descriptor of the // GetSubFolders method: // // <TypeDescriptor // Name="Path" // TypeName="System.String" // IdentifierEntityNamespace="MyFileConnector" // IdentifierEntityName="MyFolder" // IdentifierName="PathID" /> // // // Sanity check that we have an Entity name that we expect. // if (!entityInstance.Entity.Name.Equals("MyFolder", StringComparison.OrdinalIgnoreCase) && !entityInstance.Entity.Name.Equals("MyFile", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(String.Format( "Invalid Entity type: {0}", entityInstance.Entity.Name)); } // // For both the 'MyFile' and 'MyFolder' Entities, the 'Identifier' is a UNC path to the file or folder. Our // access URL format is the UNC path in URL format, with the first segment (either 'MyFolder' or 'MyFile') // to indicate entity type. So first, read the path from the 'Identifiers'. There's only one Identifier // defined in our model file so we can just access the first element of the Identifier values array. Had // there been more than one, this array would be in the order in which the identifiers are defined in the // 'Identifiers' node of an Entity. // object[] ids = entityInstance.GetIdentity().GetIdentifierValues(); String path = ids[0].ToString(); // // Now generate a Uri from the path, and insert the appropriate entity type as the first segment. // Uri pathUri = new Uri(path); StringBuilder pathWithEntityType = new StringBuilder(); pathWithEntityType.AppendFormat("myfile://{0}/{1}", pathUri.Host, entityInstance.Entity.Name); foreach (String segment in pathUri.Segments) { pathWithEntityType.Append(segment); } this.accessUri = new Uri(pathWithEntityType.ToString()); // // (Side note and general comment on this class: It's really convenient that our external repository's BCS // Identifier happens to be a UNC path, which is something that's easily translated into a URL. However, // your BCS Identifier(s) can be anything at all. You have to decide on the mapping from that set of // Identifiers (which is what BCS understands) to an access URL (which is what the SharePoint Search // gatherer works with) and implement it in this class.) // return(this.accessUri); }
/// <summary> /// Generate the access URL for an entity instance. This method is used when the instance is being enumerated /// by an association navigator (and will therefore have a "parent" entity instance). /// </summary> /// <param name="entityInstance"> /// Supplies the entity instance. /// </param> /// <param name="parentEntityInstance"> /// Supplies the entity instance that contained the entity instance in whose access URL we're interested. /// </param> /// <returns> /// Returns a Uri containing the access Url. /// </returns> public Uri GetAccessUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance) { // // The identifier of an Entity instance is defined in the model file at the Entity level: // // <Entity Name="MyFolder" Namespace="MyFileConnector" Version="1.0.0.1"> // <Identifiers> // <Identifier Name="PathID" TypeName="System.String" /> // </Identifiers> // ... // // And every method defined for that Entity must mark the field or fields in the return type descriptor that // contain the identifier(s). In the MyFileConnector example, the identifier is just the path to the file, // which is a field in the return type descriptor of every method defined in the model file for the MyFolder // Entity. Here is an example of how it's marked as an 'Identifier' in the return type descriptor of the // GetSubFolders method: // // <TypeDescriptor // Name="Path" // TypeName="System.String" // IdentifierEntityNamespace="MyFileConnector" // IdentifierEntityName="MyFolder" // IdentifierName="PathID" /> // // // Sanity check that we have an Entity name that we expect. // if (!entityInstance.Entity.Name.Equals("MyFolder", StringComparison.OrdinalIgnoreCase) && !entityInstance.Entity.Name.Equals("MyFile", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(String.Format( "Invalid Entity type: {0}", entityInstance.Entity.Name)); } // // For both the 'MyFile' and 'MyFolder' Entities, the 'Identifier' is a UNC path to the file or folder. Our // access URL format is the UNC path in URL format, with the first segment (either 'MyFolder' or 'MyFile') // to indicate entity type. So first, read the path from the 'Identifiers'. There's only one Identifier // defined in our model file so we can just access the first element of the Identifier values array. Had // there been more than one, this array would be in the order in which the identifiers are defined in the // 'Identifiers' node of an Entity. // object[] ids = entityInstance.GetIdentity().GetIdentifierValues(); String path = ids[0].ToString(); // // Now generate a Uri from the path, and insert the appropriate entity type as the first segment. // Uri pathUri = new Uri(path); StringBuilder pathWithEntityType = new StringBuilder(); pathWithEntityType.AppendFormat("myfile://{0}/{1}", pathUri.Host, entityInstance.Entity.Name); foreach (String segment in pathUri.Segments) { pathWithEntityType.Append(segment); } this.accessUri = new Uri(pathWithEntityType.ToString()); // // (Side note and general comment on this class: It's really convenient that our external repository's BCS // Identifier happens to be a UNC path, which is something that's easily translated into a URL. However, // your BCS Identifier(s) can be anything at all. You have to decide on the mapping from that set of // Identifiers (which is what BCS understands) to an access URL (which is what the SharePoint Search // gatherer works with) and implement it in this class.) // return this.accessUri; }
/// <summary> /// Generate a display URL from an EntityInstance. /// </summary> /// <param name="entityInstance"> /// Supplies the EntityInstance data object. /// </param> /// <param name="computedDisplayUri"> /// Supplies the display URL provided by the repository if there was one. /// </param> /// <returns> /// Returns a Uri containing the display URL. /// </returns> public Uri GetDisplayUri(IEntityInstance entityInstance, string computedDisplayUri) { // // The only time we expect to receive a computed display URL is when the shim itself returns a String field // in the return type descriptor containing a display URL. In order to cause the connector framework to use // this String field, the 'DisplayUriField' property must be defined on the method instance and the value of // the 'DisplayUriField' property must be the name of the String field in the return type descriptor that // contains the display URL. // // However, in this case our shim does not return a display URL, so we always expect this to be empty. // if (!String.IsNullOrEmpty(computedDisplayUri)) { throw new ArgumentException(String.Format( "Unexpectedly received a computed display URL: {0}", computedDisplayUri)); } // // In this case, the 'Path' identifier is simply the UNC path to the file or folder. So return the URL // representation of that. // object[] ids = entityInstance.GetIdentity().GetIdentifierValues(); String path = ids[0].ToString(); return new Uri(path); }
/// <summary> /// Generate the access URL for an EntityInstance. This method is called when the instance is being enumerated /// from the finder method of an entity (i.e., the RootFinder). /// </summary> public Uri GetAccessUri(IEntityInstance entityInstance) { throw new NotImplementedException(); }
public static bool InterchangeableTypes(ComputationContext ctx, IEntityInstance eval1, IEntityInstance eval2) { ctx.Env.Dereference(eval1, out eval1); ctx.Env.Dereference(eval2, out eval2); // if both types are sealed they are interchangeable only if they are the same // if one is not sealed then it has to be possible to subsitute them // otherwise they are completely alien and checking is-type/is-same does not make sense if (!interchangeableTypesTo(ctx, eval1, eval2)) { return(false); } bool result = interchangeableTypesTo(ctx, eval2, eval1); return(result); }
public static TypeMatch Matches(ComputationContext ctx, EntityInstance input, EntityInstance target, TypeMatching matching) { if (input.IsJoker || target.IsJoker) { return(TypeMatch.Same); } if (!target.Target.IsType() || !input.Target.IsType()) { return(TypeMatch.No); } if (input.Lifetime.IsAttached) { matching = matching.WithLifetimeCheck(true, input.Lifetime, target.Lifetime); } { IEnumerable <FunctionDefinition> in_conv = target.TargetType.ImplicitInConverters().StoreReadOnly(); bool conv_slicing_sub = input.TargetType.AllowSlicedSubstitution; foreach (FunctionDefinition func in in_conv) { IEntityInstance conv_type = func.Parameters.Single().TypeName.Evaluated(ctx, EvaluationCall.AdHocCrossJump).TranslateThrough(target); if (target.IsIdentical(conv_type)) // preventing circular conversion check { continue; } TypeMatch m = input.MatchesTarget(ctx, conv_type, matching.WithSlicing(conv_slicing_sub)); if (m == TypeMatch.Same || m == TypeMatch.Substitute) { return(TypeMatch.InConversion); } } } if (ctx.Env.IsReferenceOfType(target)) { if (ctx.Env.IsPointerLikeOfType(input)) { // note, that we could have reference to pointer in case of the target, we have to unpack both // to the level of the value types int target_dereferences = ctx.Env.Dereference(target, out IEntityInstance inner_target_type); int input_dereferences = ctx.Env.Dereference(input, out IEntityInstance inner_input_type); TypeMatch m = inner_input_type.MatchesTarget(ctx, inner_target_type, matching .WithSlicing(true) .WithMutabilityCheckRequest(true) .WithLifetimeCheck(true, ctx.Env.IsReferenceOfType(input) ? input.Lifetime : Lifetime.Timeless, target.Lifetime)); if (target_dereferences > input_dereferences && !m.IsMismatch()) { m |= TypeMatch.ImplicitReference; } return(m); } else { ctx.Env.Dereferenced(target, out IEntityInstance inner_target_type); TypeMatch m = input.MatchesTarget(ctx, inner_target_type, matching .WithSlicing(true) .WithMutabilityCheckRequest(true) .WithLifetimeCheck(true, input.Lifetime, target.Lifetime)); if (m == TypeMatch.Same || m == TypeMatch.Substitute) { return(m | TypeMatch.ImplicitReference); } else { return(m); } } } // automatic dereferencing pointers else if (ctx.Env.IsPointerLikeOfType(input)) { int input_dereferences; { input_dereferences = ctx.Env.Dereference(input, out IEntityInstance dummy); } // we check if we have more refs/ptrs in input than in target if (input_dereferences > (ctx.Env.IsPointerOfType(target) ? 1 : 0)) { ctx.Env.DereferencedOnce(input, out IEntityInstance inner_input_type, out bool dummy); TypeMatch m = inner_input_type.MatchesTarget(ctx, target, matching.WithSlicing(true)); if (m.Passed) { return(m | TypeMatch.AutoDereference); } } else { matching = matching.WithMutabilityCheckRequest(true) ; } } if (ctx.Env.IsReferenceOfType(input) && ctx.Env.IsPointerOfType(target)) { // note, that we could have reference to pointer in case of the target, we have to unpack both // to the level of the value types ctx.Env.DereferencedOnce(target, out IEntityInstance inner_target_type, out bool dummy1); ctx.Env.DereferencedOnce(input, out IEntityInstance inner_input_type, out bool dummy2); TypeMatch m = inner_input_type.MatchesTarget(ctx, inner_target_type, matching .WithSlicing(true) .WithMutabilityCheckRequest(true) .WithLifetimeCheck(true, input.Lifetime, Lifetime.Timeless)); if (!m.IsMismatch()) { m |= TypeMatch.Attachment; } return(m); } { IEnumerable <FunctionDefinition> out_conv = input.TargetType.ImplicitOutConverters().StoreReadOnly(); bool conv_slicing_sub = input.TargetType.AllowSlicedSubstitution; foreach (FunctionDefinition func in out_conv) { IEntityInstance conv_type = func.ResultTypeName.Evaluated(ctx, EvaluationCall.AdHocCrossJump).TranslateThrough(input); //if (target == conv_type) // preventing circular conversion check // continue; TypeMatch m = conv_type.MatchesTarget(ctx, target, matching.WithSlicing(conv_slicing_sub)); if (m == TypeMatch.Same || m == TypeMatch.Substitute) { return(TypeMatch.OutConversion); } } } if (target.TargetType.AllowSlicedSubstitution) { matching.AllowSlicing = true; } TypeMatch match = TypeMatch.No; TypeMutability input_mutability = input.MutabilityOfType(ctx); if (matching.AllowSlicing) { IEnumerable <TypeAncestor> input_family = new[] { new TypeAncestor(input, 0) } .Concat(input.Inheritance(ctx).OrderedTypeAncestorsIncludingObject // enum substitution works in reverse so we have to exclude these from here .Where(it => !it.AncestorInstance.TargetType.Modifier.HasEnum)); foreach (TypeAncestor inherited_input in input_family) { if (matchTypes(ctx, input_mutability, input.Lifetime, inherited_input.AncestorInstance, target, matching, inherited_input.Distance, out TypeMatch m)) { return(m); } else if (m != TypeMatch.No) // getting more specific rejection than just bare one { match = m; } } } // when slicing is disabled we can compare try to substitute only the same type else if (input.Target == target.Target) { if (matchTypes(ctx, input_mutability, input.Lifetime, input, target, matching, distance: 0, match: out match)) { if (match != TypeMatch.Same && !match.IsMismatch()) { throw new Exception($"Internal exception {match}"); } return(match); } } if (input.TargetType.Modifier.HasEnum) { // another option for enum-"inheritance" would be dropping it altogether, and copying all the values from the // base enum. Adding conversion constructor from base to child type will suffice and allow to get rid // of those enum-inheritance matching // since we compare only enums here we allow slicing (because it is not slicing, just passing single int) match = inversedTypeMatching(ctx, input, new[] { new TypeAncestor(target, 0) } .Concat(target.Inheritance(ctx).OrderedTypeAncestorsIncludingObject) .Where(it => it.AncestorInstance.TargetType.Modifier.HasEnum), matching.WithSlicing(true)); if (!match.IsMismatch()) { return(match); } } if (target.TargetsTemplateParameter) { // template parameter can have reversed inheritance defined via base-of constraints // todo: at this it should be already evaluated, so constraints should be surfables IEnumerable <IEntityInstance> base_of = target.TemplateParameterTarget.Constraint.BaseOfNames.Select(it => it.Evaluated(ctx, EvaluationCall.AdHocCrossJump)); match = inversedTypeMatching(ctx, input, new[] { new TypeAncestor(target, 0) } .Concat(base_of.Select(it => new TypeAncestor(it.Cast <EntityInstance>(), 1))), matching); if (!match.IsMismatch()) { return(match); } } return(match); }
private static async Task <ObjectData> createChunkOnHeap(ExecutionContext ctx, IEntityInstance elementType, IEnumerable <ObjectData> elements) { ObjectData chunk_obj = await createChunk(ctx, ctx.Env.ChunkType.GetInstance(TypeMutability.None, TemplateTranslation.Create(ctx.Env.ChunkType.InstanceOf, elementType), Lifetime.Timeless), elements.ToArray()).ConfigureAwait(false); ObjectData chunk_ptr = await allocateOnHeapAsync(ctx, ctx.Env.Reference(chunk_obj.RunTimeTypeInstance, TypeMutability.None, viaPointer: true), chunk_obj).ConfigureAwait(false); if (!ctx.Heap.TryInc(ctx, chunk_ptr, RefCountIncReason.IncChunkOnHeap, "")) { throw new Exception($"{ExceptionCode.SourceInfo()}"); } return(chunk_ptr); }
private async Task <ExecValue> executeNativeChunkFunctionAsync(ExecutionContext ctx, FunctionDefinition func, ObjectData this_value) { if (func == ctx.Env.ChunkSizeConstructor) { IEntityInstance elem_type = this_value.RunTimeTypeInstance.TemplateArguments.Single(); ObjectData size_obj = ctx.FunctionArguments.Single(); var size = size_obj.NativeNat64; ObjectData[] chunk = (await Task.WhenAll(Enumerable.Range(0, (int)size).Select(_ => ObjectData.CreateEmptyAsync(ctx, elem_type))).ConfigureAwait(false)).ToArray(); this_value.Assign(await createChunk(ctx, this_value.RunTimeTypeInstance, chunk).ConfigureAwait(false)); return(ExecValue.CreateReturn(null)); } else if (func == ctx.Env.ChunkResizeConstructor) { IEntityInstance elem_type = this_value.RunTimeTypeInstance.TemplateArguments.Single(); ObjectData size_obj = ctx.FunctionArguments[0]; var size = size_obj.NativeNat64; ObjectData source_obj = ctx.FunctionArguments[1]; if (!source_obj.TryDereferenceAnyOnce(ctx.Env, out ObjectData val_obj)) { throw new Exception($"{ExceptionCode.SourceInfo()}"); } Chunk source = val_obj.PlainValue.Cast <Chunk>(); ObjectData[] chunk = new ObjectData[size]; var copy_size = Math.Min(size, source.Count); for (UInt64 i = 0; i != copy_size; ++i) { chunk[i] = source[i]; ctx.Heap.TryInc(ctx, source[i], RefCountIncReason.CopyingChunkElem, ""); } for (var i = copy_size; i < size; ++i) { chunk[i] = await ObjectData.CreateEmptyAsync(ctx, elem_type).ConfigureAwait(false); } this_value.Assign(await createChunk(ctx, this_value.RunTimeTypeInstance, chunk).ConfigureAwait(false)); return(ExecValue.CreateReturn(null)); } else if (func == ctx.Env.ChunkAtSet) { ObjectData idx_obj = ctx.GetArgument(func, NameFactory.IndexIndexerParameter); var idx = idx_obj.NativeNat64; Chunk chunk = this_value.PlainValue.Cast <Chunk>(); ctx.Heap.TryRelease(ctx, chunk[idx], passingOutObject: null, isPassingOut: false, reason: RefCountDecReason.ReplacingChunkElem, comment: ""); ObjectData arg_ref_object = ctx.GetArgument(func, NameFactory.PropertySetterValueParameter); // indexer takes reference to element if (!arg_ref_object.TryDereferenceAnyOnce(ctx.Env, out ObjectData arg_val)) { throw new Exception($"{ExceptionCode.SourceInfo()}"); } if (!ctx.Heap.TryIncPointer(ctx, arg_val, RefCountIncReason.SettingChunkElem, "")) { arg_val = arg_val.Copy(); } chunk[idx] = arg_val; return(ExecValue.CreateReturn(null)); } else if (func == ctx.Env.ChunkAtGet) { ObjectData idx_obj = ctx.GetArgument(func, NameFactory.IndexIndexerParameter); var idx = idx_obj.NativeNat64; Chunk chunk = this_value.PlainValue.Cast <Chunk>(); ObjectData obj_value = chunk[idx]; // indexer returns reference to an element value ObjectData obj_ref = await obj_value.ReferenceAsync(ctx).ConfigureAwait(false); return(ExecValue.CreateReturn(obj_ref)); } else if (func == ctx.Env.ChunkCount) { Chunk chunk = this_value.PlainValue.Cast <Chunk>(); ObjectData result = await ObjectData.CreateInstanceAsync(ctx, func.ResultTypeName.Evaluation.Components, chunk.Count).ConfigureAwait(false); return(ExecValue.CreateReturn(result)); } else { throw new NotImplementedException($"{ExceptionCode.SourceInfo()}"); } }
public Uri GetAccessUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance) { return(this.GetAccessUri(entityInstance)); }
protected void FindCustomerByID_Click( object sender, EventArgs e) { // Make sure we have values for the entity namespace and name. if (!EntityValuesAreSet) { DisplaySetPropertyValuePrompt(true); return; } else { DisplaySetPropertyValuePrompt(false); } // Do simple validation of the customer ID. Make sure it is // an integer. int customerID = -1; if (!ValidateCustomerID(CustomerID.Text, ref customerID)) { ClearFields(false); StatusLabel.ForeColor = Color.Red; StatusLabel.Text = "Please enter an integer for the Customer ID value."; return; } try { using (new Microsoft.SharePoint.SPServiceContextScope( SPServiceContext.GetContext(SPContext.Current.Site))) { // Get the BDC service and metadata catalog. BdcService service = SPFarm.Local.Services.GetValue <BdcService>(String.Empty); IMetadataCatalog catalog = service.GetDatabaseBackedMetadataCatalog( SPServiceContext.Current); // Get the entity using the specified name and namespace. IEntity entity = catalog.GetEntity(EntityNamespace, EntityName); ILobSystemInstance LobSysteminstance = entity.GetLobSystem().GetLobSystemInstances()[0].Value; // Create an Identity based on the specified Customer ID. Identity identity = new Identity(customerID); // Get a method instance for the SpecificFinder method. IMethodInstance method = entity.GetMethodInstance("GetCustomerById", MethodInstanceType.SpecificFinder); // Execute the Specific Finder method to return the // customer data. IEntityInstance iei = entity.FindSpecific(identity, LobSysteminstance); // Display the data for the returned customer in the UI. Title.Text = iei["Title"] != null ? iei["Title"].ToString() : string.Empty; FirstName.Text = iei["FirstName"] != null ? iei["FirstName"].ToString() : string.Empty; MiddleName.Text = iei["MiddleName"] != null ? iei["MiddleName"].ToString() : string.Empty; LastName.Text = iei["LastName"] != null ? iei["LastName"].ToString() : string.Empty; Email.Text = iei["EmailAddress"] != null ? iei["EmailAddress"].ToString() : string.Empty; Phone.Text = iei["Phone"] != null ? iei["Phone"].ToString() : string.Empty; } } catch (Exception ex) { ClearFields(false); StatusLabel.ForeColor = Color.Red; StatusLabel.Text = "Unable to find customer with ID = " + CustomerID.Text + ". " + ex.Message; } }
public Uri GetDisplayUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance) { return(this.sourceUri); }
private ParameterType(IEntityInstance elementTypeInstance, IEntityInstance typeInstance) { this.ElementTypeInstance = elementTypeInstance; this.TypeInstance = typeInstance; }
public static EvaluationInfo Create(IEntityInstance components, EntityInstance merged) { return(new EvaluationInfo(components, merged)); }
internal static Task <ObjectData> CreateEmptyAsync(ExecutionContext ctx, IEntityInstance typeInstance) { return(CreateInstanceAsync(ctx, typeInstance, null)); }
public static bool DataTransfer(this IEvaluable @this, ComputationContext ctx, ref IExpression source, IEntityInstance targetTypeName, bool ignoreMutability = false) { if (source == null) { return(true); } IEntityInstance src_type = source.Evaluation.Components; TypeMatch match = src_type.MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false) .WithIgnoredMutability(ignoreMutability) .AllowedLifetimeChecking(true)); if (match.HasFlag(TypeMatch.Attachment)) { match ^= TypeMatch.Attachment; } if (match == TypeMatch.No) { ctx.ErrorManager.AddError(ErrorCode.TypeMismatch, source); return(false); } else if (match == TypeMatch.Lifetime) { ctx.ErrorManager.AddError(ErrorCode.EscapingReference, source); return(false); } else if (match == TypeMatch.InConversion) { source.DetachFrom(@this); source = ExpressionFactory.StackConstructor((targetTypeName as EntityInstance).NameOf, FunctionArgument.Create(source)); source.AttachTo(@this); TypeMatch m = source.Evaluated(ctx, EvaluationCall.AdHocCrossJump).MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)); if (m != TypeMatch.Same && m != TypeMatch.Substitute) { throw new Exception("Internal error"); } } else if (match.HasFlag(TypeMatch.ImplicitReference)) { match ^= TypeMatch.ImplicitReference; if (match != TypeMatch.Substitute && match != TypeMatch.Same) { throw new NotImplementedException(); } source.DetachFrom(@this); source = AddressOf.CreateReference(source); source.AttachTo(@this); IEntityInstance source_eval = source.Evaluated(ctx, EvaluationCall.AdHocCrossJump); TypeMatch m = source_eval.MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: true)); if (m != TypeMatch.Same && m != TypeMatch.Substitute) { throw new Exception($"Internal error: matching result {m}"); } } else if (match == TypeMatch.OutConversion) { source.DetachFrom(@this); source = FunctionCall.ConvCall(source, (targetTypeName as EntityInstance).NameOf); source.AttachTo(@this); TypeMatch m = source.Evaluated(ctx, EvaluationCall.AdHocCrossJump).MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)); if (m != TypeMatch.Same && m != TypeMatch.Substitute) { throw new Exception("Internal error"); } } else if (match.HasFlag(TypeMatch.AutoDereference)) { source.DereferencedCount_LEGACY = match.Dereferences; @this.Cast <IExpression>().DereferencingCount = match.Dereferences; match ^= TypeMatch.AutoDereference; if (match != TypeMatch.Substitute && match != TypeMatch.Same) { throw new NotImplementedException(); } } else if (match != TypeMatch.Same && match != TypeMatch.Substitute) { throw new NotImplementedException(); } return(true); }
protected override void compute(ComputationContext ctx) { IEntityInstance eval = EntityInstanceUnion.Create(Elements.Select(it => it.Evaluation.Components)); // we need to get common members bool has_reference = false; bool has_pointer = false; var dereferenced_instances = new List <EntityInstance>(); List <FunctionDefinition> members = null; foreach (EntityInstance ____instance in this.Elements.Select(it => it.Evaluation.Aggregate)) { if (ctx.Env.DereferencedOnce(____instance, out IEntityInstance __instance, out bool via_pointer)) { if (via_pointer) { has_pointer = true; } else { has_reference = true; } } EntityInstance instance = __instance.Cast <EntityInstance>(); dereferenced_instances.Add(instance); if (members == null) { members = instance.TargetType.NestedFunctions .Where(f => !f.IsAnyConstructor() && f.Parameters.All(it => !it.IsOptional)) .ToList(); } else { foreach (FunctionDefinition m in members.ToArray()) { bool found = false; foreach (FunctionDefinition func in instance.TargetType.NestedFunctions) { // todo: maybe some day handle optionals if (func.IsAnyConstructor() || func.Parameters.Any(it => it.IsOptional)) { continue; } if (FunctionDefinitionExtension.IsSame(ctx, m, func, instance)) { found = true; break; } } if (!found) { members.Remove(m); } } } } EntityInstance aggregate_instance = createAggregate(ctx, has_reference, has_pointer, dereferenced_instances, members, partialVirtualTables: false); this.Evaluation = new EvaluationInfo(eval, aggregate_instance); }
private static IEnumerable <CallResolution> resolveOverloading(IEnumerable <CallResolution> targets) { if (targets.Count() < 2) { return(targets); } // the less, the better var arguments_matches = new List <Tuple <CallResolution, List <FunctionOverloadWeight> > >(); foreach (CallResolution call_target in targets) { var weights = new List <FunctionOverloadWeight>(); foreach (FunctionArgument arg in call_target.ExtensionsArguments) { FunctionParameter param = call_target.GetParamByArg(arg); var weight = new FunctionOverloadWeight(); // prefer non-variadic parameters if (param.IsVariadic) { weight.Penalty += 1; } // prefer concrete type over generic one (foo(Int) better than foo<T>(T)) // note we use untranslated param evaluation here to achieve this effect if (!param.Evaluation.Components.IsExactlySame(arg.Evaluation.Components, jokerMatchesAll: true)) { weight.Penalty += 2; } // prefer exact match instead more general match (Int->Int is better than Int->Object) IEntityInstance param_trans_eval = call_target.GetTransParamEvalByArg(arg); TypeMatch m = call_target.TypeMatches[arg.Index].Value; if (m.HasFlag(TypeMatch.Substitute)) { weight.Penalty += 4; weight.SubstitutionDistance = m.Distance; } else if (!m.HasFlag(TypeMatch.Same)) // conversions { weight.Penalty += 8; } weights.Add(weight); } // bonus if optional parameters are explicitly targeted (i.e. default values are not used) weights.Add(new FunctionOverloadWeight(call_target.AllParametersUsed() ? 0 : 1)); arguments_matches.Add(Tuple.Create(call_target, weights)); } Option <Tuple <CallResolution, List <FunctionOverloadWeight> > > best = arguments_matches .IntransitiveMin((a, b) => Extensions.Tools.HasOneLessNoneGreaterThan(a.Item2, b.Item2, (x, y) => x < y)); if (best.HasValue) { return new[] { best.Value.Item1 } } ; else { return(targets); } }
private static void SetSecondaryFields(SPListItem listItem, SPBusinessDataField dataField, IEntityInstance entityInstance, string finderMethod) { try { // Convert the entity to a formatted datatable System.Data.DataTable dtBDCData = entityInstance.EntityAsFormattedDataTable; // Set the BCS field itself (Display Value) listItem[dataField.Id] = dtBDCData.Rows[0][dataField.BdcFieldName].ToString(); // Get the specific finder method to get the columns that returns IMethodInstance method = entityInstance.Entity.GetMethodInstances(MethodInstanceType.SpecificFinder)[finderMethod]; ITypeDescriptorCollection oDescriptors = method.GetReturnTypeDescriptor().GetChildTypeDescriptors()[0].GetChildTypeDescriptors(); // Set the column names to the correct values foreach (ITypeDescriptor oType in oDescriptors) { if (oType.ContainsLocalizedDisplayName()) { if (dtBDCData.Columns.Contains(oType.Name)) { dtBDCData.Columns[oType.Name].ColumnName = oType.GetLocalizedDisplayName(); } } } // Get the secondary field display names - these should be set string[] sSecondaryFieldsDisplayNames = dataField.GetSecondaryFieldsNames(); // Loop through the fields and set each column to its value foreach (string columnNameInt in sSecondaryFieldsDisplayNames) { foreach (SPField field in listItem.Fields) { if (field.Title.StartsWith(dataField.Title) && field.GetProperty("BdcField") == columnNameInt) { Guid gFieldID = listItem.Fields[field.Title].Id; listItem[gFieldID] = dtBDCData.Rows[0][columnNameInt].ToString(); } } } } catch (Exception e) { LogError("SetSecondaryFields errored with message " + e.Message, ErrorLevel.Warning); throw; } }
public bool Translate(TemplateParameter templateParameter, out IEntityInstance instanceArgument) { return(this.table.TryGetValue(templateParameter, out instanceArgument) && instanceArgument != null); }
/* public static bool AreOverloadDistinct(EntityInstance type1, EntityInstance type2) * { * return type2 != type1 && !type1.DependsOnTypeParameter && !type2.DependsOnTypeParameter; * }*/ public static bool IsStrictAncestorTypeOf(ComputationContext ctx, IEntityInstance ancestor, IEntityInstance descendant) { return(ancestor.IsStrictAncestorOf(ctx, descendant)); }
public void CellReady(object sender, CellReadyEventArgs cellReadyArgs) { Converter <string, object> converter = null; RowReadyEventArgs e = new RowReadyEventArgs(); Microsoft.Office.Server.ApplicationRegistry.MetadataModel.View view = null; this.cellValue = cellReadyArgs.Cell; bool doit = base.LicEd(4) || !this.Exed; if (this._cellConnected && this._rowConnected) { if (this.rowTable != null) { this.rowTable.Dispose(); } this.rowTable = new DataTable(); if (this.RowArgs.FieldList.Length > 0) { foreach (string str in this.RowArgs.FieldList) { this.rowTable.Columns.Add(str); } if (doit) { try { view = GetView(this.entity); if (this.entityInstance == null) { this.entityInstance = this.GetEntityInstance(view); } } catch { } } DataRow[] rowArray = new DataRow[1]; if (converter == null) { converter = delegate(string fieldName) { if (!doit) { return(this.CellValue); } if ((this.entityInstance != null) && (view != null)) { try { foreach (Field field in view.Fields) { if (field.Name == fieldName) { object obj2; return(((obj2 = this.entityInstance[field]) == null) ? string.Empty : obj2.ToString()); } } } catch { } } return(string.Empty); }; } rowArray[0] = this.rowTable.Rows.Add(new List <string>(this.RowArgs.FieldList).ConvertAll <object>(converter).ToArray()); e.Rows = rowArray; this.OnRowReady(e); } } }
private static bool interchangeableTypesTo(ComputationContext ctx, IEntityInstance input, IEntityInstance target) { bool is_input_sealed = input.EnumerateAll() .Select(it => { ctx.Env.Dereference(it, out IEntityInstance result); return(result); }) .SelectMany(it => it.EnumerateAll()) .All(it => it.Target.Modifier.IsSealed); if (is_input_sealed) { TypeMatch match = input.MatchesTarget(ctx, target, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: true).WithIgnoredMutability(true)); // example: we cannot check if x (of Int) is IAlien because Int is sealed and there is no way // it could be something else not available in its inheritance tree if (!match.Passed) { return(false); } } return(true); }
String GenerateXml(IEntityInstanceEnumerator enums) { XmlDocument xmldoc = new XmlDocument(); //let's add the header XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement xmlelem = xmldoc.CreateElement("", "OneBoxResults", "http://www.w3.org/2001/XMLSchema-instance"); xmldoc.AppendChild(xmlelem); XmlElement xmlelem2 = xmldoc.CreateElement(null, "resultCode", null); xmlelem.AppendChild(xmlelem2); xmlelem2.AppendChild(xmldoc.CreateTextNode("Success")); xmlelem2 = xmldoc.CreateElement("provider"); xmlelem.AppendChild(xmlelem2); xmlelem2.AppendChild(xmldoc.CreateTextNode("MOSS BDC")); xmlelem2 = xmldoc.CreateElement("title"); xmlelem.AppendChild(xmlelem2); XmlElement xmlelem3 = xmldoc.CreateElement("urlText"); xmlelem2.AppendChild(xmlelem3); xmlelem3.AppendChild(xmldoc.CreateTextNode("Results in MOSS - BDC")); xmlelem3 = xmldoc.CreateElement("urlLink"); xmlelem2.AppendChild(xmlelem3); xmlelem3.AppendChild(xmldoc.CreateTextNode(_entity.listUrl)); //find keys Regex reg = new Regex("{([^}]*)}"); //process actions //since onebox only allows one url,we only use one action here IEnumerator ait = _entity.actionCollection.GetEnumerator(); String url = null; while (ait.MoveNext()) { Action a = (Action)ait.Current; url = a.url; MatchCollection col = reg.Matches(url); IEnumerator it = col.GetEnumerator(); while (it.MoveNext()) { String match = ((Match)it.Current).Value; String key = match.Substring(1, match.Length - 2); _keys.Add(key, key); } } //now let's add body //let's add another element (child of the root) enums.Reset(); while (enums.MoveNext()) { xmlelem2 = xmldoc.CreateElement("MODULE_RESULT"); xmlelem.AppendChild(xmlelem2); IEntityInstance IE = enums.Current; String u = url; foreach (Field f in _entityInst.GetFinderView().Fields) { String key = f.Name; String value = IE[f] == null? "": IE[f].ToString(); if (_keys.ContainsKey(key)) { u = u.Replace("{" + key + "}", value); } xmlelem3 = xmldoc.CreateElement("Field"); XmlAttribute attr = xmldoc.CreateAttribute("name"); attr.Value = key; xmlelem3.Attributes.Append(attr); xmlelem2.AppendChild(xmlelem3); xmlelem3.AppendChild(xmldoc.CreateTextNode(value)); } if (u != null) { xmlelem3 = xmldoc.CreateElement("U"); xmlelem2.AppendChild(xmlelem3); xmlelem3.AppendChild(xmldoc.CreateTextNode(u)); } } return(toString(xmldoc)); }
//This method returns a strongly Typed entity based on an identifier public BdcMachine GetMachine(int identifier) { IEntityInstance instance = GetBdcEntityInstance(identifier, "Machines"); return(new DataMapper <BdcMachine>(instance.EntityAsDataTable).Instance); }
public IGroup GetGroup(IEntityInstance instance) { return (from _group in Groups where _group.Id == instance.GroupId select _group).FirstOrDefault(); }