public XmlRpcStruct[] returnKeyMap2()
 {
     Console.WriteLine("Hashmap request");
     Dictionary<int, String> machines = new Dictionary<int, String>();
     machines.Add(1, "test1");
     machines.Add(3, "test3");
     Console.WriteLine("Machines number now " + machines.Count());
     XmlRpcStruct[] test = ConvertDictionaryToStruct(machines);
     return test;
 }
 public XmlRpcStruct[] returnKeyMap(String ipAddress, int priority)
 {
     Console.WriteLine("Hashmap request from ip " + ipAddress + " with priority " + priority);
     Dictionary<int, String> machines = new Dictionary<int, String>();
     machines.Add(1, "test1");
     machines.Add(3, "test3");
     Console.WriteLine("Machines number now " + machines.Count());
     XmlRpcStruct[] test = ConvertDictionaryToStruct(machines);
     return test;
 }
Esempio n. 3
0
 public bool Multi_Reg_Check()
 {
     Dictionary<string, string> depDic = new Dictionary<string, string>();
     if (ViewState["dict"] != null)
     { depDic = (Dictionary<string, string>)ViewState["dict"]; }
     if (depDic.Count > 0 && depDic.Values.Contains("d") && depDic.Count(D=>D.Value.Contains("i")) >= 2)
     {
         return true;
     }
     return false;
 }
    private XmlRpcStruct[] ConvertDictionaryToStruct(Dictionary<int, string> dict)
    {
        XmlRpcStruct[] convertionResult = new XmlRpcStruct[dict.Count()];
        for (int i = 0; i < dict.Count; i++)
        {
            convertionResult[i] = new XmlRpcStruct();
            convertionResult[i].Add("NetworkPriority", dict.Keys.ElementAt(i));
            convertionResult[i].Add("IpAddress", dict.Values.ElementAt(i));
        }

        return convertionResult;
    }
Esempio n. 5
0
		static JointState()
		{
			NamesToJoints = new Dictionary<string, int>() {
				{"neck", 0},
				{"head", 1},
				{"right-shoulder", 2},
				{"left-shoulder", 6},
				{"right-elbow", 3},
				{"left-elbow", 7},
				{"right-wrist", 4},
				{"right-pelvis", 18},
				{"left-pelvis", 19},
				{"left-wrist", 8},
				{"right-palm", 5},
				{"right-hip", 10},
				{"left-hip", 14},
				{"left-palm", 9},
				{"right-knee", 11},
				{"left-knee", 15},
				{"right-ankle", 12},
				{"right-foot", 13},
				{"left-ankle", 16},
				{"left-foot", 17}
			};
			
			JointParents = new List<int>() { -1, // Neck
				0, // Head
				0, 2, 3, 4,
				0, 6, 7, 8,
				18, 10, 11, 12,
				19, 14, 15, 16,
				0, 0
			};
			
			// Sanity check
			foreach ( var nj in NamesToJoints ) {
				var c = NamesToJoints.Count(x => (x.Value == nj.Value));
				if ( c > 1 ) throw new Exception("Duplicate joints in relative joint name list!");
			}
			
			foreach ( var jp in JointParents ) {
				// TODO: check that there are no cycles here
			}
		}
Esempio n. 6
0
        public id3( id3 _padre, List<string[]> _baseConocimiento, 
            Dictionary<string, Tuple<int, Dictionary<string, int>>>[] _dominio,string[] _att_name, string _value, int _colRes)
        {
            att_elegido = "";
            value_att = _value;
            resultado = "";
            default_value = _padre.default_value;
            colRes = _colRes;
            att_name = _att_name;
            baseConocimiento = _baseConocimiento;
            hijos = new List<id3>();
            nAtt = _padre.nAtt - 1;
            dominio = _dominio;
            for(int i = 0; i < dominio.Count(); i++)
            {
                //foreach(var keyAtt in dominio[i].Keys)
                for(int index2 = 0; index2 < dominio[i].Keys.Count(); index2++)
                {
                    var _name = dominio[i].Keys.ElementAt(index2);
                    var keyAtt = dominio[i][_name].Item2.Keys;
                    //foreach(var key in dominio[i][keyAtt].Item2.Keys)
                    for (int j = 0; j < keyAtt.Count(); j++)
                    {
                        
                        var _qwe = keyAtt.ElementAt(j);
                        dominio[i][_name].Item2[_qwe] = 0;
                    }
                    dominio[i][_name] = Tuple.Create(0, dominio[i][_name].Item2);
                }

            }

            var k = 0;
            foreach(var ej in baseConocimiento)
            {
                dominio[k][ej[k]].Item2[ej[colRes]]++;
                dominio[k][ej[k]] = Tuple.Create(dominio[k][ej[k]].Item1 + 1, dominio[k][ej[k]].Item2);
                k++;
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            foreach (String name in Directory.GetFiles(_picturesDirectory, "*.jpg"))
                _knownNames.Add(name);

            Dictionary<DateTime, string> nameDic = new Dictionary<DateTime, string>();
            foreach (String name in _knownNames)
                nameDic.Add(Directory.GetCreationTime(name), name);

            var lastime = nameDic.Count() > 0 ? nameDic.Last().Key : DateTime.Now;

            StreamReader r = new StreamReader(_picturesDirectory +  "\\list.txt");
            String line;
            while ((line = r.ReadLine()) != null)
            {
                nameDic.Add(lastime, line);
                lastime = lastime.AddSeconds(1);
            }

            foreach (var item in nameDic.OrderByDescending(x=>x.Key))
                FindFollowers(
                    String.Format("https://api.twitter.com/1/followers/ids.json?screen_name=@{0}", Path.GetFileNameWithoutExtension(item.Value)));
        }
Esempio n. 8
0
        private void UpdateDbConditionNameList(String strConditionNameList)
        {
            FileLog.PrintF("UpdateDbConditionNameList strConditionNameList=>" + strConditionNameList);
            /*strConditionNameList==> 비고 조건명 리스트를 구분(“;”)하여 받아온다.Ex) 인덱스1 ^ 조건명1; 인덱스2 ^ 조건명2; 인덱스3 ^ 조건명3;…*/

            String lastChar = strConditionNameList.Substring(strConditionNameList.Count() - 1, 1);
            if (lastChar.Equals(";"))//마지막글자가 ; 이거이면 빈 배열공간이 하나 더생기므로 마지막 ; 이것이면 삭제
            {
                strConditionNameList = strConditionNameList.Substring(0, strConditionNameList.Count() - 1);
            }
            String[] tmp=strConditionNameList.Split(';');
            Dictionary<int, String> conditionNameList = new Dictionary<int, String>();
            for(int i = 0; i < tmp.Count(); i++)
            {
                String[] strTmp = tmp[i].Split('^');

                FileLog.PrintF("UpdateDbConditionNameList nIndex=>" + strTmp[0]);
                FileLog.PrintF("UpdateDbConditionNameList conditionName=>" + strTmp[1]);

                int nIndex = int.Parse(strTmp[0].Trim());
                String conditionName = strTmp[1];
                conditionNameList.Add(nIndex, conditionName);
            }
            try
            {
                using (MySqlConnection conn = new MySqlConnection(Config.GetDbConnStr()))
                {
                    String sql1 = "DELETE FROM condition_names;";
                    conn.Open();
                    MySqlTransaction tr = conn.BeginTransaction();
                    String dayTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    try
                    {
                        MySqlCommand cmd = new MySqlCommand(sql1, conn, tr);
                        cmd.ExecuteNonQuery();
                        string sql2 = @"INSERT INTO condition_names (
condition_name  
,nIndex
,created_at
,updated_at
)
VALUES";
                        String sql2_1 = @"
(
@조건이름{0}
,@인덱스{0}
,@등록날짜{0}
,@업데이트날짜{0}
),";
                        StringBuilder queryBuilder = new StringBuilder(sql2);
                        for (int i = 0; i < conditionNameList.Count(); i++)
                        {
                            queryBuilder.AppendFormat(sql2_1, i);
                            //once we're done looping we remove the last ',' and replace it with a ';'
                            if (i == conditionNameList.Count() - 1)
                            {
                                queryBuilder.Replace(',', ';', queryBuilder.Length - 1, 1);
                            }
                        }
                        String sql2_2 = queryBuilder.ToString();
                        FileLog.PrintF("UpdateDbConditionNameList sql2_2:" + sql2_2.ToString());
                        cmd.CommandText = sql2_2;
                        int j = 0;
                        foreach (var h in conditionNameList)
                        {
                            cmd.Parameters.AddWithValue("@조건이름" + j, h.Value); //[0]
                            cmd.Parameters.AddWithValue("@인덱스" + j, h.Key); //[1]
                            cmd.Parameters.AddWithValue("@등록날짜" + j, dayTime); //[2]
                            cmd.Parameters.AddWithValue("@업데이트날짜" + j, dayTime); //[3]
                            j++;
                        }                          
                        cmd.ExecuteNonQuery();
                        tr.Commit();

                    }
                    catch (MySqlException ex2)
                    {
                        try
                        {
                            tr.Rollback();

                        }
                        catch (MySqlException ex1)
                        {
                            FileLog.PrintF("UpdateDbConditionNameList1 Error:" + ex1.ToString());
                        }
                        FileLog.PrintF("UpdateDbConditionNameList2 Error:" + ex2.ToString());

                    }
                }
            }
            catch (MySqlException ex3)
            {
                FileLog.PrintF("UpdateDbConditionNameList3 Error:" + ex3.ToString());
            }
        }
        public NamespaceAttributes UpdateNamespace(string resourceGroupName, string namespaceName, string location, NamespaceState state, bool critical, Dictionary<string, string> tags)
        {
            var parameter = new NamespaceCreateOrUpdateParameters()
                {
                    Location = location,
                    Properties = new NamespaceProperties()
                    {
                        NamespaceType = NamespaceType.NotificationHub,
                        Status = ((state == NamespaceState.Disabled) ? state : NamespaceState.Active).ToString(),
                        Enabled = (state == NamespaceState.Disabled ) ? false:true
                    }
                };
            
            if (critical)
            {
                parameter.Properties.Critical = critical;
            }

            if (tags != null && tags.Count() > 0)
            {
                parameter.Tags = new Dictionary<string, string>(tags);
            }

            var response = Client.Namespaces.CreateOrUpdate(resourceGroupName, namespaceName, parameter);
            return new NamespaceAttributes(resourceGroupName, response.Value);
        }
Esempio n. 10
0
        public void Training2(Dictionary<double[], int> Examples)
        {
            double Error= 5;
            int Iteraciones = 0;
            StreamWriter stream = System.IO.File.CreateText("Log_Training_" + Neuronas_Ocultas + "_" + Max_Iteracion + ".txt");

            while (Error > 0.3 && Iteraciones < Max_Iteracion)
            {
                Error = 0;
                Iteraciones++;
                foreach (var E in Examples)
                {

                    // Calcular la salida de la red (a)
                    List<Nodo> Aux = NN.GetLayer(0); //Layer de Entrada
                    for (int j = 1; j < Aux.Count; j++)
                        Aux[j].a = E.Key[j - 1];
                    Aux[0].a = 1;

                    for (int j = 1; j < NN.N_Layar(); j++)
                        foreach (Nodo i in NN.GetLayer(j))
                        {
                            double Sum = 0;
                            foreach (Arco A in NN.GetArcs(i))
                                Sum += A.W * A.Ini.a;
                            i.In = Sum;
                            i.a = g(i.In);
                        }

                    //Para cada unidad de Salida k
                    foreach (Nodo k in NN.GetLayer(NN.N_Layar() - 1))
                    {
                        Error += (E.Value - k.a) * (E.Value - k.a);
                        k.delta = k.a * (1 - k.a) * (E.Value - k.a);
                    }

                    // Por cada Unidad Oculta h
                    for (int l = 1 ; l < NN.N_Layar() - 1; l++)
                        foreach (Nodo h in NN.GetLayer(l))
                        {
                            double Sum = 0;
                            foreach (Arco A in NN.GetArcsInv(h))
                                Sum += A.W * A.Fin.delta;
                            h.delta = h.a * ( 1 - h.a ) * Sum;
                        }

                    //Actualizar cada peso de la red (W)
                    for (int j = 1; j < NN.N_Layar(); j++)
                        foreach (Nodo i in NN.GetLayer(j))
                            foreach (Arco A in NN.GetArcs(i))
                                A.W += Ta * A.Fin.delta * A.Ini.a;
                }
                Error /= Examples.Count();
                Error = Math.Sqrt(Error);
                stream.WriteLine(Error);
            }
            stream.Close();
        }
Esempio n. 11
0
        public void Training(Dictionary<double[], int> Examples)
        {
            double Error;
            int Iteraciones = 0;

            StreamWriter stream = System.IO.File.CreateText("Log_Training_"+Neuronas_Ocultas+"_"+Max_Iteracion+".txt");

            do
            {
                Iteraciones++;
                Error = 0;
                foreach (var E in Examples)
                {

                    // ForwardPropagate
                    List<Nodo> Aux = NN.GetLayer(0); //Layer de Entrada
                    for (int j = 1; j < Aux.Count; j++)
                        Aux[j].a = E.Key[j - 1];
                    Aux[0].a = 1;

                    for (int j = 1; j < NN.N_Layar(); j++)
                        foreach (Nodo i in NN.GetLayer(j))
                        {
                            double Sum = 0;
                            foreach (Arco A in NN.GetArcs(i))
                                Sum += A.W * A.Ini.a;
                            i.In = Sum;
                            i.a = g(i.In);
                        }

                    foreach (Nodo i in NN.GetLayer(NN.N_Layar() - 1))
                    {

                        Error += (E.Value - i.a) * (E.Value - i.a);
                        i.delta = dg(i.In) * (E.Value - i.a);

                    }

                    //BackPropagate
                    for (int l = NN.N_Layar() - 2; l >= 0; l--)
                        foreach (Nodo j in NN.GetLayer(l))
                        {
                            double Sum = 0;
                            foreach (Arco A in NN.GetArcsInv(j))
                                Sum += A.W * A.Fin.delta;
                            j.delta = dg(j.In) * Sum;

                            foreach (Arco A in NN.GetArcsInv(j))
                                A.W += Ta * j.a * A.Fin.delta;
                        }

                }
                Error /= Examples.Count();
                Error = Math.Sqrt(Error);

                stream.WriteLine(Error);
            } while (Error > 0.84 && Iteraciones < Max_Iteracion);

            stream.Close();
        }
Esempio n. 12
0
 public String checkSingleRowOperationInverseQuestion(Dictionary<int, float[,]> matrixMap)
 {
     String feedback = "";
     for (int i = 0; i < matrixMap.Count()-1; i++)
     {
         float[,] matrix1 = null;
         matrixMap.TryGetValue(i, out matrix1);
         float[,] matrix2 = null;
         matrixMap.TryGetValue(i + 1, out matrix2);
         if (checkMatrixEquality(matrix1, matrix2))
         {
             feedback += "<div>No row operation between matrix " + i + " and matrix " + (i + 1) + ".<div>";
         }
         else if (!checkAddMultipleOfRow(matrix1, matrix2) && !checkTimesScalar(matrix1, matrix2)
               && !checkRowSwap(matrix1, matrix2))
         {
             feedback += "<div>Mistake between matrix " + i + " and matrix " + (i + 1) + ".<div>";
         }
     }
     return feedback.Equals("") ? null : feedback;
 }
Esempio n. 13
0
 public ActionResult UploadAttach_ysd()
 {
     try
     {
         供应商 model = 用户管理.查找用户<供应商>(currentUser.Id);
         Dictionary<string, List<string>> url = new Dictionary<string, List<string>>();
         List<string> str = new List<string>();
         bool exist = false;
         if (model.历史投标补充资料 != null && model.历史投标补充资料.Count() != 0)
         {
             url = model.历史投标补充资料;
         }
         string name = "";
         if (Request.Form["picture"] != null)
         {
             name = Request.Form["picture"].ToString();
         }
         //long id = 0;
         string which = "";
         if (Request.Form["which"] != null)
         {
             which = Request.Form["which"].ToString();
         }
         string path = "";
         for (int j = 0; j < Request.Files.Count; j++)
         {
             HttpPostedFileBase fileData = Request.Files[j];
             string filePath = 上传管理.获取上传路径<验收单>(媒体类型.附件, 路径类型.不带域名根路径);
             string fname = UploadImages_Ysd(fileData);
             path += filePath + fname + "|";
             ViewData["path"] = path;
             ViewData["which"] = which;
             str.Add(filePath + fname);
         }
         if (!string.IsNullOrWhiteSpace(name))
         {
             if (str.Count() != 0)
             {
                 if (url.Count() != 0)
                 {
                     foreach (var i in url)
                     {
                         if (i.Key == name)
                         {
                             exist = true;
                             break;
                         }
                     }
                     if (!exist)
                     {
                         url.Add(name, str);
                     }
                     else
                     {
                         foreach (var m in str)
                         {
                             url[name].Add(m);
                         }
                     }
                 }
                 else
                 {
                     url.Add(name, str);
                 }
                 model.历史投标补充资料 = url;
             }
             用户管理.更新用户<供应商>(model);
         }
     }
     catch
     {
         ViewData["path"] = "出错|";
     }
     return View();
 }
Esempio n. 14
0
        private bool settleAccount(IClientDepartureInstruction instruction)
        {
            bool mgtFeeCharged = false;
            instruction.Message = "";

            if (instruction.CounterAccount == null)
            {
                instruction.Message = "Could not settle the account, look up the counter account.";
                return false;
            }

            IManagementPeriod managementPeriod = instruction.Account.CurrentManagementFeePeriod;
            if (managementPeriod != null)
            {
                IList<IManagementPeriodUnit> unitsNotCharged = managementPeriod.ManagementPeriodUnits
                    .Where(x => x.ManagementFee == null)
                    .OrderByDescending(x => x.StartDate)
                    .ToList();

                Dictionary<int, Tuple<int, int>> quarterYears = new Dictionary<int, Tuple<int, int>>();
                if (unitsNotCharged != null && unitsNotCharged.Count > 0)
                {
                    BatchExecutionResults results = new BatchExecutionResults();
                    IManagementPeriodUnit lastUnit = unitsNotCharged.FirstOrDefault();
                    if (lastUnit != null && lastUnit.EndDate.Equals(managementPeriod.EndDate))
                    {
                        // get all quarter periods not yet charged
                        foreach (IManagementPeriodUnit unit in unitsNotCharged)
                        {
                            Tuple<int, int> quarterYear = new Tuple<int, int>(Util.GetQuarter(unit.EndDate), unit.EndDate.Year);
                            int key = quarterYear.Item2 * 100 + quarterYear.Item1;
                            if (!quarterYears.ContainsKey(key))
                                quarterYears.Add(key, quarterYear);
                        }

                        if (quarterYears.Count() == 0)
                        {
                            instruction.Message = "Could not charge management fee.";
                            return false;
                        }
                        else if (quarterYears.Count() == 1)
                        {
                            mgtFeeCharged = ManagementFeeOverviewAdapter.CreateMgtFeeTransactions(results, new int[] { lastUnit.ManagementPeriod.Key }, quarterYears.Values.First().Item2, quarterYears.Values.First().Item1, B4F.TotalGiro.Accounts.ManagementPeriods.ManagementTypes.ManagementFee, false);
                        }
                        else if (quarterYears.Count() > 1)
                        {
                            // Only charge last 2
                            // check if last 2 are chronological
                            int maxItemKey = quarterYears.Keys.OrderByDescending(x => x).ElementAt(0);
                            int prevItemKey = quarterYears.Keys.OrderByDescending(x => x).ElementAt(1);
                            Tuple<int, int> maxQuarterYear = quarterYears[maxItemKey];
                            if (Util.GetPreviousQuarterYear(maxQuarterYear.Item1, maxQuarterYear.Item2).Equals(quarterYears[prevItemKey]))
                                ManagementFeeOverviewAdapter.CreateMgtFeeTransactions(results, new int[] { lastUnit.ManagementPeriod.Key }, quarterYears[prevItemKey].Item2, quarterYears[prevItemKey].Item1, B4F.TotalGiro.Accounts.ManagementPeriods.ManagementTypes.ManagementFee, false);

                            mgtFeeCharged = ManagementFeeOverviewAdapter.CreateMgtFeeTransactions(results, new int[] { lastUnit.ManagementPeriod.Key }, quarterYears[maxItemKey].Item2, quarterYears[maxItemKey].Item1, B4F.TotalGiro.Accounts.ManagementPeriods.ManagementTypes.ManagementFee, false);
                        }
                        instruction.Message = ManagementFeeOverviewAdapter.FormatErrorsForCreateMgtFeeTransactions(results).Replace("<br/>", "");
                    }
                    else
                    {
                        // check if lastUnit is charged
                        IManagementPeriodUnit lastChargedUnit = managementPeriod.ManagementPeriodUnits
                            .Where(x => x.ManagementFee != null)
                            .OrderByDescending(x => x.StartDate)
                            .FirstOrDefault();
                        if (lastChargedUnit != null && lastChargedUnit.EndDate.Equals(managementPeriod.EndDate))
                        {
                            if (lastUnit == null)
                                mgtFeeCharged = true;
                            else
                            {
                                Tuple<int, int> lastQY = new Tuple<int, int>(Util.GetQuarter(lastChargedUnit.EndDate), lastChargedUnit.EndDate.Year);
                                Tuple<int, int> unChargedQY = new Tuple<int, int>(Util.GetQuarter(lastUnit.EndDate), lastUnit.EndDate.Year);
                                if (Util.GetPreviousQuarterYear(lastQY.Item1, lastQY.Item2).Equals(unChargedQY))
                                    instruction.Message = "The previous quarter {0}{1} has not been charged";
                                else
                                    mgtFeeCharged = true;
                            }
                        }
                    }
                }
            }
            else
                mgtFeeCharged = true;

            if (mgtFeeCharged)
            {
                transferAllCash(instruction);
            }
            return true;
        }
 private void ManageDuplicateNames2(ref Dictionary<string, Dictionary<string,JSONObject>> attributes)
 {
     List<string> tmp = new List<string>();            
     foreach (KeyValuePair<string, Dictionary<string,JSONObject>> kvp in attributes)
     {
         try
         {
             attributes[kvp.Key].Add("display_name", kvp.Value["name"]);
         }
         catch (ArgumentException e)
         {
             //Do Nothing.
         }
         //If there are more than 1 user with a given name                
         if (attributes.Count(x => x.Value["name"].String.Equals(kvp.Value["name"].String)) > 1)
         {
             tmp = attributes.Where(x => x.Value["name"].String.Equals(kvp.Value["name"].String)).Select(x => x.Key).ToList();
             for (int i = 0; i < tmp.Count; i++)
             {
                 attributes[tmp[i]]["display_name"] = JSONObject.CreateFromString("\""+attributes[tmp[i]]["name"].String+ "_"+(i + 1).ToString()+"\"");
             }
         }
     }
 }
Esempio n. 16
0
 private void CompleteDrop(Dictionary<Element, Tuple<object, PropertyDescriptor>> elementValues, Element element, string type)
 {
     if (elementValues.Any())
     {
         var undo = new EffectsPropertyModifiedUndoAction(elementValues);
         AddEffectsModifiedToUndo(undo);
         TimelineControl.grid.ClearSelectedElements();
         TimelineControl.SelectElement(element);
         UpdateToolStrip4(
             string.Format("{2} applied to {0} {1} effect(s).", elementValues.Count(), element.EffectNode.Effect.EffectName, type), 30);
     }
 }
        /// <summary>
        /// Process the document for production fields
        /// </summary>
        /// <param name="lstProductionDocuments"></param>
        private void ProcessDocumentFields(List<ProductionDocumentDetail> lstProductionDocuments)
        {
            
            if (lstProductionDocuments.Any())
            {
                var lstBatesAndDpnFields = new List<DocumentFieldsBEO>();
                var indexDocFields = new Dictionary<string, List<KeyValuePair<string, string>>>();
                foreach (var productionDocument in lstProductionDocuments)
                {
                    if (_documentDetails.ContainsKey(productionDocument.DocumentId))
                    {
                        productionDocument.Fields = _documentDetails[productionDocument.DocumentId];
                    }
                    productionDocument.DocumentFields = _documentDetails;

                    var lstDocFields = ConstructDocumentFields(productionDocument);
                    if (lstDocFields != null && lstDocFields.Any())
                    {
                        lstBatesAndDpnFields.AddRange(lstDocFields);
                        ConstructIndexFields(productionDocument, lstDocFields, ref indexDocFields);
                    }
                }
                if (lstBatesAndDpnFields.Any())
                {
                    var status = _documentVaultMngr.BulkAddOrUpdateDocumentFields(_mMatterId, _mCollectionId,
                        lstBatesAndDpnFields);

                    if (status)
                    {
                        var indexManagerProxy = new IndexManagerProxy(Int64.Parse(_mMatterId), _mCollectionId);
                        var docs = new List<DocumentBeo>();
                        if (indexDocFields.Any())
                        {
                            docs.AddRange(from doc in indexDocFields
                                          let
                                              fields = doc.Value.ToDictionary<KeyValuePair<string, string>, string, string>
                                              (field => field.Key, field => field.Value)
                                          select new DocumentBeo() { Id = doc.Key, Fields = fields });
                        }
                        indexManagerProxy.BulkUpdateDocumentsAsync(docs);
                        Tracer.Trace("{0} fields calling the method UpdatesBatesFields", indexDocFields.Count());
                    }
                }
            }
            Send(lstProductionDocuments);
        }
Esempio n. 18
0
	/* Adjust inserts/deletes of identical lines to join changes
	 * as much as possible.
	 *
	 * We do something when a run of changed lines include a
	 * line at one end and has an excluded, identical line at the other.
	 * We are free to choose which identical line is included.
	 * `compareseq' usually chooses the one at the beginning,
	 * but usually it is cleaner to consider the following identical line
	 * to be the DiffType.Change.
	 *
	 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
	 */
	public void _shift_boundaries ( List<string> lines, Dictionary<int,bool> changed, Dictionary<int,bool> other_changed ) {
		
		int i;
		int j;
		int len;
		int other_len;
		int start;
		double runlength;
		int corresponding;

		i = 0;
		j = 0;

		System.Diagnostics.Debug.Assert( lines.Count==changed.Count);
		len = lines.Count();
		other_len = other_changed.Count();

		while (true) {
			/*
			 * Scan forwards to find beginning of another run of changes.
			 * Also keep track of the corresponding point in the other file.
			 *
			 * Throughout this code, i and j are adjusted together so that
			 * the first i elements of changed and the first j elements
			 * of other_changed both contain the same number of zeros
			 * (unchanged lines).
			 * Furthermore, j is always kept so that j == other_len or
			 * other_changed[j] == false.
			 */
			while ( j < other_len && other_changed [j] )
			j++;

			while ( i < len && ! changed[i] ) {
				System.Diagnostics.Debug.Assert( j < other_len && ! other_changed[j] );
				i++; j++;
				while ( j < other_len && other_changed[j] )
				j++;
			}

			if ( i == len )
			break;

			start = i;

			// Find the end of this run of changes.
			while ( ++i < len && changed[i] )
			continue;

			do {
				/*
				 * Record the length of this run of changes, so that
				 * we can later determine whether the run has grown.
				 */
				runlength = i - start;

				/*
				 * Move the changed region back, so long as the
				 * previous unchanged line matches the last changed one.
				 * This merges with previous changed regions.
				 */
				while ( start > 0 && lines[start - 1] == lines[i - 1] ) {
					changed[--start] = true;
					changed[--i] = false;
					while ( start > 0 && changed[start - 1] )
					start--;
					System.Diagnostics.Debug.Assert( j > 0 );
					while ( other_changed[--j] )
					continue;
					System.Diagnostics.Debug.Assert( j >= 0 && !other_changed[j] );
				}

				/*
				 * Set CORRESPONDING to the end of the changed run, at the last
				 * point where it corresponds to a changed run in the other file.
				 * CORRESPONDING == LEN means no such point has been found.
				 */
				corresponding = j < other_len ? i : len;

				/*
				 * Move the changed region forward, so long as the
				 * first changed line matches the following unchanged one.
				 * This merges with following changed regions.
				 * Do this second, so that if there are no merges,
				 * the changed region is moved forward as far as possible.
				 */
				while ( i < len && lines[start] == lines[i] ) {
					changed[start++] = false;
					changed[i++] = true;
					while ( i < len && changed[i] )
					i++;

					System.Diagnostics.Debug.Assert( j < other_len && ! other_changed[j] );
					j++;
					if ( j < other_len && other_changed[j] ) {
						corresponding = i;
						while ( j < other_len && other_changed[j] )
						j++;
					}
				}
			} while ( runlength != i - start );

			/*
			 * If possible, move the fully-merged run of changes
			 * back to a corresponding run in the other file.
			 */
			while ( corresponding < i ) {
				changed[--start] = true;
				changed[--i] = false;
			System.Diagnostics.Debug.Assert( j > 0 );
				while ( other_changed[--j] )
				continue;
			System.Diagnostics.Debug.Assert( j >= 0 && !other_changed[j] );
			}
		}
		
	}
Esempio n. 19
0
        public static void button1_click(Form1 form1)
        {
            XDocument doc1 = XDocument.Load("typedescriptors_new.xml");
            int protocolHash1;
            var descriptors1 = TypeDescriptor.LoadXml(doc1.Root, out protocolHash1, false);

            basictypes = descriptors1.Where((w1, w2) => { return (w1.IsBasicType); }).ToList();

            descriptors1 = descriptors1.Where((w1, w2) => { return !(w1.IsBasicType); }).ToArray();

            XDocument doc2 = XDocument.Load("typedescriptors_old.xml");
            int protocolHash2;
            var descriptors2 = TypeDescriptor.LoadXml(doc2.Root, out protocolHash2, false).Where((w1, w2) => { return !(w1.IsBasicType); }).ToArray();

            Dictionary<int, StructureTypeDescriptor> matches = new Dictionary<int,StructureTypeDescriptor>();
            for (int i = 0; i < descriptors1.Length; i++)
            {
                var samenamed2a = descriptors2
                                .Where((w1,w2)=>{return (w1._Name == descriptors1[i]._Name);} )
                                .ToArray()
                                ;
                var samenamed2 = TypeDescriptor.ToStructures(samenamed2a);
                var sel2 = from al in samenamed2 select comparefields(al.Fields, ((StructureTypeDescriptor)descriptors1[i]).Fields);

                var sel3 = sel2.ToArray();
                //samenamed2.OrderBy()
                int bestval = 0;
                for (int j = 0; j < samenamed2.Length; j++)
                {
                    if (sel3[bestval] < sel3[j])
                    {
                        bestval = j;
                    }
                }
                if (sel3.Length == 0)
                    continue;

                if (matches.ContainsKey(i))
                        {
                            Console.WriteLine();
                            continue;
                        }
                matches[i] = samenamed2[bestval];
            }

            var nonmatched1 = descriptors1.Where(
                (w1, w2) =>
                {
                    return !matches.ContainsKey(w2);
                }
                    ).ToArray();
            foreach (var sd2a in nonmatched1)
            {
                var sd2 = (StructureTypeDescriptor)sd2a;
                addtoduallist(form1, sd2, null);
            }
            var nonmatched2 = descriptors2.Where(
                (w1, w2) => {
                    return matches.Count(
                    (w3) => {
                        return w3.Value.Index == w1.Index;
                    }
                    ) == 0;
            }
                    ).ToArray();
            foreach (var sd2a in nonmatched2)
            {
                var sd2 = (StructureTypeDescriptor)sd2a;
                addtoduallist(form1, null, sd2);
            }

            var matches2 = matches.OrderBy((w1) => {
                return comparefields(
                    (descriptors1[w1.Key] as StructureTypeDescriptor).Fields,
                    (w1.Value as StructureTypeDescriptor).Fields
                    );
                });
            foreach (var matchpair in matches2)
            {
                int index1 = matchpair.Key;
                var sd1 = ((StructureTypeDescriptor)descriptors1[index1]);
                var sd2 = matchpair.Value;

                addtoduallist(form1, sd1, sd2);
            }
        }
Esempio n. 20
0
        public void Import(string password)
        {
            listInvalidData = null;
            listImportData = null;
            listValueField = null;
            listDisplayField = null;
            listEntityResult = null;
            isDataSaved = false;

            if (!string.IsNullOrWhiteSpace(FileName))
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));

                    if (ImportTemplateID != Guid.Empty)
                    {
                        var importTemplate = unitOfWork.CreateQueryable<Cat_Import>(Guid.Empty,
                            d => d.ID == ImportTemplateID).Select(d => new
                            {
                                d.StartColumnIndex,
                                d.StartRowIndex,
                                d.SheetIndex,
                                d.ObjectName
                            }).FirstOrDefault();

                        if (importTemplate != null)
                        {
                            #region InitExcel

                            Aspose.Cells.WorkbookDesigner excelPackage = null;
                            excelPackage = new Aspose.Cells.WorkbookDesigner();
                            excelPackage.Workbook = new Aspose.Cells.Workbook(FileName);

                            Type objectType = GetAssembly(importTemplate.ObjectName);
                            importObjectType = null;//kiểu dữ liệu ảo để nhận data

                            if (!string.IsNullOrEmpty(password))
                            {
                                excelPackage.Workbook.Settings.Password = password;
                            }

                            Int64 startRowIndex = importTemplate.StartRowIndex != null ? importTemplate.StartRowIndex.Value : 0;
                            Int64 startColIndex = importTemplate.StartColumnIndex != null ? importTemplate.StartColumnIndex.Value : 0;
                            Int64 sheetIndex = importTemplate.SheetIndex != null ? importTemplate.SheetIndex.Value : 0;
                            int skipRowNumber = (int)startColIndex;

                            startRowIndex = startRowIndex < FirstIndex ? FirstIndex : startRowIndex;
                            startColIndex = startColIndex < FirstIndex ? FirstIndex : startColIndex;
                            sheetIndex = sheetIndex < FirstIndex ? FirstIndex : sheetIndex;
                            Aspose.Cells.Worksheet worksheet = null;

                            if (excelPackage.Workbook != null && excelPackage.Workbook.Worksheets != null)
                            {
                                if (excelPackage.Workbook.Worksheets.Count > sheetIndex)
                                {
                                    worksheet = excelPackage.Workbook.Worksheets[(int)sheetIndex];
                                }

                                if (worksheet == null)
                                {
                                    int activeSheetIndex = excelPackage.Workbook.Worksheets.ActiveSheetIndex;
                                    worksheet = excelPackage.Workbook.Worksheets[activeSheetIndex];
                                }
                            }

                            #endregion

                            #region ImportData

                            if (worksheet != null && worksheet.Cells != null)
                            {
                                if (worksheet.Cells != null && worksheet.Cells.End != null)
                                {
                                    int maxRowCount = worksheet.Cells.End.Row + 1;

                                    if (maxRowCount > 0)
                                    {
                                        #region GetImportItem

                                        //Danh sách data những đối tượng khóa ngoại của đổi tượng cần import
                                        Dictionary<Type, IList> listParentObject = new Dictionary<Type, IList>();

                                        var listImportItem = unitOfWork.CreateQueryable<Cat_ImportItem>(Guid.Empty, d => d.ImportID == ImportTemplateID
                                                && (d.ExcelField != null || (d.IsDefaultValue.HasValue && d.IsDefaultValue.Value))
                                                && d.IsDelete == null).Select(d => new
                                                {
                                                    d.ChildFieldLevel1,
                                                    d.ChildFieldLevel2,
                                                    d.ExcelField,
                                                    d.AllowNull,
                                                    d.AllowDuplicate,
                                                    d.DuplicateGroup,
                                                    d.IsDefaultValue,
                                                    d.DefaultValue
                                                }).OrderBy(d => d.ExcelField).ToList();

                                        #region DynamicType

                                        var typeBuilder = new DynamicTypeBuilder(string.Empty);
                                        List<string> listFieldName = new List<string>();

                                        foreach (var importItem in listImportItem)
                                        {
                                            string childFieldLevel1 = importItem.ChildFieldLevel1.TrimAll();
                                            string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                            PropertyInfo propertyType = objectType.GetProperty(childFieldLevel1);

                                            if (propertyType != null)
                                            {
                                                if (unitOfWork.IsMetadataType(propertyType.PropertyType))
                                                {
                                                    propertyType = propertyType.PropertyType.GetProperty(childFieldLevel2);
                                                    string importFieldName = unitOfWork.GetFieldConstraint(objectType, childFieldLevel1);
                                                    string valueField = importFieldName + "_" + childFieldLevel2;

                                                    if (!listFieldName.Contains(importFieldName))
                                                    {
                                                        typeBuilder.AddProperty(importFieldName, objectType.GetPropertyType(importFieldName));
                                                        listFieldName.Add(importFieldName);
                                                    }

                                                    if (!listFieldName.Contains(valueField))
                                                    {
                                                        typeBuilder.AddProperty(valueField, propertyType.PropertyType);
                                                        listFieldName.Add(valueField);
                                                    }

                                                    if (!ListValueField.Contains(valueField))
                                                    {
                                                        ListValueField.Add(valueField);
                                                    }
                                                }
                                                else
                                                {
                                                    string valueField = childFieldLevel1;

                                                    if (!listFieldName.Contains(valueField))
                                                    {
                                                        typeBuilder.AddProperty(valueField, propertyType.PropertyType);
                                                        listFieldName.Add(valueField);
                                                    }

                                                    if (!ListValueField.Contains(valueField))
                                                    {
                                                        ListValueField.Add(valueField);
                                                    }
                                                }

                                                string displayField = childFieldLevel2;
                                                if (string.IsNullOrWhiteSpace(displayField))
                                                {
                                                    displayField = childFieldLevel1;
                                                }

                                                if (!ListDisplayField.Contains(displayField))
                                                {
                                                    ListDisplayField.Add(displayField);
                                                }
                                            }
                                        }

                                        if (!typeBuilder.HasProperty(Constant.ID))
                                        {
                                            //thêm thuộc tính ID để làm key cho dữ liệu
                                            typeBuilder.AddProperty(Constant.ID, typeof(Guid));
                                        }
                                        if (!typeBuilder.HasProperty(Constant.RowIndex))
                                        {
                                            //thêm thuộc tính RowIndex để xác định vị trí trên excel
                                            typeBuilder.AddProperty(Constant.RowIndex, typeof(int));
                                        }

                                        if (!typeBuilder.HasProperty(Constant.ObjectType))
                                        {
                                            //thêm thuộc tính RowIndex để xác định vị trí trên excel
                                            typeBuilder.AddProperty(Constant.ObjectType, typeof(Type));
                                        }

                                        if (!typeBuilder.HasProperty(Constant.Checking))
                                        {
                                            //thêm thuộc tính ID để làm key cho dữ liệu
                                            typeBuilder.AddProperty(Constant.Checking, typeof(string));
                                        }

                                        //Dynamic type dùng để nhận giá trị từ excel file
                                        importObjectType = typeBuilder.BuildType();

                                        listInvalidData = new List<InvalidImportData>();
                                        IList listAllData = importObjectType.CreateList();
                                        listImportData = importObjectType.CreateList();

                                        #endregion

                                        #endregion

                                        #region GetExcelData

                                        for (int i = (int)startRowIndex; i <= maxRowCount; i = i + 1 + skipRowNumber)
                                        {
                                            object importData = importObjectType.CreateInstance();
                                            importData.SetPropertyValue(Constant.ObjectType, objectType);
                                            importData.SetPropertyValue(Constant.RowIndex, i);

                                            bool isRowInvalidData = false;
                                            bool hasValue = false;

                                            foreach (var importItem in listImportItem)
                                            {
                                                #region CheckDataType

                                                string childFieldLevel1 = importItem.ChildFieldLevel1.TrimAll();
                                                string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();

                                                InvalidDataType invalidDataType = InvalidDataType.None;
                                                bool isInvalidData = false;

                                                PropertyInfo propertyLevel1 = objectType.GetProperty(childFieldLevel1);
                                                PropertyInfo propertyLevel2 = null;

                                                string importFieldName = childFieldLevel1;
                                                Type importFieldType = null;

                                                //Nếu có hai thuộc tính cấp một giống nhau thì có nghĩa là 2 thuộc tính cấp 2 của nó sẽ làm key
                                                var listSameObject = listImportItem.Where(d => d.ChildFieldLevel1.TrimAll() == childFieldLevel1 &&
                                                    d.ExcelField != importItem.ExcelField && !string.IsNullOrWhiteSpace(d.ChildFieldLevel2.TrimAll())
                                                    && d.ChildFieldLevel2.TrimAll() != childFieldLevel2).ToList();

                                                if (propertyLevel1 != null)
                                                {
                                                    importFieldType = propertyLevel1.PropertyType;

                                                    if (unitOfWork.IsMetadataType(propertyLevel1.PropertyType))
                                                    {
                                                        propertyLevel2 = propertyLevel1.PropertyType.GetProperty(childFieldLevel2);
                                                        importFieldName = unitOfWork.GetFieldConstraint(objectType, childFieldLevel1);
                                                        importFieldType = objectType.GetPropertyType(importFieldName);

                                                        if (i == startRowIndex)
                                                        {
                                                            List<string> listField = new List<string>();
                                                            listField.Add(Constant.ID);//Luôn lấy cột ID
                                                            listField.Add(childFieldLevel2);

                                                            foreach (var sameItem in listSameObject)
                                                            {
                                                                if (!listField.Contains(sameItem.ChildFieldLevel2.TrimAll()))
                                                                {
                                                                    listField.Add(sameItem.ChildFieldLevel2.TrimAll());
                                                                }
                                                            }

                                                            if (propertyLevel1.PropertyType == objectType)
                                                            {
                                                                foreach (var sameItem in listImportItem.Where(d => !d.AllowDuplicate))
                                                                {
                                                                    string duplicateField = sameItem.ChildFieldLevel1.TrimAll();

                                                                    if (!string.IsNullOrWhiteSpace(sameItem.ChildFieldLevel2))
                                                                    {
                                                                        duplicateField = unitOfWork.GetFieldConstraint(objectType, duplicateField);
                                                                    }

                                                                    if (!listField.Contains(duplicateField))
                                                                    {
                                                                        listField.Add(duplicateField);
                                                                    }
                                                                }
                                                            }

                                                            if (!listParentObject.ContainsKey(propertyLevel1.PropertyType))
                                                            {
                                                                listParentObject.Add(propertyLevel1.PropertyType, unitOfWork.CreateQueryable(Guid.Empty,
                                                                    propertyLevel1.PropertyType, string.Empty).SelectFields(null, listField.ToArray()).GetList());
                                                            }
                                                        }
                                                    }
                                                }

                                                #endregion

                                                #region GetFieldData

                                                object excelValue = null;
                                                string excelAddress = string.Empty;

                                                if (importItem.IsDefaultValue.GetBoolean())
                                                {
                                                    excelValue = importItem.DefaultValue;
                                                }
                                                else
                                                {
                                                    excelAddress = importItem.ExcelField + i;
                                                    var excelRange = worksheet.Cells[excelAddress];
                                                    excelValue = excelRange.Value;

                                                    if (!string.IsNullOrWhiteSpace(excelValue.GetString()))
                                                    {
                                                        hasValue = true;//có dữ liệu ở một cell bất kỳ
                                                    }

                                                    string defaultValueField = childFieldLevel1;

                                                    if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                    {
                                                        defaultValueField += "." + childFieldLevel2;
                                                    }

                                                    if (DefaultValues.ContainsKey(defaultValueField))
                                                    {
                                                        excelValue = DefaultValues[defaultValueField];
                                                    }
                                                }

                                                object value = excelValue;

                                                if (propertyLevel2 != null && propertyLevel2.PropertyType != null)
                                                {
                                                    if (listParentObject.ContainsKey(propertyLevel1.PropertyType))
                                                    {
                                                        IQueryable objectQueryable = null;

                                                        if (propertyLevel2.PropertyType == typeof(string))
                                                        {
                                                            objectQueryable = listParentObject[propertyLevel1.PropertyType].AsQueryable().Where(childFieldLevel2 + " != null && "
                                                                + childFieldLevel2 + ".ToString().Trim().ToLower() = @0", value.GetString().Trim().ToLower());
                                                        }
                                                        else
                                                        {
                                                            objectQueryable = listParentObject[propertyLevel1.PropertyType].AsQueryable()
                                                                .Where(childFieldLevel2 + "=@0", value.TryGetValue(propertyLevel2.PropertyType));
                                                        }

                                                        if (listSameObject != null && listSameObject.Count() > 0)
                                                        {
                                                            foreach (var sameItem in listSameObject)
                                                            {
                                                                string sameExcelAddress = sameItem.ExcelField + i;
                                                                var sameExcelRange = worksheet.Cells[sameExcelAddress];
                                                                object sameValue = sameExcelRange.Value;

                                                                string sameChildFieldLevel2 = sameItem.ChildFieldLevel2.TrimAll();
                                                                Type samePropertyType2 = propertyLevel1.PropertyType.GetPropertyType(sameChildFieldLevel2);

                                                                if (propertyLevel2.PropertyType == typeof(string))
                                                                {
                                                                    objectQueryable = objectQueryable.Where(sameChildFieldLevel2 + " != null && " + sameChildFieldLevel2
                                                                        + ".ToString().Trim().ToLower() = @0", sameValue.GetString().Trim().ToLower());
                                                                }
                                                                else
                                                                {
                                                                    objectQueryable = objectQueryable.Where(sameChildFieldLevel2 + "=@0", sameValue.TryGetValue(samePropertyType2));
                                                                }
                                                            }
                                                        }

                                                        value = objectQueryable.Select(Constant.ID).FirstOrDefault();

                                                        if (value.IsNullOrEmpty() || value.GetString() == Guid.Empty.ToString())
                                                        {
                                                            if (!string.IsNullOrWhiteSpace(excelValue.GetString()) || !importItem.AllowNull)
                                                            {
                                                                invalidDataType = InvalidDataType.ReferenceNotFound;
                                                                isInvalidData = true;
                                                            }
                                                        }
                                                    }
                                                }

                                                #endregion

                                                #region CheckInvalid

                                                if (!isInvalidData)
                                                {
                                                    if (!value.IsNullOrEmpty())
                                                    {
                                                        if (importFieldType.IsDateTime())
                                                        {
                                                            if (!value.IsTypeOf(typeof(DateTime)))
                                                            {
                                                                DateTime currentValue = DateTime.Now;

                                                                if (DateTime.TryParseExact(value.GetString(), DateTimeFormat,
                                                                   CultureInfo.GetCultureInfo("vi-vn"), DateTimeStyles.None,
                                                                    out currentValue))
                                                                {
                                                                    value = currentValue;
                                                                }
                                                                else
                                                                {
                                                                    object dateValue = value.TryGetValue(importFieldType, out isInvalidData);

                                                                    if (isInvalidData)
                                                                    {
                                                                        dateValue = value.TryGetValue(typeof(double),
                                                                            out isInvalidData);

                                                                        if (!isInvalidData)
                                                                        {
                                                                            value = DateTime.FromOADate(dateValue.TryGetValue<double>());
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        value = dateValue;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            value = value.TryGetValue(importFieldType, out isInvalidData);

                                                            if (isInvalidData)
                                                            {
                                                                invalidDataType = InvalidDataType.InvalidFormat;
                                                            }
                                                            else if (!string.IsNullOrWhiteSpace(value.GetString()) && importFieldType == typeof(string))
                                                            {
                                                                //value = value.GetString().Replace("<", string.Empty).Replace("lt;", string.Empty).Replace(">", string.Empty)
                                                                //    .Replace("gt;", string.Empty).Replace("{", string.Empty).Replace("}", string.Empty).Replace("\"", string.Empty)
                                                                //    .Replace("'", string.Empty).Replace("amp;", string.Empty).Replace("quot;", string.Empty)
                                                                //    .Replace("#x27;", string.Empty).Replace("#x2F;", string.Empty).Replace("&", string.Empty);

                                                                string checkField = propertyLevel2 != null ? propertyLevel2.Name : propertyLevel1.Name;
                                                                Type checkType = propertyLevel2 != null ? propertyLevel1.PropertyType : objectType;

                                                                if (value.GetString().Length > unitOfWork.GetMaxLength(checkType, checkField))
                                                                {
                                                                    invalidDataType = InvalidDataType.TruncateData;
                                                                    isInvalidData = true;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (!importItem.AllowNull)
                                                        {
                                                            invalidDataType = InvalidDataType.NullData;
                                                            isInvalidData = true;
                                                        }
                                                    }
                                                }

                                                if (childFieldLevel1 == Constant.Checking)
                                                {
                                                    if (!unitOfWork.IsMetadataField(objectType, Constant.Checking))
                                                    {
                                                        if (!string.IsNullOrWhiteSpace(excelValue.GetString()))
                                                        {
                                                            invalidDataType = InvalidDataType.Custom;
                                                            isInvalidData = true;
                                                        }
                                                    }
                                                }

                                                importData.SetPropertyValue(importFieldName + "_"
                                                    + childFieldLevel2, excelValue.GetString());

                                                if (isInvalidData)
                                                {
                                                    isRowInvalidData = true;//1 cell lỗi là cả row lỗi
                                                    InvalidImportData invalidData = new InvalidImportData();

                                                    if (invalidDataType == InvalidDataType.Custom)
                                                    {
                                                        invalidData.Desciption = excelValue.GetString();
                                                    }
                                                    else
                                                    {
                                                        invalidData.Desciption = invalidDataType.ToString().TranslateString();
                                                        invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                        invalidData.ValueType = importFieldType.Name;
                                                        invalidData.ExcelValue = excelValue;
                                                    }

                                                    invalidData.ExcelField = excelAddress;
                                                    invalidData.ImportData = importData;
                                                    invalidData.Type = invalidDataType;
                                                    listInvalidData.Add(invalidData);
                                                }
                                                else
                                                {
                                                    importData.SetPropertyValue(importFieldName,
                                                        value.TryGetValue(importFieldType));
                                                }

                                                #endregion
                                            }

                                            if (!isRowInvalidData && hasValue)
                                            {
                                                listAllData.Add(importData);
                                            }
                                            else if (!hasValue)
                                            {
                                                listInvalidData = listInvalidData.Where(d =>
                                                    d.ImportData != importData).ToList();
                                            }

                                            if (ProgressChanged != null)
                                            {
                                                double percent = ((double)i / (double)(maxRowCount + (int)startRowIndex)) * 100;
                                                ProgressChanged(new ProgressEventArgs
                                                {
                                                    ID = UserID,
                                                    Name = "ReadData",
                                                    Value = "ReadData".TranslateString(),
                                                    Percent = (int)percent
                                                });
                                            }
                                        }

                                        #endregion

                                        #region CheckDuplicate

                                        if (listAllData != null && listAllData.Count > 0)
                                        {
                                            var listImportItemDuplicate = listImportItem.Where(d =>
                                                !d.AllowDuplicate).ToList();

                                            var listDuplicateGroup = listImportItemDuplicate.GroupBy(d =>
                                                d.DuplicateGroup).ToList();

                                            if (listDuplicateGroup.Count() > 0)
                                            {
                                                var listDuplicateByType = listImportItemDuplicate.Where(d => unitOfWork.IsMetadataType(objectType.GetPropertyType(d.ChildFieldLevel1.TrimAll()))).ToList();
                                                var listFields = listDuplicateByType.Select(d => unitOfWork.GetFieldConstraint(objectType, d.ChildFieldLevel1.TrimAll())).ToList();
                                                listFields.AddRange(listImportItemDuplicate.Where(d => !listDuplicateByType.Contains(d)).Select(d => d.ChildFieldLevel1.TrimAll()));
                                                listFields = listFields.Where(d => !string.IsNullOrWhiteSpace(d)).ToList();

                                                if (listFields.Count() > 0 && !listParentObject.ContainsKey(objectType))
                                                {
                                                    if (!listFields.Contains(Constant.ID))
                                                    {
                                                        listFields.Add(Constant.ID);
                                                    }

                                                    listParentObject.Add(objectType, unitOfWork.CreateQueryable(Guid.Empty,
                                                        objectType, string.Empty).SelectFields(null, listFields.Distinct().ToArray()).GetList());
                                                }

                                                foreach (var importData in listAllData)
                                                {
                                                    foreach (var itemDuplicate in listDuplicateGroup)
                                                    {
                                                        #region CheckData

                                                        Dictionary<string, object> listExcelValue = new Dictionary<string, object>();
                                                        Dictionary<string, string> listCheckField = new Dictionary<string, string>();

                                                        IQueryable dbQueryable = null;
                                                        IQueryable fileQueryable1 = null;
                                                        IQueryable fileQueryable2 = null;

                                                        bool isDuplicateFile = false;
                                                        bool isDuplicateDb = false;

                                                        foreach (var importItem in itemDuplicate)
                                                        {
                                                            string checkField = importItem.ChildFieldLevel1.TrimAll();
                                                            string templateField = checkField;

                                                            if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                            {
                                                                checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                templateField = checkField + "_" + importItem.ChildFieldLevel2.TrimAll();
                                                            }

                                                            if (dbQueryable == null && listParentObject.ContainsKey(objectType))
                                                            {
                                                                dbQueryable = listParentObject[objectType].AsQueryable();
                                                            }

                                                            if (fileQueryable1 == null)
                                                            {
                                                                fileQueryable1 = listAllData.AsQueryable().Where("it!=@0", importData);
                                                            }

                                                            if (fileQueryable2 == null)
                                                            {
                                                                fileQueryable2 = listInvalidData.Where(d => d.ImportData != null
                                                                    && d.ImportData != importData).Select(d => d.ImportData).AsQueryable();
                                                            }

                                                            if (!string.IsNullOrWhiteSpace(checkField))
                                                            {
                                                                Type checkFieldType = importData.GetRealPropertyType(checkField);
                                                                listCheckField.Add(checkField, templateField);

                                                                if (dbQueryable != null)
                                                                {
                                                                    if (checkFieldType == typeof(string))
                                                                    {
                                                                        dbQueryable = dbQueryable.Where(checkField + " != null && " + checkField + ".ToString().Trim().ToLower() = @0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType).GetString().Trim().ToLower());
                                                                    }
                                                                    else
                                                                    {
                                                                        dbQueryable = dbQueryable.Where(checkField + "=@0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType));
                                                                    }
                                                                }

                                                                if (fileQueryable1 != null)
                                                                {
                                                                    if (checkFieldType == typeof(string))
                                                                    {
                                                                        fileQueryable1 = fileQueryable1.Where(checkField + " != null && " + checkField + ".ToString().Trim().ToLower() = @0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType).GetString().Trim().ToLower());
                                                                    }
                                                                    else
                                                                    {
                                                                        fileQueryable1 = fileQueryable1.Where(checkField + "=@0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType));
                                                                    }
                                                                }

                                                                if (fileQueryable2 != null)
                                                                {
                                                                    fileQueryable2 = fileQueryable2.OfType<object>().Where(d =>
                                                                        d.GetPropertyValue(checkField) == importData.GetPropertyValue(checkField));
                                                                }
                                                            }
                                                        }

                                                        if (dbQueryable != null)
                                                        {
                                                            object selectedID = dbQueryable.Select(Constant.ID).FirstOrDefault();
                                                            if (selectedID != null && selectedID.ToString() != Guid.Empty.ToString())
                                                            {
                                                                isDuplicateDb = true;//dữ liệu import bị trùng với database.
                                                                importData.SetPropertyValue(Constant.ID, selectedID);

                                                                if (listCheckField != null && listCheckField.Count() > 0)
                                                                {
                                                                    foreach (var checkField in listCheckField)
                                                                    {
                                                                        var excelValue = importData.GetPropertyValue(checkField.Value);

                                                                        if (!listExcelValue.ContainsKey(checkField.Value))
                                                                        {
                                                                            listExcelValue.Add(checkField.Value, excelValue);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        if (fileQueryable1 != null && fileQueryable1.Any())
                                                        {
                                                            isDuplicateFile = true;//dữ liệu bị trùng với file.

                                                            if (listCheckField != null && listCheckField.Count() > 0)
                                                            {
                                                                foreach (var checkField in listCheckField)
                                                                {
                                                                    var excelValue = fileQueryable1.Select(checkField.Value).FirstOrDefault();

                                                                    if (!listExcelValue.ContainsKey(checkField.Value))
                                                                    {
                                                                        listExcelValue.Add(checkField.Value, excelValue);
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        if (fileQueryable2 != null && fileQueryable2.Any())
                                                        {
                                                            isDuplicateFile = true;//dữ liệu bị trùng với file.

                                                            if (listCheckField != null && listCheckField.Count() > 0)
                                                            {
                                                                foreach (var checkField in listCheckField)
                                                                {
                                                                    var excelValue = fileQueryable2.OfType<object>().Select(d =>
                                                                        d.GetPropertyValue(checkField.Value)).FirstOrDefault();

                                                                    if (!listExcelValue.ContainsKey(checkField.Value))
                                                                    {
                                                                        listExcelValue.Add(checkField.Value, excelValue);
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        #endregion

                                                        #region ProcessData

                                                        if (isDuplicateDb || isDuplicateFile)
                                                        {
                                                            if (ImportMode == ImportDataMode.Update
                                                                || ImportMode == ImportDataMode.Skip)
                                                            {
                                                                if (isDuplicateDb)
                                                                {
                                                                    if (!listImportData.Contains(importData))
                                                                    {
                                                                        //Cập nhật dữ liệu vào database
                                                                        listImportData.Add(importData);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    foreach (var importItem in itemDuplicate)
                                                                    {
                                                                        InvalidImportData invalidData = new InvalidImportData();
                                                                        object row = importData.GetPropertyValue(Constant.RowIndex);
                                                                        invalidData.ExcelField = importItem.ExcelField + row.GetString();
                                                                        invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                                        string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                                                        string checkField = importItem.ChildFieldLevel1.TrimAll();

                                                                        if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                                        {
                                                                            checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                            checkField = checkField + "_" + childFieldLevel2;
                                                                        }

                                                                        if (listExcelValue.ContainsKey(checkField))
                                                                        {
                                                                            invalidData.ExcelValue = listExcelValue[checkField];
                                                                        }

                                                                        if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                                        {
                                                                            invalidData.DataField += "." + childFieldLevel2.TranslateString();
                                                                        }

                                                                        invalidData.Type = InvalidDataType.DataNotFound;//không tìm thấy
                                                                        invalidData.Desciption = invalidData.Type.ToString().TranslateString();
                                                                        invalidData.ImportData = importData;
                                                                        listInvalidData.Add(invalidData);

                                                                        if (listImportData.Contains(importData))
                                                                        {
                                                                            listImportData.Remove(importData);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                foreach (var importItem in itemDuplicate)
                                                                {
                                                                    InvalidImportData invalidData = new InvalidImportData();
                                                                    object row = importData.GetPropertyValue(Constant.RowIndex);
                                                                    invalidData.ExcelField = importItem.ExcelField + row.GetString();
                                                                    invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                                    string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                                                    string checkField = importItem.ChildFieldLevel1.TrimAll();

                                                                    if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                                    {
                                                                        checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                        checkField = checkField + "_" + childFieldLevel2;
                                                                    }

                                                                    if (listExcelValue.ContainsKey(checkField))
                                                                    {
                                                                        invalidData.ExcelValue = listExcelValue[checkField];
                                                                    }

                                                                    if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                                    {
                                                                        invalidData.DataField += "." + childFieldLevel2.TranslateString();
                                                                    }

                                                                    if (isDuplicateDb && isDuplicateFile)
                                                                    {
                                                                        invalidData.Type = InvalidDataType.Duplicate;
                                                                    }
                                                                    else if (isDuplicateDb)
                                                                    {
                                                                        invalidData.Type = InvalidDataType.DuplicateInDb;
                                                                    }
                                                                    else if (isDuplicateFile)
                                                                    {
                                                                        invalidData.Type = InvalidDataType.DuplicateInFile;
                                                                    }

                                                                    invalidData.Desciption = invalidData.Type.ToString().TranslateString();
                                                                    invalidData.ImportData = importData;
                                                                    listInvalidData.Add(invalidData);

                                                                    if (listImportData.Contains(importData))
                                                                    {
                                                                        listImportData.Remove(importData);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (ImportMode == ImportDataMode.Update)
                                                            {
                                                                foreach (var importItem in itemDuplicate)
                                                                {
                                                                    InvalidImportData invalidData = new InvalidImportData();
                                                                    object row = importData.GetPropertyValue(Constant.RowIndex);
                                                                    invalidData.ExcelField = importItem.ExcelField + row.GetString();
                                                                    invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                                    string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                                                    string checkField = importItem.ChildFieldLevel1.TrimAll();

                                                                    if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                                    {
                                                                        checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                        checkField = checkField + "_" + childFieldLevel2;
                                                                    }

                                                                    if (listExcelValue.ContainsKey(checkField))
                                                                    {
                                                                        invalidData.ExcelValue = listExcelValue[checkField];
                                                                    }

                                                                    if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                                    {
                                                                        invalidData.DataField += "." + childFieldLevel2.TranslateString();
                                                                    }

                                                                    invalidData.Type = InvalidDataType.DataNotFound;//không tìm thấy
                                                                    invalidData.Desciption = invalidData.Type.ToString().TranslateString();
                                                                    invalidData.ImportData = importData;
                                                                    listInvalidData.Add(invalidData);

                                                                    if (listImportData.Contains(importData))
                                                                    {
                                                                        listImportData.Remove(importData);
                                                                    }
                                                                }
                                                            }
                                                            else if (!listImportData.Contains(importData) &&
                                                                !listInvalidData.Any(d => d.ImportData == importData))
                                                            {
                                                                listImportData.Add(importData);
                                                            }
                                                        }

                                                        #endregion
                                                    }

                                                    if (ProgressChanged != null)
                                                    {
                                                        double percent = ((double)listAllData.IndexOf(importData) / (double)listAllData.Count) * 100;
                                                        ProgressChanged(new ProgressEventArgs
                                                        {
                                                            ID = UserID,
                                                            Name = "CheckDuplicate",
                                                            Value = "CheckDuplicate".TranslateString(),
                                                            Percent = (int)percent
                                                        });
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                listImportData = listAllData;
                                            }
                                        }

                                        #endregion
                                    }
                                }
                            }
                            #endregion

                            #region ImportCompleted

                            if (ProgressChanged != null)
                            {
                                ProgressChanged(new ProgressEventArgs
                                {
                                    ID = UserID,
                                    Name = "ReadData",
                                    Value = "ReadData".TranslateString(),
                                    Percent = 100
                                });
                            }

                            #endregion
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        //public static void SaveReceive(List<ReceiveHeader> rh, int OrderHeaderId)
        //{
        //    var db = DCFactory.GetDataContext<PartDataContext>();
        //    db.ReceiveHeaders.InsertAllOnSubmit(rh);
        //    db.SubmitChanges();
        //}
        //public static void ModifyReceive(List<ReceiveDetail> rd)
        //{
        //    var db = DCFactory.GetDataContext<PartDataContext>();
        //    rd.ForEach(p =>
        //    {
        //        int quantity = p.GoodQuantity;
        //        if (p.ReceiveDetailId != 0)
        //        {
        //            var old = db.ReceiveDetails.Single(q => q.ReceiveDetailId == p.ReceiveDetailId);
        //            old.GoodQuantity = p.GoodQuantity;
        //            old.LackQuantity = p.LackQuantity;
        //            old.WrongQuantity = p.WrongQuantity;
        //            old.BrokenQuantity = p.BrokenQuantity;
        //            old.DealerComment = p.DealerComment;
        //            db.SubmitChanges();
        //            quantity -= old.GoodQuantity;
        //        }
        //        if (quantity != 0)
        //            PartDAO.StockAdjust(p.PartCode, "P", UserHelper.DealerCode, UserHelper.WarehouseId, null, DateTime.Now, InventoryAction.NormalImport, 0, quantity, p.DealerComment, string.Empty, null);
        //    });
        //}
        /// <summary>
        /// Close the current order, mark the status
        /// </summary>
        /// <param name="OrderHeaderId">The order Id</param>
        public static void CloseOrder(long OrderHeaderId)
        {
            var db = DCFactory.GetDataContext<PartDataContext>();
            Dictionary<string, int> order = new Dictionary<string, int>();
            var partOrderList = db.OrderDetails.Where(p => p.OrderHeaderId == OrderHeaderId).ToList();
            var partReceiveList = db.ReceiveDetails.Where(p => p.OrderHeaderId == OrderHeaderId).ToList();
            foreach (var item in partOrderList)
            {
                order.Add(item.PartCode, item.QuotationQuantity);
            }

            foreach (var item in partReceiveList)
            {
                if (order.ContainsKey(item.PartCode))
                    order[item.PartCode] -= item.ShippingQuantity;
            }
            foreach (var item in partOrderList)
            {
                if (order[item.PartCode] == 0) item.Status = "C";
                else if (partReceiveList.Find(p => p.PartCode == item.PartCode) != null) item.Status = "P";
            }
            db.SubmitChanges();
            if (order.Count(p => p.Value > 0) > 0) return; // some part has not ship
            var oh = db.OrderHeaders.Single(p => p.OrderHeaderId == OrderHeaderId);
            oh.AlreadyInStock = true;
            var query = (from ngh in db.NGFormHeaders
                         join rh in db.ReceiveHeaders on ngh.ReceiveHeaderId equals rh.ReceiveHeaderId
                         where rh.OrderHeaderId == OrderHeaderId
                         select ngh.NGFormHeaderId).Count();
            oh.Status = query == 0 ? OrderStatus.OrderClosedNormal : OrderStatus.OrderClosedAbnormal;
            db.SubmitChanges();
        }
Esempio n. 22
0
  //public class modExs {
  //  public static modExs formMod(CourseMeta.modInfo mod) { return new modExs() { jsonId = mod.jsonId, exs = mod.exs.Select(e => e.compId).ToArray() }; }
  //  public bool isGramm;
  //  public string jsonId;
  //  public string[] exs;
  //}

  public static void getDictEntries(string srcDir) {

    if (dictEntries != null) return;
    errors.Clear();
    Func<Langs, Langs, string> dictCode = (l1, l2) => LMComLib.DictInfo.GetDict(l1, l2).Code;
    Func<Langs, string> dictHalfCode = l => CommonLib.langToLingeaLang(l);

    //sound files namapovane na master sound file a seznam slovicek, ktere jsou ozvuceny
    var soundFileToMastersAndUsages = DictLib.crsLangs.SelectMany(l => LingeaSndFiles.addSoundsStart(l).files.SelectMany(f => f.clones.Select(c => new {
      lang = l,
      c.fileName,
      soundMaster = f.fileName,
      //words = f.clones.SelectMany(cl => cl.word.Split('#')).Distinct()
    }))).
      GroupBy(f => f.fileName).ToDictionary(
        g => g.Key,
        g => new DictEntry { soundMaster = g.First().lang.ToString() + "/" + g.Select(t => t.soundMaster).Distinct().Single()/*, soundWords = g.SelectMany(t => t.words).Distinct().ToArray()*/ }
     );

    //slova z entry
    Regex tagEx = new Regex(@"<.*?>", RegexOptions.Singleline);
    Func<XElement, IEnumerable<string>> removeTags = el => split(tagEx.Replace(el.ToString(), " "));
    Func<XElement, XElement> srcFromTrans = el => { foreach (var src in el.Descendants().Where(e => new string[] { "in_c", "in_v", "in_g", "in_w", "in_pp", "in_d" }.Contains(e.AttributeValue("class"))).ToArray()) src.Remove(); return el; };
    Func<DictEntry, string[][]> extractWords = de => {
      //if (de.wordId() == "dvd" && de.natLang==Langs.ru_ru) {
      //  de.entry = srcFromTrans(de.entry);
      //}
      var trans = de.entry.DescendantsAttr("class", "trans").Concat(de.entry.DescendantsAttr("class", "trg")).Select(el => srcFromTrans(el)).SelectMany(el => removeTags(el)).Distinct();
      var src = de.entry.DescendantsAttr("class", "src").SelectMany(el => removeTags(el)).Concat(de.headWords).Distinct();
      return new string[][] { src.ToArray(), trans.ToArray() };
    };
    //Dictionary<string, string[]> entryWords = null;


    //*********** vytvoreni hesla
    Regex entrTagToSoundTitleEx = new Regex(@"(\d|\*|\(.*?\))");
    Func<string, string> entrTagToSoundTitle = s => entrTagToSoundTitleEx.Replace(s, "").ToLower().Trim().Replace("\x301", null);
    Func<Langs, Langs, KeyValuePair<string, XElement>, DictEntry> createEntry = (crsLang, natLang, id_entry) => {
      var res = new DictEntry {
        //dictId = dictCode(crsLang, natLang),
        entryId = id_entry.Key,
        //soundTitle = title = entrTagToSoundTitle(id_entry.Value.DescendantsAttr("class", "entr").First().Value),
        //headWords = splitHeadwords(id_entry.Value.DescendantsAttr("class", "entr").First().Value).ToArray(),
        crsLang = crsLang,
        natLang = natLang,
        entry = id_entry.Value,
      };
      res.soundFile = id_entry.Value.AttributeValue("oldLngSound");
      var pron = id_entry.Value.DescendantsAttr("class", "pron").FirstOrDefault();
      res.pronText = pron == null ? null : pron.Value;
      DictEntry sndFileInfo = null;
      if (res.soundFile != null) {
        //res2.soundDictId = res2.soundFile.Substring(1, 4);
        soundFileToMastersAndUsages.TryGetValue(res.soundFile, out sndFileInfo);
        if (sndFileInfo != null) res.soundMaster = sndFileInfo.soundMaster;
        //res2.soundWords = sndFileInfo.soundWords;
      }
      var wordsFromEntry = extractWords(res);
      res.wordStats = new LangCounts {
        crsWords = wordsFromEntry[0],
        natWords = wordsFromEntry[1]
      };
      return res;
    };

    dictEntries = getOldLingeaEntries(srcDir).
      //k entry dej seznam used Words (puvodni "vals" atribut "w" tagu slovniku)
      SelectMany(crs => crs.Value.
        //SideEfect(nat => entryWords = nat.Value.wordToEntryId.GroupBy(d => d.Value).ToDictionary(d => d.Key, d => d.Select(t => t.Value).Distinct().ToArray())).
        SelectMany(nat => nat.Value.entryIdToEntry.Select(kv => createEntry(crs.Key, nat.Key, kv)))
      ).ToArray();

    //zjisti jazyk pres SoundMaster file
    var soundMasterLangs = dictEntries.Where(de => de.soundMaster != null).GroupBy(de => de.soundMaster).Select(g => new {
      g.Key, //soundMaser
      langs = new {
        langs = DictLib.crsLangs.Where(l => g.All(de => de.bothLangs().Contains(l))).Distinct().ToArray(), //spolecne Crs jazyk pro stejny zvuk
        dicts = g.Select(t => encodeLangs(t.crsLang, t.natLang)).Distinct().ToArray() //ruzne slovniky
      }
    }).
    Where(kv => kv.langs.dicts.Length > 2 && kv.langs.langs.Length == 1). //musi byt alespon 2 slovniky a prave jeden jazyk
    ToDictionary(kv => kv.Key, kv => kv.langs.langs[0]); //tabulka soundMaster => jazyk

    int ru = 0; int morf1 = 0; int morf1Err = 0; int morf2 = 0; int cwin1252 = 0;
    //foreach (var de in dictEntries.Where(de => de.wordId() == "affittare")) {
    foreach (var de in dictEntries) {

      //Pres spolecny soundMaster
      if (de.soundMaster != null) {
        Langs l;
        if (soundMasterLangs.TryGetValue(de.soundMaster, out l)) {
          if (de.okCrs == Langs.no) {
            de.okCrs = l;
            de.okCrsReason = OKCrsReason.soundMaster;
          } else if (de.okCrs != l)
            //errors.Add(de); 
            throw new Exception();
        }
      }
      //nemcina a francouzstina - vyslovnost
      if (de.pronText != null && (de.crsLang == Langs.en_gb && de.natLang != Langs.fr_fr || de.natLang == Langs.en_gb && de.crsLang != Langs.fr_fr)) {
        if (de.okCrs == Langs.no) {
          de.okCrs = Langs.en_gb;
          de.okCrsReason = OKCrsReason.pronunc;
        } else if (de.okCrs != Langs.en_gb)
          //errors.Add(de); 
          throw new Exception();
      }
      if (de.pronText != null && (de.crsLang == Langs.fr_fr && de.natLang != Langs.en_gb || de.natLang == Langs.fr_fr && de.crsLang != Langs.en_gb)) {
        if (de.okCrs == Langs.no) {
          de.okCrs = Langs.fr_fr;
          de.okCrsReason = OKCrsReason.pronunc;
        } else if (de.okCrs != Langs.fr_fr)
          //errors.Add(de); 
          throw new Exception();
      }
      //rustina
      if (de.crsLang == Langs.ru_ru || de.natLang == Langs.ru_ru) {
        Func<string[], bool> isRussian = words => words.SelectMany(w => w.ToCharArray()).Intersect(russianAlphabet).Any();
        var natIsRussian = isRussian(de.wordStats.natWords);
        var crsIsRussian = isRussian(de.wordStats.crsWords);
        Langs crsLng;
        Langs notRuLang = de.crsLang == Langs.ru_ru ? de.natLang : de.crsLang;

        if (natIsRussian && !crsIsRussian) {
          crsLng = notRuLang;
        } else if (crsIsRussian && !natIsRussian) {
          crsLng = Langs.ru_ru;
        } else
          crsLng = Langs.no; ;
        if (crsLng != Langs.no)
          if (de.okCrs == Langs.no) {
            ru++;
            de.okCrs = crsLng;
            de.okCrsReason = OKCrsReason.russian;
          } else if (de.okCrs != crsLng)
            //errors.Add(de); 
            throw new Exception();
      }

      //v en_gb, fr_fr x sp_sp : okCrs neni en_gb iff existuje <span class="morf"> nf nebo nm
      bool isFr = !de.bothLangs().Except(XExtension.Create(Langs.en_gb, Langs.fr_fr)).Any();
      bool isSp = !de.bothLangs().Except(XExtension.Create(Langs.en_gb, Langs.sp_sp)).Any();
      if (isFr || isSp) {
        if (de.entry.DescendantsAttr("class", "morf").Any(el => new string[] { "nm", "nf" }.Contains(el.Value.Trim()))) {
          Langs lng = isFr ? Langs.fr_fr : Langs.sp_sp;
          if (de.okCrs == Langs.no) {
            morf1++;
            de.okCrs = lng;
            de.okCrsReason = OKCrsReason.morf_nm_nf;
          } else if (de.okCrs != lng) {
            morf1Err++;
            //1 chyba, soufflé
            //errors.Add(de); 
            //throw new Exception();
          }
        }
      }
      //v en_gb, de_de x it_it : okCrs neni en_gb iff existuje <span class="morf"> m pl | m | f pl | f
      bool isDe = !de.bothLangs().Except(XExtension.Create(Langs.en_gb, Langs.de_de)).Any();
      bool isIt = !de.bothLangs().Except(XExtension.Create(Langs.en_gb, Langs.it_it)).Any();
      if (isDe || isDe) {
        if (de.entry.DescendantsAttr("class", "morf").Any(el => new string[] { "m pl", "m", "f pl", "f" }.Contains(el.Value.Trim()))) {
          Langs lng = isDe ? Langs.de_de : Langs.it_it;
          if (de.okCrs == Langs.no) {
            morf2++;
            de.okCrs = lng;
            de.okCrsReason = OKCrsReason.morf_m_pl_f;
          } else if (de.okCrs != lng)
            throw new Exception();
        }
      }

      if (de.crsLang != Langs.ru_ru && de.natLang != Langs.ru_ru && DictLib.crsLangs.Contains(de.crsLang) && !DictLib.crsLangs.Contains(de.natLang)) {
        Func<string[], bool> notWin1252 = words => words.SelectMany(w => w.ToCharArray()).Where(ch => char.IsLetter(ch)).Except(win1252).Any();
        var natNotWin1252 = notWin1252(de.wordStats.natWords);
        var crsNotWin1252 = notWin1252(de.wordStats.crsWords);
        if (natNotWin1252 != crsNotWin1252) {
          Langs crsLng;
          if (natNotWin1252 && !crsNotWin1252)
            crsLng = de.crsLang;
          else if (crsNotWin1252 && !natNotWin1252) { //šř v 
            crsLng = de.natLang;
          } else
            throw new Exception();
          if (de.okCrs == Langs.no) {
            cwin1252++;
            de.okCrs = crsLng;
            de.okCrsReason = OKCrsReason.charsOK;
          } else if (de.okCrs != crsLng)
            throw new Exception();
        }
        //cwin1252Err++;
      }

    }
    if (morf1Err > 1) throw new Exception();

    //***************** grupy dle vyslovnosti
    Langs[] enfr = new Langs[] { Langs.en_gb, Langs.fr_fr };
    Dictionary<string, Langs> pronToLang = new Dictionary<string, Langs>();
    foreach (var entr in dictEntries.Where(de => de.pronText != null).GroupBy(de => de.wordId())) {
      pronToLang.Clear();
      foreach (var pronGrp in entr.GroupBy(de => de.pronText).Where(g => g.Count() > 1)) {
        foreach (var de in pronGrp) {
          var otherLang = de.bothLangs().Except(enfr).FirstOrDefault();
          if (otherLang == Langs.no) continue;
          pronToLang[de.pronText] = de.crsLang == otherLang ? de.natLang : de.crsLang;
        };
      }
      if (pronToLang.Count() < 2) continue;
      foreach (var de in entr) {
        Langs pronl;
        if (!pronToLang.TryGetValue(de.pronText, out pronl)) {
          if (de.bothLangs().Intersect(enfr).Count() == 2)
            pronl = pronToLang.First().Value == Langs.en_gb ? Langs.fr_fr : Langs.en_gb;
          else
            continue;
        }
        if (de.okCrs == Langs.no) {
          de.okCrs = pronl;
          de.okCrsReason = OKCrsReason.viaPronunciation;
        } else if (de.okCrs != pronl)
          throw new Exception();
      }
    }


    //******************* rucne upravena slovicka 
    Dictionary<string, Admin.ByHand> hands = new Dictionary<string, Admin.ByHand>();
    var files = Directory.EnumerateFiles(@"d:\LMCom\rew\Web4\RwDicts\Sources\LingeaOld\design", "byHand_*.xml");
    foreach (var fn in files) foreach (var h in XmlUtils.FileToObject<List<Admin.ByHand>>(fn))
        hands.Add(h.id(), h);
    //var hands = Directory.EnumerateFiles(@"d:\LMCom\rew\Web4\RwDicts\Sources\LingeaOld\design", "byHand_*.xml").SelectMany(fn => XmlUtils.FileToObject<List<Admin.ByHand>>(fn)).ToDictionary(cr => cr.email(), cr => cr);
    foreach (var de in dictEntries.Where(de => de.okCrs == Langs.no && hands.ContainsKey(de.id()))) { de.okCrs = hands[de.id()].okCrs; de.okCrsReason = OKCrsReason.byHand; }

    //******************* zdroj spravnych slov jsou doposud oznacena slova v Lingea slovniku. Pro dany slovnik se udela rozdil spravnych slov.
    var allLangs = dictEntries.Where(de => de.okCrs != Langs.no).SelectMany(de => de.bothLangs()).Distinct().ToArray();
    Func<DictEntry, Langs, IEnumerable<string>> getWords = (de, l) => de.okCrs == l ? de.wordStats.crsWords : de.wordStats.natWords;

    var sources = allLangs.ToDictionary(
      l => l,
      l => dictEntries.Where(de => de.okCrs != Langs.no && de.bothLangs().Contains(l)).SelectMany(de => getWords(de, l)).Distinct().ToArray()
    );
    Dictionary<Langs, Dictionary<Langs, Dictionary<string, bool>>> diffWordsTab = allLangs.ToDictionary(myLang => myLang, myLang => allLangs.Where(nl => nl != myLang).ToDictionary(otherLang => otherLang, otherLang => {
      try {
        var ml = sources[myLang]; var ol = sources[otherLang];
        return ml.Except(ol).ToDictionary(w => w, w => true);
      } catch { return new Dictionary<string, bool>(); }
    }));
    Func<Langs, Langs, Dictionary<string, bool>> diffWords = (myLang, otherLang) => {
      return diffWordsTab.ContainsKey(myLang) && diffWordsTab[myLang].ContainsKey(otherLang) ? diffWordsTab[myLang][otherLang] : null;
    };
    //foreach (var de in dictEntries.Where(de => de.wordId() == "cofounder").Where(de => de.okCrs == Langs.no && de.crsLang != Langs.ru_ru && !CourseDictionary.crsLangs.Contains(de.natLang))) {
    foreach (var de in dictEntries.Where(de => de.okCrs == Langs.no && de.crsLang != Langs.ru_ru && !DictLib.crsLangs.Contains(de.natLang))) {
      var crsOkW = diffWords(de.crsLang, de.natLang);
      var natOkW = diffWords(de.natLang, de.crsLang);
      if (crsOkW == null || natOkW == null) continue;
      var isCrs = de.wordStats.crsWords.Where(w => crsOkW.ContainsKey(w)).Any() || de.wordStats.natWords.Where(w => natOkW.ContainsKey(w)).Any();
      var isNat = de.wordStats.natWords.Where(w => crsOkW.ContainsKey(w)).Any() || de.wordStats.crsWords.Where(w => natOkW.ContainsKey(w)).Any();

      if (isCrs == isNat) continue;

      var lng = isCrs ? de.crsLang : de.natLang;
      if (de.okCrs == Langs.no) {
        de.okCrs = lng;
        de.okCrsReason = OKCrsReason.wordsOK;
      } else if (de.okCrs != lng)
        throw new Exception();
    }

    //*********************** SOUND by hand
    var soundHands = XmlUtils.FileToObject<DictEntry[]>(@"d:\LMCom\rew\Web4\RwDicts\Sources\LingeaOld\design\entriesSoundByHand.xml").ToDictionary(de => de.entryId, de => de);
    foreach (var de in dictEntries) {
      DictEntry sh;
      if (!soundHands.TryGetValue(de.entryId, out sh)) continue;
      de.soundMaster = sh.soundMaster;
    }

    //oprava nekolika hesel v kodu, kvuli soundMaster:
    foreach (var en in dictEntries) { //.SelectMany(d => d.entries)) {
      switch (en.soundMaster) {
        case "en_gb/aenge3225654": en.headWords = new string[] { "crackdown" }; en.entry.DescendantsAttr("class", "entr").First().Value = "crackdown"; break;
        case "de_de/aenge68bb654": en.soundMaster = null; break;
        case "en_gb/aenbg23cb736": en.headWords = new string[] { "checkout" }; en.entry.DescendantsAttr("class", "entr").First().Value = "checkout"; break;
        case "de_de/aenge800026b4654": if (en.headWords[0] != "einig") en.soundMaster = null; break;
        case "de_de/aenge80006d5a654": if (en.headWords[0] != "niedrig") en.soundMaster = null; break;
        case "it_it/ageit7675661": if (en.entryId == "fr_fr|de_de|porto") en.soundMaster = null; break;
        //case "it_it/aspit7b9e663": if (en.entryId == "en_gb|sp_sp|sereno") en.soundMaster = null; break;
        case "it_it/aspit7b9e663": en.soundMaster = null; break;
        case "it_it/aspite03663": if (en.entryId == "de_de|sp_sp|atar") en.soundMaster = null; break;
        case "en_gb/afren193c659": en.soundMaster = "en_gb/aenbg190c736"; break;
        case "fr_fr/afrvn9d1c688": en.soundMaster = "it_it/afrit9d1d662"; break;
        case "fr_fr/afrvna71c688": en.soundMaster = "fr_fr/afrcza71d669"; break;
        case "fr_fr/afrvnc0ea688": en.soundMaster = "fr_fr/afrczc0eb669"; break;
        //case "it_it/aspit7b9e663": en.soundMaster = "it_it/aenit8000f16c660"; break;
        case "sp_sp/asplt7692724": en.soundMaster = "sp_sp/aensp80007692656"; break;
      }
    }

    //k jednomu Headword jeden zvuk
    Dictionary<Langs, Dictionary<string, string>> headwordToSoundMaster = dictEntries.Where(de => de.soundMaster != null).GroupBy(de => de.okCrs).ToDictionary(
      g => g.Key,
      g => g.GroupBy(de => de.headWords[0].ToLower()).ToDictionary(
        sg => sg.Key,
        sg => sg.Select(d => d.soundMaster).Distinct().Single()));

    //dopln soundMaster do entries
    var cnt = dictEntries.Where(en => en.soundMaster == null).Count();
    foreach (var de in dictEntries.Where(en => en.soundMaster == null && DictLib.crsLangs.Contains(en.okCrs))) {
      string sm;
      if (!headwordToSoundMaster[de.okCrs].TryGetValue(de.headWords[0].ToLower(), out sm)) continue;
      de.soundMaster = sm;
    }
    cnt = dictEntries.Where(en => en.soundMaster == null).Count();

    //vypis word lists
    //var sourcesAfter = allLangs.ToDictionary(
    //  l => l,
    //  l => dictEntries.Where(de => de.okCrs != Langs.no).Where(de => de.bothLangs().Contains(l)).SelectMany(de => getWords(de, l)).Distinct().ToArray()
    //);
    //foreach (var src in sourcesAfter) File.WriteAllLines(string.Format(@"d:\LMCom\rew\Web4\RwDicts\Sources\LingeaOld\design\wordList_{0}.txt", src.Key), src.Value.OrderBy(w => w));

  }
Esempio n. 23
0
 async private Task RestoreMediaFilesAsync()
 {
     string fullPath = "mediafiles.xml";
     ulong size = 0;
     try
     {
         Windows.Storage.StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fullPath);
         if (file != null)
         {
             var prop = await file.GetBasicPropertiesAsync();
             if (prop != null)
                 size = prop.Size;
         }
         var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
         if (stream != null)
         {
             using (var inputStream = stream.GetInputStreamAt(0))
             {
                 System.Runtime.Serialization.DataContractSerializer sessionSerializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary<string, MediaLibraryItem>));
                 defaultMediaDictionary = (Dictionary<string, MediaLibraryItem>)sessionSerializer.ReadObject(inputStream.AsStreamForRead());
                 fileDiscovered = (uint)defaultMediaDictionary.Count();
             }
         }            
     }
     catch (Exception e)
     {
         LogMessage("Exception while restoring mediafiles:" + e.Message);
     }
 }
Esempio n. 24
0
        internal static byte[] ConvertParametersToBytes(object[] parameters, bool addTypeIdPrefix = true)
        {
            var paramtersBytes = new List<byte[]>();
            foreach (var parameter in parameters)
            {
                if (parameter != null)
                {
                    if (addTypeIdPrefix) paramtersBytes.Add(GetTypeId(parameter.GetType()));

                    if (parameter is int)
                    {
                        paramtersBytes.Add(SerDe.ToBytes((int)parameter));
                    }
                    else if (parameter is long)
                    {
                        paramtersBytes.Add(SerDe.ToBytes((long)parameter));
                    }
                    else if (parameter is string)
                    {
                        paramtersBytes.Add(ToPayloadBytes(parameter.ToString()));
                    }
                    else if (parameter is bool)
                    {
                        paramtersBytes.Add(SerDe.ToBytes((bool)parameter));
                    }
                    else if (parameter is double)
                    {
                        paramtersBytes.Add(SerDe.ToBytes((double)parameter));
                    }
                    else if (parameter is byte[])
                    {
                        paramtersBytes.Add(SerDe.ToBytes(((byte[])parameter).Length));
                        paramtersBytes.Add((byte[])parameter);
                    }
                    else if (parameter is int[])
                    {
                        paramtersBytes.Add(GetTypeId(typeof(int)));
                        paramtersBytes.Add(SerDe.ToBytes(((int[])parameter).Length));
                        paramtersBytes.AddRange(((int[])parameter).Select(x => SerDe.ToBytes(x)));
                    }
                    else if (parameter is long[])
                    {
                        paramtersBytes.Add(GetTypeId(typeof(long)));
                        paramtersBytes.Add(SerDe.ToBytes(((long[])parameter).Length));
                        paramtersBytes.AddRange(((long[])parameter).Select(x => SerDe.ToBytes(x)));
                    }
                    else if (parameter is double[])
                    {
                        paramtersBytes.Add(GetTypeId(typeof(double)));
                        paramtersBytes.Add(SerDe.ToBytes(((double[])parameter).Length));
                        paramtersBytes.AddRange(((double[])parameter).Select(x => SerDe.ToBytes(x)));
                    }
                    else if (parameter is IEnumerable<byte[]>)
                    {
                        paramtersBytes.Add(GetTypeId(typeof(byte[])));
                        paramtersBytes.Add(SerDe.ToBytes(((IEnumerable<byte[]>)parameter).Count())); //TODO - Count() will traverse the collection - change interface?
                        foreach (var byteArray in (IEnumerable<byte[]>)parameter)
                        {
                            paramtersBytes.Add(SerDe.ToBytes(byteArray.Length));
                            paramtersBytes.Add(byteArray);
                        }
                    }
                    else if (parameter is IEnumerable<string>)
                    {
                        paramtersBytes.Add(GetTypeId(typeof(string)));
                        paramtersBytes.Add(SerDe.ToBytes(((IEnumerable<string>)parameter).Count())); //TODO - Count() will traverse the collection - change interface?
                        paramtersBytes.AddRange(from stringVal in (IEnumerable<string>)parameter select ToPayloadBytes(stringVal));
                    }
                    else if (parameter is IEnumerable<JvmObjectReference>)
                    {
                        paramtersBytes.Add(GetTypeId(typeof(JvmObjectReference)));
                        paramtersBytes.Add(SerDe.ToBytes(((IEnumerable<JvmObjectReference>)parameter).Count())); //TODO - Count() will traverse the collection - change interface?
                        paramtersBytes.AddRange(from jObj in (IEnumerable<JvmObjectReference>)parameter select ToPayloadBytes(jObj.Id));
                    }
                    else if (IsDictionary(parameter.GetType()))
                    {
                        // Generic Dictionary 'parameter' passed into this function is a object which lost its Generic Type T (namely Dictionary<T, T>). 
                        // Cannot neither cast to Dictionary<T, T> nor Dictionary<dynamic, dynamic>, so we need to first cast to Non-Generic interface IDictionary and then
                        // rebuild a Dictionary<dynamic, dynamic>. 
                        var nonGenericDict = (IDictionary)parameter;
                        var dict = new Dictionary<dynamic, dynamic>();
                        foreach (var k in nonGenericDict.Keys)
                        {
                            dict[k] = nonGenericDict[k];
                        }

                        Type keyType = parameter.GetType().GetGenericArguments()[0];

                        // Below serialization is coressponding to deserialization method ReadMap() of SerDe.scala
                        paramtersBytes.Add(SerDe.ToBytes(dict.Count())); // dictionary's length
                        paramtersBytes.Add(GetTypeId(keyType)); // keys' data type
                        paramtersBytes.Add(SerDe.ToBytes(dict.Count())); // keys' length, same as dictionary's length
                        paramtersBytes.AddRange(from kv in dict select ConvertParametersToBytes(new object[] { kv.Key }, false)); // keys, do not need type prefix
                        paramtersBytes.Add(SerDe.ToBytes(dict.Count())); // values' length, same as dictionary's length
                        paramtersBytes.AddRange(from kv in dict select ConvertParametersToBytes(new object[] { kv.Value })); // values, need type prefix
                    }
                    else if (parameter is JvmObjectReference)
                    {
                        paramtersBytes.Add(ToPayloadBytes((parameter as JvmObjectReference).Id));
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format("Type {0} is not supported", parameter.GetType()));
                    }
                }
                else
                {
                    paramtersBytes.Add(new [] { Convert.ToByte('n') });
                }

            }

            return paramtersBytes.SelectMany(byteArray => byteArray).ToArray();
        }