示例#1
0
        /// <summary>Creates the combat order.</summary>
        public void CreateCombatOrder()
        {
            Die combatDie = DiceService.Instance.GetDie(6);
            var bin = new Dictionary<string, int>();

            foreach (Thing combatant in this.CombatSession.Combatants)
            {
                // Find out who goes first, then add them to the queue.
                // Rinse and repeat, until all have been placed in the
                // correct order.

                // Do initiative roll.
                int combatantInitiative = DoInititiveRoll(combatDie, combatant);

                if (bin.ContainsValue(combatantInitiative))
                {
                    combatantInitiative = DoInititiveRoll(combatDie, combatant);
                }

                bin.Add(combatant.Name, combatantInitiative);
            }

            // Sort the bin dictionary
            var sortedBin = (from entry in bin orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);

            foreach (var ent in sortedBin)
            {
                ////Thing combatant = this.CombatSession.Combatants.Values
            }
        }
示例#2
0
 public TableResponse CreateTable(string databaseName, string tableName, Dictionary<string,bool> columnData, List<string> columnType)
 {
   if (databaseName == "database1" && tableName == "table1" && columnData.ContainsValue(false) && columnData.ContainsKey("key1") && columnType[0] == "VARCHAR(255)")
   {
     return new TableResponse(true, "success", "12");
   }
   else
     return new TableResponse(false, "failure", "13"); 
 }
 public void ZE_ValueExists()
 {
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     dictionary["one"] = "uno";
     Assert.AreEqual(FILL_ME_IN, dictionary.ContainsValue("uno"));
     Assert.AreEqual(FILL_ME_IN, dictionary.ContainsValue("dos"));
 }
示例#4
0
        /// <summary>
        /// 找模板页,加入
        /// 
        /// 搬运内容:
        /// 01、L2      02    12    证书编号
        /// 02、B4 -D4  04    02-04 送校单位
        /// 03、F4      04    06    联系地址
        /// 04、B5      05    02    仪器名称
        /// 05、F5      05    06    型号
        /// 06、H5      05    08    编号
        /// 07、J5      05    10    厂家
        /// 08、L5      05    12    电离室号
        /// 09、K7      07    11    温度
        /// 10、M7      07    13    湿度
        /// 11、J8      08    10    气压
        /// 12、D12-M12 12    04-13 量程
        /// 13、D18     18    04    数据
        /// 14、F18     18    06    数据
        /// 15、H18     18    08    数据
        /// 16、J18     18    10    数据
        /// 17、L18     18    13    数据
        /// 18、D19     19    04    数据
        /// 19、F19     19    06    数据
        /// 20、H19     19    08    数据
        /// 21、J19     19    10    数据
        /// 22、L19     19    12    数据
        /// 23、D20     20    04    数据
        /// 24、F20     20    06    数据
        /// 25、H20     20    08    数据
        /// 26、J20     20    10    数据
        /// 27、L20     20    12    数据
        /// 28、G31     31    07    记录者签名
        /// 29、I31     31    09    校对者签名
        /// 30、K31     31    11    日期
        /// </summary>
        /// <param name="sourceEx"></param>
        /// <param name="sourceIndex"></param>
        /// <param name="destiEx"></param>
        public void CopyData(ExcelUtility sourceEx, int sourceIndex, ExcelUtility destiEx, int pattern, string certIdori, bool needFix, bool shouldFix, int startDestiRowIndex, out int newSheetIndex, out bool success)
        {
            bool success1;
            bool noNeed = false;
            int templateIndex = -1;
            int startSourceRowIndex = -1;
            int destiIndex = -1;
            MSExcel.Range rr = null;
            MSExcel.Worksheet ws1 = null;

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

            string temp;
            string text = "";
            string certId = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, "L2", out success1);
            if (!success1)
            {
                AddException(@"无法提取到证书编号", true);
                success = false;
                newSheetIndex = -1;
                return;
            }

            foreach (MSExcel.Worksheet item in destiEx.ExcelWorkbook.Sheets)
            {
                if (item.Name == "统计")
                {
                    destiIndex = item.Index;
                }
                else if (item.Name == @"标准模板")
                {
                    //找到模板页
                    templateIndex = item.Index;
                }
                else if (item.Name.Contains(@"标准模板"))
                {
                    AddDataError(@"第" + item.Index + "页发现多余的标准模板", true);
                }
                else
                {
                    temp = destiEx.GetText(destiEx.ExcelWorkbook, item.Index, "L2", out success1).Trim();
                    if (temp.StartsWith(@"20") && (temp.Length == 9 || temp.Length == 10))
                    {
                        //找到有证书编号的数据页
                        if (item.Name == certId)
                        {
                            if (MessageBox.Show("在历史数据记录的Excel中已发现了证书编号为" + certId + "的页面,是否覆盖?选择是,进行覆盖。选择否,停止对本Excel的处理", "是否覆盖", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                            {
                                ws1 = item;
                            }
                            else
                            {
                                AddException(@"要合并入的数据已存在于第" + item.Index + "页", true);
                                newSheetIndex = -1;
                                success = false;
                                return;
                            }
                        }
                        else
                        {
                            exSheets.Add(item.Index, temp);
                        }
                    }
                }
            }

            if (!noNeed)
            {
                if (templateIndex == -1)
                {
                    AddException(@"找不到数据的标准模板", true);
                    success = false;
                    newSheetIndex = -1;
                    return;
                }
                else
                {
                    //有模板页。没找到参考证书编号页
                    if (ws1 == null)
                    {
                        ws1 = (MSExcel.Worksheet)destiEx.ExcelWorkbook.Sheets[templateIndex];
                        if (exSheets.Count > 0)
                        {
                            //有有效数据页
                            if (destiIndex < 1)
                            {
                                //没有统计页,把有效数据页里最前面的序号赋给destiIndex
                                foreach (int item in exSheets.Keys)
                                {
                                    if (destiIndex < 1 || destiIndex > item)
                                    {
                                        destiIndex = item;
                                    }
                                }
                            }
                            foreach (int item in exSheets.Keys)
                            {
                                if (DataUtility.DataUtility.LargerThan(certId, exSheets[item]) && destiIndex < item)
                                {
                                    //在所有比参考编号小的页面里,挑一个最靠后的序号给destiIndex
                                    destiIndex = item;
                                }
                            }
                            //在destiIndex右侧复制模板页
                            ws1.Copy(Type.Missing, destiEx.ExcelWorkbook.Sheets[destiIndex]);
                            //把新复制的模板页赋给ws1
                            ws1 = (MSExcel.Worksheet)destiEx.ExcelWorkbook.Sheets[destiIndex + 1];
                        }
                        else
                        {
                            //没有有效数据页时,在模板页左侧复制模板页
                            ws1.Copy(destiEx.ExcelWorkbook.Sheets[templateIndex], Type.Missing);
                            //把原来模板页,现在的模板复制页的位置给了ws1
                            ws1 = (MSExcel.Worksheet)destiEx.ExcelWorkbook.Sheets[templateIndex];
                        }
                        if (!ws1.Name.Contains(@"标准模板"))
                        {
                            AddException(@"标准模板复制出错", true);
                            success = false;
                            newSheetIndex = -1;
                            return;
                        }
                        if (!exSheets.ContainsValue(certId))
                        {
                            ws1.Name = certId;
                        }
                    }

                    newSheetIndex = ws1.Index;

                    //确定原始数据的数据行
                    for (int i = 15; i < 22; i++)
                    {
                        text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, i, 3, out success1).Trim();
                        if (text == "1")
                        {
                            text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, i + 1, 3, out success1).Trim();
                            if (text == "2")
                            {
                                text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, i + 2, 3, out success1).Trim();
                                if (text == "3")
                                {
                                    startSourceRowIndex = i;
                                    break;
                                }
                            }
                        }
                    }

                    if (startSourceRowIndex == -1)
                    {
                        AddException(@"找不到原始数据所在的行", true);
                        success = false;
                        newSheetIndex = -1;
                        return;
                    }

                    //拷贝数据
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 2, 12, "@", out success1);
                    if (!success1) AddException(@"《证书编号》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 4, 1, 4, 2, new string[] { @"送校单位:", @"单位名称:" }, "@", out success1);
                    if (!success1) AddException(@"《送校单位》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 4, 5, 4, 6, @"联系地址:", "@", out success1);
                    //if (!success1) AddException(@"《联系地址》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 5, 1, 5, 2, @"仪器名称:", "@", out success1);
                    if (!success1) AddException(@"《仪器名称》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 5, 5, 5, 6, @"型号:", "@", out success1);
                    if (!success1) AddException(@"《型号》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 5, 7, 5, 8, new string[] { @"主机编号:", @"编号:" }, "@", out success1);
                    if (!success1) AddException(@"《主机编号》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 5, 9, 5, 10, @"厂家:", "@", out success1);
                    if (!success1) AddException(@"《厂家》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 5, 11, 5, 12, new string[] { @"探测器编号:", "电离室号:", "探测器号:" }, "@", out success1);
                    if (!success1) AddException(@"《探测器编号》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 31, 7, "", out success1);
                    //if (!success1) AddException(@"《记录者》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 31, 9, "", out success1);
                    //if (!success1) AddException(@"《校对者》数据复制错误", true);
                    CopyDate(sourceEx, sourceIndex, destiEx, ws1.Index, out success1);

                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 7, 11, "0.000", out success1);
                    if (needFix && !success1) AddException(@"《温度》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 7, 13, "0.0%", out success1);
                    if (needFix && !success1) AddException(@"《湿度》数据复制错误", true);
                    CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 8, 10, "", out success1);
                    if (needFix && !success1) AddException(@"《气压》数据复制错误", true);

                    rr = destiEx.GetRange(destiEx.ExcelWorkbook, ws1.Index, "M8", out success1);
                    if (needFix)
                    {
                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 8, 13, "修正", out success1);
                    }
                    else
                    {
                        //电离室->半导体
                        rr = destiEx.GetRange(destiEx.ExcelWorkbook, ws1.Index, "L8", out success1);
                        rr.FormulaLocal = "";
                        rr.Formula = "";
                        rr.FormulaArray = "";
                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 8, 12, "1.000000", "@", out success1);
                        if (shouldFix)
                        {
                            destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 8, 13, "自修正", out success1);
                        }
                        else
                        {
                            destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 8, 13, "不修正", out success1);
                        }
                    }

                    ArrayList dataStructList = new ArrayList();
                    DataStruct dataStruct;
                    int standardRowIndex = -1;
                    string keyword = "标准";
                    switch (pattern)
                    {
                        case 2:
                            keyword = "滤片";
                            break;
                    }
                    for (int p = 13; p < 18; p++)
                    {
                        text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, p, 1, out success1).Trim() + sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, p, 2, out success1).Trim() + sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, p, 3, out success1).Trim();
                        if (text.ToLower().Contains(keyword))
                        {
                            standardRowIndex = p;
                            break;
                        }
                    }

                    switch (pattern)
                    {
                        case 0:
                            //Dose
                            CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 27, 13, "@", out success1);
                            CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 12, 4, "", out success1);
                            if (!success1) AddException(@"《量程》数据复制错误", true);

                            text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 4, out success1).Trim();
                            dataStructList.Add(CopyThreeDoseData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 4, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeDoseData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 6, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeDoseData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 8, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeDoseData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 10, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeDoseData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 12, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));

                            text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 12, out success1).Trim();
                            if (text.StartsWith("单位"))
                            {
                                CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 12, 13, "", out success1);
                                if (!success1) AddException(@"《单位》数据复制错误", true);
                            }
                            else
                            {
                                dataStruct = DataStruct.CalDataRange(dataStructList, sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 4, out success1).Trim(), pattern, out success);
                                switch (dataStruct.DataRanges)
                                {
                                    case DataRange.cGy:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "cGy", out success1);
                                        break;
                                    case DataRange.mGy:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "mGy", out success1);
                                        break;
                                    case DataRange.mR:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "mR", out success1);
                                        break;
                                    case DataRange.R:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "R", out success1);
                                        break;
                                    case DataRange.uGy:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "μGy", out success1);
                                        break;
                                    case DataRange.Unknown:
                                        AddException("无法判断数据单位", true);
                                        break;
                                }
                                switch (dataStruct.Distance)
                                {
                                    case Distance.d1:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 6, 13, "1.0m", out success1);
                                        break;
                                    case Distance.d1_5:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 6, 13, "1.5m", out success1);
                                        break;
                                    case Distance.Unknown:
                                        AddException("无法获取标准值,判断测试距离", true);
                                        break;
                                }
                            }

                            break;
                        case 1:
                            //CT
                            CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 27, 13, "@", out success1);
                            CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 12, 4, "", out success1);
                            if (!success1) AddException(@"《量程》数据复制错误", true);

                            text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 4, out success1).Trim();
                            dataStructList.Add(CopyThreeCTData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 4, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeCTData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 6, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeCTData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 8, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeCTData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 10, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));
                            dataStructList.Add(CopyThreeCTData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 12, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1));

                            text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 12, out success1).Trim();
                            if (text.StartsWith("单位"))
                            {
                                CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 12, 13, "", out success1);
                                if (!success1) AddException(@"《单位》数据复制错误", true);
                            }
                            else
                            {
                                dataStruct = DataStruct.CalDataRange(dataStructList, sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 4, out success1).Trim(), pattern, out success);
                                switch (dataStruct.DataRanges)
                                {
                                    case DataRange.mGycm:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "mGycm", out success1);
                                        break;
                                    case DataRange.mGy:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "mGy", out success1);
                                        break;
                                    case DataRange.cGy:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "cGy", out success1);
                                        break;
                                    case DataRange.mR:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "mR", out success1);
                                        break;
                                    case DataRange.R:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "R", out success1);
                                        break;
                                    case DataRange.uGy:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "μGy", out success1);
                                        break;
                                    case DataRange.cGycm:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "cGycm", out success1);
                                        break;
                                    case DataRange.Rcm:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 12, 13, "Rcm", out success1);
                                        break;
                                    case DataRange.Unknown:
                                        AddException("无法判断数据单位", true);
                                        break;
                                }
                                switch (dataStruct.Distance)
                                {
                                    case Distance.d1:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 6, 13, "1.0m", out success1);
                                        break;
                                    case Distance.d1_5:
                                        destiEx.WriteValue(destiEx.ExcelWorkbook, ws1.Index, 6, 13, "1.5m", out success1);
                                        break;
                                    case Distance.Unknown:
                                        AddException("无法获取标准值,判断测试距离", true);
                                        break;
                                }
                            }
                            //CopyCTData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, startDestiRowIndex, "", out success1);
                            break;
                        case 2:
                            //KV
                            CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 28, 13, "@", out success1);
                            //if (!success1) AddException(@"《备注》数据复制错误", true);
                            CopyOneData(sourceEx, sourceIndex, destiEx, ws1.Index, 12, 4, @"/", "", out success1);
                            if (!success1) AddException(@"《量程》数据复制错误", true);

                            text = sourceEx.GetText(sourceEx.ExcelWorkbook, sourceIndex, 12, 4, out success1).Trim();
                            CopyThreeKVData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 4, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1);
                            CopyThreeKVData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 6, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1);
                            CopyThreeKVData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 8, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1);
                            CopyThreeKVData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 10, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1);
                            CopyThreeKVData(sourceEx, sourceIndex, destiEx, ws1.Index, startSourceRowIndex, 12, startDestiRowIndex, "", standardRowIndex, text, pattern, out success1);

                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                newSheetIndex = 1;
            }
            success = true;
        }
 /// <summary>
 /// Generates a MyPoint object that does not belong to the dictionary passed.
 /// </summary>
 /// <param name="dictionary"></param>
 /// <returns></returns>
 private MyPoint generatePoint(ref Dictionary<int, MyPoint> dictionary )
 {
     MyPoint p = new MyPoint(-1, -1);
     bool operation = true;
     do
     {
         p.X = random.Next(KEY_WIDTH);
         p.Y = random.Next(KEY_HEIGHT);
         operation = dictionary.ContainsValue(p);
     } while (operation);
     return p;
 }
 private static string GetUniqueValue(Dictionary<string, string> dictionary, string valueToBeInserted)
 {
     int i = 0;
     string prefix = "";
     while (dictionary.ContainsValue(valueToBeInserted + prefix))
     {
         prefix = string.Format("_{0}", ++i);
     }
     return string.Format("{0}{1}", valueToBeInserted, prefix);
 }
示例#7
0
 public Dictionary<string, object> PackBans(Dictionary<string, object> result)
 {
     Dictionary<string, object> Bans = new Dictionary<string, object>();
     int i = 0;
     foreach (Scene scene in m_scenes)
     {
         foreach (EstateBan ban in scene.RegionInfo.EstateSettings.EstateBans)
         {
             if (!Bans.ContainsValue(ban.BannedUserID))
             {
                 Bans.Add(ConvertDecString(i), ban.BannedUserID);
                 i++;
             }
         }
     }
     result["Bans"] = Bans;
     return result;
 }
示例#8
0
 private void GetImagesinUrl1(HttpContext context)
 {
     string url = context.Request.QueryString["url"];
     Regex img = new Regex("<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase);
     Regex src = new Regex(@"src=(?:(['""])(?<src>(?:(?!\1).)*)\1|(?<src>[^\s>]+))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
     WebClient source = new WebClient();
     string value = source.DownloadString(new Uri(url));
     if (!string.IsNullOrEmpty(value))
     {
         MatchCollection matches = img.Matches(value);
         if (matches.Count > 0)
         {
             string rpath = Common.RelTemp + Common.UserID;
             string path = Common.Temp + Common.UserID;
             if (!Directory.Exists(path)) Directory.CreateDirectory(path);
             else
             {
                 string[] files = Directory.GetFiles(path);
                 foreach (string file in files)
                 {
                     File.Delete(file);
                 }
             }
             int i = 0;
             Dictionary<int, bool> _dict = new Dictionary<int, bool>();
             List<string> paths = new List<string>();
             AsyncCompletedEventHandler callback = (sender, e) =>
                                                       {
                                                           dynamic dyn = (dynamic)e.UserState;
                                                           _dict[dyn.i] = true;
                                                           string rfn = rpath + dyn.i + ".jpg";
                                                           paths.Add(rfn);
                                                       };
             foreach (Match match in matches)
             {
                 string imgUrl = match.Groups[1].Value;
                 WebClient client = new WebClient();
                 client.DownloadFileCompleted += callback;
                 string fn = path + "\\" + i + ".jpg";
                 dynamic dyn = new ExpandoObject();
                 dyn.fn = fn;
                 dyn.i = i;
                 client.DownloadFileAsync(new Uri(imgUrl), fn, dyn);
                 _dict.Add(i, false);
                 i++;
             }
             while (_dict.ContainsValue(false)) Thread.Sleep(500);
             context.WriteJsonP(JsonConvert.SerializeObject(paths, Formatting.Indented, Common.JsonSerializerSettings));
         }
     }
 }
        private static string GetUnique(Dictionary<string , string> dic , string value)
        {
            int i = 0;
            string prefixion = "";
            while (dic.ContainsValue(value + prefixion))
            {
                prefixion = string.Format(System.Globalization.CultureInfo.InvariantCulture, "_{0}", ++i);
            }

            string result = string.Format("{0}{1}" , value , prefixion);
            return result;
        }
        // ------------------------------------------------------------
        // Name: UpdateConvertedProspects
        // Abstract: Retrieve subscribers from a list
        // ------------------------------------------------------------
        public static Dictionary<string, string> GetDuplicateSubscribers()
        {
            Dictionary<string, string> dctDuplicateSubscribers = new Dictionary<string, string>();
            Dictionary<string, string> dctSubscribers = new Dictionary<string, string>();
            Dictionary<string, string> dctAllSubscribers = new Dictionary<string, string>();
            try
            {
                string strCustomerNumber = "";
                string strSubscriberKey = "";
                string strEmail = "";

                // Get subscriber dates
                ET_Subscriber getSub = new ET_Subscriber();
                getSub.AuthStub = m_etcTDClient;
                getSub.Props = new string[] { "SubscriberKey", "EmailAddress" };
                GetReturn getResponse = getSub.Get();
                Console.WriteLine("Get Status: " + getResponse.Status.ToString());
                Console.WriteLine("Message: " + getResponse.Message.ToString());
                Console.WriteLine("Code: " + getResponse.Code.ToString());
                Console.WriteLine("Results Length: " + getResponse.Results.Length);
                while (getResponse.MoreResults == true)
                {

                    foreach (ET_Subscriber sub in getResponse.Results)
                    {
                        Console.WriteLine("SubscriberKey: " + sub.SubscriberKey);

                        // Add to our list
                        dctAllSubscribers.Add(sub.SubscriberKey, sub.EmailAddress);
                    }

                    getResponse = getSub.GetMoreResults();
                }

                foreach (KeyValuePair<string, string> entry in dctAllSubscribers)
                {
                    strSubscriberKey = entry.Key;
                    strEmail = entry.Value;
                    // Add to duplicates if email already exists
                    if (dctSubscribers.ContainsValue(strEmail) == true)
                    {
                        // Get customer number from duplicate if duplicate hasn't been logged
                        if (dctDuplicateSubscribers.ContainsValue(strEmail) == false)
                        {
                            strCustomerNumber = dctSubscribers.FirstOrDefault(x => x.Value == strEmail).Key;

                            // Add (both) duplicate entries
                            dctDuplicateSubscribers.Add(strSubscriberKey, strEmail);
                            dctDuplicateSubscribers.Add(strCustomerNumber, strEmail);
                        }
                        else
                        {
                            dctDuplicateSubscribers.Add(strSubscriberKey, strEmail);
                        }
                    }
                    else
                    {
                        // Add to our list
                        dctSubscribers.Add(strSubscriberKey, strEmail);
                    }
                }

            }
            catch (Exception excError)
            {
                // Display Error
                Console.WriteLine("Error: " + excError.ToString());
            }

            return dctDuplicateSubscribers;
        }
 public void ValueExists()
 {
     // This should have been at the top
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     dictionary["one"] = "uno";
     Assert.Equal(FILL_ME_IN, dictionary.ContainsValue("uno"));
     Assert.Equal(FILL_ME_IN, dictionary.ContainsValue("dos"));
 }
示例#12
0
        //去除型號相同的(不管顏色)
        private void DistinctModel(string inPath, string saveRepeatFileName, string saveFileName)
        {
            string line;
            StreamReader file = new StreamReader(inPath);
            List<string> models = new List<string>();
            while ((line = file.ReadLine()) != null)
            {
                if (line.Length != 0)
                    models.Add(line.ToLower());
            }
            file.Close();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (string m in models)
            {
                if (!dic.ContainsValue(m.Substring(m.IndexOf(m.Split('\t')[1]))))//比較廠牌型號
                {
                    dic.Add(m.Split('\t')[0], m.Substring(m.IndexOf(m.Split('\t')[1])));//ID,值
                    saveData.Save(saveFileName, m);
                }
                else
                    foreach (var d in dic)//印出對應表
                    {
                        if (d.Value == m.Substring(m.IndexOf(m.Split('\t')[1])))
                            saveData.Save(saveRepeatFileName, d.Key + "\t" + m.Split('\t')[0]);
                    }
            }
            //return (String[])DistinctArray.ToArray(typeof(string));
        }
        public static string[] Split(this string line, ICollection<char> separators, Dictionary<char, char> uniters, out int nonClosedParenthesis)
        {
            List<string> parameters = new List<string>();
            int startIndex = 0;
            Stack<char> uniterStack = new Stack<char>();
            for (int j = 0; j < line.Length; j++)
            {
                char currChar = line[j];
                if (separators.Contains(currChar))
                {
                    if (uniterStack.Count == 0)
                    {
                        if (j - startIndex > 0)
                        {
                            parameters.Add(line.Substring(startIndex, j - startIndex));
                        }
                        startIndex = j + 1;
                    }
                }
                else if (uniters.ContainsKey(currChar)
                    && !(uniters[currChar] == currChar
                        && uniterStack.Count > 0 && uniterStack.Peek() == currChar))
                {
                    uniterStack.Push(currChar);
                }
                else if (uniters.ContainsValue(currChar))
                {
                    if (uniterStack.Count > 0 && uniters[uniterStack.Peek()] == currChar)
                    {
                        uniterStack.Pop();
                    }
                    else
                    {
                        throw new ArgumentException();
                    }
                }
            }
            if (startIndex < line.Length)
            {
                parameters.Add(line.Substring(startIndex, line.Length - startIndex));
            }

            nonClosedParenthesis = uniterStack.Count;
            parameters.RemoveAll(string.IsNullOrEmpty);
            return parameters.ToArray();
        }
示例#14
0
        private static void _GetLinks(string sContent, string sUrl, ref Dictionary<string, string> lisA)
        {
            const string sFilter =
@"首页|下载|中文|English|反馈|讨论区|投诉|建议|联系|关于|about|诚邀|工作|简介|新闻|掠影|风采
|登录|注销|注册|使用|体验|立即|收藏夹|收藏|添加|加入
|更多|more|专题|精选|热卖|热销|推荐|精彩
|加盟|联盟|友情|链接|相关
|订阅|阅读器|RSS
|免责|条款|声明|我的|我们|组织|概况|有限|免费|公司|法律|导航|广告|地图|隐私
|〖|〗|【|】|(|)|[|]|『|』|\.";

            Regex re = new Regex(@"<a\s+[^>]*href\s*=\s*[^>]+>[\s\S]*?</a>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
            Regex re2 = new Regex(@"""|'", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
            MatchCollection mcs = re.Matches(sContent);
            //foreach (Match mc in mcs)
            for (int i = mcs.Count - 1; i >= 0; i--)
            {
                Match mc = mcs[i];
                string strHref = GetLink(mc.Value).Trim();

                strHref = strHref.Replace("\\\"", "");//针对JS输出链接
                strHref = strHref.Replace("\\\'", "");

                string strTemp = RemoveByReg(strHref, @"^http.*/$");//屏蔽以“http”开头“/”结尾的链接地址
                if (strTemp.Length < 2)
                {
                    continue;
                }

                //过滤广告或无意义的链接
                string strText = ClearTag(GetTextByLink(mc.Value)).Trim();
                strTemp = RemoveByReg(strText, sFilter);
                if (Encoding.Default.GetBytes(strTemp).Length < 9)
                {
                    continue;
                }
                if (re2.IsMatch(strText))
                {
                    continue;
                }

                //换上绝对地址
                strHref = GetUrlByRelative(sUrl, strHref);
                if (strHref.Length <= 18)//例如,http://www.163.com = 18
                {
                    continue;
                }

                //计算#字符出现的位置,移除它后面的内容
                //如果是域名地址,就跳过
                int charIndex = strHref.IndexOf('#');
                if (charIndex > -1)
                {
                    strHref = strHref.Substring(0, charIndex);
                }
                strHref = strHref.Trim(new char[] { '/', '\\' });
                string tmpDomainURL = GetDomain(strHref);
                if (strHref.Equals(tmpDomainURL, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (!lisA.ContainsKey(strHref) && !lisA.ContainsValue(strText))
                {
                    lisA.Add(strHref, strText);
                }
            }
        }
示例#15
0
        /// <summary>
        /// Exports results to a .csv file.
        /// </summary>
        /// <param name="_filename">The name of the file to save.</param>
        /// <param name="results">The list of RowResults to persist.</param>
        public static void ExportToCsv(string filename, List<RowResults> results)
        {
            try
            {
                // Force the . as decimal separator
                NumberFormatInfo dblFormat = new NumberFormatInfo();
                dblFormat.NumberDecimalSeparator = ".";

                StringBuilder buff = new StringBuilder();
                Dictionary<int, string> metrics_cols = new Dictionary<int, string>();

                // Columns headers
                // ***************************************************************
                buff.Append("filter,parameters,durationticks,filter-chain");
                int colidx = 0;

                // Gets all distinct metrics executed ...
                // Update metrics_cols and columns headers for each one.
                foreach (RowResults rw in results)
                {
                    if (null != rw.Item4)
                    {
                        foreach (MetricResult rw_res in rw.Item4)
                        {
                            if (!metrics_cols.ContainsValue(rw_res.Key))
                            {
                                metrics_cols.Add(colidx, rw_res.Key);
                                ++colidx;
                                // Add metric to columns; change commas by _ just in case!
                                buff.Append(",").Append(rw_res.Key.Replace(",", "_"));
                            }
                        }
                    }
                }

                buff.AppendLine();

                // ***************************************************************
                // Add rows ...
                string sFilter = "", sParameters = "", sChain = "";
                int idxMetric;
                foreach (RowResults rw in results)
                {
                    if (null != rw.Item4 && rw.Item4.Count > 0)
                    {

                        // Get filter, parameters

                        Facilities.FilterExecToString(rw.Item5.FilterType, rw.Item6, out sFilter, out sParameters);

                        // Get chain of nodes ... convert to filter-list form
                        // ...
                        sChain = "";
                        // Try to get history bucket
                        Image theImage = (Image)rw.Item2;
                        if (theImage != null)
                        {
                            ArrayList bucket = Facilities.GetBucket<ArrayList>(
                                    ref theImage, Facilities.EXECUTED_FILTERS);

                            if (bucket != null)
                            {
                                foreach (object o in bucket)
                                {
                                    sChain += (string.IsNullOrEmpty(sChain) ? "" : " ; ") + o.ToString();
                                }
                            }
                        }

                        // filter
                        buff.Append(sFilter);
                        // parameters
                        buff.Append(",").Append(sParameters);
                        // duration
                        buff.Append(",").Append(rw.Item7.Ticks.ToString());
                        // chain
                        buff.Append(",").Append(sChain);

                        Dictionary<string, double> dMetrics = new Dictionary<string, double>();

                        foreach (MetricResult rw_res in rw.Item4)
                        {
                            dMetrics.Add(rw_res.Key, rw_res.Value);
                        }

                        for (int i = 0; i < colidx; ++i)
                        {
                            buff.Append(",");
                            if (dMetrics.ContainsKey(metrics_cols[i]))
                            {
                                buff.Append(dMetrics[metrics_cols[i]].ToString(dblFormat));
                            }
                        }

                        // --
                        buff.AppendLine();

                    }
                }

                File.WriteAllText(filename, buff.ToString());
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Error when trying to export to csv '{0}'.", filename), e);
            }
        }
示例#16
0
        public void CheckChestState(Dictionary<int, int> hasGotReward)
        {
            InstanceTreasureChestUIViewManager.Instance.SetTitle(LanguageData.dataMap[25500].content);

            if (hasGotReward == null)
                return;

            if (!MapUIMappingData.dataMap.ContainsKey(InstanceUILogicManager.Instance.MapID))
                return;

            List<int> chest = MapUIMappingData.dataMap[InstanceUILogicManager.Instance.MapID].chest;

            if (chest == null)
                return;

            if (chest.Count == 0)
                return;

            bool allGot = true;
            foreach (var rewardID in chest)
                if (!hasGotReward.ContainsValue(rewardID))
                    allGot = false;

            bool isAnyCanGet = false;

            if (allGot)
            {
                // 设置全部领取完毕
                InstanceTreasureChestUIViewManager.Instance.SetDesc(LanguageData.dataMap[25504].content);
                InstanceTreasureChestUIViewManager.Instance.SetInstanceLevelRewardItemImage(new List<string>(), new List<string>());
                InstanceTreasureChestUIViewManager.Instance.ChangeTab((int)TreasureChestUITab.ShowItemTab);
            }

            foreach (var rewardID in chest)
            {
                if (!MissionRewardData.fixCondition.ContainsKey(rewardID))
                    continue;

                if (hasGotReward.ContainsValue(rewardID))
                    continue;

                bool canGet = true;
                List<List<int>> result = new List<List<int>>();

                foreach (var condition in MissionRewardData.fixCondition[rewardID])
                {
                    int missionID = condition[0];
                    int missionLevel = condition[1];
                    int missionGrade = condition[2];

                    // 统计所有的不符合情况
                    if (!finishedMissions.ContainsKey(missionID))
                    {
                        canGet = false;
                        List<int> temp = new List<int>();
                        temp.Add(missionID);
                        result.Add(temp);
                        continue;
                        //break;
                    }
                    if (!finishedMissions[missionID].ContainsKey(missionLevel))
                    {
                        canGet = false;
                        List<int> temp = new List<int>();
                        temp.Add(missionID);
                        temp.Add(missionLevel);
                        result.Add(temp);
                        continue;
                        //break;
                    }
                    if (finishedMissions[missionID][missionLevel] < missionGrade)
                    {
                        canGet = false;
                        List<int> temp = new List<int>();
                        temp.Add(missionID);
                        temp.Add(missionLevel);
                        temp.Add(missionGrade);
                        result.Add(temp);
                        continue;
                        //break;
                    }
                }

                if (canGet)
                {
                    // 设置可领取
                    InstanceTreasureChestUIViewManager.Instance.SetDesc(LanguageData.dataMap[25503].content);
                    SetChestImage(MissionRewardData.dataMap[rewardID].rewards);
                    InstanceTreasureChestUIViewManager.Instance.CurrentID = rewardID;
                    InstanceTreasureChestUIViewManager.Instance.ChangeTab((int)TreasureChestUITab.GetItemTab);

                    isAnyCanGet = true;
                    InstanceMissionChooseUIViewManager.Instance.ShowMapChestRotationAnimation(isAnyCanGet);

                    return;
                }
                else
                {
                    foreach (var resultDetail in result)
                    {
                        switch (resultDetail.Count)
                        {
                            case 1:
                                break;
                            case 2:
                                break;
                            case 3:
                                break;
                        }
                    }

                    switch (rewardID % 3)
                    {
                        case 1:
                            InstanceTreasureChestUIViewManager.Instance.SetDesc(LanguageData.dataMap[25501].content);
                            break;
                        case 2:
                            InstanceTreasureChestUIViewManager.Instance.SetDesc(LanguageData.dataMap[25502].content);
                            break;
                    }

                    SetChestImage(MissionRewardData.dataMap[rewardID].rewards);
                    InstanceTreasureChestUIViewManager.Instance.ChangeTab((int)TreasureChestUITab.ShowItemTab);

                    InstanceMissionChooseUIViewManager.Instance.ShowMapChestRotationAnimation(isAnyCanGet);

                    return;
                }
            }

            InstanceMissionChooseUIViewManager.Instance.ShowMapChestRotationAnimation(isAnyCanGet);
        }
示例#17
0
        public void SetBossChestState(Dictionary<int, int> hasGotReward)
        {
            if (!MapUIMappingData.dataMap.ContainsKey(InstanceUILogicManager.Instance.MapID))
                return;

            //List<int> bossChest = MapUIMappingData.dataMap[InstanceUILogicManager.Instance.MapID].bossChest;

            //if (bossChest == null)
            //    return;

            //if (bossChest.Count == 0)
            //    return;

            List<BossTreasureGridData> listBossTreasureGridData = new List<BossTreasureGridData>();

            //foreach (var bossChestID in bossChest)
            //{
            //    if (!BossChestData.dataMap.ContainsKey(bossChestID))
            //        continue;

            //    BossChestData bossChestData = BossChestData.dataMap[bossChestID];

            bool isAnyChestCanGet = false;

            foreach (var bossChestDataSource in BossChestData.dataMap)
            {
                int bossChestID = bossChestDataSource.Value.id;
                BossChestData bossChestData = bossChestDataSource.Value;

                BossTreasureGridData gridData = new BossTreasureGridData();
                gridData.id = bossChestData.id;
                gridData.iconName = IconData.dataMap.Get(bossChestData.icon).path;
                gridData.bossName = LanguageData.GetContent(bossChestData.name);
                gridData.level = MissionData.dataMap.First(t => t.Value.mission == bossChestData.mission && t.Value.difficulty == bossChestData.difficulty).Value.level;

                //gridData.reward = new List<string>();
                //foreach (var item in bossChestData.reward)
                //    gridData.reward.Add(string.Concat(ItemParentData.GetItem(item.Key).Name, " * ", item.Value));

                if (hasGotReward.ContainsValue(bossChestID))
                {
                    // 已领取
                    gridData.status = BossTreasureStatus.HasGotReward;
                }
                else if (CheckCurrentMissionHardByGrade(bossChestData.mission, 4))
                {
                    // 未领取,获得S
                    gridData.status = BossTreasureStatus.CanGetReward;
                    isAnyChestCanGet = true;
                }
                else if (enterableMissions.ContainsKey(bossChestData.mission))
                {
                    // 未领取,未获得S,可进入(解锁)
                    gridData.status = BossTreasureStatus.NoHasStarS;
                }
                else
                {
                    // 未解锁
                    gridData.status = BossTreasureStatus.LevelNoEnough;
                }

                listBossTreasureGridData.Add(gridData);
            }

            InstanceMissionChooseUIViewManager.Instance.ShowBossChestRotationAnimation(isAnyChestCanGet);
            InstanceBossTreasureUILogicManager.Instance.SetBossTreasureList(listBossTreasureGridData);
        }
示例#18
0
 private void Dictionary_Method_ContainsValue_Sample()
 {
     //  Returns true if the dictionary contains the specified value
     Dictionary<int, string> dic = new Dictionary<int, string>();
     dic.Add(1, "string1");
     dic.Add(2, "string2");
     Debug.WriteLine(dic.ContainsValue("string3").ToString());
     // It will result false because the value string3 is not contained ihn the collection.
     Debug.WriteLine(dic.ContainsValue("string2").ToString());
     // It will result true  because the value string3 is contained in the collection.
 }
        public void Remap(
            BooleanCedent[] booleanCedents,
            CategorialCedent[] categorialCedents,
            int taskID,
            TaskTypeEnum taskType,
            string boxIdentity,
            out long allRowsInTaskDataMatrixCount)
        {
            List<AbstractAttributeStruct> abstractAttributes = new List<AbstractAttributeStruct>();
            string categoryName;

            #region EQUIVALENCE CLASS PROBLEM VARIABLES
            int attributeIdentifier;
            int literalIdentifier;
            int equivalenceClassIdentifier;
            int rewrite;
            //Pair <attribute.identifier, List Of [literal.identifier]>
            Dictionary<int, List<int>> attributesAndLiterals = new Dictionary<int, List<int>>();
            //Pair <attribute.identifier, equivalenceClass.identifier>
            Dictionary<int, int> attributesAndEquivalenceClasses = new Dictionary<int, int>();
            //Pair <literal.identifier, equivalenceClass.identifier>
            Dictionary<int, int> literalsAndEquivalenceClasses = new Dictionary<int, int>();
            #endregion

            #region BooleanCedent (tdCedentD), EquivalenceClass (tdEquivalenceClass), Literal (tdLiteralD)

            Dictionary<CedentEnum, bool> savedCedents = new Dictionary<CedentEnum, bool>();

            if (booleanCedents != null)
            {
                int booleanCedentID;
                int equivalenceClassID;
                EquivalenceClassStruct[] equivalenceClasses;

                foreach (BooleanCedent booleanCedent in booleanCedents)
                {
                    #region BooleanPartialCedent (tdCedentD)
                    CedentIdentifierAndType cedentIdentifierAndType = new CedentIdentifierAndType(booleanCedent.Cedent.identifier, booleanCedent.CedentType);
                    if (this.booleanPartialCedents.ContainsKey(cedentIdentifierAndType))
                    {
                        booleanCedentID = this.booleanPartialCedents[cedentIdentifierAndType];
                        continue;
                    }
                    else
                    {
                        booleanCedentID = this.SetBooleanPartialCedent(
                            booleanCedent.CedentType,
                            booleanCedent.Cedent.minLen,
                            booleanCedent.Cedent.maxLen,
                            taskID);
                        this.booleanPartialCedents.Add(cedentIdentifierAndType, booleanCedentID);
                    }

                    savedCedents[booleanCedent.CedentType] = true;

                    #endregion

                    #region EQUIVALENCE CLASS PROBLEM

                    equivalenceClasses = booleanCedent.Cedent.equivalenceClasses;

                    if (equivalenceClasses != null &&
                        equivalenceClasses.Length > 0)
                    {
                        //This makes attributesAndLiterals Dictionary<int, List<int>> Pair <attribute.identifier, List Of [literal.identifier]>
                        if (booleanCedent.Cedent.literalSettings != null)
                            foreach (LiteralSettingStruct literalSettingStruct in booleanCedent.Cedent.literalSettings)
                            {
                                //literalSettingStruct.identifier;
                                attributeIdentifier = literalSettingStruct.atomSetting.abstractAttribute.identifier;
                                literalIdentifier = literalSettingStruct.identifier;
                                if (attributesAndLiterals.ContainsKey(attributeIdentifier))
                                    attributesAndLiterals[attributeIdentifier].Add(literalIdentifier);
                                else
                                    attributesAndLiterals.Add(attributeIdentifier, new List<int>(new int[] { literalIdentifier }));
                                attributesAndEquivalenceClasses[attributeIdentifier] = 0;
                                literalsAndEquivalenceClasses[literalIdentifier] = 0;
                            }
                        //This makes attributesAndEquivalenceClasses Dictionary<int, int> Pair <attribute.identifier, equivalenceClass.identifier>
                        foreach (EquivalenceClassStruct equivalenceClassStruct in equivalenceClasses)
                        {
                            equivalenceClassIdentifier = equivalenceClassStruct.identifier;
                            foreach (int identifierOfAttributeInClass in equivalenceClassStruct.attributesIdentifiers)
                            {
                                rewrite = 0;
                                if (attributesAndEquivalenceClasses.ContainsKey(identifierOfAttributeInClass))
                                {
                                    if (attributesAndEquivalenceClasses[identifierOfAttributeInClass] != 0)
                                        rewrite = attributesAndEquivalenceClasses[identifierOfAttributeInClass];
                                    attributesAndEquivalenceClasses[identifierOfAttributeInClass] = equivalenceClassIdentifier;
                                }
                                else
                                    attributesAndEquivalenceClasses.Add(identifierOfAttributeInClass, equivalenceClassIdentifier);
                                if (rewrite != 0)
                                    foreach (KeyValuePair<int, int> kvp in attributesAndEquivalenceClasses)
                                    {
                                        if (attributesAndEquivalenceClasses[kvp.Key] == rewrite)
                                            attributesAndEquivalenceClasses[kvp.Key] = equivalenceClassIdentifier;
                                    }
                            }
                        }
                        //This makes literalsAndEquivalenceClasses Dictionary<int, int> Pair <literal.identifier, equivalenceClass.identifier>
                        //Process equivalence classes of attributes to literals
                        foreach (KeyValuePair<int, int> kvp in attributesAndEquivalenceClasses)
                        {
                            if (attributesAndEquivalenceClasses[kvp.Key] != 0)
                            {
                                rewrite = attributesAndEquivalenceClasses[kvp.Key];
                                foreach (int currentLiteralKey in attributesAndLiterals[kvp.Key])
                                {
                                    literalsAndEquivalenceClasses[currentLiteralKey] = rewrite;
                                }
                            }
                        }
                        //This process equivalence classes of literals
                        foreach (EquivalenceClassStruct equivalenceClassStruct in equivalenceClasses)
                        {
                            equivalenceClassIdentifier = equivalenceClassStruct.identifier;
                            foreach (int identifierOfLiteralInClass in equivalenceClassStruct.literalsIdentifiers)
                            {
                                rewrite = 0;
                                if (literalsAndEquivalenceClasses.ContainsKey(identifierOfLiteralInClass))
                                {
                                    if (literalsAndEquivalenceClasses[identifierOfLiteralInClass] != 0)
                                        rewrite = literalsAndEquivalenceClasses[identifierOfLiteralInClass];
                                    literalsAndEquivalenceClasses[identifierOfLiteralInClass] = equivalenceClassIdentifier;
                                }
                                else
                                {
                                    literalsAndEquivalenceClasses.Add(identifierOfLiteralInClass, equivalenceClassIdentifier);
                                }
                                if (rewrite != 0)
                                    foreach (KeyValuePair<int, int> kvp in literalsAndEquivalenceClasses)
                                    {
                                        if (literalsAndEquivalenceClasses[kvp.Key] == rewrite)
                                            literalsAndEquivalenceClasses[kvp.Key] = equivalenceClassIdentifier;
                                    }
                            }
                        }
                    }

                    #endregion

                    #region EquivalenceClass (tdEquivalenceClass)

                    equivalenceClasses = booleanCedent.Cedent.equivalenceClasses;
                    if (booleanCedent.Cedent.equivalenceClasses != null)
                        foreach (EquivalenceClassStruct equivalenceClassStruct in equivalenceClasses)
                        {
                            //test if equivalence class is used or if it was absorb by other equivalence class
                            if (!literalsAndEquivalenceClasses.ContainsValue(equivalenceClassStruct.identifier))
                                continue;

                            equivalenceClassID = this.SetEquivalenceClass(
                                booleanCedentID,
                                equivalenceClassStruct.identifier);
                            this.equivalenceClasses.Add(equivalenceClassStruct.identifier, equivalenceClassID);
                        }

                    #endregion

                    #region  Prepare list of Attributes from BooleanCedents
                    if (booleanCedent.Cedent.literalSettings != null)
                        foreach (LiteralSettingStruct literalSettingStruct in booleanCedent.Cedent.literalSettings)
                        {
                            abstractAttributes.Add(literalSettingStruct.atomSetting.abstractAttribute);
                        }
                    #endregion
                }
            }
            #endregion
            #region Prepare list of Attributes from CategorialCedents
            if (categorialCedents != null)
                foreach (CategorialCedent categorialCedent in categorialCedents)
                {
                    savedCedents[categorialCedent.CedentType] = true;
                    abstractAttributes.AddRange(categorialCedent.Cedent.attributes);
                }
            #endregion

            #region Saved cedents?
            //pokud totiz neni nastaven nejaky cedent (chybi treba prazdny radek), tak nejde pustit gen
            switch (taskType)
            {
                case TaskTypeEnum.FFT:
                    if (!savedCedents.ContainsKey(CedentEnum.Antecedent) || savedCedents[CedentEnum.Antecedent] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Antecedent, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.Succedent) || savedCedents[CedentEnum.Succedent] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Succedent, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.Condition) || savedCedents[CedentEnum.Condition] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Condition, 0, 0, taskID);
                    break;
                case TaskTypeEnum.SDFFT:
                    if (!savedCedents.ContainsKey(CedentEnum.Antecedent) || savedCedents[CedentEnum.Antecedent] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Antecedent, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.Succedent) || savedCedents[CedentEnum.Succedent] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Succedent, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.Condition) || savedCedents[CedentEnum.Condition] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Condition, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.FirstSet) || savedCedents[CedentEnum.FirstSet] == false)
                        this.SetBooleanPartialCedent(CedentEnum.FirstSet, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.SecondSet) || savedCedents[CedentEnum.SecondSet] == false)
                        this.SetBooleanPartialCedent(CedentEnum.SecondSet, 0, 0, taskID);
                    break;
                case TaskTypeEnum.KL:
                    if (!savedCedents.ContainsKey(CedentEnum.Antecedent) || savedCedents[CedentEnum.Antecedent] == false)
                        this.SetCategorialPartialCedent(CedentEnum.Antecedent, 0, 0, taskID, taskType);
                    if (!savedCedents.ContainsKey(CedentEnum.Succedent) || savedCedents[CedentEnum.Succedent] == false)
                        this.SetCategorialPartialCedent(CedentEnum.Succedent, 0, 0, taskID, taskType);
                    if (!savedCedents.ContainsKey(CedentEnum.Condition) || savedCedents[CedentEnum.Condition] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Condition, 0, 0, taskID);
                    break;

                case TaskTypeEnum.CF:
                    if (!savedCedents.ContainsKey(CedentEnum.Antecedent) || savedCedents[CedentEnum.Antecedent] == false)
                        this.SetCategorialPartialCedent(CedentEnum.Antecedent, 0, 0, taskID, taskType);
                    if (!savedCedents.ContainsKey(CedentEnum.Condition) || savedCedents[CedentEnum.Condition] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Condition, 0, 0, taskID);
                    break;

                case TaskTypeEnum.SDCF:
                    if (!savedCedents.ContainsKey(CedentEnum.Antecedent) || savedCedents[CedentEnum.Antecedent] == false)
                        this.SetCategorialPartialCedent(CedentEnum.Antecedent, 0, 0, taskID, taskType);
                    if (!savedCedents.ContainsKey(CedentEnum.Condition) || savedCedents[CedentEnum.Condition] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Condition, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.FirstSet) || savedCedents[CedentEnum.FirstSet] == false)
                        this.SetBooleanPartialCedent(CedentEnum.FirstSet, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.SecondSet) || savedCedents[CedentEnum.SecondSet] == false)
                        this.SetBooleanPartialCedent(CedentEnum.SecondSet, 0, 0, taskID);
                    break;

                case TaskTypeEnum.SDKL:
                    if (!savedCedents.ContainsKey(CedentEnum.Antecedent) || savedCedents[CedentEnum.Antecedent] == false)
                        this.SetCategorialPartialCedent(CedentEnum.Antecedent, 0, 0, taskID, taskType);
                    if (!savedCedents.ContainsKey(CedentEnum.Succedent) || savedCedents[CedentEnum.Succedent] == false)
                        this.SetCategorialPartialCedent(CedentEnum.Succedent, 0, 0, taskID, taskType);
                    if (!savedCedents.ContainsKey(CedentEnum.Condition) || savedCedents[CedentEnum.Condition] == false)
                        this.SetBooleanPartialCedent(CedentEnum.Condition, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.FirstSet) || savedCedents[CedentEnum.FirstSet] == false)
                        this.SetBooleanPartialCedent(CedentEnum.FirstSet, 0, 0, taskID);
                    if (!savedCedents.ContainsKey(CedentEnum.SecondSet) || savedCedents[CedentEnum.SecondSet] == false)
                        this.SetBooleanPartialCedent(CedentEnum.SecondSet, 0, 0, taskID);
                    break;

                default:
                    throw Ferda.Modules.Exceptions.SwitchCaseNotImplementedError(taskType);
            }
            #endregion

            #region DataMatrix (tmMatrix), Columns (tmAttribute), AbstractAttributes (tmQuantity), Category (tmCategory, tmCategoryEnumValue, tmInterval, tmValue)

            string dataMatrixName = "";
            int dataMatrixDBID = 0;
            string[] primaryKeyColumns = null; //must be sorted (for BinarySearch)
            string connectionString = null;
            allRowsInTaskDataMatrixCount = 0;
            ColumnSchemaInfo[] columnSchemaInfoSeq = null;
            Ferda.Modules.Boxes.DataMiningCommon.DataMatrix.DataMatrixInfo dataMatrixInfo;

            #region DataMatrix (tmMatrix)
            {
                AbstractAttributeStruct abstractAttributeStruct = abstractAttributes[0];
                dataMatrixInfo = abstractAttributeStruct.column.dataMatrix;

                //only for first attribute/column ... each attribute in one task must be in one and only one data matrix
                columnSchemaInfoSeq = dataMatrixInfo.explainDataMatrix;
                dataMatrixName = dataMatrixInfo.dataMatrixName;
                dataMatrixDBID = SetDataMatrix(dataMatrixName, dataMatrixInfo.recordsCount);
                updateTask(taskID, dataMatrixDBID);

                allRowsInTaskDataMatrixCount = dataMatrixInfo.recordsCount;

                string connectionStringForSave = dataMatrixInfo.database.odbcConnectionString.Trim();
                if (connectionStringForSave.StartsWith("DSN=", StringComparison.InvariantCultureIgnoreCase))
                    connectionStringForSave = connectionStringForSave.Substring(4);

                ExecuteUpdateQuery(
                    "UPDATE tpParamsDB SET "
                    + " strValue='" + connectionStringForSave + "' "
                    + " WHERE Name='DSN'");

                connectionString = dataMatrixInfo.database.odbcConnectionString;
                primaryKeyColumns = dataMatrixInfo.primaryKeyColumns;
                Array.Sort(primaryKeyColumns);
            }

            //Test values of primary key columns for duplicits (also test connection string and existence of data matrix)
            Ferda.Modules.Helpers.Data.DataMatrix.TestValuesInEnteredPrimaryKeyColumnsAreNotUniqueError(connectionString, dataMatrixName, primaryKeyColumns, boxIdentity);
            #endregion

            ColumnInfo columnInfo;
            CategoriesStruct categories;
            int columnID;
            int columnThereforeAlsoAttributeValueSubTypeDBID = 0;
            string columnSelectExpression;
            int primaryKeyColumnPosition;
            int categoryID;
            int enumCategoryValueID;
            int attributeID;
            //int attributeIdentifier; --allready defined
            string xCategory;
            string includeNullCategory;

            foreach (AbstractAttributeStruct abstractAttributeStruct in abstractAttributes)
            {
                //Protect from multiple saving columns or attributesAndEquivalenceClasses or caregories
                if (this.attributes.ContainsKey(abstractAttributeStruct.identifier))
                    continue;

                #region Columns (tmAttribute)

                if (dataMatrixName != abstractAttributeStruct.column.dataMatrix.dataMatrixName)
                {
                    throw Ferda.Modules.Exceptions.BoxRuntimeError(null, boxIdentity, "LM Task can not run over more than one datamatrix!");
                }
                columnSelectExpression = abstractAttributeStruct.column.columnSelectExpression;

                //Protect from multiple saving columns
                if (this.columns.ContainsKey(columnSelectExpression))
                {
                    columnID = this.columns[columnSelectExpression];
                }
                else
                {
                    columnInfo = abstractAttributeStruct.column;
                    primaryKeyColumnPosition = Array.BinarySearch(primaryKeyColumns, abstractAttributeStruct.column.columnSelectExpression);
                    columnThereforeAlsoAttributeValueSubTypeDBID = this.constants.ValueSubTypeEnumDictionary[columnInfo.columnSubType];
                    columnID = SetColumn(
                        columnInfo.columnSelectExpression,
                        dataMatrixDBID,
                        columnInfo.columnType,
                        columnInfo.columnSubType,
                        columnSelectExpression,
                        (primaryKeyColumnPosition >= 0) ? primaryKeyColumnPosition + 1 : -1);
                    this.columns.Add(columnInfo.columnSelectExpression, columnID);
                }

                int i = 0;
                foreach (string primaryKeyColumn in primaryKeyColumns)
                {
                    i++;
                    if (String.IsNullOrEmpty(primaryKeyColumn))
                        continue;
                    if (this.columns.ContainsKey(primaryKeyColumn))
                        continue;
                    foreach (ColumnSchemaInfo columnSchemaInfo in columnSchemaInfoSeq)
                    {
                        if (columnSchemaInfo.name == primaryKeyColumn)
                        {
                            int tmpColumnID = SetColumn(
                                columnSchemaInfo.name,
                                dataMatrixDBID,
                                ColumnTypeEnum.Ordinary,
                                Ferda.Modules.Helpers.Data.Column.GetColumnSubTypeByDataType(columnSchemaInfo.dataType),
                                columnSchemaInfo.name,
                                i);
                            this.columns.Add(columnSchemaInfo.name, tmpColumnID);
                            break;
                        }
                    }
                }

                #endregion

                #region Attribute (tmQuantity)

                attributeID = SetAttribute(
                        abstractAttributeStruct.nameInLiterals,
                        abstractAttributeStruct.identifier,
                        columnID);
                attributeIdentifier = abstractAttributeStruct.identifier;
                xCategory = abstractAttributeStruct.xCategory;
                includeNullCategory = abstractAttributeStruct.includeNullCategory;
                this.attributesCache.Add(abstractAttributeStruct.identifier, abstractAttributeStruct);
                this.attributes.Add(attributeIdentifier, attributeID);
                this.categories.Add(attributeIdentifier, new Dictionary<string, int>());
                this.categoriesOrds.Add(attributeIdentifier, new Dictionary<long, string>());

                #endregion

                #region Categories (tmCategory, tmCategoryEnumValue, tmInterval, tmValue)

                long categoryOrd = 0;
                categories = abstractAttributeStruct.categories;
                //if (categories.dateTimeIntervals != null)
                foreach (DictionaryEntry category in categories.dateTimeIntervals)
                {
                    categoryName = (string)category.Key;
                    //tmCategory
                    categoryOrd++;
                    categoryID = SetCategory(
                        categoryName,
                        attributeID,
                        CategoryTypeEnum.Interval,
                        (xCategory == categoryName),
                        (includeNullCategory == categoryName),
                        categoryOrd,
                        attributeIdentifier);
                    //tmValue, tmInterval
                    foreach (DateTimeIntervalStruct intervalStruct in (DateTimeIntervalStruct[])category.Value)
                    {
                        insertValueInterval(categoryID, intervalStruct);
                    }
                }
                //if (categories.floatIntervals != null)
                foreach (DictionaryEntry category in categories.floatIntervals)
                {
                    categoryName = (string)category.Key;
                    //tmCategory
                    categoryOrd++;
                    categoryID = SetCategory(
                        categoryName,
                        attributeID,
                        CategoryTypeEnum.Interval,
                        (xCategory == categoryName),
                        (includeNullCategory == categoryName),
                        categoryOrd,
                        attributeIdentifier);
                    //tmValue, tmInterval
                    foreach (FloatIntervalStruct intervalStruct in (FloatIntervalStruct[])category.Value)
                    {
                        insertValueInterval(categoryID, intervalStruct);
                    }
                }
                //if (categories.longIntervals != null)
                foreach (DictionaryEntry category in categories.longIntervals)
                {
                    categoryName = (string)category.Key;
                    //tmCategory
                    categoryOrd++;
                    categoryID = SetCategory(
                        categoryName,
                        attributeID,
                        CategoryTypeEnum.Interval,
                        (xCategory == categoryName),
                        (includeNullCategory == categoryName),
                        categoryOrd,
                        attributeIdentifier);
                    //tmValue, tmInterval
                    foreach (LongIntervalStruct intervalStruct in (LongIntervalStruct[])category.Value)
                    {
                        insertValueInterval(categoryID, intervalStruct);
                    }
                }
                //if (categories.enums != null)
                foreach (DictionaryEntry category in categories.enums)
                {
                    categoryName = (string)category.Key;
                    //tmCategory
                    categoryOrd++;
                    categoryID = SetCategory(
                        categoryName,
                        attributeID,
                        CategoryTypeEnum.Enumeration,
                        (xCategory == categoryName),
                        (includeNullCategory == categoryName),
                        categoryOrd,
                        attributeIdentifier);
                    foreach (string enumItem in (string[])category.Value)
                    {
                        //tmValue
                        if (categoryName == includeNullCategory && String.IsNullOrEmpty(enumItem))
                        {
                            enumCategoryValueID = SetValue();
                            continue;
                        }
                        else if (String.IsNullOrEmpty(enumItem))
                        {
                            //DEBUG NOTES: for debugin purposes it can be usevull if this else-if branch is removed (commented)
                            enumCategoryValueID = SetValue();
                            continue;
                        }
                        switch (columnThereforeAlsoAttributeValueSubTypeDBID)
                        {
                            case 1: //long
                                enumCategoryValueID = SetValue(Convert.ToInt64(enumItem));
                                break;
                            case 2: //double
                                enumCategoryValueID = SetValue(Convert.ToDouble(enumItem));
                                break;
                            case 3: //string
                                enumCategoryValueID = SetValue(enumItem);
                                break;
                            case 4: //bool
                                enumCategoryValueID = SetValue(Convert.ToBoolean(enumItem));
                                break;
                            case 5: //date
                                enumCategoryValueID = SetValue(Convert.ToDateTime(enumItem));
                                break;
                            default:
                                throw Ferda.Modules.Exceptions.SwitchCaseNotImplementedError(columnThereforeAlsoAttributeValueSubTypeDBID);
                        }
                        //tmCategoryEnumValue
                        this.SetCategoryEnum(
                            categoryID,
                            enumCategoryValueID);
                    }
                }

                #endregion
            }

            #endregion

            #region CategorialCedent (tdKLCedentD, tdCFCedentD, tdKLLiteralD, tdCFLiteralD)

            int categorialCedentID;
            int categorialLiteralID;

            if (categorialCedents != null)
                foreach (CategorialCedent categorialCedent in categorialCedents)
                {
                    CedentIdentifierAndType cedentIdentifierAndType = new CedentIdentifierAndType(categorialCedent.Cedent.identifier, categorialCedent.CedentType);
                    if (this.categorialPartialCedent.ContainsKey(cedentIdentifierAndType))
                    {
                        categorialCedentID = this.categorialPartialCedent[cedentIdentifierAndType];
                    }
                    else
                    {
                        categorialCedentID = SetCategorialPartialCedent(
                            categorialCedent.CedentType,
                            categorialCedent.Cedent.minLen,
                            categorialCedent.Cedent.maxLen,
                            taskID,
                            taskType);
                        this.categorialPartialCedent.Add(cedentIdentifierAndType, categorialCedentID);

                        if (categorialCedent.Cedent.attributes != null)
                            foreach (AbstractAttributeStruct abstractAttributeStruct in categorialCedent.Cedent.attributes)
                            {
                                categorialLiteralID = SetCategorialLiteralSetting(
                                    categorialCedentID,
                                    this.attributes[abstractAttributeStruct.identifier],
                                    taskType,
                                    abstractAttributeStruct.identifier);
                            }
                    }
                }

            #endregion

            #region BooleanCedent (tdLiteralD)

            int literalID;

            if (booleanCedents != null)
            {
                foreach (BooleanCedent booleanCedent in booleanCedents)
                {
                    if (booleanCedent.Cedent.literalSettings != null)
                        foreach (LiteralSettingStruct literalSettingStruct in booleanCedent.Cedent.literalSettings)
                        {
                            int literalOneCategoryDBID = (literalSettingStruct.atomSetting.category.Length > 0)
                                ? this.categories[literalSettingStruct.atomSetting.abstractAttribute.identifier][literalSettingStruct.atomSetting.category[0]]
                                : 0;
                            int literalEquivalenceClass = 0;
                            try
                            {
                                literalEquivalenceClass = this.equivalenceClasses[literalsAndEquivalenceClasses[literalSettingStruct.identifier]];
                            }
                            catch (KeyNotFoundException) { }
                            literalID = this.SetLiteralSetting(
                                    literalSettingStruct.atomSetting.minLen,
                                    literalSettingStruct.atomSetting.maxLen,
                                    literalSettingStruct.atomSetting.coefficientType,
                                    literalEquivalenceClass,
                                    literalSettingStruct.gaceType,
                                    literalSettingStruct.literalType,
                                    literalOneCategoryDBID,
                                    this.booleanPartialCedents[new CedentIdentifierAndType(booleanCedent.Cedent.identifier, booleanCedent.CedentType)],
                                    this.attributes[literalSettingStruct.atomSetting.abstractAttribute.identifier]);
                            this.literals.Add(literalID, literalSettingStruct.identifier);
                            this.attributeNameInLiterals.Add(literalID, literalSettingStruct.atomSetting.abstractAttribute.nameInLiterals);
                            //abstractAttributes.Add(literalSettingStruct.atomSetting.abstractAttribute);
                        }
                }
            }

            #endregion
        }
示例#20
0
文件: Binder.cs 项目: zooba/wix3
        /// <summary>
        /// Signal a warning if a non-keypath file was changed in a patch without also changing the keypath file of the component.
        /// </summary>
        /// <param name="output">The output to validate.</param>
        private void ValidateFileRowChanges(Output transform)
        {
            Table componentTable = transform.Tables["Component"];
            Table fileTable = transform.Tables["File"];

            // There's no sense validating keypaths if the transform has no component or file table
            if (componentTable == null || fileTable == null)
            {
                return;
            }

            Dictionary<string, string> componentKeyPath = new Dictionary<string, string>(componentTable.Rows.Count);

            // Index the Component table for non-directory & non-registry key paths.
            foreach (Row row in componentTable.Rows)
            {
                if (null != row.Fields[5].Data &&
                    0 != ((int)row.Fields[3].Data & MsiInterop.MsidbComponentAttributesRegistryKeyPath))
                {
                    componentKeyPath.Add(row.Fields[0].Data.ToString(), row.Fields[5].Data.ToString());
                }
            }

            Dictionary<string, string> componentWithChangedKeyPath = new Dictionary<string, string>();
            Dictionary<string, string> componentWithNonKeyPathChanged = new Dictionary<string, string>();
            // Verify changes in the file table, now that file diffing has occurred
            foreach (FileRow row in fileTable.Rows)
            {
                string fileId = row.Fields[0].Data.ToString();
                string componentId = row.Fields[1].Data.ToString();

                if (RowOperation.Modify != row.Operation)
                {
                    continue;
                }

                // If this file is the keypath of a component
                if (componentKeyPath.ContainsValue(fileId))
                {
                    if (!componentWithChangedKeyPath.ContainsKey(componentId))
                    {
                        componentWithChangedKeyPath.Add(componentId, fileId);
                    }
                }
                else
                {
                    if (!componentWithNonKeyPathChanged.ContainsKey(componentId))
                    {
                        componentWithNonKeyPathChanged.Add(componentId, fileId);
                    }
                }
            }

            foreach (KeyValuePair<string, string> componentFile in componentWithNonKeyPathChanged)
            {
                // Make sure all changes to non keypath files also had a change in the keypath.
                if (!componentWithChangedKeyPath.ContainsKey(componentFile.Key) && componentKeyPath.ContainsKey(componentFile.Key))
                {
                    this.core.OnMessage(WixWarnings.UpdateOfNonKeyPathFile((string)componentFile.Value, (string)componentFile.Key, (string)componentKeyPath[componentFile.Key]));
                }
            }
        }
示例#21
0
 public bool WordPattern(string pattern, string str)
 {
     var i = 0;
     var n = -1;
     var words = new Dictionary<string, char>();
     while (i < str.Length)
     {
         var j = i;
         while (j < str.Length && str[j] != ' ')
         {
             j++;
         }
         n++;
         if (n >= pattern.Length)
         {
             return false;
         }
         var s = str.Substring(i, j - i);
         if (!words.ContainsKey(s))
         {
             if (words.ContainsValue(pattern[n]))
             {
                 return false;
             }
             words.Add(s, pattern[n]);
         }
         if (words[s] != pattern[n])
         {
             return false;
         }
         i = j + 1;
     }
     return n == pattern.Length - 1;
 }
示例#22
0
        /// <summary>
        /// Gets the owners list
        /// </summary>
        /// <param name="siteURL">Site URL.</param>
        /// <param name="listName">List Name.</param>
        /// <param name="queryString">CAML Query.</param>     
        /// <returns>Dictionary Object.</returns>
        public Dictionary<string, string> GetPageOwnerList(string siteURL, string listName, string CAMLQuery)
        {
            Dictionary<string, string> listItemCollection = null;
            DataTable dtResultDatatable = null;
            string strCAMLQuery = string.Empty;
            StringBuilder strChapterId = new StringBuilder();
            objCommonDAL = new CommonDAL();
            string strViewFields = string.Empty;
            strViewFields = @"<FieldRef Name='ID' />";
            dtResultDatatable = objCommonDAL.ReadList(siteURL, listName, CAMLQuery, strViewFields);

            if (dtResultDatatable != null && dtResultDatatable.Rows.Count > 0)
            {
                for (int intRowIndex = 0; intRowIndex < dtResultDatatable.Rows.Count; intRowIndex++)
                {
                    strChapterId.Append(Convert.ToString(dtResultDatatable.Rows[intRowIndex][IDCOLUMN]));
                    strChapterId.Append(";");
                }
                objCommonBLL = new CommonBLL();
                strCAMLQuery = objCommonBLL.CreateCAMLQuery(strChapterId.ToString(), "Chapter_ID", "Number", "Owner");
                if (string.IsNullOrEmpty(CAMLQuery))
                    return listItemCollection;
                dtResultDatatable = objCommonDAL.ReadList(siteURL, CHAPTERPAGESMAPPINGLIST, strCAMLQuery);
                if (dtResultDatatable != null && dtResultDatatable.Rows.Count > 0)
                {
                    listItemCollection = new Dictionary<string, string>();

                    for (int intRowIndex = 0; intRowIndex < dtResultDatatable.Rows.Count; intRowIndex++)
                    {

                        if ((!listItemCollection.ContainsValue(Convert.ToString(dtResultDatatable.Rows[intRowIndex]["Owner"]))
                            && (!string.IsNullOrEmpty(Convert.ToString(dtResultDatatable.Rows[intRowIndex]["Owner"])))))
                        {
                            listItemCollection.Add(Convert.ToString(dtResultDatatable.Rows[intRowIndex][IDCOLUMN]), Convert.ToString(dtResultDatatable.Rows[intRowIndex]["Owner"]));
                        }
                    }
                }

            }
            if (dtResultDatatable != null)
            {
                dtResultDatatable.Dispose();
            }
            return listItemCollection;
        }
 public void ValueExists()
 {
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     dictionary["one"] = "uno";
     Assert.Equal(true, dictionary.ContainsValue("uno"));
     Assert.Equal(false, dictionary.ContainsValue("dos"));
 }
示例#24
0
        /// <summary>
        /// Get Pages for the selected Owner
        /// Modified By: Praveena  
        /// Date:03/09/2010
        /// Reason: For module Add additional attributes to change page owner table
        /// </summary>
        /// <param name="siteURL">Site URL.</param>
        /// <param name="listName">List Name.</param>
        /// <param name="queryString">CAML Query.</param>     
        /// <param name="username">Windows User ID of the selected Owner</param>
        /// <returns>DataTable</returns>
        public DataTable GetPagesForOwner(string siteURL, string listName, string CAMLQuery, string username, string pageName, string terminatedStatus, System.Text.StringBuilder chapterNames)
        {
            string strViewFields = string.Empty;
            strViewFields = @"<FieldRef Name='ID' /><FieldRef Name='Title' />";
            DataTable dtResultDatatable = null;
            DataView dvresultdataview = null;
            string strCAMLQuery = string.Empty;
            StringBuilder strChapterId = new StringBuilder();
            Dictionary<string, string> listItemCollection = null;
            objCommonDAL = new CommonDAL();
            dtResultDatatable = objCommonDAL.ReadList(siteURL, listName, CAMLQuery, strViewFields);
            if (dtResultDatatable != null && dtResultDatatable.Rows.Count > 0)
            {
                listItemCollection = new Dictionary<string, string>();
                for (int intRowIndex = 0; intRowIndex < dtResultDatatable.Rows.Count; intRowIndex++)
                {
                    strChapterId.Append(Convert.ToString(dtResultDatatable.Rows[intRowIndex][IDCOLUMN]));
                    strChapterId.Append(";");
                    if ((!listItemCollection.ContainsValue(Convert.ToString(dtResultDatatable.Rows[intRowIndex][TITLECOLUMN]))
                        && (!string.IsNullOrEmpty(Convert.ToString(dtResultDatatable.Rows[intRowIndex][TITLECOLUMN])))))
                    {
                        listItemCollection.Add(Convert.ToString(dtResultDatatable.Rows[intRowIndex][IDCOLUMN]), Convert.ToString(dtResultDatatable.Rows[intRowIndex][TITLECOLUMN]));
                    }
                }
                objCommonBLL = new CommonBLL();
                strCAMLQuery = objCommonBLL.CreateCAMLQuery(strChapterId.ToString(), CHAPTERIDCOLUMN, "Number");
                strViewFields = "<FieldRef Name='Connection_Type' /><FieldRef Name='Page_Name' /><FieldRef Name='Discipline' /><FieldRef Name='Owner' /><FieldRef Name='Empty' /><FieldRef Name='Sign_Off_Status' /><FieldRef Name='Chapter_ID' /><FieldRef Name='Terminate_Status' />";
                dtResultDatatable = objCommonDAL.ReadList(siteURL, CHAPTERPAGESMAPPINGLIST,
                   strCAMLQuery, strViewFields);

                if (dtResultDatatable != null && dtResultDatatable.Rows.Count > 0)
                {
                    Dictionary<string, string> ChapterDetails = listItemCollection;
                    DataColumn dcChapterName = dtResultDatatable.Columns.Add(CHAPTERNAMECOLUMN, typeof(string));
                    string str = string.Empty;
                    foreach (DataRow dtRow in dtResultDatatable.Rows)
                    {
                        if (ChapterDetails.ContainsKey(dtRow[CHAPTERIDCOLUMN].ToString()))
                        {
                            ChapterDetails.TryGetValue(dtRow[CHAPTERIDCOLUMN].ToString(), out str);
                            dtRow[CHAPTERNAMECOLUMN] = str;
                        }
                    }
                    dvresultdataview = dtResultDatatable.DefaultView;
                    //to apply filters to dataview
                    dvresultdataview = ApplyFilters(dvresultdataview, username, pageName, chapterNames, terminatedStatus);
                }
            }
            if (dvresultdataview != null)
            {
                return dvresultdataview.Table;
            }
            else
            {
                return dtResultDatatable;
            }
        }
示例#25
0
		public void ZeroCapacity ()
		{
			Dictionary<int, int> x = new Dictionary <int, int> (0);
			x.Add (1, 2);
			
			x = new Dictionary <int, int> (0);
			x.Clear ();

			x = new Dictionary <int, int> (0);
			int aa = x.Count;
			
			x = new Dictionary <int, int> (0);
			try {
				int j = x [1];
			} catch (KeyNotFoundException){
			}

			bool b;
			b = x.ContainsKey (10);
			b = x.ContainsValue (10);

			x = new Dictionary <int, int> (0);
			x.Remove (10);
			
			x = new Dictionary <int, int> (0);
			int intv;
			x.TryGetValue (1, out intv);

			object oa = x.Keys;
			object ob = x.Values;
			foreach (KeyValuePair<int,int> a in x){
			}
		}
示例#26
0
		/// <summary>
		/// Get the LangCode from the Database.ssf file and insert it in css file
		/// </summary>
		public static string ParaTextDcLanguage(string dataBaseName, bool hyphenlang)
		{
			string dcLanguage = string.Empty;
			if (AppDomain.CurrentDomain.FriendlyName.ToLower() == "paratext.exe") // is paratext00
			{
				// read Language Code from ssf
				SettingsHelper settingsHelper = new SettingsHelper(dataBaseName);
				string fileName = settingsHelper.GetSettingsFilename();
				string xPath = "//ScriptureText/EthnologueCode";
				XmlNode xmlLangCode = GetXmlNode(fileName, xPath);
				if (xmlLangCode != null && xmlLangCode.InnerText != string.Empty)
				{
					dcLanguage = xmlLangCode.InnerText;
				}
				xPath = "//ScriptureText/Language";
				XmlNode xmlLangNameNode = GetXmlNode(fileName, xPath);
				if (xmlLangNameNode != null && xmlLangNameNode.InnerText != string.Empty)
				{
					if (dcLanguage == string.Empty)
					{
						Dictionary<string, string> _languageCodes = new Dictionary<string, string>();
						_languageCodes = LanguageCodesfromXMLFile();
						if (_languageCodes.Count > 0)
						{
							foreach (
								var languageCode in
									_languageCodes.Where(
										languageCode => languageCode.Value.ToLower() == xmlLangNameNode.InnerText.ToLower()))
							{
								if (hyphenlang)
								{
									dcLanguage = _languageCodes.ContainsValue(languageCode.Key.ToLower())
										? _languageCodes.FirstOrDefault(x => x.Value == languageCode.Key.ToLower()).Key
										: languageCode.Key;
								}
								else
								{
									dcLanguage = languageCode.Key;
								}
								break;
							}
						}
					}
					dcLanguage += ":" + xmlLangNameNode.InnerText;
				}
			}
			return dcLanguage;
		}
示例#27
0
    protected void OldOpenDatabase(string filename)
    {
      string tableName = "Species";

      OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename);
      conn.Open();
      //Putting things in Try {} Catch{} is the worst form of flow control, or so they say.
      //But there seems no other option
      DataTable t = new DataTable();
      OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " + tableName, conn);
      da.FillSchema(t, SchemaType.Source);

      #region Change column layout to what is expected:
      Dictionary<string, string> Remapping = new Dictionary<string, string>(); //<To, From>
      List<string> NewColumns = new List<string>();

      //Check for any columns that must be renamed:
      foreach (DataColumn c in t.Columns)
        if (c.ColumnName == "Rho")
          Remapping.Add("Density", "Rho");
        else if (c.ColumnName == "dHf")
          Remapping.Add("Hf25", "dHf");
        else if (c.ColumnName == "S°298")
          Remapping.Add("S25", "S°298");
      //Check for any columns that must be added
      foreach (string s in ReqColumnList)
        if (!t.Columns.Contains(s) && !Remapping.ContainsKey(s))
          NewColumns.Add(s);


      OleDbCommand cmd = new OleDbCommand();
      cmd.Connection = conn;
      if (NewColumns.Count > 0)
      {
        for (int i = 0; i < NewColumns.Count; i++)
        {
          if (NewColumns[i] == "Ts" || NewColumns[i] == "Te")
            cmd.CommandText = "ALTER TABLE " + tableName + " ADD " + NewColumns[i] + " single;";
          else
            cmd.CommandText = "ALTER TABLE " + tableName + " ADD " + NewColumns[i] + " varchar;";
          cmd.ExecuteNonQuery();
        }
      }
      if (Remapping.Count > 0)
      {
        foreach (KeyValuePair<string, string> kvp in Remapping)
        {
          cmd.CommandText = "ALTER TABLE " + tableName + " ADD COLUMN " + kvp.Key + " varchar;";
          cmd.ExecuteNonQuery();
        }
        StringBuilder sb = new StringBuilder("UPDATE " + tableName + " SET ");
        int j = 0;
        foreach (KeyValuePair<string, string> kvp in Remapping)
        {
          sb.Append(kvp.Key + " = " + kvp.Value);
          if (j++ != Remapping.Count - 1)
            sb.Append(", ");
        }
        sb.AppendLine(";");
        cmd.CommandText = sb.ToString();
        cmd.ExecuteNonQuery();
        /*foreach (KeyValuePair<string, string> kvp in Remapping)
        {
            cmd.CommandText = "UPDATE " + tableName + " SET " + kvp.Key + " = " + kvp.Value;
            cmd.ExecuteNonQuery();
        }*/

        foreach (KeyValuePair<string, string> kvp in Remapping)
        {
          cmd.CommandText = "ALTER TABLE " + tableName + " DROP COLUMN " + kvp.Value + ";";
          cmd.ExecuteNonQuery();
        }
      }
      #endregion Column Layout

      #region Check Constraints:
      List<DataColumn> PK = new List<DataColumn>(t.PrimaryKey);
      if (t.PrimaryKey.Length == 0) //If we need to remove or change the primary key...
      {
        cmd.CommandText = "ALTER TABLE " + tableName + " ADD CONSTRAINT pk PRIMARY KEY(Compound, Phase, Ts, Te)";
        cmd.ExecuteNonQuery();
      }

      foreach (DataColumn c in t.Columns)
        if (c.DataType == typeof(string) && !Remapping.ContainsValue(c.ColumnName))
        {
          cmd.CommandText = "ALTER TABLE " + tableName + " ALTER COLUMN " + c.ColumnName + " varchar(255)";
          cmd.ExecuteNonQuery();
        }

      /*Dictionary<string, string> RequiredConstraints = new Dictionary<string, string>();
      //RequiredConstraints.Add("Occ_gls", "CHECK (Occurence IN ('g', 'l', 's', 'G', 'L', 'S'))");
      RequiredConstraints.Add("Tgt0", "CHECK (Ts > 0 and Te > 0)"); //We're not going to force Te > Ts, but rather allow the user to make the change...
      foreach (string s in RequiredConstraints.Keys)
          if (!t.Constraints.Contains(s))
          {
              cmd.CommandText = "ALTER TABLE " + tableName + " ADD CONSTRAINT " + s + " " + RequiredConstraints[s];
              cmd.ExecuteNonQuery();
          }*/
      //It seems that it really doesn't like these constraints for an unkown reason.


      #endregion Check Constraints

      m_SpecieDataAdapter = new OleDbDataAdapter("SELECT * FROM " + tableName, conn);

      m_SpecieDataTable.Clear();
      m_SpecieDataAdapter.FillSchema(m_SpecieDataTable, SchemaType.Source);
      m_SpecieDataAdapter.Fill(m_SpecieDataTable);

      new OleDbCommandBuilder(m_SpecieDataAdapter);

      #region Commented Out Code
      //Alternative (2-table) method:
      /*
      try
      {
          m_SpecieDataAdapter = new OleDbDataAdapter("SELECT * FROM Species2", conn);

          m_SpecieDataAdapter.Fill(m_SpecieDataTable);

          new OleDbCommandBuilder(m_SpecieDataAdapter);
      }
      catch
      {
          m_SpecieDataAdapter = new OleDbDataAdapter("SELECT * FROM " + tableName, conn);

          DataTableMapping mapping = m_SpecieDataAdapter.TableMappings.Add("Table", "" + tableName);
          mapping.ColumnMappings.Add("Rho", "Density");
          mapping.ColumnMappings.Add("dHf", "Hf25");
          mapping.ColumnMappings.Add("S°298", "S25");

          OleDbCommandBuilder cb = new OleDbCommandBuilder(m_SpecieDataAdapter);

          DataTable intermediate = m_SpecieDataTable.Clone();
          m_SpecieDataAdapter.Fill(intermediate);
          foreach (DataRow r in intermediate.Rows)
              m_SpecieDataTable.ImportRow(r);

          MergeRows();

          CreateNewTable(conn);

          m_SpecieDataAdapter.SelectCommand = new OleDbCommand("SELECT * FROM Species2", conn);

          SaveDatabase();
      }*/
      #endregion Commented Out Code

      MergeRows();

      SaveDatabase();

      //After we have merged the variables, we no longer need to have a 4 column primary key (Ts and Te can be removed).
      m_SpecieDataTable.PrimaryKey = new DataColumn[] { m_SpecieDataTable.Columns["Compound"], m_SpecieDataTable.Columns["Phase"] };
      cmd.CommandText = "ALTER TABLE " + tableName + " DROP CONSTRAINT pk"; cmd.ExecuteNonQuery();
      cmd.CommandText = "ALTER TABLE " + tableName + " ADD CONSTRAINT pk PRIMARY KEY(Compound, Phase)"; cmd.ExecuteNonQuery();

      UpdateFilter();
      conn.Close();

      //Create a dummy row to prevent any sort of errors...
      if (m_SpecieDataTable.Rows.Count == 0)
      {
        CreateSpecies();
        //tcSpecies.SelectedTab = tabDatabase;
      }

      //specieDatabaseControl1.DatabaseChanged();
    }
            // Add any missing KnownType (According to DataContractSerializer).
            private void EnsureKnownTypes(Dictionary<string, Type> availableTypes)
            {
                Type target = typeof(object);
                if (!availableTypes.ContainsValue(target))
                {
                    LoadTypes(availableTypes, target.Assembly.GetExportedTypes());
                }

                target = typeof(System.Guid);
                if (!availableTypes.ContainsValue(target))
                {
                    LoadTypes(availableTypes, target.Assembly.GetExportedTypes());
                }

                target = typeof(System.Xml.XmlQualifiedName);
                if (!availableTypes.ContainsValue(target))
                {
                    LoadTypes(availableTypes, target.Assembly.GetExportedTypes());
                }
            }
示例#29
0
 // Simple helper to ease maintenance and improve readability.
 private static void AddResourceSet(Dictionary<String,ResourceSet> localResourceSets, String cultureName, ref ResourceSet rs)
 {
     // InternalGetResourceSet is both recursive and reentrant - 
     // assembly load callbacks in particular are a way we can call
     // back into the ResourceManager in unexpectedly on the same thread.
     lock(localResourceSets) {
         // If another thread added this culture, return that.
         ResourceSet lostRace;
         if (localResourceSets.TryGetValue(cultureName, out lostRace)) {
             if (!Object.ReferenceEquals(lostRace, rs)) {
                 // Note: In certain cases, we can be trying to add a ResourceSet for multiple
                 // cultures on one thread, while a second thread added another ResourceSet for one
                 // of those cultures.  If there is a race condition we must make sure our ResourceSet 
                 // isn't in our dictionary before closing it.
                 if (!localResourceSets.ContainsValue(rs))
                     rs.Dispose();
                 rs = lostRace;
             }
         }
         else {
             localResourceSets.Add(cultureName, rs);
         }
     }
 }
        public void GetSDKVersions()
        {
            try
            {
                Environment.SetEnvironmentVariable("MSBUILDSDKREFERENCEDIRECTORY", s_fakeSDKStructureRoot + ";" + s_fakeSDKStructureRoot2);
                Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", "true");
                MockEngine engine = new MockEngine();
                GetInstalledSDKLocations t = new GetInstalledSDKLocations();
                t.TargetPlatformIdentifier = "Windows";
                t.TargetPlatformVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue).ToString();
                t.SDKRegistryRoot = "Somewhere";
                t.SDKRegistryRoot = "Hello;Jello";
                t.BuildEngine = engine;
                bool success = t.Execute();
                Assert.IsTrue(success);

                ITaskItem[] installedSDKs = t.InstalledSDKs;
                Assert.IsTrue(installedSDKs.Length == 6);

                Dictionary<string, string> sdksAndVersions = new Dictionary<string, string>();

                foreach (ITaskItem item in installedSDKs)
                {
                    sdksAndVersions.Add(item.GetMetadata("SDKName"), item.GetMetadata("PlatformVersion"));
                }

                Assert.IsTrue(sdksAndVersions["MyAssembly, Version=1.0"] == "1.0");
                Assert.IsTrue(sdksAndVersions["MyAssembly, Version=2.0"] == "1.0");
                Assert.IsTrue(sdksAndVersions["MyAssembly, Version=3.0"] == "2.0");
                Assert.IsTrue(sdksAndVersions["MyAssembly, Version=4.0"] == "1.0");
                Assert.IsTrue(sdksAndVersions["MyAssembly, Version=5.0"] == "1.0");
                Assert.IsTrue(sdksAndVersions["MyAssembly, Version=6.0"] == "2.0");

                Assert.IsFalse(sdksAndVersions.ContainsValue("3.0"));
                Assert.IsFalse(sdksAndVersions.ContainsValue("4.0"));
            }
            finally
            {
                Environment.SetEnvironmentVariable("MSBUILDSDKREFERENCEDIRECTORY", null);
                Environment.SetEnvironmentVariable("MSBUILDDISABLEREGISTRYFORSDKLOOKUP", null);
            }
        }