public void SubmitReport(HandlingReport handlingReport)
        {
            IList<string> errors = new List<string>();

            DateTime? completionTime = HandlingReportParser.ParseCompletionTime(handlingReport, errors);
            VoyageNumber voyageNumber = HandlingReportParser.ParseVoyageNumber(handlingReport.VoyageNumber, errors);
            HandlingType type = HandlingReportParser.ParseEventType(handlingReport.Type, errors);
            UnLocode unLocode = HandlingReportParser.ParseUnLocode(handlingReport.UnLocode, errors);

            foreach (string trackingIdStr in handlingReport.TrackingIds)
            {
                TrackingId trackingId = HandlingReportParser.ParseTrackingId(trackingIdStr, errors);

                if (errors.IsEmpty())
                {
                    DateTime registrationTime = DateTime.Now;
                    var attempt = new HandlingEventRegistrationAttempt(
                        registrationTime, completionTime.Value, trackingId, voyageNumber, type, unLocode);
                    applicationEvents.ReceivedHandlingEventRegistrationAttempt(attempt);
                }
                else
                {
                    string errorString = String.Join("\r\n", errors.ToArray());
                    logger.Error("Parse error in handling report: " + errorString);

                    throw new FaultException<HandlingReportException>(new HandlingReportException(errorString), new FaultReason(errorString));
                }
            }
        }
Example #2
0
        public void IsEmptyTest_IEnumerable()
        {
            List<int> source = new List<int>();
            Assert.True(source.IsEmpty());

            source.Add(1);
            Assert.False(source.IsEmpty());
        }
 public override bool Matches(object actual)
 {
     this.actual = actual;
     _failures = new List<Failure>();
     PropertyEquals(_expectedResponse, actual, _expectedResponse.GetType().Name);
     return _failures.IsEmpty();
 }
        public List<PropertyMatch> GetPropertyMatches(List<PropertyMatchCriteria> propertyMatchCriteria)
        {
            var propertyMatches = new List<PropertyMatch>();
            foreach (var criterion in propertyMatchCriteria)
            {
                var date = new DateTime();
                DateTime.TryParse(criterion.DateCreated, out date);
                var newApplications =
                    _propertyCaselistRepository.GetApplicationsWhereRequirementsMatchProperty(
                        criterion.Area, criterion.Beds, criterion.Price,
                        criterion.PropertyReference, date);

                foreach (var application in newApplications)
                {
                    application.GeneratePropertyCaselistStatus(_propertyCaselistStatusGenererator, criterion.PropertyReference);
                }

                propertyMatches.Add(new PropertyMatch
                {
                    Applications = newApplications.ToList(),
                    Property = new Property
                    {
                        PropertyReference = criterion.PropertyReference
                    }
                });
            }

            if(propertyMatches.IsNull() || propertyMatches.IsEmpty())
                return new List<PropertyMatch>();

            return propertyMatches;
        }
        public IList<EMVehicleGroup> SelectListByTenantCodes(List<string> tenantCodes)
        {
            IList<EMVehicleGroup> list = null;
            if (tenantCodes.IsEmpty())
                return list;

            string cmdText = string.Format("SELECT GroupID,GroupName,ParentGroupID,TenantCode,Remark FROM movo_vehiclegroup WHERE TenantCode in('{0}') order by GroupName", tenantCodes.JoinToString<string>("','"));
            using (var dr = MySqlDB.GetDataReader(CommandType.Text, cmdText))
            {
                if (dr != null)
                {
                    list = new List<EMVehicleGroup>();
                    while (dr.Read())
                    {
                        list.Add(new EMVehicleGroup
                        {
                            GroupID = dr.GetULong(0),
                            GroupName = dr.GetStringExt(1),
                            ParentGroupID = dr.GetULongNull(2),
                            TenantCode = dr.GetStringExt(3),
                            Remark = dr.GetStringExt(4)
                        });
                    }
                    dr.Close();
                }
            }
            return list;
        }
Example #6
0
        public string OrderTotal(List<OrderDetail> orderDetails)
        {
            var total = 0m;
            if (!orderDetails.IsEmpty())
                total += orderDetails.Sum(item => item.Quantity * item.UnitPrice);

            return FormatHelpers.Instance.Money(total);
        }
Example #7
0
        private void BuildOrderClause(StringBuilder queryBuilder, List<IOrderingMapper> orderingParts)
        {
            if (orderingParts.IsEmpty()) return;

             var orderBldr = new StringBuilder(Environment.NewLine + "order by");
             orderingParts.ForEach(part => orderBldr.Append(part.OrderClause));
             queryBuilder.Append(orderBldr.ToString().TrimEnd(','));
        }
        public void Think()
        {

			// lists of islands by player
			// start of by only looking for non owned islands, later we could prioritize weaker targets
			var ownedIslands = new List<IslandData> ();
			var enemyIslands = new List<IslandData> ();
			foreach (var island in Registry.Islands.Values)
			{
				var islandData = island.GetComponent<IslandData>();
				
				if (islandData.PlayerData.uid != playerData.uid)
					enemyIslands.Add(islandData);
				else 
					ownedIslands.Add(islandData);
			}

//			Debug.Log (enemyIslands.Count + " enemies vs owned " + ownedIslands.Count);

            // ai wins
            if (enemyIslands.Count == 0)
            {
                GameObject.Find("Menu").GetComponent<Menu>().ShowLoseScreen();
            }

            // player wins
            if (ownedIslands.Count == 0)
            {
                GameObject.Find("Menu").GetComponent<Menu>().ShowWinScreen();
            }

            // no enemies or owning no islands do nothing
			if (enemyIslands.IsEmpty () || ownedIslands.IsEmpty ()) 
			{
				fsm.SendEvent("Idle");
				return;
			}

            // use boost

            // defend

            // attack
			MoveUnitsTo(ownedIslands.GetRandom().gameObject, enemyIslands.GetRandom ().gameObject);
			fsm.SendEvent("Attack");

			// Debug.Log("enemy island: " + islandData.PlayerData.uid + " != " + playerData.uid);
        }
Example #9
0
        /// <summary>
        ///     Permet de charger la fiche de plusieurs salons
        /// </summary>
        /// <param name="salons">List{Salon}</param>
        /// <returns>bool</returns>
        public bool LoadFicheSalon(List<Salon> salons = null)
        {
            try
            {
                if (salons.IsEmpty()) return false;

                foreach (var salon in salons)
                    LoadFicheSalon(salon);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        void FinalizeBindingConcrete(DiContainer container, List<Type> concreteTypes)
        {
            if (concreteTypes.IsEmpty())
            {
                // This can be common when using convention based bindings
                return;
            }

            switch (BindInfo.Scope)
            {
                case ScopeTypes.Singleton:
                {
                    RegisterProvidersForAllContractsPerConcreteType(
                        container,
                        concreteTypes,
                        (_, concreteType) => container.SingletonProviderCreator.CreateProviderStandard(
                            new StandardSingletonDeclaration(
                                concreteType,
                                BindInfo.ConcreteIdentifier,
                                BindInfo.Arguments,
                                _singletonType,
                                _singletonSpecificId),
                            _providerFactory));
                    break;
                }
                case ScopeTypes.Transient:
                {
                    RegisterProvidersForAllContractsPerConcreteType(
                        container, concreteTypes, _providerFactory);
                    break;
                }
                case ScopeTypes.Cached:
                {
                    RegisterProvidersForAllContractsPerConcreteType(
                        container,
                        concreteTypes,
                        (_, concreteType) =>
                            new CachedProvider(
                                _providerFactory(container, concreteType)));
                    break;
                }
                default:
                {
                    throw Assert.CreateException();
                }
            }
        }
 public ActionResult SearchActivity( string searchTxt)
 {
     var account = _readOnlyRepository.First<Account>(x => x.EMail == User.Identity.Name);
     var lista = new List<ActividadesModel>();
     foreach (var story in account.History)
     {
         if (story.Actividad.Contains(searchTxt))
         {
             lista.Add(Mapper.Map<Actividades,ActividadesModel>(story));
         }
     }
     if (lista.IsEmpty())
     {
         var model = new ActividadesModel();
         model.Actividad = "No se encontro nada con esa busqueda";
         model.Hora = DateTime.Now;
         lista.Add(model );
     }
     return View(lista);
 }
        public DiContainer CreateSubContainer(List<TypeValuePair> args)
        {
            Assert.That(args.IsEmpty());

            var prefab = _prefabProvider.GetPrefab();
            var gameObject = _container.InstantiatePrefab(
                prefab, new object[0], _groupName);

            if (_gameObjectName != null)
            {
                gameObject.name = _gameObjectName;
            }

            var context = gameObject.GetComponent<GameObjectContext>();

            Assert.IsNotNull(context,
                "Expected prefab with name '{0}' to container a component of type 'GameObjectContext'", prefab.name);

            return context.Container;
        }
Example #13
0
        public IEnumerable<ActionPerformError> PerformAction(Gamer gamer)
        {
            var errors = new List<ActionPerformError>();
            foreach (var constraint in QtyBasedConstraints)
            {
                var result = constraint.GetResult(gamer);
                if (!result)
                {
                    errors.Add(new ActionPerformError(constraint.Description));
                }
            }

            if (errors.IsEmpty())
            {
                foreach (var trigger in TriggersToCall)
                {
                    trigger.CallOnGamer(gamer);
                }
            }

            return errors;
        }
Example #14
0
        /// <summary>
        /// ๆ นๆฎ่ฝฆ่พ†็ผ–็ ๅˆ—่กจ่Žทๅ–่ฝฆ่พ†็š„ไฟกๆฏๅˆ—่กจ(ไธๅธฆๅˆ†้กต)
        /// </summary>
        /// <param name="codeList">่ฝฆ่พ†็ผ–็ ๅˆ—่กจ</param>
        /// <returns></returns>
        public List<EMVehicle> SelectVehicleByCodeList(List<Guid> codeList)
        {
            List<EMVehicle> list = new List<EMVehicle>();
            if (codeList.IsEmpty())
                return list;

            string sCmdText = string.Format(@"SELECT VehicleCode,LicenceNumber,GroupID,GPSTypeID,DeviceNo,SIMNo,GPSCode,TenantCode,InitMileage,ExpireTime,InstallTime,IsStop,CreateTime,IconType,GPSTypeName 
 FROM movo_vehicle WHERE VehicleCode in ('{0}') order by LicenceNumber asc ", codeList.JoinToString<Guid>("','"));
            using (MySqlDataReader sdr = MySqlDB.GetDataReader(CommandType.Text, sCmdText))
            {
                if (sdr != null)
                {
                    while (sdr.Read())
                    {
                        list.Add(new EMVehicle
                        {
                            VehicleCode = sdr.GetGuid(0),
                            LicenceNumber = sdr.GetStringExt(1),
                            GroupID = sdr.GetUInt64(2),
                            GPSTypeID = sdr.GetUInt64(3),
                            DeviceNo = sdr.GetStringExt(4),
                            SIMNo = sdr.GetStringExt(5),
                            GPSCode = sdr.GetStringExt(6),
                            TenantCode = sdr.GetStringExt(7),
                            InitMileage = sdr.GetDecimal(8),
                            ExpireTime = sdr.GetDateTimeNull(9),
                            InstallTime = sdr.GetDateTime(10),
                            IsStop = sdr.GetShort(11) == 1,
                            CreateTime = sdr.GetDateTime(12),
                            IconType = (EnumVehicleType)sdr.GetInt16(13),
                            GPSTypeName = sdr.GetStringExt(14)
                        });
                    }
                    sdr.Close();
                }
            }
            return list;

        }
Example #15
0
        public static string AddContainsPattern(string value)
        {
            var stringBuilder = new StringBuilder();

            List <string> words = value
                                  .Split(' ')
                                  .Select(Prepare)
                                  .Where(x => string.IsNullOrEmpty(x) == false)
                                  .ToList();

            if (words.IsEmpty())
            {
                return(string.Empty);
            }

            stringBuilder.AppendFormat("\"{0}*\"", words[0]);

            for (int i = 1; i < words.Count; i++)
            {
                stringBuilder.AppendFormat("AND\"{0}*\"", words[i]);
            }

            return(stringBuilder.ToString());
        }
Example #16
0
        /// <summary>
        /// ๆ›ดๆ–ฐๆ•ฐๆฎ่กŒ
        /// </summary>
        /// <param name="dataRow"></param>
        /// <param name="obj">ๆบๅฏน่ฑก</param>
        /// <param name="addIfNotExists">ๅˆ—ไธๅญ˜ๅœจๆ—ถๆ˜ฏๅฆๆทปๅŠ </param>
        /// <param name="includeFields">ๆŒ‡ๅฎš็š„ๅญ—ๆฎตๅˆ—่กจๆ˜ฏๅฆไธบๅŒ…ๅซๅ…ณ็ณป๏ผˆๅฆๅˆ™ไธบๆŽ’้™คๅ…ณ็ณป๏ผ‰</param>
        /// <param name="fields">ๆŒ‡ๅฎš่ฆๅŒ…ๅซๆˆ–ๆŽ’้™ค็š„ๅญ—ๆฎตๅˆ—่กจ</param>
        /// <returns></returns>
        public static DataRow UpdateDataRow(this DataRow dataRow, object obj,
                                            bool addIfNotExists = false, bool includeFields = false, List <string> fields = null)
        {
            if (null == dataRow || null == obj)
            {
                return(dataRow);
            }

            var members = obj.GetFieldsAndProperities(inherit: true, includeStatic: true);

            if (members.IsEmpty())
            {
                return(dataRow);
            }

            foreach (var member in members)
            {
                try
                {
                    if (!fields.IsEmpty())
                    {
                        var include = fields.Contains(member.Name);
                        if (include ^ includeFields)
                        {
                            continue;
                        }
                    }

                    var value = member.GetMemberValue(obj);
                    dataRow.SetValue(member.Name, value, addIfNotExists);
                }
                catch { }
            }

            return(dataRow);
        }
        /// <summary>
        /// Set all left matches to the Saturday.
        /// </summary>
        /// <param name="matches"></param>
        /// <param name="result"></param>
        /// <param name="dateTimes"></param>
        /// <returns></returns>
        private List <Match> SetSaturdayMatches(List <Match> matches, List <Match> result, List <DateTime> dateTimes)
        {
            if (matches.IsEmpty())
            {
                return(result);
            }
            var matchDay = 1;

            foreach (var dateTime in dateTimes)
            {
                if (matches.Any())
                {
                    // remove match from list
                    var currentMatch = matches.First();
                    matches.Remove(matches.First());
                    // set dateTime of match and matchday
                    currentMatch.DateTime = dateTime;
                    currentMatch.MatchDay = matchDay;
                    result.Add(currentMatch);
                }
                matchDay++;
            }
            return(SetSaturdayMatches(matches, result, dateTimes));
        }
Example #18
0
        static public bool ProcessTillCompleteOrStagnated <T>(this IEnumerable <T> item, TryProcess <T> process)
        {
            if (item != null)
            {
                int      old_count;
                List <T> failed = new List <T>(item);

                do
                {
                    old_count = failed.Count;

                    failed.RemoveAll(delegate(T sub_item) {
                        return(process(sub_item));
                    });
                }while (failed.IsNotEmpty() && old_count != failed.Count);

                if (failed.IsEmpty())
                {
                    return(true);
                }
            }

            return(false);
        }
Example #19
0
        public override void OnPreMissionTick(float dt)
        {
            base.OnPreMissionTick(dt);
            try
            {
                if (_spawnedAgents.IsEmpty())
                {
                    return;
                }

                _spawnedAgents.Shuffle <Agent>();
                foreach (Agent agent in _spawnedAgents)
                {
                    AfterAgentSpawned(agent);
                }
                _spawnedAgents.Clear();
                OnInitialUnitsSpawned();
            }
            catch (Exception ex)
            {
                Main.LogError(ex);
                _spawnedAgents.Clear();
            }
        }
Example #20
0
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            if (randItemIndices.IsEmpty())
            {
                Debug.LogError("Fill item indices, now!!!!!");
                dstManager.DestroyEntity(entity);
                return;
            }

            dstManager.RemoveComponent <Rotation>(entity);
            dstManager.RemoveComponent <LocalToWorld>(entity);

            dstManager.AddComponentData(entity, new ItemStorageComponent()
            {
                index       = randItemIndices[new System.Random().Next(0, randItemIndices.Count)],
                gettingTime = gettingTimeSec,
                checkRadius = GetComponent <SphereCollider>().radius
            });
            dstManager.AddComponentData(entity, new ReactiveComponent()
            {
                type   = (int)ReactiveType.Item,
                search = search
            });
        }
        /// <summary>
        /// Assumes the given reader has only tsurgeon operations (not a tregex pattern), and parses
        /// these out, collecting them into one operation.
        /// </summary>
        /// <remarks>
        /// Assumes the given reader has only tsurgeon operations (not a tregex pattern), and parses
        /// these out, collecting them into one operation.  Stops on a whitespace line.
        /// </remarks>
        /// <exception cref="System.IO.IOException">If the usual kinds of IO errors occur</exception>
        public static TsurgeonPattern GetTsurgeonOperationsFromReader(BufferedReader reader)
        {
            IList <TsurgeonPattern> operations = new List <TsurgeonPattern>();

            for (string thisLine; (thisLine = reader.ReadLine()) != null;)
            {
                if (emptyLinePattern.Matcher(thisLine).Matches())
                {
                    break;
                }
                thisLine = RemoveComments(thisLine);
                if (emptyLinePattern.Matcher(thisLine).Matches())
                {
                    continue;
                }
                // log.info("Read tsurgeon op: " + thisLine);
                operations.Add(ParseOperation(thisLine));
            }
            if (operations.IsEmpty())
            {
                throw new TsurgeonParseException("No Tsurgeon operation provided.");
            }
            return(CollectOperations(operations));
        }
        public static List <Tree> .Node Insert(T x, List <Tree> .Node ts)
        {
            if (List <Tree> .IsEmpty(ts))
            {
                return(List <Tree> .Cons(new Tree(0, x, List <T> .Empty, List <Tree> .Empty), List <Tree> .Empty));
            }
            var tail = List <Tree> .Tail(ts);

            if (List <Tree> .IsEmpty(tail))
            {
                return(List <Tree> .Cons(new Tree(0, x, List <T> .Empty, List <Tree> .Empty), ts));
            }
            var t1 = List <Tree> .Head(ts);

            var t2 = List <Tree> .Head(tail);

            var rest = List <Tree> .Tail(tail);

            if (t1.Rank == t2.Rank)
            {
                return(List <Tree> .Cons(SkewLink(x, t1, t2), rest));
            }
            return(List <Tree> .Cons(new Tree(0, x, List <T> .Empty, List <Tree> .Empty), ts));
        }
Example #23
0
        public override void MouseMove(object sender, MouseEventArgs e)
        {
            var currentCoordinates = Coordinates(e);

            currentCoordinates = AdjustCoordinates(currentCoordinates);

            if (!startedMoving)
            {
                if (currentCoordinates == coordinatesOnMouseDown)
                {
                    return;
                }
                startedMoving = true;
            }
            if (!moving.IsEmpty())
            {
                var offset = currentCoordinates.Minus(oldCoordinates);
                Actions.Move(Drawing, moving, offset, toRecalculate);
            }

            // OK attention here. This is a very tricky spot. At the beginning
            // of this method, we call Coordinates(e) to get the logical mouse
            // coordinates. We could just reuse currentCoordinates, BUT!
            // If you're dragging the coordinate plane itself, the Origin changes
            // so you'll have to re-get the point coordinates in the new
            // coordinate system.
            oldCoordinates = Coordinates(e);
            if (moving != null &&
                moving.Count == 1 &&
                moving[0] is IPoint &&
                found != null &&
                found == moving[0])
            {
                oldCoordinates = moving[0].Coordinates;
            }
        }
Example #24
0
        /// <summary>
        /// ๆณจๅ†Œๅ•ไพ‹ ่ฏฅๆ–นๆณ•ไธไฝฟ็”จ็‰นๆ€ง ็จ‹ๅบ้›†ๅ†…ๅŒ…ๅซๆŒ‡ๅฎšๅ็งฐ็š„็ฑป่ฟ›่กŒ่‡ชๅŠจๆณจๅ…ฅ
        /// </summary>
        /// <param name="services"></param>
        /// <param name="currentAssembly"></param>
        /// <returns></returns>
        public static IServiceCollection AddDependency(this IServiceCollection services, Assembly currentAssembly, InjectLifeTime injectLifeTime)
        {
            List <Type> types = currentAssembly.GetTypes().Where(o => !o.IsInterface && !o.IsGenericType).ToList();

            if (types.IsEmpty())
            {
                return(services);
            }

            foreach (var currentType in types)
            {
                List <Type> interfaces = currentType.GetInterfaces().ToList();
                if (interfaces.IsEmpty())
                {
                    continue;
                }

                foreach (var currentInterface in interfaces)
                {
                    if (injectLifeTime == InjectLifeTime.Singleton)
                    {
                        services.AddSingleton(currentInterface, currentType);
                    }
                    if (injectLifeTime == InjectLifeTime.Scoped)
                    {
                        services.AddScoped(currentInterface, currentType);
                    }
                    if (injectLifeTime == InjectLifeTime.Transient)
                    {
                        services.AddTransient(currentInterface, currentType);
                    }
                }
            }

            return(services);
        }
        public DisjunctiveExamplesSpec WitnessRegexPair(GrammarRule rule, DisjunctiveExamplesSpec spec)
        {
            var result = new Dictionary <State, IEnumerable <object> >();

            foreach (var example in spec.DisjunctiveExamples)
            {
                State inputState = example.Key;
                var   input      = inputState[rule.Body[0]] as string;
                var   regexes    = new List <Tuple <Regex, Regex> >();

                foreach (int output in example.Value)
                {
                    List <Regex>[] leftMatches, rightMatches;
                    BuildStringMatches(input, out leftMatches, out rightMatches);

                    var leftRegex  = leftMatches[output];
                    var rightRegex = rightMatches[output];

                    if (leftRegex.IsEmpty() || rightRegex.IsEmpty())
                    {
                        return(null);
                    }

                    regexes.AddRange(from l in leftRegex
                                     from r in rightRegex
                                     select Tuple.Create(l, r));
                }
                if (regexes.IsEmpty())
                {
                    return(null);
                }
                result[inputState] = regexes;
            }

            return(DisjunctiveExamplesSpec.From(result));
        }
Example #26
0
        private UniformPair <EventBean[]> Output(bool isSynthesize, bool join)
        {
            // generate latest new-events from group representatives
            IList <EventBean> newEvents = new List <EventBean>(4);

            _processor.GenerateOutputBatchedArr(join, _groupReps.GetEnumerator(), true, isSynthesize, newEvents, null);
            var newEventsArr = (newEvents.IsEmpty()) ? null : newEvents.ToArrayOrNull();

            // use old-events as retained, if any
            EventBean[] oldEventsArr = null;
            if (!_groupRepsOutputLastUnordRStream.IsEmpty())
            {
                var oldEvents = _groupRepsOutputLastUnordRStream.Values;
                oldEventsArr = oldEvents.ToArrayOrNull();
                _groupRepsOutputLastUnordRStream.Clear();
            }
            _first = true;

            if (newEventsArr == null && oldEventsArr == null)
            {
                return(null);
            }
            return(new UniformPair <EventBean[]>(newEventsArr, oldEventsArr));
        }
Example #27
0
        private Bounce ApplyComparisonProcedure(IExpression expression, Environment env, Cont cont)
        {
            var combination = expression as ScmCombination;

            return(() => EvalList(combination.Operands, env, evalResults =>
            {
                var evalResultsAsList = new List <INumber> ();
                try
                {
                    evalResultsAsList = Utils.ConvertNumbers(evalResults as List <IExpression>);
                }
                catch (Exception e)
                {
                    throw new EvaluatorException(e.Message, combination);
                }
                bool isDoubleArithmetic = !evalResultsAsList.IsEmpty() && evalResultsAsList.Head() is ScmDoubleNumber;

                try
                {
                    if (isDoubleArithmetic)
                    {
                        var doubleComparison = m_NumericalOperations[typeof(ScmDoubleNumber)] as DoubleNumericalOperations;
                        return (Bounce)cont(doubleComparison.Compare(combination.Procedure as IComparisonOperation, evalResultsAsList));
                    }
                    else
                    {
                        var integerComparison = m_NumericalOperations[typeof(ScmIntegerNumber)] as IntegerNumericalOperations;
                        return (Bounce)cont(integerComparison.Compare(combination.Procedure as IComparisonOperation, evalResultsAsList));
                    }
                }
                catch (Exception e)
                {
                    throw new EvaluatorException(e.Message, combination);
                }
            }));
        }
Example #28
0
        public DiContainer CreateSubContainer(List <TypeValuePair> args, InjectContext parentContext, out Action injectAction)
        {
            Assert.That(!args.IsEmpty());

            var prefab        = _prefabProvider.GetPrefab(parentContext);
            var tempContainer = CreateTempContainer(args);

            bool shouldMakeActive;
            var  gameObject = tempContainer.CreateAndParentPrefab(
                prefab, _gameObjectBindInfo, null, out shouldMakeActive);

            var context = gameObject.GetComponent <GameObjectContext>();

            Assert.That(context != null,
                        "Expected prefab with name '{0}' to container a component of type 'GameObjectContext'", prefab.name);

            context.Install(tempContainer);

            injectAction = () =>
            {
                // Note: We don't need to call ResolveRoots here because GameObjectContext does this for us
                tempContainer.Inject(context);

                if (shouldMakeActive && !_container.IsValidating)
                {
#if UNIDI_INTERNAL_PROFILING
                    using (ProfileTimers.CreateTimedBlock("User Code"))
#endif
                    {
                        gameObject.SetActive(true);
                    }
                }
            };

            return(context.Container);
        }
Example #29
0
        /// <summary>
        /// Validates all configuration.  If validation fails, a <see cref="ListedValidationException"/>
        /// is thrown.
        /// </summary>
        public void Validate()
        {
            List <string> errors = new List <string>();

            foreach (GeneratorConfig config in this.Generators)
            {
                if (config == null)
                {
                    errors.Add($"{nameof( GeneratorConfig )} can not be null");
                }
                else
                {
                    errors.AddRange(config.TryValidate());
                }
            }

            if (errors.IsEmpty() == false)
            {
                throw new ListedValidationException(
                          $"Errors when validating {nameof( MeetBotConfig )}",
                          errors
                          );
            }
        }
Example #30
0
        public object InstantiateComponentOnNewGameObjectExplicit(
            Type componentType, string name, List <TypeValuePair> extraArgMap, InjectContext currentContext)
        {
            Assert.That(componentType.DerivesFrom <Component>(), "Expected type '{0}' to derive from UnityEngine.Component", componentType.Name());

            var gameObj = new GameObject(name);

            if (_rootTransform != null)
            {
                gameObj.transform.SetParent(_rootTransform, false);
            }

            if (componentType == typeof(Transform))
            {
                Assert.That(extraArgMap.IsEmpty());
                return(gameObj.transform);
            }

            var component = (Component)gameObj.AddComponent(componentType);

            this.InjectExplicit(component, extraArgMap, currentContext);

            return(component);
        }
Example #31
0
        public List <BotTerritory> GetSortedAttackValueTerritories()
        {
            var outvar = new List <BotTerritory>();
            var opponentTerritories = BotState.VisibleMap.Territories.Values.Where(o => BotState.IsOpponent(o.OwnerPlayerID)).ToList();
            var copy = new List <BotTerritory>();

            copy.AddRange(opponentTerritories);
            while (!copy.IsEmpty())
            {
                var maxAttackValue          = 0;
                var maxAttackValueTerritory = copy[0];
                foreach (var territory in copy)
                {
                    if (territory.AttackTerritoryValue > maxAttackValue)
                    {
                        maxAttackValue          = territory.AttackTerritoryValue;
                        maxAttackValueTerritory = territory;
                    }
                }
                copy.Remove(maxAttackValueTerritory);
                outvar.Add(maxAttackValueTerritory);
            }
            return(outvar);
        }
Example #32
0
        public static List <City> GetAllCity()
        {
            List <City>     result       = Cache.Get <List <City> >("CityALL") ?? new List <City>();
            List <Province> allProvinces = GetAllProvince();

            if (result.IsEmpty())
            {
                BaseDataRepository mr    = new BaseDataRepository();
                List <CityInfo>    cInfo = mr.GetAllCity();

                foreach (var item in cInfo)
                {
                    City c = new City();
                    c.CityID       = item.CityID;
                    c.CityName     = item.CityName;
                    c.ProvinceID   = item.ProvinceID;
                    c.ProvinceInfo = allProvinces.FirstOrDefault(t => t.ProvinceID == item.ProvinceID) ?? new Province();
                    result.Add(c);
                }
                Cache.Add("CityALL", result);
            }

            return(result);
        }
Example #33
0
        public void Update()
        {
            if (!_signalQueue.IsEmpty())
            {
                // Cache the callback list to allow handlers to be added from within callbacks
                using (var block = DisposeBlock.Spawn())
                {
                    var subscriptions = block.SpawnList <SignalSubscription>();
                    subscriptions.AddRange(_subscriptions);

                    // Cache the signals so that if the signal is fired again inside the handler that it
                    // is not executed until next frame
                    var signals = block.SpawnList <object>();
                    signals.AddRange(_signalQueue);

                    _signalQueue.Clear();

                    for (int i = 0; i < signals.Count; i++)
                    {
                        FireInternal(subscriptions, signals[i]);
                    }
                }
            }
        }
Example #34
0
        public IActionResult GetAllDepts()
        {
            var            response = new ResponseResult <IEnumerable <DeptResult> >();
            List <SysDept> dataList = null;

            using (_dbContext)
            {
                dataList = _dbContext.SysDept.ToList();
            }
            if (dataList.IsEmpty())
            {
                return(Ok(response.Error(ResponseCode.ERROR_CODE__DB__NO_ROW, "่ฏทๅ…ˆๆทปๅŠ ๆ•ฐๆฎ")));
            }
            var menuResults = from item in dataList.Where(a => a.ParentId == 0).OrderBy(a => a.OrderNum)
                              select new DeptResult
            {
                Id           = item.Id,
                ParentId     = item.ParentId,
                Ancestors    = item.Ancestors,
                DeptName     = item.DeptName,
                OrderNum     = item.OrderNum,
                Leader       = item.Leader,
                Phone        = item.Phone,
                Email        = item.Email,
                Status       = item.Status,
                DelFlag      = item.DelFlag,
                CreateBy     = item.CreateBy,
                CreatedAt    = item.CreatedAt?.ToUtcDateTimeString(),
                UpdateBy     = item.UpdateBy,
                UpdatedAt    = item.UpdatedAt?.ToUtcDateTimeString(),
                Remark       = item.Remark,
                ChildrenList = GetChildDatas(item.Id, dataList)
            };

            return(Ok(response.Success("ๆ•ฐๆฎ่Žทๅ–ๆˆๅŠŸ", menuResults)));
        }
        private static String GetCSharpTypeConstraintsClause_Impl(this Type t, ToCSharpOptions opt)
        {
            t.IsGenericParameter.AssertTrue();
            var mods = new List <String>();

            if ((t.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) == GenericParameterAttributes.ReferenceTypeConstraint)
            {
                mods.Add("class");
            }
            if ((t.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) == GenericParameterAttributes.NotNullableValueTypeConstraint)
            {
                mods.Add("struct");
            }
            if ((t.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) == GenericParameterAttributes.DefaultConstructorConstraint)
            {
                mods.Add("new()");
            }
            var inheritance = t.GetGenericParameterConstraints();

            inheritance.ForEach(t_c => mods.Add(t_c.GetCSharpRef(opt)));

            if (mods.IsEmpty())
            {
                return(String.Empty);
            }
            else
            {
                var buffer = new StringBuilder();
                buffer.Append("    ");
                buffer.Append("where ");
                buffer.Append(t.GetCSharpRef(opt));
                buffer.Append(" : ");
                buffer.Append(mods.StringJoin());
                return(buffer.ToString());
            }
        }
Example #36
0
            private ImmutableArray <SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
            {
                var finalParts    = new List <SymbolDisplayPart>();
                var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);

                foreach (var group in orderedGroups)
                {
                    if ((groups & group) == 0)
                    {
                        continue;
                    }

                    if (!finalParts.IsEmpty())
                    {
                        var newLines = GetPrecedingNewLineCount(group);
                        finalParts.AddRange(LineBreak(newLines));
                    }

                    var parts = _groupMap[group];
                    finalParts.AddRange(parts);
                }

                return(finalParts.AsImmutable());
            }
        public IProvider CreateProvider(
            UnityEngine.Object prefab, Type resultType, GameObjectCreationParameters gameObjectBindInfo,
            List <TypeValuePair> extraArguments, object concreteIdentifier, Func <Type, IPrefabInstantiator, IProvider> providerFactory)
        {
            IPrefabInstantiator creator;

            var prefabId = new PrefabId(concreteIdentifier, prefab);

            _markRegistry.MarkSingleton(
                resultType, concreteIdentifier, SingletonTypes.FromPrefab);

            if (_prefabCreators.TryGetValue(prefabId, out creator))
            {
                // TODO: Check the arguments are the same?
                Assert.That(creator.ExtraArguments.IsEmpty() && extraArguments.IsEmpty(),
                            "Ambiguous creation parameters (arguments) when using ToPrefab with AsSingle");

                Assert.IsEqual(creator.GameObjectCreationParameters, gameObjectBindInfo,
                               "Ambiguous creation parameters (game object naming/parent info) when using ToPrefab with AsSingle");
            }
            else
            {
                creator = new PrefabInstantiatorCached(
                    new PrefabInstantiator(
                        _container, gameObjectBindInfo, resultType, extraArguments, new PrefabProvider(prefab)));

                _prefabCreators.Add(prefabId, creator);
            }

            if (resultType == typeof(GameObject))
            {
                return(new PrefabGameObjectProvider(creator));
            }

            return(providerFactory(resultType, creator));
        }
Example #38
0
        public override void GetAllInstancesWithInjectSplit(
            InjectContext context, List <TypeValuePair> args, out Action injectAction, List <object> buffer)
        {
            Assert.That(args.IsEmpty());

            Assert.IsNotNull(context);

            Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));

            // Do this even when validating in case it has its own dependencies
            var factory = Container.ResolveId(typeof(IFactory <TContract>), FactoryId);

            injectAction = null;
            if (Container.IsValidating)
            {
                // We assume here that we are creating a user-defined factory so there's
                // nothing else we can validate here
                buffer.Add(new ValidationMarker(typeof(TContract)));
            }
            else
            {
                buffer.Add(((IFactory <TContract>)factory).Create());
            }
        }
Example #39
0
        public static ICertificateBuilder WithSubjectAlternativeName(this ICertificateBuilder builder, List <string> hostnames = null, List <string> ipAddresses = null)
        {
            var result = new List <Asn1Encodable>();

            hostnames?.Select(x => new GeneralName(GeneralName.DnsName, x))
            .Select(x => x as Asn1Encodable)
            .ToList()
            .ForEach(result.Add);

            ipAddresses?.Select(x => new GeneralName(GeneralName.IPAddress, x))
            .Select(x => x as Asn1Encodable)
            .ToList()
            .ForEach(result.Add);

            if (result.IsEmpty())
            {
                return(builder);
            }

            var extension = new DerSequence(result.ToArray());

            builder.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, extension);
            return(builder);
        }
Example #40
0
        public async Task <ReturnResult> DeleteItemsAsync(IEnumerable <IStorageItemWithPath> source, bool showDialog, bool permanently, bool registerHistory)
        {
            source = await source.ToListAsync();

            var returnStatus = ReturnResult.InProgress;

            var deleteFromRecycleBin = source.Select(item => item.Path).Any(path => recycleBinHelpers.IsPathUnderRecycleBin(path));
            var canBeSentToBin       = !deleteFromRecycleBin && await recycleBinHelpers.HasRecycleBin(source.FirstOrDefault()?.Path);

            if (((!permanently && !canBeSentToBin) || UserSettingsService.PreferencesSettingsService.ShowConfirmDeleteDialog) && showDialog) // Check if the setting to show a confirmation dialog is on
            {
                var incomingItems             = new List <BaseFileSystemDialogItemViewModel>();
                List <ShellFileItem> binItems = null;
                foreach (var src in source)
                {
                    if (recycleBinHelpers.IsPathUnderRecycleBin(src.Path))
                    {
                        binItems ??= await recycleBinHelpers.EnumerateRecycleBin();

                        if (!binItems.IsEmpty())                                                        // Might still be null because we're deserializing the list from Json
                        {
                            var matchingItem = binItems.FirstOrDefault(x => x.RecyclePath == src.Path); // Get original file name
                            incomingItems.Add(new FileSystemDialogDefaultItemViewModel()
                            {
                                SourcePath = src.Path, DisplayName = matchingItem?.FileName ?? src.Name
                            });
                        }
                    }
                    else
                    {
                        incomingItems.Add(new FileSystemDialogDefaultItemViewModel()
                        {
                            SourcePath = src.Path
                        });
                    }
                }

                var dialogViewModel = FileSystemDialogViewModel.GetDialogViewModel(
                    new() { IsInDeleteMode = true },
                    (canBeSentToBin ? permanently : true, canBeSentToBin),
                    FilesystemOperationType.Delete,
                    incomingItems,
                    new());

                var dialogService = Ioc.Default.GetRequiredService <IDialogService>();

                if (await dialogService.ShowDialogAsync(dialogViewModel) != DialogResult.Primary)
                {
                    return(ReturnResult.Cancelled); // Return if the result isn't delete
                }

                // Delete selected items if the result is Yes
                permanently = dialogViewModel.DeletePermanently;
            }

            // post the status banner
            var banner = PostBannerHelpers.PostBanner_Delete(source, returnStatus, permanently, false, 0);

            banner.ErrorCode.ProgressChanged += (s, e) => returnStatus = returnStatus < ReturnResult.Failed ? e.ToStatus() : returnStatus;

            var token = banner.CancellationToken;

            var sw = new Stopwatch();

            sw.Start();

            IStorageHistory history = await filesystemOperations.DeleteItemsAsync((IList <IStorageItemWithPath>) source, banner.Progress, banner.ErrorCode, permanently, token);

            ((IProgress <float>)banner.Progress).Report(100.0f);
            await Task.Yield();

            if (!permanently && registerHistory)
            {
                App.HistoryWrapper.AddHistory(history);
            }
            var itemsDeleted = history?.Source.Count() ?? 0;

            source.ForEach(x => App.JumpList.RemoveFolder(x.Path)); // Remove items from jump list

            banner.Remove();
            sw.Stop();

            PostBannerHelpers.PostBanner_Delete(source, returnStatus, permanently, token.IsCancellationRequested, itemsDeleted);

            return(returnStatus);
        }
Example #41
0
        ////////////////////////////////////////////////////////////////////////////////
        //
        // Fixing
        //
        private bool Fix(int iParam)
        {
            Debug.Assert(IsUnfixed(iParam));

            // SPEC: An unfixed CType parameter with a set of bounds is fixed as follows:

            // SPEC:  The set of candidate types starts out as the set of all types in
            // SPEC:   the bounds.

            // SPEC:  We then examine each bound in turn. For each exact bound U of Xi,
            // SPEC:   all types which are not identical to U are removed from the candidate set.

            // Optimization: if we have two or more exact bounds, fixing is impossible.

            if (_pExactBounds[iParam].Count >= 2)
            {
                return false;
            }

            List<CType> initialCandidates = new List<CType>();

            // Optimization: if we have one exact bound then we need not add any
            // inexact bounds; we're just going to remove them anyway.

            if (_pExactBounds[iParam].IsEmpty())
            {
                HashSet<CType> typeSet = new HashSet<CType>();

                foreach (CType pCurrent in _pLowerBounds[iParam])
                {
                    if (!typeSet.Contains(pCurrent))
                    {
                        typeSet.Add(pCurrent);
                        initialCandidates.Add(pCurrent);
                    }
                }
                foreach (CType pCurrent in _pUpperBounds[iParam])
                {
                    if (!typeSet.Contains(pCurrent))
                    {
                        typeSet.Add(pCurrent);
                        initialCandidates.Add(pCurrent);
                    }
                }
            }
            else
            {
                initialCandidates.Add(_pExactBounds[iParam].Head());
            }

            if (initialCandidates.IsEmpty())
            {
                return false;
            }

            // SPEC:   For each lower bound U of Xi all types to which there is not an
            // SPEC:   implicit conversion from U are removed from the candidate set.

            foreach (CType pBound in _pLowerBounds[iParam])
            {
                List<CType> removeList = new List<CType>();
                foreach (CType pCandidate in initialCandidates)
                {
                    if (pBound != pCandidate && !_binder.canConvert(pBound, pCandidate))
                    {
                        removeList.Add(pCandidate);
                    }
                }
                foreach (CType pRemove in removeList)
                {
                    initialCandidates.Remove(pRemove);
                }
            }

            // SPEC:   For each upper bound U of Xi all types from which there is not an
            // SPEC:   implicit conversion to U are removed from the candidate set.
            foreach (CType pBound in _pUpperBounds[iParam])
            {
                List<CType> removeList = new List<CType>();
                foreach (CType pCandidate in initialCandidates)
                {
                    if (pBound != pCandidate && !_binder.canConvert(pCandidate, pBound))
                    {
                        removeList.Add(pCandidate);
                    }
                }
                foreach (CType pRemove in removeList)
                {
                    initialCandidates.Remove(pRemove);
                }
            }

            // SPEC:  If among the remaining candidate types there is a unique CType V from
            // SPEC:   which there is an implicit conversion to all the other candidate
            // SPEC:   types, then the parameter is fixed to V.

            CType pBest = null;
            foreach (CType pCandidate in initialCandidates)
            {
                foreach (CType pCandidate2 in initialCandidates)
                {
                    if (pCandidate != pCandidate2 && !_binder.canConvert(pCandidate2, pCandidate))
                    {
                        goto OuterBreak;
                    }
                }
                if (pBest != null)
                {
                    // best candidate is not unique
                    return false;
                }
                pBest = pCandidate;
            OuterBreak:
                ;
            }

            if (pBest == null)
            {
                // no best candidate
                return false;
            }

            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // RUNTIME BINDER ONLY CHANGE
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // 
            // just as we fix each individual type parameter, we need to
            // ensure that we infer accessible type parameters, and so we
            // widen them when necessary using the same technique that we
            // used to alter the types at the beginning of binding. that
            // way we get an accessible type, and if it so happens that
            // the selected type is inappropriate (for conversions) then
            // we let overload resolution sort it out. 
            //
            // since we can never infer ref/out or pointer types here, we
            // are more or less guaranteed a best accessible type. However,
            // in the interest of safety, if it becomes impossible to
            // choose a "best accessible" type, then we will fail type
            // inference so we do not try to pass the inaccessible type
            // back to overload resolution.

            CType pBestAccessible;
            if (GetTypeManager().GetBestAccessibleType(_binder.GetSemanticChecker(), _binder.GetContext(), pBest, out pBestAccessible))
            {
                pBest = pBestAccessible;
            }
            else
            {
                Debug.Assert(false, "Method type inference could not find an accessible type over the best candidate in fixed");
                return false;
            }

            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // END RUNTIME BINDER ONLY CHANGE
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            _pFixedResults[iParam] = pBest;
            UpdateDependenciesAfterFix(iParam);
            return true;
        }
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        internal IDictionary<String, Object> GetAllDocs(QueryOptions options)
        {
            var result = new Dictionary<String, Object>();
            var rows = new AList<QueryRow>();
            if (options == null)
                options = new QueryOptions();

            var includeDeletedDocs = (options.GetAllDocsMode() == AllDocsMode.IncludeDeleted);
            var updateSeq = 0L;
            if (options.IsUpdateSeq())
            {
                updateSeq = GetLastSequenceNumber();
            }

            // TODO: needs to be atomic with the following SELECT
            var sql = new StringBuilder("SELECT revs.doc_id, docid, revid, sequence");
            if (options.IsIncludeDocs())
            {
                sql.Append(", json");
            }
            if (includeDeletedDocs)
            {
                sql.Append(", deleted");
            }
            sql.Append(" FROM revs, docs WHERE");

            if (options.GetKeys() != null)
            {
                if (options.GetKeys().Count() == 0)
                {
                    return result;
                }
                var commaSeperatedIds = JoinQuotedObjects(options.GetKeys());
                sql.Append(String.Format(" revs.doc_id IN (SELECT doc_id FROM docs WHERE docid IN ({0})) AND", commaSeperatedIds));
            }
            sql.Append(" docs.doc_id = revs.doc_id AND current=1");

            if (!includeDeletedDocs)
            {
                sql.Append(" AND deleted=0");
            }

            var args = new AList<String>();
            var minKey = options.GetStartKey();
            var maxKey = options.GetEndKey();
            var inclusiveMin = true;
            var inclusiveMax = options.IsInclusiveEnd();

            if (options.IsDescending())
            {
                minKey = maxKey;
                maxKey = options.GetStartKey();
                inclusiveMin = inclusiveMax;
                inclusiveMax = true;
            }
            if (minKey != null)
            {
                Debug.Assert((minKey is String));
                sql.Append((inclusiveMin ? " AND docid >= ?" : " AND docid > ?"));
                args.AddItem((string)minKey);
            }
            if (maxKey != null)
            {
                Debug.Assert((maxKey is string));
                sql.Append((inclusiveMax ? " AND docid <= ?" : " AND docid < ?"));
                args.AddItem((string)maxKey);
            }
            sql.Append(
                String.Format(" ORDER BY docid {0}, {1} revid DESC LIMIT ? OFFSET ?", 
                    options.IsDescending() ? "DESC" : "ASC", 
                    includeDeletedDocs ? "deleted ASC," : String.Empty
                )
            );
            args.AddItem(options.GetLimit().ToString());
            args.AddItem(options.GetSkip().ToString());

            Cursor cursor = null;
            var docs = new Dictionary<String, QueryRow>();
            try
            {
                cursor = StorageEngine.RawQuery(
                    sql.ToString(),
                    CommandBehavior.SequentialAccess,
                    args.ToArray()
                );

//                cursor.MoveToNext();

                var keepGoing = cursor.MoveToNext();
                while (keepGoing)
                {
                    var docNumericID = cursor.GetLong(0);

                    var includeDocs = options.IsIncludeDocs();

                    var docId = cursor.GetString(1);
                    var revId = cursor.GetString(2);
                    var sequenceNumber = cursor.GetLong(3);
                    byte[] json = null;
                    if (includeDocs)
                    {
                        json = cursor.GetBlob(4);
                    }
                    var deleted = includeDeletedDocs && cursor.GetInt(GetDeletedColumnIndex(options)) > 0;

                    IDictionary<String, Object> docContents = null;

                    if (includeDocs)
                    {
                        docContents = DocumentPropertiesFromJSON(json, docId, revId, deleted, sequenceNumber, options.GetContentOptions());
                    }
                    // Iterate over following rows with the same doc_id -- these are conflicts.
                    // Skip them, but collect their revIDs if the 'conflicts' option is set:
                    var conflicts = new List<string>();
                    while (((keepGoing = cursor.MoveToNext())) && cursor.GetLong(0) == docNumericID)
                    {
                       if (options.GetAllDocsMode() == AllDocsMode.ShowConflicts || options.GetAllDocsMode() == AllDocsMode.OnlyConflicts)
                       {
                           if (conflicts.IsEmpty())
                           {
                               conflicts.AddItem(revId);
                           }
                           conflicts.AddItem(cursor.GetString(2));
                       }
                    }
                    if (options.GetAllDocsMode() == AllDocsMode.OnlyConflicts && conflicts.IsEmpty())
                    {
                       continue;
                    }
                    var value = new Dictionary<string, object>();
                    value["rev"] = revId;
                    value["_conflicts"] = conflicts;
                    if (includeDeletedDocs)
                    {
                        value["deleted"] = deleted;
                    }
                    var change = new QueryRow(docId, sequenceNumber, docId, value, docContents);
                    change.Database = this;

                    if (options.GetKeys() != null)
                    {
                        docs[docId] = change;
                    }
                    else
                    {
                        rows.AddItem(change);
                    }
                }
                if (options.GetKeys() != null)
                {
                    foreach (var docIdObject in options.GetKeys())
                    {
                        if (docIdObject is string)
                        {
                            var docId = (string)docIdObject;
                            var change = docs.Get(docId);
                            if (change == null)
                            {
                                var value = new Dictionary<string, object>();
                                var docNumericID = GetDocNumericID(docId);
                                if (docNumericID > 0)
                                {
                                    bool deleted;
                                    var outIsDeleted = new AList<bool>();
                                    var outIsConflict = new AList<bool>();
                                    var revId = WinningRevIDOfDoc(docNumericID, outIsDeleted, outIsConflict);
                                    if (outIsDeleted.Count > 0)
                                    {
                                        deleted = true;
                                    }
                                    if (revId != null)
                                    {
                                        value["rev"] = revId;
                                        value["deleted"] = true; // FIXME: SHould this be set the value of `deleted`?
                                    }
                                }
                                change = new QueryRow((value != null ? docId : null), 0, docId, value, null);
                                change.Database = this;
                            }
                            rows.AddItem(change);
                        }
                    }
                }
            }
            catch (SQLException e)
            {
                Log.E(Tag, "Error getting all docs", e);
                throw new CouchbaseLiteException("Error getting all docs", e, new Status(StatusCode.InternalServerError));
            }
            finally
            {
                if (cursor != null)
                    cursor.Close();
            }
            result["rows"] = rows;
            result["total_rows"] = rows.Count;
            result.Put("offset", options.GetSkip());
            if (updateSeq != 0)
            {
                result["update_seq"] = updateSeq;
            }
            return result;
        }
        void OnGUI()
        {
            var backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0.3f);

            EditorGUILayout.Separator();

            var acbPath = selectAcbAsset != null?AssetDatabase.GetAssetPath(selectAcbAsset) : null;

            if (!string.IsNullOrEmpty(acbPath))
            {
                EditorLayoutTools.DrawLabelWithBackground("CueSheet", backgroundColor);

                GUILayout.Space(5f);

                EditorGUILayout.ObjectField(selectAcbAsset, typeof(Object), false);

                EditorGUILayout.Separator();

                if (acbPath.StartsWith(resourceDir))
                {
                    var resourcePath = string.Empty;

                    resourcePath = UnityPathUtility.GetLocalPath(acbPath, resourceDir);
                    resourcePath = PathUtility.GetPathWithoutExtension(resourcePath);

                    EditorLayoutTools.DrawLabelWithBackground("Resource Path", backgroundColor);

                    GUILayout.Space(5f);

                    using (new EditorGUILayout.HorizontalScope())
                    {
                        if (GUILayout.Button("copy", GUILayout.Width(40f)))
                        {
                            GUIUtility.systemCopyBuffer = resourcePath;
                        }

                        EditorGUILayout.SelectableLabel(resourcePath, EditorStyles.textArea, GUILayout.Height(18f));
                    }
                }
            }

            if (string.IsNullOrEmpty(acbPath))
            {
                EditorGUILayout.HelpBox("Drag and drop Acb asset.", MessageType.Info);
            }

            EditorGUILayout.Separator();

            if (!string.IsNullOrEmpty(acbPath))
            {
                if (isLoaded && cueInfos != null)
                {
                    if (cueInfos.IsEmpty())
                    {
                        EditorGUILayout.HelpBox("CueSheet dont have Cue.", MessageType.Warning);
                    }
                    else
                    {
                        EditorLayoutTools.DrawLabelWithBackground("Cue", backgroundColor);

                        GUILayout.Space(5f);

                        using (var scrollViewScope = new EditorGUILayout.ScrollViewScope(scrollPosition))
                        {
                            foreach (var cueInfo in cueInfos)
                            {
                                using (new EditorGUILayout.HorizontalScope())
                                {
                                    if (GUILayout.Button("copy", GUILayout.Width(40f)))
                                    {
                                        GUIUtility.systemCopyBuffer = cueInfo.Cue;
                                    }

                                    GUIContent contentText = null;

                                    if (string.IsNullOrEmpty(cueInfo.Summary))
                                    {
                                        contentText = new GUIContent(cueInfo.Cue);
                                    }
                                    else
                                    {
                                        var tooltip = string.Format("[{0}]\n{1}", cueInfo.Cue, cueInfo.Summary);
                                        contentText = new GUIContent(cueInfo.Cue, tooltip);
                                    }

                                    GUILayout.Label(contentText, GUILayout.Height(18f));
                                }

                                GUILayout.Space(2f);
                            }

                            scrollPosition = scrollViewScope.scrollPosition;
                        }
                    }
                }

                GUILayout.FlexibleSpace();
            }

            EditorGUILayout.Separator();

            UpdateDragAndDrop();
        }
Example #44
0
        private static void RecursiveCompile(
            EvalFactoryNode evalNode,
            StatementContext context,
            ExprEvaluatorContext evaluatorContext,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            MatchEventSpec tags,
            Deque <int> subexpressionIdStack,
            Stack <EvalFactoryNode> parentNodeStack,
            ICollection <string> allTagNamesOrdered)
        {
            var counter = 0;

            parentNodeStack.Push(evalNode);
            foreach (var child in evalNode.ChildNodes)
            {
                subexpressionIdStack.AddLast(counter++);
                RecursiveCompile(
                    child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack,
                    parentNodeStack, allTagNamesOrdered);
                subexpressionIdStack.RemoveLast();
            }
            parentNodeStack.Pop();

            LinkedHashMap <string, Pair <EventType, string> > newTaggedEventTypes = null;
            LinkedHashMap <string, Pair <EventType, string> > newArrayEventTypes  = null;

            if (evalNode is EvalFilterFactoryNode)
            {
                var filterNode = (EvalFilterFactoryNode)evalNode;
                var eventName  = filterNode.RawFilterSpec.EventTypeName;
                if (context.TableService.GetTableMetadata(eventName) != null)
                {
                    throw new ExprValidationException("Tables cannot be used in pattern filter atoms");
                }

                var resolvedEventType = FilterStreamSpecRaw.ResolveType(
                    context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs);
                var finalEventType       = resolvedEventType;
                var optionalTag          = filterNode.EventAsName;
                var isPropertyEvaluation = false;
                var isParentMatchUntil   = IsParentMatchUntil(evalNode, parentNodeStack);

                // obtain property event type, if final event type is properties
                if (filterNode.RawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    var optionalPropertyEvaluator =
                        PropertyEvaluatorFactory.MakeEvaluator(
                            context.Container,
                            filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                            resolvedEventType,
                            filterNode.EventAsName,
                            context.EventAdapterService,
                            context.EngineImportService,
                            context.SchedulingService,
                            context.VariableService,
                            context.ScriptingService,
                            context.TableService,
                            context.EngineURI,
                            context.StatementId,
                            context.StatementName,
                            context.Annotations,
                            subexpressionIdStack,
                            context.ConfigSnapshot,
                            context.NamedWindowMgmtService,
                            context.StatementExtensionServicesContext);
                    finalEventType       = optionalPropertyEvaluator.FragmentEventType;
                    isPropertyEvaluation = true;
                }

                if (finalEventType is EventTypeSPI)
                {
                    eventTypeReferences.Add(((EventTypeSPI)finalEventType).Metadata.PrimaryName);
                }

                // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
                if (optionalTag != null)
                {
                    var       pair         = tags.TaggedEventTypes.Get(optionalTag);
                    EventType existingType = null;
                    if (pair != null)
                    {
                        existingType = pair.First;
                    }
                    if (existingType == null)
                    {
                        pair = tags.ArrayEventTypes.Get(optionalTag);
                        if (pair != null)
                        {
                            throw new ExprValidationException(
                                      "Tag '" + optionalTag + "' for event '" + eventName +
                                      "' used in the repeat-until operator cannot also appear in other filter expressions");
                        }
                    }
                    if ((existingType != null) && (existingType != finalEventType))
                    {
                        throw new ExprValidationException(
                                  "Tag '" + optionalTag + "' for event '" + eventName +
                                  "' has already been declared for events of type " + existingType.UnderlyingType.FullName);
                    }
                    pair = new Pair <EventType, string>(finalEventType, eventName);

                    // add tagged type
                    if (isPropertyEvaluation || isParentMatchUntil)
                    {
                        newArrayEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newArrayEventTypes.Put(optionalTag, pair);
                    }
                    else
                    {
                        newTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newTaggedEventTypes.Put(optionalTag, pair);
                    }
                }

                // For this filter, filter types are all known tags at this time,
                // and additionally stream 0 (self) is our event type.
                // Stream type service allows resolution by property name event if that name appears in other tags.
                // by defaulting to stream zero.
                // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
                var selfStreamName = optionalTag;
                if (selfStreamName == null)
                {
                    selfStreamName = "s_" + UuidGenerator.Generate();
                }
                var filterTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                var typePair    = new Pair <EventType, string>(finalEventType, eventName);
                filterTypes.Put(selfStreamName, typePair);
                filterTypes.PutAll(tags.TaggedEventTypes);

                // for the filter, specify all tags used
                var filterTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(tags.TaggedEventTypes);
                filterTaggedEventTypes.Remove(optionalTag);

                // handle array tags (match-until clause)
                LinkedHashMap <string, Pair <EventType, string> > arrayCompositeEventTypes = null;
                if (tags.ArrayEventTypes != null && !tags.ArrayEventTypes.IsEmpty())
                {
                    arrayCompositeEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                    var patternSubexEventType = GetPatternSubexEventType(
                        context.StatementId, "pattern", subexpressionIdStack);

                    foreach (var entry in tags.ArrayEventTypes)
                    {
                        var specificArrayType = new LinkedHashMap <string, Pair <EventType, string> >();
                        specificArrayType.Put(entry.Key, entry.Value);
                        var arrayTagCompositeEventType =
                            context.EventAdapterService.CreateSemiAnonymousMapType(
                                patternSubexEventType, Collections.GetEmptyMap <string, Pair <EventType, string> >(),
                                specificArrayType, isInsertInto);
                        context.StatementSemiAnonymousTypeRegistry.Register(arrayTagCompositeEventType);

                        var tag = entry.Key;
                        if (!filterTypes.ContainsKey(tag))
                        {
                            var pair = new Pair <EventType, string>(arrayTagCompositeEventType, tag);
                            filterTypes.Put(tag, pair);
                            arrayCompositeEventTypes.Put(tag, pair);
                        }
                    }
                }

                StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                    filterTypes, context.EngineURI, true, false);
                var exprNodes = filterNode.RawFilterSpec.FilterExpressions;

                var spec = FilterSpecCompiler.MakeFilterSpec(
                    resolvedEventType, eventName, exprNodes,
                    filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                    filterTaggedEventTypes,
                    arrayCompositeEventTypes,
                    streamTypeService,
                    null, context, subexpressionIdStack);
                filterNode.FilterSpec = spec;
            }
            else if (evalNode is EvalObserverFactoryNode)
            {
                var observerNode = (EvalObserverFactoryNode)evalNode;
                try
                {
                    var observerFactory = context.PatternResolutionService.Create(observerNode.PatternObserverSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "observer", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNOBSERVER, observerNode.PatternObserverSpec.ObjectParameters,
                        validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    observerNode.ObserverFactory = observerFactory;
                    observerFactory.SetObserverParameters(validated, convertor, validationContext);
                }
                catch (ObserverParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " +
                              e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message,
                              e);
                }
            }
            else if (evalNode is EvalGuardFactoryNode)
            {
                var guardNode = (EvalGuardFactoryNode)evalNode;
                try
                {
                    var guardFactory = context.PatternResolutionService.Create(guardNode.PatternGuardSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "guard", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNGUARD, guardNode.PatternGuardSpec.ObjectParameters, validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    guardNode.GuardFactory = guardFactory;
                    guardFactory.SetGuardParameters(validated, convertor);
                }
                catch (GuardParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
            }
            else if (evalNode is EvalEveryDistinctFactoryNode)
            {
                var distinctNode             = (EvalEveryDistinctFactoryNode)evalNode;
                var matchEventFromChildNodes = AnalyzeMatchEvent(distinctNode);
                var streamTypeService        = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                    subexpressionIdStack, "every-distinct", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);
                IList <ExprNode> validated;
                try
                {
                    validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNEVERYDISTINCT, distinctNode.Expressions, validationContext);
                }
                catch (ExprValidationPropertyException ex)
                {
                    throw new ExprValidationPropertyException(
                              ex.Message +
                              ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                              ex.InnerException);
                }

                MatchedEventConvertor convertor =
                    new MatchedEventConvertorImpl(
                        matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                        allTagNamesOrdered, context.EventAdapterService);

                distinctNode.Convertor = convertor;

                // Determine whether some expressions are constants or time period
                IList <ExprNode>             distinctExpressions  = new List <ExprNode>();
                ExprTimePeriodEvalDeltaConst timeDeltaComputation = null;
                ExprNode expiryTimeExp = null;
                var      count         = -1;
                var      last          = validated.Count - 1;
                foreach (var expr in validated)
                {
                    count++;
                    if (count == last && expr is ExprTimePeriod)
                    {
                        expiryTimeExp = expr;
                        var timePeriodExpr = (ExprTimePeriod)expiryTimeExp;
                        timeDeltaComputation =
                            timePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(context, false));
                    }
                    else if (expr.IsConstantResult)
                    {
                        if (count == last)
                        {
                            var evaluateParams = new EvaluateParams(null, true, evaluatorContext);
                            var value          = expr.ExprEvaluator.Evaluate(evaluateParams);
                            if (!(value.IsNumber()))
                            {
                                throw new ExprValidationException(
                                          "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)");
                            }

                            var secondsExpire = expr.ExprEvaluator.Evaluate(evaluateParams);

                            long?timeExpire;
                            if (secondsExpire == null)
                            {
                                timeExpire = null;
                            }
                            else
                            {
                                timeExpire = context.TimeAbacus.DeltaForSecondsNumber(secondsExpire);
                            }

                            if (timeExpire != null && timeExpire > 0)
                            {
                                timeDeltaComputation = new ExprTimePeriodEvalDeltaConstGivenDelta(timeExpire.Value);
                                expiryTimeExp        = expr;
                            }
                            else
                            {
                                Log.Warn("Invalid seconds-expire " + timeExpire + " for " + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr));
                            }
                        }
                        else
                        {
                            Log.Warn(
                                "Every-distinct node utilizes an expression returning a constant value, please check expression '{0}', not adding expression to distinct-value expression list",
                                expr.ToExpressionStringMinPrecedenceSafe());
                        }
                    }
                    else
                    {
                        distinctExpressions.Add(expr);
                    }
                }
                if (distinctExpressions.IsEmpty())
                {
                    throw new ExprValidationException(
                              "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
                }
                distinctNode.SetDistinctExpressions(distinctExpressions, timeDeltaComputation, expiryTimeExp);
            }
            else if (evalNode is EvalMatchUntilFactoryNode)
            {
                var matchUntilNode = (EvalMatchUntilFactoryNode)evalNode;

                // compile bounds expressions, if any
                var untilMatchEventSpec = new MatchEventSpec(tags.TaggedEventTypes, tags.ArrayEventTypes);
                var streamTypeService   = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, subexpressionIdStack,
                    "until", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                var lower = ValidateBounds(matchUntilNode.LowerBounds, validationContext);
                matchUntilNode.LowerBounds = lower;

                var upper = ValidateBounds(matchUntilNode.UpperBounds, validationContext);
                matchUntilNode.UpperBounds = upper;

                var single = ValidateBounds(matchUntilNode.SingleBound, validationContext);
                matchUntilNode.SingleBound = single;

                var convertor = new MatchedEventConvertorImpl(
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, allTagNamesOrdered,
                    context.EventAdapterService);
                matchUntilNode.Convertor = convertor;

                // compile new tag lists
                ISet <string> arrayTags = null;
                var           matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes)
                {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null)
                    {
                        if (arrayTags == null)
                        {
                            arrayTags = new HashSet <string>();
                        }
                        arrayTags.Add(optionalTag);
                    }
                }

                if (arrayTags != null)
                {
                    foreach (var arrayTag in arrayTags)
                    {
                        if (!tags.ArrayEventTypes.ContainsKey(arrayTag))
                        {
                            tags.ArrayEventTypes.Put(arrayTag, tags.TaggedEventTypes.Get(arrayTag));
                            tags.TaggedEventTypes.Remove(arrayTag);
                        }
                    }
                }
                matchUntilNode.TagsArrayed = GetIndexesForTags(allTagNamesOrdered, arrayTags);
            }
            else if (evalNode is EvalFollowedByFactoryNode)
            {
                var followedByNode = (EvalFollowedByFactoryNode)evalNode;
                StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.EngineURI, false);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService,
                    evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                if (followedByNode.OptionalMaxExpressions != null)
                {
                    IList <ExprNode> validated = new List <ExprNode>();
                    foreach (var maxExpr in followedByNode.OptionalMaxExpressions)
                    {
                        if (maxExpr == null)
                        {
                            validated.Add(null);
                        }
                        else
                        {
                            var visitor = new ExprNodeSummaryVisitor();
                            maxExpr.Accept(visitor);
                            if (!visitor.IsPlain)
                            {
                                var errorMessage = "Invalid maximum expression in followed-by, " + visitor.GetMessage() +
                                                   " are not allowed within the expression";
                                Log.Error(errorMessage);
                                throw new ExprValidationException(errorMessage);
                            }

                            var validatedExpr = ExprNodeUtility.GetValidatedSubtree(
                                ExprNodeOrigin.FOLLOWEDBYMAX, maxExpr, validationContext);
                            validated.Add(validatedExpr);
                            if ((validatedExpr.ExprEvaluator.ReturnType == null) ||
                                (!validatedExpr.ExprEvaluator.ReturnType.IsNumeric()))
                            {
                                var message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                                throw new ExprValidationException(message);
                            }
                        }
                    }
                    followedByNode.OptionalMaxExpressions = validated;
                }
            }

            if (newTaggedEventTypes != null)
            {
                tags.TaggedEventTypes.PutAll(newTaggedEventTypes);
            }
            if (newArrayEventTypes != null)
            {
                tags.ArrayEventTypes.PutAll(newArrayEventTypes);
            }
        }
Example #45
0
        private void ProcessGrandTenantTree(List<ETenant> ds, string superTenantID, List<ETenant> res)
        {
            if (ds.IsEmpty())
                return;

            var grand = ds.Find(p => !string.IsNullOrEmpty(p.TenantName) && p.TenantCode.Equals(superTenantID, StringComparison.CurrentCultureIgnoreCase));

            if (grand != null)
            {
                res.Add(grand);
                if (!string.IsNullOrEmpty(grand.SuperTenantID))
                {
                    ProcessGrandTenantTree(ds, grand.SuperTenantID, res);
                }
            }
        }
Example #46
0
        /// <summary>
        /// Loads user settings from the NuGet configuration files. The method walks the directory
        /// tree in <paramref name="fileSystem"/> up to its root, and reads each NuGet.config file
        /// it finds in the directories. It then reads the user specified <paramref name="configFileName"/>
        /// in <paramref name="fileSystem"/> if <paramref name="configFileName"/> is not null. 
        /// If <paramref name="configFileName"/> is null, file %AppData%\NuGet\NuGet.config is loaded.
        /// </summary>
        /// <remarks>
        /// For example, if <paramref name="fileSystem"/> is c:\dir1\dir2, <paramref name="configFileName"/> 
        /// is "userConfig.file", the files loaded are (in the order that they are loaded):
        ///     c:\dir1\dir2\nuget.config
        ///     c:\dir1\nuget.config
        ///     c:\nuget.config
        ///     c:\dir1\dir2\userConfig.file
        /// </remarks>
        /// <param name="fileSystem">The file system to walk to find configuration files.</param>
        /// <param name="configFileName">The user specified configuration file.</param>
        /// <returns>The settings object loaded.</returns>
        public static ISettings LoadDefaultSettings(
            IFileSystem fileSystem,
            string configFileName)
        {
            // Walk up the tree to find a config file; also look in .nuget subdirectories
            var validSettingFiles = new List<Settings>();
            if (fileSystem != null)
            {
                validSettingFiles.AddRange(
                    GetSettingsFileNames(fileSystem)
                        .Select(f => ReadSettings(fileSystem, f))
                        .Where(f => f != null));
            }

            // for the default location, allow case where file does not exist, in which case it'll end
            // up being created if needed
            Settings appDataSettings = null;
            if (configFileName == null)
            {
                // load %AppData%\NuGet\NuGet.config
                string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                if (!String.IsNullOrEmpty(appDataPath))
                {
                    var defaultSettingsPath = Path.Combine(appDataPath, "NuGet");
                    appDataSettings = ReadSettings(new PhysicalFileSystem(defaultSettingsPath),
                        Constants.SettingsFileName);
                }
            }
            else
            {
                appDataSettings = ReadSettings(fileSystem, configFileName);
            }
            if (appDataSettings != null)
            {
                validSettingFiles.Add(appDataSettings);
            }

            if (validSettingFiles.IsEmpty())
            {
                // This means we've failed to load all config files and also failed to load or create the one in %AppData%
                // Work Item 1531: If the config file is malformed and the constructor throws, NuGet fails to load in VS. 
                // Returning a null instance prevents us from silently failing and also from picking up the wrong config
                return NullSettings.Instance;
            }

            // if multiple setting files were loaded, chain them in a linked list
            for (int i = 1; i < validSettingFiles.Count; ++i)
            {
                validSettingFiles[i]._next = validSettingFiles[i - 1];
            }

            // return the linked list head, typically %APPDATA%\NuGet\nuget.config
            // This is the one we want to read first, and also the one that we want to write to
            // TODO: add UI to allow specifying which one to write to
            return validSettingFiles.Last();
        }
Example #47
0
        /// <summary>
        /// Loads user settings from the NuGet configuration files. The method walks the directory
        /// tree in <paramref name="fileSystem"/> up to its root, and reads each NuGet.config file
        /// it finds in the directories. It then reads the user specific settings,
        /// which is file <paramref name="configFileName"/>
        /// in <paramref name="fileSystem"/> if <paramref name="configFileName"/> is not null,
        /// If <paramref name="configFileName"/> is null, the user specific settings file is
        /// %AppData%\NuGet\NuGet.config.
        /// After that, the machine wide settings files are added.
        /// </summary>
        /// <remarks>
        /// For example, if <paramref name="fileSystem"/> is c:\dir1\dir2, <paramref name="configFileName"/> 
        /// is "userConfig.file", the files loaded are (in the order that they are loaded):
        ///     c:\dir1\dir2\nuget.config
        ///     c:\dir1\nuget.config
        ///     c:\nuget.config
        ///     c:\dir1\dir2\userConfig.file
        ///     machine wide settings (e.g. c:\programdata\NuGet\Config\*.config)
        /// </remarks>
        /// <param name="fileSystem">The file system to walk to find configuration files.</param>
        /// <param name="configFileName">The user specified configuration file.</param>
        /// <param name="machineWideSettings">The machine wide settings. If it's not null, the
        /// settings files in the machine wide settings are added after the user sepcific 
        /// config file.</param>
        /// <returns>The settings object loaded.</returns>
        public static ISettings LoadDefaultSettings(
            IFileSystem fileSystem,
            string configFileName,
            IMachineWideSettings machineWideSettings)
        {
            // Walk up the tree to find a config file; also look in .nuget subdirectories
            var validSettingFiles = new List<Settings>();
            #if DNX451
            var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            #else
            var appData = Environment.GetEnvironmentVariable("APPDATA");
            #endif
            var redirectSettingsPath = Path.Combine(appData,
                                                    "nuget",
                                                    "nuget.redirect.config");

            Settings redirectSettings = null;
            if (fileSystem != null)
            {
                validSettingFiles.AddRange(
                    GetSettingsFileNames(fileSystem)
                        .Select(f => ReadSettings(fileSystem, f))
                        .Where(f => f != null));

                if (fileSystem.FileExists(redirectSettingsPath))
                {
                    redirectSettings = ReadSettings(fileSystem, redirectSettingsPath);
                }
            }

            LoadUserSpecificSettings(validSettingFiles, fileSystem, configFileName);

            if (machineWideSettings != null)
            {
                validSettingFiles.AddRange(
                    machineWideSettings.Settings.Select(
                        s => new Settings(s._fileSystem, s._fileName, s._isMachineWideSettings)));
            }

            if (validSettingFiles.IsEmpty())
            {
                // This means we've failed to load all config files and also failed to load or create the one in %AppData%
                // Work Item 1531: If the config file is malformed and the constructor throws, NuGet fails to load in VS.
                // Returning a null instance prevents us from silently failing and also from picking up the wrong config
                return NullSettings.Instance;
            }

            validSettingFiles[0]._redirect = redirectSettings;

            // if multiple setting files were loaded, chain them in a linked list
            for (int i = 1; i < validSettingFiles.Count; ++i)
            {
                validSettingFiles[i]._next = validSettingFiles[i - 1];
                validSettingFiles[i]._redirect = redirectSettings;
            }

            // return the linked list head. Typicall, it's either the config file in %ProgramData%\NuGet\Config,
            // or the user specific config (%APPDATA%\NuGet\nuget.config) if there are no machine
            // wide config files. The head file is the one we want to read first, while the user specific config
            // is the one that we want to write to.
            // TODO: add UI to allow specifying which one to write to
            return validSettingFiles.Last();
        }
Example #48
0
        private void ProcessTenantTree(List<ETenant> ds, string superTenantID, List<ETenant> res)
        {
            if (ds.IsEmpty())
                return;

            var _tList = ds.FindAll(p => !string.IsNullOrEmpty(p.TenantName) && p.SuperTenantID.Equals(superTenantID, StringComparison.CurrentCultureIgnoreCase));
            res.AddRange(_tList);
            var ltCode = (from o in _tList
                          where o.TenantType == EnumTenantType.OperatingMerchant
                          select o.TenantCode).ToList();
            foreach (var item in ltCode)
            {
                ProcessTenantTree(ds, item, res);
            }
        }
Example #49
0
        private bool StartAllTasks()
        {
            _tasksToStart.Clear();

            var enabledTasks = Tasks.Where(s => s.Settings.IsEnabled).ToArray();

            if (enabledTasks.Length > 0)
            {
                foreach (var task in enabledTasks)
                {
                    task.AddInfoLog(LocalizedStrings.Str2906);

                    if (task.Settings.Securities.IsEmpty())
                    {
                        task.AddInfoLog(LocalizedStrings.Str2907);
                        continue;
                    }

                    _tasksToStart.Add(task);
                }
            }

            if (_tasksToStart.IsEmpty())
            {
                return(false);
            }

            foreach (var task in _tasksToStart)
            {
                task.Started += OnStartedTask;
                task.Stopped += OnStopedTask;

                task.Start();
            }

            // TODO
            //// ะณั€ัƒะฟะฟะธั€ะพะฒะบะฐ ะฟะพ "ะบะพั€ะฝัะผ"
            //foreach (var taskGroup in _tasksToStart.GroupBy(t =>
            //{
            //	while (t.Settings.DependFrom != null)
            //		t = t.Settings.DependFrom;

            //	return t.Id;
            //}))
            //{
            //	var tasks = new CachedSynchronizedSet<IHydraTask>();
            //	tasks.AddRange(taskGroup);

            //	ThreadingHelper.Thread(() =>
            //	{
            //		try
            //		{
            //			foreach (var task in tasks.Cache)
            //			{
            //				task.Start();

            //				if (task.State != TaskStates.Started)
            //					tasks.Remove(task);
            //			}

            //			while (true)
            //			{
            //				if (tasks.Cache.Length == 0)
            //					break;

            //				foreach (var task in tasks.Cache)
            //				{
            //					task.Process();

            //					if (task.)
            //				}
            //			}
            //		}
            //		catch (Exception ex)
            //		{
            //			_logManager.Application.AddErrorLog(ex);
            //		}
            //	})
            //	.Name("{0} Task thread".Put(Name))
            //	.Launch();
            //}

            return(true);
        }
Example #50
0
        public ProgramTask()
        {
            Monitor.ClientSize = new Size(640, 480);
            ColoredChessboard = new ColoredChessboard(Chessboard, Color.CornflowerBlue.Alpha(0.9f), Color.Orange.Alpha(0.3f));

            var maybeSecondaryScreen = Screen.AllScreens.Where(s => s != Screen.PrimaryScreen).FirstOrDefault() ?? Screen.PrimaryScreen;

            // Projector = new RealProjector("Optoma EW1610", "1018", maybeSecondaryScreen.Bounds.Size, maybeSecondaryScreen);
            var virtualProjectorOrbit = new OrbitCamera("Virtual Projector Orbit", "N/A", new Size(1280, 800), new PointF(640, 850), 100, 2, 134);
            Projector = new VirtualProjector(Monitor, virtualProjectorOrbit);

            WorldCamera = new OrbitCamera("World Orbit", "1018", Monitor.Size, Monitor.Size.CenterF(), Monitor.Size.Width, 0.1f, 100)
            {
                Center = Chessboard.VertexCenter,
                Distance = 56,
                YawPitch = new Vector2(0.2f, -0.2f),
            };

            WorldScene = new Scene(WorldCamera)
            {
                // MakeColoredAxisOfLength(Vector3.UnitX, Color.Red, length: 20.0f),
                // MakeColoredAxisOfLength(Vector3.UnitY, Color.Green, length: 20.0f),
                // MakeColoredAxisOfLength(Vector3.UnitZ, Color.Blue, length: 20.0f),
                
                // ColoredChessboard,

                // new Grid(Matrix.CreateRotationX(MathHelper.PiOver2),  Color.Red.Lerp(Color.White, 0.9f).Alpha(0.3f), Color.Red.Alpha(0.5f)),
                // new Grid(Matrix.CreateRotationY(-MathHelper.PiOver2), Color.Green.Lerp(Color.White, 0.9f).Alpha(0.1f), Color.Green.Alpha(0.3f)),
                // new Grid(Matrix.Identity,                             Color.Blue.Lerp(Color.White, 0.9f).Alpha(0.1f), Color.Blue.Alpha(0.4f)),

                new MeshModel("ManStanding", Matrix.CreateScale(0.1f) * Matrix.CreateRotationY(-MathHelper.PiOver2) * Matrix.CreateTranslation(4, 0, 2)) { ProjectorViewProject = Projector },
                new MeshModel("MutantStanding", Matrix.CreateScale(0.4f) * Matrix.CreateRotationY(0) * Matrix.CreateTranslation(8, 0, 1)) { ProjectorViewProject = Projector },
                new MeshModel("HeadFemale", Matrix.CreateScale(0.2f) * Matrix.CreateRotationX(-MathHelper.PiOver2) * Matrix.CreateTranslation(-3, 6, 0)) { ProjectorViewProject = Projector },
            };

            CaptureCameras = CreateCaptureCameras().ToList();
            if (CaptureCameras.IsEmpty())
                AddVirtualCaptureCamera("VirCam 1", "1018", Color.Red);

            CaptureCameraSelectionPictureGray = new Picture2D(CaptureCameraSelected.Intrinsics.ImageSize.LimitProportional(290, 290).AnchorWithin(Monitor.ClientRectangle, AnchorPoints.BottomLeft), CaptureCameraSelected.Capture.GrayTexture2D);
            CaptureCameraSelectionPictureRgba = new Picture2D(CaptureCameraSelected.Intrinsics.ImageSize.LimitProportional(290, 290).ToRect(CaptureCameraSelectionPictureGray.Rectangle.Left, CaptureCameraSelectionPictureGray.Rectangle.Top, AnchorPoints.BottomLeft), CaptureCameraSelected.Capture.RgbaTexture2D);
            CaptureCameraSelected.Highlight = true;

            WorldScene.Add(CaptureCameras);
            WorldScene.Add(Projector);

            Monitor.Scene = new Scene(new ScreenCamera(Monitor))
            {
                new Clear(Color.LightGray),
                WorldScene,
                CaptureCameraSelectionPictureGray,
                CaptureCameraSelectionPictureRgba,
            };

            LocateTrigger = new Trigger(() => new LocateTask(Monitor, CaptureCameraSelected, Chessboard).Run(), Keys.L);
            CalibrateTrigger = new Trigger(() => new CalibrateTask(Monitor, CaptureCameraSelected, Chessboard).Run(CaptureCameraSelected), Keys.C);
            ChessboardShapeTrigger = new Trigger(() => new ChessboardShapeTask(Monitor, Projector, Chessboard).Run(), Keys.S);
            CalibrateIndirectlyTrigger = new Trigger(() => { WorldScene.Remove(ColoredChessboard); return new CalibrateIndirectlyTask(Monitor, CaptureCameras, Projector, Chessboard).Run(WorldScene); }, Keys.I);
            GrayScanTrigger = new Trigger(() => new GrayScanTask(Monitor, CaptureCameras.First(), Projector).Run(WorldScene), Keys.G);

            AttachInputToCamera(Program.WhenInput.Where(input => !input.KeyPressed(Keys.LeftAlt)), Monitor, WorldCamera);
            AttachInputToCamera(Program.WhenInput.Where(input => input.KeyPressed(Keys.LeftAlt)), Monitor, virtualProjectorOrbit);

            AttachPerformanceBar();

            Program.WhenInput.Where(input => input.KeyDown(Keys.Tab)).Subscribe(input =>
                {
                    CaptureCameraSelected.Highlight = false;
                    CaptureCameraSelectionIdx = (CaptureCameraSelectionIdx + 1) % CaptureCameras.Count;
                    CaptureCameraSelected.Highlight = true;
                    CaptureCameraSelectionPictureGray.Texture2D = CaptureCameraSelected.Capture.GrayTexture2D;
                    CaptureCameraSelectionPictureRgba.Texture2D = CaptureCameraSelected.Capture.RgbaTexture2D;

                });
        }
        public ViewModelFormAddSalonToEmploye(List<Salon> salons)
        {
            if (salons.IsEmpty())
            {
                Salons = new List<SelectListItem>();
                return;
            }

            Salons = salons.Select(s => new SelectListItem
            {
                Value = s.Id.ToString(), Text = s.FicheSalon.Nom
            }).ToList();
        }
Example #52
0
		public Task<bool> DeleteAssets (List<PHAsset> assets)
		{
			var tcs = new TaskCompletionSource<bool> ();

			if (assets.IsEmpty()) tcs.TrySetResult(false);

			PHPhotoLibrary.RequestAuthorization(status => {

				if (status == PHAuthorizationStatus.Authorized) {

					PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => 

						PHAssetChangeRequest.DeleteAssets(assets.ToArray()), (success, error) => {
						
						if (!tcs.TrySetResult(success)) {
							var ex = new Exception ("DeleteAssets Failed");
							tcs.TrySetException(ex);
							// Log.Error(ex);
						}
					});
					
				} else {
					var ex = new Exception ("Unauthorized");
					tcs.TrySetException(ex);
					// Log.Error(ex);
				}
			});

			return tcs.Task;
		}
Example #53
0
        public override void MouseDown(object sender, MouseButtonEventArgs e)
        {
#if !SILVERLIGHT
            if (e.ClickCount == 2)
            {
                Drawing.CoordinateSystem.ZoomExtend();
                return;
            }
#endif
            offsetFromFigureLeftTopCorner = Coordinates(e, false, false, false);
            oldCoordinates         = offsetFromFigureLeftTopCorner;
            coordinatesOnMouseDown = offsetFromFigureLeftTopCorner;
            startedMoving          = false;

            moving = new List <IMovable>();
            IEnumerable <IFigure> roots = null;
            bool isLocked = false;

            found = Drawing.Figures.HitTest(offsetFromFigureLeftTopCorner);

            IMovable oneMovable = found as IMovable;
            if (oneMovable != null && (found.Locked || oneMovable.AllowMove()))
            {
                if (found.Locked)
                {
                    isLocked = true;
                }
                else if (oneMovable.AllowMove())
                {
                    if (oneMovable is IPoint)
                    {
                        // when we drag a point, we want it to snap to the cursor
                        // so that the point center is directly under the tip of the mouse
                        offsetFromFigureLeftTopCorner = new Point();
                        oldCoordinates = oneMovable.Coordinates;
                    }
                    else
                    {
                        // however when we drag other stuff (such as text labels)
                        // we want the mouse to always touch the part of the draggable
                        // where it first touched during MouseDown
                        // we don't want the draggable to "snap" to the cursor like points do
                        offsetFromFigureLeftTopCorner = offsetFromFigureLeftTopCorner.Minus(oneMovable.Coordinates);
                    }
                    roots = DependencyAlgorithms.FindRoots(f => f.Dependents, found);
                    if (roots.All(root => (!root.Locked)))
                    {
                        moving.Add(oneMovable);
                        roots = found.AsEnumerable();
                    }
                    else
                    {
                        isLocked = true;
                    }
                }
            }
            else if (found != null)
            {
                if (!found.Locked)
                {
                    roots = DependencyAlgorithms.FindRoots(f => f.Dependencies, found);
                    if (roots.All(root => root is IMovable))
                    {
                        if (roots.All(root => ((IMovable)root).AllowMove()))
                        {
                            moving.AddRange(roots.OfType <IMovable>());
                        }
                        else
                        {
                            isLocked = true;
                        }
                    }
                }
                else
                {
                    isLocked = true;
                }
            }

            if (roots != null)
            {
                toRecalculate = DependencyAlgorithms.FindDescendants(f => f.Dependents, roots);
                toRecalculate.Reverse();
            }
            else
            {
                toRecalculate = null;
            }

            if (moving.IsEmpty() && !isLocked && !Drawing.CoordinateGrid.Locked)
            {
                moving.Add(Drawing.CoordinateSystem);
                //var allFigures = Drawing.Figures.GetAllFiguresRecursive();
                //roots = DependencyAlgorithms.FindRoots(f => f.Dependencies, allFigures);
                //moving.AddRange(roots.OfType<IMovable>());
                //roots = null;
                toRecalculate = null; // Figures;
            }
        }
 public bool SetTypePrestation(List<TypePrestation> liste = null)
 {
     try
     {
         if (liste.IsEmpty()) return false;
         TypePrestations = new MultiSelectList(liste, "Id", "Nom");
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #55
0
        private void OnFileChanged(object source, FileSystemEventArgs e)
        {
            try
            {
				string strings;

                using (var fs = new FileStream(_tranFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (var sr = new StreamReader(fs))
                    strings = sr.ReadToEnd();

                if (string.IsNullOrEmpty(strings))
                    return;

                var lines = strings.Split(_endOfLine);

                var newlines = new List<string>();

                if (_lastTranId > 0)
                {
                    for (var i = lines.Count() - 1; i >= 0; i--)
                    {
                        if (!lines[i].Contains(_endOfLine))
                            continue;

                        var id = GetTransId(lines[i]);

                        if (id > _lastTranId)
                            newlines.Add(lines[i]);
                        else
                        {
                            if (newlines.IsEmpty())
                                return;
                        }
                    }

                    newlines.Reverse();
                }
                else
                    newlines.AddRange(lines.Where(l => l.Contains(_endOfLine)));

                NewLinesParsing(newlines);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Stop();
            }
        }
Example #56
0
        private BoundSwitchLabel BindSwitchSectionLabel(SwitchLabelSyntax node, Binder sectionBinder, DiagnosticBag diagnostics)
        {
            var switchGoverningType = GetSwitchGoverningType(diagnostics);
            BoundExpression boundLabelExpressionOpt = null;

            SourceLabelSymbol boundLabelSymbol = null;
            ConstantValue labelExpressionConstant = null;
            List<SourceLabelSymbol> matchedLabelSymbols;

            // Prevent cascading diagnostics
            bool hasErrors = node.HasErrors;

            switch (node.Kind())
            {
                case SyntaxKind.CaseSwitchLabel:
                var caseLabelSyntax = (CaseSwitchLabelSyntax)node;
                // Bind the label case expression
                boundLabelExpressionOpt = sectionBinder.BindValue(caseLabelSyntax.Value, diagnostics, BindValueKind.RValue);

                boundLabelExpressionOpt = ConvertCaseExpression(switchGoverningType, caseLabelSyntax, boundLabelExpressionOpt, sectionBinder, ref labelExpressionConstant, diagnostics);

                // Check for bind errors
                hasErrors = hasErrors || boundLabelExpressionOpt.HasAnyErrors;


                // SPEC:    The constant expression of each case label must denote a value that
                // SPEC:    is implicitly convertible (ยง6.1) to the governing type of the switch statement.

                // Prevent cascading diagnostics
                if (!hasErrors && labelExpressionConstant == null)
                {
                    diagnostics.Add(ErrorCode.ERR_ConstantExpected, caseLabelSyntax.Location);
                    hasErrors = true;
                }

                // LabelSymbols for all the switch case labels are created by BuildLabels().
                // Fetch the matching switch case label symbols
                matchedLabelSymbols = FindMatchingSwitchCaseLabels(labelExpressionConstant, caseLabelSyntax);
                    break;
                case SyntaxKind.CasePatternSwitchLabel:
                    // pattern matching in case is not yet implemented.
                    if (!node.HasErrors)
                    {
                        Error(diagnostics, ErrorCode.ERR_FeatureIsUnimplemented, node, MessageID.IDS_FeaturePatternMatching.Localize());
                        hasErrors = true;
                    }
                    matchedLabelSymbols = new List<SourceLabelSymbol>();
                    break;
                case SyntaxKind.DefaultSwitchLabel:
                matchedLabelSymbols = GetDefaultLabels();
                    break;
                default:
                    throw ExceptionUtilities.Unreachable;
            }

            // Get the corresponding matching label symbol created during BuildLabels()
            // and also check for duplicate case labels.

            Debug.Assert(hasErrors || !matchedLabelSymbols.IsEmpty());
            bool first = true;
            bool hasDuplicateErrors = false;
            foreach (SourceLabelSymbol label in matchedLabelSymbols)
            {
                if (node.Equals(label.IdentifierNodeOrToken.AsNode()))
                {
                    // we must have exactly one matching label created during BuildLabels()
                    boundLabelSymbol = label;

                    // SPEC:    A compile-time error occurs if two or more case labels
                    // SPEC:    in the same switch statement specify the same constant value.

                    if (!hasErrors && !first)
                    {
                        // Skipping the first label symbol ensures that the errors (if any),
                        // are reported on all but the first duplicate case label.
                        diagnostics.Add(ErrorCode.ERR_DuplicateCaseLabel, node.Location,
                            label.SwitchCaseLabelConstant?.Value ?? label.Name);
                        hasDuplicateErrors = true;
                    }
                    break;
                }
                first = false;
            }

            if ((object)boundLabelSymbol == null)
            {
                Debug.Assert(hasErrors);
                boundLabelSymbol = new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, node, labelExpressionConstant);
            }

            return new BoundSwitchLabel(
                syntax: node,
                label: boundLabelSymbol,
                expressionOpt: boundLabelExpressionOpt,
                hasErrors: hasErrors || hasDuplicateErrors);
        }
            private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
            {
                var finalParts = new List<SymbolDisplayPart>();
                var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);

                foreach (var group in orderedGroups)
                {
                    if ((groups & group) == 0)
                    {
                        continue;
                    }

                    if (!finalParts.IsEmpty())
                    {
                        var newLines = GetPrecedingNewLineCount(group);
                        finalParts.AddRange(LineBreak(newLines));
                    }

                    var parts = _groupMap[group];
                    finalParts.AddRange(parts);
                }

                return finalParts.AsImmutable();
            }
        private Post ScrapePost(HtmlNode contentNode, Post post)
        {
            post = post ?? new Post();

            contentNode.NullCheck();

            /// title
            HtmlNode titleNode = contentNode.SelectSingleNode(PostPageXPath.Title);
            if (titleNode != null)
            {
                post.Title = titleNode.InnerText.SafeTrimAndEscapeHtml();
            }
            else
            {
                this._logger.ErrorFormat("ScrapingService, ScrapePost, Title node is null - URL: {0}, NODE: {1}", post.Url, contentNode.SerializeHtmlNode());
            }

            /// subtitle
            HtmlNode subtitleNode = contentNode.SelectSingleNode(PostPageXPath.Subtitle);
            if (subtitleNode != null)
            {
                post.Subtitle = subtitleNode.InnerText.SafeTrimAndEscapeHtml();
            }
            else
            {
                this._logger.ErrorFormat("ScrapingService, ScrapePost, Subtitle node is null - URL: {0}, NODE: {1}", post.Url, contentNode.SerializeHtmlNode());
            }

            /// author
            HtmlNode authorNode = contentNode.SelectSingleNode(PostPageXPath.Auhtor);
            if (authorNode != null)
            {
                IList<HtmlNode> authorNameNodes = authorNode.ChildNodes.Where(x => x.Name == "b" && x.ChildNodes.Where(t => t.Name == "a").Count() == 0).ToList();
                if (!authorNameNodes.IsEmpty())
                {
                    foreach (HtmlNode author in authorNameNodes)
                    {
                        //TODO http://www.rtvslo.si/mmc-priporoca/dame-niso-sposobne-zmagati-na-dirki-formule-ena/306771
                        User authorUser = new User()
                        {
                            Name = author.InnerText.SafeTrim().Replace(",", string.Empty).Replace("foto:", string.Empty).SafeTrimAndEscapeHtml(),
                            Function = UserFunctionEnum.Journalist
                        };

                        post.Authors.Add(authorUser);
                    }
                }

                //HtmlNode authorName = authorNode.ChildNodes.FindFirst("b");
                //if (authorName != null)
                //{
                //    post.Authors = authorName.InnerText.SafeTrimAndEscapeHtml();
                //}
            }

            if (post.Authors.IsEmpty())
            {
                //this._logger.WarnFormat("ScrapingService, ScrapePost, Author is empty - URL: {0}, NODE: {1}", post.Url, contentNode.SerializeHtmlNode());
                this._logger.WarnFormat("ScrapingService, ScrapePost, Author is empty - URL: {0}", post.Url);
            }

            /// info
            HtmlNode infoNode = contentNode.SelectSingleNode(PostPageXPath.InfoContent);
            if (infoNode != null)
            {
                // <div class="info">16. februar 2013 ob 07:22,<br>zadnji poseg: 16. februar 2013 ob 15:16<br>Schladming - MMC RTV SLO</div>

                IList<HtmlNode> textNodes = infoNode.ChildNodes.Where(x => x.Name == "#text").ToList();
                if (textNodes != null && textNodes.Count > 1)
                {
                    /// Created datetime
                    string createdDateTimeString = textNodes.First().InnerText.SafeTrim();

                    DateTime createdDate;
                    if (createdDateTimeString.TryParseExactLogging(ParsingHelper.LongDateTimeParseExactPattern, this.cultureInfo, DateTimeStyles.None, out createdDate))
                    {
                        post.DateCreated = createdDate.ToUniversalTime();
                        post.LastUpdated = createdDate.ToUniversalTime();
                    }

                    /// Location
                    string locationString = textNodes.Last().InnerText;
                    IList<string> locationList = locationString.Split(new string[]{"-"}, StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (locationList != null && locationList.Count > 1)
                    {
                        post.Location = locationList.First().SafeTrim();

                        if (locationList.Last().SafeTrim() != "MMC RTV SLO")
                        {
                            this._logger.DebugFormat("ScrapingService, ScrapePost, InfoNode, Location - URL: {0}, LIST: {1}", post.Url, locationList.SerializeObject());
                        }
                    }
                    else
                    {
                        this._logger.WarnFormat("ScrapingService, ScrapePost, InfoNode, Location - URL: {0}, NODE: {1}", post.Url, infoNode.SerializeHtmlNode());
                    }

                    if (textNodes.Count == 3)
                    {
                        /// Updated datetime
                        string updatedDateTimeString = textNodes[1].InnerText.SafeTrim();

                        Regex dateTimeRegex = new Regex(@"(?<date>[0-9\.]+[\w+\s+]+[0-9\:]+)", RegexOptions.IgnoreCase);

                        //TODO fix regex
                        Match dateTimeMatch = dateTimeRegex.Match(updatedDateTimeString);

                        if (dateTimeMatch.Success)
                        {
                            updatedDateTimeString = dateTimeMatch.Groups["date"].Value;

                            DateTime updatedDate;
                            if (updatedDateTimeString.TryParseExactLogging(ParsingHelper.LongDateTimeParseExactPattern, this.cultureInfo, DateTimeStyles.None, out updatedDate))
                            {
                                post.DateCreated = updatedDate.ToUniversalTime();
                            }
                        }
                    }
                }
                else
                {
                    this._logger.ErrorFormat("ScrapingService, ScrapePost, InfoNode - URL: {0}, NODE: {1}", post.Url, infoNode.SerializeHtmlNode());
                }
            }

            /// Main content
            IList<HtmlNode> contentNodes = new List<HtmlNode>();
            foreach (HtmlNode node in contentNode.ChildNodes)
            {
                /// ends with author
                if (node.Name == "div" && node.Attributes.FirstOrDefault(x => x.Value == "author") != null)
                {
                    break;
                }

                if ((node.Name == "p" || node.Name == "div") && node.FirstChild != null && node.FirstChild.Name != "div" && contentNodes.Count > 0)
                {
                    contentNodes.Add(node);
                }

                /// starts with p tag
                if (node.Name == "p" && node.FirstChild.Name != "div" && contentNodes.Count == 0)
                {
                    contentNodes.Add(node);
                }
            }

            //TODO remove
            string sasas = post.Url;

            if (!contentNodes.IsEmpty())
            {
                /// Abstract - text inside strong tag in first node
                HtmlNode abstractNode = contentNodes.First();
                HtmlNode strongAbstractNode = abstractNode.ChildNodes.First(x => x.Name == "strong");
                post.Abstract = strongAbstractNode.InnerText.SafeTrimAndEscapeHtml();

                /// remove abstract from main content
                abstractNode.ChildNodes.Remove(strongAbstractNode);

                /// Content
                StringBuilder content = new StringBuilder();

                foreach (HtmlNode node in contentNodes)
                {
                    // to get white space after paragraph title
                    foreach (HtmlNode childNode in node.ChildNodes)
                    {
                        string text = childNode.InnerText.SafeTrimAndEscapeHtml();
                        if (text.Length > 0)
                        {
                            content.AppendFormat("{0} ", text);
                        }
                    }
                }

                post.Content = content.ToString().SafeTrim();
            }
            else
            {
                this._logger.ErrorFormat("ScrapingService, ScrapePost - Post content is null - URL: {0}, NODE: {1}", post.Url, contentNode.SerializeHtmlNode());
            }

            return post;
        }
        /// <summary>
        /// Writes all stylesheet source.
        /// </summary>
        /// <param name="writer">The writer.</param>
        protected virtual void Write(TextWriter writer)
        {
            IList<string> mergedList = new List<string>();

            bool isSecured = ViewContext.HttpContext.Request.IsSecureConnection;
            bool canCompress = ViewContext.HttpContext.Request.CanCompress();

            Action<WebAssetItemCollection> append = assets =>
                                                    {
                                                        IList<string> result = AssetMerger.Merge("text/css", AssetHandlerPath, isSecured, canCompress, assets);

                                                        if (!result.IsNullOrEmpty())
                                                        {
                                                            mergedList.AddRange(result);
                                                        }
                                                    };

            if (!StyleSheets.IsEmpty())
            {
                append(StyleSheets);
            }

            if (!mergedList.IsEmpty())
            {
                foreach (string stylesheet in mergedList)
                {
                    writer.WriteLine("<link type=\"text/css\" href=\"{0}\" rel=\"stylesheet\"/>".FormatWith(stylesheet));
                }
            }
        }
Example #60
0
 public static void SubstituteWith(this IFigure figure, IFigure replacement)
 {
     List<IFigure> dependents = new List<IFigure>(figure.Dependents.Where(f => !(f is PointLabel)));
     if (dependents.IsEmpty())
     {
         return;
     }
     foreach (var dependent in dependents)
     {
         dependent.ReplaceDependency(figure, replacement);
     }
     replacement.Dependents.AddRange(figure.Dependents.ToArray());
     figure.Dependents.Clear();
 }