示例#1
0
        private void SendNotificationEmail(string message)
        {
            var templateName = "exception_report";

            var exceptionRecipients = ReadConfig.CommonCloudCoreApplicationSettings.ExceptionRecipients;
            var recipients = new List<EmailRecipient>();
            for (int index = 0; index < exceptionRecipients.Count; index++)
            {
                recipients.Add(new EmailRecipient() { RecipientEmail = exceptionRecipients[index].RecipientAddress });
            }

            if (recipients.Any())
            {
                var globalVariables = new Dictionary<string, string>
                {
                    { "exceptioncontent", message.Replace("\n", "<br />") },
                    { "subject", "Exception Report" },
                };

                var postageAppClient = new PostageAppClient()
                {
                    TemplateName = templateName,
                    GlobalVariables = globalVariables.ToList(),
                    Recipients = recipients
                };

                postageAppClient.Send();
            }
        }
        public IList GetBingLanguages()
        {
            var languages = new Dictionary<string, string>
                                {
                                    {"Arabic", "ar"},
                                    {"Czech", "cs"},
                                    {"Danish", "da"},
                                    {"German", "de"},
                                    {"English", "en"},
                                    {"Estonian", "et"},
                                    {"Finnish", "fi"},
                                    {"French", "fr"},
                                    {"Dutch", "nl"},
                                    {"Greek", "el"},
                                    {"Hebrew", "he"},
                                    {"Haitian Creole", "ht"},
                                    {"Hungarian", "hu"},
                                    {"Indonesian", "id"},
                                    {"Italian", "it"},
                                    {"Japanese", "ja"},
                                    {"Korean", "ko"},
                                    {"Lithuanian", "lt"},
                                    {"Latvian", "lv"},
                                    {"Norwegian", "no"},
                                    {"Polish", "pl"},
                                    {"Portuguese", "pt"},
                                    {"Romanian", "ro"},
                                    {"Spanish", "es"},
                                    {"Russian", "ru"},
                                    {"Slovak", "sk"},
                                    {"Slovene", "sl"},
                                    {"Swedish", "sv"},
                                    {"Thai", "th"},
                                    {"Turkish", "tr"},
                                    {"Ukrainian", "uk"},
                                    {"Vietnamese", "vi"},
                                    {"Simplified Chinese", "zh-CHS"},
                                    {"Traditional Chinese", "zh-CHT"}
                                };

            return languages.ToList();
        }
		public IronPythonComposablePart(IronPythonTypeWrapper typeWrapper, IEnumerable<Type> exports, IEnumerable<KeyValuePair<string, IronPythonImportDefinition>> imports, IDictionary<object, object> exportMetadatas)
		{
			_typeWrapper = typeWrapper;
			_instance = typeWrapper.Activator();
			_exports = new List<ExportDefinition>(exports.Count());
			_imports = new Dictionary<string, ImportDefinition>(imports.Count());
			foreach (var export in exports)
			{
				var metadata = new Dictionary<string, object>()
                                   {
                                       {"ExportTypeIdentity", AttributedModelServices.GetTypeIdentity(export)}
                                   };

				if (exportMetadatas != null)
				{
					foreach (var data in exportMetadatas)
					{
						metadata.Add(data.Key.ToString(), data.Value);
					}
				}

				var contractName = AttributedModelServices.GetContractName(export);
				_exports.Add(new ExportDefinition(contractName, metadata));
			}
			foreach (var import in imports)
			{
				var contractName = AttributedModelServices.GetContractName(import.Value.Type);
				var metadata = new Dictionary<string, Type>();

				_imports[import.Key] = new IronPythonContractBasedImportDefinition(
					import.Key,
					contractName,
					AttributedModelServices.GetTypeIdentity(import.Value.Type),
					metadata.ToList(),
					import.Value.Cardinality, import.Value.IsRecomposable, import.Value.IsPrerequisite,
					CreationPolicy.Any);
			}
		}
        public IList GetGoogleLanguages()
        {
            var languages = new Dictionary<string, string>
                                {
                                    {"Afrikaans", "af"},
                                    {"Albanian", "sq"},
                                    {"Arabic", "ar"},
                                    {"Belarusian", "be"},
                                    {"Bulgarian", "bg"},
                                    {"Catalan", "ca"},
                                    {"Chinese Simplified", "zh-CN"},
                                    {"Chinese Traditional", "zh-TW"},
                                    {"Croatian", "hr"},
                                    {"Czech", "cs"},
                                    {"Danish", "da"},
                                    {"Dutch", "nl"},
                                    {"English", "en"},
                                    {"Estonian", "et"},
                                    {"Filipino", "tl"},
                                    {"Finnish", "fi"},
                                    {"French", "fr"},
                                    {"Galician", "gl"},
                                    {"German", "de"},
                                    {"Greek", "el"},
                                    {"Haitian Creole", "ht"},
                                    {"Hebrew", "iw"},
                                    {"Hindi", "hi"},
                                    {"Hungarian", "hu"},
                                    {"Icelandic", "is"},
                                    {"Indonesian", "id"},
                                    {"Irish", "ga"},
                                    {"Italian", "it"},
                                    {"Japanese", "ja"},
                                    {"Latvian", "lv"},
                                    {"Lithuanian", "lt"},
                                    {"Macedonian", "mk"},
                                    {"Malay", "ms"},
                                    {"Maltese", "mt"},
                                    {"Norwegian", "no"},
                                    {"Persian", "fa"},
                                    {"Polish", "pl"},
                                    {"Portuguese", "pt"},
                                    {"Romanian", "ro"},
                                    {"Russian", "ru"},
                                    {"Serbian", "sr"},
                                    {"Slovak", "sk"},
                                    {"Slovenian", "sl"},
                                    {"Spanish", "es"},
                                    {"Swahili", "sw"},
                                    {"Swedish", "sv"},
                                    {"Thai", "th"},
                                    {"Turkish", "tr"},
                                    {"Ukrainian", "uk"},
                                    {"Vietnamese", "vi"},
                                    {"Welsh", "cy"},
                                    {"Yiddish", "yi"}
                                };

            return languages.ToList();
        }
示例#5
0
		private void validateMergedCellBorder(RtfTableCell representative, Direction dir)
		{
			if (!representative.IsMerged) {
				throw new Exception("Invalid representative (cell is not merged).");
			}
			Dictionary<Border, int> stat = new Dictionary<Border, int>();
			Border majorityBorder;
			int majorityCount;
			int limit = (dir == Direction.Top || dir == Direction.Bottom) ? 
				representative.MergeInfo.ColSpan : representative.MergeInfo.RowSpan;
			
			for (int i = 0; i < limit; i++) {
				int r, c;
				Border bdr;
				if (dir == Direction.Top || dir == Direction.Bottom) {
					if (dir == Direction.Top) {
						r = 0;
					} else { // dir == bottom
						r = representative.MergeInfo.RowSpan - 1;
					}
					c = i;
				} else { // dir == right || left
					if (dir == Direction.Right) {
						c = representative.MergeInfo.ColSpan - 1;
					} else { // dir == left
						c = 0;
					}
					r = i;
				}
				bdr = _cells[representative.RowIndex + r][representative.ColIndex + c].Borders[dir];
				if (stat.ContainsKey(bdr)) {
					stat[bdr] = (int)stat[bdr] + 1;
				} else {
					stat[bdr] = 1;
				}
			}
			majorityCount = -1;
			majorityBorder = representative.Borders[dir];
			foreach(KeyValuePair<Border, int> de in stat.ToList()) {
				if(de.Value > majorityCount) {
					majorityCount = de.Value;
					majorityBorder.Style = de.Key.Style;
					majorityBorder.Width = de.Key.Width;
					majorityBorder.Color = de.Key.Color;
				}
			}
		}
示例#6
0
        /// <summary>
        /// Gets a <see cref="FrameworkTemplate"/> based on the specified parameters.
        /// </summary>
        /// <param name="xmlElement">The xml element to get template xaml from.</param>
        /// <param name="parentObject">The <see cref="XamlObject"/> to use as source for resources and contextual information.</param>
        /// <returns>A <see cref="FrameworkTemplate"/> based on the specified parameters.</returns>
        public static FrameworkTemplate GetFrameworkTemplate(XmlElement xmlElement, XamlObject parentObject)
        {
            var nav = xmlElement.CreateNavigator();

            var ns = new Dictionary<string, string>();
            while (true)
            {
                var nsInScope = nav.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
                foreach (var ak in nsInScope)
                {
                    if (!ns.ContainsKey(ak.Key) && ak.Key != "")
                        ns.Add(ak.Key, ak.Value);
                }
                if (!nav.MoveToParent())
                    break;
            }

            xmlElement = (XmlElement)xmlElement.CloneNode(true);

            foreach (var dictentry in ns.ToList())
            {
                var value = dictentry.Value;
                if (value.StartsWith("clr-namespace") && !value.Contains(";assembly=")) {
                    if (!string.IsNullOrEmpty(parentObject.OwnerDocument.CurrentProjectAssemblyName)) {
                        value += ";assembly=" + parentObject.OwnerDocument.CurrentProjectAssemblyName;
                    }
                }
                xmlElement.SetAttribute("xmlns:" + dictentry.Key, value);
            }

            var keyAttrib = xmlElement.GetAttribute("Key", XamlConstants.XamlNamespace);

            if (string.IsNullOrEmpty(keyAttrib)) {
                xmlElement.SetAttribute("Key", XamlConstants.XamlNamespace, "$$temp&&§§%%__");
            }

            var xaml = xmlElement.OuterXml;
            xaml = "<ResourceDictionary xmlns=\"http://schemas.microsoft.com/netfx/2007/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" + xaml + "</ResourceDictionary>";
            StringReader stringReader = new StringReader(xaml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            var xamlReader = new XamlXmlReader(xmlReader, parentObject.ServiceProvider.SchemaContext);

            var seti = new XamlObjectWriterSettings();

            var resourceDictionary = new ResourceDictionary();
            var obj = parentObject;
            while (obj != null)
            {
                if (obj.Instance is ResourceDictionary)
                {
                    var r = obj.Instance as ResourceDictionary;
                    foreach (var k in r.Keys)
                    {
                        if (!resourceDictionary.Contains(k))
                            resourceDictionary.Add(k, r[k]);
                    }
                }
                else if (obj.Instance is FrameworkElement)
                {
                    var r = ((FrameworkElement)obj.Instance).Resources;
                    foreach (var k in r.Keys)
                    {
                        if (!resourceDictionary.Contains(k))
                            resourceDictionary.Add(k, r[k]);
                    }
                }

                obj = obj.ParentObject;
            }

            seti.BeforePropertiesHandler = (s, e) =>
            {
                if (seti.BeforePropertiesHandler != null)
                {
                    var rr = e.Instance as ResourceDictionary;
                    rr.MergedDictionaries.Add(resourceDictionary);
                    seti.BeforePropertiesHandler = null;
                }
            };

            var writer = new XamlObjectWriter(parentObject.ServiceProvider.SchemaContext, seti);

            XamlServices.Transform(xamlReader, writer);

            var result = (ResourceDictionary)writer.Result;

            var enr = result.Keys.GetEnumerator();
            enr.MoveNext();
            var rdKey = enr.Current;

            var template = result[rdKey] as FrameworkTemplate;

            result.Remove(rdKey);
            return template;
        }
示例#7
0
        /// <summary>
        /// Builds the report.
        /// </summary>
        /// <param name="reportDocument">The report document.</param>
        public void BuildReport(ICustomReport reportDocument)
        {
            var currentReport = reportDocument.Reports.First();

            SetIdentity(currentReport);
            //_originalPageHeaderHeight = ((PageHeaderSection) currentReport.Items["pageHeader"]).Height;

            //This report parameter holds the current template system name.
            _processName = currentReport.ReportParameters["processName"].Value.ToString();

            //This report parameter holds the currently visible columns of the grid and in what order they're in
            var cols = currentReport.ReportParameters["columns"].Value.ToString();

            var columns = cols.Split(';').ToList();
            _columns = new List<ColumnInfo>();
            foreach (var col in columns)
            {
                _columns.Add(new ColumnInfo(col));
            }

            var groupsStr = currentReport.ReportParameters["groups"].Value.ToString();
            _groups = (string.IsNullOrEmpty(groupsStr) ? new string[0] : groupsStr.Split(';')).ToList();

            //TODO: Uncomment if needed
           // _columns.AddRange(_groups);

            if (reportDocument.FitToPage)
            {
                if (currentReport.GetType().Name.ToLower().Contains("landscape"))
                {
                    FitToPageColumnWidth = Math.Min(1, 10.0 / _columns.Count);
                    FitToPageColumnCount = (short) Math.Max(10, _columns.Count);
                }

                if (currentReport.GetType().Name.ToLower().Contains("portrait"))
                {
                    FitToPageColumnWidth = Math.Min(1.1, 7.0 / _columns.Count);
                    FitToPageColumnCount = (short) Math.Max(7, _columns.Count);
                }

                currentReport.Width = new Unit(_columns.Count * FitToPageColumnWidth, UnitType.Inch);
            }

            _groupColumn = currentReport.ReportParameters["groupColumn"].Value.ToString();

            var fldList = new List<FieldInfo>(_columns.Count);

            var processProperties = new Dictionary<PropertyInfo, string>();
            var processType = TheDynamicTypeManager.GetInfoType<IInfoClass>(_processName);

            if (processType != null)
            {
                processProperties = processType.GetAllPropertiesWithPaths();
                var properties = processProperties.Where(p => _columns.Any(c=>c.SystemName == p.Value));

                foreach (var column in _columns)
                {
                    foreach (var property in properties)
                    {
                        if (property.Value == column.SystemName)
                        {
                            fldList.Add(new FieldInfo(property.Key, column));
                            break;
                        }
                    }
                }

                _fieldAttrDict = GetFieldAttributes(processProperties.Select(x => x.Key));
            }

            if (_fieldAttrDict == null)
                _fieldAttrDict = new Dictionary<PropertyInfo, FieldParametres>();

            _colDict = new SortedDictionary<int, string[]>();

            //Grouping            
            foreach (var colName in _groups)
            {
                var group = new Telerik.Reporting.Group();
                group.Name = colName;
                var groupHeaderSection = new GroupHeaderSection();
                var groupFooterSection = new GroupFooterSection();
                group.GroupHeader = groupHeaderSection;
                group.GroupFooter = groupFooterSection;

                var txt = new TextBox();
                txt.Style.Font.Size = new Unit(10, UnitType.Point);
                txt.Style.Font.Bold = true;
                txt.Style.BackgroundColor = Color.FromArgb(255, 225, 225, 225);
                txt.Style.TextAlign = HorizontalAlign.Left;
                txt.Style.VerticalAlign = VerticalAlign.Middle;
                groupHeaderSection.Items.Add(txt);
                groupHeaderSection.Height = new Unit(21);
                groupHeaderSection.Style.BorderStyle.Default = BorderType.Solid;
                groupHeaderSection.Style.BorderColor.Default = Color.White;
                groupHeaderSection.Style.BorderColor.Left = Color.Transparent;

                var panel = new Panel();
                panel.Height = new Unit(20);
                panel.Style.LineStyle = LineStyle.Solid;
                panel.Style.LineWidth = new Unit(2.0);
                panel.Style.BorderColor.Default = Color.Black;
                panel.Style.BorderWidth.Default = new Unit(2.0);
                panel.Style.BorderStyle.Default = BorderType.None;
                panel.Style.BorderStyle.Top = BorderType.Solid;
                panel.Style.BorderStyle.Bottom = BorderType.Solid;
                groupFooterSection.Items.Add(panel);
                groupFooterSection.Height = new Unit(25);
                //groupFooterSection.Style.BorderStyle.Default = BorderType.Solid;
                //groupFooterSection.Style.BorderColor.Default = Color.White;
                groupFooterSection.Style.BorderColor.Left = Color.Transparent;
                groupFooterSection.Style.Padding.Top = new Unit(2);
                groupFooterSection.Style.Padding.Bottom = new Unit(2);

                //if you need to filter the data, apply filtering
                //group1.Filters.Add(new Telerik.Reporting.Data.Filter("=Fields.ProductID", Telerik.Reporting.Data.FilterOperator.Equal, "=10"));

                currentReport.Groups.Add(group);
            }

            var aggregateData = currentReport.ReportParameters["aggregates"].Value.ToString();
            _aggregateDict = ParseAggregateData(aggregateData);

            var nextLeft = _groups.Count > 0 ? (_groups.Count - 1) * 0.15 : 0;
            var availableWidth = currentReport.Width.Value - nextLeft;
            var ctrlSize = availableWidth / (fldList.Count() - _groups.Count);

            _indentOffset = 0;

            _reportItemCounter = new Dictionary<string, int>();

            var counter = 0;
            double fitToPageFooterLocationX = 0;

            //posess fields
            foreach (var fld in fldList)
            {
                if (_reportItemCounter.ContainsKey(fld.Property.Name))
                {
                    continue;
                }

                var fieldValueMap = GetFieldValueMap(currentReport, fld.Property, processProperties[fld.Property]);

                if (_groups.Contains(processProperties[fld.Property] ?? string.Empty))
                {
                    //create group
                    var fieldGroup = currentReport.Groups.FirstOrDefault(x => x.Name == processProperties[fld.Property]);
                    if (fieldGroup != null)
                    {
                        _indentOffset = 0.15 * _groups.IndexOf(processProperties[fld.Property]);

                        fieldGroup.Groupings.Add(new Grouping(fieldValueMap));
                        ((TextBox)fieldGroup.GroupHeader.Items[0]).Value = string.Format("='  ' + {0} + '    Total: ' + Exec('{1}', Count(IsNull({0},1)))", fieldValueMap.TrimStart('='), fieldGroup.Name);
                        ((TextBox)fieldGroup.GroupHeader.Items[0]).Location = new PointU(new Unit(_indentOffset, UnitType.Inch), new Unit(0, UnitType.Inch));
                        ((TextBox)fieldGroup.GroupHeader.Items[0]).Size = new SizeU(new Unit(currentReport.Width.Value - _indentOffset, UnitType.Inch), new Unit(20, UnitType.Pixel));
                        //AddGroupLevelLines(fieldGroup.GroupHeader.Items);

                        ((Panel)fieldGroup.GroupFooter.Items[0]).Location = new PointU(new Unit(_indentOffset, UnitType.Inch), new Unit(0, UnitType.Inch));
                        ((Panel)fieldGroup.GroupFooter.Items[0]).Size = new SizeU(new Unit(currentReport.Width.Value - _indentOffset, UnitType.Inch), new Unit(20, UnitType.Pixel));
                        //AddGroupLevelLines(fieldGroup.GroupFooter.Items);                    
                    }

                    continue;
                }

                var cPoint = new PointU(new Unit(nextLeft, UnitType.Inch), new Unit(0.4, UnitType.Inch));
                var uSize = new SizeU(new Unit(ctrlSize, UnitType.Inch), new Unit(0.2, UnitType.Inch));

                var attr = fld.Property.GetCustomAttributes(false);
                var displayAttr = attr.FirstOrDefault(x => x is DisplayAttribute) as DisplayAttribute;

                string colName = "<NoName>";
                if (displayAttr == null)
                {
                    colName = fld.Column.Header;
                    //var infoInstance = Activator.CreateInstance(processType);
                    //if (infoInstance != null)
                    //{
                    //    var field = processType.GetField(fld.Name + "Property");
                    //    if (field != null)
                    //    {
                    //        var fieldValue = field.GetValue(infoInstance) as IPropertyInfo;
                    //        if (fieldValue != null)
                    //        {
                    //            colName = fieldValue.FriendlyName;
                    //        }
                    //    }
                    //}
                }
                else
                {
                    colName = displayAttr.GetName();
                }

                var headerLabel = new TextBox { Value = colName, Location = cPoint, Size = uSize, StyleName = "Caption", Multiline = true, CanGrow = true };
                headerLabel.Style.BackgroundColor = Color.Transparent;
                headerLabel.Style.Font.Size = new Unit(10, UnitType.Point);
                headerLabel.Style.VerticalAlign = VerticalAlign.Top;

                var dataTextBox = new TextBox();
                var dataTextBoxName = string.Format("{0}TextBox", processProperties[fld.Property]);
                dataTextBox.Name = dataTextBoxName;

                var propertyName = processProperties[fld.Property];
                var isExistsBackgroudColor = processProperties.Any(x => x.Key.Name == propertyName + Constants.FieldBackColorPostfix);

                dataTextBox.TextWrap = true;
                dataTextBox.Location = new PointU(new Unit(nextLeft, UnitType.Inch), new Unit(0, UnitType.Inch));
                dataTextBox.Size = uSize;
                dataTextBox.CanGrow = true;

                if (isExistsBackgroudColor)
                {
                    if (fieldValueMap.StartsWith("="))
                    {
                        fieldValueMap = fieldValueMap.Remove(0, 1);
                        fieldValueMap = string.Format("=GetValueWithBackgroundColor({0}, Fields.[{1}{2}])", fieldValueMap, processProperties[fld.Property], Constants.FieldBackColorPostfix);

                        EventHandler itemDataBoundHandler = (sender, args) =>
                            {
                                var textBox = sender as Telerik.Reporting.Processing.TextBox;
                                if (textBox == null)
                                {
                                    return;
                                }

                                var colorAsLong = ((KeyValuePair<object, long>)textBox.Value).Value;
                                if (colorAsLong != 0)
                                {
                                    var bytes = BitConverter.GetBytes(colorAsLong);
                                    if (bytes[3] == 0) bytes[3] = 255;
                                    var color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);

                                    ((Telerik.Reporting.Processing.ProcessingElement)sender).Style.BackgroundColor = color;
                                }

                                textBox.Value = ((KeyValuePair<object, long>)textBox.Value).Key;

                            };
                        dataTextBox.ItemDataBound += itemDataBoundHandler;

                        EventHandler dataTextBoxDisposedHandler = null;
                        dataTextBoxDisposedHandler = (sender, args) =>
                        {
                            dataTextBox.ItemDataBound -= itemDataBoundHandler;
                            dataTextBox.Disposed -= dataTextBoxDisposedHandler;
                        };
                        dataTextBox.Disposed += dataTextBoxDisposedHandler;
                    }
                }

                dataTextBox.Value = fieldValueMap;

                if (!reportDocument.FitToPage)
                {
                    dataTextBox.ItemDataBound += OnItemDataBound;

                    EventHandler dataTextBoxDisposedHandler = null;
                    dataTextBoxDisposedHandler = (sender, args) =>
                    {
                        dataTextBox.ItemDataBound -= OnItemDataBound;
                        dataTextBox.Disposed -= dataTextBoxDisposedHandler;
                    };
                    dataTextBox.Disposed += dataTextBoxDisposedHandler;
                }

                var pictureBox = new PictureBox { Value = fieldValueMap };
                pictureBox.Name = string.Format("{0}TextBox", processProperties[fld.Property]);
                pictureBox.Sizing = ImageSizeMode.ScaleProportional;

                if (!reportDocument.FitToPage)
                {
                    pictureBox.ItemDataBound += OnItemDataBound;

                    EventHandler pictureBoxDisposedHandler = null;
                    pictureBoxDisposedHandler = (sender, args) =>
                        {
                            pictureBox.ItemDataBound -= OnItemDataBound;
                            pictureBox.Disposed -= pictureBoxDisposedHandler;
                        };
                    pictureBox.Disposed += pictureBoxDisposedHandler;
                }

                nextLeft = nextLeft + ctrlSize;

                if (reportDocument.FitToPage)
                {
                    currentReport.Items["labelsGroupHeaderSection"].Items.Add(headerLabel);
                }
                else
                {
                    currentReport.Items["pageHeader"].Items.Add(headerLabel);
                }

                if (_fieldAttrDict[fld.Property].FieldEditor == "Image")
                {
                    currentReport.Items["detail"].Items["rowPanel"].Items.Add(pictureBox);
                }
                else
                {
                    currentReport.Items["detail"].Items["rowPanel"].Items.Add(dataTextBox);
                }

                _reportItemCounter.Add(processProperties[fld.Property], 0);

                if (reportDocument.FitToPage)
                {
                    _colDict.Add(currentReport.Items["labelsGroupHeaderSection"].Items.Count - 1, new[] { processProperties[fld.Property], headerLabel.Value });
                }
                else
                {
                    _colDict.Add(currentReport.Items["pageHeader"].Items.Count - 1, new[] { processProperties[fld.Property], headerLabel.Value });
                }

                if (reportDocument.FitToPage)
                {
                    fitToPageFooterLocationX = counter % FitToPageColumnCount == 0 ? 0 : fitToPageFooterLocationX;

                    if (_aggregateDict.Keys.All(x => x != fld.Property.Name))
                    {
                        var footerTextBox = new TextBox
                        {
                            Name = string.Format("{0}{1}FooterTextBox", fld.Property.Name, fldList.IndexOf(fld)),
                            Location = new PointU(new Unit(fitToPageFooterLocationX, UnitType.Inch), new Unit(0, UnitType.Inch)),
                            Size = new SizeU(new Unit(FitToPageColumnWidth, UnitType.Inch), new Unit(0.15, UnitType.Inch))
                        };

                        currentReport.Items["pageFooter"].Items.Add(footerTextBox);
                    }

                    //calculate server-side aggregates
                    var aggregateDefinitions = _aggregateDict.ToList()
                        .SelectMany(i => i.Value)
                        .Where(d => !AggregateHelper.IsPageAggregateType(d.SummaryType))
                        .ToList();

                    var queryCriteria = new AggregateDataSourceQueryCriteria
                    {
                        ProcessName = _processName,
                        FilterDefinition = GetFilterDefinition(currentReport)
                    };
                    var serverAggregateResults = AggregateProcessor.CalculateAggregates(aggregateDefinitions, queryCriteria);

                    foreach (var aggregateItem in _aggregateDict)
                    {
                        if (aggregateItem.Key != fld.Property.Name)
                        {
                            continue;
                        }

                        double fitToPageFooterLocationY = 0;

                        for (var i = 0; i < aggregateItem.Value.Count; i++)
                        {
                            var footerTextBox = new TextBox
                                {
                                    Name = string.Format("{0}{1}FooterTextBox", fld.Property.Name, aggregateItem.Value[i].SummaryType), // telerik recommends set unique names for all controls
                                    Size = new SizeU(new Unit(GetWidthFitToPage(fld.Property.Name, i), UnitType.Inch), new Unit(0.15, UnitType.Inch)),
                                    Location = new PointU(new Unit(fitToPageFooterLocationX, UnitType.Inch), new Unit(fitToPageFooterLocationY, UnitType.Inch))
                                };

                            if (AggregateHelper.IsPageAggregateType(aggregateItem.Value[i].SummaryType))
                            {
                                footerTextBox.Value = string.Format(@"='{0}: ' + AfterCalculateAggregates(PageExec('{1}TextBox', {2}(BeforeCalculateAggregates(Fields.[{1}], ""{2}"", ""{3}"", ""{4}"", ""{5}"", ""{6}""))), ""{2}"", ""{3}"", ""{4}"", ""{5}"", ""{6}"")",
                                        AggregateProcessor.GetAggregateFunctionShortName(aggregateItem.Value[i].SummaryType), aggregateItem.Key, aggregateItem.Value[i].SummaryType, aggregateItem.Value[i].CustomConverter, aggregateItem.Value[i].TargetType, aggregateItem.Value[i].TypeName, aggregateItem.Value[i].ConverterParameter);
                            }
                            else
                            {
                                var result = serverAggregateResults.FirstOrDefault(r => r.ColumnName == aggregateItem.Key && r.SummaryType == aggregateItem.Value[i].SummaryType);
                                footerTextBox.Value = string.Format("{0}: {1}", AggregateHelper.GetAttribute(aggregateItem.Value[i].SummaryType).ShortName, result != null ? result.Value : Constants.Empty);
                            }

                            if (aggregateItem.Value[i].SummaryType == SummaryTypes.Count)
                            {
                                footerTextBox.Bindings.Add(new Binding("Visible", string.Format(@"=IIf(PageExec(""{0}"", Count(Fields.{1})) = 0, False, True)", dataTextBoxName, fld.Property.Name)));
                            }

                            if (aggregateItem.Value[i].SummaryType == SummaryTypes.Min || aggregateItem.Value[i].SummaryType == SummaryTypes.Max)
                            {
                                if (fld.Property.PropertyType != typeof(bool) && fld.Property.PropertyType != typeof(bool?))//VRN-5079
                                {
                                    footerTextBox.Bindings.Add(new Binding("Visible", string.Format(@"=FooterTextBoxVisibilityWithValue(PageExec(""{0}"", Min(Fields.{1})))", dataTextBoxName, fld.Property.Name)));
                                }
                            }

                            fitToPageFooterLocationY += 0.15;
                            currentReport.Items["pageFooter"].Items.Add(footerTextBox);
                        }
                    }

                    fitToPageFooterLocationX += FitToPageColumnWidth;
                    counter++;
                }
            }

            if (reportDocument.FitToPage)
            {
                var max = _aggregateDict.Count == 0 ? 0 : _aggregateDict.Max(x => x.Value.Count);
                if (max != 0)
                {
                    ((PageFooterSection) currentReport.Items["pageFooter"]).Height = new Unit(max*0.15 + 0.2, UnitType.Inch);
                }

                currentReport.Items["pageFooter"].Items["currentTimeTextBox"].Visible = false;
                currentReport.Items["pageFooter"].Items["pageInfoTextBox"].Visible = false;
            }

            _indentOffset = _groups.Count > 0 ? (_groups.Count - 1) * 0.15 : 0;

            //AddGroupLevelLines(currentReport.Items["detail"].Items["rowPanel"].Items);
        }
        private void CleanupModel(Dictionary<string, object> model)
        {
            foreach (var entry in model.ToList())
            {
                var value = entry.Value;
                var list = value as ArrayList;
                if (list != null)
                {
                    var objs = list.OfType<object>().ToList();
                    model[entry.Key] = objs;
                    value = objs;

                    //continue;
                }

                var enumerable = value as IEnumerable<object>;
                if (enumerable != null)
                {
                    foreach (var item in enumerable)
                    {
                        var dItem = item as Dictionary<string, object>;
                        if (dItem != null)
                            CleanupModel(dItem);
                    }
                }

                var dict = value as Dictionary<string, object>;
                if (dict != null)
                    CleanupModel(dict);
            }
        }
        Document CreateUpdateDocument( SetItemDocumentParameters p )
        {
            var doc = new Document();

            var map = new Dictionary<string, object>
                          {
                              {"$set", p.Set},
                              {"$inc", p.Inc},
                              {"$pop", p.Pop},
                              {"$pull", p.Pull},
                              {"$pullAll", p.PullAll},
                              {"$push", p.Push},
                              {"$pushAll", p.PushAll},
                              {"$rename", p.Rename},
                              {"$unset", p.Unset},
                              {"$bit", p.Bit}
                          };

            map.ToList().ForEach( pair=> AppendUpdateAtomDocument(doc, pair.Key, pair.Value ) );

            return doc;
        }
示例#10
0
        public static void pngToTgaRectNesting(string path, string filter = "*.png", int deep = 0, bool isPreset = false)
        {
            Dictionary<string, RectNode> mapRectNode = new Dictionary<string, RectNode>();
            string projPath = Project.Setting.s_projPath;
            int presetCount = 0;
            int fileCount = 0;

            printString("========开始打包========\r\n" + "路径:" + path + "\r\n");
            fileCount = addFileToArr(path, filter, mapRectNode);

            if (fileCount == 0)
            {
                return;
            }
            if (isPreset)
            {
                DirectoryInfo di = new DirectoryInfo(projPath + "\\images\\");
                DirectoryInfo[] arrPreDri = di.GetDirectories("*_preset*");
                DirectoryInfo[] arrAllDri = di.GetDirectories("*");

                if (arrPreDri.Count() != arrAllDri.Count())
                {
                    MessageBox.Show("存在自定义图片分包,无法进行预设打包。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                printString("模式:预设打包\r\n");
                presetCount = getRectNestingByPreset(mapRectNode, conf_maxSizeOfPreset, conf_maxSizeOfPreset);
            }
            else
            {
                bool isFirst = true;
                int maxPow = 0;

                //得到预期的2的整数次幂
                maxPow = getMaxPow(mapRectNode.Values.ToList());
                s_fileCount = mapRectNode.Count;

                printString("模式:开发打包\r\n");
                do
                {
                    if (isFirst)
                    {
                        isFirst = false;
                        printString("文件数量:" + mapRectNode.Count + "\r\ntga图片预计尺寸:" + Math.Pow(2, maxPow) + "\r\n");
                    }
                    else
                    {
                        maxPow++;
                        printString("本次尝试失败,尝试下一尺寸...\r\ntga图片预计尺寸:" + Math.Pow(2, maxPow) + "\r\n");
                    }
                } while (!getRectNesting(mapRectNode, (int)Math.Pow(2, maxPow), (int)Math.Pow(2, maxPow)));
            }

            if (path.Last() == '\\')
            {
                path = path.Remove(path.Length - 1);
                if (path.Last() == '\\')
                {
                    path = path.Remove(path.Length - 1);
                }
            }

            if (isPreset && presetCount != 0)
            {
                DirectoryInfo di = new DirectoryInfo(projPath + "\\images\\");
                DirectoryInfo[] arrDirInfo = di.GetDirectories("*_preset*");
                XmlDocument docRes = new XmlDocument();
                XmlElement xeResRoot = docRes.CreateElement("BoloUI");

                foreach(DirectoryInfo dri in arrDirInfo)
                {
                    Directory.Delete(dri.FullName, true);
                }

                XmlDocument[] arrDocGrid = new XmlDocument[presetCount];

                for (int i = 0; i < presetCount; i++)
                {
                    arrDocGrid[i] = new XmlDocument();
                    XmlElement xeRoot = arrDocGrid[i].CreateElement("UIImageResource");
                    arrDocGrid[i].AppendChild(xeRoot);
                    Directory.CreateDirectory(projPath + "\\images\\_preset" + (i + 1).ToString("00"));

                    XmlElement xeRes = docRes.CreateElement("resource");

                    xeRes.SetAttribute("name", "_preset" + (i + 1).ToString("00"));
                    xeResRoot.AppendChild(xeRes);
                }

                foreach (KeyValuePair<string, RectNode> pairRn in mapRectNode.ToList())
                {
                    XmlDocument docGrid = arrDocGrid[pairRn.Value.m_packCount];
                    XmlElement xe = docGrid.CreateElement("Image");
                    string name = pairRn.Key.Remove(pairRn.Key.LastIndexOf("."));

                    xe.SetAttribute("Name", name);
                    //因为差值什么的显示问题,所以要-2和+1。
                    xe.SetAttribute("Width", (pairRn.Value.m_rect.Width - 2).ToString());
                    xe.SetAttribute("Height", (pairRn.Value.m_rect.Height - 2).ToString());
                    xe.SetAttribute("X", (pairRn.Value.m_rect.X + 1).ToString());
                    xe.SetAttribute("Y", (pairRn.Value.m_rect.Y + 1).ToString());
                    docGrid.DocumentElement.AppendChild(xe);
                    File.Copy(path + "\\" + pairRn.Key, projPath + "\\images\\_preset" + (pairRn.Value.m_packCount + 1).ToString("00") + "\\" + pairRn.Key, true);
                }

                for(int i = 0; i < presetCount; i++)
                {
                    string xmlPath = projPath + "\\images\\_preset" + (i + 1).ToString("00") + ".xml";

                    arrDocGrid[i].Save(xmlPath);
                    //MainWindow.s_pW.openFileByPath(xmlPath);
                    PackImage.refreshImagePack(xmlPath);
                }

                docRes.AppendChild(xeResRoot);
                docRes.Save(projPath + "\\images\\resource.xml");
            }
            else
            {
                string fileName = System.IO.Path.GetFileName(path);
                XmlDocument docGrid = new XmlDocument();
                XmlElement xeRoot = docGrid.CreateElement("UIImageResource");

                docGrid.AppendChild(xeRoot);
                foreach (KeyValuePair<string, RectNode> pairRn in mapRectNode.ToList())
                {
                    XmlElement xe = docGrid.CreateElement("Image");
                    string name = pairRn.Key.Remove(pairRn.Key.LastIndexOf("."));

                    xe.SetAttribute("Name", name);
                    //因为差值什么的显示问题,所以要-2和+1。
                    xe.SetAttribute("Width", (pairRn.Value.m_rect.Width - 2).ToString());
                    xe.SetAttribute("Height", (pairRn.Value.m_rect.Height - 2).ToString());
                    xe.SetAttribute("X", (pairRn.Value.m_rect.X + 1).ToString());
                    xe.SetAttribute("Y", (pairRn.Value.m_rect.Y + 1).ToString());
                    xeRoot.AppendChild(xe);
                }
                string xmlPath = projPath + "\\images\\" + fileName + ".xml";

                docGrid.Save(xmlPath);
                //MainWindow.s_pW.openFileByPath(xmlPath);
                PackImage.refreshImagePack(xmlPath);
            }
        }
示例#11
0
        public void ConstructSortedDictionary(DataBase db)
        {
            var sortedDistDict = new Dictionary<PointPair, float>();
            for (int i=0; i<NumOfRows; ++i)
            {
                for (int j=0; j<i; ++j)
                {
                    if (i != j)
                        sortedDistDict.Add(new PointPair(i, j), Point.Distance(db[i], db[j]));
                }
            }

            sortedDistList = sortedDistDict.ToList();
            sortedDistList.Sort((firstPair, nextPair) =>
            {
                return firstPair.Value.CompareTo(nextPair.Value);
            });
        }
        /// <summary>
        /// Generates a full list of headers from a list of applications.
        /// This includes the base list of headers for application metadata, as well
        /// as the combination of all fields in all applications (in the event that the form
        /// definition changes).
        /// </summary>
        /// <param name="applications">List of applications.</param>
        /// <returns>A key-value pair of headers and sub headers.</returns>
        public List<KeyValuePair<string, List<string>>> GenerateHeaders(IEnumerable<Application> applications)
        {
            if (applications == null || !applications.Any())
            {
                return null;
            }

            Dictionary<string, Dictionary<string, object>> headers = new Dictionary<string, Dictionary<string, object>>();
            foreach (var prop in applications.First().GetType().GetProperties().Where(prop => prop.Name != "ApplicationData").Select(prop => prop.Name))
            {
                headers.Add(prop, null);
                if (this.userByTypes.Contains(prop))
                {
                    headers.Add(prop + "DisplayName", null);
                }
            }

            foreach (var app in applications)
            {
                if (app.ApplicationData != null)
                {
                    this.ExtractHeaders(app.ApplicationData, headers);
                }
            }

            var finalHeaders = headers.ToList().Select(header => new KeyValuePair<string, List<string>>(header.Key, header.Value != null ? header.Value.Keys.ToList() : null)).ToList();
            return finalHeaders;
        }
示例#13
0
 private void setLengths(List<Artifact> allArtifacts)
 {
     Dictionary<Artifact, int> descLengths = new Dictionary<Artifact, int>();
     foreach (Artifact a in allArtifacts)
     {
         int len = a.Function.Length + a.CanadianSignificance.Length + a.TechSignificance.Length;
         if(len > 0)
             descLengths.Add(a, len);
     }
     descLengths = descLengths.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
     //descLengths = descLengths.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
     descLengthsList = descLengths.ToList();
 }
示例#14
0
        /// <summary>
        /// Calculates the khipu auth header value
        /// </summary>
        /// <param name="path">Request path.</param>
        /// <param name="method">Request method.</param>
        /// <param name="queryParams">Query parameters.</param>
        /// <param name="formParams">Form parameters.</param>
        public String AuthHeader(String path, RestSharp.Method method, Dictionary<String, String> queryParams, Dictionary<String, String> formParams) {
            Dictionary<String, String> ps = new Dictionary<String, String>();
            queryParams.ToList().ForEach(x => ps[x.Key] = x.Value);
            formParams.ToList().ForEach(x => ps[x.Key] = x.Value);

            List<String> keys = new List<String>(ps.Keys.OrderBy(q => q));
            String toSign = method + "&" + Uri.EscapeDataString(BasePath + path);

            foreach(var key in keys)
                toSign += "&" + Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(ps[key]);

            String hmac = HmacSha256(Configuration.Secret, toSign);
            return Configuration.ReceiverId + ":" + hmac;
        }
        public void GeneratePLTS()
        {
            int i, j, m, k;
            uint eidcount = 10;
            uint sidbegin;
            uint sid;
            uint layernum;
            uint current;
            uint Allsnum = 0;
            HashSet<uint> tmpeset = new HashSet<uint>();

    
            Queue<uint> generatelts = new Queue<uint>();
            Dictionary<uint, uint> tmpdic = new Dictionary<uint,uint>();
            List<KeyValuePair<uint,uint>> tmplist;
            
            Random rd = new Random((int)System.DateTime.Today.Ticks);
            
            generatelts.Enqueue(1);

            string path1 = "./test/Lts1.txt";
            string path2 = "./test/Lts2.txt";
            string path3 = "./test/evt.txt";
            string path4 = "./test/allsnum.txt";

            StreamWriter [] sw = new StreamWriter[2];
            sw[0] = new StreamWriter(path1, true);
            sw[1] = new StreamWriter(path2, true);

            StreamWriter sw2 = new StreamWriter(path3, true);
            StreamWriter sw3 = new StreamWriter(path4, true);

            for (i = 0; i < LTSnum; i++)
            {
                Allsnum++;
                layernum = (uint)(Math.Pow(2, beginsynlayer)*2 - 1);
                for (j = 0; j < layernum; j++)
                {
                    current = generatelts.Dequeue();
                    
                    //layernum = layernum * 2;
                    sidbegin = current * 2;
                    for (m = 0; m < 2; m++)
                    {
                        sid = sidbegin + (uint)m;
                        generatelts.Enqueue(sid);
                        Allsnum++;
                        if (i == 0)
                        {
                            eidcount = (uint)rd.Next(11, 31);

                            if(!tmpeset.Contains(eidcount))
                            {
                                  tmpeset.Add(eidcount);
                                  if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                  //sw[i].Write(eidcount);
                            }
                            else
                            {
                                while (tmpeset.Contains(eidcount))
                                {
                                    eidcount = (uint)rd.Next(11, 31);
                                }
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }

                        }
                        else
                        {
                            eidcount = (uint)rd.Next(31, 51);

                            if (!tmpeset.Contains(eidcount))
                            {
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }
                            else
                            {
                                while (tmpeset.Contains(eidcount))
                                {
                                    eidcount = (uint)rd.Next(11, 31);
                                }
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }
                        }
                       
                        //sw[i].Write(" ");
                        tmpdic.Add(eidcount,sid);
                   
                       
                        
                    }
                    tmpdic = tmpdic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                    tmplist = tmpdic.ToList();
                    for(k = 0; k < tmplist.Count; k++){
                        sw[i].Write(tmplist[k].Key);
                        sw[i].Write(" ");
                        sw[i].Write(tmplist[k].Value);
                        sw[i].Write(" ");
                    }
                    
                    tmpeset.Clear();
                    tmpdic.Clear();
                    sw[i].Write("\n");
                }

                layernum = (uint)(Math.Pow(2, beginsynlayer + 1));
                layernum = (uint)((layernum + layernum*4*(totallayer-beginsynlayer-1))*(totallayer-beginsynlayer))/2; 
                for (k = 0; k < layernum; k++ )
                {
                    current = generatelts.Dequeue();
                    sidbegin = current * 4;
                    if (rd.Next(0, 2) == 0)
                    {
                        for (m = 0; m < 4; m++)
                        {
                            sid = sidbegin + (uint)m;
                            generatelts.Enqueue(sid);
                            Allsnum++;
                            if (i == 0)
                            {
                                eidcount = (uint)rd.Next(11, 31);

                                if (!tmpeset.Contains(eidcount))
                                {
                                    tmpeset.Add(eidcount);
                                    if(!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                    //sw[i].Write(eidcount);
                                }
                                else
                                {
                                    while (tmpeset.Contains(eidcount))
                                    {
                                        eidcount = (uint)rd.Next(11, 31);
                                    }
                                    tmpeset.Add(eidcount);
                                    if (!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                    //sw[i].Write(eidcount);
                                }

                            }
                            else
                            {
                                eidcount = (uint)rd.Next(31, 51);

                                if (!tmpeset.Contains(eidcount))
                                {
                                    tmpeset.Add(eidcount);
                                    if (!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                   // sw[i].Write(eidcount);
                                }
                                else
                                {
                                    while (tmpeset.Contains(eidcount))
                                    {
                                        eidcount = (uint)rd.Next(31, 51);
                                    }
                                    tmpeset.Add(eidcount);
                                    if (!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                    //sw[i].Write(eidcount);
                                }
                            }
                            
                            tmpdic.Add(eidcount, sid);
                            
                            //sw[i].Write(" ");
                            //sw[i].Write(sid);
                           
                        }
                        tmpdic = tmpdic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                        tmplist = tmpdic.ToList();
                        for(m = 0; m < tmplist.Count; m++){
                            sw[i].Write(tmplist[m].Key);
                            sw[i].Write(" ");
                            sw[i].Write(tmplist[m].Value);
                            sw[i].Write(" ");
                        }
                    
                        tmpeset.Clear();
                        tmpdic.Clear();
                        sw[i].Write("\n");
                    }
                    else
                    {
                        sid = sidbegin;
                        generatelts.Enqueue(sid);
                        Allsnum++;
                        if(i == 0)
                            eidcount = (uint)rd.Next(11, 31);
                        else
                            eidcount = (uint)rd.Next(31, 51);
                        sw[i].Write(eidcount);
                        sw[i].Write(" ");
                        sw[i].Write(sid);
                       
                        sw[i].Write(" 0 1 ");

                        for (m = 1; m < 4; m++)
                        {
                            sid = sidbegin + (uint)m;
                            generatelts.Enqueue(sid);
                            Allsnum++;

                            eidcount = (uint)rd.Next(0, 11);
                            if (!tmpeset.Contains(eidcount))
                            {
                                //sw[i].Write(eidcount);
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                            }
                            else
                            {
                                while (tmpeset.Contains(eidcount))
                                {
                                    eidcount = (uint)rd.Next(11, 31);
                                }
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }
                            tmpdic.Add(eidcount, sid);
                            
                            //sw[i].Write(" ");
                            //sw[i].Write(sid);
                        }
                        tmpdic = tmpdic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                        tmplist = tmpdic.ToList();
                        for(m = 0; m < tmplist.Count; m++){
                            sw[i].Write(tmplist[m].Key);
                            sw[i].Write(" ");
                            sw[i].Write(tmplist[m].Value);
                            sw[i].Write(" ");
                        }
                    
                        tmpeset.Clear();
                        tmpdic.Clear();
                        sw[i].Write("\n");
                    }
                }
                while (generatelts.Count > 0)
                {
                    sw[i].Write("\n");
                    generatelts.Dequeue();
                }
                sw[i].Flush();
                sw[i].Close();
                generatelts.Clear();
                generatelts.Enqueue(1);
            }
            

            for (k = 0; k < this.eventlist.Count; k++)
            {
                sw2.Write(this.eventlist[k]);
                sw2.Write(" ");
            }
            sw2.Flush();
            sw2.Close();

            sw3.Write(Allsnum);
            sw3.Write("\n");
            sw3.Flush();
            sw3.Close();
        }
示例#16
0
        static void SortDictionary()
        {
            Dictionary<string, string> diction = new Dictionary<string,string>();
            diction.Add("3", "three");
            diction.Add("1", "one");
            diction.Add("5", "five");
            diction.Add("2", "two");

            List<KeyValuePair<string, string>> sortList = diction.ToList();

            var sorted = from entry in diction orderby entry.Value ascending select entry;
            Console.ReadLine();
        }
 public Dictionary<string,char>ReversePolarity(Dictionary<char,string>collection)
 {
     var temporaryCollection = new Dictionary<string, char>();
     collection.ToList().ForEach(p =>
     {
         temporaryCollection.Add(p.Value, p.Key);
     });
     return temporaryCollection;
 }
		/// <summary>
		/// Perform a read against the WSAPI operation based
		/// on the data in the specified request
		/// </summary>
		/// <param name="request">The request configuration</param>
		/// <returns>A <see cref="DynamicJsonObject"/> with the response from Rally.</returns>
		/// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception>
		/// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception>
		/// <example>
		/// <code language="C#">
		/// // Build request
		/// Request request = new Request("defect");
		/// request.Fetch = new List&lt;string&gt;() { "Name", "Description", "FormattedID" };
		/// 
		/// request.Query = new Query("Name", Query.Operator.Equals, "My Defect").And(new Query("State", Query.Operator.Equals, "Submitted"));
		/// 
		/// // Make request and process results 
		/// QueryResult queryResult = restApi.Query(request);
		/// foreach (var result in queryResult.Results)
		/// {
		/// 	string itemName = result["Name"];
		/// }
		/// </code>
		/// </example>
		public QueryResult Query(Request request)
		{
			if (ConnectionInfo == null)
				throw new InvalidOperationException(AUTH_ERROR);

			DynamicJsonObject response;
			if (IsWsapi2)
				response = DoGetAsPost(request);
			else
				response = DoGet(GetFullyQualifiedUri(request.RequestUrl));

			var result = new QueryResult(response["QueryResult"]);
			int maxResultsAllowed = Math.Min(request.Limit, result.TotalResultCount);
			int alreadyDownloadedItems = request.Start - 1 + request.PageSize;
			var subsequentQueries = new List<Request>();

			while ((maxResultsAllowed - alreadyDownloadedItems) > 0)
			{
				Request newRequest = request.Clone();
				newRequest.Start = request.Start + request.PageSize;
				request.Start += request.PageSize;

				//makes sure partial pages are downloaded. IE limit 201
				newRequest.PageSize = Math.Min((maxResultsAllowed - alreadyDownloadedItems), request.PageSize);
				subsequentQueries.Add(newRequest);

				// Start has 1 for its lowest value.
				alreadyDownloadedItems = request.Start - 1 + request.PageSize;
			}

			Trace.TraceInformation("The number of threaded requests is : {0}", subsequentQueries.Count);

			var resultDictionary = new Dictionary<int, QueryResult>();
			Parallel.ForEach(subsequentQueries, new ParallelOptions { MaxDegreeOfParallelism = MAX_THREADS_ALLOWED }, request1 =>
			{
				var response1 = DoGet(GetFullyQualifiedUri(request1.RequestUrl));
				lock (resultDictionary)
				{
					resultDictionary[request1.Start] = new QueryResult(response1["QueryResult"]);
				}
			});

			var allResults = new List<object>(result.Results);
			foreach (var sortedResult in resultDictionary.ToList()
					.OrderBy(p => p.Key))
			{
				result.Errors.AddRange(sortedResult.Value.Errors);
				result.Warnings.AddRange(sortedResult.Value.Warnings);
				allResults.AddRange(sortedResult.Value.Results);
			}

			result.Results = allResults;
			return result;
		}
 public Huffman(Dictionary<char, string> codeCombinations)
 {
     codeCombinations.ToList().ForEach(p => CodeCombinations.Add(p.Key, p.Value));
 }