Example #1
0
 /// <summary>
 /// Creates instance of the <see cref="Action"></see> class with properties initialized with specified parameters.
 /// </summary>
 /// <param name="returnType">The return type of the action.</param>
 /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
 /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
 /// <param name="condition">The launch condition for the <see cref="Action"/>.</param>
 protected Action(Return returnType, When when, Step step, Condition condition)
 {
     Return = returnType;
     Step = step;
     When = when;
     Condition = condition;
 }
		/// <summary>
		/// Creates a vocabulary from a list of strings.
		/// Applies grouping.
		/// Applies stop words and stemming (if available for the language)
		/// Does not performs a Distinct
		/// </summary>
		/// <param name="language">la cultura para la que se realiza el análisis</param>
		/// <param name="strings">la cadenas de texto (no están divididas en words)</param>
		/// <returns></returns>
		public Return<List<string>> CreateVocabulary(string language, List<string> strings)
		{
			Return<List<string>> _answer = new Return<List<string>>();
			if (strings == null)
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("strings"), this.GetType());
			}
			else
			{
				try
				{
					Return<EnumLanguage> _answerParseLanguage = MLUtility.ParseLanguage(language);
					if (_answerParseLanguage.theresError)
					{
						_answer.theresError = true;
						_answer.error = _answerParseLanguage.error;
					}
					else
						_answer = CreateVocabulary(_answerParseLanguage.data, strings);
				}
				catch (Exception _ex)
				{
					_answer.theresError = true;
					_answer.error = Utility.GetError(_ex, this.GetType());
				}
			}
			return _answer;
		}
 public static Return<List<string>> RegexTest(Dictionary<string, bool> dictionary, string pattern)
 {
     Return<List<string>> _answer = new Return<List<string>>() { data = new List<string>() };
     if (dictionary == null)
     {
         _answer.theresError = true;
         _answer.error = Utility.GetError(new ArgumentNullException("dictionary"), typeof(Utility));
     }
     else
         if (string.IsNullOrEmpty(pattern))
         {
             _answer.theresError = true;
             _answer.error = Utility.GetError(new ArgumentNullException("pattern"), typeof(Utility));
         }
         else
         {
             try
             {
                 foreach (string _key in dictionary.Keys)
                 {
                     if (Regex.IsMatch(_key, pattern) != dictionary[_key])
                         _answer.data.Add(_key);
                 }
             }
             catch (Exception _ex)
             {
                 _answer.theresError = true;
                 _answer.error = Utility.GetError(_ex, typeof(Utility));
             }
         }
     return _answer;
 }
 public static Return<double> ArithmeticMean(List<double> numbers)
 {
     Return<double> _answer = new Return<double>();
     try
     {
         if (numbers == null)
         {
             _answer.theresError = true;
             _answer.error = Utility.GetError(new ArgumentException("numbers"), typeof(Mathematics));
         }
         else
             if (!numbers.Any())
                 _answer.data = 0;
             else
             {
                 double _sum = 0;
                 int _count = numbers.Count();
                 numbers.ForEach(n => _sum += n);
                 _answer.data = _sum / _count;
             }
     }
     catch (Exception _ex)
     {
         _answer.theresError = true;
         _answer.error = Utility.GetError(_ex, typeof(Mathematics));
     }
     return _answer;
 }
Example #5
0
    public void LoadReturn()
    {
        Return e = new Return();
        if (ReturnID == 0)
        {
            imgOrder.ImageUrl = "none";
            btnOk.Enabled = true;
        }
        else
        {
            e = ReturnBLL.Get(ReturnID);
            imgOrder.ImageUrl = BarcodeBLL.Url4Return(e.ID);
            btnOk.Enabled = false;
        }

        txtNote.Text = e.Note;

        txtDate.Text = e.Date.ToStringVN_Hour();

        PackOrderList = e.PackOrders.Select(r => r.ID).ToList();

        urlPrint.NavigateUrl = ResolveClientUrl(string.Format("~/Store/PrintReturn.aspx?ReturnID={0}", e.ID));

        GridViewPack.DataBind();

        CurrentDIN = "";
        imgCurrentDIN.ImageUrl = "none";

        GridViewSum.DataBind();
    }
Example #6
0
    public void LoadReturn()
    {
        Return e = new Return();
        if (ReturnID == 0)
        {
            imgOrder.ImageUrl = "none";
            btnOk.Enabled = true;
        }
        else
        {
            e = ReturnBLL.Get(ReturnID);
            imgOrder.ImageUrl = BarcodeBLL.Url4Return(e.ID);
            btnOk.Enabled = false;
        }

        txtNote.Text = e.Note;

        txtDate.Text = e.Date.ToStringVN_Hour();

        PackOrderList = e.PackOrders.Select(r => r.ID).ToList();

        GridViewPack.DataBind();

        CurrentDIN = "";
        imgCurrentDIN.ImageUrl = "none";
    }
		public Return<Task> GetTask(string taskName)
		{
			Return<Task> _answer = new Return<Task>();
			if (string.IsNullOrEmpty(taskName))
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("taskName"), this.GetType());
			}
			else
			{
				Return<SqlConnection> _answerConnection = this.connection;
				if (_answerConnection.theresError)
				{
					_answer.theresError = true;
					_answer.error = _answerConnection.error;
				}
				else
				{
					try
					{
						using (SqlConnection _connection = _answerConnection.data)
						{
							if (_connection.State != ConnectionState.Open)
								_connection.Open();
							using (SqlCommand _command = new SqlCommand() { CommandType = CommandType.Text, Connection = _connection, CommandTimeout = timeoutInSecondsBD })
							{//using SqlCommand

								string _fields = string.Format("{0},{1},{2},{3},{4}", SQLGrp_Class.FLD_TASK_ID, SQLGrp_Class.FLD_TASK_NAME, SQLGrp_Class.FLD_TASK_GCDESCRIPTION
																									, SQLGrp_Class.FLD_TASK_CREATIONDATE, SQLGrp_Class.FLD_TASK_LASTMODIFICATIONDATE);

								_command.CommandText = string.Format("select {0} from {1} where {2}=@taskName", _fields, SQLGrp_Class.TAB_TASK, SQLGrp_Class.FLD_TASK_NAME);
								_command.Parameters.AddWithValue("@taskName", taskName);
								using (SqlDataReader _dataReader = _command.ExecuteReader())
								{//using SqlDataReader
									using (DataTable _table = new DataTable())
									{//using DataTable
										_table.Load(_dataReader);
										Return<List<Task>> _answerConversion = DataRowCollectionToTask(_table.Rows);
										if (_answerConversion.theresError)
										{
											_answer.theresError = true;
											_answer.error = _answerConversion.error;
										}
										else
											_answer.data = _answerConversion.data.FirstOrDefault();
									}//using DataTable
								}//using SqlDataReader
							}//using SqlCommand
						}
					}
					catch (Exception _ex)
					{
						_answer.theresError = true;
						_answer.error = Utility.GetError(_ex, this.GetType());
					}
				}
			}
			return _answer;
		}
 public static Return<SqlConnection> GetSqlConnection(string connectionString)
 {
     Return<SqlConnection> _answer = new Return<SqlConnection>();
     if (string.IsNullOrEmpty(connectionString))
     {
         _answer.theresError = true;
         _answer.error = Utility.GetError(new ArgumentException("connectionString"), typeof(Utility));
     }
     else
     {
         try
         {
             int _indexInit = connectionString.IndexOf("["), _indexEnd = connectionString.IndexOf("]");
             if (_indexInit < 0 || _indexEnd < 0 || _indexInit >= _indexEnd)
             {
                 string _message = "The connection string has a wrong format";
                 _answer.theresError = true;
                 _answer.error = Utility.GetError(new Exception(_message), typeof(DataUtility));
             }
             else
             {
                 string _password = connectionString.Substring(_indexInit + 1, _indexEnd - _indexInit - 1);
                 if (string.IsNullOrEmpty(_password))
                 {
                     string _message = "The password in the connection string is empty";
                     _answer.theresError = true;
                     _answer.error = Utility.GetError(new Exception(_message), typeof(DataUtility));
                 }
                 else
                 {
                     Return<string> _answerDecryptString = SecurityUtility.DecryptString(_password);
                     if (_answerDecryptString.theresError)
                     {
                         _answer.theresError = true;
                         _answer.error = _answerDecryptString.error;
                     }
                     else
                     {
                         string _firPart = connectionString.Substring(0, _indexInit)
                             , _lastPart = connectionString.Substring(_indexEnd + 1, connectionString.Length - _indexEnd - 1);
                         string _realConnectionString = string.Format("{0}{1}{2}", _firPart, _answerDecryptString.data, _lastPart);
                         _answer.data = new SqlConnection(_realConnectionString);
                     }
                 }
             }
         }
         catch (Exception _ex)
         {
             _answer.theresError = true;
             _answer.error = Utility.GetError(_ex, typeof(Utility));
         }
     }
     return _answer;
 }
        public static Return<string> DecryptString(string inputString, string key)
        {
            Return<string> _answer = new Return<string>() { data = string.Empty };
            if (string.IsNullOrEmpty(inputString))
            {
                _answer.theresError = true;
                _answer.error = Utility.GetError(new ArgumentException("inputString"), typeof(Utility));
            }
            else
                if (string.IsNullOrEmpty(key))
                {
                    _answer.theresError = true;
                    _answer.error = Utility.GetError(new ArgumentException("key"), typeof(Utility));
                }
                else
                {
                    try
                    {
                        TripleDESCryptoServiceProvider _tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                        // Put the string into a byte array
                        byte[] _inputbyteArray = new byte[inputString.Length / 2]; //Encoding.UTF8.GetBytes(inputString);
                        // Create the crypto objects, with the key, as passed in
                        MD5CryptoServiceProvider _hashMD5 = new MD5CryptoServiceProvider();
                        _tripleDESCryptoServiceProvider.Key = _hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
                        _tripleDESCryptoServiceProvider.Mode = CipherMode.ECB;
                        // Put the input string into the byte array
                        for (int _x = 0; _x < _inputbyteArray.Length; _x++)
                        {
                            Int32 _iJ = (Convert.ToInt32(inputString.Substring(_x * 2, 2), 16));
                            _inputbyteArray[_x] = new Byte();
                            _inputbyteArray[_x] = (byte)_iJ;
                        }
                        MemoryStream _memoryStream = new MemoryStream();
                        CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _tripleDESCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
                        // Flush the data through the crypto stream into the memory stream
                        _cryptoStream.Write(_inputbyteArray, 0, _inputbyteArray.Length);
                        _cryptoStream.FlushFinalBlock();

                        // Get the decrypted data back from the memory stream
                        StringBuilder _stringBuilder = new StringBuilder();
                        byte[] _byteArray = _memoryStream.ToArray();
                        _memoryStream.Close();
                        for (int I = 0; I < _byteArray.Length; I++)
                            _stringBuilder.Append((char)(_byteArray[I]));
                        _answer.data = _stringBuilder.ToString();
                    }
                    catch (Exception _ex)
                    {
                        _answer.theresError = true;
                        _answer.error = Utility.GetError(_ex, typeof(Utility));
                    }
                }
            return _answer;
        }
 public static Return<string> EncryptString(string inputString, string key)
 {
     Return<string> _answer = new Return<string>() { data = string.Empty };
     if (string.IsNullOrEmpty(inputString))
     {
         _answer.theresError = true;
         _answer.error = Utility.GetError(new ArgumentException("inputString"), typeof(Utility));
     }
     else
         if (string.IsNullOrEmpty(key))
         {
             _answer.theresError = true;
             _answer.error = Utility.GetError(new ArgumentException("key"), typeof(Utility));
         }
         else
         {
             try
             {
                 TripleDESCryptoServiceProvider _tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                 // Put the string into a byte array
                 byte[] _inputbyteArray = Encoding.UTF8.GetBytes(inputString);
                 // Create the crypto objects, with the key, as passed in
                 MD5CryptoServiceProvider _hashMD5 = new MD5CryptoServiceProvider();
                 _tripleDESCryptoServiceProvider.Key = _hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
                 _tripleDESCryptoServiceProvider.Mode = CipherMode.ECB;
                 MemoryStream _memoryStream = new MemoryStream();
                 CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _tripleDESCryptoServiceProvider.CreateEncryptor(), CryptoStreamMode.Write);
                 // Write the byte array into the crypto stream
                 // (It will end up in the memory stream)
                 _cryptoStream.Write(_inputbyteArray, 0, _inputbyteArray.Length);
                 _cryptoStream.FlushFinalBlock();
                 // Get the data back from the memory stream, and into a string
                 StringBuilder _stringBuilder = new StringBuilder();
                 byte[] _byteArray = _memoryStream.ToArray();
                 _memoryStream.Close();
                 for (int I = 0; I < _byteArray.Length; I++)
                 {
                     //Format as hex
                     _stringBuilder.AppendFormat("{0:X2}", _byteArray[I]);
                 }
                 _answer.data = _stringBuilder.ToString();
             }
             catch (Exception _ex)
             {
                 _answer.theresError = true;
                 _answer.error = Utility.GetError(_ex, typeof(Utility));
             }
         }
     return _answer;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strParamID = Request["ReturnID"];

            if (!string.IsNullOrEmpty(strParamID))
            {
                returnObj = ReturnBLL.Get(strParamID.ToInt());

                if (returnObj != null)
                {
                    LabelTitle1.Text = "BIÊN BẢN THU HỒI";

                    LoadReturn();

                    RedBloodDataContext db = new RedBloodDataContext();

                    var v1 = db.PackOrders.Where(r => r.ReturnID.Value == returnObj.ID)
                        .Select(r => r.Pack)
                        .ToList();

                    var v = v1.GroupBy(r => r.ProductCode)
                        .Select(r => new
                        {
                            ProductDesc = ProductBLL.GetDesc(r.Key),
                            ProductCode = r.Key,
                            Sum = r.Count(),
                            BloodGroupSumary = r.GroupBy(r1 => r1.Donation.BloodGroup).Select(r1 => new
                            {
                                BloodGroupDesc = BloodGroupBLL.GetDescription(r1.Key),
                                Total = r1.Count(),
                                VolumeSumary = r1.GroupBy(r2 => r2.Volume).Select(r2 => new
                                {
                                    Volume = r2.Key.HasValue ? r2.Key.Value.ToString() : "_",
                                    Total = r2.Count(),
                                    DINList = r2.Select(r3 => new { DIN = r3.DIN }).OrderBy(r4 => r4.DIN),
                                }).OrderBy(r2 => r2.Volume)
                            }).OrderBy(r1 => r1.BloodGroupDesc),
                        });

                    GridViewSum.DataSource = v;
                    GridViewSum.DataBind();

                    LableCount.Text = v1.Count().ToStringRemoveZero();
                }
            }
        }
    }
Example #12
0
 public JsonMtGOX()
 {
     high = new High();
     low = new Low();
     avg = new Avg();
     vwap = new Vwap();
     vol = new Vol();
     lastlocal = new LastLocal();
     lastorig = new LastOrig();
     lastall = new LastAll();
     last = new Last();
     buy = new Buy();
     sell = new Sell();
     rootobject = new RootObject();
     returnObject = new Return();
 }
Example #13
0
    public static int Add(List<int> packOrderIDList, string note)
    {
        RedBloodDataContext db = new RedBloodDataContext();

        List<PackOrder> poL = PackOrderBLL.Get4Return(db, packOrderIDList);

        Return re = new Return();
        re.Note = note;

        db.Returns.InsertOnSubmit(re);
        db.SubmitChanges();

        foreach (var item in packOrderIDList)
        {
            PackOrderBLL.Return(re.ID, item, note);
        }

        return re.ID;
    }
 public static Return<decimal> ArithmeticMean(List<decimal> numbers)
 {
     Return<decimal> _answer = new Return<decimal>();
     try
     {
         Return<double> _answerDouble = ArithmeticMean(numbers.Select(n => (double)n).ToList());
         if (_answerDouble.theresError)
         {
             _answer.theresError = true;
             _answer.error = _answerDouble.error;
         }
         else
             _answer.data = (decimal)_answerDouble.data;
     }
     catch (Exception _ex)
     {
         _answer.theresError = true;
         _answer.error = Utility.GetError(_ex, typeof(Mathematics));
     }
     return _answer;
 }
Example #15
0
        public void Return_SetsProgramCounterToDecodedAddress()
        {
            // Arrange
            var returner = new Return();
            var stack = new Mock<IStack>();
            var decoder = new Mock<IDecoder>();
            decoder.Setup(d => d.Decode(It.IsAny<UInt64>()))
                .Returns(new Instruction { Operand = 999999999 });

            var context = new ExecutionContext
            {
                Stack = stack.Object,
                Decoder = decoder.Object
            };

            // Act
            returner.Execute(context, null);

            // Asserty
            context.ProgramCounter.Should().Be(999999999);
        }
Example #16
0
        public void Return_CallsDecodeToGetAddress()
        {
            // Arrange
            var returner = new Return();
            var stack = new Mock<IStack>();
            var decoder = new Mock<IDecoder>();
            decoder.Setup(d => d.Decode(It.IsAny<UInt64>()))
                .Returns(new Instruction { Operand = 999999999 });

            var context = new ExecutionContext
            {
                Stack = stack.Object,
                Decoder = decoder.Object
            };

            // Act
            returner.Execute(context, null);

            // Asserty
            decoder.Verify(d => d.Decode(It.IsAny<UInt64>()), Times.Once);
        }
		/// <summary>
		/// Performs a  grouping.
		/// </summary>
		/// <param name="entities">object id,variable id, variable description</param>
		/// <returns>A list of groupings</returns>
		public Return<List<List<BlatellaGroup>>> Grouping(SortedList<int, SortedList<int, ICharacteristic>> entities)
		{
			Return<List<List<BlatellaGroup>>> _answer = new Return<List<List<BlatellaGroup>>>() { data = new List<List<BlatellaGroup>>() };
			if (entities == null)
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("entities"), this.GetType());
			}
			else
			{
				try
				{
					_answer = GroupingKMeans(entities);
				}
				catch (Exception _ex)
				{
					_answer.theresError = true;
					_answer.error = Utility.GetError(_ex, this.GetType());
				}
			}
			return _answer;
		}
 public static Return<double> StandardDeviation(List<double> numbers)
 {
     Return<double> _answer = new Return<double>();
     try
     {
         if (numbers == null)
         {
             _answer.theresError = true;
             _answer.error = Utility.GetError(new ArgumentException("numbers"), typeof(Mathematics));
         }
         else
             if (!numbers.Any())
                 _answer.data = 0;
             else
             {
                 Return<double> _answerArithmeticMean = ArithmeticMean(numbers);
                 if (_answerArithmeticMean.theresError)
                 {
                     _answer.theresError = true;
                     _answer.error = _answerArithmeticMean.error;
                 }
                 else
                 {
                     double _arithmeticMean = _answerArithmeticMean.data, _variance = 0;
                     int _count = numbers.Count();
                     numbers.ForEach(n => _variance += Math.Pow(n - _arithmeticMean, 2));
                     _variance = _variance / _count;
                     _answer.data = Math.Sqrt(_variance);
                 }
             }
     }
     catch (Exception _ex)
     {
         _answer.theresError = true;
         _answer.error = Utility.GetError(_ex, typeof(Mathematics));
     }
     return _answer;
 }
		/// <summary>
		/// Receives a list of words and makes a word collection.
		/// </summary>
		/// <param name="strings">strings, aren't separated into words</param>
		/// <returns>list of words</returns>
		public static Return<List<string>> GetWords(List<string> strings)
		{
			Return<List<string>> _answer = new Return<List<string>>() { data = new List<string>() };
			if (strings == null)
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("strings"), typeof(MLUtility));
			}
			else
			{
				try
				{
					Return<List<string>> _answerExtractSentences = ExtractSentences(strings);
					if (_answerExtractSentences.theresError)
					{
						_answer.theresError = true;
						_answer.error = _answerExtractSentences.error;
					}
					else
					{//tenemos las oraciones
						string _words = string.Join(MLConstants.STRING_SPACE_CHARACTER, _answerExtractSentences.data);
						Dictionary<string, string> _replacements = new Dictionary<string, string>();
						_replacements.Add("'", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(",", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(":", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(";", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add("(", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(")", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(@"\", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add("/", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(@"""", MLConstants.STRING_SPACE_CHARACTER);
						_replacements.Add(Environment.NewLine, string.Empty);

						foreach (KeyValuePair<string, string> _r in _replacements)
							_words = _words.Replace(_r.Key, _r.Value);

						_words = _words.Replace((char)13, MLConstants.SPACE_CHARACTER);

						_answer.data = _words.Split(new string[] { MLConstants.STRING_SPACE_CHARACTER }, StringSplitOptions.RemoveEmptyEntries).ToList();

					}//tenemos las oraciones
				}
				catch (Exception _ex)
				{
					_answer.theresError = true;
					_answer.error = Utility.GetError(_ex, typeof(MLUtility));
				}
			}
			return _answer;
		}
		/// <summary>
		///Receives a list of strings and creates a collection of sentences.
		/// </summary>
		/// <param name="strings">the strings (not divided into words)</param>
		/// <returns>List of sentences</returns>
		public static Return<List<string>> ExtractSentences(List<string> strings)
		{
			Return<List<string>> _answer = new Return<List<string>>() { data = new List<string>() };
			if (strings == null)
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("strings"), typeof(MLUtility));
			}
			else
			{
				try
				{
					Dictionary<string, string> _replacements = new Dictionary<string, string>();
					_replacements.Add(".", MLConstants.STRING_DOT);
					_replacements.Add("¿", string.Empty);
					_replacements.Add("?", MLConstants.STRING_DOT);
					_replacements.Add("¡", string.Empty);
					_replacements.Add("!", MLConstants.STRING_DOT);

					string _words = string.Join(MLConstants.STRING_DOT, strings);

					foreach (KeyValuePair<string, string> _r in _replacements)
						_words = _words.Replace(_r.Key, _r.Value);

					_words = _words.Replace((char)13, MLConstants.CHARACTER_DOT);

					_answer.data = _words.Split(new string[] { MLConstants.STRING_DOT }, StringSplitOptions.RemoveEmptyEntries).Select(c => c.Trim()).ToList();
				}
				catch (Exception _ex)
				{
					_answer.theresError = true;
					_answer.error = Utility.GetError(_ex, typeof(MLUtility));
				}
			}
			return _answer;
		}
		public static Return<int?> GetDayFromISO8601Text(string text)
		{
			Return<int?> _answer = new Return<int?>();
			if (string.IsNullOrWhiteSpace(text))
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("text"), typeof(MLUtility));
			}
			else
			{
				try
				{
					MatchCollection _matches = Regex.Matches(text, PATTERN_VALUE_DATE, RegexOptions.ExplicitCapture);
					if (_matches.Count == 0)
					{
						string _message = "no match";
						_answer.theresError = true;
						_answer.error = Utility.GetError(new Exception(_message), typeof(MLUtility));
					}
					else
					{//there's match
						foreach (Match _match in _matches)
						{//match to match
							List<System.Text.RegularExpressions.Group> _groups = new List<System.Text.RegularExpressions.Group>();
							foreach (string _name in groupNamePartDay)
							{
								System.Text.RegularExpressions.Group _group = _match.Groups[_name];
								if (_group != null && !string.IsNullOrEmpty(_group.Value))
									_groups.Add(_group);
							}
							_groups = _groups.OrderBy(g => g.Index).ToList();

							string _part = string.Empty;

							if (_groups.Any())
							{
								foreach (System.Text.RegularExpressions.Group _grupo in _groups)
								{
									string _foundText = _grupo.Value;
									_part = string.Format("{0}{1}", _part, _foundText);
								}
							}

							if (!string.IsNullOrEmpty(_part))
								_answer.data = int.Parse(_part);
						}//match to match
					}//there's match
				}
				catch (Exception _ex)
				{
					_answer.theresError = true;
					_answer.error = Utility.GetError(_ex, typeof(MLUtility));
				}
			}
			return _answer;
		}
Example #22
0
        public void ShouldResolveDependencyTest()
        {
            DependencyManager     dependencyManager;
            MockFactory           mockFactory;
            IDependencyResolution mockDependencyResolution;
            IDependencyManager    _unusedDependencyManager = null;
            Type   _unusedType   = null;
            string _unusedString = null;
            Type   targetType;
            string selectorKey;
            bool   includeAssignableTypes;
            object value;

            dependencyManager = new DependencyManager();

            mockFactory = new MockFactory();
            mockDependencyResolution = mockFactory.CreateInstance <IDependencyResolution>();

            targetType             = typeof(object);
            selectorKey            = COMMON_SELECTOR_KEY;
            includeAssignableTypes = false;

            Expect.On(mockDependencyResolution).One.Method(x => x.Resolve(_unusedDependencyManager, _unusedType, _unusedString)).With(dependencyManager, targetType, selectorKey).Will(Return.Value(1));

            dependencyManager.AddResolution(targetType, selectorKey, includeAssignableTypes, mockDependencyResolution);
            value = dependencyManager.ResolveDependency(targetType, selectorKey, includeAssignableTypes);

            Assert.IsNotNull(value);
            Assert.AreEqual(1, value);

            mockFactory.VerifyAllExpectationsHaveBeenMet();
        }
Example #23
0
 public virtual Statement VisitReturn(Return Return, Return changes, Return deletions, Return insertions){
   this.UpdateSourceContext(Return, changes);
   if (Return == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return Return;
 }
Example #24
0
        public void ShouldWaitUntilABooleanResultIsTrue()
        {
            var condition = GetCondition(() => true,
                                         () => true);

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(true));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout         = TimeSpan.FromMilliseconds(0);
            wait.PollingInterval = TimeSpan.FromSeconds(2);
            wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(NoSuchFrameException));

            Assert.IsTrue(wait.Until(condition));
        }
Example #25
0
        public void CanIgnoreMultipleExceptions()
        {
            var condition = GetCondition(() => { throw new NoSuchElementException(); },
                                         () => { throw new NoSuchFrameException(); },
                                         () => defaultReturnValue);

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(true));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(true));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(true));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout         = TimeSpan.FromMilliseconds(0);
            wait.PollingInterval = TimeSpan.FromSeconds(2);
            wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(NoSuchFrameException));

            Assert.AreEqual(defaultReturnValue, wait.Until(condition));
        }
Example #26
0
        public void TimeoutMessageIncludesLastIgnoredException()
        {
            var ex        = new NoSuchWindowException("");
            var condition = GetCondition <object>(() => { throw ex; });

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(false));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout         = TimeSpan.FromMilliseconds(0);
            wait.PollingInterval = TimeSpan.FromSeconds(2);
            wait.IgnoreExceptionTypes(typeof(NoSuchWindowException));

            var caughtException = Assert.Throws <WebDriverTimeoutException>(() => wait.Until(condition));

            Assert.AreSame(ex, caughtException.InnerException);
        }
Example #27
0
        void DataReceived(IAsyncResult ar)
        {
            // BeginReceive에서 추가적으로 넘어온 데이터를
            // AsyncObject 형식으로 변환한다.
            AsyncObject obj = (AsyncObject)ar.AsyncState;
            // as AsyncObject로 해도 됨
            // 데이터 수신을 끝낸다.
            int received = obj.WorkingSocket.EndReceive(ar);

            // 받은 데이터가 없으면(연결끊어짐) 끝낸다.
            if (received <= 0)
            {
                obj.WorkingSocket.Disconnect(false);
                obj.WorkingSocket.Close();
                return;
            }
            string id, msg;
            string x, y, stone, Return;
            // 텍스트로 변환한다.
            string text = Encoding.UTF8.GetString(obj.Buffer);

            // : 기준으로 짜른다.
            // tokens[0] - 보낸 사람 ID
            // tokens[1] - 보낸 메세지
            string[] tokens = text.Split(':');
            if (tokens[0].Equals("0"))
            {
                Console.WriteLine(text);
                id  = tokens[1];
                msg = tokens[2];
                AppendText(txtHistory, string.Format("[받음]{0}: {1}", id, msg));
            }
            else if (tokens[0].Equals("1"))
            {
                Console.WriteLine(text);
                x      = tokens[1];
                y      = tokens[2];
                stone  = tokens[3];
                Return = tokens[4];
                Console.WriteLine("x:" + x);
                Console.WriteLine("y:" + x);
                Console.WriteLine("stone:" + stone);

                //턴확인
                if (Return.Equals("myturn"))
                {
                    myturn = true;
                }


                //그림판에 그림을 그려야됨

                int x1 = Convert.ToInt32(x);
                int y1 = Convert.ToInt32(y);
                Pannel1_Read(x1, y1, stone);
            }

            // 텍스트박스에 추가해준다.
            // 비동기식으로 작업하기 때문에 폼의 UI 스레드에서 작업을 해줘야 한다.
            // 따라서 대리자를 통해 처리한다.
            // 클라이언트에게 다시 전송

            // 데이터를 받은 후엔 다시 버퍼를 비워주고 같은 방법으로 수신을 대기한다.
            obj.ClearBuffer();
            // 수신 대기
            obj.WorkingSocket.BeginReceive
                (obj.Buffer, 0, 4096, 0, DataReceived, obj);
        }
Example #28
0
 private void StubTypeMapper(Type type)
 {
     Stub.On(typeNamesCache).Method("GetTypeName").With(type).Will(Return.Value(type.ToString()));
 }
Example #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ManagedAction"/> class with properties/fields initialized with specified parameters.
        /// </summary>
        /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ManagedAction"/> instance.</param>
        /// <param name="action">The full name of static CustomAction method.</param>
        /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly
        /// is in the Wix# script.</param>
        /// <param name="returnType">The return type of the action.</param>
        /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
        /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
        /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param>
        /// <param name="sequence">The MSI sequence the action belongs to.</param>
        /// <param name="rollback">The full name of static CustomAction rollback method.</param>
        public ManagedAction(Id id, CustomActionMethod action, string actionAssembly, Return returnType, When when, Step step, Condition condition, Sequence sequence, CustomActionMethod rollback)
            : base(id, returnType, when, step, condition, sequence)
        {
            string name = action.Method.Name;

            Name           = name;
            MethodName     = name;
            Rollback       = rollback.Method.Name;
            ActionAssembly = actionAssembly;
        }
Example #30
0
 public void SetupExpectations()
 {
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.LEG_GET_Datos_Personales", Is.Anything }).Will(Return.Value(resultado_sp_legajo_por_dni));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.MODI_GET_Datos_Personales_Por_Id_interna", Is.Anything }).Will(Return.Value(resultado_sp_legajo_por_id_interna));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.MODI_GET_Datos_Personales_Por_Apellido_Y_Nombre", Is.Anything }).Will(Return.Value(resultado_sp_legajo_por_apellido_y_nombre));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.LEG_GET_Indice_Documentos", Is.Anything }).Will(Return.Value(resultado_sp_indice_documentos));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.MODI_Imagenes_De_Un_Legajo", Is.Anything }).Will(Return.Value(resultado_sp_id_imagenes_sin_asignar));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.MODI_Imagenes_Asignadas_A_Un_Documento", Is.Anything }).Will(Return.Value(resultado_sp_id_imagenes_del_documento));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.MODI_Categoria_De_Un_Documento", Is.Anything }).Will(Return.Value(resultado_sp_categoria_del_documento));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("Ejecutar").With(new object[] { "dbo.MODI_Get_Imagen", Is.Anything }).Will(Return.Value(resultado_sp_get_imagen));
     Expect.AtLeastOnce.On(conexion_mockeada).Method("EjecutarEscalar").With(new object[] { "dbo.MODI_Agregar_Imagen_Sin_Asignar_A_Un_Legajo", Is.Anything });
 }
Example #31
0
        public WeeeReused ReturnWeeeReused(Aatf aatf, Return @return)
        {
            var weeeReused = new WeeeReused(aatf, @return);

            return(weeeReused);
        }
 public static Return <T> Tee <T, A, B, C>(this Return <T> m, Action <T, A, B, C> f, A a, B b, C c)
 {
     return(m.Tee(t => f(t, a, b, c)));
 }
Example #33
0
        public void ShouldFailOnNullTypeAddResolutionTest()
        {
            DependencyManager     dependencyManager;
            MockFactory           mockFactory;
            IDependencyResolution mockDependencyResolution;
            IDependencyManager    _unusedDependencyManager = null;
            Type   _unusedType   = null;
            string _unusedString = null;
            Type   targetType;
            string selectorKey;
            bool   includeAssignableTypes;

            mockFactory = new MockFactory();
            mockDependencyResolution = mockFactory.CreateInstance <IDependencyResolution>();

            dependencyManager      = new DependencyManager();
            targetType             = null;
            selectorKey            = COMMON_SELECTOR_KEY;
            includeAssignableTypes = false;

            Expect.On(mockDependencyResolution).One.Method(x => x.Resolve(_unusedDependencyManager, _unusedType, _unusedString)).With(dependencyManager, targetType, selectorKey).Will(Return.Value(null));

            dependencyManager.AddResolution(targetType, selectorKey, includeAssignableTypes, mockDependencyResolution);
        }
        // TEE #2


        public static Task <Return <T> > Tea <T, A>(this Return <T> m, Func <T, A, Task> f, A a)
        {
            return(m.Tea(t => f(t, a)));
        }
Example #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ManagedAction"/> class with properties/fields initialized with specified parameters.
        /// </summary>
        /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ManagedAction"/> instance.</param>
        /// <param name="action">The full name of static CustomAction method.</param>
        /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly
        /// is in the Wix# script.</param>
        /// <param name="returnType">The return type of the action.</param>
        /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
        /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
        /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param>
        public ManagedAction(Id id, CustomActionMethod action, string actionAssembly, Return returnType, When when, Step step, Condition condition)
            : base(id, returnType, when, step, condition)
        {
            string name = action.Method.Name;

            Name           = name;
            MethodName     = name;
            ActionAssembly = actionAssembly;
        }
 public static Task <Return <T> > Tea <T, A, B>(this Return <T> m, Func <T, A, B, Task> f, A a, B b)
 {
     return(m.Tea(t => f(t, a, b)));
 }
Example #37
0
        public void RecordA()
        {
            var stuff = BluetopiaTesting.InitMockery_SdpCreator();
            var bldr  = new ServiceRecordBuilder();

            bldr.AddServiceClass(BluetoothService.Wap);
            bldr.AddBluetoothProfileDescriptor(BluetoothService.WapClient, 0x1, 0x2);
            //
            Expect.AtLeastOnce.On(stuff.MockApi2).Method("SDP_Add_Attribute")
            .With(
                stuff.StackId, stuff.SrHandle,
                (ushort)UniversalAttributeId.ProtocolDescriptorList,
                //Is.Anything
                new Structs.SDP_Data_Element__Class_ElementArray(
                    StackConsts.SDP_Data_Element_Type.Sequence,
                    2,
                    new Structs.SDP_Data_Element__Class_ElementArray(
                        StackConsts.SDP_Data_Element_Type.Sequence,
                        1,
                        new Structs.SDP_Data_Element__Class_InlineByteArray(
                            StackConsts.SDP_Data_Element_Type.UUID_16,
                            2, new byte[] { 0x01, 0x00 }
                            )
                        ),
                    new Structs.SDP_Data_Element__Class_ElementArray(
                        StackConsts.SDP_Data_Element_Type.Sequence,
                        2,
                        new Structs.SDP_Data_Element__Class_InlineByteArray(
                            StackConsts.SDP_Data_Element_Type.UUID_16,
                            2, new byte[] { 0x00, 0x03 }
                            ),
                        new Structs.SDP_Data_Element__Class_InlineByteArray(
                            StackConsts.SDP_Data_Element_Type.UnsignedInteger1Byte,
                            1, new byte[] { 0 }
                            )
                        )
                    )
                )
            .Will(Return.Value(BluetopiaError.OK));
            Expect.AtLeastOnce.On(stuff.MockApi2).Method("SDP_Add_Attribute")
            .With(
                stuff.StackId, stuff.SrHandle,
                (ushort)UniversalAttributeId.BluetoothProfileDescriptorList,
                new Structs.SDP_Data_Element__Class_ElementArray(
                    StackConsts.SDP_Data_Element_Type.Sequence,
                    1,
                    new Structs.SDP_Data_Element__Class_ElementArray(
                        StackConsts.SDP_Data_Element_Type.Sequence,
                        2,
                        new Structs.SDP_Data_Element__Class_InlineByteArray(
                            StackConsts.SDP_Data_Element_Type.UUID_16,
                            2, new byte[] { 0x11, 0x14, }
                            ),
                        new Structs.SDP_Data_Element__Class_InlineByteArray(
                            StackConsts.SDP_Data_Element_Type.UnsignedInteger2Bytes,
                            2, new byte[] { 0x02, 0x01, }    //endian!
                            )
                        )
                    )
                )
            .Will(Return.Value(BluetopiaError.OK));
            //
            stuff.DutSdpCreator.CreateServiceRecord(bldr.ServiceRecord);
            //--
            VerifyDispose(stuff);
        }
 public static Task <Return <T> > Tea <T, A, B, C>(this Return <T> m, Func <T, A, B, C, Task> f, A a, B b, C c)
 {
     return(m.Tea(t => f(t, a, b, c)));
 }
Example #39
0
        public void Write_CachesTheObjectAndEnodesClassTypeObject()
        {
            var testObject  = new TestClass1();
            var parentNode  = NewMock <INodeWriter>();
            var classNode   = NewMock <INodeWriter>();
            var membersNode = NewMock <INodeWriter>();

            StubTypeMapper();

            Expect.Once.On(document).Method("CreateClassElement").With(testObject.GetType().ToString(), 7, parentNode).
            Will(
                Return.Value(classNode));

            Expect.Once.On(document).Method("CreateMembersElement").With(classNode).Will(Return.Value(membersNode));
            Expect.Once.On(cache).Method("Add").With(testObject).Will(Return.Value(7));
            Expect.Once.On(memberWriter).Method("Write").With(testObject, membersNode, testObject.GetType());
            Expect.Once.On(baseTypeMembersWriter).Method("WriteMembers").With(testObject, classNode,
                                                                              testObject.GetType());
            Expect.Once.On(classNode).Method("Dispose").WithNoArguments();
            Expect.Once.On(membersNode).Method("Dispose").WithNoArguments();

            writer.Write(testObject, parentNode, parentNode.GetType());
        }
 public static Return <TResult> Map <T, A, B, TResult>(this Return <T> m, Func <T, A, B, Return <TResult> > f, A a, B b)
 {
     return(m.Map(t => f(t, a, b)));
 }
Example #41
0
        public void PropagatesUnIgnoredExceptions()
        {
            var ex        = new NoSuchWindowException("");
            var condition = GetCondition <object>(() => { NonInlineableThrow(ex); return(null); });

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(true));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout         = TimeSpan.FromMilliseconds(0);
            wait.PollingInterval = TimeSpan.FromSeconds(2);
            wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(NoSuchFrameException));

            var caughtException = Assert.Throws <NoSuchWindowException>(() => wait.Until(condition));

            Assert.AreSame(ex, caughtException);

            // Regression test for issue #6343
            StringAssert.Contains("NonInlineableThrow", caughtException.StackTrace, "the stack trace must include the call to NonInlineableThrow()");
        }
        // MAP #2-A


        public static Task <Return <TResult> > Map <T, A, TResult>(this Return <T> m, Func <T, A, Task <Return <TResult> > > f, A a)
        {
            return(m.Map(t => f(t, a)));
        }
Example #43
0
        public void TmeoutMessageIncludesCustomMessage()
        {
            var condition = GetCondition(() => false);

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(false));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout = TimeSpan.FromMilliseconds(0);
            wait.Message = "Expected custom timeout message";

            wait.Until(condition);
        }
 public static Task <Return <TResult> > Map <T, A, B, C, TResult>(this Return <T> m, Func <T, A, B, C, Task <Return <TResult> > > f, A a, B b, C c)
 {
     return(m.Map(t => f(t, a, b, c)));
 }
Example #45
0
        public void ChecksTimeoutAfterConditionSoZeroTimeoutWaitsCanSucceed()
        {
            var condition = GetCondition(() => null,
                                         () => defaultReturnValue);

            Expect.Once.On(mockClock).Method("LaterBy").With(TimeSpan.FromMilliseconds(0)).Will(Return.Value(startDate.Add(TimeSpan.FromSeconds(2))));
            Expect.Once.On(mockClock).Method("IsNowBefore").With(startDate.Add(TimeSpan.FromSeconds(2))).Will(Return.Value(false));

            IWait <IWebDriver> wait = new DefaultWait <IWebDriver>(mockDriver, mockClock);

            wait.Timeout = TimeSpan.FromMilliseconds(0);

            wait.Until(condition);
        }
Example #46
0
 public Return<bool> Update(bool rollBackTransaction = false)
 {
     Return<bool> lastResult = new Return<bool>(Return<bool>.ResultEnum.Success, "", "", true);
     foreach (ViewRow item in this)
     {
         lastResult = item.UpdateRow();
         if (!lastResult.Success) { break; }
     }
     return lastResult;
 }
Example #47
0
 public void StartTimeIsRounded()
 {
     Expect.Once.On(mockTimeSystem).GetProperty("Now").Will(Return.Value(DateTime.Parse("2111-11-11 5:00:00.5")));
     activity = new RunningActivity("activity", mockTimeSystem);
     Assert.AreEqual(DateTime.Parse("2111-11-11 5:00:01"), activity.Start);
 }
Example #48
0
            internal static stmt Convert(Statement stmt) {
                stmt ast;

                if (stmt is FunctionDefinition)
                    ast = new FunctionDef((FunctionDefinition)stmt);
                else if (stmt is ReturnStatement)
                    ast = new Return((ReturnStatement)stmt);
                else if (stmt is AssignmentStatement)
                    ast = new Assign((AssignmentStatement)stmt);
                else if (stmt is AugmentedAssignStatement)
                    ast = new AugAssign((AugmentedAssignStatement)stmt);
                else if (stmt is DelStatement)
                    ast = new Delete((DelStatement)stmt);
                else if (stmt is PrintStatement)
                    ast = new Print((PrintStatement)stmt);
                else if (stmt is ExpressionStatement)
                    ast = new Expr((ExpressionStatement)stmt);
                else if (stmt is ForStatement)
                    ast = new For((ForStatement)stmt);
                else if (stmt is WhileStatement)
                    ast = new While((WhileStatement)stmt);
                else if (stmt is IfStatement)
                    ast = new If((IfStatement)stmt);
                else if (stmt is WithStatement)
                    ast = new With((WithStatement)stmt);
                else if (stmt is RaiseStatement)
                    ast = new Raise((RaiseStatement)stmt);
                else if (stmt is TryStatement)
                    ast = Convert((TryStatement)stmt);
                else if (stmt is AssertStatement)
                    ast = new Assert((AssertStatement)stmt);
                else if (stmt is ImportStatement)
                    ast = new Import((ImportStatement)stmt);
                else if (stmt is FromImportStatement)
                    ast = new ImportFrom((FromImportStatement)stmt);
                else if (stmt is ExecStatement)
                    ast = new Exec((ExecStatement)stmt);
                else if (stmt is GlobalStatement)
                    ast = new Global((GlobalStatement)stmt);
                else if (stmt is ClassDefinition)
                    ast = new ClassDef((ClassDefinition)stmt);
                else if (stmt is BreakStatement)
                    ast = new Break();
                else if (stmt is ContinueStatement)
                    ast = new Continue();
                else if (stmt is EmptyStatement)
                    ast = new Pass();
                else
                    throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());

                ast.GetSourceLocation(stmt);
                return ast;
            }
Example #49
0
        private void QueryWithIOSystem()
        {
            if (_view.Length == 0 && _source.Length != 0)
                _view = _source;

            string selectSQL = SQL();

            try
            {
                using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(_ioSystem.Connection(_connectionIndex).ConnectionString))
                {
                    var cmd = new System.Data.SqlClient.SqlCommand(selectSQL, cn);

                    foreach (System.Data.SqlClient.SqlParameter item in _sqlParameterCollection)
                        cmd.Parameters.Add(item);

                    using (System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd))
                    {
                        da.SelectCommand.CommandTimeout = 0;
                        da.Fill(this);
                    }

                    cn.Close();
                }
                if (Event_AfterQuery != null)
                    Event_AfterQuery();

                _result = new Return<System.Data.DataTable>(Return<DataTable>.ResultEnum.Success, "", _ioSystem, "", this);
            }
            catch (Exception ex)
            {
                _result = new Return<System.Data.DataTable>(Return<DataTable>.ResultEnum.Failure, ex.Message, _ioSystem, selectSQL, null);
            }
        }
Example #50
0
 public void SplitByCommaWhenNoComma()
 {
     Stub.On(mockTimeSystem).GetProperty("Now").Will(Return.Value(startTime));
     activity = new RunningActivity("just one", mockTimeSystem);
     Assert.AreEqual(1, activity.SplitByComma().Length);
 }
			public override object Visit (Return returnStatement)
			{
				var result = new ReturnStatement ();
				
				result.AddChild (new CSharpTokenNode (Convert (returnStatement.loc), ReturnStatement.ReturnKeywordRole), ReturnStatement.ReturnKeywordRole);
				if (returnStatement.Expr != null)
					result.AddChild ((Expression)returnStatement.Expr.Accept (this), Roles.Expression);
				
				var location = LocationsBag.GetLocations (returnStatement);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.Semicolon), Roles.Semicolon);
				
				return result;
			}
Example #52
0
 public void SplitByCommaTrim()
 {
     Stub.On(mockTimeSystem).GetProperty("Now").Will(Return.Value(startTime));
     activity = new RunningActivity("first, second", mockTimeSystem);
     Assert.AreEqual("second", activity.SplitByComma()[1].Name);
 }
Example #53
0
 public virtual Return VisitReturn(Return r)
 {
     return r;
 }
Example #54
0
 public void ActivityRecordsStartTime()
 {
     Stub.On(mockTimeSystem).GetProperty("Now").Will(Return.Value(startTime));
     activity = new RunningActivity("test activity", mockTimeSystem);
     Assert.AreEqual(startTime, activity.Start);
 }
		public static Return<EnumLanguage> ParseLanguage(string language)
		{
			Return<EnumLanguage> _answer = new Return<EnumLanguage>() { data = EnumLanguage.undetermined };
			try
			{
				if (!string.IsNullOrEmpty(language) && !string.IsNullOrWhiteSpace(language))
				{
					language = language.ToLower().Trim();
					if (language == MLConstants.PREFIX_LANGUAGE_CASTILIAN || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_CASTILIAN, "-")))
						_answer.data = EnumLanguage.castilian;
					else
						if (language == MLConstants.PREFIX_LANGUAGE_CATALAN || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_CATALAN, "-")))
							_answer.data = EnumLanguage.catalan;
						else
							if (language == MLConstants.PREFIX_LANGUAGE_ENGLISH || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_ENGLISH, "-")))
								_answer.data = EnumLanguage.english;
							else
								if (language == MLConstants.PREFIX_LANGUAGE_FRENCH || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_FRENCH, "-")))
									_answer.data = EnumLanguage.french;
								else
									if (language == MLConstants.PREFIX_LANGUAGE_ITALIAN || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_ITALIAN, "-")))
										_answer.data = EnumLanguage.italian;
									else
										if (language == MLConstants.PREFIX_LANGUAGE_GERMAN || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_GERMAN, "-")))
											_answer.data = EnumLanguage.german;
										else
											if (language == MLConstants.PREFIX_LANGUAGE_DUTCH || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_DUTCH, "-")))
												_answer.data = EnumLanguage.dutch;
											else
												if (language == MLConstants.PREFIX_LANGUAGE_PORTUGUESE || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_PORTUGUESE, "-")))
													_answer.data = EnumLanguage.portuguese;
												else
													if (language == MLConstants.PREFIX_LANGUAGE_LATIN || language.StartsWith(string.Format("{0}{1}", MLConstants.PREFIX_LANGUAGE_LATIN, "-")))
														_answer.data = EnumLanguage.latin;
				}
			}
			catch (Exception _ex)
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(_ex, typeof(MLUtility));
			}
			return _answer;
		}
Example #56
0
 /// <summary>
 /// Sets the result of the specified <paramref name="returnType"/>.
 /// </summary>
 /// <param name="returnType">The type to be returned as a result.</param>
 /// <param name="result">The result to be set.</param>
 public void SetResult(Type returnType, object result)
 {
     lock (_lock)
         _results[returnType] = Return.Value(result);
 }
		public static Return<DateTime?> GetDate(string text, bool start)
		{
			Return<DateTime?> _answer = new Return<DateTime?>();
			if (string.IsNullOrWhiteSpace(text))
			{
				_answer.theresError = true;
				_answer.error = Utility.GetError(new ArgumentNullException("text"), typeof(MLUtility));
			}
			else
			{
				try
				{
					int? _year = null, _month = null, _day = null;
					if (!_answer.theresError)
					{
						Return<int?> _answerPart = MLUtility.GetYearFromISO8601Text(text);
						if (_answerPart.theresError)
						{
							_answer.theresError = true;
							_answer.error = _answerPart.error;
						}
						else
							_year = _answerPart.data;
					}
					if (!_answer.theresError)
					{
						Return<int?> _answerPart = MLUtility.GetMonthFromISO8601Text(text);
						if (_answerPart.theresError)
						{
							_answer.theresError = true;
							_answer.error = _answerPart.error;
						}
						else
							_month = _answerPart.data;
					}
					if (!_answer.theresError)
					{
						Return<int?> _answerPart = MLUtility.GetDayFromISO8601Text(text);
						if (_answerPart.theresError)
						{
							_answer.theresError = true;
							_answer.error = _answerPart.error;
						}
						else
							_day = _answerPart.data;
					}
					if (!_answer.theresError)
					{
						if (_year.HasValue)
						{
							if (!_month.HasValue)
								_answer.data = start ? _answer.data = new DateTime(_year.Value, 1, 1) : new DateTime(_year.Value, 12, MLUtility.GetFinalDay(_year.Value, 12));//a whole year
							else
								if (!_day.HasValue)
									_answer.data = start ? _answer.data = new DateTime(_year.Value, _month.Value, 1) : new DateTime(_year.Value, _month.Value, MLUtility.GetFinalDay(_year.Value, _month.Value));//a whole month
								else
									if (!DateTime.IsLeapYear(_year.Value) && _month.Value == 2 && _day.Value == 29)
										_answer.data = new DateTime(_year.Value, _month.Value, 28);
									else
										_answer.data = new DateTime(_year.Value, _month.Value, _day.Value);
						}
					}
				}
				catch (Exception _ex)
				{
					_answer.theresError = true;
					_answer.error = Utility.GetError(_ex, typeof(MLUtility));
				}
			}
			return _answer;
		}
Example #58
0
        public void deberia_traer_dos_evaluaciones_con_una_pregunta()
        {
            string source = @"  |id_evaluado|Apellido |Nombre   |NroDocumento |id_evaluacion |estado_evaluacion |id_periodo |descripcion_periodo |id_nivel |descripcion_nivel |id_pregunta |orden_pregunta |Enunciado |Rpta1 |Rpta2 |Rpta3 |Rpta4 |Rpta5 |opcion_elegida |deficiente |regular|bueno |destacado| escalafon   | nivel | grado | agrupamiento  | puesto | id_area_evaluado | codigo_unidad_eval | Organismo    | Secretaria    | Subsecretaria | DireccionNacional | Area_Coordinacion | detalle_nivel | periodo_desde         | periodo_hasta         | nivel_estudios    | codigo_gde    | agrupamiento_evaluado | legajo    | factor
                                |1234       |Caino    |fer      |11111        |1             |0                 |     1     | p1                 |1        |niv 1             |1           |1              | en1      |pr1   |pr2   |pr3   |pr4   |pr5   |1              |6          |16     |26    |36       | 1a          |   1a  | a     |  d            | b      | 1                | a                  | Mds          | s             | ss            | dn                | ac                | niv           | 2014-11-24 00:00:00   | 2014-11-24 00:00:00   | primaria          | gde_1         | a                     | 123       | 1a
                                |1234       |Caino    |fer      |11111        |2             |0                 |     1     | p1                 |1        |niv 1             |1           |1              | en1      |pr1   |pr2   |pr3   |pr4   |pr5   |1              |6          |16     |26    |36       | 1a          |   1a  | a     |  d            | b      | 1                | a                  | Mds          | s             | ss            | dn                | ac                | niv           | 2014-11-24 00:00:00   | 2014-11-24 00:00:00   | primaria          | gde_1         | a                     | 123       | 1b";

            IConexionBD conexion     = TestObjects.ConexionMockeada();
            var         resultado_sp = TablaDeDatos.From(source);// CrearResultadoSP();

            Expect.AtLeastOnce.On(conexion).Method("Ejecutar").WithAnyArguments().Will(Return.Value(resultado_sp));

            RepositorioEvaluacionDesempenio repo = RepositorioEvaluacionDesempenio.NuevoRepositorioEvaluacion(conexion);

            var result = repo.GetAgentesEvaluablesPor(usr_fer).asignaciones;

            Assert.AreEqual(2, result.Count);
        }
Example #59
0
		//
		// Creates a proxy base method call inside this container for hoisted base member calls
		//
		public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
		{
			Method proxy_method;

			//
			// One proxy per base method is enough
			//
			if (hoisted_base_call_proxies == null) {
				hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
				proxy_method = null;
			} else {
				hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
			}

			if (proxy_method == null) {
				string name = CompilerGeneratedContainer.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);

				MemberName member_name;
				TypeArguments targs = null;
				TypeSpec return_type = method.ReturnType;
				var local_param_types = method.Parameters.Types;

				if (method.IsGeneric) {
					//
					// Copy all base generic method type parameters info
					//
					var hoisted_tparams = method.GenericDefinition.TypeParameters;
					var tparams = new TypeParameters ();

					targs = new TypeArguments ();
					targs.Arguments = new TypeSpec[hoisted_tparams.Length];
					for (int i = 0; i < hoisted_tparams.Length; ++i) {
						var tp = hoisted_tparams[i];
						var local_tp = new TypeParameter (tp, null, new MemberName (tp.Name, Location), null);
						tparams.Add (local_tp);

						targs.Add (new SimpleName (tp.Name, Location));
						targs.Arguments[i] = local_tp.Type;
					}

					member_name = new MemberName (name, tparams, Location);

					//
					// Mutate any method type parameters from original
					// to newly created hoisted version
					//
					var mutator = new TypeParameterMutator (hoisted_tparams, tparams);
					return_type = mutator.Mutate (return_type);
					local_param_types = mutator.Mutate (local_param_types);
				} else {
					member_name = new MemberName (name);
				}

				var base_parameters = new Parameter[method.Parameters.Count];
				for (int i = 0; i < base_parameters.Length; ++i) {
					var base_param = method.Parameters.FixedParameters[i];
					base_parameters[i] = new Parameter (new TypeExpression (local_param_types [i], Location),
						base_param.Name, base_param.ModFlags, null, Location);
					base_parameters[i].Resolve (this, i);
				}

				var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
				if (method.Parameters.HasArglist) {
					cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
					cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
				}

				// Compiler generated proxy
				proxy_method = new Method (this, new TypeExpression (return_type, Location),
					Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
					member_name, cloned_params, null);

				var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location) {
					IsCompilerGenerated = true
				};

				var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
				mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
				if (targs != null)
					mg.SetTypeArguments (rc, targs);

				// Get all the method parameters and pass them as arguments
				var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
				Statement statement;
				if (method.ReturnType.Kind == MemberKind.Void)
					statement = new StatementExpression (real_base_call);
				else
					statement = new Return (real_base_call, Location);

				block.AddStatement (statement);
				proxy_method.Block = block;

				members.Add (proxy_method);
				proxy_method.Define ();
				proxy_method.PrepareEmit ();

				hoisted_base_call_proxies.Add (method, proxy_method);
			}

			return proxy_method.Spec;
		}
 internal void WarmUpIndicators(BaseData bar)
 {
     Return.Update(bar.EndTime, bar.Value);
 }