Example #1
0
        static void Main(string[] args)
        {
            var species = new Dictionary<string, int>()
            {
                {"Emperor Penguin", 0},
                {"Little Penguin", 1},
                {"Macaroni Penguin", 2},
            };
            var result = new int[3];
            int n = int.Parse(Console.ReadLine());
            var notebook = new List<string>();
            for (int i = 0; i < n; i++)
            {
                notebook.Add(Console.ReadLine());
            }

            foreach (var peng in notebook)
            {
                int index = species.SingleOrDefault(p => p.Key == peng).Value;
                result[index]++;
            }

            var maxNotes = Array.FindIndex(result, r => r == result.Max());
            var output = species.SingleOrDefault(s => s.Value == maxNotes).Key;
            Console.WriteLine(output);


        }
        protected List<TicketAttachment> GetFilesFromForm(ControllerContext controllerContext)
        {
            var request = controllerContext.HttpContext.Request;

            var formElements = new Dictionary<string, object>();
            request.Form.CopyTo(formElements);

            List<TicketAttachment> files = new List<TicketAttachment>();

            var fileIdElements = formElements.Where(fe => fe.Key.StartsWith("fileId_") || fe.Key.StartsWith("newFileId_"));
            foreach (var fileIdElement in fileIdElements)
            {
                string fileId = fileIdElement.Value as string;
                var fileNamePair = formElements.SingleOrDefault(fe => fe.Key == "fileName_" + fileId || fe.Key == "newFileName_" + fileId);
                var fileDescPair = formElements.SingleOrDefault(fe => fe.Key == "fileDescription_" + fileId || fe.Key == "newFileDescription_" + fileId);
                if (!string.IsNullOrEmpty(fileNamePair.Key) && !string.IsNullOrEmpty(fileNamePair.Key))
                {
                    string fileName = fileNamePair.Value as string;
                    string fileDescription = fileDescPair.Value as string;
                    files.Add(new TicketAttachment { FileId = Convert.ToInt32(fileId), FileName = fileName, FileDescription = fileDescription });
                }
            }
            return files;
        }
Example #3
0
        private void PreventiveToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook preventiveFile;
            List<XLWorkbook> preventiveFiles = new List<XLWorkbook>();
            int[] preventivFileLocations = new int[] { 3, 3, 16, 15, 17, 18, 0 };//use 3 twice so we can get the 2 metrics from BMI file
            //this allows the loop in the preventive metrics object to iterate over file 3 2 times with different results

            foreach (int fileNum in preventivFileLocations)
            {
                preventiveFile = new XLWorkbook(metrics_files[fileNum]);
                string name = preventiveFile.Properties.Title;
                preventiveFiles.Add(preventiveFile);
            }

            foreach (String provider in providers)
            {
                PreventiveMetric preventive = new PreventiveMetric(provider, preventiveFiles);
                List<object> metrics = preventive.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
Example #4
0
        private void DiabetesToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook diabetesFile;
            List<XLWorkbook> diabetesFiles = new List<XLWorkbook>();
            int[] diabetesFileLocations = new int[] { 8, 10, 11, 12, 9 }; //order is pretty important here, because of the hardcode int he actual Metricsa Class file and the way it is searchinf for values. Just keep the order on all metrics the same as they are no unless osmehitng chnages like file name or what have you that might mess this order up.

            foreach (int fileNum in diabetesFileLocations)
            {
                diabetesFile = new XLWorkbook(metrics_files[fileNum]);
                diabetesFiles.Add(diabetesFile);
            }

            foreach (String provider in providers)
            {
                DiabetesMetric diabetes = new DiabetesMetric(provider, diabetesFiles);
                List<object> metrics = diabetes.Metrics;

                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                if (row != null)
                {

                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else if (x == 2 || x == 3 ) { cell.Style.NumberFormat.Format = "@"; }
                        else if (x == 5) { cell.Style.NumberFormat.Format = "0.0"; }
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
Example #5
0
        private void DepressionToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook depressionFile;
            List<XLWorkbook> depressionFiles = new List<XLWorkbook>();
            int[] depressionFileLocations = new int[] { 7, 5, 4, 6 };

            foreach (int fileNum in depressionFileLocations)
            {
                depressionFile = new XLWorkbook(metrics_files[fileNum]);
                depressionFiles.Add(depressionFile);
            }
            foreach (String provider in providers)
            {
                DepressionMetric depression = new DepressionMetric(provider, depressionFiles);
                List<object> metrics = depression.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                //if Keys do not contain provider name, then row will be null , and no sense in trying to populate!
                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        if (x > 7) //do this to up the cell number it x => 7 because in the dashboard cell 7 is a blank line down th middle to seprate the two sides and we want to skip this column
                            cell = row.Cell(x + 1);

                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else if (x == 2 || x == 3 || x == 8) { cell.Style.NumberFormat.Format = "@";}
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
Example #6
0
        private void CardiovascularToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook cardiovascularFile;
            List<XLWorkbook> cardiovascularFiles = new List<XLWorkbook>();
            int[] cardiovascularFileLocations = new int[] { 13 };

            foreach (int fileNum in cardiovascularFileLocations)
            {
                cardiovascularFile = new XLWorkbook(metrics_files[fileNum]);
                cardiovascularFiles.Add(cardiovascularFile);
            }

            foreach (String provider in providers)
            {
                CardiovascularMetric cardio = new CardiovascularMetric(provider, cardiovascularFiles);
                List<object> metrics = cardio.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else if (x == 2) { cell.Style.NumberFormat.Format = "@";  }
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
        private async Task Play(TimingMessage playMessage)
        {
            var folders = new Dictionary<string, StorageFolder>
                              {
                                  { "MUSIC:", KnownFolders.MusicLibrary }, 
                                  { "VIDEOS:", KnownFolders.VideosLibrary }, 
                                  { "PICTURES:", KnownFolders.PicturesLibrary }, 
                                  { "CAMERA:", KnownFolders.CameraRoll }, 
                                  { "SAVED:", KnownFolders.SavedPictures }
                              };

            try
            {
                await this.dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal, 
                    async () =>
                        {
                            // force start of whatever is most recently sent
                            if (this.player.CurrentState != MediaElementState.Closed
                                && this.player.CurrentState != MediaElementState.Stopped)
                            {
                                this.player.Stop();
                            }

                            if (this.player.Source != null)
                            {
                                this.player.Source = null;
                            }

                            StorageFile file = null;

                            var url = playMessage.Url;
                            var isWebUrl = false;

                            var colon = url.IndexOf(':');
                            if (colon > -1)
                            {
                                var root = url.Substring(0, colon + 1).ToUpperInvariant();

                                var folder = folders.SingleOrDefault(f => root.StartsWith(f.Key));
                                if (folder.Value != null)
                                {
                                    file = await folder.Value.GetFileAsync(url.Substring(colon + 1));
                                }
                                else
                                {
                                    isWebUrl = true;
                                }
                            }

                            if (isWebUrl)
                            {
                                this.player.Source = new Uri(url);
                            }
                            else
                            {
                                if (file == null)
                                {
                                    await
                                        this.SendResult(
                                            new ResultMessage(playMessage)
                                                {
                                                    ResultId = -3, 
                                                    Result = "file does not exist"
                                                });
                                    return;
                                }

                                var stream = await file.OpenAsync(FileAccessMode.Read);
                                this.player.SetSource(stream, file.ContentType);
                            }

                            this.player.Tag = playMessage;
                            this.player.CurrentStateChanged += this.Player_CurrentStateChanged;

                            this.player.Play();
                        });
            }
            catch (Exception e)
            {
                await this.SendResult(new ResultMessage(playMessage) { ResultId = e.HResult, Result = e.Message });
            }
        }
        public static FilterNode Parse(string filterStr)
        {
            var tok = new StringTokenizer(filterStr)
                {
                    IgnoreWhiteSpace = true,
                    // the following two should be mutually exclusive
                    // if the following have a mutually shared char, Word char will take precedence
                    // when creating tokens at this time...
                    AdditionalWordChars = new char[] { '*', ' ', '.' },
                    SymbolChars = new[] { '(', ')', '^', '|', ':' }
                };

            var nodeid = 0;
            var nodes = new Dictionary<int, FilterNode>();

            var currentNodeId = ++nodeid;
            nodes.Add(currentNodeId, new FilterNode { ParentNodeId = 0, NodeId = currentNodeId, NodeType = FilterNodeType.Root });
            var currentNode = nodes[nodeid];

            // parse tokens
            Token token;
            do
            {
                token = tok.Next();

                if (token.Kind == TokenKind.Symbol && token.Value == "(")
                {
                    currentNodeId = ++nodeid;
                    nodes.Add(currentNodeId, new FilterNode { ParentNodeId = currentNode.NodeId, NodeId = currentNodeId });
                    currentNode = nodes[nodeid];
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == ")")
                {
                    currentNode = nodes[currentNode.ParentNodeId];
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == "^")
                {
                    currentNode.NodeType = FilterNodeType.AndExpression;
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == "|")
                {
                    currentNode.NodeType = FilterNodeType.OrExpression;
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == ":")
                {
                }
                else if (token.Kind == TokenKind.Word || token.Kind == TokenKind.Number || token.Kind == TokenKind.QuotedString)
                {
                    currentNode.Elements.Add(token.Value);
                }

            } while (token.Kind != TokenKind.EOF);

            // build the tree
            foreach (var node in nodes)
            {
                node.Value.Nodes.AddRange(nodes.Where(n => n.Value.ParentNodeId == node.Key).Select(n => n.Value));
                node.Value.ParentNode = nodes.SingleOrDefault(n => n.Key == node.Value.ParentNodeId).Value;
            }

            // return the root node
            var filterNode = nodes[1];
            return filterNode;
        }
Example #9
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var thisController = ((ProductController)filterContext.Controller);
            IMenuProductRepository prodRepository = thisController.MenuProductRepository;
            string user = thisController.CurrentUser.UserName;

            //Sperimentale
            // first look at routedata then at request parameter:
            var id = (filterContext.RequestContext.RouteData.Values["id"] as string) ?? ("" as string);


            //associazione tra la categoria del prodotto e la Role
            Dictionary<string, string> prodMod = new Dictionary<string, string>();
            prodMod.Add("FogliSingoli", "SmallFormat");
            prodMod.Add("Book", "SmallFormat");
            prodMod.Add("GrandeFormato", "WideFormat");
            prodMod.Add("Rotoli", "Label");
            prodMod.Add("Cliche", "Cliche");
            prodMod.Add("Description", "Description");

            bool redirect = false;

            if (prodRepository != null)
            {
                var product = prodRepository.GetSingle(id);

                Console.WriteLine(product.CodCategory);

                if (product != null)
                {
                   
                    if (!System.Web.Security.Roles.RoleExists(product.CodCategory))
                    {
                        System.Web.Security.Roles.CreateRole(product.CodCategory);
                    }

                    //if is Generico 
                    if (product.CodCategory == "Description")
                    {
                        try
                        {
                            //user that is not in... 
                            var _users = System.Web.Security.Roles.GetUsersInRole(prodMod.SingleOrDefault(k => k.Key == product.CodCategory).Value);
                            if (!_users.Contains(user))
                            {
                                System.Web.Security.Roles.AddUserToRole(user, "Description");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Write(e.Message);
                            System.Web.Security.Roles.AddUserToRole(user, "Description");
                        }                        
                    }

                    //traduzione e ricerca dal prodotto -> modulo
                    var users = System.Web.Security.Roles.GetUsersInRole(prodMod.SingleOrDefault(k => k.Key == product.CodCategory).Value);
                    redirect = !users.Contains(user);
                }
            }

            if (redirect)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Account",
                        action = "EditProfile",
                        view = "EditProfileModule",
                        area = "Account"
                    }));
            }

            //sperimentale ----------------------------------------

        }
        public void DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                { 1, "A" },
                { 2, "B" },
            };

            Assert.That(() => dictionary.SingleOrDefault(),
                Throws.TypeOf<InvalidOperationException>());
        }
        public void DictionaryExtensions_SingleOrDefault_ReturnsSingleItemInDictionary()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                { 4, "A" },
            };

            var result = dictionary.SingleOrDefault();

            TheResultingValue(result).ShouldBe(new KeyValuePair<Int32, String>(4, "A"));
        }
        public void DictionaryExtensions_SingleOrDefault_ReturnsDefaultValueIfDictionaryIsEmpty()
        {
            var dictionary = new Dictionary<Int32, String>();

            var result = dictionary.SingleOrDefault();

            TheResultingValue(result).ShouldBe(default(KeyValuePair<Int32, String>));
        }
        public void DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                { 1, "A" },
                { 2, "B" },
            };

            dictionary.SingleOrDefault();
        }
Example #14
0
        internal void CreateSolution(MainViewModel mainViewModel)
        {
            var model = mainViewModel.SelectedTemplate;
            var company = mainViewModel.Company;
            var solutionName = mainViewModel.SolutionName;

            if (model == null)
            {
                return;
            }

            var registryPath = String.Format(Environment.Is64BitOperatingSystem ? @"Software\Wow6432Node\Microsoft\VisualStudio\{0}" : @"Software\Microsoft\VisualStudio\{0}", DTE.Version);
            var registryKey = Registry.LocalMachine.OpenSubKey(registryPath);

            if (registryKey == null)
            {
                return;
            }

            var installDir = registryKey.GetValue("InstallDir");
            var solution = DTE.Solution as Solution4;

            if (solution == null)
            {
                return;
            }

            string solutionFileName;

            if (solution.IsOpen)
            {
                solution.Close();
            }

            var properties = DTE.Properties["Environment", "ProjectsAndSolution"];
            var setting = properties.Item("ProjectsLocation");

            if (setting != null && setting.Value != null)
            {
                var targetDir = Path.Combine(setting.Value.ToString(), solutionName);

                if (!Directory.Exists(targetDir))
                {
                    Directory.CreateDirectory(targetDir);
                }

                solutionFileName = Path.Combine(targetDir, String.Format("{0}.sln", solutionName));
                solution.Create(targetDir, solutionName);
                solution.SaveAs(solutionName);
            }
            else
            {
                return;
            }

            var projects = new Dictionary<Guid, Tuple<Project, string, ICollection<Guid>, ICollection<string>>>();
            DTE.Events.SolutionEvents.ProjectAdded += project =>
            {
                var item = projects.SingleOrDefault(x => x.Value.Item2 == project.Name);

                if (projects.ContainsKey(item.Key))
                {
                    projects[item.Key] = new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(project, item.Value.Item2, item.Value.Item3, item.Value.Item4);
                }
            };

            // Create Folders & Projects
            foreach (var folder in model.Folders)
            {
                var solutionFolder = (SolutionFolder)solution.AddSolutionFolder(folder.Name).Object;

                foreach (var project in folder.Projects)
                {
                    var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
                    var projectFolder = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);

                    if (Directory.Exists(projectFolder))
                    {
                        continue;
                    }

                    projects.Add(project.Id, new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(null, fullProjectName, project.References, project.Packages));

                    var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
                    solutionFolder.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
                }
            }

            // Create Projects - without folders
            foreach (var project in model.Projects)
            {
                var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
                var projectFolder = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);

                if (Directory.Exists(projectFolder))
                {
                    continue;
                }

                projects.Add(project.Id, new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(null, fullProjectName, project.References, project.Packages));

                var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
                solution.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
            }

            // Reference the Projects
            foreach (var project in projects)
            {
                var vsProject = project.Value.Item1;
                var solutionProject = vsProject.Object as VSProject;

                InstallNugetPackages(vsProject, project.Value.Item4);

                if (solutionProject != null)
                {
                    var references = projects.Where(x => project.Value.Item3.Contains(x.Key)).Select(x => x.Value.Item1);

                    foreach (var reference in references)
                    {
                        solutionProject.References.AddProject(reference);
                    }
                }

                vsProject.Save();
            }

            solution.SaveAs(solutionFileName);
        }
        /// <summary>
        /// Verify file stream information
        /// </summary>
        /// <param name="fileStreamInformations">A list of FileStreamInformation structures</param>
        /// <param name="streamList">A dictionary of streamname and streamsize mapping</param>
        private void VerifyFileStreamInformations(List<FileStreamInformation> fileStreamInformations, Dictionary<string, long> streamList)
        {
            // To verify whether the count of filestreaminformation data elements equals to the actual data streams counts
            BaseTestSite.Assert.AreEqual(streamList.Count, fileStreamInformations.Count,
                "The total number of the returned FILE_STREAM_INFORMATION data elements should be equal the total streams that has been added to the file.");

            // To verify whether each data element of filestreaminformation matches with the actual data streams in name and size
            foreach (FileStreamInformation fileStreamInformation in fileStreamInformations)
            {
                string streamName = Encoding.Unicode.GetString(fileStreamInformation.StreamName);
                KeyValuePair<string, long> streamListElement = streamList.SingleOrDefault(x => x.Key.Equals(streamName));
                BaseTestSite.Assert.IsNotNull(streamListElement, "The stream with name {0} is found.", streamListElement.Key);
                BaseTestSite.Assert.AreEqual(streamListElement.Value, (long)fileStreamInformation.StreamSize,
                    "The StreamSize field of each of the returned FILE_STREAM_INFORMATION data elements should match the size of bytes written to each data stream.");
            }
        }
Example #16
0
        private void AsthmaToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook asthmaFile;
            List<XLWorkbook> asthmaFiles = new List<XLWorkbook>();
            int[] asthmaFileLocations = new int[] {1, 2};

            foreach (int fileNum in asthmaFileLocations)
            {
                asthmaFile = new XLWorkbook(metrics_files[fileNum]);
                asthmaFiles.Add(asthmaFile);
            }
            foreach (String provider in providers)
            {
                AsthmaMetric asthma = new AsthmaMetric(provider, asthmaFiles);
                List<object> metrics = asthma.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grab the row out of the value field for the matching KVP entry. this ensures the providert names are matched and no missing providers get data for some one who does exist

                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        if (x == 2 || x == 4) { cell.Style.NumberFormat.Format = "@"; }
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
Example #17
0
        private void InternalPrintOrders(PrintJob printJob, Ticket ticket, IEnumerable<Order> orders)
        {
            if (printJob.PrinterMaps.Count == 1
                && printJob.PrinterMaps[0].MenuItemId == 0
                && printJob.PrinterMaps[0].MenuItemGroupCode == null)
            {
                PrintOrderLines(ticket, orders, printJob.PrinterMaps[0]);
                return;
            }

            var ordersCache = new Dictionary<PrinterMap, IList<Order>>();

            foreach (var item in orders)
            {
                var p = GetPrinterMapForItem(printJob.PrinterMaps, item.MenuItemId);
                if (p != null)
                {
                    var lmap = p;
                    var pmap = ordersCache.SingleOrDefault(
                            x => x.Key.PrinterId == lmap.PrinterId && x.Key.PrinterTemplateId == lmap.PrinterTemplateId).Key;
                    if (pmap == null)
                        ordersCache.Add(p, new List<Order>());
                    else p = pmap;
                    ordersCache[p].Add(item);
                }
            }

            foreach (var order in ordersCache)
            {
                PrintOrderLines(ticket, order.Value, order.Key);
            }
        }
        private IEnumerable<TicketPrintTask> GetPrintTasks(PrintJob printJob, Ticket ticket, IEnumerable<Order> orders)
        {
            var result = new List<TicketPrintTask>();

            if (printJob.PrinterMaps.Count == 1
                && printJob.WhatToPrint != 3
                && printJob.WhatToPrint != 4
                && printJob.PrinterMaps[0].MenuItemId == 0
                && printJob.PrinterMaps[0].MenuItemGroupCode == null)
            {
                result.Add(GetPrintTask(ticket, orders, printJob.PrinterMaps[0]));
                return result;
            }

            var ordersCache = new Dictionary<PrinterMap, IList<Order>>();

            foreach (var item in orders)
            {
                var p = GetPrinterMapForItem(printJob.PrinterMaps, item.MenuItemId);
                if (p != null)
                {
                    var lmap = p;
                    var pmap = ordersCache.SingleOrDefault(
                            x => x.Key.PrinterId == lmap.PrinterId && x.Key.PrinterTemplateId == lmap.PrinterTemplateId).Key;
                    if (pmap == null)
                        ordersCache.Add(p, new List<Order>());
                    else p = pmap;
                    ordersCache[p].Add(item);
                }
            }
            switch (printJob.WhatToPrintType)
            {
                case WhatToPrintTypes.SeparatedByQuantity: result.AddRange(GenerateSeparatedTasks(ticket, ordersCache));
                    break;
                default:
                    result.AddRange(ordersCache.Select(order => GetPrintTask(ticket, order.Value, order.Key)));
                    break;
            }
            return result;
        }
        /// <summary>
        /// Updating catalogs (only their names, not their fields or records)
        /// </summary>
        /// <param name="entity">The contract-type defining the catalog</param>
        /// <param name="newEntryTexts">Name/Description of the catalog</param>
        /// <param name="CreateNew">true to signal the creation of a new catalog, false for updating existing catalogs</param>
        public void SaveEntityGroup(TopContractsEntities.ContractType entity, Dictionary<string, SysTableEntryText> newEntryTexts, bool CreateNew)
        {
            TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName());
            TopContractsEntities.FieldGroup efFieldGroup = new TopContractsEntities.FieldGroup();

            //efFieldGroup.InitCommonFields(efFieldGroup, entity, efFieldGroup.FieldGroupsLNGs);
            if (CreateNew)
            {
                foreach (var cTypeLng in entity.ContractTypesLNGs)
                {
                    efFieldGroup.FieldGroupsLNGs.Add(new FieldGroupsLNG { OrganizationIdentifier = this.organizationIdentifier, CultureId = cTypeLng.CultureId, DescShort = cTypeLng.DescShort, DescLong = cTypeLng.DescLong });
                }
                efFieldGroup.OrganizationIdentifier = this.organizationIdentifier;
                efFieldGroup.ContractTypeVisibility = (byte)FieldGroupContractTypeVisibility.VisibleToTypes;
                efFieldGroup.RolesVisibility = (byte)FieldGroupRoleVisibility.VisibleToAll;
                efFieldGroup.Inactive = false;
                efFieldGroup.Locked = false;
                efFieldGroup.DisplayOrder = null;
                efFieldGroup.ExternalID = null;
                efFieldGroup.SingleRecord = true;
                efFieldGroup.FieldGroupsContractTypesMAPs.Add(new FieldGroupsContractTypesMAP { OrganizationIdentifier = this.organizationIdentifier, ContractTypeID = entity.ContractTypeID });
                context.FieldGroups.Add(efFieldGroup);
            }
            else
            {
                // code to modify action of the entity field group when action of an entity is changed.
                if (context.FieldGroupsContractTypesMAPs.Any(u => u.ContractTypeID == entity.ContractTypeID))
                {
                    List<FieldGroupsLNG> fgLngs = context.FieldGroupsContractTypesMAPs.SingleOrDefault(u => u.ContractTypeID == entity.ContractTypeID).FieldGroup.FieldGroupsLNGs.ToList();
                    foreach (var fgLng in fgLngs)
                    {
                        fgLng.DescShort = newEntryTexts.SingleOrDefault(l => l.Key == fgLng.CultureId.Trim()).Value.DescShort;
                        fgLng.DescLong = newEntryTexts.SingleOrDefault(l => l.Key == fgLng.CultureId.Trim()).Value.DescLong;
                    }
                }
            }
            context.SaveChanges();
        }
Example #20
0
        private static void InternalPrintOrders(PrintJob printJob, Ticket ticket, IEnumerable<TicketItem> ticketItems)
        {
            if (printJob.PrinterMaps.Count == 1
                && printJob.PrinterMaps[0].TicketTag == null
                && printJob.PrinterMaps[0].MenuItem == null
                && printJob.PrinterMaps[0].MenuItemGroupCode == null
                && printJob.PrinterMaps[0].Department == null)
            {
                PrintOrderLines(ticket, ticketItems, printJob.PrinterMaps[0]);
                return;
            }

            var ordersCache = new Dictionary<PrinterMap, IList<TicketItem>>();

            foreach (var item in ticketItems)
            {
                var p = GetPrinterMapForItem(printJob.PrinterMaps, ticket, item);
                if (p != null)
                {
                    var lmap = p;
                    var pmap = ordersCache.SingleOrDefault(
                            x => x.Key.Printer == lmap.Printer && x.Key.PrinterTemplate == lmap.PrinterTemplate).Key;
                    if (pmap == null)
                        ordersCache.Add(p, new List<TicketItem>());
                    else p = pmap;
                    ordersCache[p].Add(item);
                }
            }

            foreach (var order in ordersCache)
            {
                PrintOrderLines(ticket, order.Value, order.Key);
            }
        }