예제 #1
0
        /// <summary>
        /// Translates a text from one language to another.
        /// You can input multiple texts and get them translated all at once.
        /// Warning: Setting source and destination languages to the same language will result in an error.
        /// </summary>
        /// <param name="sourceLanguage">The language to translate from. Set it to Language.Automatic to let Google Translate determine the language.</param>
        /// <param name="destinationLanaguage">The language to translate to.</param>
        /// <param name="text">The text to translate. You may input more than one text.</param>
        /// <returns>The translated text.</returns>
        public List <Translation> Translate(Language sourceLanguage, Language destinationLanaguage, params string[] text)
        {
            //https://www.googleapis.com/language/translate/v2?key=key&q=hello%20world&source=en&target=de
            RestRequest request = CreateRequest(string.Empty);

            CheckRequest(text);

            //Required
            foreach (string q in text)
            {
                request.AddParameter("q", q);
            }
            request.AddParameter("target", destinationLanaguage.GetStringValue());

            //Optional
            if (sourceLanguage != Language.Automatic)
            {
                request.AddParameter("source", sourceLanguage.GetStringValue());
            }

            //Output
            TranslateResult results = GetResponse <TranslateResult>(request);

            return(results.Data.Translations);
        }
예제 #2
0
        // ActionClause ::= Action Article ActionSubjectTerminal
        private TranslateResult ActionClause(ILexer lexer)
        {
            var result             = new TranslateResult();
            var simpleActionResult = ActionVerbTerminal(lexer);

            result.Join(simpleActionResult);

            if (result.IsSuccessful)
            {
                var nextToken = lexer.PeekNextToken();

                while (nextToken.Type == TokenType.Article)
                {
                    lexer.ConsumeNextToken();
                    nextToken = lexer.PeekNextToken();
                }

                var actionSubjectResult = ActionSubjectTerminal(lexer);
                result.Join(actionSubjectResult);

                if (result.IsSuccessful)
                {
                    result.Code = $"{actionSubjectResult.Code}\n\t\t{simpleActionResult.Code}";
                }
            }

            return(result);
        }
예제 #3
0
 /// <summary>
 /// Скрипт ожидания появления перевода
 /// </summary>
 private void WaitScript(object e)
 {
     //Выполняем в UI потоке
     panel.Dispatcher.BeginInvoke(new Action(() =>
     {
         string result = "";
         try
         {
             //Запрашиваем результат
             result = (string)browser.InvokeScript("eval", GET_RESULT_SCRIPT);
         }
         catch { }
         //Если результат есть
         if ((result != null) && (result.Length != 0))
         {
             //ОВзвращаем результат
             TranslateResult?.Invoke(result);
         }
         //Если результата нету
         else
         {
             //Запускаем таймер ещё раз
             waitTimer.Change(100, Timeout.Infinite);
         }
     }));
 }
예제 #4
0
        public void LinqParse_select_another_object_clause()
        {
            using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
            {
                ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
                var q = from s in set
                        select new Temp
                {
                    Str = s.CharacterField,
                    dt  = (DateTime)s.DateTimeField,
                    de  = (Decimal)s.DecimalNumberField
                };
                Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
                //var tr2 = ((ARQueryProvider<NRemedy_Test_Regular_Form>)q.Provider).ExecuteOnlyTranslate(q.Expression);
                TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
                Assert.IsTrue(tr.SelectResult != null);

                DateTime dt = DateTime.Now;
                NRemedy_Test_Regular_Form tmp = new NRemedy_Test_Regular_Form();
                tmp.CharacterField     = "3.14";
                tmp.DateTimeField      = dt;
                tmp.DecimalNumberField = 3.14m;

                var  fun  = tr.SelectResult.SelectExpression.Compile();
                Temp temp = (Temp)fun.DynamicInvoke(tmp);
                Assert.AreEqual("3.14", temp.Str);
                Assert.AreEqual(dt, temp.dt);
                Assert.AreEqual(3.14m, temp.de);

                Assert.IsTrue(tr.SelectResult.SelectedProperties.First(m => m == "CharacterField") != null);
                Assert.IsTrue(tr.SelectResult.SelectedProperties.First(m => m == "DateTimeField") != null);
                Assert.IsTrue(tr.SelectResult.SelectedProperties.First(m => m == "DecimalNumberField") != null);
            }
        }
예제 #5
0

        
예제 #6
0
        private object Execute(TranslateResult result)
        {
            Delegate projector = result.Projector.Compile();

            if (Connection.State != ConnectionState.Open)
            {
                Connection.Open();
            }

            OleDbCommand cmd = Connection.CreateCommand();

            cmd.CommandText = result.CommandText;

            if (Log != null)
            {
                Log.Invoke(result.CommandText);
            }

            OleDbDataReader reader = cmd.ExecuteReader();

            Type elementType = result.Projector.Body.Type; //TypeSystem.GetElementType(result.Projector.Body.Type);

            return(Activator.CreateInstance(
                       typeof(ProjectionReader <>).MakeGenericType(elementType),
                       BindingFlags.Instance | BindingFlags.NonPublic,
                       null,
                       new object[] { reader, projector, this },
                       null));
        }
예제 #7
0
 private void ScriptTranslated(DatabaseType dbType, DatabaseObject dbObject, TranslateResult result)
 {
     if (this.OnTranslated != null)
     {
         this.OnTranslated(dbType, dbObject, result);
     }
 }
예제 #8
0
        public void LinqParse_select_anouymous_object_clause()
        {
            using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
            {
                ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
                var q = from s in set
                        select new
                {
                    s.RealNumberField,
                    s.DateTimeField
                };
                Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
                TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
                Assert.IsTrue(tr.SelectResult != null);

                DateTime dt = DateTime.Now;
                NRemedy_Test_Regular_Form tmp = new NRemedy_Test_Regular_Form();
                tmp.RealNumberField = 3.14;
                tmp.DateTimeField   = dt;

                var     fun   = tr.SelectResult.SelectExpression.Compile();
                dynamic dymic = fun.DynamicInvoke(tmp);
                Assert.AreEqual(3.14, dymic.RealNumberField);
                Assert.AreEqual(dt, dymic.DateTimeField);

                Assert.IsTrue(tr.SelectResult.SelectedProperties.First(m => m == "RealNumberField") != null);
                Assert.IsTrue(tr.SelectResult.SelectedProperties.First(m => m == "DateTimeField") != null);
            }
        }
예제 #9
0
 public static int applyTranslate(ILuaState luaState)
 {
     if (luaState.IsTable(-1))
     {
         TranslateResult transRes = new TranslateResult();
         // 位移目标
         luaState.GetField(-1, "target");
         transRes.target = (Unit)luaState.ToUserData(-1);
         luaState.Pop(1);
         // 行偏移量
         luaState.GetField(-1, "offsetRow");
         transRes.offsetRow = luaState.ToInteger(-1);
         luaState.Pop(1);
         // 列偏移量
         luaState.GetField(-1, "offsetCol");
         transRes.offsetCol = luaState.ToInteger(-1);
         luaState.Pop(1);
         //// 位移原因
         //luaState.GetField(-1, "translateReason");
         //transRes. = luaState.ToInteger(-1);
         //luaState.Pop(1);
         ProcessManager.getInstance().addResult(transRes);
     }
     return 0;
 }
예제 #10
0
        public static async Task <TranslateResult> GetTranslateResult(string text, string targetLangCode = "vi")
        {
            if (text.Length > 0)
            {
                try
                {
                    HttpClient client = new HttpClient();
                    client.Timeout = TimeSpan.FromMinutes(5);

                    string translateUrl = @"http://translate.google.com/translate_a/single?client=gtx&dt=t&dt=bd&dj=1" +
                                          "&source=input&sl=auto&tl=" + targetLangCode + "&q=" + Uri.EscapeDataString(text);

                    Stream response = await client.GetStreamAsync(translateUrl);

                    using (StreamReader reader = new StreamReader(response))
                    {
                        string          responseString = reader.ReadToEnd();
                        TranslateResult result         = JsonConvert.DeserializeObject <TranslateResult>(responseString);
                        return(result);
                    }
                }
                catch
                {
                    return(null);
                }
                //return translateText;
            }
            else
            {
                //MessageBox.Show("Vui lòng chọn lại.");
                return(null);
            }
        }
        public object Execute(Expression expression)
        {
            TranslateResult result = this.Translate(expression);

            if (result.SQLCommand != null)
            {
                this.misession.Do(result.SQLCommand);
            }

            Type elementType = TypeSystem.GetElementType(expression.Type);

            IDataReader        reader       = this.readerfactory.GetReaderFor(result.TableName);
            EntityMaterializer materializer = this.entityfactory.CreateMaterializerFor(result.TableName, reader);

            if (result.Projector != null)
            {
                Delegate projector = result.Projector.Compile();

                return(Activator.CreateInstance(typeof(ProjectionReader <>).MakeGenericType(elementType),
                                                new object[] { reader, projector }));
            }
            else
            {
                return(Activator.CreateInstance(typeof(RowList <>).MakeGenericType(elementType),
                                                new object[] { reader, materializer }));
            }
        }
예제 #12
0
        public bool AddNew(List <TTable> records)
        {
            if (records == null || records.Count == 0)
            {
                return(false);
            }

            List <List <Parameter> > listParameters = new List <List <Parameter> >();

            TranslateResult resultFirst = null;
            TranslateResult resultNext  = null;

            for (int i = 0, count = records.Count; i < count; i++)
            {
                var record = records[i];
                if (i == 0)
                {
                    resultFirst = PreAddNew(record, null);
                    listParameters.Add(resultFirst.Parameters);
                }
                else
                {
                    resultNext = PreAddNew(record, resultFirst.Parameters);
                    listParameters.Add(resultNext.Parameters);
                }
            }

            TableSchema tableSchema = TableSchemaResolver.GetTableSchema(typeof(TTable));

            _sqlBuilder.From(tableSchema.PrimaryTable);

            for (int i = 0, fieldCount = tableSchema.FieldsSchema.Count; i < fieldCount; i++)
            {
                _sqlBuilder.Column(tableSchema.FieldsSchema[i].FieldName);
            }

            _dbSet.BeginTransaction();

            if (listParameters.Count == 1)
            {
                this._dbError = _excuteUpdate.Excute <TTable>(_sqlBuilder.Insert(), listParameters[0], _dbSet.Transaction);
            }
            else
            {
                this._dbError = _excuteUpdate.ExcuteBatch <TTable>(_sqlBuilder.Insert(), listParameters, _dbSet.Transaction);
            }

            if (this._dbError.Code == ErrorCode.Success)
            {
                records.ForEach(rec => InsertRecordToCache(rec));
            }
            else
            {
                _dbSet.Cancel();
            }

            return(this._dbError.Code == ErrorCode.Success);
        }
예제 #13
0
        private TranslateResult ParseTranslateResponse(string response)
        {
            var translateResult = new TranslateResult();
            var jResult         = JArray.Parse(response);



            return(translateResult);
        }
예제 #14
0
        /// <summary>
        /// Translate Single Criteria
        /// </summary>
        /// <param name="criteria">criteria</param>
        /// <param name="parameters">parameters</param>
        /// <returns></returns>
        TranslateResult TranslateCriteria(IQuery query, Criteria criteria, Dictionary <string, object> parameters, string objectName)
        {
            if (criteria == null)
            {
                return(TranslateResult.Empty);
            }
            IQuery valueQuery    = criteria.Value as IQuery;
            string parameterName = criteria.Name + ParameterSequence++;
            string sqlOperator   = GetOperator(criteria.Operator);

            if (valueQuery != null)
            {
                string valueQueryObjectName = DataManager.GetQueryRelationObjectName(ServerType.SQLServer, valueQuery);
                var    valueQueryField      = DataManager.GetField(ServerType.SQLServer, valueQuery, valueQuery.QueryFields[0]);
                string subObjName           = "TSB" + subObjectSequence;
                subObjectSequence++;
                var    subQueryResult = ExecuteTranslate(valueQuery, parameters, subObjName, true);
                string topString      = "";
                if (sqlOperator != InOperator && sqlOperator != NotInOperator)
                {
                    topString = "TOP 1";
                }
                string conditionString = subQueryResult.ConditionString;
                if (!string.IsNullOrWhiteSpace(conditionString))
                {
                    conditionString = "WHERE " + conditionString;
                }
                var valueQueryCondition = string.Format("{0} {1} (SELECT {2} {3}.[{4}] FROM [{5}] AS {6}{7} {8} {9})"
                                                        , ConvertCriteriaName(valueQuery, objectName, criteria)
                                                        , sqlOperator
                                                        , topString
                                                        , subObjName
                                                        , valueQueryField.FieldName
                                                        , valueQueryObjectName
                                                        , subObjName
                                                        , subQueryResult.JoinScript
                                                        , conditionString
                                                        , subQueryResult.OrderString);
                var valueQueryResult = TranslateResult.CreateNewResult(valueQueryCondition);
                if (!subQueryResult.WithScripts.IsNullOrEmpty())
                {
                    valueQueryResult.WithScripts       = new List <string>(subQueryResult.WithScripts);
                    valueQueryResult.RecurveObjectName = subQueryResult.RecurveObjectName;
                    valueQueryResult.RecurvePetName    = subQueryResult.RecurvePetName;
                }
                return(valueQueryResult);
            }
            parameters.Add(parameterName, FormatCriteriaValue(criteria.Operator, criteria.GetCriteriaRealValue()));
            var criteriaCondition = string.Format("{0} {1} {2}{3}"
                                                  , ConvertCriteriaName(query, objectName, criteria)
                                                  , sqlOperator
                                                  , parameterPrefix
                                                  , parameterName);

            return(TranslateResult.CreateNewResult(criteriaCondition));
        }
예제 #15
0
        public async Task <string> GetEngNameAsync(string name)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(await GetTranslateAsync(name));

            string          json   = JsonConvert.SerializeXmlNode(doc);
            JObject         search = JObject.Parse(json);
            TranslateResult Str    = JsonConvert.DeserializeObject <TranslateResult>(search.ToString());

            return(Str.String.Text);
        }
예제 #16
0
        /// <summary>
        /// translate query condition
        /// </summary>
        /// <param name="queryItem">query condition</param>
        /// <returns></returns>
        TranslateResult TranslateCondition(IQuery query, Tuple <QueryOperator, IQueryItem> queryItem, Dictionary <string, object> parameters, string objectName)
        {
            if (queryItem == null)
            {
                return(TranslateResult.Empty);
            }
            Criteria criteria = queryItem.Item2 as Criteria;

            if (criteria != null)
            {
                return(TranslateCriteria(query, criteria, parameters, objectName));
            }
            IQuery groupQuery = queryItem.Item2 as IQuery;

            if (groupQuery != null && groupQuery.Criterias != null && groupQuery.Criterias.Count > 0)
            {
                groupQuery.SetEntityType(query.EntityType);
                if (groupQuery.Criterias.Count == 1)
                {
                    var firstCriterias = groupQuery.Criterias[0];
                    if (firstCriterias.Item2 is Criteria)
                    {
                        return(TranslateCriteria(groupQuery, firstCriterias.Item2 as Criteria, parameters, objectName));
                    }
                    return(TranslateCondition(groupQuery, firstCriterias, parameters, objectName));
                }
                StringBuilder subCondition        = new StringBuilder("(");
                List <string> groupWithScripts    = new List <string>();
                string        recurveTableName    = string.Empty;
                string        recurveTablePetName = string.Empty;
                int           index = 0;
                foreach (var subQueryItem in groupQuery.Criterias)
                {
                    var subGroupResult = TranslateCondition(groupQuery, subQueryItem, parameters, objectName);
                    if (!subGroupResult.WithScripts.IsNullOrEmpty())
                    {
                        recurveTableName    = subGroupResult.RecurveObjectName;
                        recurveTablePetName = subGroupResult.RecurvePetName;
                        groupWithScripts.AddRange(subGroupResult.WithScripts);
                    }
                    subCondition.AppendFormat("{0} {1}"
                                              , index > 0 ? " " + subQueryItem.Item1.ToString() : ""
                                              , subGroupResult.ConditionString);
                    index++;
                }
                var groupResult = TranslateResult.CreateNewResult(subCondition.Append(")").ToString());
                groupResult.RecurveObjectName = recurveTableName;
                groupResult.RecurvePetName    = recurveTablePetName;
                groupResult.WithScripts       = groupWithScripts;
                return(groupResult);
            }
            return(TranslateResult.Empty);
        }
예제 #17
0
        /// <summary>
        /// 获取某一语言下的某一种msgid的翻译
        /// </summary>
        /// <param name="cultureCode">语言code,如zh-CN</param>
        /// <param name="msgid">某条语言的唯一标识</param>
        /// <returns></returns>
        public TranslateResult GetTranslate(string cultureCode, string msgid)
        {
            //获取关联索引
            var AttachLannguageIndex      = _managerLanguageListIndex.ContainsKey(cultureCode)? _managerLanguageListIndex[cultureCode]:null;
            var AttachSingleLanguageModel = AttachLannguageIndex.SingleLanguage;

            var msgresult = AttachSingleLanguageModel.GetTranslate(msgid);

            TranslateResult result = new TranslateResult(msgid, msgresult);

            return(result);
        }
        public async void Finder_Should_Return_Empty_If_NotEnabled()
        {
            TranslatorConfiguration.CanSupport().Returns(false);
            TranslatorConfiguration.IsActive().Returns(false);

            TurengMeanFinder sut = ResolveSut();

            var             translateRequest = new TranslateRequest("hi", "en");
            TranslateResult response         = await sut.FindMean(translateRequest);

            response.IsSuccess.ShouldBe(false);
            response.ResultMessage.ShouldBe(new Maybe <string>());
        }
예제 #19
0
 private void Where(TranslateResult result, Concatenate concatenate)
 {
     try
     {
         result.CommandText = TranslateToNativeColumn(result.CommandText);
         _parameters.AddRange(result.Parameters);
         _sqlBuilder.Where(result.CommandText, concatenate);
     }
     catch (Exception e)
     {
         this._dbError.Code = ErrorCode.InvalidOperation;
         this._dbError.Text = e.Message;
     }
 }
예제 #20
0
 public void LinqParse_Take_const_clause()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         var q = from s in set.Take(11)
                 select s;
         Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.NoQueryableResult.HasTake);
         Assert.IsNotNull(tr.NoQueryableResult.Take);
         Assert.AreEqual(11, tr.NoQueryableResult.Take);
     }
 }
예제 #21
0
 public void LinqParse_Take_Skip_Combine_clause()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         var q = from s in set.Take(10).Skip(2)
                 select s;
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.NoQueryableResult.HasTake);
         Assert.IsTrue(tr.NoQueryableResult.HasSkip);
         Assert.AreEqual(10, tr.NoQueryableResult.Take);
         Assert.AreEqual(2, tr.NoQueryableResult.Skip);
     }
 }
예제 #22
0
 public void LinqParse_OrderByDescending_clause()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         var q = from s in set
                 orderby s.CharacterField descending
                 select s;
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.OrderByResult != null);
         Assert.AreEqual("CharacterField", tr.OrderByResult.OrderByList.First().Property);
         Assert.AreEqual("OrderByDescending", tr.OrderByResult.OrderByList.First().Method);
     }
 }
예제 #23
0
 public void LinqParse_where_gt_clause()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         var q = from s in set
                 where s.IntegerField > 1
                 select s;
         Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.ConditionResult != null);
         Assert.AreEqual("('20000002' > 1)", tr.ConditionResult.Qulification.ToString());
     }
 }
예제 #24
0
        public static async Task <TranslateResult> TranslateText(string input, lang lang_in = lang.en, lang lang_out = lang.vi,
                                                                 string TemplateRequest     = "https://translate.google.com/translate_a/single?client=webapp&sl={lang_in}&tl={lang_out}&hl=vi&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&pc=1&otf=1&ssel=3&tsel=3&kc=1&tk={tk}&q={input}")
        {
            var r = new TranslateResult
            {
                IsSuccess    = false,
                lang_in      = lang_in,
                lang_out     = lang_out,
                Text_in      = input,
                Text_out     = input,
                ResponseCode = null
            };

            try
            {
                string tk  = computed_tk(input);
                string url = TemplateRequest
                             .Replace("{lang_in}", lang_in.ToString())
                             .Replace("{lang_out}", lang_out.ToString())
                             .Replace("{tk}", tk.ToString())
                             .Replace("{input}", Uri.EscapeUriString(input));
                Debug.WriteLine(url);

                var client  = new RestClient(url);
                var request = new RestRequest(Method.GET);
                foreach (var item in cookies)
                {
                    request.AddCookie(item.Name, item.Value);
                }
                var restResponse = await client.ExecuteTaskAsync(request);

                r.ResponseCode = restResponse.StatusCode;
                r.ResponseText = restResponse.Content;
                if (r.ResponseCode == HttpStatusCode.OK)
                {
                    r.IsSuccess = true;
                    r.Text_out  = Regex.Match(r.ResponseText, "\\[\\[\\[\"([^\"]+)").Groups[1].Value;
                }
                else
                {
                    Count_fail++;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(input + ": " + ex);
            }
            return(r);
        }
예제 #25
0
 public void LinqParse_Skip_var_clause()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         string i = "10";
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         var q = from s in set.Skip(Convert.ToInt32(i))
                 select s;
         Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.NoQueryableResult.HasSkip);
         Assert.IsNotNull(tr.NoQueryableResult.Skip);
         Assert.AreEqual(10, tr.NoQueryableResult.Skip);
     }
 }
예제 #26
0
        public override object Execute(Expression expression)
        {
            TranslateResult result = Translate(expression);

            Delegate projector = result.Projector.Compile();

            Type modelType  = result.Projector.Parameters[0].Type;
            Type resultType = result.Projector.ReturnType;

            var executeMethod = _context.GetType()
                                .GetMethod("ExecuteSoqlQuery")
                                .MakeGenericMethod(modelType, resultType);

            return(executeMethod.Invoke(_context, new object[] { result.CommandText, projector }));
        }
예제 #27
0
 public void LinqParse_where_mixed_clause_02()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         var q = from s in set
                 where s.CharacterField.Contains("%Hello world%") && (s.IntegerField == 65535 || s.IntegerField > 65535)
                 select s;
         Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.ConditionResult != null);
         Assert.AreEqual("(('20000001' LIKE \"%Hello world%\") AND (('20000002' = 65535) OR ('20000002' > 65535)))"
                         , tr.ConditionResult.Qulification.ToString());
     }
 }
예제 #28
0
        private TranslateResult GetTerminalTranslatedCode(ILexer lexer, TerminalTypes terminalType)
        {
            var terminals = _terminalCache[terminalType];

            var result = new TranslateResult()
            {
                Code = " "
            };
            var token = lexer.GetNextToken();

            if (token.Type != TokenType.Keyword)
            {
                result.ErrorMessage = string.Format(ErrorMessageFormat, GetKeywordList(terminals), token.Text);

                return(result);
            }

            if (!terminals.ContainsKey((token.Text.ToLower())))
            {
                result.ErrorMessage = $@"Keyword not defined: {token.Text}";
            }
            else
            {
                var terminal = terminals[token.Text.ToLower()];

                if (terminal.SupportingKeywords != null)
                {
                    // consume supporting keywords
                    for (var i = 0; i < terminal.SupportingKeywords.Length; i++)
                    {
                        var supportingKeyword = terminal.SupportingKeywords[i];

                        token = lexer.GetNextToken();

                        if (token.Type != TokenType.Keyword)
                        {
                            result.ErrorMessage = string.Format(ErrorMessageFormat, supportingKeyword, token.Text);

                            return(result);
                        }
                    }
                }
                result.Code = terminal.TranslateTo;
            }
            return(result);
        }
예제 #29
0
 public void LinqParse_where_lteq_clause()
 {
     using (ARLoginContext context = new ARLoginContext(TestServer, TestAdmin, TestAdminPwd))
     {
         ARSet <NRemedy_Test_Regular_Form> set = new ARSet <NRemedy_Test_Regular_Form>(context);
         DateTime dt  = DateTime.Now;
         string   str = dt.ToString();
         var      q   = from s in set
                        where s.RealNumberField <= 3.14
                        select s;
         Assert.IsTrue(q.Provider is ARQueryProvider <NRemedy_Test_Regular_Form>);
         TranslateResult tr = q.Translate <NRemedy_Test_Regular_Form>();
         Assert.IsTrue(tr.ConditionResult != null);
         Assert.AreEqual("('20000006' <= 3.14)"
                         , tr.ConditionResult.Qulification.ToString());
     }
 }
예제 #30
0
        private TranslateResult BusinessRule(ILexer lexer)
        {
            var result = new TranslateResult();

            var token = lexer.PeekNextToken();

            if (token.Type == TokenType.If)
            {
                result = IfClause(lexer);
            }
            else
            {
                result.ErrorMessage = string.Format(ErrorMessageFormat, "If", token.Text);
            }

            return(result);
        }
        public async void Finder_Should_Work()
        {
            TranslatorConfiguration.CanSupport().Returns(true);
            TranslatorConfiguration.IsActive().Returns(true);

            MeanOrganizer.OrganizeMean(Arg.Any <string>(), Arg.Any <string>()).Returns(Task.FromResult(new Maybe <string>("selam")));

            RestClient.ExecuteGetTaskAsync(Arg.Any <RestRequest>()).Returns(Task.FromResult <IRestResponse>(new RestResponse {
                StatusCode = HttpStatusCode.OK
            }));

            TurengMeanFinder sut = ResolveSut();

            var             translateRequest = new TranslateRequest("hi", "en");
            TranslateResult response         = await sut.FindMean(translateRequest);

            response.IsSuccess.ShouldBe(true);
            response.ResultMessage.ShouldBe(new Maybe <string>("selam"));
        }
예제 #32
0
 public InjectedExpression(TranslateResult translateResult, Type type)
 {
     this.TranslateResult = translateResult;
     this.type = type;
 }