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 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;
        }
        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 override bool Matches(object actual)
 {
     this.actual = actual;
     _failures = new List<Failure>();
     PropertyEquals(_expectedResponse, actual, _expectedResponse.GetType().Name);
     return _failures.IsEmpty();
 }
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 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;
        }
 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);
 }
Example #13
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 #14
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;
        }
        /// <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 #16
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();
            }
        }
            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();
            }
Example #18
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 #19
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;

                });
        }
        /// <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;
        }
Example #21
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;
        }
 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 #23
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);
        }
Example #24
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();
        }
        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 #26
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 #27
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 #28
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 #29
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();
 }
        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;
        }