public static IEnumerable<RecipeDef> AllRecipes()
        {
            List<RecipeDef> list = new List<RecipeDef>();

            foreach (var def in DefDatabase<ManufacturingPlantRecipesDef>.AllDefs)
            {
                foreach (var recipe in def.recipes)
                {
                    list.Add(recipe);
                }
            }
            foreach (var def in DefDatabase<RecipeDef>.AllDefs.Where(d => d.workSkill != null && (d.workSkill == SkillDefOf.Crafting || d.workSkill == SkillDefOf.Cooking || d.workSkill == SkillDefOf.Artistic)))
            {
                if(!list.Contains(def))
                    list.Add(def);
            }
            foreach (var def in DefDatabase<ManufacturingPlantRecipesDef>.AllDefs)
            {
                if (def.blackList != null)
                {
                    foreach (var recipe in def.blackList)
                    {
                        if (list.Contains(recipe))
                        {
                            list.Remove(recipe);
                        }
                    }
                }
            }
            return list.AsEnumerable();
        }
        public IEnumerable<Product> getProduct(IEnumerable<ProductModel> data)
        {
            var list = new List<Product>();
            if (data.Count() > 0)
            {
                foreach (var model in data)
                {
                    var prod = new Product();

                    if (model != null)
                    {
                        prod.CategoryId = model.CategoryId;
                        prod.Discontinued = model.Discontinued;
                        prod.Name = model.Name;
                        prod.ProductCategory = getCategory(model.ProductCategory);
                        prod.ProductId = model.ProductId;
                        prod.ProductSupplier = getSupplier(model.ProductSupplier);
                        prod.QuantityPerUnit = model.QuantityPerUnit;
                        prod.ReorderLevel = model.ReorderLevel;
                        prod.SupplierId = model.SupplierId;
                        prod.UnitPrice = model.UnitPrice;
                        prod.UnitsInStock = model.UnitsInStock;
                        prod.UnitsOnOrder = model.UnitsOnOrder;
                    }
                    list.Add(prod);
                }
            }
            return list.AsEnumerable();
        }
Ejemplo n.º 3
0
        public override void Execute()
        {
            List<XElement> xList = new List<XElement>();

            for(int i=0; i < QueueState.Count();i++)
            {
                IBuilding b = QueueState.ElementAt(i).Key;
                IBuildingFunction f = BuildingState.Where( x => x.Value == b).FirstOrDefault().Key;
                ITimer t = QueueState.ElementAt(i).Value;

                XElement xEl = new XElement("Queue",
                    new XElement("Building",
                        new XElement("Id", b.Id),
                        new XElement("Time", t.Get()),
                        new XElement("Function",f.Name),
                        new XElement("X",b.Tile.X),
                        new XElement("Z",b.Tile.Z)
                        ));
                xList.Add(xEl);
            }

            XElement New = new XElement("QueueSystem",
               xList.AsEnumerable()
                   );
            Debug.Log(New.ToString());
            GameData.SaveQueueState(New);
        }
Ejemplo n.º 4
0
        public static IReparentingHost FindReparentingHost(this IControl control)
        {
            var tp = control.TemplatedParent;
            var chain = new List<IReparentingHost>();

            while (tp != null)
            {
                var reparentingHost = tp as IReparentingHost;
                var styleable = tp as IStyleable;

                if (reparentingHost != null)
                {
                    chain.Add(reparentingHost);
                }

                tp = styleable?.TemplatedParent ?? null;
            }

            foreach (var reparenting in chain.AsEnumerable().Reverse())
            {
                if (reparenting.WillReparentChildrenOf(control))
                {
                    return reparenting;
                }
            }

            return null;
        }
Ejemplo n.º 5
0
        public static PagingSearchOption PagingGetSearchOption()
        {
            var request = HttpContext.Current.Request;

            var ret = new PagingSearchOption()
            {
                CurrentPageNo = int.Parse((request[Paging.KEY_CURRENT_PAGE_NO] ?? "1")),
                RowCountOnPage = int.Parse((request[Paging.KEY_ROWCOUNT_ON_PAGE] ?? Paging.CONST_ROWCOUNT_ON_PAGE.ToString())),
                TotalRowCount = int.Parse(request[Paging.KEY_TOTAL_ROW_COUNT] ?? "1")
            };

            var searchOption = (request[Paging.KEY_SEARCH_OPTION] ?? "");

            List<KeyValuePair<string, string>> optionList = new List<KeyValuePair<string,string>>();
            foreach(var option in searchOption.Split(';'))
            {
                if ( option.Contains('=') == false ) continue;
                var optionItem = option.Split('=');

                optionList.Add(new KeyValuePair<string,string>(optionItem[0], optionItem[1]));
            }

            ret.SearchOption = optionList.AsEnumerable();

            return ret;
        }
Ejemplo n.º 6
0
        public IEnumerable GetErrors(string propertyName)
        {
            List <ErrorInfo>?errors = null;

            _propertyErrors?.TryGetValue(propertyName, out errors);
            return(errors?.AsEnumerable() ?? Array.Empty <ErrorInfo>());
        }
 protected override IEnumerable<IRefactoringConditionChecker> GetAllConditionCheckers()
 {
     var checkers = new List<IRefactoringConditionChecker>();
     checkers.Add(new ParametersChecker());
     checkers.Add(new ReturnTypeChecker());
     return checkers.AsEnumerable();
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Menus the specified date range.
        /// </summary>
        /// <param name="dateRange">The date range.</param>
        /// <returns>Archive widget</returns>
        public PartialViewResult Menu(string dateRange = null)
        {
            ViewBag.SelectedArchive = dateRange;

            IEnumerable<DateTime> dates = this.repository.Articles
                                            .Select(b => b.Modified)
                                            .Distinct()
                                            .OrderByDescending(b => b);

            List<string> dateRanges = new List<string>();

            foreach(DateTime date in dates)
            {
                StringBuilder archiveName = new StringBuilder();

                archiveName.Append(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(date.Month));
                archiveName.Append(" ");
                archiveName.Append(date.Year.ToString());

                if (!dateRanges.Exists(d => d == archiveName.ToString()))
                {
                    dateRanges.Add(archiveName.ToString());
                }
            }

            return PartialView(dateRanges.AsEnumerable());
        }
Ejemplo n.º 9
0
        IEnumerator PerformUpdate()
        {
            while (true)
            {
                for (var i = 0; i < _agents.Count; i++)
                {
                    for (var j = 0; j < _agents.Count; j++)
                    {
                        if (i == j) continue;

                        if (Vector3.Distance(_agents[i].transform.position, _agents[j].transform.position) > SenseDistance) continue;

                        var sense = new Sight { AgentSensed = _agents[j] };

                        _nodeGraph = sense.PropagateSense(PathFinder, _agents[i].transform.position, _agents[j].transform.position);

                        var attenuation = _nodeGraph.AsEnumerable().Sum(node => node.Attenuation);

                        if (attenuation > MaxAttenuation) continue;

                        _agents[i].HandleSense(sense);

                    }
                }

                yield return new WaitForSeconds(.5f);

            }
        }
Ejemplo n.º 10
0
 protected override Job TryGiveTerminalJob(Pawn pawn)
 {
     if (!(pawn is Droid))
     {
         return null;
     }
     Droid droid = (Droid)pawn;
     if (!droid.Active)
         return null;
     //Check the charge level
     if (droid.TotalCharge < droid.MaxEnergy * chargeThreshold)
     {
         IEnumerable<Thing> chargers;
         List<Thing> list = new List<Thing>();
         foreach(var c in Find.ListerBuildings.AllBuildingsColonistOfClass<Building_DroidChargePad>())
         {
             list.Add((Thing)c);
         }
         chargers = list.AsEnumerable();
         Predicate<Thing> pred = (Thing thing) => { return ((Building_DroidChargePad)thing).IsAvailable(droid); };
         Thing target = GenClosest.ClosestThing_Global_Reachable(pawn.Position, chargers, PathEndMode.OnCell, TraverseParms.For(pawn), distance, pred);
         if (target != null)
         {
             return new Job(DefDatabase<JobDef>.GetNamed("MD2ChargeDroid"), new TargetInfo(target));
         }
     }
     return null;
 }
        /// <summary>
        /// Email seding regrading process
        /// </summary>
        public void SendingMail()
        {
            var pendingEmailQueue = EmailUtility.GetPendingEmailQueue();
            foreach (var queue in pendingEmailQueue)
            {
                queue.EmailContent = GetEmailContent(queue);
                try
                {
                    List<string> to = new List<string>();
                    to.Add(queue.Receiver);

                    Tuple<bool, string> mailResult = EmailUtility.SendEmail(EmailUtility.FromEmail, to.AsEnumerable(), null, null, queue.ProcessName, queue.EmailContent, null);
                    if (mailResult.Item1 == true)
                    {
                        EmailLogVM emailLogVM = new EmailLogVM();
                        emailLogVM.Process = queue.Process;
                        emailLogVM.EmailBody = queue.EmailContent;
                        emailLogVM.Receiver = queue.Receiver;
                        emailLogVM.SentTime = System.DateTime.Now;
                        EmailUtility.SaveEmailLog(emailLogVM, queue.Id);
                    }
                    else
                    {
                        queue.ErrorStatus = mailResult.Item2;
                        EmailUtility.UpdateEmailQueue(queue);
                    }
                }
                catch (Exception ex)
                {
                    queue.ErrorStatus = ex.Message;
                    EmailUtility.UpdateEmailQueue(queue);
                }
            }
        }
Ejemplo n.º 12
0
        public static IEnumerable<EventViewModel> ConvertToEventViewModel(this List<EventfulEvent> EventfulEvents)
        {
            List<EventViewModel> model = new List<EventViewModel>();

            foreach (EventfulEvent events in EventfulEvents)
            {
                string url = null;

                var images = events.image as System.Xml.XmlNode[];

                if (images != null)
                {
                    url = images.Any(e => string.Equals(e.Name, "medium", StringComparison.InvariantCultureIgnoreCase)) ?
                        images.Single(e => string.Equals(e.Name, "medium", StringComparison.InvariantCultureIgnoreCase)).InnerText : null;
                }

                model.Add(new EventViewModel
                        {
                            EventfulId = events.id,
                            Author = events.owner,
                            Location = events.venue_address,
                            StartDateTime = DateTime.Parse(events.start_time),
                            Title = events.title,
                            IsEventfultEvent = true,
                            ImageURI = url
                        });
            }

            return model.AsEnumerable();
        }
Ejemplo n.º 13
0
 public static IEnumerable<module> GetMyModules()
 {
     DBFactory db;
     SqlDataReader rdr;
     List<module> data = null;
                 
     try
     {
         db = new DBFactory("CCATDBEntities");
         rdr = db.ExecuteReader("MSI_GetLeftSideMenu", new SqlParameter("@roleName", GetRoleName()));
         data = new List<module>();
         module record;
         while (rdr.Read())
         {
             record = new module();
             record.moduleId = Convert.ToInt32(rdr["moduleId"].ToString());
             record.pageMenuGroups = rdr["pageMenuGroups"].ToString();
             data.Add(record);
         }
         //Close the datareader
         rdr.Close();
     }
     catch (Exception ex)
     {
         throw new Exception("Exception in DataQueries.GetMyModules:" + ex.Message);
     }
     return data.AsEnumerable<module>();
     
 }
Ejemplo n.º 14
0
        protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var newTypeDeclaration = (TypeDeclarationSyntax)base.VisitClassDeclaration(node);

            if (_fields.Count > 0 || _methods.Count > 0)
            {
                var members = new List<MemberDeclarationSyntax>(newTypeDeclaration.Members);
                members.InsertRange(0, _methods);
                members.InsertRange(0, _fields);

                return ((ClassDeclarationSyntax)newTypeDeclaration).Update(
                    newTypeDeclaration.Attributes,
                    newTypeDeclaration.Modifiers,
                    newTypeDeclaration.Keyword,
                    newTypeDeclaration.Identifier,
                    newTypeDeclaration.TypeParameterListOpt,
                    newTypeDeclaration.BaseListOpt,
                    newTypeDeclaration.ConstraintClauses,
                    newTypeDeclaration.OpenBraceToken,
                    Syntax.List(members.AsEnumerable()),
                    newTypeDeclaration.CloseBraceToken,
                    newTypeDeclaration.SemicolonTokenOpt);
            }

            return newTypeDeclaration;
        }
Ejemplo n.º 15
0
        // GET: Employees
        public ActionResult Index()
        {
            //get the token from the cache.
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            ADALTokenCache UserTokenCache = new ADALTokenCache(signedInUserID);

            List<TokenCacheItem> items = UserTokenCache.ReadItems().Where(tc => tc.Resource == "https://graph.microsoft.com").ToList();

            string myAccessToken = items[0].AccessToken;

            //make a HTTPClient request for the information and include the token.
            // thanks to post Vardhaman Deshpande.
            string resourceUrl = string.Format("https://graph.microsoft.com/beta/{0}/users", ConfigurationManager.AppSettings["ida:Domain"]);
            List<Employee> json = new List<Employee>();

            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, resourceUrl))
                {
                    request.Headers.Add("Authorization", "Bearer " + myAccessToken);
                    request.Headers.Add("Accept", "application/json;odata.metadata=minimal");
                    using (var response = client.SendAsync(request).Result)
                    {
                        var jsonResult = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                        json = JsonConvert.DeserializeObject<List<Employee>>(jsonResult["value"].ToString());
                    }
                }
            }

            return View(json.AsEnumerable<Employee>());
        }
Ejemplo n.º 16
0
        //- To get the GetWOClassification for Check In Page
        public IEnumerable<WOClassification> GetWOClassification(string userName)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<WOClassification> woClassificationList = new List<WOClassification>();
            try
            {
                DataTable resultTable = axHelper.GetWOClassificationList(userName);

                foreach (DataRow row in resultTable.Rows)
                {
                    WOClassification woObject = new WOClassification();
                    woObject.WOClassificationCode = row["WOCode"].ToString();
                    woObject.WOClassificationName = row["WOCode"].ToString() + " - " + row["WODescription"].ToString();

                    woClassificationList.Add(woObject);

                }
            }
            catch (Exception e)
            {
                throw e;

            }

            return woClassificationList.AsEnumerable<WOClassification>();
        }
Ejemplo n.º 17
0
        public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
        {
            //Console.WriteLine("Truncating Table");
            //TruncateTable(this.TargetTable, this.ConnectionStringSettings.ConnectionString);
            Console.WriteLine("Current feed data processing started");
            var rowsToBeInserted = new List<Row>();
            foreach (var row in rows)
            {
                var array = row["AWord"].ToString().Split(',');
                var i = 1;
                row["Name"] = array[i++];
                row["Description"] = array[i++];
                row["ImagePath"] = array[i++];
                row["PromotionId"] = array[i++];
                row["RAM"] = array[i++];
                row["Harddisk"] = array[i++];
                row["Processor"] = array[i++];
                row["Display"] = array[i++];
                rowsToBeInserted.Add(row);
            }
            //Bulk insert data
            var results = base.Execute(rowsToBeInserted.AsEnumerable());

            //Display all the rows to be inserted
            DisplayRows(rowsToBeInserted);

            Console.WriteLine("Feeds are processed");
            return results;
        }
Ejemplo n.º 18
0
        //- To get the GetTechnicians for Check In Page
        public IEnumerable<ServiceTechnician> GetTechnicians(string userName)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<ServiceTechnician> techniciansList = new List<ServiceTechnician>();
            try
            {
                DataTable resultTable = axHelper.GetTechnicians(userName);

                foreach (DataRow row in resultTable.Rows)
                {
                    ServiceTechnician technicianObject = new ServiceTechnician();
                    technicianObject.ServiceTechnicianName = row["Name"].ToString();
                    technicianObject.ServiceTechnicianNo = row["Number"].ToString();

                    techniciansList.Add(technicianObject);

                }
            }
            catch (Exception ex)
            {
                throw ex;

            }
            return techniciansList.AsEnumerable<ServiceTechnician>();
        }
Ejemplo n.º 19
0
        private IEnumerable<CodeCoverageStatistics> ReadDataFromNodes(XmlDocument doc, string summaryXmlLocation)
        {
            var listCoverageStats = new List<CodeCoverageStatistics>();

            if (doc == null)
            {
                return null;
            }

            XmlNode reportNode = doc.SelectSingleNode("coverage");

            if (reportNode != null)
            {
                if (reportNode.Attributes != null)
                {
                    CodeCoverageStatistics coverageStatisticsForLines = GetCCStats(labelTag: _linesCovered, coveredTag: _linesCoveredTag, validTag: _linesValidTag,
                                                                                    priorityTag: "line", summaryXmlLocation: summaryXmlLocation, reportNode: reportNode);

                    if (coverageStatisticsForLines != null)
                    {
                        listCoverageStats.Add(coverageStatisticsForLines);
                    }

                    CodeCoverageStatistics coverageStatisticsForBranches = GetCCStats(labelTag: _branchesCovered, coveredTag: _branchesCoveredTag, validTag: _branchesValidTag,
                                                                                        priorityTag: "branch", summaryXmlLocation: summaryXmlLocation, reportNode: reportNode);

                    if (coverageStatisticsForBranches != null)
                    {
                        listCoverageStats.Add(coverageStatisticsForBranches);
                    }
                }
            }

            return listCoverageStats.AsEnumerable();
        }
Ejemplo n.º 20
0
        public IEnumerable<LineProperty> GetLineProperty(string userName)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<LineProperty> LinePropertyList = new List<LineProperty>();
            try
            {
                DataTable resultTable = axHelper.GetLinePropertyList(userName);

                foreach (DataRow row in resultTable.Rows)
                {
                    LineProperty LinePropertyObject = new LineProperty();
                    LinePropertyObject.LinePropertyCode = row["LinePropertyCode"].ToString();
                    LinePropertyObject.LinePropertyDescription =  row["LinePropertyName"].ToString();

                    LinePropertyList.Add(LinePropertyObject);

                }
            }
            catch (Exception e)
            {
                throw e;

            }
            return LinePropertyList.AsEnumerable<LineProperty>();
        }
Ejemplo n.º 21
0
        public static IEnumerable<Tuple<string, string>> Swummarize(string directoryPath)
        {
            var swummaries = new List<Tuple<string, string>>();

            var srcmlMethods = MethodExtractor.ExtractAllMethodsFromDirectory(directoryPath);

            foreach (var methodDef in srcmlMethods)
            {
                // Extract SUnit Statements from MethodDefinition
                var statements = SUnitExtractor.ExtractAll(methodDef).ToList();

                // Translate Statements into SUnits
                List<SUnit> sunits = statements.ConvertAll(
                            new Converter<Statement, SUnit>(SUnitTranslator.Translate));

                // Generate text from SUnits
                List<string> sentences = sunits.ConvertAll(
                            new Converter<SUnit, string>(TextGenerator.GenerateText));

                // Collect text and summarize
                var methodDocument = String.Join<string>("\n", sentences);

                // TEMP: Just use full set of sentences for now. Don't use Summarizer.
                //       Maybe set a flag for this.
                //var summary = Summarizer.Summarize(methodDocument);
                var summary = methodDocument;

                // Add swummary to collection with its full method name
                var methodName = methodDef.GetFullName();
                swummaries.Add(new Tuple<string, string>(methodName, summary));
            }

            return swummaries.AsEnumerable();
        }
Ejemplo n.º 22
0
        public IEnumerable<SpecialtyCode> GetSpecialCodes(string userName, string TransactionId)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<SpecialtyCode> SpecialtyCodeList = new List<SpecialtyCode>();
            try
            {

                DataTable resultTable = axHelper.GetSpecialityCodeList(userName, TransactionId.ToString());

                foreach (DataRow row in resultTable.Rows)
                {
                    SpecialtyCode SpecialtyCodeObject = new SpecialtyCode();
                    SpecialtyCodeObject.SpecialityCodeNo = row["SpecialityCode"].ToString();
                    SpecialtyCodeObject.SpecialityDescription =  row["SpecialityDescription"].ToString();

                    SpecialtyCodeList.Add(SpecialtyCodeObject);

                }

            }
            catch (Exception e)
            {
                throw e;
            }
            return SpecialtyCodeList.AsEnumerable<SpecialtyCode>();
        }
Ejemplo n.º 23
0
        public IEnumerable<PartDetails> GetItemNumbers(string userName)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<PartDetails> itemnumberList = new List<PartDetails>();
            try
            {
                DataTable resultTable = axHelper.GetItemNumbersList(userName);

                foreach (DataRow row in resultTable.Rows)
                {
                    PartDetails partObject = new PartDetails();
                    partObject.ItemNumber = row["ItemNumber"].ToString();
                    partObject.ProductName = row["ProductName"].ToString();
                    partObject.ProductSubType = row["ProductSubType"].ToString();
                    itemnumberList.Add(partObject);

                }
            }
            catch (Exception e)
            {
                throw e;

            }
            return itemnumberList.AsEnumerable<PartDetails>();
        }
Ejemplo n.º 24
0
 public List<CampaignConflitView> GetDataDemo()
 {
     string s = "אבגדaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgGaAbBcCdDeEFfgG";
     char[] ch = s.ToCharArray();
     var data = new List<CampaignConflitView>();
     ;
     int i = 0;
     while (i < 28)
     {
         data.Add(new CampaignConflitView
         {
             TypeCode = i.ToString(),
             CampaignId = Guid.NewGuid(),
             CampaignName = ch[i].ToString(),
             CampaignSubtypeId = Guid.NewGuid(),
             CampaignApprovalStatus = true.ToString(),
             ProposedStartDate = DateTime.Now.AddDays(i),
             ProposedEndDate = DateTime.Now.AddDays(i),
             ConflitContacts = i,
             ListId = Guid.NewGuid(),
             ListName = ch[i].ToString(),
             CampaignSubtypeName = "dd"
         });
         i++;
     }
     return data.AsEnumerable().OrderBy(r => r.CampaignName).ToList();
 }
Ejemplo n.º 25
0
 public static IEnumerable<pageMenuGroupId_and_pageMenuId> get_myPageMenuGroupIds_and_pageMenuIds(int _appId)
 {
     DBFactory db;
     SqlDataReader rdr;
     List<pageMenuGroupId_and_pageMenuId> data = null;
     try
     {
         db = new DBFactory("CCATDBEntities");
         rdr = db.ExecuteReader("MSI_GetMenuDetails", new SqlParameter("@appId", _appId));
         data = new List<pageMenuGroupId_and_pageMenuId>();
         pageMenuGroupId_and_pageMenuId record;
         while (rdr.Read())
         {
             record = new pageMenuGroupId_and_pageMenuId();
             record.listOrder = Convert.ToInt32(rdr["listOrder"].ToString());
             record.pageMenuGroupId = Convert.ToInt32(rdr["pageMenuGroupId"].ToString());
             record.pageMenuId = Convert.ToInt32(rdr["pageMenuId"].ToString());
             data.Add(record);
         }
         //Close the datareader
         rdr.Close();
     }
     catch (Exception ex)
     {
         throw new Exception("Exception in DataQueries.get_myPageMenuGroupIds_and_pageMenuIds:" + ex.Message);
     }
     return data.AsEnumerable<pageMenuGroupId_and_pageMenuId>();
 }
Ejemplo n.º 26
0
        public static Task<IEnumerable<LocationDescription>> GetLocationsAndBusiness(string query, GeoCoordinate currentUserPosition)
        {
            var locations = new List<LocationDescription>();

            return GetBingLocations(query, currentUserPosition).ContinueWith(
                bingContinuation =>
                {
                    return GetGooglePlaces(query, currentUserPosition).ContinueWith(
                        googleContinuation =>
                        {
                            if (bingContinuation.IsCompleted)
                            {
                                locations.AddRange(bingContinuation.Result);
                            }

                            if (googleContinuation.IsCompleted)
                            {
                                locations.AddRange(googleContinuation.Result);
                            }

                            locations = SortLocationDescriptionsByDistance(locations, currentUserPosition);

                            return locations.AsEnumerable();
                        });
                }).Unwrap();
        }
 public static IEnumerable<FileInfo> ParseBISolutionFile(this FileInfo source)
 {
     var biFiles = new List<FileInfo>();
     biFiles.AddRange(source.GetSSISPackages());
     biFiles.AddRange(source.GetSqlScripts());
     return biFiles.AsEnumerable();
 }
Ejemplo n.º 28
0
        public IEnumerable<FailureCode> GetFailureCode(string userName)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<FailureCode> failureCodeList = new List<FailureCode>();
            try
            {
                DataTable resultTable = axHelper.GetFailureCodeList(userName);

                foreach (DataRow row in resultTable.Rows)
                {
                    FailureCode failureCodeObject = new FailureCode();
                    failureCodeObject.FailureCodeNo = row["FailureCode"].ToString();
                    failureCodeObject.FailureDescription = row["FailureCode"].ToString() + " - " + row["FailureDescription"].ToString();

                    failureCodeList.Add(failureCodeObject);

                }
            }
            catch (Exception e)
            {
                throw e;

            }
            return failureCodeList.AsEnumerable<FailureCode>();
        }
Ejemplo n.º 29
0
 public JsonResult CreateJson(List<TaskViewModel> viewTasks, List<LinkViewModel> viewLinks)
 {
     var jsonData = new
     {
         // create tasks array
         data = (
             from t in viewTasks.AsEnumerable()
             select new
             {
                 id = t.TaskId,
                 text = t.Text,
                 start_date = t.StartDate.ToString("u"),
                 duration = t.Duration,
                 order = t.SortOrder,
                 progress = t.Progress,
                 open = true,
                 parent = t.ParentId,
                 type = (t.Type != null) ? t.Type : String.Empty,
                 holder = (t.Holder != null) ? t.Holder : String.Empty
             }
         ).ToArray(),
         // create links array
         links = (
             from l in viewLinks.AsEnumerable()
             select new
             {
                 id = l.LinkId,
                 source = l.SourceTaskId,
                 target = l.TargetTaskId,
                 type = l.Type
             }
         ).ToArray()
     };
     return new JsonResult { Data = jsonData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
 }
Ejemplo n.º 30
0
        IEnumerable<Price> IMarketPriceRepository.FetchPrices(IEnumerable<Item> items, SolarSystem system)
        {
            string urlData = "";
            foreach (Item item in items)
            {
                urlData += "typeid=" + item.ApiId + "&";
            }
            urlData += "usesystem=" + system.ApiId;

            XDocument doc = XDocument.Load(String.Format(String.Format(_priceURL, urlData)));
            IEnumerable<XElement> itemElements = doc.Element("evec_api").Element("marketstat").Elements("type");
            IList<Price> prices = new List<Price>();
            foreach (XElement itemElement in itemElements)
            {
                string itemApi = itemElement.Attribute("id").Value;
                Item currentItem = items.Single(i => i.ApiId.Equals(itemApi));
                Price price = new Price
                {
                    Item = currentItem,
                    SolarSystem = system,
                    Buy = Double.Parse(itemElement.Element("buy").Element("max").Value, CultureInfo.InvariantCulture),
                    Sell = Double.Parse(itemElement.Element("sell").Element("min").Value, CultureInfo.InvariantCulture),
                    Date = DateTime.Today
                };
                prices.Add(price);
            }
            return prices.AsEnumerable();
        }
Ejemplo n.º 31
0
        //- To get the GetCustomers for Check In Page
        public IEnumerable<Customer> GetCustomers(string userName)
        {
            IAXHelper axHelper = ObjectFactory.GetInstance<IAXHelper>();
            List<Customer> customerList = new List<Customer>();
            try
            {
                DataTable resultTable = axHelper.GetCustomers(userName);

                foreach (DataRow row in resultTable.Rows)
                {
                    Customer customerObject = new Customer();
                    customerObject.CustomerAccount = row["CustomerAccount"].ToString();
                    customerObject.CustomerName = row["CustomerAccount"].ToString() + " - " + row["CustomerName"].ToString();

                    customerList.Add(customerObject);

                }
            }
            catch (Exception e)
            {
                throw e;

            }
            return customerList.AsEnumerable<Customer>();
        }
Ejemplo n.º 32
0
        public IEnumerable GetErrors(string?propertyName)
        {
            List <ErrorInfo>?errors = null;

#pragma warning disable CS8604 // Possible null reference argument.
            _propertyErrors?.TryGetValue(propertyName, out errors);
#pragma warning restore CS8604 // Possible null reference argument.
            return(errors?.AsEnumerable() ?? Array.Empty <ErrorInfo>());
        }
Ejemplo n.º 33
0
 public IEnumerable <IDeviceParserAbstract> GetDeviceParsers()
 {
     return(deviceParsers.AsEnumerable());
 }
Ejemplo n.º 34
0
 /// <summary>
 /// 初始化 <see cref="RegexSeries{T}"/> 类的新实例。该实例指定内部的正则对象列表。
 /// </summary>
 /// <param name="series">要作为内部正则对象列表的参数数组。</param>
 /// <exception cref="ArgumentNullException"><paramref name="series"/> 的值为 null 。</exception>
 public RegexSeries(params RegexObject <T>[] series) :
     this(series?.AsEnumerable() ?? throw new ArgumentNullException(nameof(series)))
 {
 }
 /// <summary>
 /// 初始化 <see cref="RegexParallels{T}"/> 类的新实例。该实例指定内部的正则对象列表。
 /// </summary>
 /// <param name="parallels">要作为内部正则对象列表的参数数组。</param>
 /// <exception cref="ArgumentNullException"><paramref name="parallels"/> 的值为 null 。</exception>s
 public RegexParallels(params RegexObject <T>[] parallels) :
     this(parallels?.AsEnumerable() ?? throw new ArgumentNullException(nameof(parallels)))
 {
 }
Ejemplo n.º 36
0
 public IEnumerable <T> GetSelected()
 {
     return(SelectedItems?.AsEnumerable <T>());
 }
Ejemplo n.º 37
0
        public System.Data.DataSet GetAllFeaturesBackUp(PCCS feature = null, PCCS feature1 = null, PCCS feature2 = null, PCCS specification = null, PRD_MAST productMaster = null)
        {
            System.Data.DataSet dsReport = null;
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("SELECT DISTINCT 123456789012 AS SNO, A.PART_NO, ");
                sb.Append("  A.PART_DESC, ");
                sb.Append("  B.FEATURE, ");
                sb.Append("  B.SPEC_MIN, ");
                sb.Append("  B.SPEC_MAX, ");
                sb.Append("  A.QUALITY, ");
                sb.Append("  E.CUST_NAME, ");
                sb.Append("  B.CTRL_SPEC_MIN, ");
                sb.Append("  B.CTRL_SPEC_MAX, ");

                sb.Append("  ' ' AS COLLAR_FLANGE_DIA_MIN, ");
                sb.Append("  ' ' AS COLLAR_FLANGE_DIA_MAX, ");

                sb.Append("  ' ' AS COLLAR_FLANGE_TK_MIN, ");
                sb.Append("  ' ' AS COLLAR_FLANGE_TK_MAX, ");

                sb.Append("  ' ' AS FORGING_COST_CENTER, ");

                sb.Append("  ' ' AS WIRE_DIA_MIN, ");
                sb.Append("  ' ' AS WIRE_DIA_MAX ");

                sb.Append("FROM PRD_MAST A, ");
                sb.Append("  PCCS B, ");
                sb.Append("  PRD_CIREF C, ");
                sb.Append("  DDCI_INFO D, ");
                sb.Append("  DDCUST_MAST E ");
                sb.Append("WHERE A.PART_NO =B.PART_NO ");
                sb.Append("AND A.PART_NO   =C.PART_NO ");

                sb.Append("AND C.CI_REF    =D.CI_REFERENCE AND C.CURRENT_CIREF = 1 ");
                //sb.Append("AND C.CI_REF    =D.CI_REFERENCE ");

                sb.Append("AND D.CUST_CODE =E.CUST_CODE ");
                //sb.Append("AND A.PART_NO   ='M03920' ");

                string featureSql = "";
                if (feature.IsNotNullOrEmpty() && feature.FEATURE.IsNotNullOrEmpty())
                {
                    featureSql = featureSql + "UPPER(B.FEATURE) LIKE '%" + feature.FEATURE.ToUpper() + "%' ";
                }

                string feature1Sql = "";
                if (feature1.IsNotNullOrEmpty() && feature1.FEATURE.IsNotNullOrEmpty())
                {
                    feature1Sql = feature1Sql + "UPPER(B.FEATURE) LIKE '%" + feature1.FEATURE.ToUpper() + "%' ";
                }

                if (featureSql.IsNotNullOrEmpty() && feature1Sql.IsNotNullOrEmpty())
                {
                    featureSql = featureSql + " OR " + feature1Sql;
                }
                else if (!featureSql.IsNotNullOrEmpty() && feature1Sql.IsNotNullOrEmpty())
                {
                    featureSql = feature1Sql;
                }

                string feature2Sql = "";
                if (feature2.IsNotNullOrEmpty() && feature2.FEATURE.IsNotNullOrEmpty())
                {
                    feature2Sql = feature2Sql + "UPPER(B.FEATURE) LIKE '%" + feature2.FEATURE.ToUpper() + "%' ";
                }

                if (featureSql.IsNotNullOrEmpty() && feature2Sql.IsNotNullOrEmpty())
                {
                    featureSql = featureSql + " OR " + feature2Sql;
                }
                else if (!featureSql.IsNotNullOrEmpty() && feature2Sql.IsNotNullOrEmpty())
                {
                    featureSql = feature2Sql;
                }

                if (featureSql.IsNotNullOrEmpty() && featureSql.Trim().Length > 0)
                {
                    sb.Append(" AND ( " + featureSql + ") ");
                }

                if (productMaster.IsNotNullOrEmpty() && productMaster.PART_DESC.IsNotNullOrEmpty())
                {
                    sb.Append(" AND UPPER(A.PART_DESC) LIKE '%" + productMaster.PART_DESC.ToUpper() + "%' ");
                }

                if (specification.IsNotNullOrEmpty())
                {
                    if (specification.SPEC_MIN.IsNotNullOrEmpty() && specification.SPEC_MIN.IsNumeric())
                    {
                        sb.Append(" AND B.SPEC_MIN BETWEEN '" + specification.SPEC_MIN + "' AND '" + Convert.ToDouble(specification.SPEC_MIN) + 1 + "' ");
                    }
                    else if (specification.SPEC_MIN.IsNotNullOrEmpty())
                    {
                        sb.Append(" AND  UPPER(B.SPEC_MIN) LIKE '" + specification.SPEC_MIN.ToUpper() + "%' ");
                    }

                    if (specification.SPEC_MAX.IsNotNullOrEmpty() && specification.SPEC_MAX.IsNumeric() && 1 == 2)
                    {
                        sb.Append(" AND B.SPEC_MAX BETWEEN '" + specification.SPEC_MAX + "' AND '" + Convert.ToDouble(specification.SPEC_MAX) + 1 + "' ");
                    }
                    else if (specification.SPEC_MAX.IsNotNullOrEmpty())
                    {
                        sb.Append(" AND  UPPER(B.SPEC_MAX) = '" + specification.SPEC_MAX.ToUpper() + "' ");
                    }
                }

                sb.Append(" ORDER BY A.PART_NO ");

                List <StringBuilder> sqlList = new List <StringBuilder>()
                {
                    sb
                };

                dsReport = Dal.GetDataSet(sqlList);
                if (dsReport.IsNotNullOrEmpty() && dsReport.Tables.IsNotNullOrEmpty() && dsReport.Tables.Count > 0)
                {
                    dsReport.Tables[0].TableName = "FEATURE_WISE_REPORT";

                    List <PCCS> lstAllPCCS = (from row in DB.PCCS
                                              where (
                                                  row.FEATURE.ToUpper().StartsWith("HEAD HEI") ||
                                                  row.FEATURE.ToUpper().StartsWith("HEAD TH") ||
                                                  row.FEATURE.ToUpper().StartsWith("COLLAR DIA") ||
                                                  row.FEATURE.ToUpper().StartsWith("FLANGE DIA") ||
                                                  row.FEATURE.ToUpper().StartsWith("COLLAR TH") ||
                                                  row.FEATURE.ToUpper().StartsWith("FLANGE TH"))
                                              select row).ToList <PCCS>();

                    List <PCCS> lstPCCS = null;


                    List <V_FORGING_COST_CENTER> lstAllFORGING_COST_CENTER = (from row in DB.V_FORGING_COST_CENTER
                                                                              select row).ToList <V_FORGING_COST_CENTER>();

                    List <V_FORGING_COST_CENTER> lstFORGING_COST_CENTER = null;

                    //SELECT PC.CC_CODE,
                    //  PC.PART_NO,
                    //  PC.WIRE_SIZE_MIN,
                    //  PC.WIRE_SIZE_MAX
                    //FROM PROCESS_CC PC
                    //WHERE PC.PART_NO = 'M92910'
                    //AND PC.SEQ_NO   IN
                    //  (SELECT a.SEQ_NO
                    //  FROM PROCESS_SHEET a
                    //  WHERE a.OPN_DESC LIKE 'FORG%'
                    //  AND A.PART_NO   = PC.PART_NO
                    //  AND A.PART_NO   = 'M92910'
                    //  AND a.ROUTE_NO IN
                    //    (SELECT DISTINCT(B.ROUTE_NO)
                    //    FROM PROCESS_MAIN B
                    //    WHERE B.CURRENT_PROC=1
                    //    AND B.PART_NO       =a.PART_NO
                    //    AND B.PART_NO       = PC.PART_NO
                    //    AND B.PART_NO       = 'M92910'
                    //    )
                    //  )
                    //AND PC.ROUTE_NO IN
                    //  (SELECT DISTINCT(C.ROUTE_NO)
                    //  FROM PROCESS_MAIN C
                    //  WHERE C.CURRENT_PROC=1
                    //  AND C.PART_NO       = PC.PART_NO
                    //  AND C.PART_NO       = 'M92910'
                    //  )
                    long sno = 0;
                    foreach (DataRow dataRow in dsReport.Tables[0].Rows)
                    {
                        string part_no = dataRow["PART_NO"].ToValueAsString();

                        sno++;
                        dataRow["SNO"] = sno.ToValueAsString();

                        lstPCCS = (from row in lstAllPCCS.AsEnumerable()
                                   where row.PART_NO == part_no && (row.FEATURE.ToUpper().StartsWith("HEAD HEI") ||
                                                                    row.FEATURE.ToUpper().StartsWith("HEAD TH"))
                                   select row).ToList <PCCS>();
                        if (lstPCCS.IsNotNullOrEmpty() && lstPCCS.Count > 0)
                        {
                            dataRow["CTRL_SPEC_MIN"] = lstPCCS[0].CTRL_SPEC_MIN;
                            dataRow["CTRL_SPEC_MAX"] = lstPCCS[0].CTRL_SPEC_MAX;
                        }

                        lstPCCS = (from row in lstAllPCCS.AsEnumerable()
                                   where row.PART_NO == part_no && (row.FEATURE.ToUpper().StartsWith("COLLAR DIA") ||
                                                                    row.FEATURE.ToUpper().StartsWith("FLANGE DIA"))
                                   select row).ToList <PCCS>();
                        if (lstPCCS.IsNotNullOrEmpty() && lstPCCS.Count > 0)
                        {
                            dataRow["COLLAR_FLANGE_DIA_MIN"] = lstPCCS[0].CTRL_SPEC_MIN;
                            dataRow["COLLAR_FLANGE_DIA_MAX"] = lstPCCS[0].CTRL_SPEC_MAX;
                        }

                        lstPCCS = (from row in lstAllPCCS.AsEnumerable()
                                   where row.PART_NO == part_no && (row.FEATURE.ToUpper().StartsWith("COLLAR TH") ||
                                                                    row.FEATURE.ToUpper().StartsWith("FLANGE TH"))
                                   select row).ToList <PCCS>();
                        if (lstPCCS.IsNotNullOrEmpty() && lstPCCS.Count > 0)
                        {
                            dataRow["COLLAR_FLANGE_TK_MIN"] = lstPCCS[0].CTRL_SPEC_MIN;
                            dataRow["COLLAR_FLANGE_TK_MAX"] = lstPCCS[0].CTRL_SPEC_MAX;
                        }

                        lstFORGING_COST_CENTER = (from row in lstAllFORGING_COST_CENTER.AsEnumerable()
                                                  where row.PART_NO == part_no
                                                  select row).ToList <V_FORGING_COST_CENTER>();
                        if (lstFORGING_COST_CENTER.IsNotNullOrEmpty() && lstFORGING_COST_CENTER.Count > 0)
                        {
                            dataRow["FORGING_COST_CENTER"] = lstFORGING_COST_CENTER[0].CC_CODE.ToValueAsString();
                            dataRow["WIRE_DIA_MIN"]        = lstFORGING_COST_CENTER[0].WIRE_SIZE_MIN.ToValueAsString();
                            dataRow["WIRE_DIA_MAX"]        = lstFORGING_COST_CENTER[0].WIRE_SIZE_MAX.ToValueAsString();
                        }

                        //sb = new StringBuilder();
                        //sb.Append("SELECT CC_CODE, ");
                        //sb.Append("  WIRE_SIZE_MIN, ");
                        //sb.Append("  WIRE_SIZE_MAX ");
                        //sb.Append("FROM PROCESS_CC ");
                        //sb.Append("WHERE PART_NO='" + part_no + "' ");
                        //sb.Append("AND SEQ_NO   = ");
                        //sb.Append("  (SELECT a.SEQ_NO ");
                        //sb.Append("  FROM PROCESS_SHEET a ");
                        //sb.Append("  WHERE a.OPN_DESC LIKE 'FORG%' ");
                        //sb.Append("  AND a.ROUTE_NO= ");
                        //sb.Append("    (SELECT DISTINCT(ROUTE_NO) ");
                        //sb.Append("    FROM PROCESS_MAIN B ");
                        //sb.Append("    WHERE B.CURRENT_PROC=1 ");
                        //sb.Append("    AND B.PART_NO       =a.PART_NO ");
                        //sb.Append("    AND B.PART_NO       ='" + part_no + "' ");
                        //sb.Append("    ) ");
                        //sb.Append("  ) ");
                        //sb.Append("AND ROUTE_NO= ");
                        //sb.Append("  (SELECT DISTINCT(ROUTE_NO) ");
                        //sb.Append("  FROM PROCESS_MAIN B ");
                        //sb.Append("  WHERE B.CURRENT_PROC=1 ");
                        //sb.Append("  AND B.PART_NO       =PART_NO ");
                        //sb.Append("  AND B.PART_NO       ='" + part_no + "' ");
                        //sb.Append("  )");
                        //sqlList = new List<StringBuilder>() { sb };

                        //DataSet dsResult = Dal.GetDataSet(sqlList);

                        //if (dsResult.IsNotNullOrEmpty() && dsResult.Tables.IsNotNullOrEmpty() && dsResult.Tables.Count > 0 && dsResult.Tables[0].Rows.Count > 0)
                        //{
                        //    DataRow resultRow = dsResult.Tables[0].Rows[0];
                        //    dataRow["FORGING_COST_CENTER"] = resultRow["CC_CODE"].ToValueAsString();
                        //    dataRow["WIRE_DIA_MIN"] = resultRow["WIRE_SIZE_MIN"].ToValueAsString();
                        //    dataRow["WIRE_DIA_MAX"] = resultRow["WIRE_SIZE_MAX"].ToValueAsString();
                        //    dataRow.AcceptChanges();
                        //}

                        dataRow.AcceptChanges();
                    }
                    dsReport.Tables[0].AcceptChanges();
                }
                DataTable dtCompany = new DataTable();
                dtCompany.TableName = "CompanyName";
                dtCompany.Columns.Add("Name");
                dtCompany.Columns.Add("ShortName");
                dtCompany.Columns.Add("Phone");
                dtCompany.Columns.Add("Fax");
                dtCompany.Columns.Add("Mobile");
                dtCompany.Columns.Add("EMail");
                dtCompany.Columns.Add("Title");
                dtCompany.Columns.Add("ReportTitle");
                if (dsReport.IsNotNullOrEmpty())
                {
                    dsReport.Tables.Add(dtCompany);
                }
            }
            catch (Exception ex)
            {
                throw ex.LogException();
            }

            return(dsReport);
        }
Ejemplo n.º 38
0
        public async Task <ActionResult> Inventory()
        {
            var date = DateTime.Now.Date.ToShortDateString();

            try
            {
                var datequery = db.transactions.Where(m => m.DateOfTrans.Contains(date)).Count();

                if (datequery != 0)
                {
                    //gets the total amount received for transactions made per day
                    var today = await db.transactions.Where(m => m.DateOfTrans.Contains(date)).Select(m => m.TotalAmount).SumAsync();

                    var todaycash = Math.Round(today, 2);
                    ViewBag.todaycash = todaycash;
                    //gets the number of transaction made per day
                    ViewBag.Tnumber = await db.transactions.Where(m => m.DateOfTrans.Contains(date)).Select(m => m.transactionID).CountAsync();
                }
                else
                {
                    ViewBag.todaycash = "";
                    ViewBag.Tnumber   = "";
                }



                //gets the number of transaction made through out app life cycle
                var transactionQuery = await db.transactions.CountAsync();

                if (transactionQuery != 0)
                {
                    var total = await db.transactions.Select(m => m.TotalAmount).SumAsync();

                    var totalcash = Math.Round(total, 2).ToString();
                    ViewBag.totalcash = totalcash;
                    //gets details of the latest transaction made
                    var transactions = await db.transactions.OrderByDescending(m => m.DateOfTrans).ToListAsync();

                    ViewBag.Transaction = transactions.AsEnumerable();
                }
                else
                {
                    ViewBag.totalcash   = "";
                    ViewBag.Transaction = "";
                }



                //gets details of the drugs and their current stock value
                var Bermah = await db.drugs.Join(db.mainstocks, d => d.DrugID, f => f.DrugID, (d, f) => d).CountAsync();

                if (Bermah != 0)
                {
                    var robotDogs = await db.drugs.Join(db.mainstocks, d => d.DrugID, f => f.DrugID, (d, f) => d).ToListAsync();

                    ViewBag.productDetails = robotDogs.AsEnumerable();
                }
                else
                {
                    ViewBag.productDetails = "";
                }



                DateTime dates = DateTime.Now;
                var      dat   = TimeSpan.FromDays(2);
                //string query = "SELECT COUNT(BrandName) AS ExpDrug,BrandName,(ExpireDate -GETDATE()) FROM drugs WHERE (ExpireDate -GETDATE()) < 180 group by ExpireDate,BrandName;";
                //ViewBag.notes = await db.drugs.SqlQuery("SELECT COUNT(BrandName) AS ExpDrug,BrandName,(ExpireDate -GETDATE()) FROM drugs WHERE (ExpireDate -GETDATE()) < 180 group by ExpireDate,BrandName;").ToListAsync();

                //TimeSpan daye = dates.Subtract(DateTime.Parse(dat+""));
                //var mom = daye.Subtract(days);
                //creating a drugID list to hold list of drugs due to expire
                List <Guid> DrugIDList = new List <Guid>();

                //Get list of all drug from db to be used in the loop to find expiring ones
                var DrugList = db.drugs.ToList();
                var DrugEnum = DrugList.AsEnumerable();
                //loop searches through DrugEnum to find expiring drugs and add their drugID to the DrugIDList created earlier
                foreach (var item in DrugEnum)
                {
                    var ExpireDateTimeSpan = item.ExpireDate - DateTime.Now;
                    if (ExpireDateTimeSpan != null)
                    {
                        if (ExpireDateTimeSpan - TimeSpan.FromDays(180) < TimeSpan.FromDays(0))
                        {
                            DrugIDList.Add(item.DrugID);
                        }
                    }
                }
                //returns number of drugs due to expire by counting drugIDs in the DrugIDList to view
                var count = DrugIDList.Count();
                if (count != 0)
                {
                    ViewBag.DueToExpireDrugs = DrugIDList.Count();
                    //converts the DrugIDList to and Enumerable which will be looped to get details of drugs by their id
                    var         DrugIDListEnum = DrugIDList.AsEnumerable();
                    List <drug> drugs          = new List <drug>();
                    foreach (var item in DrugIDListEnum)
                    {
                        var DrugID = item;
                        var drug   = await db.drugs.Where(m => m.DrugID.Equals(DrugID)).FirstOrDefaultAsync();

                        drugs.Add(drug);
                    }
                    //return "list" of drugs that are due to expire to view
                    ViewBag.ExpireDrugs = drugs.AsEnumerable();
                }
                else
                {
                    ViewBag.DueToExpireDrugs = "";
                    ViewBag.ExpireDrugs      = "";
                }

                //getting info on drugs that are running out of stock with a minimum of 10 products
                int threshold     = 10;
                var DueOutOfStock = await db.drugs.Join(db.mainstocks, d => d.DrugID, f => f.DrugID, (d, f) => d).Where(m => m.mainstock.QuantityInStock - threshold <= 0).ToListAsync();

                var NumOfDueOutOfStock = await db.mainstocks.Where(m => m.QuantityInStock - threshold <= 0).CountAsync();

                if (NumOfDueOutOfStock != 0)
                {
                    ViewBag.outofstock = DueOutOfStock.AsEnumerable();
                    ViewBag.outnum     = NumOfDueOutOfStock.ToString();
                }
                else
                {
                    ViewBag.outofstock = "";
                    ViewBag.outnum     = "";
                }
            }
            catch (Exception e)
            {
                var exception = e.Message;
            }
            finally
            {
            }
            //returning number of employees to view
            if (TempData["NOU"] != null)
            {
                ViewBag.NOU = TempData["NOU"];
            }

            return(View());
        }
        public void ExportExcel(string filePathSource, string filePathTarget, DateTime dtRef)
        {
            const int idDesconhecido      = 204;
            var       getDescription      = new Func <TipoDominio, string>(e => string.Concat(e.Id, "-", e.Descricao));
            var       dados               = _excelDocumentService.OpenExcelDocument(filePathSource).ReadExcelDocument <DebitoData>(0, true);
            var       minDate             = dados.Select(d => d.Data).Min();
            var       lstEstabelecimentos = _dominioRepository.List <Estabelecimento>().OrderByDescending(e => e.PalavraChave.Length);
            var       prefixos            = _dominioRepository.FindBy <ClassificacaoExtra>(x => x.DataInicio >= minDate);
            var       tipoDesconhecido    = _dominioRepository.Get <TipoDominio>(idDesconhecido);

            var arquivos    = new Dictionary <string, List <DebitoData> >();
            var lancamentos = new List <Lancamento>();
            var qtdEstab    = new Dictionary <string, int>();

            foreach (var item in dados)
            {
                var            estab          = lstEstabelecimentos.FirstOrDefault(e => Regex.IsMatch(item.Local.Replace("*", string.Empty).ToUpper(), e.PalavraChave.ToUpper().LikeToRegular()));
                var            prefixoExtra   = prefixos.Where(x => x.DataInicio <= item.Data && x.DataFim >= item.Data).FirstOrDefault();
                DescricaoExtra descricaoExtra = null;
                var            lanc           = new Lancamento {
                    Estabelecimento = estab
                };

                if (estab != null)
                {
                    #region Mudando a classificação de uma compra específica na data

                    var estabKey = $"{estab.Id}{item.Data}";
                    if (!qtdEstab.ContainsKey(estabKey))
                    {
                        qtdEstab[estabKey] = 0;
                    }
                    qtdEstab[estabKey] += 1;

                    //item.Valor = Convert.ToDecimal(item.Valor, new CultureInfo("en-US")).ToString();
                    descricaoExtra = _dominioRepository.FindBy <DescricaoExtra>(x => x.Ativo &&
                                                                                x.DataCompra == item.Data &&
                                                                                x.Estabelecimento.Id == estab.Id &&
                                                                                qtdEstab[estabKey] >= x.IndiceCompraDe && qtdEstab[estabKey] <= x.IndiceCompraAte)
                                     .FirstOrDefault();

                    if (descricaoExtra != null)
                    {
                        item.Local = $"{descricaoExtra.Descricao}-{item.Local}";
                        estab      = new Estabelecimento {
                            Classificacao = descricaoExtra.Classificacao
                        };
                    }

                    #endregion
                }
                else
                {
                    estab = new Estabelecimento {
                        Classificacao = prefixoExtra != null ? prefixoExtra.Classificacao : tipoDesconhecido
                    }
                };

                #region Adicionando prefixo por range de data

                if (prefixoExtra != null)
                {
                    item.Local = string.Concat(prefixoExtra.Prefixo, item.Local);
                }

                #endregion


                if (!arquivos.ContainsKey(getDescription(estab.Classificacao)))
                {
                    arquivos.Add(getDescription(estab.Classificacao), new List <DebitoData> {
                        new DebitoData {
                            Local = item.Local, Data = item.Data, Valor = item.Valor
                        }
                    });
                }
                else
                {
                    arquivos[getDescription(estab.Classificacao)].Add(new DebitoData {
                        Local = item.Local, Data = item.Data, Valor = item.Valor
                    });
                }


                lanc.Valor              = item.Valor;
                lanc.Descricao          = item.Local;
                lanc.DtCompra           = item.Data;
                lanc.DtReferencia       = new DateTime(dtRef.Year, dtRef.Month, 1);
                lanc.DescricaoExtra     = descricaoExtra;
                lanc.ClassificacaoExtra = prefixoExtra;
                lanc.CriadoEm           = DateTime.Now;
                lancamentos.Add(lanc);
            }

            _excelDocumentService.WriteExcelDocument(filePathTarget, arquivos);
            _excelDocumentService.CloseExcelDocument();

            _dominioRepository.ApagarLancamentosPorDtRef(dtRef);
            _dominioRepository.Save(lancamentos.AsEnumerable());
            //excelApp.CloseExcelDocument();
        }
    }
Ejemplo n.º 40
0
 public IEnumerable <IClientParserAbstract> GetClientsParsers()
 {
     return(clientParsers.AsEnumerable());
 }
Ejemplo n.º 41
0
        static void Main(string[] args)
        {
            //Sequences in Original Order
            //Some methods return a new sequence where all or a portion of the original sequence is included, in its original order.
            //These methods do not require materialization of the sequence to begin returning items.
            //These methods include: Append, AsEnumerable, Cast, Concat, DefaultIfEmpty, OfType, Prepend, Range, Repeat, Select, SelectMany, Skip, SkipWhile, Take, TakeWhile, Where, and Zip.

            //Append ?????
            //The Append method adds a single item to the end of the sequence.
            string[] berries = { "blackberry", "blueberry", "raspberry" };
            //var a = berries.Append("strawberry");

            //AsEnumerable
            //The AsEnumerable method is a bit beyond the scope of this article.
            //Basically, it allows a transition from the other flavor of LINQ(IQueryable) to the flavor described in this article(IEnumerable).
            //We’ll revisit this method in later articles and explain in more detail.

            IEnumerable <string> mySequence = new List <string> {
                "blackberry", "blueberry", "raspberry"
            };
            var enumerablerValue = mySequence.AsEnumerable();
            var typeOfValue      = enumerablerValue.GetType();

            //Cast
            //Sometimes, it is necessary to deal with a weakly-typed sequence, especially when dealing with older.NET data types.
            //In these cases, the sequence may implement IEnumerable, but not IEnumerable<T>.
            //When all of the data types in the sequence are known to be of the same data type, the Cast method allows you to cast all of the items to that data type.
            //The Cast method casts every item in the sequence to a different data type.

            var intList = new ArrayList {
                123, 456, 789
            };
            IEnumerable <int> castedToInts = intList.Cast <int>();

            //If any of items are of a different data type, than what is specified, an exception will occur.
            var stringList = new ArrayList {
                "Alpha", 123, "Beta", "Gamma"
            };
            IEnumerable <int> castedToStrings = stringList.Cast <int>(); //don't know why but there is not exception at all!

            //Concat
            //Concat method adds items, from another sequence, to the end of the sequence.
            var citrus      = new[] { "grapefruit", "lemon", "lime", "orange" };
            var justBerries = new[] { "blackberry", "blueberry", "raspberry" };
            var newSequence = berries.Concat(citrus);

            //DefaultIfEmpty
            //The DefaultIfEmpty method gets either the original sequence or a sequence with a singe default value, if the original sequence is empty(contains no item);
            var bytes          = new[] { 1, 2, 3, 4 };
            var defaultIfEmpty = bytes.DefaultIfEmpty(); //returns whole array

            var emptyArray      = Enumerable.Empty <int>();
            var defaultIfEmpty2 = emptyArray.DefaultIfEmpty();    //returns array with one value = 0. because 0 is the value by default for int.
            //Parameters:  The sequence to return the specified value for if it is empty.
            var defaultIfEmpty3 = emptyArray.DefaultIfEmpty(123); // returns 123 because emptyArray is empty and '123' was sent as argument to DefaultIfEmpty method

            //OfType
            // The OfType method allows you to select items (of homogenous type) from that sequence and produce an IEnumerable<T> instance
            //OfType method selects only items of specified type
            var list = new ArrayList {
                "Alpha", 123, "Beta", "Gamma"
            };
            var convertedList = list.OfType <string>(); // returns "Alpha", "Beta", "Gamma"  baceuse 'string' type was specified

            //Prepend ???? the same as Append -> there is no this method
            //The Prepend method adds a single item to the start of the sequence
            var collection = new[] { "grapefruit", "lemon", "lime", "orange" };
            //var newCollection = collection.Prepend();

            //Select
            //The Select method alters every item, in a senquence
            var citrus2            = new[] { "grapefruit", "lemon", "lime", "orange" };
            var selectedCollection = citrus2.Select(x => x + " super");

            //SelectMany
            //The SelectMany method alters multiple sequences and lettens them into a single sequence.
            int[][] manyNumbers  = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } };
            var     changedArray = manyNumbers.SelectMany(x => x.Concat(new int[] { 9999 }));

            //Skip
            //The Skip method skips a fixed number of items at the start of a sequence.
            var someArray     = new[] { 'A', 'B', 'C' };
            var changedArray2 = someArray.Skip(1); // returns 'B', 'C'

            //SkipWhile
            //The SkipWhile skips items at the start of the sequence, while they meet a specified condition
            var someArray2   = new[] { 'A', 'B', 'C', 'D' };
            var skippedArray = someArray2.SkipWhile(x => x < 'B'); // returns 'B', 'C', 'D'

            //Take
            //The Take method takes a fixed number of items from the start of a sequence
            var someArray3 = new[] { 'A', 'B', 'C', 'D' };
            var someArray4 = someArray3.Take(2); // returns 'A', 'B'

            //TakeWhile
            //The TakeWhile method takes items, from the start of a sequence, while they meet a specified condition
            var someArray5 = new[] { 'A', 'B', 'C', 'D' };
            var someArray6 = someArray5.TakeWhile(x => x < 'D'); //returned 'A', 'B', 'C'

            //Where
            //The Where method takes all of the items that meet specified condition
            var collection1 = new List <string> {
                "Item", "Something", "Last thing"
            };
            var filteredCollection = collection1.Where(x => x.Contains("Some")); //returned only 'Something'

            //Zip
            //The Zip method combines a sequence with items from another sequence
            string[] citrus4      = { "grapefruit", "lemon", "lime", "orange" };
            char[]   letters      = { 'A', 'B', 'C', 'D' };
            var      somethingNew = citrus4.Zip(letters, (fruit, letter) => $"{fruit} {letter}"); //it authomatically undersrtands: fruit -> one item in cutrus4, letter -> one item in letters.
            //And there is an opportunity to make my own collection using the elements from other 2 collections.
        }
Ejemplo n.º 42
0
 public Task <IEnumerable <Contact> > GetAll()
 {
     return(Task.FromResult(_contacts.AsEnumerable()));
 }
Ejemplo n.º 43
0
        public async Task <CalculationProviderResultSearchResultViewModel> PerformSearch(SearchRequestViewModel request)
        {
            SearchFilterRequest requestOptions = new SearchFilterRequest()
            {
                Page          = request.PageNumber.HasValue ? request.PageNumber.Value : 1,
                PageSize      = request.PageSize.HasValue ? request.PageSize.Value : 50,
                SearchTerm    = request.SearchTerm,
                IncludeFacets = request.IncludeFacets,
                ErrorToggle   = string.IsNullOrWhiteSpace(request.ErrorToggle) ? (bool?)null : (request.ErrorToggle == "Errors" ? true : false),
                Filters       = request.Filters
            };

            if (request.PageNumber.HasValue && request.PageNumber.Value > 0)
            {
                requestOptions.Page = request.PageNumber.Value;
            }

            PagedResult <CalculationProviderResultSearchResultItem> searchRequestResult = await _resultsClient.FindCalculationProviderResults(requestOptions);

            if (searchRequestResult == null)
            {
                _logger.Error("Find providers HTTP request failed");
                return(null);
            }

            CalculationProviderResultSearchResultViewModel result = new CalculationProviderResultSearchResultViewModel
            {
                TotalResults      = searchRequestResult.TotalItems,
                CurrentPage       = searchRequestResult.PageNumber,
                TotalErrorResults = searchRequestResult.TotalErrorItems
            };

            List <SearchFacetViewModel> searchFacets = new List <SearchFacetViewModel>();

            if (searchRequestResult.Facets != null)
            {
                foreach (SearchFacet facet in searchRequestResult.Facets)
                {
                    searchFacets.Add(_mapper.Map <SearchFacetViewModel>(facet));
                }
            }

            result.Facets = searchFacets.AsEnumerable();

            List <CalculationProviderResultSearchResultItemViewModel> itemResults = new List <CalculationProviderResultSearchResultItemViewModel>();

            foreach (CalculationProviderResultSearchResultItem searchresult in searchRequestResult.Items)
            {
                itemResults.Add(_mapper.Map <CalculationProviderResultSearchResultItemViewModel>(searchresult));
            }

            result.CalculationProviderResults = itemResults.AsEnumerable();

            if (result.TotalResults == 0)
            {
                result.StartItemNumber = 0;
                result.EndItemNumber   = 0;
            }
            else
            {
                result.StartItemNumber = ((requestOptions.Page - 1) * requestOptions.PageSize) + 1;
                result.EndItemNumber   = result.StartItemNumber + requestOptions.PageSize - 1;
            }

            if (result.EndItemNumber > searchRequestResult.TotalItems)
            {
                result.EndItemNumber = searchRequestResult.TotalItems;
            }

            result.PagerState = new PagerState(requestOptions.Page, searchRequestResult.TotalPages, 4);

            return(result);
        }
Ejemplo n.º 44
0
        public async Task <PartialViewResult> CreateOrUpdateTaxRuleRuleModal(long taxRuleId, long?id = null)
        {
            ITaxRuleAppService     taxRuleAppService = this._taxRuleAppService;
            NullableIdInput <long> nullableIdInput   = new NullableIdInput <long>()
            {
                Id = id
            };
            GetTaxRuleRuleForEditOutput taxRuleRuleForEdit = await taxRuleAppService.GetTaxRuleRuleForEdit(nullableIdInput);

            if (!taxRuleRuleForEdit.TaxRuleRule.Id.HasValue)
            {
                taxRuleRuleForEdit.TaxRuleRule.TaxRuleId = taxRuleId;
            }
            CreateOrUpdateTaxRuleRuleModalViewModel createOrUpdateTaxRuleRuleModalViewModel = new CreateOrUpdateTaxRuleRuleModalViewModel(taxRuleRuleForEdit);
            List <SelectListItem> selectListItems = new List <SelectListItem>();

            using (HttpClient httpClient = new HttpClient())
            {
                string str = this.Url.RouteUrl("DefaultApiWithAction", new { httproute = "", controller = "Generic", action = "GetCountriesAsSelectListItems", countryId = 0, selectedCountryId = createOrUpdateTaxRuleRuleModalViewModel.TaxRuleRule.CountryId }, this.Request.Url.Scheme);
                using (HttpResponseMessage async = await httpClient.GetAsync(str))
                {
                    if (async.IsSuccessStatusCode)
                    {
                        string str1 = await async.Content.ReadAsStringAsync();

                        selectListItems = JsonConvert.DeserializeObject <List <SelectListItem> >(str1);
                    }
                }
            }
            List <SelectListItem> selectListItems1 = selectListItems;
            SelectListItem        selectListItem   = new SelectListItem()
            {
                Text     = "",
                Value    = "",
                Disabled = false
            };

            selectListItems1.Insert(0, selectListItem);
            this.ViewData["Countries"] = selectListItems.AsEnumerable <SelectListItem>();
            List <SelectListItem> selectListItems2 = new List <SelectListItem>();

            foreach (Tax taxesForTaxRule in await this._taxAppService.GetTaxesForTaxRules())
            {
                List <SelectListItem> selectListItems3 = selectListItems2;
                SelectListItem        selectListItem1  = new SelectListItem()
                {
                    Text     = string.Format("{0} - {1}%", taxesForTaxRule.Name, taxesForTaxRule.Rate),
                    Value    = taxesForTaxRule.Id.ToString(),
                    Disabled = false,
                    Selected = false
                };
                selectListItems3.Add(selectListItem1);
            }
            List <SelectListItem> selectListItems4 = selectListItems2;
            SelectListItem        selectListItem2  = new SelectListItem()
            {
                Text     = "",
                Value    = "",
                Disabled = false
            };

            selectListItems4.Insert(0, selectListItem2);
            this.ViewData["Taxes"] = selectListItems2.AsEnumerable <SelectListItem>();
            List <SelectListItem> selectListItems5 = new List <SelectListItem>();

            foreach (Lookup lookupItem in (new LookupFill("TaxRuleBehaviors", this.AbpSession.TenantId.Value)).LookupItems)
            {
                SelectListItem selectListItem3 = new SelectListItem()
                {
                    Text     = lookupItem.Text,
                    Value    = lookupItem.Value,
                    Disabled = lookupItem.Disabled,
                    Selected = lookupItem.Selected
                };
                selectListItems5.Add(selectListItem3);
            }
            SelectListItem selectListItem4 = new SelectListItem()
            {
                Text     = "",
                Value    = "",
                Disabled = false
            };

            selectListItems5.Insert(0, selectListItem4);
            this.ViewData["TaxRuleBehaviors"] = selectListItems5;
            return(this.PartialView("_CreateOrUpdateTaxRuleRuleModal", createOrUpdateTaxRuleRuleModalViewModel));
        }