Example #1
0
        /// <summary>
        /// update orders
        /// </summary>
        /// <param name="categories"></param>
        internal int UpdateRowOrdersByIds(ObservableCollection <ItemModel> models)
        {
            int count = 0;

            foreach (var(model, index) in models.Select((model, index) => (model, index)))
            {
                model.RowOrder = index;
            }

            var sql = new SqlBuilder();

            sql.AppendSql("UPDATE items SET")
            .AppendSql(" row_order =@row_order")
            .AppendSql("WHERE id = @id");
            var paramList = new ParameterList();

            paramList.Add("@row_order", 0);
            paramList.Add("@id", 0);

            this.OpenDatabase();
            base.Database.BeginTrans();
            try {
                foreach (var model in models)
                {
                    paramList.GetParam("@row_order").Value = model.RowOrder;
                    paramList.GetParam("@id").Value        = model.Id;
                    count += base.Database.ExecuteNonQuery(sql, paramList);
                }
            } catch {
                base.Database.RollbackTrans();
            }
            base.Database.CommitTrans();
            return(count);
        }
Example #2
0
        /// <summary>
        /// insert profile data
        /// </summary>
        /// <param name="model">insert data</param>
        /// <returns>row id</returns>
        internal long Insert(ProfileModel model)
        {
            var sql = new SqlBuilder();

            sql.AppendSql("INSERT INTO profiles")
            .AppendSql("(")
            .AppendSql(" file_path")
            .AppendSql(",display_name")
            .AppendSql(",row_order")
            .AppendSql(")")
            .AppendSql("VALUES")
            .AppendSql("(")
            .AppendSql(" @file_path")
            .AppendSql(",@display_name")
            .AppendSql(",@row_order")
            .AppendSql(")");
            var paramList = new ParameterList();

            paramList.Add("@file_path", model.FilePath);
            paramList.Add("@display_name", model.DisplayName);
            paramList.Add("@row_order", model.RowOrder);

            var id = -1L;

            using (var database = new SystemDatabase()) {
                database.Open();
                id = database.Insert(sql, paramList);
            }
            return(id);
        }
Example #3
0
        public Store.TypeOfVendor.BusinessObject.TypeOfVendorList GetAllTypeOfVendorList(int TypeofVendorID, int Flag, string FlagValue)
        {
            Store.TypeOfVendor.BusinessObject.TypeOfVendorList objTypeOfVendorList = new BusinessObject.TypeOfVendorList();
            Store.TypeOfVendor.BusinessObject.TypeOfVendor     objTypeOfVendor     = new BusinessObject.TypeOfVendor();
            string          SQL       = string.Empty;
            ParameterList   paramList = new ParameterList();
            DataTableReader dr;

            try
            {
                SQL = "proc_TypeOfVendor";
                paramList.Add(new SQLParameter("@TypeofVendorID", TypeofVendorID));
                paramList.Add(new SQLParameter("@Flag", Flag));
                paramList.Add(new SQLParameter("@FlagValue", Flag));
                dr = ExecuteQuery.ExecuteReader(SQL, paramList);
                while (dr.Read())
                {
                    objTypeOfVendor = new BusinessObject.TypeOfVendor();
                    if (dr.IsDBNull(dr.GetOrdinal("TypeofVendorID")) == false)
                    {
                        objTypeOfVendor.TypeofVendorID = dr.GetInt32(dr.GetOrdinal("TypeofVendorID"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("TypeofVendorName")) == false))
                    {
                        objTypeOfVendor.TypeofVendorName = dr.GetString(dr.GetOrdinal("TypeofVendorName"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ClientID")) == false))
                    {
                        objTypeOfVendor.ClientID = dr.GetInt32(dr.GetOrdinal("ClientID"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("CreatedOn")) == false))
                    {
                        objTypeOfVendor.CreatedOn = dr.GetDateTime(dr.GetOrdinal("CreatedOn"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("CreatedBy")) == false))
                    {
                        objTypeOfVendor.CreatedBy = dr.GetInt32(dr.GetOrdinal("CreatedBy"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ModifiedBy")) == false))
                    {
                        objTypeOfVendor.ModifiedBy = dr.GetInt32(dr.GetOrdinal("ModifiedBy"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ModifiedOn")) == false))
                    {
                        objTypeOfVendor.ModifiedOn = dr.GetDateTime(dr.GetOrdinal("ModifiedOn"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ReferenceID")) == false))
                    {
                        objTypeOfVendor.ReferenceID = dr.GetInt32(dr.GetOrdinal("ReferenceID"));;
                    }
                    objTypeOfVendorList.Add(objTypeOfVendor);
                }
                dr.Close();
            }
            catch (Exception ex)
            {
                Store.Common.Utility.ExceptionLog.Exceptionlogs(ex.Message, Store.Common.Utility.ExceptionLog.LineNumber(ex), typeof(TypeOfVendor).FullName, 1);
            }
            return(objTypeOfVendorList);
        }
Example #4
0
        internal override long Insert()
        {
            var sql = new SqlBuilder();

            sql.AppendSql($"INSERT INTO {TableName}")
            .AppendSql("(")
            .AppendSql($" {Cols.Priority}")
            .AppendSql($",{Cols.Todo}")
            .AppendSql($",{Cols.Memo}")
            .AppendSql($",{Cols.CreateAt}")
            .AppendSql($",{Cols.UpdateAt}")
            .AppendSql(")")
            .AppendSql("VALUES")
            .AppendSql("(")
            .AppendSql($" @{Cols.Priority}")
            .AppendSql($",@{Cols.Todo}")
            .AppendSql($",@{Cols.Memo}")
            .AppendSql(",datetime('now', 'localtime')")
            .AppendSql(",datetime('now', 'localtime')")
            .AppendSql(")");
            var paramList = new ParameterList();

            paramList.Add($"@{Cols.Priority}", this.Priority);
            paramList.Add($"@{Cols.Todo}", this.Todo);
            paramList.Add($"@{Cols.Memo}", this.Memo);
            return(base.Database.Insert(sql, paramList));
        }
Example #5
0
        public Store.Common.MessageInfo ManageStock(Store.Stock.BusinessObject.Stock objstock, CommandMode cmdMode)
        {
            string          SQL       = "";
            ParameterList   paramList = new ParameterList();
            DataTableReader dr;

            Store.Common.MessageInfo objMessageInfo = null;
            try
            {
                SQL = "USP_ManageStock";
                paramList.Add(new SQLParameter("@StockID", objstock.StockID));
                paramList.Add(new SQLParameter("@ItemID", objstock.ItemID));
                paramList.Add(new SQLParameter("@StockQuantity", objstock.StockQuantity));
                paramList.Add(new SQLParameter("@CMDMode", cmdMode));
                dr = ExecuteQuery.ExecuteReader(SQL, paramList);
                if (dr.Read())
                {
                    objMessageInfo              = new Store.Common.MessageInfo();
                    objMessageInfo.ErrorCode    = Convert.ToInt32(dr["ErrorCode"]);
                    objMessageInfo.ErrorMessage = Convert.ToString(dr["ErrorMessage"]);
                    objMessageInfo.TranID       = Convert.ToInt32(dr["TranID"]);
                    objMessageInfo.TranCode     = Convert.ToString(dr["TranCode"]);
                    objMessageInfo.TranMessage  = Convert.ToString(dr["TranMessage"]);
                }
            }
            catch (Exception ex)
            {
                Store.Common.Utility.ExceptionLog.Exceptionlogs(ex.Message, Store.Common.Utility.ExceptionLog.LineNumber(ex), typeof(Stock).FullName, 1);
            }
            return(objMessageInfo);
        }
Example #6
0
        public void ExecuteServerTask(ParameterList parameterList)
        {
            var startDate         = DateTime.Now;
            var serializedRequest = new BaseDtoSerialized {
                Data     = TypeConvert.ToString(parameterList[2]),
                TypeName = TypeConvert.ToString(parameterList[3])
            };
            var    request    = serializedRequest.Deserialize();
            var    baseDto    = request as BaseDto;
            string methodName = TypeConvert.ToString(parameterList[1]);

            Log.WriteLog(SystemServer, LogLevel.INFO, $"ExecuteServerTask.{methodName}.Request", $"Id[{baseDto.Id}] Data[{(baseDto.MockLog ? baseDto.SerializeForLogging().Data : serializedRequest.Data)}]");

            var response = (SystemServer.ExecuteServerTask(TypeConvert.ToString(parameterList[0]), methodName
                                                           , new Type[] { serializedRequest.GetDtoType() }, new object[] { request }, false) as BaseDtoResponse);

            response.Id = baseDto.Id;

            var serializedResponse = response.Serialize();

            Log.WriteLog(SystemServer, LogLevel.INFO, $"ExecuteServerTask.{methodName}.Response"
                         , $"Id[{response.Id}] Time[{(DateTime.Now - startDate).ToString()}] Data[{(response.MockLog ? response.SerializeForLogging().Data : serializedResponse.Data)}]");

            parameterList.Clear();
            parameterList.Add(serializedResponse.Data);
            parameterList.Add(serializedResponse.TypeName);
        }
Example #7
0
        public Store.State.BusinessObject.State GetAllState(int StateID, int Flag, string FlagValue)
        {
            Store.State.BusinessObject.State objState = null;
            string          SQL       = string.Empty;
            ParameterList   paramList = new ParameterList();
            DataTableReader dr;

            try
            {
                SQL = "";
                paramList.Add(new SQLParameter("@StateID", StateID));
                paramList.Add(new SQLParameter("@Flag", Flag));
                paramList.Add(new SQLParameter("@FlagValue", FlagValue));
                dr = ExecuteQuery.ExecuteReader(SQL, paramList);
                while (dr.Read())
                {
                    if (dr.IsDBNull(dr.GetOrdinal("StateID")) == false)
                    {
                        objState.StateID = dr.GetInt32(dr.GetOrdinal("StateID"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("StateName")) == false)
                    {
                        objState.StateName = dr.GetString(dr.GetOrdinal("StateName"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("CountryID")) == false)
                    {
                        objState.CountryID = dr.GetInt32(dr.GetOrdinal("CountryID"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("CreatedBy")) == false)
                    {
                        objState.CreatedBy = dr.GetInt32(dr.GetOrdinal("CreatedBy"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("CreatedOn")) == false)
                    {
                        objState.CreatedOn = dr.GetDateTime(dr.GetOrdinal("CreatedOn"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("ModifiedBy")) == false)
                    {
                        objState.ModifiedBy = dr.GetInt32(dr.GetOrdinal("ModifiedBy"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("ModifiedOn")) == false)
                    {
                        objState.ModifiedOn = dr.GetDateTime(dr.GetOrdinal("ModifiedOn"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("ReferenceID")) == false)
                    {
                        objState.ReferenceID = dr.GetInt32(dr.GetOrdinal("ReferenceID"));
                    }
                }
                dr.Close();
                return(objState);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #8
0
		public void FetchPage(string board, int? start=null)
		{
			this.board = board;
			this.start = start;
			ParameterList qry = new ParameterList();
			qry.Add("board", board);
			if (start != null)
				qry.Add("start", start.Value.ToString());
			DoAction(this.FetchPageCompleted, "bbstdoc", qry);
		}
Example #9
0
        /// <summary>
        /// 更新を行う
        /// </summary>
        internal void Update()
        {
            var sql = new SqlBuilder();

            sql.AppendSql($"UPDATE {TableName} SET")
            .AppendSql($" {Cols.Name} = @{Cols.Name}")
            .AppendSql($",{Cols.Sun} = @{Cols.Sun}")
            .AppendSql($",{Cols.Mon} = @{Cols.Mon}")
            .AppendSql($",{Cols.Tue} = @{Cols.Tue}")
            .AppendSql($",{Cols.Wed} = @{Cols.Wed}")
            .AppendSql($",{Cols.Thu} = @{Cols.Thu}")
            .AppendSql($",{Cols.Fri} = @{Cols.Fri}")
            .AppendSql($",{Cols.Sat} = @{Cols.Sat}")
            .AppendSql($",{Cols.UpdateAt} = datetime('now', 'localtime')")
            .AppendSql($"WHERE {Cols.Id}=@{Cols.Id}");
            var paramList = new ParameterList();

            paramList.Add($"@{Cols.Id}", this.Id);
            paramList.Add($"@{Cols.Name}", this.Name);
            paramList.Add($"@{Cols.Sun}", this.Sun);
            paramList.Add($"@{Cols.Mon}", this.Mon);
            paramList.Add($"@{Cols.Tue}", this.Tue);
            paramList.Add($"@{Cols.Wed}", this.Wed);
            paramList.Add($"@{Cols.Thu}", this.Thu);
            paramList.Add($"@{Cols.Fri}", this.Fri);
            paramList.Add($"@{Cols.Sat}", this.Sat);
            base.Database.ExecuteNonQuery(sql, paramList);
        }
Example #10
0
		public void Login(string username, string password)
		{
			Random rand = new Random();
			connection.BaseUrl = string.Format("{0}vd{1}/", Connection.BbsUrl, new Random().Next(10000, 100000));
			ParameterList qry = new ParameterList();
			qry.Add("type", "2");
			ParameterList data = new ParameterList();
			data.Add("id", username);
			data.Add("pw", password);
			DoAction(LoginCompleted, "bbslogin", qry, data);
		}
Example #11
0
        public Store.PurchaseOrderItem.BusinessObject.PurchaseOrderItemList GetAllPurchaseOrderItemList(int PurchaseOrderItemID, int Flag, string FlagValue)
        {
            Store.PurchaseOrderItem.BusinessObject.PurchaseOrderItem     objPurchaseOrderItem     = null;
            Store.PurchaseOrderItem.BusinessObject.PurchaseOrderItemList objPurchaseOrderItemList = null;
            string          SQL       = string.Empty;
            ParameterList   paramList = new ParameterList();
            DataTableReader dr;

            try
            {
                objPurchaseOrderItemList = new BusinessObject.PurchaseOrderItemList();
                SQL = "proc_PurchaseOrderItem";
                paramList.Add(new SQLParameter("@PurchaseOrderItemID", PurchaseOrderItemID));
                paramList.Add(new SQLParameter("@Flag", Flag));
                paramList.Add(new SQLParameter("@FlagValue", FlagValue));
                dr = ExecuteQuery.ExecuteReader(SQL, paramList);
                while (dr.Read())
                {
                    objPurchaseOrderItem = new BusinessObject.PurchaseOrderItem();

                    if (dr.IsDBNull(dr.GetOrdinal("ItemID")) == false)
                    {
                        objPurchaseOrderItem.ItemID = dr.GetInt32(dr.GetOrdinal("ItemID"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("ItemPrefix")) == false)
                    {
                        objPurchaseOrderItem.ItemPrefix = dr.GetString(dr.GetOrdinal("ItemPrefix"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("ItemUnit")) == false)
                    {
                        objPurchaseOrderItem.ItemUnit = dr.GetString(dr.GetOrdinal("ItemUnit"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("Description")) == false)
                    {
                        objPurchaseOrderItem.Description = dr.GetString(dr.GetOrdinal("Description"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("ItemPrice")) == false)
                    {
                        objPurchaseOrderItem.ItemPrice = dr.GetDecimal(dr.GetOrdinal("ItemPrice"));
                    }
                    if (dr.IsDBNull(dr.GetOrdinal("TotalPrice")) == false)
                    {
                        objPurchaseOrderItem.TotalPrice = dr.GetDecimal(dr.GetOrdinal("TotalPrice"));
                    }
                    objPurchaseOrderItemList.Add(objPurchaseOrderItem);
                }
                dr.Close();
            }
            catch (Exception ex)
            {
                Store.Common.Utility.ExceptionLog.Exceptionlogs(ex.Message, Store.Common.Utility.ExceptionLog.LineNumber(ex), typeof(PurchaseOrderItem).FullName, 1);
            }
            return(objPurchaseOrderItemList);
        }
Example #12
0
        private static ParameterList GetUserParameter(User user)
        {
            var parameters = new ParameterList();

            parameters.Add(Constants.Parameter.UserId, user.UserId);
            parameters.Add(Constants.Parameter.Email, user.Email);
            //parameters.Add(Constants.Parameter.RoleId, user.Role.RoleId);
            parameters.Add(Constants.Parameter.RoleId, user.RoleId);

            return(parameters);
        }
Example #13
0
        public Store.Country.BusinessObject.Country GetAllCountry(int CountryID, int Flag, string FlagValue)
        {
            Store.Country.BusinessObject.Country objCountry = null;
            string          SQL       = string.Empty;
            ParameterList   paramList = new ParameterList();
            DataTableReader dr;

            try
            {
                SQL = "proc_Country";
                paramList.Add(new SQLParameter("@CountryID", CountryID));
                paramList.Add(new SQLParameter("@Flag", Flag));
                paramList.Add(new SQLParameter("@FlagValue", Flag));
                dr = ExecuteQuery.ExecuteReader(SQL, paramList);
                while (dr.Read())
                {
                    objCountry = new BusinessObject.Country();
                    if (dr.IsDBNull(dr.GetOrdinal("CountryID")) == false)
                    {
                        objCountry.CountryID = dr.GetInt32(dr.GetOrdinal("CountryID"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("CountryName")) == false))
                    {
                        objCountry.CountryName = dr.GetString(dr.GetOrdinal("CountryName"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("CreatedOn")) == false))
                    {
                        objCountry.CreatedOn = dr.GetDateTime(dr.GetOrdinal("CreatedOn"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("CreatedBy")) == false))
                    {
                        objCountry.CreatedBy = dr.GetInt32(dr.GetOrdinal("CreatedBy"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ModifiedBy")) == false))
                    {
                        objCountry.ModifiedBy = dr.GetInt32(dr.GetOrdinal("ModifiedBy"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ModifiedOn")) == false))
                    {
                        objCountry.ModifiedOn = dr.GetDateTime(dr.GetOrdinal("ModifiedOn"));
                    }
                    if ((dr.IsDBNull(dr.GetOrdinal("ReferenceID")) == false))
                    {
                        objCountry.ReferenceID = dr.GetInt32(dr.GetOrdinal("ReferenceID"));
                    }
                }
                dr.Close();
            }
            catch (Exception ex)
            {
                Store.Common.Utility.ExceptionLog.Exceptionlogs(ex.Message, Store.Common.Utility.ExceptionLog.LineNumber(ex), typeof(Country).FullName, 1);
            }
            return(objCountry);
        }
Example #14
0
                public static void Exceptionlogs(string msg, string loc, string page, int userId)
                {
                    string        SQL   = "";
                    ParameterList param = new ParameterList();

                    SQL = "proc_ExceptionLog";
                    param.Add(new SQLParameter("@msg", msg));
                    param.Add(new SQLParameter("@loc", loc));
                    param.Add(new SQLParameter("@page", page));
                    param.Add(new SQLParameter("@UserId", userId));
                    ExecuteQuery.ExecuteNonQuery(SQL, param);
                }
Example #15
0
        private ParameterList AddTimeAndICAO(string time, List <string> icao24List)
        {
            ParameterList tmp = new ParameterList();

            icao24List?.ForEach(i => tmp.Add("icao24", i));

            if (_authenticated)
            {
                tmp.Add("time", time);
            }

            return(tmp);
        }
Example #16
0
        /// <summary>
        /// update category id by category id
        /// </summary>
        /// <param name="oldCateogryId">old category id</param>
        /// <param name="newCateogoryId">new category id</param>
        /// <returns>affected rows</returns>
        internal int UpdateCategoryIdByCategoryId(long oldCateogryId, long newCateogoryId)
        {
            var sql = new SqlBuilder();

            sql.AppendSql("UPDATE items SET")
            .AppendSql("category_id = @new_category_id")
            .AppendSql("WHERE category_id = @old_category_id");
            var paramList = new ParameterList();

            paramList.Add("@new_category_id", newCateogoryId);
            paramList.Add("@old_category_id", oldCateogryId);
            return(base.Database.ExecuteNonQuery(sql, paramList));
        }
Example #17
0
        public BaseDtoResponse ExecuteServerTask(string serverTaskName, string methodName, BaseDtoRequest request, bool newTransaction = false)
        {
            var parameterList = new ParameterList();

            parameterList.Add(serverTaskName);
            parameterList.Add(methodName);
            var requestSerialized = request.Serialize();

            parameterList.Add(requestSerialized.Data);
            parameterList.Add(requestSerialized.TypeName);

            return((BaseDtoResponse)systemServer.ExecuteServerTask(serverTaskName, methodName
                                                                   , new Type[] { request.GetType() }, new object[] { request }, newTransaction));
        }
        /// <summary>
        /// update category data by id
        /// </summary>
        /// <param name="model">insert data</param>
        /// <returns>affected row count</returns>
        internal long UpdateById(CategoryModel model)
        {
            var sql = new SqlBuilder();

            sql.AppendSql("UPDATE categories SET")
            .AppendSql(" display_name =@display_name")
            .AppendSql("WHERE id = @id");
            var paramList = new ParameterList();

            paramList.Add("@display_name", model.DisplayName);
            paramList.Add("@id", model.Id);

            this.OpenDatabase();
            return(base.Database.ExecuteNonQuery(sql, paramList));
        }
Example #19
0
        static J2KEncoder()
        {
            pl = new ParameterList();
            string[][] parameters = GetAllParameters();
            for (int i = 0; i < parameters.Length; i++)
            {
                string[] param = parameters[i];
                pl.Add(param[0], param[3]);
            }

            // Custom parameters
            pl.Add("Aptype", "layer");
            pl.Add("Qguard_bits", "1");
            pl.Add("Alayers", "sl");
            //pl.Set("lossless", "on");
        }
Example #20
0
        public ParameterBuilder DefineParameter()
        {
            ParameterBuilder builder = new ParameterBuilder(this);

            ParameterList.Add(builder);
            return(builder);
        }
Example #21
0
        /// <summary>
        /// Creates a map with the name and type of the parameters.
        /// </summary>
        private void InitiateParameterMap2(EntryReact entry)
        {
            var paramDic = entry.ParameterClass;

            this.ParameterList = new List <IParameterReaction>();
            foreach (var param in paramDic)
            {
                string paramName = "NCDK.Reactions.Types.Parameters." + param[0];
                try
                {
                    var ipc = (IParameterReaction)this.GetType().Assembly.GetType(paramName).GetConstructor(Type.EmptyTypes).Invoke(Array.Empty <object>());
                    ipc.IsSetParameter = bool.Parse(param[1]);
                    ipc.Value          = param[2];

                    Trace.TraceInformation("Loaded parameter class: ", paramName);
                    ParameterList.Add(ipc);
                }
                catch (ArgumentException exception)
                {
                    Trace.TraceError($"Could not find this IParameterReact: {paramName}");
                    Debug.WriteLine(exception);
                }
                catch (Exception exception)
                {
                    Trace.TraceError($"Could not load this IParameterReact: {paramName}");
                    Debug.WriteLine(exception);
                }
            }
        }
Example #22
0
        /// <summary>
        /// Creates appropriate input system dependent on platform.
        /// </summary>
        /// <param name="windowHandle">Contains OS specific window handle (such as HWND or X11 Window)</param>
        /// <returns>A reference to the created manager, or raises an Exception</returns>
        /// <exception cref="Exception">Exception</exception>
        /// <exception cref="ArgumentException">ArgumentException</exception>
        public static InputManager CreateInputSystem(object windowHandle)
        {
            var args = new ParameterList();

            args.Add(new Parameter("WINDOW", windowHandle));
            return(CreateInputSystem(args));
        }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CSharpFeatureCall"/> class.
        /// </summary>
        /// <param name="context">The creation context.</param>
        /// <param name="source">Details of the feature call.</param>
        public CSharpFeatureCall(ICSharpContext context, IFeatureCall source)
        {
            foreach (IParameter Item in source.ParameterList)
            {
                ICSharpClass     Owner        = context.GetClass(Item.ResolvedParameter.Location.EmbeddingClass);
                ICSharpParameter NewParameter = CSharpParameter.Create(context, Item, Owner);
                ParameterList.Add(NewParameter);
            }

            foreach (IParameter Item in source.ResultList)
            {
                ICSharpClass     Owner        = context.GetClass(Item.ResolvedParameter.Location.EmbeddingClass);
                ICSharpParameter NewParameter = CSharpParameter.Create(context, Item, Owner);
                ResultList.Add(NewParameter);
            }

            foreach (IArgument Item in source.ArgumentList)
            {
                ICSharpArgument NewArgument = CSharpArgument.Create(context, Item);
                ArgumentList.Add(NewArgument);
            }

            Debug.Assert(ParameterList.Count >= ArgumentList.Count);
            Count = ParameterList.Count;

            ArgumentStyle = source.TypeArgumentStyle;
        }
Example #24
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (gridProdutos.SelectedRows.Count == 0)
            {
                MessageBox.Show("Selecione a linha que deseja excluir!!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DialogResult dr = MessageBox.Show("Certeza que deseja excluir o registro?", "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

            if (dr == DialogResult.Yes)
            {
                //obtendo a linha atual
                var     focusedGridRow = gridProdutos.SelectedRows[0];
                DataRow focusedRow     = ((DataTable)gridProdutos.DataSource).Rows[focusedGridRow.Index];

                //query de deleção
                string _sqlDelete = "DELETE FROM PRODUTOS WHERE IdProduto = @IdProduto";
                //criando nova lista de parametros
                ParameterList pList = new ParameterList();
                pList.Add(new SqlParameter("@IdProduto", focusedRow["IdProduto"]));

                //depois que o produto foi removido, é necessário remover esse produto
                //que é um DataRow (focusedRow) da fonte de dados do grid, sem precisar ir ao BD novamente
                Program.ServerAccess.ExecuteScalar(_sqlDelete, pList);
                ((DataTable)gridProdutos.DataSource).Rows.Remove(focusedRow);

                //atualizando a visao do grid
                gridProdutos.Refresh();

                MessageBox.Show("Produto excluido com sucesso");
            }
        }
Example #25
0
        public MethodName(MethodInfo method, TypeNameFlag flags)
        {
            Method     = method;
            ReturnType = TypeNameFactory.Create(method.ReturnType, flags);

            if (!method.Name.Contains("."))
            {
                Name = method.Name;
                ExplicitInterface = null;
            }
            else
            {
                var iSplit        = method.Name.LastIndexOf('.');
                var interfacePart = method.Name.Substring(0, iSplit);
                Name = method.Name.Substring(iSplit + 1);
                var interfaceType = method.DeclaringType.GetInterface(interfacePart);
                ExplicitInterface = TypeNameFactory.Create(interfaceType, flags);
            }

            Generics = new GenericList();
            if (method.IsGenericMethod)
            {
                foreach (var generic in method.GetGenericArguments())
                {
                    Generics.Add(TypeNameFactory.Create(generic, flags));
                }
            }

            Parameters = new ParameterList();
            foreach (var parameter in method.GetParameters())
            {
                Parameters.Add(new ParameterName(parameter, flags));
            }
        }
        public virtual void AddParameter()
        {
            var p = new Parameter();

            ParameterList.Add(p);
            TargetObject.ParameterList.Add(p);
        }
Example #27
0
        /// <summary>
        /// To fetch details
        /// </summary>
        /// <param name="districtID"></param>
        /// <returns></returns>
        public ParameterList GetOptionAvailable()
        {
            OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["UETCL_WIS"].ConnectionString);
            OracleCommand    cmd;
            string           proc = "USP_MST_GET_OPTIONS";

            cmd             = new OracleCommand(proc, con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("Sp_recordset", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
            cmd.Connection.Open();
            OracleDataReader dr           = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            ParameterBO      objcountBO   = null;
            ParameterList    objcountlist = new ParameterList();

            while (dr.Read())
            {
                objcountBO = new ParameterBO();
                objcountBO.AvailableOptionsID = (Convert.ToInt32(dr.GetValue(dr.GetOrdinal("ID"))));
                objcountBO.AvailableOptions   = dr.GetValue(dr.GetOrdinal("OPTIONAVAILABLE")).ToString();
                objcountlist.Add(objcountBO);
            }

            dr.Close();
            return(objcountlist);
        }
Example #28
0
        /// <summary>
        /// select max row_order
        /// </summary>
        /// <param name="categoryId"></param>
        internal int SelectMaxRowOrderByCategoryId(long categoryId)
        {
            int rowOrder = 0;
            var sql      = new SqlBuilder();

            sql.AppendSql("SELECT ")
            .AppendSql(" row_order")
            .AppendSql("FROM items")
            .AppendSql("WHERE category_id = @category_id")
            .AppendSql("ORDER BY row_order desc")
            .AppendSql("        ,id");
            this.OpenDatabase();

            var paramList = new ParameterList();

            paramList.Add("@category_id", categoryId);

            this.OpenDatabase();
            base._record = base.Database.OpenRecordset(sql, paramList);
            if (base._record.Read())
            {
                rowOrder = base._record.GetInt(0);
            }
            base._record.Close();
            base.Database.Close();
            return(rowOrder + 1);
        }
Example #29
0
        ParameterList readParams(TokenStream gStream)
        {
            var plist = new ParameterList();

            while (true)
            {
                var param = new Variable();

                param.Name = gStream.GetIdentifier();
                param.Type = gStream.NextType(false);

                plist.Add(param);

                if (gStream.Next() == ")")
                {
                    break;
                }
                if (gStream.Current != ",")
                {
                    InfoProvider.AddError("`,` or `)` expected in parameter declaration", ExceptionType.IllegalToken, gStream.SourcePosition);
                }
            }

            return(plist);
        }
Example #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="type">the current type being extended</param>
        /// <param name="extensionMethodTemplate">A reference to the extension method. For generic methods, this is a reference to the
        /// non-specialized method, e.g. System.Linq.Enumerable.Select``2.
        /// </param>
        /// <param name="specialization">When the current type implements or inherits from a specialization of a generic type,
        /// this parameter has a TypeNode for the type used as apecialization of the generic type's first template param.
        /// </param>
        private void AddExtensionMethod(XmlWriter writer, TypeNode type, Method extensionMethodTemplate, TypeNode specialization)
        {
            // If this is a specialization of a generic method, construct a Method object that describes the specialization
            Method extensionMethodTemplate2 = extensionMethodTemplate;

            if (extensionMethodTemplate2.IsGeneric && (specialization != null))
            {
                // the specialization type is the first of the method's template arguments
                TypeNodeList templateArgs = new TypeNodeList();
                templateArgs.Add(specialization);
                // add any additional template arguments
                for (int i = 1; i < extensionMethodTemplate.TemplateParameters.Count; i++)
                {
                    templateArgs.Add(extensionMethodTemplate.TemplateParameters[i]);
                }
                extensionMethodTemplate2 = extensionMethodTemplate.GetTemplateInstance(type, templateArgs);
            }
            TypeNode      extensionMethodTemplateReturnType = extensionMethodTemplate2.ReturnType;
            ParameterList extensionMethodTemplateParameters = extensionMethodTemplate2.Parameters;

            ParameterList extensionMethodParameters = new ParameterList();

            for (int i = 1; i < extensionMethodTemplateParameters.Count; i++)
            {
                Parameter extensionMethodParameter = extensionMethodTemplateParameters[i];
                extensionMethodParameters.Add(extensionMethodParameter);
            }
            Method extensionMethod = new Method(extensionMethodTemplate.DeclaringType, new AttributeList(), extensionMethodTemplate.Name, extensionMethodParameters, extensionMethodTemplate.ReturnType, null);

            extensionMethod.Flags = extensionMethodTemplate.Flags & ~MethodFlags.Static;

            // for generic methods, set the template args and params so the template data is included in the id and the method data
            if (extensionMethodTemplate2.IsGeneric)
            {
                extensionMethod.IsGeneric = true;
                if (specialization != null)
                {
                    // set the template args for the specialized generic method
                    extensionMethod.TemplateArguments = extensionMethodTemplate2.TemplateArguments;
                }
                else
                {
                    // set the generic template params for the non-specialized generic method
                    extensionMethod.TemplateParameters = extensionMethodTemplate2.TemplateParameters;
                }
            }

            // Get the id
            string extensionMethodTemplateId = reflector.ApiNamer.GetMemberName(extensionMethodTemplate);

            // write the element node
            writer.WriteStartElement("element");
            writer.WriteAttributeString("api", extensionMethodTemplateId);
            writer.WriteAttributeString("source", "extension");
            isExtensionMethod = true;
            reflector.WriteMember(extensionMethod);
            isExtensionMethod = false;
            writer.WriteEndElement();
        }
Example #31
0
        public ParameterList GetParameters(string CommandName)
        {
            ParameterList      pList = new ParameterList();
            CommandInteraction ci    = new CommandInteraction();

            try
            {
                List <string> requierdInputs = ci.getRequiredInputs(CommandName);
                foreach (string i in requierdInputs)
                {
                    Parameter p = new Parameter();
                    p.Name = i;
                    pList.Add(p);
                }
                TeamInfo teamInfo = TeamInfoAccess.getTeam(0);

                using (PSDataAccess psDataAccess = new PSDataAccess(teamInfo.domain, teamInfo.product))
                {
                    string psFieldNames = string.Empty;
                    foreach (Parameter p in pList)
                    {
                        p.Name = p.Name.Replace("__", " ");
                        if (psFieldNames == string.Empty)
                        {
                            psFieldNames = p.Name;//"__" is for the white space issue
                        }
                        else
                        {
                            psFieldNames = string.Format("{0};{1}", psFieldNames, p.Name);
                        }
                    }
                    List <PSFieldDefinition> fieldDefinitions = psDataAccess.LoadingPSFields(psFieldNames);
                    foreach (Parameter p in pList)
                    {
                        if (p.Name.Equals("AssignedTo"))
                        {
                            p.Values.AddRange(new string[] { "t-limliu", "yuanzhua", "zachary", "zichsun" });
                        }
                        foreach (PSFieldDefinition definition in fieldDefinitions)
                        {
                            if (p.Name.Equals(definition.Name))
                            {
                                List <object> values = definition.GetAllowedValues();
                                foreach (object v in values)
                                {
                                    p.Values.Add(v.ToString());
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new WebFaultException <string>(e.ToString(), HttpStatusCode.InternalServerError);
            }
            return(pList);
        }
Example #32
0
        /// <summary>
        /// Generates the list of parameter controls.
        /// </summary>
        /// <remarks>
        /// We need to get the list of parameters from the VisGen plugin, then for each
        /// parameter we need to merge the value from the Visualization's value list.
        /// If we don't find a corresponding entry in the Visualization, we use the
        /// default value.
        /// </remarks>
        private void GenerateParamControls(VisDescr descr)
        {
            VisParamDescr[] paramDescrs = descr.VisParamDescrs;

            ParameterList.Clear();
            foreach (VisParamDescr vpd in paramDescrs)
            {
                string rangeStr   = string.Empty;
                object defaultVal = vpd.DefaultValue;

                // If we're editing a visualization, use the values from that as default.
                if (mOrigVis != null)
                {
                    if (mOrigVis.VisGenParams.TryGetValue(vpd.Name, out object val))
                    {
                        // Do we need to confirm that val has the correct type?
                        defaultVal = val;
                    }
                }
                else
                {
                    // New visualization.  Use the set's offset as the default value for
                    // any parameter called "offset".  Otherwise try to pull a value with
                    // the same name out of the last thing we edited.
                    if (vpd.Name.ToLowerInvariant() == "offset")
                    {
                        defaultVal = mSetOffset;
                    }
                    else if (sLastParams.TryGetValue(vpd.Name, out object value))
                    {
                        defaultVal = value;
                    }
                }

                // Set up rangeStr, if appropriate.
                VisParamDescr altVpd = vpd;
                if (vpd.CsType == typeof(int) || vpd.CsType == typeof(float))
                {
                    if (vpd.Special == VisParamDescr.SpecialMode.Offset)
                    {
                        defaultVal = mFormatter.FormatOffset24((int)defaultVal);
                        rangeStr   = "[" + mFormatter.FormatOffset24(0) + "," +
                                     mFormatter.FormatOffset24(mProject.FileDataLength - 1) + "]";

                        // Replace the vpd to provide a different min/max.
                        altVpd = new VisParamDescr(vpd.UiLabel, vpd.Name, vpd.CsType,
                                                   0, mProject.FileDataLength - 1, vpd.Special, vpd.DefaultValue);
                    }
                    else
                    {
                        rangeStr = "[" + vpd.Min + "," + vpd.Max + "]";
                    }
                }

                ParameterValue pv = new ParameterValue(altVpd, defaultVal, rangeStr);

                ParameterList.Add(pv);
            }
        }
Example #33
0
		public void TestExpand ()
		{
			Func<SampleContext,List<string>> r1 = (ctx) => new List<string>() {"1","2","3"}; 
			Func<SampleContext,List<string>> r2 = (ctx) => new List<string>() {"a","b","c","d"}; 
			Func<SampleContext,List<string>> r3 = (ctx) => new List<string>() {"Green","Blue"}; 


			var context = new SampleContext ();
			var parameterList = new ParameterList<SampleContext> ();
			parameterList.Add (new mtgfool.Utils.Parameter<SampleContext> ("number",r1));
			parameterList.Add (new mtgfool.Utils.Parameter<SampleContext> ("letter",r2));
			parameterList.Add (new mtgfool.Utils.Parameter<SampleContext> ("color",r3));

			var x = parameterList.Expand (context);

			Assert.AreEqual (24, x.Count);
			var y = x.FindAll ((d) => d ["number"] == "2" && d ["letter"] == "d" && d ["color"] == "Green");
			Assert.AreEqual	(1, y.Count);

		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="type">the current type being extended</param>
        /// <param name="extensionMethodTemplate">A reference to the extension method. For generic methods, this is a reference to the 
        /// non-specialized method, e.g. System.Linq.Enumerable.Select``2.
        /// </param>
        /// <param name="specialization">When the current type implements or inherits from a specialization of a generic type,
        /// this parameter has a TypeNode for the type used as apecialization of the generic type's first template param. 
        /// </param>
        private void AddExtensionMethod(XmlWriter writer, TypeNode type, Method extensionMethodTemplate, TypeNode specialization)
        {
            // If this is a specialization of a generic method, construct a Method object that describes the specialization
            Method extensionMethodTemplate2 = extensionMethodTemplate;
            if (extensionMethodTemplate2.IsGeneric && (specialization != null))
            {
                // the specialization type is the first of the method's template arguments
                TypeNodeList templateArgs = new TypeNodeList();
                templateArgs.Add(specialization);
                // add any additional template arguments
                for (int i = 1; i < extensionMethodTemplate.TemplateParameters.Count; i++)
                    templateArgs.Add(extensionMethodTemplate.TemplateParameters[i]);
                extensionMethodTemplate2 = extensionMethodTemplate.GetTemplateInstance(type, templateArgs);
            }
            TypeNode extensionMethodTemplateReturnType = extensionMethodTemplate2.ReturnType;
            ParameterList extensionMethodTemplateParameters = extensionMethodTemplate2.Parameters;

            ParameterList extensionMethodParameters = new ParameterList();
            for (int i = 1; i < extensionMethodTemplateParameters.Count; i++)
            {
                Parameter extensionMethodParameter = extensionMethodTemplateParameters[i];
                extensionMethodParameters.Add(extensionMethodParameter);
            }
            Method extensionMethod = new Method(extensionMethodTemplate.DeclaringType, new AttributeList(), extensionMethodTemplate.Name, extensionMethodParameters, extensionMethodTemplate.ReturnType, null);
            extensionMethod.Flags = extensionMethodTemplate.Flags & ~MethodFlags.Static;

            // for generic methods, set the template args and params so the template data is included in the id and the method data
            if (extensionMethodTemplate2.IsGeneric)
            {
                extensionMethod.IsGeneric = true;
                if (specialization != null)
                {
                    // set the template args for the specialized generic method
                    extensionMethod.TemplateArguments = extensionMethodTemplate2.TemplateArguments;
                }
                else
                {
                    // set the generic template params for the non-specialized generic method
                    extensionMethod.TemplateParameters = extensionMethodTemplate2.TemplateParameters;
                }
            }

            // Get the id
            string extensionMethodTemplateId = reflector.ApiNamer.GetMemberName(extensionMethodTemplate);

            // write the element node
            writer.WriteStartElement("element");
            writer.WriteAttributeString("api", extensionMethodTemplateId);
            writer.WriteAttributeString("source", "extension");
            isExtensionMethod = true;
            reflector.WriteMember(extensionMethod);
            isExtensionMethod = false;
            writer.WriteEndElement();
        }
Example #35
0
        private SourceBase(Uri uri)
        {
            m_parameters = new ParameterList();

            var defaultParams = GetDefaultParameters();
            if (defaultParams != null)
            {
                foreach (Parameter parameter in defaultParams)
                {
                    m_parameters.Add(parameter.Name, parameter);
                }
            }

            SetParameterValue(SourceCreatorBase.UriParameterName, uri);
        }
Example #36
0
		public void SendPost(string brd, string title, string text, int? pid=null, int? gid=null, int signature=0, string autocr="on")
		{
			ParameterList qry = new ParameterList();
			qry.Add("board", brd);
			ParameterList data = new ParameterList();
			data.Add("title", title);
			data.Add("text", text);
			if (pid != null)		// replying a post
			{
				data.Add("reid", pid.ToString());
				data.Add("pid", gid.ToString());
			}
			data.Add("signature", signature.ToString());
			data.Add("autocr", autocr);
			DoAction(SendPostCompleted, "bbssnd", qry, data);
		}
Example #37
0
 public ParameterList GetParameters(string CommandName)
 {
     ParameterList pList=new ParameterList();
     CommandInteraction ci = new CommandInteraction();
     try
     {
         List<string> requierdInputs = ci.getRequiredInputs(CommandName);
         foreach (string i in requierdInputs)
         {
             Parameter p = new Parameter();
             p.Name = i;
             pList.Add(p);
         }
     }
     catch (Exception e)
     {
         throw new HttpException((int)HttpStatusCode.InternalServerError,e.Message);
     }
     return pList;
 }
Example #38
0
    //HS D
    //HACK FIXME: define a BlockHole method so can represent block holes by calls to it
    private void DefineBlockHoleMethod(TypeNode t) {
	if (definedTypeNodes.ContainsKey(t))
	    return;
	definedTypeNodes[t] = true;
	ParameterList parList = new ParameterList();
	TypeNode intTp = CoreSystemTypes.Int32;
	TypeNode strTp = CoreSystemTypes.Object.GetArrayType(1);
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("repeat"), intTp, null, null));
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("ifbranches"), intTp, null, null));
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("branchops"), intTp, null, null));
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("conjunctions"), intTp, null, null));
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("ops"), strTp, null, null));
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("condvars"), strTp, null, null));
	parList.Add(new Parameter(null, ParameterFlags.None, new Identifier("argvars"), strTp, null, null));
	Method m = new Method(t, null, new Identifier("BlockHole"), parList, this.TypeExpressionFor(Token.Void), new Block());
	m.Flags |= MethodFlags.Static;
	t.Members.Add(m);	
    }
Example #39
0
    public virtual void CoerceArguments(ParameterList parameters, ref ExpressionList arguments, bool doNotVisitArguments, CallingConventionFlags callingConvention) {
      if (arguments == null) arguments = new ExpressionList();
      int n = arguments.Count;
      int m = parameters == null ? 0 : parameters.Count;
      //if fewer arguments than parameters, supply default values
      for (; n < m; n++) {
        Parameter p = parameters[n];
        TypeNode type = p == null ? null : p.Type;
        if (type == null) type = SystemTypes.Object;
        type = TypeNode.StripModifiers(type);
        if (p.DefaultValue != null)
          arguments.Add(p.DefaultValue);
        else {
          //There should already have been a complaint. Just recover.
          TypeNode elementType = parameters[n].GetParamArrayElementType();
          if (elementType != null) break;
          arguments.Add(new UnaryExpression(new Literal(type, SystemTypes.Type), NodeType.DefaultValue, type));
        }
      }
      if (m > 0) {
        TypeNode elementType = TypeNode.StripModifiers(parameters[m-1].GetParamArrayElementType());
        TypeNode lastArgType = null;
        if (elementType != null && (n > m || (n == m - 1) || n == m
          && (lastArgType = TypeNode.StripModifiers(arguments[m-1].Type)) != null && 
              !this.GetTypeView(lastArgType).IsAssignableTo(TypeNode.StripModifiers(parameters[m-1].Type)) &&
          !(arguments[m-1].Type == SystemTypes.Object && arguments[m-1] is Literal && ((Literal)arguments[m-1]).Value == null))) {
          ExpressionList varargs = new ExpressionList(n-m+1);
          for (int i = m-1; i < n; i++)
            varargs.Add(arguments[i]);
          Debug.Assert(m <= n || m == n+1);
          while (m > n++) arguments.Add(null);
          arguments[m-1] = new ConstructArray(parameters[m-1].GetParamArrayElementType(), varargs);
          arguments.Count = m;
          n = m;
        }
      }
      if (n > m) {
        // Handle Varargs
        Debug.Assert(n == m+1);
        Debug.Assert((callingConvention & CallingConventionFlags.VarArg) != 0);
        ArglistArgumentExpression ale = arguments[n-1] as ArglistArgumentExpression;
        if (ale != null) {
          // rewrite nested arguments to one level.
          // otherwise, the method does not match and I expect the Checker to issue a nice message.
          ExpressionList newArgs = new ExpressionList(n - 1 + ale.Operands.Count);
          for (int i=0; i<n-1; i++) {
            newArgs.Add(arguments[i]);
          }
          for (int i=0; i<ale.Operands.Count; i++) {
            newArgs.Add(ale.Operands[i]);
          }
          arguments = newArgs;
          // adjust formal parameters to actuals
          parameters = (ParameterList)parameters.Clone();
          for (int i=0; i<ale.Operands.Count; i++) {
            if (arguments[i+m] != null) {
              TypeNode pType = arguments[i+m].Type;
              Reference r = pType as Reference;
              if (r != null) pType = r.ElementType;
              parameters.Add(new Parameter(null, pType));
            } else {
              parameters.Add(new Parameter(null, SystemTypes.Object));
            }
          }
          m = arguments.Count;
          n = m;
        } else {
          // leave arguments and let type coercion fail
          // adjust formal parameters to actuals
          parameters = (ParameterList)parameters.Clone();
          parameters.Add(Resolver.ArglistDummyParameter);
          n = parameters.Count;
        }
      }
      if (doNotVisitArguments) {
        for (int i = 0; i < n; i++) {
          Parameter p = this.typeSystem.currentParameter = parameters[i];
          Literal lit = arguments[i] as Literal;
          if (lit != null && lit.Value is TypeNode && p.Type == SystemTypes.Type)
            arguments[i] = lit;
          else {
            if (!this.DoNotVisitArguments(p.DeclaringMethod)) {
              Expression e = arguments[i] = this.typeSystem.ImplicitCoercion(arguments[i], p.Type, this.TypeViewer);
              if (e is BinaryExpression && e.NodeType == NodeType.Box) e = arguments[i] = ((BinaryExpression)e).Operand1;
            }
          }
        }
      } else {
        for (int i = 0; i < n; i++) {

          Parameter p = this.typeSystem.currentParameter = parameters[i];

          bool savedMayReferenceThisAndBase = this.MayReferenceThisAndBase;
          if (p.IsOut
            && this.currentMethod is InstanceInitializer) {
            // allow calls "f(out this.x)" before the explicit base ctor call
            this.MayReferenceThisAndBase = true;
          }

          arguments[i] = this.CoerceArgument(this.VisitExpression(arguments[i]), p);

          this.MayReferenceThisAndBase = savedMayReferenceThisAndBase;
        }
      }
      this.typeSystem.currentParameter = null;
    }
        private ParameterList ParseMethodParameters()
        {
            bool flag;
            TokenInfo token;
            ParameterList paramList;
            Parameter param;

            bool expectParam = true;

            flag = true;
            paramList = new ParameterList();

            Expect(Token.LeftParenthesis);

            while (flag)
            {
                token = GetNextToken();

                tokenQueue.Enqueue(token);

                switch (token.Token)
                {
                    case Token.ByRef:
                    case Token.ByVal:
                        ParseMethodParameterModifier();
                        break;

                    case Token.Identifier:
                        if (!expectParam)
                        {
                        }
                        param = ParseMethodParameter(paramList);
                        paramList.Add(param);
                        expectParam = false;
                        break;

                    case Token.Comma:
                        if (expectParam)
                        {
                        }
                        tokenQueue.Dequeue();
                        expectParam = true;
                        break;

                    case Token.EOL:
                        tokenQueue.Dequeue();
                        Report.AddItem(VBErrors.RighParenthesisExpected, token.SourceFile,
                                       new SourceSpan(token.GetSourceLocation(), default(SourceLocation)), null);
                        goto case Token.RightParenthesis;

                    case Token.RightParenthesis:
                        tokenQueue.Dequeue();
                        flag = false;
                        break;

                    default:

                        break;
                }
            }

            return paramList;
        }
Example #41
0
        public static FunctionType For(TypeNode returnType, ParameterList parameters, TypeNode referringType)
        {
            if(returnType == null || referringType == null)
                return null;
            Module module = referringType.DeclaringModule;
            if(module == null)
                return null;
            TypeFlags visibility = returnType.Flags & TypeFlags.VisibilityMask;
            StringBuilder name = new StringBuilder();
            name.Append("Function_");
            name.Append(returnType.Name.ToString());
            int n = parameters == null ? 0 : parameters.Count;
            if(parameters != null)
                for(int i = 0; i < n; i++)
                {
                    Parameter p = parameters[i];
                    if(p == null || p.Type == null)
                        continue;
                    visibility = TypeNode.GetVisibilityIntersection(visibility, p.Type.Flags & TypeFlags.VisibilityMask);
                    name.Append('_');
                    name.Append(p.Type.Name.ToString());
                }
            FunctionType func = null;
            int count = 0;
            string fNameString = name.ToString();
            Identifier fName = Identifier.For(fNameString);
            TypeNode result = module.GetStructurallyEquivalentType(StandardIds.StructuralTypes, fName);
            while(result != null)
            {
                //Mangled name is the same. But mangling is not unique (types are not qualified with assemblies), so check for equality.
                func = result as FunctionType;
                bool goodMatch = func != null && func.ReturnType == returnType;
                if(goodMatch)
                {
                    //^ assert func != null;
                    ParameterList fpars = func.Parameters;
                    int m = fpars == null ? 0 : fpars.Count;
                    goodMatch = n == m;
                    if(parameters != null && fpars != null)
                        for(int i = 0; i < n && goodMatch; i++)
                        {
                            Parameter p = parameters[i];
                            Parameter q = fpars[i];
                            goodMatch = p != null && q != null && p.Type == q.Type;
                        }
                }
                if(goodMatch)
                    return func;
                //Mangle some more
                fName = Identifier.For(fNameString + (++count).ToString());
                result = module.GetStructurallyEquivalentType(StandardIds.StructuralTypes, fName);
            }

            if(parameters != null)
            {
                ParameterList clonedParams = new ParameterList();

                for(int i = 0; i < n; i++)
                {
                    Parameter p = parameters[i];
                    if(p != null)
                        p = (Parameter)p.Clone();
                    clonedParams.Add(p);
                }

                parameters = clonedParams;
            }

            func = new FunctionType(fName, returnType, parameters);
            func.DeclaringModule = module;
            switch(visibility)
            {
                case TypeFlags.NestedFamANDAssem:
                case TypeFlags.NestedFamily:
                case TypeFlags.NestedPrivate:
                    referringType.Members.Add(func);
                    func.DeclaringType = referringType;
                    func.Flags &= ~TypeFlags.VisibilityMask;
                    func.Flags |= TypeFlags.NestedPrivate;
                    break;
                default:
                    module.Types.Add(func);
                    break;
            }
            module.StructurallyEquivalentType[func.Name.UniqueIdKey] = func;
            func.ProvideMembers();
            return func;
        }
 public virtual Differences VisitParameterList(ParameterList list1, ParameterList list2,
   out ParameterList changes, out ParameterList deletions, out ParameterList insertions){
   changes = list1 == null ? null : list1.Clone();
   deletions = list1 == null ? null : list1.Clone();
   insertions = list1 == null ? new ParameterList() : list1.Clone();
   //^ assert insertions != null;
   Differences differences = new Differences();
   //Compare definitions that have matching key attributes
   TrivialHashtable matchingPosFor = new TrivialHashtable();
   TrivialHashtable matchedNodes = new TrivialHashtable();
   for (int j = 0, n = list2 == null ? 0 : list2.Count; j < n; j++){
     //^ assert list2 != null;
     Parameter nd2 = list2[j];
     if (nd2 == null || nd2.Name == null) continue;
     matchingPosFor[nd2.Name.UniqueIdKey] = j;
     insertions.Add(null);
   }
   for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
     //^ assert list1 != null && changes != null && deletions != null;
     Parameter nd1 = list1[i];
     if (nd1 == null || nd1.Name == null) continue;
     object pos = matchingPosFor[nd1.Name.UniqueIdKey];
     if (!(pos is int)) continue;
     //^ assert pos != null;
     int j = (int)pos;
     //^ assume list2 != null; //since there was entry int matchingPosFor
     Parameter nd2 = list2[j];
     //^ assume nd2 != null;
     //nd1 and nd2 have the same key attributes and are therefore treated as the same entity
     matchedNodes[nd1.UniqueKey] = nd1;
     matchedNodes[nd2.UniqueKey] = nd2;
     //nd1 and nd2 may still be different, though, so find out how different
     Differences diff = this.VisitParameter(nd1, nd2);
     if (diff == null){Debug.Assert(false); continue;}
     if (diff.NumberOfDifferences != 0){
       changes[i] = diff.Changes as Parameter;
       deletions[i] = diff.Deletions as Parameter;
       insertions[i] = diff.Insertions as Parameter;
       insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation
       Debug.Assert(diff.Changes == changes[i] && diff.Deletions == deletions[i] && diff.Insertions == insertions[i]);
       differences.NumberOfDifferences += diff.NumberOfDifferences;
       differences.NumberOfSimilarities += diff.NumberOfSimilarities;
       continue;
     }
     changes[i] = null;
     deletions[i] = null;
     insertions[i] = null;
     insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation
   }
   //Find deletions
   for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
     //^ assert list1 != null && changes != null && deletions != null;
     Parameter nd1 = list1[i]; 
     if (nd1 == null) continue;
     if (matchedNodes[nd1.UniqueKey] != null) continue;
     changes[i] = null;
     deletions[i] = nd1;
     insertions[i] = null;
     differences.NumberOfDifferences += 1;
   }
   //Find insertions
   for (int j = 0, n = list1 == null ? 0 : list1.Count, m = list2 == null ? 0 : list2.Count; j < m; j++){
     //^ assert list2 != null;
     Parameter nd2 = list2[j]; 
     if (nd2 == null) continue;
     if (matchedNodes[nd2.UniqueKey] != null) continue;
     insertions[n+j] = nd2;  //Records nd2 as an insertion into list1, along with its position in list2
     differences.NumberOfDifferences += 1; //REVIEW: put the size of the tree here?
   }
   if (differences.NumberOfDifferences == 0){
     changes = null;
     deletions = null;
     insertions = null;
   }
   return differences;
 }
Example #43
0
    /// <summary>
    /// Tries to reuse or create the attribute
    /// </summary>
    private static InstanceInitializer GetRuntimeContractsAttributeCtor(AssemblyNode assembly)
    {
      EnumNode runtimeContractsFlags = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsFlags")) as EnumNode;
      Class RuntimeContractsAttributeClass = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsAttribute")) as Class;

      if (runtimeContractsFlags == null)
      {
        #region Add [Flags]
        Member flagsConstructor = RewriteHelper.flagsAttributeNode.GetConstructor();
        AttributeNode flagsAttribute = new AttributeNode(new MemberBinding(null, flagsConstructor), null, AttributeTargets.Class);
        #endregion Add [Flags]
        runtimeContractsFlags = new EnumNode(assembly,
          null, /* declaringType */
          new AttributeList(2),
          TypeFlags.Sealed,
          ContractNodes.ContractNamespace,
          Identifier.For("RuntimeContractsFlags"),
          new InterfaceList(),
          new MemberList());
        runtimeContractsFlags.Attributes.Add(flagsAttribute);
        RewriteHelper.TryAddCompilerGeneratedAttribute(runtimeContractsFlags);
        runtimeContractsFlags.UnderlyingType = SystemTypes.Int32;

        Type copyFrom = typeof(RuntimeContractEmitFlags);
        foreach (System.Reflection.FieldInfo fi in copyFrom.GetFields())
        {
          if (fi.IsLiteral)
          {
            AddEnumValue(runtimeContractsFlags, fi.Name, fi.GetRawConstantValue());
          }
        }
        assembly.Types.Add(runtimeContractsFlags);

      }


      InstanceInitializer ctor = (RuntimeContractsAttributeClass == null) ? null : RuntimeContractsAttributeClass.GetConstructor(runtimeContractsFlags);

      if (RuntimeContractsAttributeClass == null)
      {
        RuntimeContractsAttributeClass = new Class(assembly,
          null, /* declaringType */
          new AttributeList(),
          TypeFlags.Sealed,
          ContractNodes.ContractNamespace,
          Identifier.For("RuntimeContractsAttribute"),
          SystemTypes.Attribute,
          new InterfaceList(),
          new MemberList(0));

        RewriteHelper.TryAddCompilerGeneratedAttribute(RuntimeContractsAttributeClass);
        assembly.Types.Add(RuntimeContractsAttributeClass);
      }
      if (ctor == null) {

        Block returnBlock = new Block(new StatementList(new Return()));

        Block body = new Block(new StatementList());
        Block b = new Block(new StatementList());
        ParameterList pl = new ParameterList();
        Parameter levelParameter = new Parameter(Identifier.For("contractFlags"), runtimeContractsFlags);
        pl.Add(levelParameter);

        ctor = new InstanceInitializer(RuntimeContractsAttributeClass, null, pl, body);
        ctor.Flags = MethodFlags.Assembly | MethodFlags.HideBySig | MethodFlags.SpecialName | MethodFlags.RTSpecialName;

        Method baseCtor = SystemTypes.Attribute.GetConstructor();

        b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, baseCtor), new ExpressionList(ctor.ThisParameter))));
        b.Statements.Add(returnBlock);
        body.Statements.Add(b);

        RuntimeContractsAttributeClass.Members.Add(ctor);
      }

      return ctor;
    }
Example #44
0
    /// <summary>
    /// Constructs (and returns) a method that looks like this:
    /// 
    ///   [System.Diagnostics.DebuggerNonUserCodeAttribute]
    ///   [System.Runtime.ConstrainedExecution.ReliabilityContractReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    ///   static void name(bool condition, string message, string conditionText){
    ///     if (!condition) {
    ///       System.Diagnostics.Contracts.Contract.Failure(kind, message, conditionText, null);
    ///     }
    ///   }
    ///
    /// Or, if the ContractFailureKind is PostconditionOnException, then the generated method
    /// gets an extra parameter which is an Exception and that parameter is passed to Contract.Failure instead of null
    /// </summary>
    private Method MakeMethod(string name, ContractFailureKind kind)
    {
      Parameter conditionParameter = new Parameter(Identifier.For("condition"), SystemTypes.Boolean);
      Parameter messageParameter = new Parameter(Identifier.For("msg"), SystemTypes.String);
      Parameter conditionTextParameter = new Parameter(Identifier.For("conditionTxt"), SystemTypes.String);
      Parameter exceptionParameter = new Parameter(Identifier.For("originalException"), SystemTypes.Exception);

      Block returnBlock = new Block(new StatementList(new Return()));

      Block body = new Block(new StatementList());
      Block b = new Block(new StatementList());
      b.Statements.Add(new Branch(conditionParameter, returnBlock));
      ExpressionList elist = new ExpressionList();
      elist.Add(TranslateKindForBackwardCompatibility(kind));
      elist.Add(messageParameter);
      elist.Add(conditionTextParameter);
      if (kind == ContractFailureKind.PostconditionOnException)
      {
        elist.Add(exceptionParameter);
      }
      else
      {
        elist.Add(Literal.Null);
      }
      b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, this.FailureMethod), elist)));
      b.Statements.Add(returnBlock);
      body.Statements.Add(b);

      ParameterList pl = new ParameterList(conditionParameter, messageParameter, conditionTextParameter);
      if (kind == ContractFailureKind.PostconditionOnException)
      {
        pl.Add(exceptionParameter);
      }
      Method m = new Method(this.RuntimeContractType, null, Identifier.For(name), pl, SystemTypes.Void, body);
      m.Flags = MethodFlags.Assembly | MethodFlags.Static;
      m.Attributes = new AttributeList();
      this.RuntimeContractType.Members.Add(m);

      Member constructor = null;
      AttributeNode attribute = null;

      #region Add [DebuggerNonUserCodeAttribute]
      if (this.HideFromDebugger) {
        TypeNode debuggerNonUserCode = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Diagnostics"), Identifier.For("DebuggerNonUserCodeAttribute"));
        if (debuggerNonUserCode != null)
        {
          constructor = debuggerNonUserCode.GetConstructor();
          attribute = new AttributeNode(new MemberBinding(null, constructor), null, AttributeTargets.Method);
          m.Attributes.Add(attribute);
        }
      }
      #endregion Add [DebuggerNonUserCodeAttribute]

      TypeNode reliabilityContract = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("ReliabilityContractAttribute"));
      TypeNode consistency = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("Consistency"));
      TypeNode cer = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.ConstrainedExecution"), Identifier.For("Cer"));
      if (reliabilityContract != null && consistency != null && cer != null) {
        constructor = reliabilityContract.GetConstructor(consistency, cer);
        if (constructor != null) {
          attribute = new AttributeNode(
            new MemberBinding(null, constructor),
            new ExpressionList(
              new Literal(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, consistency),
              new Literal(System.Runtime.ConstrainedExecution.Cer.MayFail, cer)),
              AttributeTargets.Method
              );
          m.Attributes.Add(attribute);
        }
      }
      return m;
    }
Example #45
0
    private Class MakeContractException() {
      Class contractExceptionType;

      #region If we're rewriting an assembly for v4 or above and it *isn't* Silverlight (so serialization support is needed), then use new embedded dll as the type
      if (4 <= TargetPlatform.MajorVersion) {
        var iSafeSerializationData = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.Serialization"), Identifier.For("ISafeSerializationData")) as Interface;
        if (iSafeSerializationData != null) {
          // Just much easier to write the C# and have the compiler generate everything than to try and create it all manually
          System.Reflection.Assembly embeddedAssembly;
          Stream embeddedAssemblyStream;
          embeddedAssembly = System.Reflection.Assembly.GetExecutingAssembly();
          embeddedAssemblyStream = embeddedAssembly.GetManifestResourceStream("Microsoft.Contracts.Foxtrot.InternalException.dll");
          byte[] data = new byte[0];
          using (var br = new BinaryReader(embeddedAssemblyStream)) {
            var len = embeddedAssemblyStream.Length;
            if (len < Int32.MaxValue)
              data = br.ReadBytes((int)len);
            AssemblyNode assemblyNode = AssemblyNode.GetAssembly(data, TargetPlatform.StaticAssemblyCache, true, false, true);
            contractExceptionType = assemblyNode.GetType(Identifier.For(""), Identifier.For("ContractException")) as Class;
          }
          if (contractExceptionType == null)
            throw new RewriteException("Tried to create the ContractException type from the embedded dll, but failed");
          var d = new Duplicator(this.targetAssembly, this.RuntimeContractType);
          d.FindTypesToBeDuplicated(new TypeNodeList(contractExceptionType));

          var ct = d.Visit(contractExceptionType);
          contractExceptionType = (Class)ct;
          contractExceptionType.Flags |= TypeFlags.NestedPrivate;
          this.RuntimeContractType.Members.Add(contractExceptionType);
          return contractExceptionType;
        }
      }
      #endregion

      contractExceptionType = new Class(this.targetAssembly, this.RuntimeContractType, new AttributeList(), TypeFlags.Class | TypeFlags.NestedPrivate | TypeFlags.Serializable, null, Identifier.For("ContractException"), SystemTypes.Exception, null, null);

      RewriteHelper.TryAddCompilerGeneratedAttribute(contractExceptionType);

      var kindField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_Kind"), contractNodes.ContractFailureKind, null);
      var userField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_UserMessage"), SystemTypes.String, null);
      var condField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_Condition"), SystemTypes.String, null);
      contractExceptionType.Members.Add(kindField);
      contractExceptionType.Members.Add(userField);
      contractExceptionType.Members.Add(condField);

      #region Constructor for setting the fields
      var parameters = new ParameterList();
      var kindParam = new Parameter(Identifier.For("kind"), this.contractNodes.ContractFailureKind);
      var failureParam = new Parameter(Identifier.For("failure"), SystemTypes.String);
      var usermsgParam = new Parameter(Identifier.For("usermsg"), SystemTypes.String);
      var conditionParam = new Parameter(Identifier.For("condition"), SystemTypes.String);
      var innerParam = new Parameter(Identifier.For("inner"), SystemTypes.Exception);
      parameters.Add(kindParam);
      parameters.Add(failureParam);
      parameters.Add(usermsgParam);
      parameters.Add(conditionParam);
      parameters.Add(innerParam);
      var body = new Block(new StatementList());
      var ctor = new InstanceInitializer(contractExceptionType, null, parameters, body);
      ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig;
      ctor.CallingConvention = CallingConventionFlags.HasThis;
      body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(ctor.ThisParameter, contractExceptionType.BaseClass.GetConstructor(SystemTypes.String, SystemTypes.Exception)), new ExpressionList(failureParam, innerParam))));
      body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, kindField), kindParam));
      body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, userField), usermsgParam));
      body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, condField), conditionParam));
      body.Statements.Add(new Return());
      contractExceptionType.Members.Add(ctor);
      #endregion

      if (SystemTypes.SerializationInfo != null && SystemTypes.SerializationInfo.BaseClass != null) {
        // Silverlight (e.g.) is a platform that doesn't support serialization. So check to make sure the type really exists.
        // 
        var baseCtor = SystemTypes.Exception.GetConstructor(SystemTypes.SerializationInfo, SystemTypes.StreamingContext);

        if (baseCtor != null) {
          #region Deserialization Constructor
          parameters = new ParameterList();
          var info = new Parameter(Identifier.For("info"), SystemTypes.SerializationInfo);
          var context = new Parameter(Identifier.For("context"), SystemTypes.StreamingContext);
          parameters.Add(info);
          parameters.Add(context);
          body = new Block(new StatementList());
          ctor = new InstanceInitializer(contractExceptionType, null, parameters, body);
          ctor.Flags |= MethodFlags.Private | MethodFlags.HideBySig;
          ctor.CallingConvention = CallingConventionFlags.HasThis;
          // : base(info, context) 
          body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(ctor.ThisParameter, baseCtor), new ExpressionList(info, context))));
          // _Kind = (ContractFailureKind)info.GetInt32("Kind");
          var getInt32 = SystemTypes.SerializationInfo.GetMethod(Identifier.For("GetInt32"), SystemTypes.String);
          body.Statements.Add(new AssignmentStatement(
              new MemberBinding(new This(), kindField),
              new MethodCall(new MemberBinding(info, getInt32), new ExpressionList(new Literal("Kind", SystemTypes.String)))
              ));
          // _UserMessage = info.GetString("UserMessage");
          var getString = SystemTypes.SerializationInfo.GetMethod(Identifier.For("GetString"), SystemTypes.String);
          body.Statements.Add(new AssignmentStatement(
              new MemberBinding(new This(), userField),
              new MethodCall(new MemberBinding(info, getString), new ExpressionList(new Literal("UserMessage", SystemTypes.String)))
              ));
          // _Condition = info.GetString("Condition");
          body.Statements.Add(new AssignmentStatement(
              new MemberBinding(new This(), condField),
              new MethodCall(new MemberBinding(info, getString), new ExpressionList(new Literal("Condition", SystemTypes.String)))
              ));
          body.Statements.Add(new Return());
          contractExceptionType.Members.Add(ctor);
          #endregion

          #region GetObjectData

          var securityCriticalCtor = SystemTypes.SecurityCriticalAttribute.GetConstructor();
          var securityCriticalAttribute = new AttributeNode(new MemberBinding(null, securityCriticalCtor), null, System.AttributeTargets.Method);
          var attrs = new AttributeList(securityCriticalAttribute);
          parameters = new ParameterList();
          info = new Parameter(Identifier.For("info"), SystemTypes.SerializationInfo);
          context = new Parameter(Identifier.For("context"), SystemTypes.StreamingContext);
          parameters.Add(info);
          parameters.Add(context);
          body = new Block(new StatementList());
          var getObjectDataName = Identifier.For("GetObjectData");
          var getObjectData = new Method(contractExceptionType, attrs, getObjectDataName, parameters, SystemTypes.Void, body);
          getObjectData.CallingConvention = CallingConventionFlags.HasThis;
          // public override
          getObjectData.Flags = MethodFlags.Public | MethodFlags.Virtual;
          // base.GetObjectData(info, context);
          var baseGetObjectData = SystemTypes.Exception.GetMethod(getObjectDataName, SystemTypes.SerializationInfo, SystemTypes.StreamingContext);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(new This(), baseGetObjectData), new ExpressionList(info, context), NodeType.Call, SystemTypes.Void)
            ));
          // info.AddValue("Kind", _Kind);
          var addValueObject = SystemTypes.SerializationInfo.GetMethod(Identifier.For("AddValue"), SystemTypes.String, SystemTypes.Object);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(info, addValueObject), new ExpressionList(new Literal("Kind", SystemTypes.String), new BinaryExpression(new MemberBinding(new This(), kindField), new Literal(contractNodes.ContractFailureKind), NodeType.Box)), NodeType.Call, SystemTypes.Void)
            ));
          // info.AddValue("UserMessage", _UserMessage);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(info, addValueObject), new ExpressionList(new Literal("UserMessage", SystemTypes.String), new MemberBinding(new This(), userField)), NodeType.Call, SystemTypes.Void)
            ));
          // info.AddValue("Condition", _Condition);
          body.Statements.Add(new ExpressionStatement(
            new MethodCall(new MemberBinding(info, addValueObject), new ExpressionList(new Literal("Condition", SystemTypes.String), new MemberBinding(new This(), condField)), NodeType.Call, SystemTypes.Void)
            ));

          body.Statements.Add(new Return());
          contractExceptionType.Members.Add(getObjectData);
          #endregion
        }
      }

      this.RuntimeContractType.Members.Add(contractExceptionType);
      return contractExceptionType;
    }
Example #46
0
 private ParameterList ParseParameters(Token closingToken, TokenSet followers, bool namesAreOptional, bool typesAreOptional){
   bool arglist = false;
   Debug.Assert(closingToken == Token.RightParenthesis || closingToken == Token.RightBracket);
   SourceContext sctx = this.scanner.CurrentSourceContext;
   if (closingToken == Token.RightParenthesis){
     if (this.currentToken != Token.LeftParenthesis){
       this.SkipTo(followers|Parser.UnaryStart, Error.SyntaxError, "(");
     }
     if (this.currentToken == Token.LeftParenthesis)
       this.GetNextToken();
   }else{
     if (this.currentToken != Token.LeftBracket)
       this.SkipTo(followers|Parser.UnaryStart, Error.SyntaxError, "[");
     if (this.currentToken == Token.LeftBracket)
       this.GetNextToken();
   }
   ParameterList result = new ParameterList();
   if (this.currentToken != closingToken && this.currentToken != Token.EndOfFile){
     bool allowRefParameters = closingToken == Token.RightParenthesis;
     TokenSet followersOrCommaOrRightParenthesis = followers|Token.Comma|closingToken|Token.ArgList;
     int counter = 0;
     for (;;){
       if (this.currentToken == Token.ArgList) {
         Parameter ap = new Parameter(StandardIds.__Arglist, this.TypeExpressionFor(Token.Void));
         ap.SourceContext = this.scanner.CurrentSourceContext;
         this.GetNextToken();
         arglist = true;
         result.Add(ap);
         break;
       }
       Parameter p = this.ParseParameter(followersOrCommaOrRightParenthesis, allowRefParameters, namesAreOptional, typesAreOptional);
       if (namesAreOptional && p != null && p.Name == Identifier.Empty){
         p.Name = new Identifier("p"+counter++);
         if (p.Type != null)
           p.Name.SourceContext = p.Type.SourceContext;
       }
       if (typesAreOptional && p != null && p.Type == null) allowRefParameters = false;
       result.Add(p);
       if (this.currentToken == Token.Comma)
         this.GetNextToken();
       else
         break;
     }
   }
   if (closingToken == Token.RightBracket) {
     if (result.Count == 0)
       this.HandleError(Error.IndexerNeedsParam);
     else if (arglist) {
       this.HandleError(result[result.Count-1].SourceContext, Error.NoArglistInIndexers);
       result.Count = result.Count-1;
     }
   }
   if (this.currentToken == closingToken){
     if (this.sink != null)
       this.sink.MatchPair(sctx, this.scanner.CurrentSourceContext);
     this.GetNextToken();
     this.SkipTo(followers);
   }else{
     this.SkipTo(followers, closingToken==Token.RightBracket ? Error.ExpectedRightBracket : Error.ExpectedRightParenthesis);
   }
   return result;
 }
		public void TestBasicFunctionality ()
		{
			var list = new ParameterList ();
			Parameter parameter;
			string value;
			int index;

			Assert.IsFalse (list.IsReadOnly, "IsReadOnly");
			Assert.AreEqual (0, list.Count);

			list.Add (new Parameter ("abc", "0"));
			list.Add (Encoding.UTF8, "def", "1");
			list.Add ("ghi", "2");

			Assert.AreEqual (3, list.Count, "Count");
			Assert.IsTrue (list.Contains (list[0]));
			Assert.IsTrue (list.Contains ("aBc"));
			Assert.IsTrue (list.Contains ("DEf"));
			Assert.IsTrue (list.Contains ("gHI"));
			Assert.AreEqual (0, list.IndexOf ("aBc"));
			Assert.AreEqual (1, list.IndexOf ("dEF"));
			Assert.AreEqual (2, list.IndexOf ("Ghi"));
			Assert.AreEqual ("abc", list[0].Name);
			Assert.AreEqual ("def", list[1].Name);
			Assert.AreEqual ("ghi", list[2].Name);
			Assert.AreEqual ("0", list["AbC"]);
			Assert.AreEqual ("1", list["dEf"]);
			Assert.AreEqual ("2", list["GHi"]);

			Assert.IsTrue (list.TryGetValue ("Abc", out parameter));
			Assert.AreEqual ("abc", parameter.Name);
			Assert.IsTrue (list.TryGetValue ("Abc", out value));
			Assert.AreEqual ("0", value);

			Assert.IsFalse (list.Remove ("xyz"), "Remove");
			list.Insert (0, new Parameter ("xyz", "3"));
			Assert.IsTrue (list.Remove ("xyz"), "Remove");

			var array = new Parameter[list.Count];
			list.CopyTo (array, 0);
			Assert.AreEqual ("abc", array[0].Name);
			Assert.AreEqual ("def", array[1].Name);
			Assert.AreEqual ("ghi", array[2].Name);

			index = 0;
			foreach (var param in list) {
				Assert.AreEqual (array[index], param);
				index++;
			}

			list.Clear ();
			Assert.AreEqual (0, list.Count, "Clear");

			list.Add ("xyz", "3");
			list.Insert (0, array[2]);
			list.Insert (0, array[1].Name, array[1].Value);
			list.Insert (0, array[0]);

			Assert.AreEqual (4, list.Count);
			Assert.AreEqual ("abc", list[0].Name);
			Assert.AreEqual ("def", list[1].Name);
			Assert.AreEqual ("ghi", list[2].Name);
			Assert.AreEqual ("xyz", list[3].Name);
			Assert.AreEqual ("0", list["AbC"]);
			Assert.AreEqual ("1", list["dEf"]);
			Assert.AreEqual ("2", list["GHi"]);
			Assert.AreEqual ("3", list["XYZ"]);

			list.RemoveAt (3);
			Assert.AreEqual (3, list.Count);

			Assert.AreEqual ("; abc=\"0\"; def=\"1\"; ghi=\"2\"", list.ToString ());
		}
		public void TestArgumentExceptions ()
		{
			const string invalid = "X-测试文本";
			var list = new ParameterList ();
			Parameter param;
			string value;

			// Add
			Assert.Throws<ArgumentNullException> (() => list.Add ((Encoding) null, "name", "value"));
			Assert.Throws<ArgumentNullException> (() => list.Add (Encoding.UTF8, null, "value"));
			Assert.Throws<ArgumentException> (() => list.Add (Encoding.UTF8, string.Empty, "value"));
			Assert.Throws<ArgumentException> (() => list.Add (Encoding.UTF8, invalid, "value"));
			Assert.Throws<ArgumentNullException> (() => list.Add (Encoding.UTF8, "name", null));
			Assert.Throws<ArgumentNullException> (() => list.Add ((string) null, "name", "value"));
			Assert.Throws<ArgumentNullException> (() => list.Add ("utf-8", null, "value"));
			Assert.Throws<ArgumentException> (() => list.Add ("utf-8", string.Empty, "value"));
			Assert.Throws<ArgumentException> (() => list.Add ("utf-8", invalid, "value"));
			Assert.Throws<ArgumentNullException> (() => list.Add ("utf-8", "name", null));
			Assert.Throws<ArgumentNullException> (() => list.Add (null, "value"));
			Assert.Throws<ArgumentException> (() => list.Add (string.Empty, "value"));
			Assert.Throws<ArgumentException> (() => list.Add (invalid, "value"));
			Assert.Throws<ArgumentNullException> (() => list.Add ("name", null));
			Assert.Throws<ArgumentNullException> (() => list.Add (null));

			// Contains
			Assert.Throws<ArgumentNullException> (() => list.Contains ((Parameter) null));
			Assert.Throws<ArgumentNullException> (() => list.Contains ((string) null));

			// CopyTo
			Assert.Throws<ArgumentOutOfRangeException> (() => list.CopyTo (new Parameter[0], -1));
			Assert.Throws<ArgumentNullException> (() => list.CopyTo (null, 0));

			// IndexOf
			Assert.Throws<ArgumentNullException> (() => list.IndexOf ((Parameter) null));
			Assert.Throws<ArgumentNullException> (() => list.IndexOf ((string) null));

			// Insert
			list.Add ("name", "value");
			Assert.Throws<ArgumentOutOfRangeException> (() => list.Insert (-1, new Parameter ("name", "value")));
			Assert.Throws<ArgumentOutOfRangeException> (() => list.Insert (-1, "field", "value"));
			Assert.Throws<ArgumentNullException> (() => list.Insert (0, null, "value"));
			Assert.Throws<ArgumentException> (() => list.Insert (0, string.Empty, "value"));
			Assert.Throws<ArgumentException> (() => list.Insert (0, invalid, "value"));
			Assert.Throws<ArgumentNullException> (() => list.Insert (0, "name", null));
			Assert.Throws<ArgumentNullException> (() => list.Insert (0, null));

			// Remove
			Assert.Throws<ArgumentNullException> (() => list.Remove ((Parameter) null));
			Assert.Throws<ArgumentNullException> (() => list.Remove ((string) null));

			// RemoveAt
			Assert.Throws<ArgumentOutOfRangeException> (() => list.RemoveAt (-1));

			// TryGetValue
			Assert.Throws<ArgumentNullException> (() => list.TryGetValue (null, out param));
			Assert.Throws<ArgumentNullException> (() => list.TryGetValue (null, out value));

			// Indexers
			Assert.Throws<ArgumentOutOfRangeException> (() => list[-1] = new Parameter ("name", "value"));
			Assert.Throws<ArgumentOutOfRangeException> (() => param = list[-1]);
			Assert.Throws<ArgumentNullException> (() => list[0] = null);
			Assert.Throws<ArgumentNullException> (() => list[null] = "value");
			Assert.Throws<ArgumentNullException> (() => value = list[null]);
			Assert.Throws<ArgumentNullException> (() => list["name"] = null);
		}
Example #49
0
        internal static void ParseStringToParameters(string content, ParameterList parameterlist, out SXL.XDocument xdoc)
        {
            var lo = new System.Xml.Linq.LoadOptions();

            xdoc = System.Xml.Linq.XDocument.Parse(content,lo);
            var root = xdoc.Root;
            var fault_el = root.Element("fault");
            if (fault_el != null)
            {
                var f = Fault.ParseXml(fault_el);

                string msg = string.Format("XMLRPC FAULT [{0}]: \"{1}\"", f.FaultCode, f.FaultString);
                var exc = new XmlRpcException(msg);
                exc.Fault = f;

                throw exc;
            }

            var params_el = root.GetElement("params");
            var param_els = params_el.Elements("param").ToList();

            foreach (var param_el in param_els)
            {
                var value_el = param_el.GetElement("value");

                var val = XmlRpc.Value.ParseXml(value_el);
                parameterlist.Add(val);
            }
        }
Example #50
0
    private Method CreateWrapperMethod(bool virtcall, TypeNode virtcallConstraint, Method templateMethod, TypeNode templateType, TypeNode wrapperType, Method methodWithContract, Method instanceMethod, SourceContext callingContext)
    {
      bool isProtected = IsProtected(templateMethod);
      Identifier name = templateMethod.Name;
      if (virtcall) {
        if (virtcallConstraint != null) {
          name = Identifier.For("CV$" + name.Name);
        }
        else {
          name = Identifier.For("V$" + name.Name);
        }
      }
      else {
        name = Identifier.For("NV$" + name.Name);
      }
      Duplicator dup = new Duplicator(this.assemblyBeingRewritten, wrapperType);
      TypeNodeList typeParameters = null;
      TypeNodeList typeParameterFormals = new TypeNodeList();
      TypeNodeList typeParameterActuals = new TypeNodeList();

      if (templateMethod.TemplateParameters != null) {
        dup.FindTypesToBeDuplicated(templateMethod.TemplateParameters);
        typeParameters = dup.VisitTypeParameterList(templateMethod.TemplateParameters);
        for (int i = 0; i < typeParameters.Count; i++) {
          typeParameterFormals.Add(typeParameters[i]);
          typeParameterActuals.Add(templateMethod.TemplateParameters[i]);
        }
      }
      ITypeParameter constraintTypeParam = null;
      if (virtcallConstraint != null) {
        if (typeParameters == null) { typeParameters = new TypeNodeList(); }
        var constraint = templateMethod.DeclaringType;
        var classConstraint = constraint as Class;
        if (classConstraint != null) {
          var classParam = new MethodClassParameter();
          classParam.BaseClass = classConstraint;
          classParam.Name = Identifier.For("TC");
          classParam.DeclaringType = wrapperType;
          typeParameters.Add(classParam);
          constraintTypeParam = classParam;
        }
        else {
          var mtp = new MethodTypeParameter();
          Interface intf = constraint as Interface;
          if (intf != null) {
            mtp.Interfaces.Add(intf);
          }
          mtp.Name = Identifier.For("TC");
          mtp.DeclaringType = wrapperType;
          typeParameters.Add(mtp);
          constraintTypeParam = mtp;
        }
      }
      var consolidatedTemplateTypeParameters = templateType.ConsolidatedTemplateParameters;
      if (consolidatedTemplateTypeParameters != null && consolidatedTemplateTypeParameters.Count > 0) {
        var consolidatedWrapperTypeParameters = wrapperType.ConsolidatedTemplateParameters;
        for (int i = 0; i < consolidatedTemplateTypeParameters.Count; i++) {
          typeParameterFormals.Add(consolidatedWrapperTypeParameters[i]);
          typeParameterActuals.Add(consolidatedTemplateTypeParameters[i]);
        }
      }
      Specializer spec = null;
      if (typeParameterActuals.Count > 0) {
        spec = new Specializer(this.assemblyBeingRewritten, typeParameterActuals, typeParameterFormals);
      }
      var parameters = new ParameterList();
      var asTypeConstraintTypeParam = constraintTypeParam as TypeNode;

      if (!isProtected && !templateMethod.IsStatic) {
        TypeNode thisType = GetThisTypeInstance(templateType, wrapperType, asTypeConstraintTypeParam);
        parameters.Add(new Parameter(Identifier.For("@this"), thisType));
      }
      for (int i = 0; i < templateMethod.Parameters.Count; i++) {
        parameters.Add((Parameter)dup.VisitParameter(templateMethod.Parameters[i]));
      }
      var retType = dup.VisitTypeReference(templateMethod.ReturnType);
      if (spec != null) {
        parameters = spec.VisitParameterList(parameters);
        retType = spec.VisitTypeReference(retType);
      }

      var wrapperMethod = new Method(wrapperType, null, name, parameters, retType, null);
      RewriteHelper.TryAddCompilerGeneratedAttribute(wrapperMethod);

      if (isProtected) {
        wrapperMethod.Flags = templateMethod.Flags & ~MethodFlags.Abstract;
        wrapperMethod.CallingConvention = templateMethod.CallingConvention;
      }
      else {
        wrapperMethod.Flags |= MethodFlags.Static | MethodFlags.Assembly;
      }
      if (constraintTypeParam != null) {
        constraintTypeParam.DeclaringMember = wrapperMethod;
      }
      if (typeParameters != null) {
        if (spec != null) {
          typeParameters = spec.VisitTypeParameterList(typeParameters);
        }
        wrapperMethod.IsGeneric = true;
        wrapperMethod.TemplateParameters = typeParameters;
      }

      // create body
      var sl = new StatementList();
      Block b = new Block(sl);

      // insert requires
      AddRequiresToWrapperMethod(wrapperMethod, b, methodWithContract);

      // create original call
      var targetType = templateType;
      if (isProtected)
      {
        // need to use base chain instantiation of target type.
        targetType = instanceMethod.DeclaringType;
      }
      else
      {
        if (targetType.ConsolidatedTemplateParameters != null && targetType.ConsolidatedTemplateParameters.Count > 0)
        {
          // need selfinstantiation
          targetType = targetType.GetGenericTemplateInstance(this.assemblyBeingRewritten, wrapperType.ConsolidatedTemplateParameters);
        }
      }
      Method targetMethod = GetMatchingMethod(targetType, templateMethod, wrapperMethod);
      if (targetMethod.IsGeneric) {
        if (typeParameters.Count > targetMethod.TemplateParameters.Count) {
          // omit the extra constrained type arg.
          TypeNodeList origArgs = new TypeNodeList();
          for (int i = 0; i < targetMethod.TemplateParameters.Count; i++) {
            origArgs.Add(typeParameters[i]);
          }
          targetMethod = targetMethod.GetTemplateInstance(wrapperType, origArgs);
        }
        else {
          targetMethod = targetMethod.GetTemplateInstance(wrapperType, typeParameters);
        }
      }
      MethodCall call;
      NodeType callType = virtcall ? NodeType.Callvirt : NodeType.Call;
      if (isProtected) {
        var mb = new MemberBinding(wrapperMethod.ThisParameter, targetMethod);
        var elist = new ExpressionList(wrapperMethod.Parameters.Count);
        for (int i = 0; i < wrapperMethod.Parameters.Count; i++) {
          elist.Add(wrapperMethod.Parameters[i]);
        }
        call = new MethodCall(mb, elist, callType);
      }
      else if (templateMethod.IsStatic) {
        var elist = new ExpressionList(wrapperMethod.Parameters.Count);
        for (int i = 0; i < wrapperMethod.Parameters.Count; i++) {
          elist.Add(wrapperMethod.Parameters[i]);
        }
        call = new MethodCall(new MemberBinding(null, targetMethod), elist, callType);
      }
      else {
        var mb = new MemberBinding(wrapperMethod.Parameters[0], targetMethod);
        var elist = new ExpressionList(wrapperMethod.Parameters.Count - 1);
        for (int i = 1; i < wrapperMethod.Parameters.Count; i++) {
          elist.Add(wrapperMethod.Parameters[i]);
        }
        call = new MethodCall(mb, elist, callType);
      }
      if (constraintTypeParam != null) {
        call.Constraint = asTypeConstraintTypeParam;
      }
      if (HelperMethods.IsVoidType(templateMethod.ReturnType)) {
        sl.Add(new ExpressionStatement(call,callingContext));
        sl.Add(new Return(callingContext));
      }
      else {
        sl.Add(new Return(call,callingContext));
      }
      wrapperMethod.Body = b;

      wrapperType.Members.Add(wrapperMethod);
      return wrapperMethod;
    }
Example #51
0
        public ParameterList GetParameters(string CommandName)
        {
            ParameterList pList = new ParameterList();
            CommandInteraction ci = new CommandInteraction();
            try
            {
                List<string> requierdInputs = ci.getRequiredInputs(CommandName);
                foreach (string i in requierdInputs)
                {
                    Parameter p = new Parameter();
                    p.Name = i;
                    pList.Add(p);
                }
                TeamInfo teamInfo=TeamInfoAccess.getTeam(0);

                using (PSDataAccess psDataAccess = new PSDataAccess(teamInfo.domain, teamInfo.product))
                {
                    string psFieldNames = string.Empty;
                    foreach (Parameter p in pList)
                    {
                        p.Name = p.Name.Replace("__", " ");
                        if (psFieldNames == string.Empty)
                        {
                            psFieldNames = p.Name;//"__" is for the white space issue
                        }
                        else
                        {
                            psFieldNames = string.Format("{0};{1}", psFieldNames, p.Name);
                        }
                    }
                    List<PSFieldDefinition> fieldDefinitions = psDataAccess.LoadingPSFields(psFieldNames);
                    foreach (Parameter p in pList)
                    {
                        if (p.Name.Equals("AssignedTo"))
                        {
                            p.Values.AddRange(new string[] { "t-limliu", "yuanzhua", "zachary", "zichsun" });
                        }
                        foreach (PSFieldDefinition definition in fieldDefinitions)
                        {
                            if (p.Name.Equals(definition.Name))
                            {
                                List<object> values = definition.GetAllowedValues();
                                foreach (object v in values)
                                {
                                    p.Values.Add(v.ToString());
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new WebFaultException<string>(e.ToString(),HttpStatusCode.InternalServerError);
            }
            return pList;
        }
Example #52
0
 private void ParseEvent(TypeNode parentType, AttributeList attributes, TokenList modifierTokens,
   SourceContextList modifierContexts, object sctx, TokenSet followers){
   Debug.Assert(this.currentToken == Token.Event);
   this.GetNextToken();
   Event e = new Event(parentType, attributes, EventFlags.None, null, null, null, null, null);
   e.DeclaringType = parentType;
   e.Documentation = this.LastDocComment;
   TypeNode t = this.ParseTypeExpression(Identifier.Empty, followers|Parser.IdentifierOrNonReservedKeyword);
   //REVIEW: allow events with anonymous delegate type?
   e.HandlerType = e.HandlerTypeExpression = t;
   TypeExpression interfaceType = null;
   Identifier id = this.scanner.GetIdentifier();
   this.SkipIdentifierOrNonReservedKeyword();
   TypeNodeList templateArguments = null;
   int endPos = 0, arity = 0;
   while (this.currentToken == Token.Dot || this.currentToken == Token.LessThan) {
     if (interfaceType == null && this.ExplicitInterfaceImplementationIsAllowable(parentType, id)) {
       for (int i = 0, n = modifierContexts == null ? 0 : modifierContexts.Length; i < n; i++){
         this.HandleError(modifierContexts[i], Error.InvalidModifier, modifierContexts[i].SourceText);
         modifierTokens = new TokenList(0);
       }
     }
     TypeExpression intfExpr = interfaceType;
     if (intfExpr == null) {
       intfExpr = new TypeExpression(id, id.SourceContext);
     } else if( templateArguments == null) {
       SourceContext ctx = intfExpr.Expression.SourceContext;
       ctx.EndPos = id.SourceContext.EndPos;
       intfExpr.Expression = new QualifiedIdentifier(intfExpr.Expression, id, ctx);
     }
     if (templateArguments != null) {
       intfExpr.TemplateArguments = templateArguments;
       intfExpr.SourceContext.EndPos = endPos;
     }
     if (this.currentToken == Token.LessThan) {
       templateArguments = this.ParseTypeArguments(true, false, followers | Token.Dot | Token.LeftParenthesis | Token.LeftBrace, out endPos, out arity);
     } else {  //  Dot
       templateArguments = null;
       this.GetNextToken();
       id = this.scanner.GetIdentifier();
       this.SkipIdentifierOrNonReservedKeyword();
       if (intfExpr == null) id.SourceContext.Document = null;
     }
     interfaceType = intfExpr;
   }
   e.Name = id;
   MethodFlags mflags = this.GetMethodFlags(modifierTokens, modifierContexts, parentType, e);
   if ((mflags & MethodFlags.Static) != 0 && parentType is Interface){
     this.HandleError(id.SourceContext, Error.InvalidModifier, "static");
     mflags &= ~MethodFlags.Static;
     mflags |= MethodFlags.Abstract;
   }
   e.HandlerFlags = mflags|MethodFlags.SpecialName;
   bool hasAccessors = this.currentToken == Token.LeftBrace || interfaceType != null;
   if (hasAccessors){
     if (interfaceType != null){
       e.ImplementedTypeExpressions = e.ImplementedTypes = new TypeNodeList(interfaceType);
       if (this.currentToken != Token.LeftBrace){
         this.HandleError(Error.ExplicitEventFieldImpl);
         hasAccessors = false;
         goto nextDeclarator;
       }
     }
     this.Skip(Token.LeftBrace);
     TokenSet followersOrRightBrace = followers|Token.RightBrace;
     bool alreadyGivenAddOrRemoveExpectedError = false;
     bool alreadyComplainedAboutAccessors = false;
     for(;;){
       SourceContext sc = this.scanner.CurrentSourceContext;
       AttributeList accessorAttrs = this.ParseAttributes(null, followers|Parser.AddOrRemoveOrModifier|Token.LeftBrace);
       switch (this.currentToken){
         case Token.Add:
           if (parentType is Interface && !alreadyComplainedAboutAccessors){
             this.HandleError(Error.EventPropertyInInterface, parentType.FullName+"."+id);
             alreadyComplainedAboutAccessors = true;
           }else if (e.HandlerAdder != null)
             this.HandleError(Error.DuplicateAccessor);
           SourceContext scntx = this.scanner.CurrentSourceContext;
           this.GetNextToken();
           ParameterList parList = new ParameterList();
           parList.Add(new Parameter(null, ParameterFlags.None, StandardIds.Value, t, null, null));
           Method m = new Method(parentType, accessorAttrs, new Identifier("add_"+id.ToString()), parList, this.TypeExpressionFor(Token.Void), null);
           m.HidesBaseClassMember = e.HidesBaseClassMember;
           m.OverridesBaseClassMember = e.OverridesBaseClassMember;
           m.Name.SourceContext = scntx;
           if ((mflags & MethodFlags.Static) == 0)
             m.CallingConvention = CallingConventionFlags.HasThis;
           m.Flags = mflags|MethodFlags.HideBySig|MethodFlags.SpecialName;
           if (interfaceType != null){
             m.Flags = MethodFlags.Private|MethodFlags.HideBySig|MethodFlags.NewSlot|MethodFlags.Final|MethodFlags.Virtual|MethodFlags.SpecialName;
             m.ImplementedTypeExpressions = m.ImplementedTypes = new TypeNodeList(interfaceType);
           }
           if (this.currentToken != Token.LeftBrace){
             this.SkipTo(followersOrRightBrace|Token.Remove, Error.AddRemoveMustHaveBody);
             alreadyGivenAddOrRemoveExpectedError = true;
           }else
             m.Body = this.ParseBody(m, sc, followersOrRightBrace|Token.Remove);
           if (!(parentType is Interface)){
             e.HandlerAdder = m;
             m.DeclaringMember = e;
             parentType.Members.Add(m);
           }
           continue;
         case Token.Remove:
           if (parentType is Interface && !alreadyComplainedAboutAccessors){
             this.HandleError(Error.EventPropertyInInterface, parentType.FullName+"."+id);
             alreadyComplainedAboutAccessors = true;
           }else if (e.HandlerRemover != null)
             this.HandleError(Error.DuplicateAccessor);
           scntx = this.scanner.CurrentSourceContext;
           this.GetNextToken();
           parList = new ParameterList();
           parList.Add(new Parameter(null, ParameterFlags.None, StandardIds.Value, t, null, null));
           m = new Method(parentType, accessorAttrs, new Identifier("remove_"+id.ToString()), parList, this.TypeExpressionFor(Token.Void), null);
           m.HidesBaseClassMember = e.HidesBaseClassMember;
           m.OverridesBaseClassMember = e.OverridesBaseClassMember;
           m.Name.SourceContext = scntx;
           if ((mflags & MethodFlags.Static) == 0)
             m.CallingConvention = CallingConventionFlags.HasThis;
           m.Flags = mflags|MethodFlags.HideBySig|MethodFlags.SpecialName;
           if (interfaceType != null){
             m.Flags = MethodFlags.Private|MethodFlags.HideBySig|MethodFlags.NewSlot|MethodFlags.Final|MethodFlags.Virtual|MethodFlags.SpecialName;
             m.ImplementedTypeExpressions = m.ImplementedTypes = new TypeNodeList(interfaceType);
           }
           if (this.currentToken != Token.LeftBrace){
             this.SkipTo(followersOrRightBrace|Token.Add, Error.AddRemoveMustHaveBody);
             alreadyGivenAddOrRemoveExpectedError = true;
           }else
             m.Body = this.ParseBody(m, sc, followersOrRightBrace|Token.Add);
           if (!(parentType is Interface)){
             e.HandlerRemover = m;
             m.DeclaringMember = e;
             parentType.Members.Add(m);
           }
           continue;
         case Token.New:
         case Token.Public:
         case Token.Protected:
         case Token.Internal:
         case Token.Private:
         case Token.Abstract:
         case Token.Sealed:
         case Token.Static:
         case Token.Readonly:
         case Token.Volatile:
         case Token.Virtual:
         case Token.Override:
         case Token.Extern:
         case Token.Unsafe:
           this.HandleError(Error.NoModifiersOnAccessor);
           this.GetNextToken();
           break;
         default:
           if ((e.HandlerAdder == null || e.HandlerRemover == null) && this.sink != null && this.currentToken == Token.Identifier && this.scanner.endPos == this.scanner.maxPos){
             e.SourceContext.EndPos = this.scanner.startPos;
             KeywordCompletionList keywords;
             if (e.HandlerAdder != null)
               keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("remove"));
             else if (e.HandlerRemover != null)
               keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("add"));
             else
               keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("add"), new KeywordCompletion("remove"));
             parentType.Members.Add(keywords);
             this.GetNextToken();
           }
           if (!alreadyGivenAddOrRemoveExpectedError && !alreadyComplainedAboutAccessors && (e.HandlerAdder == null || e.HandlerRemover == null)) {
             if (this.currentToken == Token.RightBrace)
               this.HandleError(id.SourceContext, Error.EventNeedsBothAccessors, parentType.FullName+"."+id.Name);
             else
               this.HandleError(Error.AddOrRemoveExpected);
             alreadyGivenAddOrRemoveExpectedError = true;
             if (!(Parser.EndOfFile|Token.LeftBrace|Token.RightBrace)[this.currentToken])
               this.GetNextToken();
             this.SkipTo(followersOrRightBrace|Token.LeftBrace, Error.None);
             if (this.currentToken == Token.LeftBrace){
               this.ParseBlock(followersOrRightBrace|Token.Add|Token.Remove);
               continue;
             }
           }
           break;
       }
       break;
     }
     this.Skip(Token.RightBrace); //TODO: brace matching
   }
   nextDeclarator:
     e.Name = id;
   e.SourceContext = (SourceContext)sctx;
   e.SourceContext.EndPos = this.scanner.endPos;
   parentType.Members.Add(e);
   if (!hasAccessors){
     switch(this.currentToken){
       case Token.Assign:
         this.GetNextToken();
         e.InitialHandler = this.ParseExpression(followers|Token.Semicolon);
         if (parentType is Interface && e.InitialHandler != null){
           this.HandleError(e.InitialHandler.SourceContext, Error.InterfaceEventInitializer, parentType.FullName+"."+id);
           e.InitialHandler = null;
         }
         if (this.currentToken == Token.Comma)
           goto case Token.Comma;
         else
           goto default;
       case Token.Comma:
         this.GetNextToken();
         id = this.scanner.GetIdentifier();
         this.SkipIdentifierOrNonReservedKeyword(); //REVIEW: allow interface name?
         e = new Event(parentType, attributes, (EventFlags)0, null, null, null, null, null);
         e.HandlerFlags = mflags;
         e.HandlerType = e.HandlerTypeExpression = t;
         goto nextDeclarator;
       default:
         this.Skip(Token.Semicolon);
         break;
     }
   }
 }
Example #53
0
 private ParameterList Configuration()
 {
     ParameterList list = new ParameterList();
     list.Add(new Parameter() { Flag = PathToKeyFlag, Key = PathToKeyParameter });
     list.Add(new Parameter() { Flag = MainBranchFlag, Key = MainBranchParameter });
     list.Add(new Parameter() { Flag = HelpFlag, Key = HelpParameter });
     list.Add(new Parameter() { Flag = UserFlag, Key = UserParameter });
     list.Add(new Parameter() { Flag = AccessControlFlag, Key = AccessControlParameter });
     list.Add(new Parameter() { Flag = InheritanceFlagsFlag, Key = InheritanceFlagsParameter, Value = "0" });
     list.Add(new Parameter() { Flag = PropagationFlagsFlag, Key = PropagationFlagsParameter, Value = "0" });
     list.Add(new Parameter() { Flag = PermissionFlag, Key = PermissionParameter });
     list.Add(new Parameter() { Flag = PermissionToExcludeFlag, Key = PermissionToExcludeParameter });
     return list;
 }
Example #54
0
        private ParameterList ParseParameters(Stream stream)
        {
            var parameterList = new ParameterList();

            //( parameterlist )
            var open = stream.Next();

            while (stream.Peek() != null)
            {
                var token = stream.Peek();
                if (token == null)
                {
                    break;
                }

                switch (token.Type)
                {
                    case TokenType.Identifier:
                    case TokenType.QuotedStringLiteral:
                    case TokenType.StringLiteralPipe:
                        parameterList.Add(ParseParameter(stream));
                        break;
                    case TokenType.Comma:
                        //another parameter - consume this
                        stream.NextNoReturn();
                        break;
                    case TokenType.CloseParenthesis:
                        //consume close parenthesis
                        stream.NextNoReturn();
                        goto doneWithParameter;
                    default:
                        //read until )
                        Errors.Add(new UnexpectedToken(token));
                        return parameterList;
                    //throw new ParserException(token);
                }
            }

            doneWithParameter:
            return parameterList;
        }
        //=====================================================================

        /// <summary>
        /// Add extension method information to a type
        /// </summary>
        /// <param name="writer">The reflection data XML writer</param>
        /// <param name="type">the current type being extended</param>
        /// <param name="extensionMethodTemplate">A reference to the extension method. For generic methods,
        /// this is a reference to the non-specialized method, e.g. System.Linq.Enumerable.Select``2.</param>
        /// <param name="specialization">When the current type implements or inherits from a specialization
        /// of a generic type, this parameter has a TypeNode for the type used as a specialization of the
        /// generic type's first template parameter.</param>
        private void AddExtensionMethod(XmlWriter writer, TypeNode type, Method extensionMethodTemplate,
          TypeNode specialization)
        {
            // !EFW - Bug fix
            // Don't add extension method support to enumerations and static classes
            if(type != null && (type.NodeType == NodeType.EnumNode || (type.NodeType == NodeType.Class &&
              type.IsAbstract && type.IsSealed)))
                return;

            // If this is a specialization of a generic method, construct a Method object that describes
            // the specialization.
            Method extensionMethodTemplate2 = extensionMethodTemplate;

            if(extensionMethodTemplate2.IsGeneric && specialization != null)
            {
                // The specialization type is the first of the method's template arguments
                TypeNodeList templateArgs = new TypeNodeList();
                templateArgs.Add(specialization);

                // Add any additional template arguments
                for(int i = 1; i < extensionMethodTemplate.TemplateParameters.Count; i++)
                    templateArgs.Add(extensionMethodTemplate.TemplateParameters[i]);

                extensionMethodTemplate2 = extensionMethodTemplate.GetTemplateInstance(type, templateArgs);
            }

            ParameterList extensionMethodTemplateParameters = extensionMethodTemplate2.Parameters;

            ParameterList extensionMethodParameters = new ParameterList();

            for(int i = 1; i < extensionMethodTemplateParameters.Count; i++)
            {
                Parameter extensionMethodParameter = extensionMethodTemplateParameters[i];
                extensionMethodParameters.Add(extensionMethodParameter);
            }

            Method extensionMethod = new Method(extensionMethodTemplate.DeclaringType, new AttributeList(),
                extensionMethodTemplate.Name, extensionMethodParameters, extensionMethodTemplate2.ReturnType,
                null);
            extensionMethod.Flags = extensionMethodTemplate.Flags & ~MethodFlags.Static;

            // For generic methods, set the template arguments and parameters so the template data is included in
            // the ID and the method data.
            if(extensionMethodTemplate2.IsGeneric)
            {
                extensionMethod.IsGeneric = true;

                if(specialization != null)
                {
                    // Set the template arguments for the specialized generic method
                    extensionMethod.TemplateArguments = extensionMethodTemplate2.TemplateArguments;
                }
                else
                {
                    // Set the generic template parameters for the non-specialized generic method
                    extensionMethod.TemplateParameters = extensionMethodTemplate2.TemplateParameters;
                }
            }

            // Get the ID
            string extensionMethodTemplateId = mrw.ApiNamer.GetMemberName(extensionMethodTemplate);

            // Write the element node
            writer.WriteStartElement("element");
            writer.WriteAttributeString("api", extensionMethodTemplateId);
            writer.WriteAttributeString("source", "extension");

            isExtensionMethod = true;
            mrw.WriteMember(extensionMethod);
            isExtensionMethod = false;

            writer.WriteEndElement();
        }
Example #56
0
 public void SetUpClosureClass(Method method){
   Class closureClass = method.Scope.ClosureClass;
   if (this.CodeMightBeVerified) {
     // Closure classes contain user-written code, but it doesn't get verified.
     closureClass.Attributes.Add(
       new AttributeNode(new MemberBinding(null, SystemTypes.VerifyAttribute.GetConstructor(SystemTypes.Boolean)),
             new ExpressionList(Literal.False), AttributeTargets.Class)
       );
   }
   this.currentType.Members.Add(closureClass);
   MemberList members = closureClass.Members;
   ParameterList parameters = new ParameterList();
   StatementList statements = new StatementList();
   TypeNode thisType = method.Scope.ThisTypeInstance;
   This thisParameter = new This(closureClass);
   if (thisType != null && !method.IsStatic) {
     if (!thisType.IsValueType)
       thisType = OptionalModifier.For(SystemTypes.NonNullType, thisType);
     Field f = (Field)closureClass.Members[0];
     f.Type = thisType;
     Parameter p = new Parameter(f.Name, f.Type);
     // The captured class object parameters to closure class constructors are delayed
     p.Attributes.Add(new AttributeNode(new MemberBinding(null, ExtendedRuntimeTypes.DelayedAttribute.GetConstructor()), null, AttributeTargets.Parameter));
     method.Scope.ThisField = f;
     parameters.Add(p);
     Expression pval = p;
     if (p.Type.IsValueType) pval = new AddressDereference(p, p.Type);
     statements.Add(new AssignmentStatement(new MemberBinding(thisParameter, f), p));
   }
   MemberList scopeMembers = method.Scope.Members;
   for (int i = 0, n = scopeMembers.Count; i < n; i++){
     Member m = scopeMembers[i];
     Field f = m as Field;
     if (f == null || f.Type is Reference) continue;
     f.Type = method.Scope.FixTypeReference(f.Type);
     members.Add(f);
     if (!(f is ParameterField)) continue;
     Parameter p = new Parameter(f.Name, f.Type);
     parameters.Add(p);
     statements.Add(new AssignmentStatement(new MemberBinding(thisParameter, f), p));
   }
   InstanceInitializer cons = new InstanceInitializer();
   cons.ThisParameter = thisParameter;
   cons.DeclaringType = closureClass;
   cons.Flags |= MethodFlags.CompilerControlled;
   cons.Parameters = parameters;
   cons.Scope = new MethodScope(closureClass, new UsedNamespaceList(0));
   cons.Body = new Block(statements);
   MethodCall mcall = new MethodCall(new MemberBinding(thisParameter, CoreSystemTypes.Object.GetConstructor()),
     new ExpressionList(0), NodeType.Call, CoreSystemTypes.Void);
   statements.Add(new ExpressionStatement(mcall));
   statements.Add(new Return());
   closureClass.Members.Add(cons);
 }
Example #57
0
        public virtual void ProvideMembers()
        {
            if(this.membersAlreadyProvided)
                return;

            this.membersAlreadyProvided = true;
            this.memberCount = 0;
            MemberList members = this.members = new MemberList();

            //ctor
            ParameterList parameters = new ParameterList();
            parameters.Add(new Parameter(null, ParameterFlags.None, StandardIds.Object, CoreSystemTypes.Object, null, null));
            parameters.Add(new Parameter(null, ParameterFlags.None, StandardIds.Method, CoreSystemTypes.IntPtr, null, null));
            InstanceInitializer ctor = new InstanceInitializer(this, null, parameters, null);
            ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig;
            ctor.CallingConvention = CallingConventionFlags.HasThis;
            ctor.ImplFlags = MethodImplFlags.Runtime;
            members.Add(ctor);

            //Invoke
            Method invoke = new Method(this, null, StandardIds.Invoke, this.Parameters, this.ReturnType, null);
            invoke.Flags = MethodFlags.Public | MethodFlags.HideBySig | MethodFlags.Virtual;
            invoke.CallingConvention = CallingConventionFlags.HasThis;
            invoke.ImplFlags = MethodImplFlags.Runtime;
            members.Add(invoke);

            //BeginInvoke
            ParameterList dparams = this.parameters;
            int n = dparams == null ? 0 : dparams.Count;
            parameters = new ParameterList();

            for(int i = 0; i < n; i++)
            {
                //^ assert dparams != null;
                Parameter p = dparams[i];
                if(p == null)
                    continue;
                parameters.Add((Parameter)p.Clone());
            }

            parameters.Add(new Parameter(null, ParameterFlags.None, StandardIds.callback, SystemTypes.AsyncCallback, null, null));
            parameters.Add(new Parameter(null, ParameterFlags.None, StandardIds.Object, CoreSystemTypes.Object, null, null));

            Method beginInvoke = new Method(this, null, StandardIds.BeginInvoke, parameters, SystemTypes.IASyncResult, null);
            beginInvoke.Flags = MethodFlags.Public | MethodFlags.HideBySig | MethodFlags.NewSlot | MethodFlags.Virtual;
            beginInvoke.CallingConvention = CallingConventionFlags.HasThis;
            beginInvoke.ImplFlags = MethodImplFlags.Runtime;
            members.Add(beginInvoke);

            //EndInvoke
            parameters = new ParameterList();

            for(int i = 0; i < n; i++)
            {
                Parameter p = dparams[i];

                if(p == null || p.Type == null || !(p.Type is Reference))
                    continue;

                parameters.Add((Parameter)p.Clone());
            }

            parameters.Add(new Parameter(null, ParameterFlags.None, StandardIds.result, SystemTypes.IASyncResult, null, null));
            Method endInvoke = new Method(this, null, StandardIds.EndInvoke, parameters, this.ReturnType, null);
            endInvoke.Flags = MethodFlags.Public | MethodFlags.HideBySig | MethodFlags.NewSlot | MethodFlags.Virtual;
            endInvoke.CallingConvention = CallingConventionFlags.HasThis;
            endInvoke.ImplFlags = MethodImplFlags.Runtime;
            members.Add(endInvoke);
            if(!this.IsGeneric)
            {
                TypeNodeList templPars = this.TemplateParameters;
                for(int i = 0, m = templPars == null ? 0 : templPars.Count; i < m; i++)
                {
                    //^ assert templPars != null;
                    TypeNode tpar = templPars[i];
                    if(tpar == null)
                        continue;
                    members.Add(tpar);
                }
            }
        }
Example #58
0
        internal Member GetMemberFromRef(int i, out TypeNodeList varArgTypes, int numGenericArgs)
        {
            MemberRefRow mref = this.tables.MemberRefTable[i - 1];
            if (mref.Member != null)
            {
                varArgTypes = mref.VarargTypes;
                return mref.Member;
            }
            varArgTypes = null;
            Member result = null;
            int codedIndex = mref.Class;
            if (codedIndex == 0) return null;
            TypeNode parent = null;
            TypeNodeList savedCurrentTypeParameters = this.currentTypeParameters;
            switch (codedIndex & 0x7)
            {
                case 0x00: parent = this.GetTypeFromDef(codedIndex >> 3); break;
                case 0x01: parent = this.GetTypeFromRef(codedIndex >> 3); break;
                case 0x02: parent = this.GetTypeGlobalMemberContainerTypeFromModule(codedIndex >> 3); break;
                case 0x03: result = this.GetMethodFromDef(codedIndex >> 3);
                    if ((((Method)result).CallingConvention & CallingConventionFlags.VarArg) != 0)
                    {
                        MemoryCursor sRdr = this.tables.GetBlobCursor(mref.Signature);
                        sRdr.ReadByte(); //hdr
                        int pCount = sRdr.ReadCompressedInt();
                        this.ParseTypeSignature(sRdr); //rType
                        bool genParameterEncountered = false;
                        this.ParseParameterTypes(out varArgTypes, sRdr, pCount, ref genParameterEncountered);
                    }
                    goto done;
                case 0x04: parent = this.GetTypeFromSpec(codedIndex >> 3); break;
                default: throw new InvalidMetadataException("");
            }
            if (parent != null && parent.IsGeneric)
            {
                if (parent.Template != null)
                    this.currentTypeParameters = parent.ConsolidatedTemplateArguments;
                else
                    this.currentTypeParameters = parent.ConsolidatedTemplateParameters;
            }
            Identifier memberName = this.tables.GetIdentifier(mref.Name);
            MemoryCursor sigReader = this.tables.GetBlobCursor(mref.Signature);
            byte header = sigReader.ReadByte();
            if (header == 0x6)
            {
                TypeNode fieldType = this.ParseTypeSignature(sigReader);
                TypeNode fType = TypeNode.StripModifiers(fieldType);
                TypeNode parnt = parent;
                while (parnt != null)
                {
                    MemberList members = parnt.GetMembersNamed(memberName);
                    for (int j = 0, n = members.Count; j < n; j++)
                    {
                        Field f = members[j] as Field;
                        if (f == null) continue;
                        if (TypeNode.StripModifiers(f.Type) == fType) { result = f; goto done; }
                    }
                    Class c = parnt as Class;
                    if (c != null) parnt = c.BaseClass; else break;
                }
                if (result == null)
                {
                    result = new Field(memberName);
                    result.DeclaringType = parent;
                    ((Field)result).Type = fieldType;
                    goto error;
                }
                goto done;
            }
            int typeParamCount = int.MinValue;
            CallingConventionFlags callingConvention = CallingConventionFlags.Default;
            if ((header & 0x20) != 0) callingConvention |= CallingConventionFlags.HasThis;
            if ((header & 0x40) != 0) callingConvention |= CallingConventionFlags.ExplicitThis;
            switch (header & 7)
            {
                case 1: callingConvention |= CallingConventionFlags.C; break;
                case 2: callingConvention |= CallingConventionFlags.StandardCall; break;
                case 3: callingConvention |= CallingConventionFlags.ThisCall; break;
                case 4: callingConvention |= CallingConventionFlags.FastCall; break;
                case 5: callingConvention |= CallingConventionFlags.VarArg; break;
            }
            if ((header & 0x10) != 0)
            {
                typeParamCount = sigReader.ReadCompressedInt();
                callingConvention |= CallingConventionFlags.Generic;
            }
            int paramCount = sigReader.ReadCompressedInt();
            TypeNodeList savedMethodTypeParameters = this.currentMethodTypeParameters;
            this.currentTypeParameters = parent.ConsolidatedTemplateArguments;
            TypeNode pnt = parent;
            if (numGenericArgs > 0)
            {
                while (pnt != null)
                {
                    MemberList members = pnt.GetMembersNamed(memberName);
                    for (int k = 0, n = members.Count; k < n; k++)
                    {
                        Method m = members[k] as Method;
                        if (m == null) continue;
                        if (m.TemplateParameters == null || m.TemplateParameters.Count != numGenericArgs) continue;
                        if (m.Parameters == null || m.Parameters.Count != paramCount) continue;
                        this.currentMethodTypeParameters = m.TemplateParameters;
                        this.currentTypeParameters = pnt.ConsolidatedTemplateArguments;
                        goto parseSignature;
                    }
                    Class c = pnt as Class;
                    if (c != null) pnt = c.BaseClass; else break;
                }
            }
        parseSignature:
            TypeNode returnType = this.ParseTypeSignature(sigReader);
            if (returnType == null) returnType = CoreSystemTypes.Object;
            bool genericParameterEncountered = returnType.IsGeneric;
            TypeNodeList paramTypes = this.ParseParameterTypes(out varArgTypes, sigReader, paramCount, ref genericParameterEncountered);
            this.currentMethodTypeParameters = savedMethodTypeParameters;
            this.currentTypeParameters = savedCurrentTypeParameters;
            pnt = parent;
            while (pnt != null)
            {
                MemberList members = pnt.GetMembersNamed(memberName);
                for (int k = 0, n = members.Count; k < n; k++)
                {
                    Method m = members[k] as Method;
                    if (m == null) continue;
                    if (m.ReturnType == null) continue;
                    TypeNode mrtype = TypeNode.StripModifiers(m.ReturnType);
                    //^ assert mrtype != null;
                    if (!mrtype.IsStructurallyEquivalentTo(TypeNode.StripModifiers(returnType))) continue;
                    if (!m.ParameterTypesMatchStructurally(paramTypes)) continue;
                    if (m.CallingConvention != callingConvention) continue;
                    if (typeParamCount != int.MinValue && (!m.IsGeneric || m.TemplateParameters == null || m.TemplateParameters.Count != typeParamCount))
                        continue;
                    result = m;
                    goto done;
                }
                if (memberName.UniqueIdKey == StandardIds.Ctor.UniqueIdKey)
                {
                    //Can't run up the base class chain for constructors.
                    members = pnt.GetConstructors();
                    if (members != null && members.Count == 1 && paramCount == 0)
                    {
                        //Only one constructor. The CLR metadata API's seem to think that this should match the empty signature
                        result = members[0];
                        goto done;
                    }
                    break;
                }
                Class c = pnt as Class;
                if (c != null) pnt = c.BaseClass; else break;
            }
            if (result == null)
            {
                ParameterList parameters = new ParameterList();

                for (int j = 0; j < paramCount; j++)
                {
                    Parameter p = new Parameter(Identifier.Empty, paramTypes[j]);
                    parameters.Add(p);
                }

                //TODO: let the caller indicate if it expects a constructor
                Method meth = new Method(parent, null, memberName, parameters, returnType, null);
                meth.CallingConvention = callingConvention;
                if ((callingConvention & CallingConventionFlags.HasThis) == 0) meth.Flags |= MethodFlags.Static;
                result = meth;
            }
        error:
            if (this.module != null)
            {
                HandleError(this.module, String.Format(CultureInfo.CurrentCulture,
                  ExceptionStrings.CouldNotResolveMemberReference, parent.FullName + "::" + memberName));
                if (parent != null) parent.Members.Add(result);
            }
        done:
            if (Reader.CanCacheMember(result))
            {
                this.tables.MemberRefTable[i - 1].Member = result;
                this.tables.MemberRefTable[i - 1].VarargTypes = varArgTypes;
            }
            this.currentTypeParameters = savedCurrentTypeParameters;
            return result;
        }
Example #59
0
 private void ParseProperty(TypeNode parentType, AttributeList attributes, TokenList modifierTokens,
   SourceContextList modifierContexts, object sctx, TypeNode type, TypeNode interfaceType, Identifier name, TokenSet followers){
   SourceContext ctx = (SourceContext)sctx;
   ctx.EndPos = this.scanner.endPos;
   bool isIndexer = this.currentToken == Token.This && name.UniqueIdKey == StandardIds.Item.UniqueIdKey;
   Debug.Assert(this.currentToken == Token.LeftBrace || isIndexer);
   this.GetNextToken();
   ParameterList paramList = null;
   if (isIndexer){
     if (interfaceType == null){
       AttributeNode defaultMember = new AttributeNode();
       defaultMember.Constructor = new Literal(TypeExpressionFor("System", "Reflection", "DefaultMemberAttribute"));
       defaultMember.Expressions = new ExpressionList(1);
       defaultMember.Expressions.Add(new Literal("Item"));
       if (parentType.Attributes == null) parentType.Attributes = new AttributeList(1);
       parentType.Attributes.Add(defaultMember);
     }
     paramList = this.ParseParameters(Token.RightBracket, followers|Token.LeftBrace);
     this.Skip(Token.LeftBrace);
   }
   Property p = new Property(parentType, attributes, PropertyFlags.None, name, null, null);
   parentType.Members.Add(p);
   p.SourceContext = ctx;
   p.Documentation = this.LastDocComment;
   p.Type = p.TypeExpression = type;
   MethodFlags mflags;
   if (interfaceType != null){
     p.ImplementedTypeExpressions = p.ImplementedTypes = new TypeNodeList(interfaceType);
     mflags = MethodFlags.Private|MethodFlags.HideBySig|MethodFlags.NewSlot|MethodFlags.Final|MethodFlags.Virtual|MethodFlags.SpecialName;
     for (int i = 0, n = modifierContexts == null ? 0 : modifierContexts.Length; i < n; i++) {
       if (modifierTokens[i] == Token.Extern)
         mflags |= MethodFlags.PInvokeImpl;
       else if (modifierTokens[i] == Token.Unsafe) {
         if (!this.allowUnsafeCode) {
           this.allowUnsafeCode = true;
           this.HandleError(modifierContexts[i], Error.IllegalUnsafe);
         }
         this.inUnsafeCode = true;
       } else
         this.HandleError(modifierContexts[i], Error.InvalidModifier, modifierContexts[i].SourceText);
     }
   }else
     mflags = this.GetMethodFlags(modifierTokens, modifierContexts, parentType, p)|MethodFlags.SpecialName;
   if ((mflags & MethodFlags.Static) != 0 && parentType is Interface){
     this.HandleError(name.SourceContext, Error.InvalidModifier, "static");
     mflags &= ~MethodFlags.Static;
     mflags |= MethodFlags.Abstract;
   }
   TokenSet followersOrRightBrace = followers|Token.RightBrace;
   bool accessorModifiersAlreadySpecified = false;
   MethodFlags accessorFlags = mflags;
   while (Parser.GetOrLeftBracketOrSetOrModifier[this.currentToken]){
     SourceContext sc = this.scanner.CurrentSourceContext;
     AttributeList accessorAttrs = this.ParseAttributes(null, followers|Token.Get|Token.Set|Token.LeftBrace);
     switch (this.currentToken){
       case Token.Get:{
         if (p.Getter != null)
           this.HandleError(Error.DuplicateAccessor);
         SourceContext scntx = this.scanner.CurrentSourceContext;
         this.GetNextToken();
         Method m = new Method(parentType, accessorAttrs, new Identifier("get_"+name.ToString()), paramList, type, null);
         m.SourceContext = sc;
         m.ReturnTypeExpression = type;
         m.Name.SourceContext = scntx;
         if ((accessorFlags & MethodFlags.Static) == 0)
           m.CallingConvention = CallingConventionFlags.HasThis;
         parentType.Members.Add(m);
         m.Flags = accessorFlags|MethodFlags.HideBySig;
         if (interfaceType != null)
           m.ImplementedTypeExpressions = m.ImplementedTypes = new TypeNodeList(interfaceType);
         bool swallowedSemicolonAlready = false;
         bool bodyAllowed = true;
         if (this.currentToken == Token.Semicolon){
           m.SourceContext.EndPos = this.scanner.endPos;
           this.GetNextToken();
           bodyAllowed = false;
           swallowedSemicolonAlready = true;
         }
         this.ParseMethodContract(m, followers|Token.LeftBrace|Token.Semicolon, ref swallowedSemicolonAlready);
         if (bodyAllowed)
           m.Body = this.ParseBody(m, sc, followersOrRightBrace|Token.Set, swallowedSemicolonAlready);
         else if (!swallowedSemicolonAlready)
           this.SkipSemiColon(followersOrRightBrace|Token.Set);
         p.Getter = m;
         m.DeclaringMember = p;
         accessorFlags = mflags;
         break;}
       case Token.Set:{
         if (p.Setter != null)
           this.HandleError(Error.DuplicateAccessor);
         SourceContext scntx = this.scanner.CurrentSourceContext;
         this.GetNextToken();
         ParameterList parList = new ParameterList();
         if (paramList != null)
           for (int i = 0, n = paramList.Count; i < n; i++) parList.Add((Parameter)paramList[i].Clone());
         parList.Add(new Parameter(null, ParameterFlags.None, Identifier.For("value"), type, null, null));
         Method m = new Method(parentType, accessorAttrs, new Identifier("set_"+name.ToString()), parList, this.TypeExpressionFor(Token.Void), null);
         m.SourceContext = sc;
         m.Name.SourceContext = scntx;
         if ((accessorFlags & MethodFlags.Static) == 0)
           m.CallingConvention = CallingConventionFlags.HasThis;
         parentType.Members.Add(m);
         m.Flags = accessorFlags|MethodFlags.HideBySig;
         if (interfaceType != null)
           m.ImplementedTypeExpressions = m.ImplementedTypes = new TypeNodeList(interfaceType);
         bool swallowedSemicolonAlready = false;
         bool bodyAllowed = true;
         if (this.currentToken == Token.Semicolon) {
           m.SourceContext.EndPos = this.scanner.endPos;
           this.GetNextToken();
           bodyAllowed = false;
           swallowedSemicolonAlready = true;
         }
         this.ParseMethodContract(m, followers|Token.LeftBrace|Token.Semicolon, ref swallowedSemicolonAlready);
         if (bodyAllowed)
           m.Body = this.ParseBody(m, sc, followersOrRightBrace|Token.Get, swallowedSemicolonAlready);
         else if (!swallowedSemicolonAlready)
           this.SkipSemiColon(followersOrRightBrace|Token.Get);
         p.Setter = m;
         m.DeclaringMember = p;
         accessorFlags = mflags;
         break;}
       case Token.Protected:
       case Token.Internal:
       case Token.Private:
         if (parentType is Interface || interfaceType != null || accessorModifiersAlreadySpecified)
           goto case Token.New;
         accessorFlags = this.ParseAccessorModifiers(mflags);
         accessorModifiersAlreadySpecified = true;
         break;
       case Token.Public:
       case Token.New:
       case Token.Abstract:
       case Token.Sealed:
       case Token.Static:
       case Token.Readonly:
       case Token.Volatile:
       case Token.Virtual:
       case Token.Override:
       case Token.Extern:
       case Token.Unsafe:
         this.HandleError(Error.NoModifiersOnAccessor);
         this.GetNextToken();
         break;
       default:
         this.SkipTo(followersOrRightBrace, Error.GetOrSetExpected);
         break;
     }
   }
   p.SourceContext.EndPos = this.scanner.endPos;
   Error e = Error.GetOrSetExpected;
   if (p.Getter == null && p.Setter == null) p.Parameters = paramList;
   if (p.Getter != null && p.Setter != null) e = Error.ExpectedRightBrace;
   if ((p.Getter == null || p.Setter == null) && this.sink != null && this.currentToken == Token.Identifier){
     p.SourceContext.EndPos = this.scanner.startPos-1;
     KeywordCompletionList keywords;
     if (p.Getter != null)
       keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("set"));
     else if (p.Setter != null)
       keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("get"));
     else
       keywords = new KeywordCompletionList(this.scanner.GetIdentifier(), new KeywordCompletion("get"), new KeywordCompletion("set"));
     parentType.Members.Add(keywords);
     this.GetNextToken();
     this.SkipTo(followers);
     return;
   }
   this.ParseBracket(ctx, Token.RightBrace, followers, e);
 }
Example #60
0
        private ParameterList ParseParameters(Stream stream)
        {
            var parameterList = new ParameterList(_host);

            //( parameterlist )
            var open = stream.Next();

            while (stream.Peek() != null)
            {
                var token = stream.Peek();
                if (token == null)
                {
                    break;
                }

                switch (token.Type)
                {
                    case TokenType.Identifier:
                    case TokenType.QuotedStringLiteral:
                    case TokenType.StringLiteralPipe:
                    case TokenType.MultiLineStringLiteral:
                        parameterList.Add(ParseParameter(stream));
                        break;
                    case TokenType.CloseParenthesis:
                        //consume close parenthesis
                        stream.NextNoReturn();
                        goto doneWithParameter;
                    default:
                        throw new ParserException(token);
                }
            }

            doneWithParameter:
            return parameterList;
        }