示例#1
0
 public void SetUp()
 {
     this._bag = Bag<int>.Create();
     this._bag.Add(FirstBagItem);
     this._bag.Add(SecondBagItem);
     this._bag.Add(ThirdBagItem);
 }
        private static string ReplaceSystem(IBag bag, string text, string token)
        {
            bag.Logger.StartSection("ReplaceSystemSystem " + token);
            string systemtoken = GetSeparatedPart(token, "|", 2).ToLowerInvariant();
            string format      = GetSeparatedPart(token, "|", 3);

            bag.Logger.Log($"SystemToken: {systemtoken} Format: {format}");

            string value = "";

            switch (systemtoken.ToUpperInvariant())
            {
            case "NOW":
                value = SystemNow(format);
                break;

            case "TODAY":
                value = SystemToday(format);
                break;

            case "USER":
                value = bag.SystemUser(format);
                break;

            case "CHAR":
                value = SystemChars(format);
                break;

            default:
                throw new InvalidPluginExecutionException("Unknown system token: " + systemtoken);
            }

            bag.Logger.Log($"Replacing <{token}> with {value}");
            bag.Logger.EndSection();
            return(text.Replace("<" + token + ">", value));
        }
示例#3
0
        private int CheckInBags(IPassenger passenger, IEnumerable <int> bagsToCheckIn)
        {
            IList <IBag> bags = passenger.Bags;

            int confiscatedBagCount = 0;

            foreach (var index in bagsToCheckIn)
            {
                IBag currentBag = bags[index];
                bags.RemoveAt(index);

                if (ShouldConfiscate(currentBag))
                {
                    airport.AddConfiscatedBag(currentBag);
                    confiscatedBagCount++;
                }
                else
                {
                    this.airport.AddCheckedBag(currentBag);
                }
            }

            return(confiscatedBagCount);
        }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bag"></param>
        /// <param name="entity"></param>
        /// <param name="relatedentities"></param>
        /// <param name="intersect"></param>
        /// <param name="batchSize"></param>
        public static void Disassociate(this IBag bag, Entity entity, List <EntityReference> relatedentities, string intersect, int batchSize)
        {
            if (batchSize < 1)
            {
                throw new ArgumentException("Must be a positive number", "batchSize");
            }

            var processed = 0;

            while (processed < relatedentities.Count)
            {
                var batch = new EntityReferenceCollection(relatedentities.Skip(processed).Take(batchSize).ToList());
                processed += batch.Count();

                var req = new DisassociateRequest
                {
                    Target          = entity.ToEntityReference(),
                    Relationship    = new Relationship(intersect),
                    RelatedEntities = batch
                };
                bag.Service.Execute(req);
                bag.Logger.Log($"Disassociated {batch.Count} {(relatedentities.Count > 0 ? relatedentities[0].LogicalName : "")} from {entity.ToStringExt(bag.Service)}");
            }
        }
示例#5
0
        /// <summary>
        /// Internal method for the Intersection operation.
        /// </summary>
        /// <param name="bag">The bag to perform the intersection on.</param>
        /// <returns>The result of the intersection.</returns>
        private Bag <T> IntersectionInternal(IBag <T> bag)
        {
            Guard.ArgumentNotNull(bag, "bag");


            var resultBag = new Bag <T>();

            using (var enumerator = bag.GetCountEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    var item = enumerator.Current;

                    if (_data.TryGetValue(item.Key, out var itemCount))
                    {
                        resultBag.Add(item.Key,
                                      Math.Min(item.Value, itemCount)
                                      );
                    }
                }
            }

            return(resultBag);
        }
示例#6
0
        static async Task ImagesGigImagesGET(int count, DbAgent agent)
        {
            DataSItem itm = new DataSItem();

            itm.Schema = "general";

            itm.Name = "Images_Get";
            // itm.AddParam(new DataParam("@path", CustomSqlTypes.String));
            itm.AddReturnParam(CustomSqlTypes.Int);
            //  itm.FillPRocedureParamsFromSQLAgent(agent);
            // itm.Params.Add("@path",new DataParam());

            Task compleateT = RunLimitedNumberAtATime(10, Enumerable.Range(1, count), async x =>
                                                      Task.Factory.StartNew(async() =>
            {
                Console.WriteLine("Start! ");
                // itm.Params["@path"].Value = Guid.NewGuid().ToString();
                ExecAsyncResult res = await itm.ExecuteDataReaderByRefAsync <Img>(agent);
                IBag <Img> images   = res.Object as IBag <Img>;
                Console.WriteLine("Item Count : " + images.Objects.Count.ToString() + "  " + res.ToString());
            }, TaskCreationOptions.LongRunning));

            await compleateT;
        }
示例#7
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="bag"></param>
 /// <param name="entity"></param>
 public static void Update(this IBag bag, Entity entity)
 {
     bag.Service.Update(entity);
     bag.Logger.Log($"Updated {entity.LogicalName} {entity.Id} with {entity.Attributes.Count} attributes");
 }
示例#8
0
 public void AddCheckedBag(IBag bag)
 {
     this.checkedInBags.Add(bag);
 }
示例#9
0
 /// <inheritdoc />
 /// <exception cref="InvalidCastException"><paramref name="bag"/> is not a <see cref="Bag{T}"/>.</exception>
 IBag <T> IBag <T> .Union(IBag <T> bag)
 {
     return(Union((Bag <T>)bag));
 }
示例#10
0
 /// <inheritdoc />
 IBag <T> IBag <T> .Intersection(IBag <T> bag)
 {
     return(IntersectionInternal(bag));
 }
示例#11
0
 public static IList <ReferenceItem> DeleteableToReferenceItems <T>(IBag <T> list, Func <T, string> toText) where T : class, IIdentifiable, IDeleteable
 {
     return(ToReferenceItems(list.Where(x => x.DeletedKey == null), toText));
 }
示例#12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="source"></param>
 /// <param name="bag"></param>
 /// <param name="entity"></param>
 /// <param name="referencingattribute"></param>
 /// <param name="onlyactive"></param>
 /// <param name="columns"></param>
 /// <returns></returns>
 public static EntityCollection GetRelating(this Entity source, IBag bag, string entity, string referencingattribute, bool onlyactive, params string[] columns) => source.GetRelating(bag, entity, referencingattribute, onlyactive, null, null, new ColumnSet(columns), false);
示例#13
0
 public DocumentDatabase(IDatabase database)
 {
     _database          = database;
     _documents         = database.GetOrCreateBag <DocumentEntity>("Documents");
     _documentIdsByName = database.GetOrCreateMultiValueDictionary <string, RowId>("DocumentIdsByName");
 }
示例#14
0
 public void AddNode(IBag bag)
 {
     _bags.Add(bag.BagName, bag);
 }
        /// <summary>
        /// Check diagonal symmetry.
        /// </summary>
        /// <param name="result">The result accumulator.</param>
        /// <param name="grid">The grid.</param>
        private void CheckDiagonal(IBag <TechniqueInfo> result, IReadOnlyGrid grid)
        {
            bool diagonalHasEmptyCell = false;

            for (int i = 0; i < 9; i++)
            {
                if (grid.GetStatus(i * 9 + i) == Empty)
                {
                    diagonalHasEmptyCell = true;
                    break;
                }
            }
            if (!diagonalHasEmptyCell)
            {
                // No conclusion.
                return;
            }

            int?[] mapping = new int?[9];
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    int  c1        = i * 9 + j;
                    int  c2        = j * 9 + i;
                    bool condition = grid.GetStatus(c1) == Empty;
                    if (condition ^ grid.GetStatus(c2) == Empty)
                    {
                        // One of two cells is empty. Not this symmetry.
                        return;
                    }

                    if (condition)
                    {
                        continue;
                    }

                    int d1 = grid[c1], d2 = grid[c2];
                    if (d1 == d2)
                    {
                        int?o1 = mapping[d1];
                        if (o1 is null)
                        {
                            mapping[d1] = d1;
                            continue;
                        }

                        if (o1 != d1)
                        {
                            return;
                        }
                    }
                    else
                    {
                        int?o1 = mapping[d1], o2 = mapping[d2];
                        if (o1 is null ^ o2 is null)
                        {
                            return;
                        }

                        if (o1 is null && o2 is null)
                        {
                            mapping[d1] = d2;
                            mapping[d2] = d1;
                            continue;
                        }

                        // 'o1' and 'o2' are both not null.
                        if (o1 != d2 || o2 != d1)
                        {
                            return;
                        }
                    }
                }
            }

            var singleDigitList = new List <int>();

            for (int digit = 0; digit < 9; digit++)
            {
                int?mappingDigit = mapping[digit];
                if (mappingDigit is null || mappingDigit == digit)
                {
                    singleDigitList.Add(digit);
                }
            }

            var candidateOffsets = new List <(int, int)>();
            var conclusions      = new List <Conclusion>();

            for (int i = 0; i < 9; i++)
            {
                int cell = i * 9 + i;
                if (grid.GetStatus(cell) != Empty)
                {
                    continue;
                }

                foreach (int digit in grid.GetCandidatesReversal(cell).GetAllSets())
                {
                    if (singleDigitList.Contains(digit))
                    {
                        candidateOffsets.Add((0, cell * 9 + digit));
                        continue;
                    }

                    conclusions.Add(new Conclusion(Elimination, cell, digit));
                }
            }

            if (conclusions.Count == 0)
            {
                return;
            }

            result.Add(
                new GspTechniqueInfo(
                    conclusions,
                    views: new[]
            {
                new View(
                    cellOffsets: null,
                    candidateOffsets,
                    regionOffsets: null,
                    links: null)
            },
                    symmetryType: SymmetryType.Diagonal,
                    mappingTable: mapping));
        }
示例#16
0
 protected EntitySystem()
 {
     Index = _NextIndex++;
     ActiveEntities = new Bag<Entity>();
 }
示例#17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        /// <param name="bag"></param>
        /// <param name="related"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public static Entity GetRelated(this Entity source, IBag bag, string related, ColumnSet columns)
        {
            bag.Logger.StartSection($"GetRelated {related} from {source.LogicalName} {source.Id}");
            Entity result  = null;
            var    refname = related;
            var    refatt  = string.Empty;

            if (refname.Contains("."))
            {
                refatt  = refname.Substring(refname.IndexOf('.') + 1);
                refname = refname.Substring(0, refname.IndexOf('.'));
            }
            if (source.Attributes.Contains(refname))
            {
                EntityReference reference = null;
                if (source.Attributes[refname] is EntityReference er)
                {
                    reference = er;
                }
                else if (source.Attributes[refname] is Guid id && refname.EndsWith("id"))
                {
                    reference = new EntityReference(string.Empty, id);
                }
                if (string.IsNullOrEmpty(reference.LogicalName))
                {
                    //reference.LogicalName = Common.CintDynEntity.GetRelatedEntityNameFromLookupAttributeName(refname);
                }
                if (reference != null)
                {
                    if (refatt != "")
                    {
                        var nextref = refatt;
                        if (nextref.Contains("."))
                        {
                            nextref = nextref.Substring(0, nextref.IndexOf('.'));
                        }

                        bag.Logger.Log($"Loading {reference.LogicalName} {reference.Id} column {nextref}");
                        var cdNextRelated = bag.Service.Retrieve(reference.LogicalName, reference.Id, new ColumnSet(new string[] { nextref }));
                        if (cdNextRelated != null)
                        {
                            result = cdNextRelated.GetRelated(bag, refatt, columns);
                        }
                    }
                    else
                    {
                        result = bag.Service.Retrieve(reference.LogicalName, reference.Id, columns);
                    }
                }
            }
            else
            {
                bag.Logger.Log($"Record does not contain attribute {refname}");
            }
            if (result == null)
            {
                bag.Logger.Log("Could not load related record");
            }
            else
            {
                bag.Logger.Log($"Loaded related {result.LogicalName} {result.Id}");
            }

            bag.Logger.EndSection();
            return(result);
        }
示例#18
0
 private Astronaut()
 {
     this.bag = new Bag();
 }
示例#19
0
        /// <summary>Gets the value of a property as a formatted string</summary>
        /// <param name="entity"></param>
        /// <param name="bag"></param>
        /// <param name="name"></param>
        /// <param name="def"></param>
        /// <param name="supresserrors"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string PropertyAsString(this Entity entity, IBag bag, string name, string def = null, bool supresserrors = false, string format = null)
        {
            bool hasValueFormat = false;

            if (!entity.Contains(name))
            {
                if (!supresserrors)
                {
                    throw new InvalidPluginExecutionException(string.Format("Attribute {0} not found in entity {1} {2}", name, entity.LogicalName, entity.Id));
                }
                else
                {
                    return(def);
                }
            }

            // Extrahera eventuella egna implementerade formatsträngar, t.ex. "<MaxLen=20>"
            var extraFormats = new List <string>();

            format = XrmSubstituter.ExtractExtraFormatTags(format, extraFormats);

            string result     = null;
            object oAttrValue = entity.Contains(name) ? entity[name] : null;

            if (oAttrValue != null && format?.StartsWith("<value>") == true)
            {
                hasValueFormat = true;
                format         = format.Replace("<value>", "");

                oAttrValue = AttributeToBaseType(oAttrValue);
            }

            if (oAttrValue != null && !string.IsNullOrWhiteSpace(format))
            {
                if (oAttrValue is AliasedValue)
                {
                    oAttrValue = AttributeToBaseType(((AliasedValue)oAttrValue).Value);
                }

                if (oAttrValue is Money)
                {
                    decimal dAttrValue = ((Money)oAttrValue).Value;
                    result = dAttrValue.ToString(format);
                }
                else if (oAttrValue is int)
                {
                    result = ((int)oAttrValue).ToString(format);
                }
                else if (oAttrValue is decimal)
                {
                    result = ((decimal)oAttrValue).ToString(format);
                }
            }
            if (result == null)
            {
                if (oAttrValue != null && oAttrValue is EntityReference er)
                {   // Introducerat för att nyttja metadata- och entitetscache på CrmServiceProxy
                    var related = entity.GetRelated(bag, name, bag.Service.GetPrimaryAttribute(er.LogicalName).LogicalName);
                    result = Utils.EntityToString(related, bag.Service);
                }
                else if (hasValueFormat)
                {
                    result = oAttrValue.ToString();
                }
                else
                {
                    result = entity.AttributeToString(name, def, bag.Service);
                }

                if (!string.IsNullOrWhiteSpace(format))
                {
                    DateTime tmpDateTime;
                    int      tmpInt;
                    decimal  tmpDecimal;
                    if (DateTime.TryParse(result, out tmpDateTime))
                    {
                        result = tmpDateTime.ToString(format);
                    }
                    else if (int.TryParse(result, out tmpInt))
                    {
                        result = tmpInt.ToString(format);
                    }
                    else if (decimal.TryParse(result.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator).Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator), out tmpDecimal))
                    {
                        result = tmpDecimal.ToString(format);
                    }
                    else
                    {
                        if (!format.Contains("{0}"))
                        {
                            format = "{0:" + format + "}";
                        }
                        result = string.Format(format, result);
                    }
                }
            }
            // Applicera eventuella egna implementerade formatsträngar
            foreach (var extraFormat in extraFormats)
            {
                result = XrmSubstituter.FormatByTag(result, extraFormat);
            }
            return(result);
        }
示例#20
0
 public void AddCheckedBag(IBag bag) => this.takenBags.Add(bag);
示例#21
0
 public static IList <SelectListItem> DeleteableToSelectListItems <T>(IBag <T> list, Func <T, string> toText, IEnumerable <int> selectedIds) where T : class, IIdentifiable, IDeleteable
 {
     return(ToSelectListItems(list.Where(x => x.DeletedKey == null), toText, selectedIds));
 }
示例#22
0
 public void AddConfiscatedBag(IBag bag) => this.notTakenBags.Add(bag);
示例#23
0
 /// <inheritdoc />
 IBag <T> IBag <T> .Subtract(IBag <T> bag)
 {
     return(SubtractInternal(bag));
 }
示例#24
0
 public EntityItem(Entity entity, IBag bag)
     : this(entity, string.Empty, bag)
 {
 }
示例#25
0
 public Astronaut(string name, double oxygen)
 {
     this.Name   = name;
     this.Oxygen = oxygen;
     this.bag    = new Backpack();
 }
示例#26
0
 public static void Add <TKey, TValue>(this IBag <TKey, TValue> dictionary, TKey key, IEnumerable <TValue> values)
 {
     dictionary.Add(values.ToLookup(_ => key, Id));
 }
示例#27
0
 public void AddConfiscatedBag(IBag bag)
 {
     this.confiscatedBags.Add(bag);
 }
示例#28
0
 public static void Add <TKey, TValue>(this IBag <TKey, TValue> dictionary, TKey key, params TValue[] values)
 {
     dictionary.Add(values.ToLookup(_ => key, Id));
 }
示例#29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bag"></param>
        /// <param name="entity"></param>
        /// <param name="relatedentities"></param>
        /// <param name="intersect"></param>
        /// <param name="batchSize"></param>
        public static void Disassociate(this IBag bag, Entity entity, List <Entity> relatedentities, string intersect, int batchSize)
        {
            var entRefCollection = relatedentities.Select(e => e.ToEntityReference()).ToList();

            Disassociate(bag, entity, entRefCollection, intersect, batchSize);
        }
示例#30
0
 public static void Add <TKey, TValue>(this IBag <TKey, TValue> dictionary, IEnumerable <KeyValuePair <TKey, TValue> > items)
 {
     dictionary.Add(items.ToLookup(k => k.Key, k => k.Value));
 }
示例#31
0
        private static bool ShouldConfiscate(IBag bag)
        {
            var bagValue = bag.Items.Sum(x => x.Value);

            return(bagValue > bagValueMaxLimit);
        }
示例#32
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="source"></param>
 /// <param name="bag"></param>
 /// <param name="related"></param>
 /// <param name="columns"></param>
 /// <returns></returns>
 public static Entity GetRelated(this Entity source, IBag bag, string related, params string[] columns) => source.GetRelated(bag, related, new ColumnSet(columns));