public FindResult<SubCategoryViewModel> GetAllSubcategoriesByCategory(Guid id)
        {
            FindResult<SubCategoryViewModel> entityResult = new FindResult<SubCategoryViewModel>() { Success = false };

            List<SubCategoryViewModel> subCategories = new List<SubCategoryViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                var query = from c in dbContext.CategorySet
                            join csbmap in dbContext.CategorySubCategoryMapSet
                            on c.CategoryId equals csbmap.CategoryId
                            join sb in dbContext.SubCategorySet
                            on csbmap.SubCategoryId equals sb.SubCategoryId
                            where c.CategoryId == id
                            select sb;

                foreach (var item in query)
                {
                    subCategories.Add(ObjectMapper.PropertyMap(item, new SubCategoryViewModel()));
                }

                entityResult.Entities = subCategories;
                entityResult.Success = true;
            }

            return entityResult;
        }
        public void Execute()
        {
            Results = DuplicateFinder.FindDuplicates();

            var bytesDeleted = Results.Duplicates
                .Select(x =>
                    {
                        var delete = _select.FilesToDelete(x);
                        var keep = x.Except(delete);

                        return new { Keep = keep, Delete = delete };
                    })
                .SelectMany(x =>
                    {
                        foreach (var keep in x.Keep)
                        {
                            _output.WriteLine(String.Format("Keeping {0}", keep));
                        }

                        return x.Delete;
                    })
                .Concat(Results.Resurrected.SelectMany(x => x))
                .Distinct()
                .Select(FileDeleter.Delete)
                .Sum();

            _output.WriteLine(String.Format("{0} deleted.", bytesDeleted.ToFileSize()));
        }
        public FindResult<ProductListItem> GetAllProductListItems(ProductFilterOption filterOption)
        {
            FindResult<ProductListItem> result = new FindResult<ProductListItem>() { Success = false };

            try
            {

                using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
                {
                    List<ProductListItem> productListItems = (from pr in dbContext.ProductSet.ToList()
                                                              join catSubCatMap in dbContext.CategorySubCategoryMapSet.ToList()
                                                              on pr.CategorySubCategoryMapId equals catSubCatMap.CategorySubCategoryMapId
                                                              join category in dbContext.CategorySet.ToList()
                                                              on catSubCatMap.CategoryId equals category.CategoryId
                                                              join subCategory in dbContext.SubCategorySet
                                                              on catSubCatMap.SubCategoryId equals subCategory.SubCategoryId
                                                              select new ProductListItem
                                                              {
                                                                  CategoryId = category.CategoryId,
                                                                  CategoryName = category.CategoryName,
                                                                  Description = pr.Description,
                                                                  ImageId = pr.ImageId,
                                                                  ItemType = pr.ItemType,
                                                                  ProductName = pr.ProductName,
                                                                  SubCategoryId = subCategory.SubCategoryId,
                                                                  SubCategoryName = subCategory.SubCategoryName,
                                                                  ProductId = pr.ProductId

                                                              }).ToList();

                    if (!string.IsNullOrEmpty(filterOption.SearchString) && filterOption.SearchString.Trim() != string.Empty)
                    {
                        productListItems = productListItems.Where(x => x.ProductName.Contains(filterOption.SearchString)).ToList();

                    }

                    if (filterOption.CategoryId != Guid.Empty)
                    {
                        productListItems = productListItems.Where(x => x.CategoryId == filterOption.CategoryId).ToList();
                    }

                    if (filterOption.SubCategoryId != Guid.Empty)
                    {
                        productListItems = productListItems.Where(x => x.SubCategoryId == filterOption.SubCategoryId).ToList();
                    }

                    result.Entities = productListItems.OrderBy(x => x.ProductName).ToList();
                }

                result.Success = true;

            }
            catch (Exception ex)
            {
                result.Success = false;
                throw;
            }

            return result;
        }
		public IOccurence MakeOccurence(FindResult findResult) {
			var findResultText = findResult as FindResultText;
			if (findResultText == null || findResultText.DocumentRange.Document.GetOutsideSolutionPath().IsEmpty)
				return null;
			
			IRangeMarker rangeMarker = findResultText.Solution.GetComponent<DocumentManager>().CreateRangeMarker(findResultText.DocumentRange);
			return new T4OutsideSolutionOccurence(rangeMarker);
		}
        internal static new IFileSystemInformation Create(FindResult findResult, string directory, IFileService fileService)
        {
            if ((findResult.Attributes & FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0) throw new ArgumentOutOfRangeException(nameof(findResult));

            var directoryInfo = new DirectoryInformation(fileService);
            directoryInfo.PopulateData(findResult, directory);
            return directoryInfo;
        }
Exemple #6
0
 public FindResult(FindResult findResult)
 {
     FindPredicate = findResult.FindPredicate;
     Bookmark = findResult.Bookmark;
     Document = findResult.Document;
     FindMatch = findResult.FindMatch;
     LocationName = findResult.LocationName;
     LocationType = findResult.LocationType;
     IsValid = findResult.IsValid;
 }
Exemple #7
0
		bool IsWholeWord(ITextStructureNavigator textStructureNavigator, ITextSnapshot snapshot, FindResult result) {
			Debug.Assert(textStructureNavigator != null);
			if (textStructureNavigator == null)
				return false;
			if (result.Length == 0)
				return false;
			var start = textStructureNavigator.GetExtentOfWord(new SnapshotPoint(snapshot, result.Position));
			if (start.Span.Start.Position != result.Position)
				return false;
			var end = textStructureNavigator.GetExtentOfWord(new SnapshotPoint(snapshot, result.Position + result.Length - 1));
			return end.Span.End.Position == result.Position + result.Length;
		}
Exemple #8
0
        public FindResult Find(string deployment)
        {
            DeploymentFinder finder = deployment == "SEARCH" ?
                new SearchesForAnAssemblyNameContainingDeployment() :
                    deployment.EndsWith(".dll") || deployment.EndsWith(".exe") ?
                        new AssemblyWasSpecifiedAssumingOnlyOneDeploymentClass() :
                            (DeploymentFinder) new TypeWasSpecifiedAssumingItHasADefaultConstructor();

            var dep = finder.Find(deployment);

            var result = new FindResult
                {
                    Deployment = dep,
                    MethodOfFinding = finder.Name
                };
            return result;
        }
        public FindResult<StoreProductSearchModel> SearchExternalStoreProducts(StoreProductSearchRequest searchRequest)
        {
            IExternalStoreService externalService = null;

            FindResult<StoreProductSearchModel> result = new FindResult<StoreProductSearchModel>();

            if (searchRequest.StoreType == Lotus.Core.Common.StoreProviderTypeEnum.Amazon)
            {
                externalService = new AmazonServiceClient();
            }

            if (searchRequest.StoreType == Lotus.Core.Common.StoreProviderTypeEnum.eBay)
            {
                externalService = new eBayServiceCall();
            }

            result = externalService.SearchExternalStoreProduct(searchRequest);

            return result;
        }
        public HttpResponseMessage GetCategorySelectList(HttpRequestMessage request, Guid? id = null)
        {
            FindResult<SubCategoryViewModel> findSubCategoryResult = new FindResult<SubCategoryViewModel>();

            if (id.HasValue)
            {
                findSubCategoryResult = subCategoryActivity.GetAllSubcategoriesByCategory(id.Value);
            }
            else
            {
                findSubCategoryResult = subCategoryActivity.GetAllSubcategories();
            }

            SelectEntityModelListResult<SubCategoryViewModel> selectSubCategories = null;

            HttpResponseMessage response = null;

            return GetHttpResponse(request, () =>
            {

                if (findSubCategoryResult.Success)
                {
                    selectSubCategories = new SelectEntityModelListResult<SubCategoryViewModel>(findSubCategoryResult.Entities);
                    selectSubCategories.Success = true;
                }
                else
                {
                    selectSubCategories = new SelectEntityModelListResult<SubCategoryViewModel>(new List<SubCategoryViewModel>());
                    selectSubCategories.Success = false;
                }

                response = new HttpResponseMessage(HttpStatusCode.OK);

                response.Content = new ObjectContent<SelectEntityModelListResult<SubCategoryViewModel>>(selectSubCategories, Configuration.Formatters.JsonFormatter);

                return response;

            });
        }
        public void Execute()
        {
            var timer = new Stopwatch();
              timer.Start();

              try
              {
            Results = DuplicateFinder.FindDuplicates();
            var bytesDeleted = Results.Duplicates
                                  .Select(x =>
                                  {
                                    var delete = _select.FilesToDelete(x);
                                    var keep = x.Except(delete);

                                    return new { Keep = keep, Delete = delete };
                                  })
                                  .SelectMany(x =>
                                  {
                                    foreach (var keep in x.Keep)
                                    {
                                      _output.WriteLine("Keeping {0}", keep);
                                    }

                                    return x.Delete;
                                  })
                                  .Concat(Results.Resurrected.SelectMany(x => x))
                                  .Distinct()
                                  .Select(FileDeleter.Delete)
                                  .Sum();

            _output.WriteLine("{0} deleted.", bytesDeleted.ToFileSize());
              }
              finally
              {
            timer.Stop();
            _output.WriteLine("Took {0}", timer.Elapsed);
              }
        }
        private void buttonFind_Click(object sender, EventArgs e)
        {
            listBoxSearchResult.Items.Clear();
            listBoxSearchResult.Visible = false;
            Find find = null;
            Column searchColumn = _searchTable.TableInfo.Columns[comboBoxSearchColumn.SelectedItem.ToString()];
            if ( _refiningTable != null && _refiningTable.IsOpen )
            {
                if (comboBoxRefiningColumn.Items.Count > 0 )
                {
                    Column refiningColumn = _refiningTable.TableInfo.Columns[comboBoxRefiningColumn.SelectedItem.ToString()];
                    find = new Find(_searchTable, searchColumn, _refiningTable, refiningColumn);
                }
                else
                {
                    MessageBox.Show(String.Format("No indexed columns in " + _refiningTable + "."));
                    return;
                }

            }
            else
            {
                find = new Find(_searchTable, searchColumn);
            }

            if ( checkBoxUseCloseMatches.Checked )
            {
                find.UseCloseMatches = true;
                find.CloseMatchesMax = int.Parse(textBoxMaxCloseMatches.Text);
            }

            if ( checkBoxAddressNumAfterStreet.Checked )
            {
                find.AddressNumberAfterStreet = true;
            }

            // Do the actual search.
            if ( _refiningTable != null && _refiningTable.IsOpen )
            {
                if (_bSearchIntersection)
                {
                    _result= find.SearchIntersection(textBoxSearchString.Text, textBoxIntersection.Text, textBoxRefiningString.Text);
                }
                else
                {
                    _result = find.Search(textBoxSearchString.Text, textBoxRefiningString.Text);
                }
            }
            else
            {
                if (_bSearchIntersection)
                {
                    _result= find.SearchIntersection(textBoxSearchString.Text, textBoxIntersection.Text);
                }
                else
                {
                    _result = find.Search(textBoxSearchString.Text);
                }
            }

            // display label that tells us when multiple matches were found
            labelMultipleMatchesFound.Visible = _result.MultipleMatches;

            if ( _result.ExactMatch
                && _result.NameResultCode.Equals(FindNameCode.ExactMatch)
                && _result.FoundPoint != null)
            {
                labelSearchResult.Text = "Exact Match";
                showPointOnSearchTableMap(_result.FoundPoint.X, _result.FoundPoint.Y);
            }
            else if (_result.NameResultCode.Equals(FindNameCode.ExactMatch)
                && _result.AddressResultCode.Equals(FindAddressCode.AddressNumNotSpecified))
            {
                labelSearchResult.Text = _result.AddressResultCode.ToString();
                FindAddressRangeEnumerator _enum = _result.GetAddressRangeEnumerator();
                FindAddressRange _findAddressRange;

                listBoxSearchResult.Visible = true;
                while (_enum.MoveNext())
                {
                    _findAddressRange = _enum.Current;
                    listBoxSearchResult.Items.Add(
                        String.Format("Address range: [{0} - {1}]", _findAddressRange.BeginRange, _findAddressRange.EndRange));
                }
            }
            else if (_result.NameResultCode.Equals(FindNameCode.ExactMatch)
                && _result.MultipleMatches)
            {
                labelSearchResult.Text = _result.NameResultCode.ToString();
                listBoxSearchResult.Visible = true;
                FindCloseMatchEnumerator enumerator = _result.GetCloseMatchEnumerator();
                while ( enumerator.MoveNext() )
                {
                    listBoxSearchResult.Items.Add(enumerator.Current.Name);
                }
            }
            else
            {
                labelSearchResult.Text = _result.NameResultCode.ToString();
                if ( find.UseCloseMatches )
                {
                    listBoxSearchResult.Visible = true;
                    FindCloseMatchEnumerator enumerator = _result.GetCloseMatchEnumerator();
                    while ( enumerator.MoveNext() )
                    {
                        listBoxSearchResult.Items.Add(enumerator.Current.Name);
                    }
                }
            }
            find.Dispose();
        }
 public UnityAssetFindResult Build(FindResult result)
 {
     return(result as UnityAssetFindResult);
 }
Exemple #14
0
        public void HighlightFindResult(FindResult findResult)
        {
            if (!IsComplete)
            {
                _pendingFindResult = findResult;
                return;
            }
            var bookmarkEnumerator = BookmarkEnumerator.TryGet(_dataSchema.Document, findResult.Bookmark);

            if (bookmarkEnumerator == null)
            {
                return;
            }
            var chromInfo = bookmarkEnumerator.CurrentChromInfo;

            if (chromInfo == null)
            {
                return;
            }
            int?iRowMatch = null;

            for (int iRow = 0; iRow < BindingListSource.Count; iRow++)
            {
                var rowItem = BindingListSource[iRow] as RowItem;
                if (rowItem == null)
                {
                    continue;
                }
                var replicate = rowItem.Value as Replicate;
                if (replicate != null)
                {
                    if (replicate.Files.Any(file => ReferenceEquals(file.ChromFileInfoId, chromInfo.FileId)))
                    {
                        iRowMatch = iRow;
                        break;
                    }
                }
                var result = rowItem.Value as Result;
                if (null != result)
                {
                    if (ReferenceEquals(result.GetResultFile().ChromFileInfoId, chromInfo.FileId))
                    {
                        iRowMatch = iRow;
                        break;
                    }
                }
            }
            if (!iRowMatch.HasValue)
            {
                return;
            }
            BindingListSource.Position = iRowMatch.Value;
            DataGridViewColumn column;

            if (findResult.FindMatch.Note)
            {
                column = FindColumn(PropertyPath.Root.Property("Note")); // Not L10N
            }
            else if (findResult.FindMatch.AnnotationName != null)
            {
                column = FindColumn(PropertyPath.Root.Property(
                                        AnnotationDef.ANNOTATION_PREFIX + findResult.FindMatch.AnnotationName));
            }
            else
            {
                return;
            }
            if (null != column && null != DataGridView.CurrentRow)
            {
                DataGridView.CurrentCell = DataGridView.CurrentRow.Cells[column.Index];
            }
        }
Exemple #15
0
        private void buttonFind_Click(object sender, System.EventArgs e)
        {
            listBoxSearchResult.Items.Clear();
            listBoxSearchResult.Visible = false;
            Find   find         = null;
            Column searchColumn = _searchTable.TableInfo.Columns[comboBoxSearchColumn.SelectedItem.ToString()];

            if (_refiningTable != null && _refiningTable.IsOpen)
            {
                if (comboBoxRefiningColumn.Items.Count > 0)
                {
                    Column refiningColumn = _refiningTable.TableInfo.Columns[comboBoxRefiningColumn.SelectedItem.ToString()];
                    find = new Find(_searchTable, searchColumn, _refiningTable, refiningColumn);
                }
                else
                {
                    MessageBox.Show(String.Format("No indexed columns in " + _refiningTable + "."));
                    return;
                }
            }
            else
            {
                find = new Find(_searchTable, searchColumn);
            }

            if (checkBoxUseCloseMatches.Checked)
            {
                find.UseCloseMatches = true;
                find.CloseMatchesMax = int.Parse(textBoxMaxCloseMatches.Text);
            }

            if (checkBoxAddressNumAfterStreet.Checked)
            {
                find.AddressNumberAfterStreet = true;
            }

            // Do the actual search.
            if (_refiningTable != null && _refiningTable.IsOpen)
            {
                if (_bSearchIntersection)
                {
                    _result = find.SearchIntersection(textBoxSearchString.Text, textBoxIntersection.Text, textBoxRefiningString.Text);
                }
                else
                {
                    _result = find.Search(textBoxSearchString.Text, textBoxRefiningString.Text);
                }
            }
            else
            {
                if (_bSearchIntersection)
                {
                    _result = find.SearchIntersection(textBoxSearchString.Text, textBoxIntersection.Text);
                }
                else
                {
                    _result = find.Search(textBoxSearchString.Text);
                }
            }

            // display label that tells us when multiple matches were found
            labelMultipleMatchesFound.Visible = _result.MultipleMatches;

            if (_result.ExactMatch &&
                _result.NameResultCode.Equals(FindNameCode.ExactMatch) &&
                _result.FoundPoint != null)
            {
                labelSearchResult.Text = "Exact Match";
                showPointOnSearchTableMap(_result.FoundPoint.X, _result.FoundPoint.Y);
            }
            else if (_result.NameResultCode.Equals(FindNameCode.ExactMatch) &&
                     _result.AddressResultCode.Equals(FindAddressCode.AddressNumNotSpecified))
            {
                labelSearchResult.Text = _result.AddressResultCode.ToString();
                FindAddressRangeEnumerator _enum = _result.GetAddressRangeEnumerator();
                FindAddressRange           _findAddressRange;

                listBoxSearchResult.Visible = true;
                while (_enum.MoveNext())
                {
                    _findAddressRange = _enum.Current;
                    listBoxSearchResult.Items.Add(
                        String.Format("Address range: [{0} - {1}]", _findAddressRange.BeginRange, _findAddressRange.EndRange));
                }
            }
            else if (_result.NameResultCode.Equals(FindNameCode.ExactMatch) &&
                     _result.MultipleMatches)
            {
                labelSearchResult.Text      = _result.NameResultCode.ToString();
                listBoxSearchResult.Visible = true;
                FindCloseMatchEnumerator enumerator = _result.GetCloseMatchEnumerator();
                while (enumerator.MoveNext())
                {
                    listBoxSearchResult.Items.Add(enumerator.Current.Name);
                }
            }
            else
            {
                labelSearchResult.Text = _result.NameResultCode.ToString();
                if (find.UseCloseMatches)
                {
                    listBoxSearchResult.Visible = true;
                    FindCloseMatchEnumerator enumerator = _result.GetCloseMatchEnumerator();
                    while (enumerator.MoveNext())
                    {
                        listBoxSearchResult.Items.Add(enumerator.Current.Name);
                    }
                }
            }
            find.Dispose();
        }
        public HttpResponseMessage GetSubCategories(HttpRequestMessage request)
        {
            return GetHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                FindResult<SubCategoryCategories> subCategoryCategoriesResult = new FindResult<SubCategoryCategories>();

                FindResult<SubCategoryViewModel> subCategoryResult = subCategoryActivity.GetAllSubcategories();

                response = GetFindResultResponse(request, subCategoryResult);
                return response;
            });
        }
        public FindResult<ProductVariantListItem> GetAllProductVariantListItems(Guid productId)
        {
            FindResult<ProductVariantListItem> result = new FindResult<ProductVariantListItem> { Success = false };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                var productVariants = (from prv in dbContext.ProductVariantSet
                                       where prv.ProductId == productId
                                       select new ProductVariantListItem
                                       {
                                           ProductVariantId = prv.ProductVariantId,
                                           AvailableQuantity = prv.AvailableQuantity,
                                           BasePrice = prv.BasePrice,
                                           ShelfPrice = prv.ShelfPrice,
                                           SKUCode = prv.SKUCode,
                                       }).ToList();

                foreach (ProductVariantListItem pvm in productVariants)
                {

                    var productVariantAttributeValues = GetProductVariantAttributeValueVMS(dbContext, pvm.ProductVariantId);

                    if (productVariantAttributeValues.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();

                        foreach (var item in productVariantAttributeValues)
                        {
                            sb.AppendFormat("{0}: {1}; ", item.ProductAttributeName, item.ProductAttributeValue);
                            sb.Append(" ");
                        }

                        string formattedAttributeValues = sb.ToString().Trim();

                        if (formattedAttributeValues.EndsWith(";"))
                        {
                            formattedAttributeValues = formattedAttributeValues.Substring(0, formattedAttributeValues.Length - 1);
                        }

                        pvm.AttributeValuesString = formattedAttributeValues;
                    }

                }

                result.Entities = productVariants;
            }

            result.Success = true;

            return result;
        }
        private FindResult<ProductAttributeViewModel> SetFindResult(FindResult<ProductAttributeViewModel> findResult, InnoventoryDBContext dbContext)
        {
            //findResult.Success = false;

            FindResult<SubCategoryViewModel> subCategoryResult = subCategoryRepository.GetAll(dbContext);

            FindResult<ProductAttributeViewModel> retResult = new FindResult<ProductAttributeViewModel>();

            retResult.Entities = new List<ProductAttributeViewModel>();

            if (findResult.Success && findResult.Entities.Count > 0)
            {
                foreach (var entity in findResult.Entities)
                {
                    Guid productAttributeId = entity.ProductAttributeId;

                    FindResult<SubCategoryAttributeMapViewModel> subCategoryAttributeMapResult = subCategoryAttributeMapRepository.FindBy(x => x.ProductAttributeId == productAttributeId);

                    List<AttributeSubCategorySelection> subCategorySelections = new List<AttributeSubCategorySelection>();

                    subCategoryResult.Entities.ForEach(x => subCategorySelections.Add(new AttributeSubCategorySelection
                    {
                        SubCategory = x,
                        IsSelected = false,
                    }));

                    subCategorySelections.ForEach(x => x.IsSelected = false);

                    entity.SubCategorySelections = new List<AttributeSubCategorySelection>();

                    entity.SubCategorySelections = subCategorySelections;
                    entity.SubCategoryNames = string.Empty;

                    AttributeSubCategorySelection selection = new AttributeSubCategorySelection();

                    if (subCategoryAttributeMapResult.Success && subCategoryAttributeMapResult.Entities.Count > 0)
                    {
                        foreach (SubCategoryAttributeMapViewModel map in subCategoryAttributeMapResult.Entities)
                        {
                            AttributeSubCategorySelection selectedSubCategory = entity.SubCategorySelections
                                .FirstOrDefault(x => x.SubCategory.SubCategoryId == map.SubCategoryId);

                            selectedSubCategory.IsSelected = true;

                            entity.SubCategoryNames += selectedSubCategory.SubCategory.SubCategoryName + ", ";
                        }
                    }

                    if (entity.SubCategoryNames.Contains(","))
                    {
                        entity.SubCategoryNames = entity.SubCategoryNames.Trim().Substring(0, entity.SubCategoryNames.Trim().Length - 1);
                    }

                    retResult.Entities.Add(entity);
                }

                retResult.Success = true;

            }

            return retResult;
        }
Exemple #19
0
        /// <summary>
        /// Determines whether a variable should be inlined in non-aggressive mode, even though it is not a generated variable.
        /// </summary>
        /// <param name="next">The next top-level expression</param>
        /// <param name="loadInst">The load within 'next'</param>
        /// <param name="inlinedExpression">The expression being inlined</param>
        static bool NonAggressiveInlineInto(ILInstruction next, FindResult findResult, ILInstruction inlinedExpression, ILVariable v)
        {
            if (findResult.Type == FindResultType.NamedArgument)
            {
                var originalStore = (StLoc)inlinedExpression.Parent;
                return(!originalStore.ILStackWasEmpty);
            }
            Debug.Assert(findResult.Type == FindResultType.Found);

            var loadInst = findResult.LoadInst;

            Debug.Assert(loadInst.IsDescendantOf(next));

            // decide based on the source expression being inlined
            switch (inlinedExpression.OpCode)
            {
            case OpCode.DefaultValue:
            case OpCode.StObj:
            case OpCode.NumericCompoundAssign:
            case OpCode.UserDefinedCompoundAssign:
            case OpCode.Await:
                return(true);

            case OpCode.LdLoc:
                if (v.StateMachineField == null && ((LdLoc)inlinedExpression).Variable.StateMachineField != null)
                {
                    // Roslyn likes to put the result of fetching a state machine field into a temporary variable,
                    // so inline more aggressively in such cases.
                    return(true);
                }
                break;
            }

            var parent = loadInst.Parent;

            if (NullableLiftingTransform.MatchNullableCtor(parent, out _, out _))
            {
                // inline into nullable ctor call in lifted operator
                parent = parent.Parent;
            }
            if (parent is ILiftableInstruction liftable && liftable.IsLifted)
            {
                return(true);                // inline into lifted operators
            }
            // decide based on the new parent into which we are inlining:
            switch (parent.OpCode)
            {
            case OpCode.NullCoalescingInstruction:
                if (NullableType.IsNullable(v.Type))
                {
                    return(true);                            // inline nullables into ?? operator
                }
                break;

            case OpCode.NullableUnwrap:
                return(true);                        // inline into ?. operator

            case OpCode.UserDefinedLogicOperator:
            case OpCode.DynamicLogicOperatorInstruction:
                return(true);                        // inline into (left slot of) user-defined && or || operator

            case OpCode.DynamicGetMemberInstruction:
            case OpCode.DynamicGetIndexInstruction:
            case OpCode.LdObj:
                if (parent.Parent.OpCode == OpCode.DynamicCompoundAssign)
                {
                    return(true);                            // inline into dynamic compound assignments
                }
                break;

            case OpCode.ArrayToPointer:
            case OpCode.LocAllocSpan:
                return(true);                        // inline size-expressions into localloc.span
            }
            // decide based on the top-level target instruction into which we are inlining:
            switch (next.OpCode)
            {
            case OpCode.Leave:
            case OpCode.YieldReturn:
                return(parent == next);

            case OpCode.IfInstruction:
                while (parent.MatchLogicNot(out _))
                {
                    parent = parent.Parent;
                }
                return(parent == next);

            case OpCode.BlockContainer:
                if (((BlockContainer)next).EntryPoint.Instructions[0] is SwitchInstruction switchInst)
                {
                    next = switchInst;
                    goto case OpCode.SwitchInstruction;
                }
                else
                {
                    return(false);
                }

            case OpCode.SwitchInstruction:
                if (parent == next)
                {
                    return(true);
                }
                if (parent.MatchBinaryNumericInstruction(BinaryNumericOperator.Sub) && parent.Parent == next)
                {
                    return(true);
                }
                if (parent is StringToInt stringToInt && stringToInt.Parent == next)
                {
                    return(true);
                }
                return(false);

            default:
                return(false);
            }
        }
        public FindResult<CategorySubCategoryAttributeValuesViewModel> GetAllCategorySubCategoryAttributesValueList(Guid categorySubCategoryMapId)
        {
            FindResult<CategorySubCategoryAttributeValuesViewModel> result = new FindResult<CategorySubCategoryAttributeValuesViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                var categorySubCategoryMapResult = dbContext.CategorySubCategoryMapSet.Where(x=>x.CategorySubCategoryMapId == categorySubCategoryMapId).FirstOrDefault();

                Guid categoryId = Guid.Empty;
                Guid subCategoryId = Guid.Empty;

                if(categorySubCategoryMapResult == null)
                {
                    result.Success = false;

                    return result;
                }

                categoryId = categorySubCategoryMapResult.CategoryId;

                subCategoryId = categorySubCategoryMapResult.SubCategoryId;

                var prodAttributes = (from pa in dbContext.ProductAttributeSet
                                     join sca in dbContext.SubCategoryAttributeMapSet
                                     on pa.ProductAttributeId equals sca.ProductAttributeId
                                     where sca.SubCategoryId == subCategoryId
                                     select new CategorySubCategoryAttributeValuesViewModel
                                     {
                                         AttributeName = pa.AttributeName,
                                         ProductAttributeId = pa.ProductAttributeId,
                                          CategorySubCategoryMapId = sca.SubCategoryAttributeMapId,

                                     }).ToList();

                List<AttributeValueList> attributeValueLists = dbContext.AttributeValueListSet.ToList();

                foreach (var pa in prodAttributes)
                {
                    var attributeValueList = (from attvl in attributeValueLists
                                             where attvl.SubCategoryAttributeMapID == pa.CategorySubCategoryMapId
                                             && attvl.CategoryId == categoryId
                                             select new AttributeValueItem
                                             {
                                                 AttributeValue = attvl.AttributeValue,
                                                 AttributeValueListId = attvl.AttributeValueListId
                                             }).ToList();

                    pa.AttributeValues = attributeValueList;
                }

                result.Entities = prodAttributes;

                result.Success = true;

            }

            return result;
        }
        //[Import]
        //private ICategorySubCategoryMapRepository categorySubCategoryMapRepo;
        public FindResult<ProductAttributeViewModel> GetProductAttributes()
        {
            FindResult<ProductAttributeViewModel> findResult = new FindResult<ProductAttributeViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                findResult = productAttributeRepository.GetAll(dbContext);

                if (!findResult.Success)
                {
                    return findResult;
                }

                return SetFindResult(findResult, dbContext);
            }
        }
Exemple #22
0
        public bool Add(T item)
        {
            if (item == null)
            {
                return(false); // dont allow null to be added, just say it is already there
            }
            if (NeedToResize())
            {
                Resize();
            }

            var hc = PositiveHashCode(item);
            //var res = FindSlot(item, hc);
            // inline FindSlot for 25% better performance
            FindResult res;

            {
                const int UNSET     = -1;
                var       slot      = hc % indexes.Length;
                int       firstFree = UNSET;
                for (;;)
                {
                    int valueIdx = GetIndex(slot);
                    if (valueIdx == FREE)
                    {
                        res = new FindResult(-1, firstFree == UNSET ? slot : firstFree);
                        break;
                    }
                    else if (valueIdx == DELETED)
                    {
                        if (firstFree == UNSET)
                        {
                            firstFree = slot;
                        }
                    }
                    else if (hc == hashCodes[valueIdx] && Equality.Equals(item, values[valueIdx]))
                    {
                        res = new FindResult(slot, firstFree);
                        break;
                    }

                    // another value is in that slot, try the next index
                    slot += 1;
                    if (slot == indexes.Length)
                    {
                        slot = 0;
                    }

                    // wrap around termination check no longer needed because there will now always be spare capacity
                }
            }

            if (res.Found)
            {
                return(false);
            }

            // not found, add it
            values[count]    = item;
            hashCodes[count] = hc;
            SetIndex(res.FirstFreeSlot, count);
            count++;
            return(true);
        }
Exemple #23
0
        public void run()
        {
            IXConnFactory connFact = null;
            IXConnection  ix       = null;

            try
            {
                IXProperties connProps = IXConnFactory.CreateConnProperties(url);
                IXProperties sessOpts  = IXConnFactory.CreateSessionOptions("IX-Examples", "1.0");
                connFact = new IXConnFactory(connProps, sessOpts);
                Logger.instance().log("create IXConnFactory OK");

                // Prepare ClientInfo object with language and country
                // ClientInfo ci = new ClientInfo();
                // ci.language = "de";
                // ci.country = "DE";

                // LOGIN
                Logger.instance().log("login...");
                ix = connFact.Create(userName, userPwd, "myComputer", null);
                // ci = ix.Login.ci
                Logger.instance().log("login OK");

                // get constants
                Logger.instance().log("get const...");
                IXServicePortC CONST = ix.CONST;
                Logger.instance().log("get const OK");

                // 1. Create test sords with search term in name, desc and index data

                // sord1 has search term in name attribute
                Sord sord1 = ix.Ix.createSord("1", null, EditInfoC.mbSord).sord;
                sord1.name = "C# example FindAll sord1 " + searchAllFor;
                sord1.id   = ix.Ix.checkinSord(sord1, SordC.mbAll, LockC.NO);
                Logger.instance().log("sord1.id=" + sord1.id);

                // sord2 has search term in desc attribute
                Sord sord2 = ix.Ix.createSord("1", null, EditInfoC.mbSord).sord;
                sord2.name = "C# example FindAll sord2";
                sord2.desc = searchAllFor;
                sord2.id   = ix.Ix.checkinSord(sord2, SordC.mbAll, LockC.NO);
                Logger.instance().log("sord2.id=" + sord2.id);

                // sord3 has search term in index attribute
                Sord sord3 = ix.Ix.createSord("1", null, EditInfoC.mbSord).sord;
                sord3.name = "C# example FindAll sord3";
                ObjKey okey = new ObjKey();
                okey.id       = 0;
                okey.name     = "IX-EXAMPLE";
                okey.data     = new String[] { "find " + searchAllFor + " in index line" };
                sord3.objKeys = new ObjKey[] { okey };
                sord3.id      = ix.Ix.checkinSord(sord3, SordC.mbAll, LockC.NO);
                Logger.instance().log("sord3.id=" + sord3.id);

                // 2. Execute find

                // Prepare FindInfo object
                Logger.instance().log("find ...");
                FindInfo findInfo = new FindInfo();
                findInfo.findByIndex      = new FindByIndex();
                findInfo.findByIndex.name = "#" + searchAllFor;

                // find
                FindResult findResult = ix.Ix.findFirstSords(findInfo, 1000, SordC.mbAll);
                if (findResult.sords != null)
                {
                    Logger.instance().log("found #=" + findResult.sords.Length);
                    for (int i = 0; i < findResult.sords.Length; i++)
                    {
                        Logger.instance().log("sord.id=" + findResult.sords[i].id + ", sord.name=" + findResult.sords[i].name);
                    }
                }
                ix.Ix.findClose(findResult.searchId);
                Logger.instance().log("find OK");

                bool cleanUp = true;
                if (cleanUp)
                {
                    DeleteOptions delOpts = new DeleteOptions();
                    delOpts.deleteFinally = true;
                    ix.Ix.deleteSord(null, sord1.guid, LockC.NO, null);
                    ix.Ix.deleteSord(null, sord2.guid, LockC.NO, null);
                    ix.Ix.deleteSord(null, sord3.guid, LockC.NO, null);
                    ix.Ix.deleteSord(null, sord1.guid, LockC.NO, delOpts);
                    ix.Ix.deleteSord(null, sord2.guid, LockC.NO, delOpts);
                    ix.Ix.deleteSord(null, sord3.guid, LockC.NO, delOpts);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // Logout
                // --
                if (ix != null)
                {
                    Logger.instance().log("IX logout...");
                    ix.Logout();
                    Logger.instance().log("IX logout OK");
                }
            }
        }
Exemple #24
0
        // determine if this section of text (some portion of one or more paragraphs) has the find what text in it
        public FindResult FindReplaceCompare(WordRange aRunRange, ref int SearchAreaStart, ref int FoundAreaLength)
        {
            FindResult res      = FindResult.eNothingFound;
            string     strInput = aRunRange.Text;

            if (String.IsNullOrEmpty(strInput) || (m_aECRegex == null))
            {
                return(res);
            }

            // otherwise 'convert' it to see if the 'Find what' string is in it
            string strOutput = m_aECRegex.Convert(strInput);

            // if the input string is different from the output string, then the FindWhat string was found.
            if (strInput != strOutput)
            {
#if !DefineToNotUseSplitAndConvert
                // The way the convert works is that it will replace each instance of the input string that matches
                //  the FindWhat syntax (i.e. there may be more than one replacement we have to deal with).
                // here's the problem: if there was more than one replacment, then I really can't tell what portion
                //  of the FindWhat text each replacement goes with. Consider the string "ababbbbbabb". If the 'Find
                //  what' string is "ab+", then it breaks up to: "ab", "abbbbb", and "abb", but if these three are
                //  right in a row and the replacement is "", then the resulting strOutput will be <delim><delim>...
                //  repeated 3 times. So there's no way to tell which portion of the input text corresponds to which
                //  portion of the output text. My original stab at it just treated them evenly and divide by the
                //  number of consecutive replacements... this works if the 'FindWhat' is something like "ab". But all
                //  bets are off if the user uses the "+" (eat-em-up) expression code.
                // I think the only solution is to always only deal with a single replacement... So... if we have more
                //  than one match in a particular output (which we can tell by the Length of astrSegments), do a binary
                //  search until we have only one.
                string[] astrSegments = GetFirstReplacementSplitArray(ref strInput, ref strOutput);

                // get the index to the first character of the replacement (which is the same as the first character
                //  of the 'Find what' string as well).
                int nIndex = astrSegments[0].Length;

                // remember this so we pick up here later
                SearchAreaStart += nIndex;
                if (nIndex > 0)
                {
                    aRunRange.Start = SearchAreaStart;
                }

                // the replacement string is easy. It's just whatever's in the one'th element of the Split array.
                string strReplacementString = astrSegments[1];

                // There might be some stuff between the end of the replacement and the end of the input string.
                string strStuffFollowingMatch = astrSegments[2];   // may be null

                // get the index to the end of the 'Find what' string
                int nEndOfFindWhatSelection;
                if (String.IsNullOrEmpty(strStuffFollowingMatch))
                {
                    nEndOfFindWhatSelection = strInput.Length;
                }
                else
                {
                    nEndOfFindWhatSelection = strInput.Length - strStuffFollowingMatch.Length;
                }
#else
                // this could probably be done more elegantly with Split rather than what I do in the #else case
                string[] astrSegments = strOutput.Split(m_achDelimiter);

                // must be odd (before, ||: replace, following :||), where any or all can be null
                int nTotalSegments = astrSegments.Length;
                System.Diagnostics.Debug.Assert((nTotalSegments % 2) == 1);

                // get the index to the first character of the replacement (which is the same as the first character
                //  of the 'Find what' as well).
                int nIndex = astrSegments[0].Length;

                // remember this so we pick up here later
                SearchAreaStart += nIndex;
                if (nIndex > 0)
                {
                    aRunRange.Start = SearchAreaStart;
                }

                // the replacement string is easy. It's just whatever's in the 1st element of the Split array.
                //  but we have to figure out what the 'Find what' text is so that we can select it (so we can replace
                //  it). This is not so easy, because it could be anything and not just a string of text like in a normal
                //  find.
                string strReplacementString = astrSegments[1];

                // Between the end of the first replacement and the beginning of the next (if multiple replacments)
                //  is a string which should match something in the original, which we can search for
                string strStuffFollowingMatch = astrSegments[2];   // may be null

                int nEndOfFindWhatSelection;
                if (String.IsNullOrEmpty(strStuffFollowingMatch))
                {
                    // If the 'Find what' is repeated twice in a row, then the stuff in-between the two instances of
                    //  replacement text will be null.
                    // Detect this by looking at the length of the even number string array elements (2, 4, etc),
                    //  which are the segments following the replacements. This tells us what we have to divide by
                    //  to get the proportion for only one find.
                    int nNumReplacmentsInARow = 1;
                    int nNextReplacementIndex = 2;
                    nTotalSegments--;
                    while ((nNextReplacementIndex < nTotalSegments) && String.IsNullOrEmpty(astrSegments[nNextReplacementIndex]))
                    {
                        nNumReplacmentsInARow++;
                        nNextReplacementIndex += 2;
                    }

                    if (nNextReplacementIndex < astrSegments.Length)
                    {
                        strStuffFollowingMatch = astrSegments[nNextReplacementIndex];
                    }

                    int numerator;
                    if (String.IsNullOrEmpty(strStuffFollowingMatch))
                    {
                        numerator = strInput.Length;
                    }
                    else
                    {
                        numerator = strInput.IndexOf(strStuffFollowingMatch, nIndex + 1);
                    }
                    nEndOfFindWhatSelection = ((numerator - nIndex) / nNumReplacmentsInARow) + nIndex;
                }
                else
                {
                    nEndOfFindWhatSelection = strInput.IndexOf(strStuffFollowingMatch, nIndex + 1);
                }

                /*
                 * int nIndex = strOutput.IndexOf(m_achDelimiter[0]);
                 * System.Diagnostics.Debug.Assert(nIndex != -1);
                 * SearchAreaStart += nIndex;
                 * if (nIndex > 0)
                 *  aRunRange.Start = SearchAreaStart;
                 *
                 * int nEndOfReplacement = strOutput.IndexOf(m_achDelimiter[0], nIndex + 1);
                 * System.Diagnostics.Debug.Assert(nEndOfReplacement != -1);
                 *
                 * // the replacement string is what's between these two
                 * string strReplacementString = strOutput.Substring(nIndex + 1, (nEndOfReplacement - nIndex - 1));
                 *
                 * // now the complicated part. Between the end of the first replacement and the next
                 * //  one is a string which should match something in the original. But if the replacement
                 * //  were null, then it could be the very next character...
                 * // This also handles the situation where there may be several "found whats"
                 * int nNumReplacmentsInARow = 1;
                 * int nNextIndex = nEndOfReplacement + 1;
                 * while ((nNextIndex < strOutput.Length) && (strOutput[nNextIndex] == m_achDelimiter[0]))
                 * {
                 *  nNumReplacmentsInARow++;
                 *  nEndOfReplacement = strOutput.IndexOf(m_achDelimiter[0], nNextIndex + 1);
                 *  nNextIndex = nEndOfReplacement + 1;
                 * }
                 *
                 * if (nNextIndex < strOutput.Length)
                 * {
                 *  nEndOfReplacement = strOutput.IndexOf(m_achDelimiter[0], nNextIndex + 1);
                 *  if (nEndOfReplacement == -1)
                 *      nEndOfReplacement = strOutput.Length;
                 * }
                 * else if (nNextIndex == strOutput.Length)
                 *  nNextIndex--;
                 *
                 * string strStuffFollowingMatch = strOutput.Substring(nNextIndex, nEndOfReplacement - nNextIndex);
                 *
                 * nEndOfFindWhatSelection = ((strInput.Length - nIndex) / nNumReplacmentsInARow) + nIndex;
                 * if (!String.IsNullOrEmpty(strStuffFollowingMatch))
                 * {
                 *  nEndOfFindWhatSelection = strInput.IndexOf(strStuffFollowingMatch, nIndex + 1) / nNumReplacmentsInARow;
                 * }
                 */
#endif // !UseSplitToFindReplacements

                FoundAreaLength = nEndOfFindWhatSelection - nIndex;
                aRunRange.End   = SearchAreaStart + FoundAreaLength;

                // if we're doing ReplaceAll or Replace when the FindWhat string has been found...
                System.Diagnostics.Debug.Assert(FormButton != FormButtons.Cancel);  // means it wasn't initialized
                if (!DontReplaceOnNextFind &&
                    ((ReplaceAll) || ((FormButton == FormButtons.ReplaceOnce) && (nIndex == 0))))
                {
                    if (FormButton == FormButtons.ReplaceOnce)
                    {
                        DontReplaceOnNextFind = true;  // so we do a virtual find next after this
                    }
                    // this means replace the word in situ, with what was converted
                    ReplaceText(aRunRange, strReplacementString);
                    NumOfReplacements++;

                    // start the next search after this replaced value
                    string strReplacedText = aRunRange.Text;   // this may not be exactly the same as strReplace (e.g. after replacing final '\r')
                    if (!String.IsNullOrEmpty(strReplacedText))
                    {
                        FoundAreaLength  = strReplacedText.Length;
                        SearchAreaStart += FoundAreaLength;
                    }

                    res = FindResult.eReplaceFound;
                }
                else
                {
                    // select just the search string and return as if cancelled so the outer loop can prompt for it.
                    IsFound = true;

                    // select the FindWhat text found
                    aRunRange.Select();

                    res = FindResult.eFindFound;
                }
            }
            else if (FormButton == FormButtons.ReplaceOnce)
            {
                // otherwise, if the user clicked ReplaceOnce and we didn't find it right away,
                //  then change it to function like Find instead.
                DontReplaceOnNextFind = true;  // so we do a virtual find next after this
            }

            return(res);
        }
        public FindResult<PurchaseOrderViewModel> SearchPurchaseOrders(PurchaseOrderSearchOptions searchOptions)
        {
            FindResult<PurchaseOrderViewModel> purchaseOrderResult = new FindResult<PurchaseOrderViewModel>
            {
                Entities = new List<PurchaseOrderViewModel>(),
                Success = false,

            };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                purchaseOrderResult = purchaseOrderRepository.GetAll();

                if (!purchaseOrderResult.Success || purchaseOrderResult.Entities == null || purchaseOrderResult.Entities.Count == 0)
                {
                    return purchaseOrderResult;
                }

                List<PurchaseOrderViewModel> purchaseOrders = purchaseOrderResult.Entities;

                if (searchOptions.FromDate.HasValue)
                {

                    DateTime tDate = searchOptions.FromDate.Value;

                    purchaseOrders = purchaseOrders.Where(x => x.PurchaseOrderDate >= searchOptions.FromDate.Value).ToList();
                }

                if (searchOptions.ToDate.HasValue)
                {

                    purchaseOrders = purchaseOrders.Where(x => x.PurchaseOrderDate <= searchOptions.ToDate.Value).ToList();
                }

                if (!string.IsNullOrEmpty(searchOptions.InvoiceReferenceNumber))
                {
                    purchaseOrders = purchaseOrders.Where(x => x.SupplierReference.Contains(searchOptions.InvoiceReferenceNumber)).ToList();
                }

                purchaseOrders = purchaseOrders.OrderByDescending(x => x.PurchaseOrderDate).ToList();

                foreach (PurchaseOrderViewModel item in purchaseOrders)
                {

                    Supplier supplier = dbContext.SupplierSet.Where(x => x.SupplierId == item.SupplierId).FirstOrDefault();

                    SupplierViewModel cvm = ObjectMapper.PropertyMap(supplier, new SupplierViewModel());

                    item.Supplier = cvm;

                    //FindResult<PurchaseOrderItemViewModel> soItemResult = purchaseOrderItemRepository.FindBy(dbContext, x => x.PurchaseOrderId == item.PurchaseOrderId);

                    List<PurchaseOrderItemViewModel> poItemVMs = (from poitem in dbContext.PurchaseOrderItemSet
                                                                  join pv in dbContext.ProductVariantSet on poitem.ProductVariantId equals pv.ProductVariantId
                                                                  join prod in dbContext.ProductSet on pv.ProductId equals prod.ProductId
                                                                  where (poitem.PurchaseOrderId == item.PurchaseOrderId)
                                                                  select new PurchaseOrderItemViewModel
                                                                  {
                                                                      Price = poitem.Price,
                                                                      Quantity = poitem.Quantity,
                                                                      PurchaseOrderId = poitem.PurchaseOrderId,
                                                                      ProductVariantId = poitem.ProductVariantId,
                                                                      PurchaseOrderItemId = poitem.PurchaseOrderItemId,
                                                                      ProductName = prod.ProductName,
                                                                      SKUCode = pv.SKUCode,

                                                                  }).ToList();

                    if (poItemVMs != null)
                    {

                        foreach (var poItem in poItemVMs)
                        {
                            poItem.AttributeValueString = productVariantRepository.GetProductVariantAttributeValueString(poItem.ProductVariantId);
                        }

                        item.PurchaseOrderItems = poItemVMs;
                        item.InvoiceAmount = poItemVMs.Sum(x => (x.Amount));
                    }

                }

                if (searchOptions.SupplierId.HasValue)
                {
                    purchaseOrders = purchaseOrders.Where(x => x.Supplier.SupplierId == searchOptions.SupplierId).ToList();

                }

                purchaseOrderResult.Entities = purchaseOrders;
            }

            return purchaseOrderResult;
        }
 internal static IFileSystemInformation Create(FindResult findResult, string directory, IFileService fileService)
 {
     if ((findResult.Attributes & FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0)
     {
         return DirectoryInformation.Create(findResult, directory, fileService);
     }
     else
     {
         return FileInformation.Create(findResult, directory, fileService);
     }
 }
        public static async Task <FindResult> FindByImage(Mode mode, CancellationTokenSource cancellationTokenSource, string imageName = null, int timeOut = 20, string imgPath = null)
        {
            Console.WriteLine(@"[FIND_BY_IMAGE]");

            return(await Task.Run(() =>
            {
                FindResult result = null;

                for (var i = 0; i < timeOut; i++)
                {
                    if (cancellationTokenSource != null)
                    {
                        if (cancellationTokenSource.IsCancellationRequested)
                        {
                            break;
                        }
                    }

                    var currentPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
                    string filePath;
                    switch (mode)
                    {
                    case Mode.Login:
                        filePath = $"{currentPath}\\Resources\\login\\login.bmp";
                        break;

                    case Mode.Server:
                        filePath = $"{currentPath}\\Resources\\servers\\{imageName}.bmp";
                        break;

                    case Mode.Play:
                        filePath = $"{currentPath}\\Resources\\play\\play.bmp";
                        //filePath = imgPath;
                        break;

                    case Mode.ServerList:
                        filePath = $"{currentPath}\\Resources\\server_list.bmp";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
                    }

                    if (!File.Exists(filePath))
                    {
                        Console.WriteLine(@"Error : file not found : " + filePath);
                        break;
                    }
                    result = ImageHelper.SearchImage(filePath, 6);
                    Console.WriteLine($@"Looking for {mode} - {imageName} [{i}]");
                    if (result != null)
                    {
                        break;
                    }

                    Thread.Sleep(1000);
                }

                return result;
            }, cancellationTokenSource.Token));
        }
Exemple #28
0
 public bool Build(FindResult result)
 {
     results.Add(result);
     return(true);
 }
Exemple #29
0
        bool IsWholeWord(ITextStructureNavigator textStructureNavigator, ITextSnapshot snapshot, FindResult result)
        {
            Debug.Assert(textStructureNavigator != null);
            if (textStructureNavigator == null)
            {
                return(false);
            }
            if (result.Length == 0)
            {
                return(false);
            }
            var start = textStructureNavigator.GetExtentOfWord(new SnapshotPoint(snapshot, result.Position));

            if (start.Span.Start.Position != result.Position)
            {
                return(false);
            }
            var end = textStructureNavigator.GetExtentOfWord(new SnapshotPoint(snapshot, result.Position + result.Length - 1));

            return(end.Span.End.Position == result.Position + result.Length);
        }
        public async Task<IHttpActionResult> SearchStoreProductMatch(HttpRequestMessage request, [FromBody]StoreProductSearchRequest storeProductSearchRequest)
        {


            Task<IHttpActionResult> t = Task.Run<IHttpActionResult>(() =>
                {

                    FindResult<StoreProductSearchModel> searchResult = new FindResult<StoreProductSearchModel> { Success = false };

                    try
                    {

                        searchResult = externalProductService.SearchExternalStoreProduct(storeProductSearchRequest);
                        searchResult.Success = true;
                        return Ok(searchResult);
                    }
                    catch (Exception ex)
                    {
                        searchResult.ErrorMessage = string.Format("An error occurred while tryign to sarch products: {0}", ex.Message);
                        return Ok(searchResult);
                    }
                }

            );

            return await t;

        }
        // Find the left/right indices for adding a new node in the scope of the given list of nodes.
        // When left is true (and the point is not inside a node), finds the leftmost node with a start and end point >= the position.
        // When left is false (and the point is not inside a node), finds the rightmost node with a start and end point <= the position.
        static FindResult FindIndexForAdd(SnapshotPoint point, List <TrackingSpanNode <T> > nodes, bool left, int lo = -1, int hi = -1)
        {
            ITextSnapshot snapshot = point.Snapshot;
            int           position = point.Position;

            if (lo == -1)
            {
                lo = 0;
            }
            if (hi == -1)
            {
                hi = nodes.Count - 1;
            }

            // Use the general FindIndex to start
            FindResult result = FindChild(point, nodes, left, lo, hi);

            int          index   = result.Index;
            SnapshotSpan midSpan = nodes[index].TrackingSpan.GetSpan(snapshot);

            // If we hit a gap, figure out the correct index to use
            if (!result.Intersects)
            {
                // midSpan is the last span we found
                if (position < midSpan.Start && !left)
                {
                    index--;
                }
                else if (position > midSpan.End && left)
                {
                    index++;
                }
            }
            else if (result.Type == FindResultType.Outer)
            {
                // For an outer hit, we need to walk left or right to make sure we're containing all empty regions
                if (left)
                {
                    while (index <= hi)
                    {
                        midSpan = nodes[index].TrackingSpan.GetSpan(snapshot);
                        if (position <= midSpan.Start)
                        {
                            break;
                        }

                        index++;
                    }
                }
                else
                {
                    while (index >= lo)
                    {
                        midSpan = nodes[index].TrackingSpan.GetSpan(snapshot);
                        if (position >= midSpan.End)
                        {
                            break;
                        }

                        index--;
                    }
                }
            }

            return(new FindResult()
            {
                Type = result.Type, Index = index, Intersects = result.Intersects
            });
        }
        public FindResult<StoreProductSearchModel> SearchExternalStoreProduct(StoreProductSearchRequest searchRequest)
        {
            List<string> itemIds = new List<string>();

            FindResult<StoreProductSearchModel> searchResult = new FindResult<StoreProductSearchModel>()
            {
                Entities = new List<StoreProductSearchModel>(),
                Success = false
            };

            int totalItems = 0;

            eBayContext = eBayApiContextFactory.CreateServiceContext();
            eBayFindingApiClient findingClient = new eBayFindingApiClient(eBayFindingApiClient.FindingServiceType.findItemsByKeywords.ToString());

            FindItemsByKeywordsRequest request = new FindItemsByKeywordsRequest();

            request.keywords = searchRequest.ProductName;

            PaginationInput pagination = new PaginationInput();
            pagination.entriesPerPageSpecified = true;
            pagination.entriesPerPage = 100;
            pagination.pageNumberSpecified = true;
            pagination.pageNumber = 1;
            request.paginationInput = pagination;

            List<ItemFilter> filters = new List<ItemFilter>();

            filters.Add(new ItemFilter
            {
                name = ItemFilterType.Currency,
                value = new string[] { "GBP" }
            });

            filters.Add(new ItemFilter
            {
                name = ItemFilterType.Seller,
                value = new string[] { "stellatraders" },

            });

            request.itemFilter = filters.ToArray();

            request.sortOrderSpecified = true;

            request.sortOrder = SortOrderType.BestMatch;
            request.keywords = searchRequest.ProductName;

            FindItemsByKeywordsResponse response = findingClient.findItemsByKeywords(request);

            if (response.ack != AckValue.Failure)
            {
                if (response.paginationOutput.totalEntriesSpecified)
                {
                    totalItems = response.paginationOutput.totalEntries;
                }

                foreach (SearchItem searchItem in response.searchResult.item)
                {
                    if (itemIds.Contains(searchItem.itemId.Trim()))
                    {
                        continue;
                    }

                    itemIds.Add(searchItem.itemId);

                    searchResult.Entities.Add(ConvertSearchItemToSearchItemModel(searchItem));

                    //StoreProductSearchModel searchModel = new StoreProductSearchModel()
                    //{
                    //    ProductTitle = searchItem.title,
                    //    StoreProductId = searchItem.itemId,

                    //    StoreProductId1 = searchItem.productId.Value,

                    //};

                }

                if (response.paginationOutput.pageNumberSpecified && response.paginationOutput.totalPagesSpecified)
                {

                    int totalPages = response.paginationOutput.totalPages;
                    int currentPageNo = response.paginationOutput.pageNumber;

                    while (totalPages > currentPageNo)
                    {

                        currentPageNo += 1;
                        pagination.pageNumber = currentPageNo;
                        request.paginationInput = pagination;

                        response = findingClient.findItemsByKeywords(request);

                        if (response.ack != AckValue.Failure)
                        {
                            foreach (SearchItem searchItem in response.searchResult.item)
                            {

                                if (itemIds.Contains(searchItem.itemId.Trim()))
                                {
                                    continue;
                                }

                                itemIds.Add(searchItem.itemId);

                                searchResult.Entities.Add(ConvertSearchItemToSearchItemModel(searchItem));

                            }

                        }
                    }

                }

                searchResult.Success = true;
            }
            else
            {
                searchResult.Success = false;

                searchResult.ErrorMessage = "Error occurred while searching for product in Ebay";
            }

            return searchResult;
        }
 protected override void PopulateData(FindResult findResult, string directory)
 {
     base.PopulateData(findResult, directory);
 }
        static TrackingSpanNode <T> TryAddNodeToRoot(TrackingSpanNode <T> newNode, SnapshotSpan span, TrackingSpanNode <T> root)
        {
            var children = root.Children;

            if (children.Count == 0)
            {
                children.Add(newNode);
                return(newNode);
            }

            FindResult leftResult  = FindIndexForAdd(span.Start, children, left: true);
            FindResult rightResult = FindIndexForAdd(span.End, children, left: false);

            // See if we can add the node anywhere

            // The indices cross if the searches fail, and the node is inside a gap.
            if (leftResult.Index > rightResult.Index)
            {
                // Case #1: If the new node should go in a gap between two nodes, just insert it in the correct location
                Debug.Assert(leftResult.Type == FindResultType.Outer || rightResult.Type == FindResultType.Outer);

                children.Insert(leftResult.Index, newNode);
                return(newNode);
            }
            else
            {
                if (leftResult.Type == FindResultType.Inner || rightResult.Type == FindResultType.Inner)
                {
                    // Case #2: The new node is contained entirely in a single child node, so add it to that child
                    //  Check the nodes at either end of the resulting indices (they may not be the same index due to
                    //  0-length nodes that abut the correct child).
                    if (children[leftResult.Index].TrackingSpan.GetSpan(span.Snapshot).Contains(span))
                    {
                        return(TryAddNodeToRoot(newNode, span, children[leftResult.Index]));
                    }
                    if (leftResult.Index != rightResult.Index && children[rightResult.Index].TrackingSpan.GetSpan(span.Snapshot).Contains(span))
                    {
                        return(TryAddNodeToRoot(newNode, span, children[rightResult.Index]));
                    }

                    // This fails if the node isn't fully contained in a single child
                }
                else
                {
                    // Case #3: The new node contains any number of children, so we:
                    int start = leftResult.Index;
                    int count = rightResult.Index - leftResult.Index + 1;

                    // a) Add all the children this should contain to the new node,
                    newNode.Children.AddRange(children.Skip(start).Take(count));
                    // b) Remove them from the existing root node, and
                    children.RemoveRange(start, count);
                    // c) Add the new node in their place
                    children.Insert(start, newNode);

                    return(newNode);
                }
            }

            // We couldn't find a place to add this node, so return failure
            return(null);
        }
Exemple #35
0
    /// <summary>
    /// Find items by name.
    /// </summary>

    void FindAllByName(string partial)
    {
        partial = partial.ToLower();
        mResults.Clear();

        // Exact match comes first
        foreach (InvDatabase db in InvDatabase.list)
        {
            foreach (InvBaseItem item in db.items)
            {
                if (item.name.Equals(partial, System.StringComparison.OrdinalIgnoreCase))
                {
                    FindResult fr = new FindResult();
                    fr.db   = db;
                    fr.item = item;
                    mResults.Add(fr);
                }
            }
        }

        // Next come partial matches that begin with the specified string
        foreach (InvDatabase db in InvDatabase.list)
        {
            foreach (InvBaseItem item in db.items)
            {
                if (item.name.StartsWith(partial, System.StringComparison.OrdinalIgnoreCase))
                {
                    bool exists = false;

                    foreach (FindResult res in mResults)
                    {
                        if (res.item == item)
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        FindResult fr = new FindResult();
                        fr.db   = db;
                        fr.item = item;
                        mResults.Add(fr);
                    }
                }
            }
        }

        // Other partial matches come last
        foreach (InvDatabase db in InvDatabase.list)
        {
            foreach (InvBaseItem item in db.items)
            {
                if (item.name.ToLower().Contains(partial))
                {
                    bool exists = false;

                    foreach (FindResult res in mResults)
                    {
                        if (res.item == item)
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        FindResult fr = new FindResult();
                        fr.db   = db;
                        fr.item = item;
                        mResults.Add(fr);
                    }
                }
            }
        }
    }
            internal static FindResult FindNextFile(FindResult initialResult)
            {
                WIN32_FIND_DATA findData;
                if (!Private.FindNextFileW(initialResult.FindHandle.DangerousGetHandle(), out findData))
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error == WinError.ERROR_NO_MORE_FILES)
                    {
                        return null;
                    }
                    throw GetIoExceptionForError(error);
                }

                return new FindResult(initialResult.FindHandle, findData, initialResult.BasePath);
            }
        public GetEntityResult<ProductAttributeViewModel> FindById(Guid id)
        {
            GetEntityResult<ProductAttributeViewModel> getEntityResult = null;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                getEntityResult = productAttributeRepository.FindById(dbContext, id);

                if (!getEntityResult.Success)
                {
                    return getEntityResult;
                }

                FindResult<ProductAttributeViewModel> findResult = new FindResult<ProductAttributeViewModel>();

                findResult.Entities.Add(getEntityResult.Entity);

                findResult = SetFindResult(findResult, dbContext);

                getEntityResult.Success = true;

                getEntityResult.Entity = findResult.Entities.FirstOrDefault();
            }

            return getEntityResult;
        }
        static IEnumerable <TrackingSpanNode <T> > FindNodes(NormalizedSnapshotSpanCollection spans, TrackingSpanNode <T> root, bool recurse = true, bool contained = false)
        {
            if (spans == null || spans.Count == 0 || root.Children.Count == 0)
            {
                yield break;
            }

            int          requestIndex   = 0;
            SnapshotSpan currentRequest = spans[requestIndex];

            // Find the first child
            FindResult findResult = FindChild(currentRequest.Start, root.Children, left: true);
            int        childIndex = findResult.Index;

            if (childIndex >= root.Children.Count)
            {
                yield break;
            }

            ITextSnapshot snapshot     = currentRequest.Snapshot;
            SnapshotSpan  currentChild = root.Children[childIndex].TrackingSpan.GetSpan(snapshot);

            while (requestIndex < spans.Count && childIndex < root.Children.Count)
            {
                if (currentRequest.Start > currentChild.End)
                {
                    // Find the next child
                    childIndex = FindNextChild(root, currentRequest.Start, childIndex);

                    if (childIndex < root.Children.Count)
                    {
                        currentChild = root.Children[childIndex].TrackingSpan.GetSpan(snapshot);
                    }
                }
                else if (currentChild.Start > currentRequest.End)
                {
                    // Skip to the next request
                    if (++requestIndex < spans.Count)
                    {
                        currentRequest = spans[requestIndex];
                    }
                }
                else
                {
                    // Yield the region then move to the next
                    if (!contained || currentRequest.Contains(currentChild))
                    {
                        yield return(root.Children[childIndex]);
                    }

                    if (recurse)
                    {
                        foreach (var result in FindNodes(spans, root.Children[childIndex], recurse, contained))
                        {
                            yield return(result);
                        }
                    }

                    // Find the next child
                    childIndex = FindNextChild(root, currentRequest.Start, childIndex);

                    if (childIndex < root.Children.Count)
                    {
                        currentChild = root.Children[childIndex].TrackingSpan.GetSpan(snapshot);
                    }
                }
            }
        }
 protected virtual void PopulateData(FindResult findResult, string directory)
 {
     _source = Source.FindResult;
     Path = Paths.Combine(directory, findResult.FileName);
     Attributes = (System.IO.FileAttributes)findResult.Attributes;
     CreationTime = findResult.Creation;
     LastAccessTime = findResult.LastAccess;
     LastWriteTime = findResult.LastWrite;
     Name = findResult.FileName;
     Exists = true;
 }
Exemple #40
0
    /// <summary>
    /// Find items by name.
    /// </summary>

    void FindAllByName(string partial)
    {
        partial = partial.ToLower();
        mResults.Clear();
        {
            var __array2       = InvDatabase.list;
            var __arrayLength2 = __array2.Length;
            for (int __i2 = 0; __i2 < __arrayLength2; ++__i2)
            {
                var db = (InvDatabase)__array2[__i2];
                {
                    {
                        // foreach(var item in db.items)
                        var __enumerator5 = (db.items).GetEnumerator();
                        while (__enumerator5.MoveNext())
                        {
                            var item = (InvBaseItem)__enumerator5.Current;
                            {
                                if (item.name.Equals(partial, System.StringComparison.OrdinalIgnoreCase))
                                {
                                    FindResult fr = new FindResult();
                                    fr.db   = db;
                                    fr.item = item;
                                    mResults.Add(fr);
                                }
                            }
                        }
                    }
                }
            }
        }
        {
            var __array3       = InvDatabase.list;
            var __arrayLength3 = __array3.Length;
            for (int __i3 = 0; __i3 < __arrayLength3; ++__i3)
            {
                var db = (InvDatabase)__array3[__i3];
                {
                    {
                        // foreach(var item in db.items)
                        var __enumerator7 = (db.items).GetEnumerator();
                        while (__enumerator7.MoveNext())
                        {
                            var item = (InvBaseItem)__enumerator7.Current;
                            {
                                if (item.name.StartsWith(partial, System.StringComparison.OrdinalIgnoreCase))
                                {
                                    bool exists = false;
                                    {
                                        var __list10      = mResults;
                                        var __listCount10 = __list10.Count;
                                        for (int __i10 = 0; __i10 < __listCount10; ++__i10)
                                        {
                                            var res = (FindResult)__list10[__i10];
                                            {
                                                if (res.item == item)
                                                {
                                                    exists = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    if (!exists)
                                    {
                                        FindResult fr = new FindResult();
                                        fr.db   = db;
                                        fr.item = item;
                                        mResults.Add(fr);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        {
            var __array4       = InvDatabase.list;
            var __arrayLength4 = __array4.Length;
            for (int __i4 = 0; __i4 < __arrayLength4; ++__i4)
            {
                var db = (InvDatabase)__array4[__i4];
                {
                    {
                        // foreach(var item in db.items)
                        var __enumerator9 = (db.items).GetEnumerator();
                        while (__enumerator9.MoveNext())
                        {
                            var item = (InvBaseItem)__enumerator9.Current;
                            {
                                if (item.name.ToLower().Contains(partial))
                                {
                                    bool exists = false;
                                    {
                                        var __list11      = mResults;
                                        var __listCount11 = __list11.Count;
                                        for (int __i11 = 0; __i11 < __listCount11; ++__i11)
                                        {
                                            var res = (FindResult)__list11[__i11];
                                            {
                                                if (res.item == item)
                                                {
                                                    exists = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    if (!exists)
                                    {
                                        FindResult fr = new FindResult();
                                        fr.db   = db;
                                        fr.item = item;
                                        mResults.Add(fr);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
		public FindResult GetMatchingEntries(string writingSystemId, string form, string findMethod)
		{
			FindMethods method;
			try
			{
				method = (FindMethods) Enum.Parse(typeof (FindMethods), findMethod);
			}
			catch (ArgumentException e)
			{
				throw new ArgumentException(
						"'" + findMethod + "' is not a recognized find method.", e);
			}

			//in case something goes wrong
			FindResult r = new FindResult();
			try
			{
				Logger.WriteMinorEvent("GetIdsOfMatchingEntries({0},{1},{2})",
									   writingSystemId,
									   form,
									   method.ToString());
				if (!_project.WritingSystems.ContainsKey(writingSystemId))
				{
					return r;
				}
				WritingSystem ws = _project.WritingSystems[writingSystemId];

				ResultSet<LexEntry> matches;
				switch (method)
				{
					case FindMethods.Exact:
						matches = _lexEntryRepository.GetEntriesWithMatchingLexicalForm(form, ws);
						break;

					default:
					case FindMethods.DefaultApproximate:
						matches = _lexEntryRepository.GetEntriesWithSimilarLexicalForm(form,
																					   ws,
																					   ApproximateMatcherOptions
																							   .
																							   IncludePrefixedAndNextClosestForms);
						break;
				}
				r.ids = new string[matches.Count];
				r.forms = new string[matches.Count];
				int i = 0;
				foreach (RecordToken<LexEntry> token in matches)
				{
					LexEntry entry = token.RealObject;
					if (i == _maxNumberOfEntriesToReturn)
					{
						break;
					}
					r.forms[i] = entry.LexicalForm.GetBestAlternative(writingSystemId);
					r.ids[i] = entry.Id;
					i++;
				}
			}
			catch (Exception e)
			{
				Logger.WriteEvent("Error from dictionary services, RegisterClient: " + e.Message);
				Debug.Fail(e.Message);
			}
			return r;
		}
Exemple #42
0
        public static void Deploy(string commandLine)
        {
            if (!_coarseLog.IsDebugEnabled)
            {
                Console.WriteLine("Sad Emo Otter says \"DEBUG LOGGING IS OFF - THIS ISN'T GOING TO BE FUN :(\"");
            }

            try
            {
                _coarseLog.Info("****************************************************");
                _coarseLog.Info("DropkicK");
                _coarseLog.Info("****************************************************");
                _coarseLog.Info("");

                DeploymentArguments newArgs = DeploymentCommandLineParser.Parse(commandLine);



                _coarseLog.Info("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
                _coarseLog.InfoFormat("Command:     {0}", newArgs.Command);
                _coarseLog.InfoFormat("Environment: {0}", newArgs.Environment);
                _coarseLog.InfoFormat("Role:        {0}", newArgs.Role);

                //////// DEPLOYMENT STUFF
                FindResult findResult = _finder.Find(newArgs.Deployment);
                Deployment deployment = findResult.Deployment;
                _coarseLog.InfoFormat("Deployment Method: '{0}'", findResult.MethodOfFinding);
                _coarseLog.InfoFormat("Deployment Found:  '{0}'", findResult.Deployment.GetType().Name);

                if (deployment.GetType().Equals(typeof(NullDeployment)))
                {
                    _coarseLog.Fatal("Couldn't find a deployment to run.");
                    return;
                }
                ////////



                ////////// File Checks
                if (!VerifyPathToServerMapsFile(newArgs.PathToServerMapsFile))
                {
                    return;
                }
                if (!VerifyPathToSettingsFile(newArgs.PathToSettingsFile))
                {
                    return;
                }
                ////////////////////

                RoleToServerMap maps = _serverParser.Parse(new FileInfo(newArgs.PathToServerMapsFile));
                newArgs.ServerMappings.Merge(maps);
                DisplayServerMappingsForEnvironment(newArgs.ServerMappings);

                if (!newArgs.Quiet)
                {
                    _coarseLog.Info("");
                    _coarseLog.Info("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
                    _coarseLog.Info("Please review the settings above when you are ready,");
                    _coarseLog.Info("  Press 'ctrl+c' to cancel.");
                }

                if (deployment.HardPrompt)
                {
                    bool wrong = true;
                    do
                    {
                        _coarseLog.Info("  Please type the environment name '{0}' to continue.".FormatWith(newArgs.Environment));
                        var environment = Console.ReadLine();
                        if (environment.EqualsIgnoreCase(newArgs.Environment))
                        {
                            wrong = false;
                        }
                    } while (wrong);
                }
                else if (!newArgs.Quiet)
                {
                    _coarseLog.Info("  Press enter to kick it out there");
                    Console.ReadKey(true);
                }



                /////// how to clean this up - below
                Type settingsType = deployment.GetType().BaseType.GetGenericArguments()[1];

                var settings = (DropkickConfiguration)_parser.Parse(settingsType, new FileInfo(newArgs.PathToSettingsFile), commandLine,
                                                                    newArgs.Environment);

                settings.Environment = newArgs.Environment;
                deployment.Initialize(settings);

                DeploymentPlanDispatcher.KickItOutThereAlready(deployment, newArgs);
            }
            catch (Exception ex)
            {
                _coarseLog.Debug(commandLine);
                _coarseLog.Error(ex);
            }
        }
        public GetEntityResult<CategorySubCategoryMapViewModel> GetCategorySubCategoryMap(Guid categoryId, Guid subCategoryId)
        {
            FindResult<CategorySubCategoryMapViewModel> findResult = new FindResult<CategorySubCategoryMapViewModel>();

            findResult = categorySubCategoryMapRepo.FindBy(x => x.CategoryId == categoryId && x.SubCategoryId == subCategoryId);

            GetEntityResult<CategorySubCategoryMapViewModel> result = new GetEntityResult<CategorySubCategoryMapViewModel>();

            if (findResult.Success)
            {
                result.Entity = findResult.Entities.FirstOrDefault();
                result.Success = true;
            }
            else
            {
                result.Success = false;
                result.Entity = null;
            }

            return result;
        }
Exemple #44
0
        private FindResult FindFace(Image InputImage)
        {
            int   counter = 0;
            float face_width, face_height, face_delta_min, face_delta_max;
            int   dpi;

            try
            {
                face_width     = float.Parse(ConfigurationManager.AppSettings["face_width"], System.Globalization.CultureInfo.InvariantCulture);
                face_height    = float.Parse(ConfigurationManager.AppSettings["face_height"], System.Globalization.CultureInfo.InvariantCulture);
                face_delta_min = float.Parse(ConfigurationManager.AppSettings["face_delta_min"], System.Globalization.CultureInfo.InvariantCulture);
                face_delta_max = float.Parse(ConfigurationManager.AppSettings["face_delta_max"], System.Globalization.CultureInfo.InvariantCulture);
                dpi            = int.Parse(ConfigurationManager.AppSettings["ScannerDpi"]);
            }
            catch
            {
                //Console.WriteLine("Не смог считать параметры face_wigth и.т.д.");
                logger.Error("Не смог считать параметры face_wigth и.т.д.");
                face_width     = 2.0f;
                face_height    = 2.6f;
                face_delta_min = 0.2f;
                face_delta_max = 0.9f;
                dpi            = 300;
            }
            double minRectangleSquare = face_width * face_height * face_delta_min;
            double maxRectamgleSquare = face_width * face_height * face_delta_max;

            int goodFacesFound = 0;
            var Result         = new FindResult(false, null);

            while (counter <= 3)
            {
                FaceDetectorProcessor scanFaceDetectorProcessor = new FaceDetectorProcessor(new Image <Bgr, byte>(new Bitmap(InputImage)));
                Rectangle[]           facesOnScan = scanFaceDetectorProcessor.isFaceDetected();
                goodFacesFound = 0;
                double RectangleSquare = 0;
                foreach (var item in facesOnScan)
                {
                    RectangleSquare = ((double)item.Width / Math.Round(InputImage.HorizontalResolution) * 2.54 * ((double)item.Height / Math.Round(InputImage.HorizontalResolution)) * 2.54);
                    var croppedFace = DocDetector.CropImage(new Bitmap(InputImage), item);
                    if (checkFaceSquare(RectangleSquare, minRectangleSquare, maxRectamgleSquare))
                    {
                        croppedFace.Save("ScanCropedFaceGood" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".jpg");
                        Result.update(true, croppedFace);
                        goodFacesFound++;
                    }
                    else
                    {
                        Result.update(false, croppedFace);
                        croppedFace.Save("ScanCropedFaceBad" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".jpg");
                    }
                }
                if (goodFacesFound == 1)
                {
                    return(Result);
                    //return new FindResult(true,)
                }
                InputImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
                scanFaceDetectorProcessor = null;
                facesOnScan = null;
                counter++;
                System.Windows.Forms.Application.DoEvents();
            }
            return(Result);
        }
 protected override void PopulateData(FindResult findResult, string directory)
 {
     base.PopulateData(findResult, directory);
 }
        public void run()
        {
            IXConnFactory connFact = null;
            IXConnection  ix       = null;

            try
            {
                IXProperties connProps = IXConnFactory.CreateConnProperties(url);
                IXProperties sessOpts  = IXConnFactory.CreateSessionOptions("IX-Examples", "1.0");
                connFact = new IXConnFactory(connProps, sessOpts);
                Logger.instance().log("create IXConnFactory OK");

                // Prepare ClientInfo object with language and country
                // ClientInfo ci = new ClientInfo();
                // ci.language = "de";
                // ci.country = "DE";

                // LOGIN
                Logger.instance().log("login...");
                ix = connFact.Create(userName, userPwd, "myComputer", null);
                // ci = ix.Login.ci
                Logger.instance().log("login OK");

                // get constants
                Logger.instance().log("get const...");
                IXServicePortC CONST = ix.CONST;
                Logger.instance().log("get const OK");

                // 1. Create a root folder
                Sord sordRoot = ix.Ix.createSord("1", null, EditInfoC.mbSord).sord;
                sordRoot.name = "C# example FindFirstFindNext";
                sordRoot.id   = ix.Ix.checkinSord(sordRoot, SordC.mbAll, LockC.NO);

                // 2. Create 30 sords under the root folder with a name that contains the search term
                Logger.instance().log("create " + nbOfSords + " sords...");
                for (int i = 0; i < nbOfSords; i++)
                {
                    String namePrefix = "" + i;
                    while (namePrefix.Length < 4)
                    {
                        namePrefix = "0" + namePrefix;
                    }
                    Sord sord = ix.Ix.createSord(sordRoot.guid, null, EditInfoC.mbSord).sord;
                    sord.name = namePrefix + "-" + searchTerm + "-" + namePrefix;
                    sord.id   = ix.Ix.checkinSord(sord, SordC.mbAll, LockC.NO);
                }
                Logger.instance().log("create sords OK");

                // 3. Execute find
                Logger.instance().log("find...");

                // Prepare FindInfo object
                FindInfo findInfo = new FindInfo();
                findInfo.findByIndex      = new FindByIndex();
                findInfo.findByIndex.name = "*" + searchTerm + "*";

                // find
                int maxSordsPerLoop = 9;
                int idx             = 0;

                SordZ sordZ = new SordZ();

                FindResult findResult = ix.Ix.findFirstSords(findInfo, maxSordsPerLoop, SordC.mbAll);

                do
                {
                    // log find results
                    Logger.instance().log("found #=" + findResult.sords.Length);
                    for (int i = 0; i < findResult.sords.Length; i++)
                    {
                        Logger.instance().log("sord.id=" + findResult.sords[i].id + ", sord.name=" + findResult.sords[i].name);
                    }

                    // more results?
                    if (!findResult.moreResults)
                    {
                        break;
                    }

                    // next results
                    idx       += findResult.sords.Length;
                    findResult = ix.Ix.findNextSords(findResult.searchId, idx, maxSordsPerLoop, SordC.mbAll);
                } while (true);

                // release find result buffer in IndexServer
                ix.Ix.findClose(findResult.searchId);
                Logger.instance().log("find OK");

                // clean up
                bool cleanUp = true;
                if (cleanUp)
                {
                    DeleteOptions delOpts = new DeleteOptions();
                    delOpts.deleteFinally = true;
                    ix.Ix.deleteSord(null, sordRoot.guid, LockC.NO, null);
                    ix.Ix.deleteSord(null, sordRoot.guid, LockC.NO, delOpts);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // Logout
                // --
                if (ix != null)
                {
                    Logger.instance().log("IX logout...");
                    ix.Logout();
                    Logger.instance().log("IX logout OK");
                }
            }
        }
 public IUnityYamlReference Build(FindResult result)
 {
     return((result as FindResultReference)?.Reference as IUnityYamlReference);
 }
Exemple #48
0
        //public async void Zoom()
        //{
        //    // define a new camera over San Francisco
        //    var camera = new Camera(32.715, -117.1625, 330.0, 180, 73.0);
        //    // create a ViewPoint with the camera, a target geometry (Envelope), and rotation (same as camera heading)
        //    var viewPoint = new Viewpoint(camera, new Envelope(31, -116, 33, 118, SpatialReferences.Wgs84), 126.0);
        //    var animationDuration = new TimeSpan(71.75, 36.5, 2);

        //    await this.sceneView.SetViewAsync(viewPoint, animationDuration, true);
        //}
        //public async void Zoom()
        //{
        //    // define a new camera over Everest
        //    var camera = new Camera(28.1, 86.9253, 8000, 180, 73.0);
        //    // create a ViewPoint with the camera, a target geometry (Envelope), and rotation (same as camera heading)
        //    var viewPoint = new Viewpoint(camera, new Envelope(27.9, 86.7, 28.1, 87.3, SpatialReferences.Wgs84), 126.0);
        //    var animationDuration = new TimeSpan(71.75, 36.5, 2);

        //    await this.sceneView.SetViewAsync(viewPoint, animationDuration, true);
        //}
        public async void Search(int wkid)
        {
            var findTask = new FindTask(new System.Uri(this.USAUri));

            var findParameters = new FindParameters();

            findParameters.LayerIDs.Add(0); // Cities
            findParameters.LayerIDs.Add(3); // Counties
            findParameters.LayerIDs.Add(2); // States

            findParameters.SearchFields.Add("name");
            findParameters.SearchFields.Add("areaname");
            findParameters.SearchFields.Add("state_name");

            findParameters.ReturnGeometry = true;

            SpatialReference sr = new SpatialReference(wkid);

            findParameters.SpatialReference = sr;


            findParameters.SearchText = this.SearchText;
            findParameters.Contains   = true;

            FindResult findResult = await
                                    findTask.ExecuteAsync(findParameters);

            var foundCities   = 0;
            var foundCounties = 0;
            var foundStates   = 0;

            // Loop thru results; count the matches found in each layer
            foreach (FindItem findItem in findResult.Results)
            {
                switch (findItem.LayerID)
                {
                case 0:     // Cities
                    foundCities++;
                    break;

                case 3:     // Counties
                    foundCounties++;
                    break;

                case 2:     // States
                    foundStates++;
                    break;
                }
            }

            // Report the number of matches for each layer
            var msg = string.Format("Found {0} cities, {1} counties, and {2} states containing '" + this.SearchText +
                                    "' in a Name attribute", foundCities, foundCounties,
                                    foundStates);

            // Bind the results to a DataGrid control on the page
            IReadOnlyList <FindItem> temp = findResult.Results;

            ObservableCollection <FindItem> obsCollection = new ObservableCollection <FindItem>();

            foreach (FindItem item in temp)
            {
                obsCollection.Add(item);
            }

            this.GridDataResults = obsCollection;

            // show message
            Messenger.Default.Send <NotificationMessage>(new NotificationMessage(msg));
        }
Exemple #49
0
 public bool Equals(FindResult other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return Equals(other.FindPredicate, FindPredicate) && Equals(other.Document, Document) && Equals(other.Bookmark, Bookmark) && Equals(other.FindMatch, FindMatch) && other.IsValid.Equals(IsValid) && Equals(other.LocationName, LocationName) && Equals(other.LocationType, LocationType);
 }
Exemple #50
0
        /// <summary>
        /// Determines whether a variable should be inlined in non-aggressive mode, even though it is not a generated variable.
        /// </summary>
        /// <param name="next">The next top-level expression</param>
        /// <param name="v">The variable being eliminated by inlining.</param>
        /// <param name="inlinedExpression">The expression being inlined</param>
        static bool NonAggressiveInlineInto(ILInstruction next, FindResult findResult, ILInstruction inlinedExpression, ILVariable v)
        {
            if (findResult.Type == FindResultType.NamedArgument)
            {
                var originalStore = (StLoc)inlinedExpression.Parent;
                return(!originalStore.ILStackWasEmpty);
            }
            Debug.Assert(findResult.Type == FindResultType.Found);

            var loadInst = findResult.LoadInst;

            Debug.Assert(loadInst.IsDescendantOf(next));

            // decide based on the source expression being inlined
            switch (inlinedExpression.OpCode)
            {
            case OpCode.DefaultValue:
            case OpCode.StObj:
            case OpCode.NumericCompoundAssign:
            case OpCode.UserDefinedCompoundAssign:
            case OpCode.Await:
            case OpCode.SwitchInstruction:
                return(true);

            case OpCode.LdLoc:
                if (v.StateMachineField == null && ((LdLoc)inlinedExpression).Variable.StateMachineField != null)
                {
                    // Roslyn likes to put the result of fetching a state machine field into a temporary variable,
                    // so inline more aggressively in such cases.
                    return(true);
                }
                break;
            }
            if (inlinedExpression.ResultType == StackType.Ref)
            {
                // VB likes to use ref locals for compound assignment
                // (the C# compiler uses ref stack slots instead).
                // We want to avoid unnecessary ref locals, so we'll always inline them if possible.
                return(true);
            }

            var parent = loadInst.Parent;

            if (NullableLiftingTransform.MatchNullableCtor(parent, out _, out _))
            {
                // inline into nullable ctor call in lifted operator
                parent = parent.Parent;
            }
            if (parent is ILiftableInstruction liftable && liftable.IsLifted)
            {
                return(true);                // inline into lifted operators
            }
            // decide based on the new parent into which we are inlining:
            switch (parent.OpCode)
            {
            case OpCode.NullCoalescingInstruction:
                if (NullableType.IsNullable(v.Type))
                {
                    return(true);                            // inline nullables into ?? operator
                }
                break;

            case OpCode.NullableUnwrap:
                return(true);                        // inline into ?. operator

            case OpCode.UserDefinedLogicOperator:
            case OpCode.DynamicLogicOperatorInstruction:
                return(true);                        // inline into (left slot of) user-defined && or || operator

            case OpCode.DynamicGetMemberInstruction:
            case OpCode.DynamicGetIndexInstruction:
                if (parent.Parent.OpCode == OpCode.DynamicCompoundAssign)
                {
                    return(true);                            // inline into dynamic compound assignments
                }
                break;

            case OpCode.DynamicCompoundAssign:
                return(true);

            case OpCode.GetPinnableReference:
            case OpCode.LocAllocSpan:
                return(true);                        // inline size-expressions into localloc.span

            case OpCode.Call:
            case OpCode.CallVirt:
                // Aggressive inline into property/indexer getter calls for compound assignment calls
                // (The compiler generates locals for these because it doesn't want to evalute the args twice for getter+setter)
                if (parent.SlotInfo == CompoundAssignmentInstruction.TargetSlot)
                {
                    return(true);
                }
                if (((CallInstruction)parent).Method is SyntheticRangeIndexAccessor)
                {
                    return(true);
                }
                break;

            case OpCode.CallIndirect when loadInst.SlotInfo == CallIndirect.FunctionPointerSlot:
                return(true);

            case OpCode.LdElema:
                if (((LdElema)parent).WithSystemIndex)
                {
                    return(true);
                }
                break;

            case OpCode.Leave:
            case OpCode.YieldReturn:
                return(true);

            case OpCode.SwitchInstruction:
            //case OpCode.BinaryNumericInstruction when parent.SlotInfo == SwitchInstruction.ValueSlot:
            case OpCode.StringToInt when parent.SlotInfo == SwitchInstruction.ValueSlot:
                return(true);

            case OpCode.MatchInstruction when((MatchInstruction)parent).IsDeconstructTuple:
                return(true);
            }
            // decide based on the top-level target instruction into which we are inlining:
            switch (next.OpCode)
            {
            case OpCode.IfInstruction:
                while (parent.MatchLogicNot(out _))
                {
                    parent = parent.Parent;
                }
                return(parent == next);

            default:
                return(false);
            }
        }
Exemple #51
0
 public FindResult ChangeDocument(SrmDocument document)
 {
     var result = new FindResult(this) {Document = document};
     var bookMarkEnumerator = BookmarkEnumerator.TryGet(document, Bookmark);
     FindMatch findMatch = null;
     if (bookMarkEnumerator != null)
     {
         findMatch = FindPredicate.Match(bookMarkEnumerator);
     }
     if (findMatch == null)
     {
         result.IsValid = false;
     }
     else
     {
         result.IsValid = true;
         result.FindMatch = findMatch;
     }
     return result;
 }
Exemple #52
0
        /// <summary>
        /// Finds the position to inline to.
        /// </summary>
        /// <returns>true = found; false = cannot continue search; null = not found</returns>
        internal static FindResult FindLoadInNext(ILInstruction expr, ILVariable v, ILInstruction expressionBeingMoved, InliningOptions options)
        {
            if (expr == null)
            {
                return(FindResult.Stop);
            }
            if (expr.MatchLdLoc(v) || expr.MatchLdLoca(v))
            {
                // Match found, we can inline
                if (expr.SlotInfo == StObj.TargetSlot && !((StObj)expr.Parent).CanInlineIntoTargetSlot(expressionBeingMoved))
                {
                    if ((options & InliningOptions.AllowChangingOrderOfEvaluationForExceptions) != 0)
                    {
                        // Intentionally change code semantics so that we can avoid a ref local
                        if (expressionBeingMoved is LdFlda ldflda)
                        {
                            ldflda.DelayExceptions = true;
                        }
                        else if (expressionBeingMoved is LdElema ldelema)
                        {
                            ldelema.DelayExceptions = true;
                        }
                    }
                    else
                    {
                        // special case: the StObj.TargetSlot does not accept some kinds of expressions
                        return(FindResult.Stop);
                    }
                }
                return(FindResult.Found(expr));
            }
            else if (expr is Block block)
            {
                // Inlining into inline-blocks?
                switch (block.Kind)
                {
                case BlockKind.ControlFlow when block.Parent is BlockContainer:
                case BlockKind.ArrayInitializer:
                case BlockKind.CollectionInitializer:
                case BlockKind.ObjectInitializer:
                case BlockKind.CallInlineAssign:
                    // Allow inlining into the first instruction of the block
                    if (block.Instructions.Count == 0)
                    {
                        return(FindResult.Stop);
                    }
                    return(NoContinue(FindLoadInNext(block.Instructions[0], v, expressionBeingMoved, options)));

                // If FindLoadInNext() returns null, we still can't continue searching
                // because we can't inline over the remainder of the block.
                case BlockKind.CallWithNamedArgs:
                    return(NamedArgumentTransform.CanExtendNamedArgument(block, v, expressionBeingMoved));

                default:
                    return(FindResult.Stop);
                }
            }
            else if (options.HasFlag(InliningOptions.FindDeconstruction) && expr is DeconstructInstruction di)
            {
                return(FindResult.Deconstruction(di));
            }
            foreach (var child in expr.Children)
            {
                if (!expr.CanInlineIntoSlot(child.ChildIndex, expressionBeingMoved))
                {
                    return(FindResult.Stop);
                }

                // Recursively try to find the load instruction
                FindResult r = FindLoadInNext(child, v, expressionBeingMoved, options);
                if (r.Type != FindResultType.Continue)
                {
                    if (r.Type == FindResultType.Stop && (options & InliningOptions.IntroduceNamedArguments) != 0 && expr is CallInstruction call)
                    {
                        return(NamedArgumentTransform.CanIntroduceNamedArgument(call, child, v, expressionBeingMoved));
                    }
                    return(r);
                }
            }
            if (IsSafeForInlineOver(expr, expressionBeingMoved))
            {
                return(FindResult.Continue);                // continue searching
            }
            else
            {
                return(FindResult.Stop);                // abort, inlining not possible
            }
        }
Exemple #53
0
	/// <summary>
	/// Find items by name.
	/// </summary>

	void FindAllByName (string partial)
	{
		partial = partial.ToLower();
		mResults.Clear();

		// Exact match comes first
		foreach (InvDatabase db in InvDatabase.list)
		{
			foreach (InvBaseItem item in db.items)
			{
				if (item.name.Equals(partial, System.StringComparison.OrdinalIgnoreCase))
				{
					FindResult fr = new FindResult();
					fr.db = db;
					fr.item = item;
					mResults.Add(fr);
				}
			}
		}

		// Next come partial matches that begin with the specified string
		foreach (InvDatabase db in InvDatabase.list)
		{
			foreach (InvBaseItem item in db.items)
			{
				if (item.name.StartsWith(partial, System.StringComparison.OrdinalIgnoreCase))
				{
					bool exists = false;

					foreach (FindResult res in mResults)
					{
						if (res.item == item)
						{
							exists = true;
							break;
						}
					}

					if (!exists)
					{
						FindResult fr = new FindResult();
						fr.db = db;
						fr.item = item;
						mResults.Add(fr);
					}
				}
			}
		}

		// Other partial matches come last
		foreach (InvDatabase db in InvDatabase.list)
		{
			foreach (InvBaseItem item in db.items)
			{
				if (item.name.ToLower().Contains(partial))
				{
					bool exists = false;

					foreach (FindResult res in mResults)
					{
						if (res.item == item)
						{
							exists = true;
							break;
						}
					}

					if (!exists)
					{
						FindResult fr = new FindResult();
						fr.db = db;
						fr.item = item;
						mResults.Add(fr);
					}
				}
			}
		}
	}
        /// <summary>
        /// Fonction qui va permettre de trouver la position d'un élément sur l'écran.
        /// </summary>
        /// <param name="textToFind"></param>
        /// <param name="cancellationTokenSource"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static async Task <FindResult> FindByOcr(OcrString ocrString, CancellationTokenSource cancellationTokenSource, int timeOut = 20)
        {
            Console.WriteLine(@"[FIND_BY_OCR]");

            return(await Task.Run(() =>
            {
                FindResult result = null;

                for (var i = 0; i < timeOut; i++)
                {
                    if (cancellationTokenSource != null)
                    {
                        if (cancellationTokenSource.IsCancellationRequested)
                        {
                            break;
                        }
                    }


                    var p = new Process();
                    var findByOcrExe = Path.Combine(Environment.CurrentDirectory, @"Resources\find_by_ocr.exe");
                    if (!File.Exists(findByOcrExe))
                    {
                        result = new FindResult($"[ERREUR] : Impossible de trouver {findByOcrExe}");
                        break;
                    }

                    var pi = new ProcessStartInfo(findByOcrExe, ocrString.Data);
                    p.StartInfo = pi;
                    pi.UseShellExecute = false;
                    p.OutputDataReceived += (w, o) =>
                    {
                        if (string.IsNullOrEmpty(o.Data) || o.Data.Trim().Length <= 2 || !o.Data.Contains(";"))
                        {
                            return;
                        }
                        try
                        {
                            var point = o.Data.Trim().Split(';');
                            var x = Convert.ToInt32(point[0].Substring(0, point[0].IndexOf('.') > 0 ? point[0].IndexOf('.') : point[0].Length));
                            var y = Convert.ToInt32(point[1].Substring(0, point[1].IndexOf('.') > 0 ? point[1].IndexOf('.') : point[1].Length));
                            Console.WriteLine($@"[FIND_BY_OCR] : {x}:{y}");
                            result = new FindResult(x, y);
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    };
                    p.EnableRaisingEvents = true;
                    pi.RedirectStandardOutput = true;
                    pi.StandardOutputEncoding = Encoding.UTF8;


                    Console.WriteLine($@"Looking for {ocrString.Name} [{i}]");


                    p.Start();
                    p.BeginOutputReadLine();

                    p.WaitForExit();



                    if (result != null && string.IsNullOrEmpty(result.Error))
                    {
                        break;
                    }

                    Thread.Sleep(1000);
                }


                return result;
            }));
        }