Esempio n. 1
0
        /**
         * @brief Calculate the volatility for an option.
         * Request the calculation of the implied volatility based on hypothetical option and its underlying prices. The calculation will be return in EWrapper's tickOptionComputation callback.
         * @param reqId unique identifier of the request.
         * @param contract the option's contract for which the volatility wants to be calculated.
         * @param optionPrice hypothetical option price.
         * @param underPrice hypothetical option's underlying price.
         * @sa EWrapper::tickOptionComputation, cancelCalculateImpliedVolatility, Contract
         */
        public void calculateImpliedVolatility(int reqId, Contract contract, double optionPrice, double underPrice)
        {
            if (!CheckConnection())
                return;
            if(!CheckServerVersion(MinServerVer.REQ_CALC_IMPLIED_VOLAT, " It does not support calculate implied volatility."))
                return;
            if (!Util.StringIsEmpty(contract.TradingClass) && !CheckServerVersion(MinServerVer.TRADING_CLASS, ""))
                return;
            const int version = 2;
            List<byte> paramsList = new List<byte>();
            paramsList.AddParameter(OutgoingMessages.ReqCalcImpliedVolat);
            paramsList.AddParameter(version);
            paramsList.AddParameter(reqId);
            paramsList.AddParameter(contract.ConId);
            paramsList.AddParameter(contract.Symbol);
            paramsList.AddParameter(contract.SecType);
            paramsList.AddParameter(contract.Expiry);
            paramsList.AddParameter(contract.Strike);
            paramsList.AddParameter(contract.Right);
            paramsList.AddParameter(contract.Multiplier);
            paramsList.AddParameter(contract.Exchange);
            paramsList.AddParameter(contract.PrimaryExch);
            paramsList.AddParameter(contract.Currency);
            paramsList.AddParameter(contract.LocalSymbol);
            if(serverVersion >= MinServerVer.TRADING_CLASS)
                paramsList.AddParameter(contract.TradingClass);
            paramsList.AddParameter(optionPrice);
            paramsList.AddParameter(underPrice);

            Send(reqId, paramsList, EClientErrors.FAIL_SEND_REQCALCIMPLIEDVOLAT);
        }
Esempio n. 2
0
        public ActionResult ConView(String Contract_ID)
        {
            if (Session["Login"] != null)
            {
                LoginSession loginsession = (LoginSession)Session["Login"];
                ViewBag.CompanyLogo = loginsession.CompanyLogo;
                ViewBag.Layout1 = BAL.Common.LayoutType(loginsession.UserType);
                String actionName = this.ControllerContext.RouteData.Values["action"].ToString();
                String controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
                ViewBag.Menu = BAL.Common.GetActiveMenu(controllerName, actionName, BAL.Common.LayoutType(loginsession.UserType));
                ViewBag.RoleName = loginsession.RoleName;
                if (Contract_ID != null)
                {
                    String Dec_Contract_ID = BAL.Security.URLDecrypt(Contract_ID);
                    Contract contract = new Contract();
                    if ((Dec_Contract_ID != "0") && (Dec_Contract_ID != null))
                    {
                        contract = BAL.ContractModel.ViewContract(Dec_Contract_ID);
                    }
                    return View(contract);
                }
                else
                { return RedirectToAction("Index", "Contract"); }

            }
            else
            { return RedirectToAction("Index", "Home"); }
        }
Esempio n. 3
0
 public ActionResult CreateContract(Contract contract)
 {
     contract.Id = Guid.NewGuid();
     Context.Contracts.Add(contract);
     Context.SaveChanges();
     return View();
 }
 protected void OnParameterChange(Contract c, ContractParameter p)
 {
     if (c == Root)
     {
         CheckVessel(FlightGlobals.ActiveVessel);
     }
 }
 /// <summary>
 /// Full Constructor
 /// </summary>
 /// <param name="requestId">The request Id for the Execution Details.</param>
 /// <param name="orderId">The order Id that was specified previously in the call to placeOrder().</param>
 /// <param name="contract">This structure contains a full description of the contract that was executed.</param>
 /// <param name="execution">This structure contains addition order execution details.</param>
 public ExecDetailsEventArgs(int requestId, int orderId, Contract contract, Execution execution)
 {
     this.requestId = requestId;
     this.orderId = orderId;
     this.execution = execution;
     this.contract = contract;
 }
        /// <summary>
        ///     Adds an order for the given contract and market side with the given properties
        /// </summary>
        /// <returns>The added order</returns>
        public IOrder AddOrder(long orderID,
                               Contract contract,
                               OrderType orderType,
                               MarketSide marketSide,
                               decimal price,
                               decimal quantity,
                               string clOrdID,
                               TradingAccount account)
        {
            var order = new Order(orderID,
                                  orderType,
                                  contract,
                                  marketSide,
                                  price,
                                  quantity,
                                  clOrdID,
                                  account);

            var stack = _market.GetOrCreate(
                contract,
                () =>
                    {
                        var os = OrderStackFactory.CreateStandardSortedStack(_orderMatcher);
                        os.OrdersMatched += OnOrdersMatched;
                        return os;
                    });
            stack.AddOrder(order);
            return order;
        }
Esempio n. 7
0
        public static List<Contract> GetData(Options salesforceOptions)
        {
            var discoContractsToReturn = new List<Contract>();

            var salesforceData = Salesforce.Data.GetData(salesforceOptions);
            foreach (var salesforceContract in salesforceData.Contracts)
            {
                var discoContract = new Contract
                {
                    Type = salesforceContract.Type__c,
                    TransactionalPricePerGB = salesforceContract.Price_Per_GB__c ?? 0,
                    BillingAccount = CreateDiscoAccountFromAccountId(salesforceData,
                        salesforceContract.BillingAccount__c),
                    UserAccount = CreateDiscoAccountFromAccountId(salesforceData,
                        salesforceContract.AccountId)
                };

                if (salesforceContract.Matters__r != null)
                {
                    discoContract.Matters.AddRange(
                        salesforceContract.Matters__r.Records.Select(
                            salesforceMatter => CreateDiscoMatterFromMatterId(salesforceData, salesforceMatter.Id)));
                }

                discoContractsToReturn.Add(discoContract);
            }

            return discoContractsToReturn;
        }
 public ExecutionMessage(int reqId, Contract contract, Execution execution)
 {
     Type = MessageType.ExecutionData;
     ReqId = reqId;
     Contract = contract;
     Execution = execution;
 }
 protected void OnContractAccepted(Contract c)
 {
     if (c == Root)
     {
         launchID = HighLogic.CurrentGame.launchID;
     }
 }
Esempio n. 10
0
 public ContractDetailsDialog(Contract contract)
 {
     InitializeComponent();
     textBox1.Text = Wallet.ToAddress(contract.ScriptHash);
     textBox2.Text = contract.ScriptHash.ToString();
     textBox3.Text = contract.RedeemScript.ToHexString();
 }
Esempio n. 11
0
        public async Task Creer_un_contrat()
        {
            Creer_un_client();
            var repo = IoC.Resolve<IAsyncRepositoryWithLogicalDeletion<Client>>();
            var result = await repo.FindBy(x => x.Id == 1);
            if (!result.Any())
            {
                Assert.Fail("Impossible de poursuire le test : client introuvalble");
                return;
            }

            var client = result.FirstOrDefault();
            client.Name = "sexodrome4";
            var contrat = new Contract();

            contrat.Comment = "super commentaire";
            contrat.EffectiveOn = DateTime.Now.Date.AddMonths(1);
            contrat.EffectiveUntil = DateTime.Now.Date.AddYears(5);
            contrat.Type = new ContractType { Label = "F*****g Contract!" };
            if (contrat.Documents == null) contrat.Documents = new Collection<Document>();
            contrat.Documents.Add(new Document { Name = "le putain de contrat man" });

            // TODO : revoir les notions de contractants et de co-contractants.

            if (client.Contracts == null) client.Contracts = new Collection<Contract>();
            client.Contracts.Add(contrat);
           
            await repo.Save();


        }
Esempio n. 12
0
        private String addUser()
        {
            try
            {
                Contract contract = new Contract();
                String cxnString = "Driver={SQL Server};Server=HC-sql7;Database=REVINT;Trusted_Connection=yes;";
                using (OdbcConnection dbConnection = new OdbcConnection(cxnString))
                {
                    //open OdbcConnection object
                    dbConnection.Open();

                    OdbcCommand cmd = new OdbcCommand();

                    cmd.CommandText = "{CALL [REVINT]." + contract.getSchema() + ".[OCP_addUser]( ?, ?, ?, ? )}";
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Connection = dbConnection;

                    cmd.Parameters.Add("@hawkId", OdbcType.NVarChar, 400).Value = txtHealthcareID.Text;
                    cmd.Parameters.Add("@administrator", OdbcType.Bit).Value = chkAdmin.IsChecked;
                    cmd.Parameters.Add("@name", OdbcType.NVarChar, 400).Value = txtName.Text;
                    cmd.Parameters.Add("@numRecords", OdbcType.Int);
                    cmd.Parameters["@numRecords"].Direction = System.Data.ParameterDirection.ReturnValue;

                    cmd.ExecuteNonQuery();

                    dbConnection.Close();

                    return cmd.Parameters["@numRecords"].Value.ToString();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Full Constructor
 /// </summary>
 /// <param name="orderId">The order Id assigned by TWS. Used to cancel or update the order.</param>
 /// <param name="contract">Describes the contract for the open order.</param>
 /// <param name="order">Gives the details of the open order.</param>
 /// <param name="orderState">The openOrder() callback with the new OrderState() object will now be invoked each time TWS receives commission information for a trade.</param>
 public OpenOrderEventArgs(int orderId, Contract contract, Order order, OrderState orderState)
 {
     this.orderId = orderId;
     this.order = order;
     this.contract = contract;
     this.orderState = orderState;
 }
Esempio n. 14
0
 ///<summary>
 /// Parameterless OpenOrderEventArgs Constructor
 ///</summary>
 public OpenOrderEventArgs()
 {
     this.orderId = -1;
     this.order = new Order();
     this.contract = new Contract();
     this.orderState = new OrderState();
 }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            //Contract bla = (Contract)CollectionViewSource.GetDefaultView(contractViewSource.View).CurrentItem;
            //MessageBox.Show(bla.EndDate.ToShortDateString());
            Company selectedCompany = (Company)companyComboBox.SelectedItem;
            ContractFormula selectedFormula = (ContractFormula)contractFormulaComboBox.SelectedItem;
            Contract newContract = new Contract();
            try
            {
                newContract.Company = selectedCompany;
                newContract.ContractFormula = selectedFormula;
                newContract.EndDate = (DateTime)endDateDatePicker.SelectedDate;
                newContract.StartDate = (DateTime)startDateDatePicker.SelectedDate;
                newContract.Number = Convert.ToInt32(numberTextBox.Text);

                if (viewModel.addContract(newContract) > 0)
                {
                    MessageBoxResult msbResult = MessageBox.Show("Contract has been added !", "Success", MessageBoxButton.OK);
                    if (msbResult == MessageBoxResult.OK)
                    {
                        this.DialogResult = true;
                        this.Close();
                    }

                }
                else
                {
                    MessageBox.Show("The new contract would overlap an existing contract, \n please change the startdate", "Error");
                }
            }
            catch (FormatException)
            {
                MessageBox.Show("The entered number is in a wrong format", "Error");
            }
        }
        public BidType AskForBid(Contract currentContract, IList<BidType> allowedBids, IList<BidType> previousBids)
        {
            this.Contract = currentContract;
            while (true)
            {
                this.Draw();

                var availableBidsAsString = AvailableBidsAsString(allowedBids);

                ConsoleHelper.WriteOnPosition(availableBidsAsString, 0, Settings.ConsoleHeight - 2);
                ConsoleHelper.WriteOnPosition("It's your turn! Please enter your bid: ", 0, Settings.ConsoleHeight - 3);

                BidType bid;

                var playerContract = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(playerContract))
                {
                    continue;
                }

                playerContract = playerContract.Trim();
                switch (char.ToUpper(playerContract[0]))
                {
                    case 'A':
                        bid = BidType.AllTrumps;
                        break;
                    case 'N':
                        bid = BidType.NoTrumps;
                        break;
                    case 'S':
                        bid = BidType.Spades;
                        break;
                    case 'H':
                        bid = BidType.Hearts;
                        break;
                    case 'D':
                        bid = BidType.Diamonds;
                        break;
                    case 'C':
                        bid = BidType.Clubs;
                        break;
                    case 'P':
                        bid = BidType.Pass;
                        break;
                    case '2':
                        bid = BidType.Double;
                        break;
                    case '4':
                        bid = BidType.ReDouble;
                        break;
                    default:
                        continue;
                }

                if (allowedBids.Contains(bid))
                {
                    return bid;
                }
            }
        }
Esempio n. 17
0
        public bool addContract(Contract c)
        {
            try
             {
                 int param = 13;

                 string[] name = new string[param];
                 object[] value = new object[param];

                 name[0] = "@begindate"; value[0] = c.Begindate;
                 name[1] = "@enddate"; value[1] = c.Enddate;
                 name[2] = "@setdate"; value[2] = c.Setdate;
                 name[3] = "@nameestablish"; value[3] = c.NameEstablish;
                 name[4] = "@roomid"; value[4] = c.Roomid;
                 name[5] = "@customerid"; value[5] = c.Customerid;
                 name[6] = "@note"; value[6] = c.Note;
                 name[7] = "@priceroom"; value[7] = c.PriceRoom;
                 name[8] = "@deposit"; value[8] = c.Deposit;
                 name[9] = "@bail"; value[9] = c.Bail;
                 name[10] = "@rest"; value[10] = c.Rest;
                 name[11] = "@numbermonth"; value[11] = c.Numbermonth;

                 int result = this.Update("contract_Insert", name, value, param);
                 if (result != 0)
                 {
                     return true;
                 }
             }
             catch (System.Exception ex)
             {
                 Console.WriteLine("Message = {1}", ex.Message);
             }

             return false;
        }
 public override void CalculateRevenueRecognitions(Contract contract)
 {
     var allocation = contract.Revenue.Allocate(3);
     contract.AddRevenueRecognition(new RevenueRecognition(allocation[0], contract.WhenSigned));
     contract.AddRevenueRecognition(new RevenueRecognition(allocation[1], contract.WhenSigned.AddDays(_firstRecognitionOffset)));
     contract.AddRevenueRecognition(new RevenueRecognition(allocation[2], contract.WhenSigned.AddDays(_secondRecognitionOffset)));
 }
Esempio n. 19
0
        public ActionResult ContractList( string seq, string contractnum, string projectnum,
            string projectname, string rfid, string contractplace,
            string bcompany, string money, string pvalue, string pkey = "seq", int pageidx = 1, int pagesize = 20)
        {

            Contract query = new Contract();
            query.seq = seq;
            query.contractnum = contractnum;
            query.projectnum = projectnum;
            query.projectname = projectname;
            query.contractrfid = rfid;
            query.contractplace = contractplace;
            query.bcompany = bcompany;
            query.money = money;

            //
            query.pkey = pkey;
            query.pvalue = pvalue;

            Page<Contract> page = GetData(query, pageidx, pagesize);

            

            return View(page);  
        }
        public override ContractParameter Generate(Contract contract)
        {
            // Get the OrbitGenerator behaviour
            OrbitGenerator orbitGenerator = ((ConfiguredContract)contract).Behaviours.OfType<OrbitGenerator>().FirstOrDefault<OrbitGenerator>();

            if (orbitGenerator == null)
            {
                LoggingUtil.LogError(this, "Could not find OrbitGenerator BEHAVIOUR to couple with ReachSpecificOrbit PARAMETER.");
                return null;
            }

            // Get the parameter for that orbit
            try
            {
                SpecificOrbitWrapper s = orbitGenerator.GetOrbitParameter(index);
                if (deviationWindow != 0.0)
                {
                    s.deviationWindow = deviationWindow;
                }
                return new VesselParameterDelegator(s);
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Couldn't find orbit in OrbitGenerator with index " + index + ": " + e.Message);
                return null;
            }
        }
Esempio n. 21
0
 private static void SetContract(int seq, string cellValue, int columnIndex, Contract contract)
 {
     switch (columnIndex)
     {
         case 1:
             contract.Seq = seq;
             break;
         case 2:
             break;
         case 3:
             contract.Code = cellValue;
             break;
         case 4:
             contract.Name = cellValue;
             break;
         case 5:
             contract.Title = cellValue;
             break;
         case 6:
             contract.Tel = cellValue;
             break;
         case 7:
             contract.Mobile = cellValue;
             break;
         case 8:
             contract.Email = cellValue;
             break;
         default:
             break;
     }
 }
Esempio n. 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OpenOrderEventArgs"/> class
 /// </summary>
 public OpenOrderEventArgs(int orderId, Contract contract, Order order, OrderState orderState)
 {
     OrderId = orderId;
     Contract = contract;
     Order = order;
     OrderState = orderState;
 }
        public ContractListItemModel fromDomain(Contract contract)
        {
            this.value = contract.ContractId.ToString();
            this.description = contract.Description;

            return this;
        }
Esempio n. 24
0
        public static string getContractTxt(Contract con)
        {
            string content = "\r\n 合同详细信息:\r\n\r\n";

            content += "协议类型:" + con.proCate + "\r\n";
            content += "协议名称:" + con.proName + "\r\n";
            content += "协议编号:" + con.proId + "\r\n";
            content += "联通公司业务联系人:" + con.unicomLinkMan + "\r\n";
            content += "联系电话:" + con.linkPhone + "\r\n";
            content += "集团客户客户经理:" + con.groupCusManager + "\r\n";
            content += "协议签署单位名称:" + con.proSignUnitName + "\r\n";
            content += "单位地址:" + con.unitAdd + "\r\n";
            content += "协议签署:" + con.proSign + "\r\n";
            content += "签署单位联系人:" + con.signUnitLinkMan + "\r\n";
            content += "联系电话:" + con.signUnitLinkPhone + "\r\n";
            content += "付费号码:" + con.payPhone + "\r\n";
            content += "收费标准:" + con.payStand + "\r\n";
            content += "协议签订日期:" + con.proSignDate + "\r\n";
            content += "协议执行日期:" + con.proSignExeDate + "\r\n";
            content += "协议期限:" + con.proDeadLine + "\r\n";
            content += "协议到期日期:" + con.proExpireData + "\r\n";
            content += "协议内容简述:" + con.proDesc + "\r\n";
            content += "备注:" + con.remark + "\r\n";
            content += "电路调单号:" + con.dltdh + "\r\n";
            content += "文件名:" + con.fileName + "\r\n";

            return content;
        }
 public override ContractParameter Generate(Contract contract)
 {
     ReachState param = new ReachState(targetBodies, biome == null ? "" : biome.biome, situation, minAltitude, maxAltitude,
         minTerrainAltitude, maxTerrainAltitude, minSpeed, maxSpeed, minRateOfClimb, maxRateOfClimb, minAcceleration, maxAcceleration, title);
     param.FailWhenUnmet = failWhenUnmet;
     return param;
 }
Esempio n. 26
0
        public void MockContract_GetAll_GotData()
        {
            Contract c1 = new Contract()
            {
                Id = 1,
                FirstName = "Иван",
                LastName = "Петров",
                MiddleName = "Вениаминович",
                Snils = "111-222-333 01"
            };

            Contract c2 = new Contract()
            {
                Id = 2,
                FirstName = "Иван",
                LastName = "Сидоров",
                MiddleName = "Вениаминович",
                Snils = "111-222-333 01"
            };
            List<Contract> contracts = new List<Contract> { c1, c2 };
            //int total = _rep.GetAll().Count;
            var mockCustomer = new Mock<Contract>();
            var mockRep = new Mock<IContractRepository>();
            mockRep.Setup(x => x.GetAll()).Returns(contracts);
              
            var tmp = mockRep.Object.GetAll();

            Assert.IsTrue(tmp.Count > 0);
            //.IsTrue(1 > 0);
        }
Esempio n. 27
0
 /// <summary>
 /// Delete the specified contract.
 /// </summary>
 /// <param name="contract">The contract to be deleted.</param>
 /// <returns>Number of affected rows.</returns>
 public static int Delete(Contract contract)
 {
     using (SqlConnection connection = SamenSterkerDB.GetConnection())
     {
         return connection.Execute(sql: deleteQuery, param: contract);
     }
 }
        public int Add(string hitmanId, string clientId, DateTime deadline, string targetName = null, string location = null)
        {
            var hitmanFromDb = this.users
                .All()
                .Where(x => x.Id == hitmanId)
                .FirstOrDefault();
            var client = this.users
                .All()
                .Where(x => x.Id == clientId)
                .FirstOrDefault();
            if (hitmanFromDb == null)
            {
                throw new ArgumentException("Invalid hitman!");
            }
            else if (client == null)
            {
                throw new ArgumentException("Invalid client!");
            }

            var contract = new Contract();
            contract.Client = client;
            contract.Hitman = hitmanFromDb;
            contract.Deadline = deadline;
            contract.TargetName = targetName;
            contract.Location = location;

            this.contracts.Add(contract);
            return this.contracts.SaveChanges();
        }
Esempio n. 29
0
 public static IList<Call> CreateCallListWithTwoCalls(Contract contract)
 {
     return new List<Call>
                      {
                          new Call(1)
                             {
                                 CalledFrom = "SATELLITE",
                                 ContractId = contract.Id.Value,
                                 Volume = 2.54M,
                                 HasFreeCallTariff = true,
                                 ImportedCallType = "TEST CALL",
                                 NumberCalled = "0400000001",
                                 PhoneNumber = contract.PhoneNumber1,
                                 UnitCost = 1M,
                                 UnitsOfTime = 6,
                                 Cost = 6.5M
                             },
                         new Call(2)
                             {
                                 CalledFrom = "SATELLITE",
                                 ContractId = contract.Id.Value,
                                 Volume = 5.23M,
                                 HasFreeCallTariff = true,
                                 ImportedCallType = "TEST CALL",
                                 NumberCalled = "0400000002",
                                 PhoneNumber = contract.PhoneNumber1,
                                 UnitCost = 1M,
                                 UnitsOfTime = 11,
                                 Cost = 11.5M
                             }
                      };
 }
Esempio n. 30
0
    public static Contract GetRandomContract(int Tier)
    {
        Contract contract = new Contract();

        //Get Contract element Tier lists
        int indexedTier = Tier - 1;

        List<ContractContent> contents = ContractManager.Contents[indexedTier];
        List<ContractTargetName> targetNames = ContractManager.TargetNames[indexedTier];
        List<ContractTargetImage> targetImages = ContractManager.TargetImages[indexedTier];
        List<ContractTargetShipImage> targetShipImages = ContractManager.TargetShipImages[indexedTier];

        ContractContent content = new ContractContent();
        ContractTargetName targetName = new ContractTargetName();
        ContractTargetImage targetImage = new ContractTargetImage();
        ContractTargetShipImage targetShipImage = new ContractTargetShipImage();

        //Get random content
        if (contents != null)
            content = contents[Random.Range(0, contents.Count)];

        if (targetNames != null)
            targetName = targetNames[Random.Range(0, targetNames.Count)];

        if (targetImages != null)
            targetImage = targetImages[Random.Range(0, targetImages.Count)];

        if (targetShipImages != null)
            targetShipImage = targetShipImages[Random.Range(0, targetShipImages.Count)];

        //Build contract
        contract = new Contract(targetName.TargetName, content.Description, content.Title, targetImage.TargetImagePath, targetShipImage.TargetShipImagePath, content.Objectives);

        return contract;
    }
Esempio n. 31
0
 private void EnsureNotReadOnly() {
     if( m_readOnly) {
         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
     }
     Contract.EndContractBlock();
 }
        public void StartDebuggingSession(Solution solution)
        {
            var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(solution, _compilationOutputsProvider), null);

            Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended.");
        }
Esempio n. 33
0
 private void ObjectInvariants() {
     Contract.Invariant(Crs != null);
 }
Esempio n. 34
0
 internal RAMI(List <RAM> rami)
 {
     Contract.Requires(rami != null, "lista de rami");
     this.rami = rami;
 }
 public ImmutableArray<Document> GetDocuments(Uri documentUri)
 {
     Contract.ThrowIfNull(_currentSolution);
     return _currentSolution.GetDocuments(documentUri);
 }
 public Solution GetCurrentSolutionForMainWorkspace()
 {
     Contract.ThrowIfNull(_currentSolution);
     return _currentSolution;
 }
Esempio n. 37
0
 void ObjectInvariant()
 {
     Contract.Invariant(this.edgeCount >= 0);
 }
Esempio n. 38
0
 [System.Security.SecurityCritical]  // auto-generated
 private void EnsureNotDisposed() {
     if( m_buffer == null) {
         throw new ObjectDisposedException(null);
     }
     Contract.EndContractBlock();
 }
Esempio n. 39
0
        private IEnumerable<PathNode> FindAllPathsFrom(PathNode current, bool mustMoveToProjected, bool transformationRestricted) {
            Contract.Requires(current != null);
            Contract.Ensures(Contract.Result<IEnumerable<PathNode>>() != null);

            throw new NotImplementedException();

            /*var currentCode = current.Crs.Code;
            if (currentCode == TargetCrs.Code)
                return ArrayUtil.CreateSingleElementArray(current);

            var currentKind = current.CrsKind;
            var visitedCrsCodes = new HashSet<int>(current.GetCrsCodes());
            var results = new List<PathNode>();

            var derrivedProjectionCodes = EpsgCrsProjected.GetProjectionCodesBasedOn(currentCode);
            if (derrivedProjectionCodes.Count != 0) {
                // move down to projected from here, all new nodes must now move towards projected
                foreach (var derrivedProjectionCode in derrivedProjectionCodes) {
                    if (visitedCrsCodes.Contains(derrivedProjectionCode))
                        continue;

                    var derrivedProjection = EpsgCrsProjected.GetProjected(derrivedProjectionCode);
                    if (!IsCrsAllowed(derrivedProjection))
                        continue;

                    var projection = derrivedProjection.Projection;
                    if (!IsOpAllowed(projection))
                        continue;

                    var nextNode = current.Append(derrivedProjection, projection);
                    var localResults = FindAllPathsFrom(nextNode, true, transformationRestricted);
                    results.AddRange(localResults);
                }
            }

            if (currentKind == EpsgCrsKind.Projected && !mustMoveToProjected) {
                // can only move away from projected if not restricted and if this is projected
                var projectedCrs = (EpsgCrsProjected)current.Crs;
                var baseCrs = projectedCrs.BaseCrs;
                if (baseCrs != null && !visitedCrsCodes.Contains(baseCrs.Code) && IsCrsAllowed(baseCrs)) {
                    var projection = projectedCrs.Projection;
                    if (projection != null && projection.HasInverse) {
                        var projectionInverse = projection.GetInverse();
                        if (IsOpAllowed(projectionInverse)) {
                            var nextNode = current.Append(baseCrs, projectionInverse);
                            var localResults = FindAllPathsFrom(nextNode, false, transformationRestricted);
                            results.AddRange(localResults);
                        }
                    }
                }
            }

            if (!transformationRestricted) {

                var concatenatedForward = EpsgCoordinateOperationInfoRepository.GetConcatenatedForwardReferenced(currentCode);
                foreach (var catOp in concatenatedForward) {
                    if (visitedCrsCodes.Contains(catOp.TargetCrsCode))
                        continue;
                    if (!IsOpAllowed(catOp))
                        continue;

                    // TODO: is this path OK?
                    // NOTE: ignore mustMoveToProjected ... for now
                    var targetCrs = catOp.TargetCrs;
                    if (!IsCrsAllowed(targetCrs))
                        continue;
                    var nextNode = current.Append(targetCrs, catOp);
                    var localResults = FindAllPathsFrom(nextNode, mustMoveToProjected, true);
                    results.AddRange(localResults);
                }

                var concatenatedReverse = EpsgCoordinateOperationInfoRepository.GetConcatenatedReverseReferenced(currentCode);
                foreach (var catOp in concatenatedReverse) {
                    if (!catOp.HasInverse)
                        continue;
                    if (visitedCrsCodes.Contains(catOp.SourceCrsCode))
                        continue;
                    var inverseCatOp = catOp.GetInverse();
                    if (!IsOpAllowed(inverseCatOp))
                        continue;

                    // TODO: is this path OK?
                    // NOTE: ignore mustMoveToProjected ... for now
                    var sourceCrs = catOp.SourceCrs;
                    if (!IsCrsAllowed(sourceCrs))
                        continue;
                    var nextNode = current.Append(sourceCrs, inverseCatOp);
                    var localResults = FindAllPathsFrom(nextNode, mustMoveToProjected, true);
                    results.AddRange(localResults);
                }

                var transformForward = EpsgCoordinateOperationInfoRepository.GetTransformForwardReferenced(currentCode);
                foreach (var txOp in transformForward) {
                    if (visitedCrsCodes.Contains(txOp.TargetCrsCode))
                        continue;
                    if (!IsOpAllowed(txOp))
                        continue;

                    // TODO: is this path OK?
                    // TODO: enforce mustMoveToProjected
                    var targetCrs = txOp.TargetCrs;
                    if (!IsCrsAllowed(targetCrs))
                        continue;
                    var nextNode = current.Append(targetCrs, txOp);
                    var localResults = FindAllPathsFrom(nextNode, mustMoveToProjected, true);
                    results.AddRange(localResults);
                }
                var transformReverse = EpsgCoordinateOperationInfoRepository.GetTransformReverseReferenced(currentCode);
                foreach (var txOp in transformReverse) {
                    if (!txOp.HasInverse)
                        continue;
                    if (visitedCrsCodes.Contains(txOp.SourceCrsCode))
                        continue;
                    var inverseOp = txOp.GetInverse();
                    if (!IsOpAllowed(inverseOp))
                        continue;

                    // TODO: is this path OK?
                    // TODO: enforce mustMoveToProjected
                    var sourceCrs = txOp.SourceCrs;
                    if (!IsCrsAllowed(sourceCrs))
                        continue;
                    var nextNode = current.Append(sourceCrs, inverseOp);
                    var localResults = FindAllPathsFrom(nextNode, mustMoveToProjected, true);
                    results.AddRange(localResults);
                }
            }

            return results;*/
        }
        public async Task <ImmutableArray <Diagnostic> > GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
        {
            try
            {
                var debuggingSession = _debuggingSession;
                if (debuggingSession == null)
                {
                    return(ImmutableArray <Diagnostic> .Empty);
                }

                // Not a C# or VB project.
                var project = document.Project;
                if (!SupportsEditAndContinue(project))
                {
                    return(ImmutableArray <Diagnostic> .Empty);
                }

                // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only)
                if (document.State.Attributes.DesignTimeOnly || !document.SupportsSyntaxTree)
                {
                    return(ImmutableArray <Diagnostic> .Empty);
                }

                // Do not analyze documents (and report diagnostics) of projects that have not been built.
                // Allow user to make any changes in these documents, they won't be applied within the current debugging session.
                // Do not report the file read error - it might be an intermittent issue. The error will be reported when the
                // change is attempted to be applied.
                var(mvid, _) = await debuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false);

                if (mvid == Guid.Empty)
                {
                    return(ImmutableArray <Diagnostic> .Empty);
                }

                var(oldDocument, oldDocumentState) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(document.Id, cancellationToken).ConfigureAwait(false);

                if (oldDocumentState == CommittedSolution.DocumentState.OutOfSync ||
                    oldDocumentState == CommittedSolution.DocumentState.Indeterminate ||
                    oldDocumentState == CommittedSolution.DocumentState.DesignTimeOnly)
                {
                    // Do not report diagnostics for existing out-of-sync documents or design-time-only documents.
                    return(ImmutableArray <Diagnostic> .Empty);
                }

                // The document has not changed while the application is running since the last changes were committed:
                var editSession = _editSession;

                if (editSession == null)
                {
                    if (document == oldDocument)
                    {
                        return(ImmutableArray <Diagnostic> .Empty);
                    }

                    // Any changes made in loaded, built projects outside of edit session are rude edits (the application is running):
                    var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                    Contract.ThrowIfNull(newSyntaxTree);

                    var changedSpans = await GetChangedSpansAsync(oldDocument, newSyntaxTree, cancellationToken).ConfigureAwait(false);

                    return(GetRunModeDocumentDiagnostics(document, newSyntaxTree, changedSpans));
                }

                var analysis = await editSession.GetDocumentAnalysis(oldDocument, document).GetValueAsync(cancellationToken).ConfigureAwait(false);

                if (analysis.HasChanges)
                {
                    // Once we detected a change in a document let the debugger know that the corresponding loaded module
                    // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying
                    // the change blocks the UI when the user "continues".
                    if (debuggingSession.AddModulePreparedForUpdate(mvid))
                    {
                        // fire and forget:
                        _ = Task.Run(() => _debugeeModuleMetadataProvider.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken);
                    }
                }

                if (analysis.RudeEditErrors.IsEmpty)
                {
                    return(ImmutableArray <Diagnostic> .Empty);
                }

                editSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors);

                // track the document, so that we can refresh or clean diagnostics at the end of edit session:
                editSession.TrackDocumentWithReportedDiagnostics(document.Id);

                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                return(analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree));
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                return(ImmutableArray <Diagnostic> .Empty);
            }
        }
Esempio n. 41
0
 public static PathNode CreateStartNode(EpsgCrs crs) {
     Contract.Requires(crs != null);
     Contract.Ensures(Contract.Result<PathNode>() != null);
     return new PathNode(crs);
 }
Esempio n. 42
0
 private PathNode(EpsgCrs crs) {
     Contract.Requires(crs != null);
     Crs = crs;
 }
Esempio n. 43
0
 internal void WriteCharsSimple(char[] chars, int len=0)
 {
     Contract.Requires(TextEncoding.GetByteCount(chars) <= WriteSpaceLeft);
     WritePosition += TextEncoding.GetBytes(chars, 0, len == 0 ? chars.Length : len, _buf, WritePosition);
 }
Esempio n. 44
0
 private void ObjectInvariants() {
     Contract.Invariant(SourceCrs != null);
     Contract.Invariant(TargetCrs != null);
 }
Esempio n. 45
0
 public void WriteBytesSimple(byte[] buf, int offset, int count)
 {
     Contract.Requires(count <= WriteSpaceLeft);
     Buffer.BlockCopy(buf, offset, _buf, _writePosition, count);
     _writePosition += count;
 }
            /// <summary>
            /// Given a symbol, finds the symbol that actually defines the name that we're using.
            /// </summary>
            public static async Task<ISymbol> FindDefinitionSymbolAsync(
                ISymbol symbol, Solution solution, CancellationToken cancellationToken)
            {
                Contract.ThrowIfNull(symbol);
                Contract.ThrowIfNull(solution);

                // Make sure we're on the original source definition if we can be
                var foundSymbol = await SymbolFinder.FindSourceDefinitionAsync(
                    symbol, solution, cancellationToken).ConfigureAwait(false);

                var bestSymbol = foundSymbol ?? symbol;
                symbol = bestSymbol;

                // If we're renaming a property, it might be a synthesized property for a method
                // backing field.
                if (symbol.Kind == SymbolKind.Parameter)
                {
                    if (symbol.ContainingSymbol.Kind == SymbolKind.Method)
                    {
                        var containingMethod = (IMethodSymbol)symbol.ContainingSymbol;
                        if (containingMethod.AssociatedSymbol is IPropertySymbol)
                        {
                            var associatedPropertyOrEvent = (IPropertySymbol)containingMethod.AssociatedSymbol;
                            var ordinal = containingMethod.Parameters.IndexOf((IParameterSymbol)symbol);
                            if (ordinal < associatedPropertyOrEvent.Parameters.Length)
                            {
                                return associatedPropertyOrEvent.Parameters[ordinal];
                            }
                        }
                    }
                }

                // if we are renaming a compiler generated delegate for an event, cascade to the event
                if (symbol.Kind == SymbolKind.NamedType)
                {
                    var typeSymbol = (INamedTypeSymbol)symbol;
                    if (typeSymbol.IsImplicitlyDeclared && typeSymbol.IsDelegateType() && typeSymbol.AssociatedSymbol != null)
                    {
                        return typeSymbol.AssociatedSymbol;
                    }
                }

                // If we are renaming a constructor or destructor, we wish to rename the whole type
                if (symbol.Kind == SymbolKind.Method)
                {
                    var methodSymbol = (IMethodSymbol)symbol;
                    if (methodSymbol.MethodKind == MethodKind.Constructor ||
                        methodSymbol.MethodKind == MethodKind.StaticConstructor ||
                        methodSymbol.MethodKind == MethodKind.Destructor)
                    {
                        return methodSymbol.ContainingType;
                    }
                }

                // If we are renaming a backing field for a property, cascade to the property
                if (symbol.Kind == SymbolKind.Field)
                {
                    var fieldSymbol = (IFieldSymbol)symbol;
                    if (fieldSymbol.IsImplicitlyDeclared &&
                        fieldSymbol.AssociatedSymbol.IsKind(SymbolKind.Property))
                    {
                        return fieldSymbol.AssociatedSymbol;
                    }
                }

                // in case this is e.g. an overridden property accessor, we'll treat the property itself as the definition symbol
                var property = await GetPropertyFromAccessorOrAnOverrideAsync(bestSymbol, solution, cancellationToken).ConfigureAwait(false);

                return property ?? bestSymbol;
            }
Esempio n. 47
0
 internal byte ReadByte()
 {
     Contract.Requires(ReadBytesLeft >= sizeof(byte));
     return _buf[ReadPosition++];
 }
Esempio n. 48
0
 internal void WriteStringSimple(string s, int len=0)
 {
     Contract.Requires(TextEncoding.GetByteCount(s) <= WriteSpaceLeft);
     WritePosition += TextEncoding.GetBytes(s, 0, len == 0 ? s.Length : len, _buf, WritePosition);
 }
Esempio n. 49
0
 /// <summary>
 /// Tests if item exists in collection.
 /// </summary>
 public bool Contains(Id id)
 {
     Contract.AssertNotNull(id, "id");
     return items.ContainsKey(id);
 }
Esempio n. 50
0
 internal void ReadBytesSimple(byte[] output, int outputOffset, int len)
 {
     Contract.Requires(len <= ReadBytesLeft);
     Array.Copy(_buf, ReadPosition, output, outputOffset, len);
     ReadPosition += len;
 }
Esempio n. 51
0
 /// <summary>
 /// Find item by id. Returns null if item is not found.
 /// </summary>
 public T Find(Id id)
 {
     Contract.AssertNotNull(id, "id");
     return items.GetValueOrDefault(id, default(T));
 }      
Esempio n. 52
0
 internal void CopyTo(NpgsqlBuffer other)
 {
     Contract.Assert(other.Size - other._filledBytes >= ReadBytesLeft);
     Array.Copy(_buf, ReadPosition, other._buf, other._filledBytes, ReadBytesLeft);
     other._filledBytes += ReadBytesLeft;
 }
        protected void PopulateApiDescriptions(ODataActionDescriptor oDataActionDescriptor, List<ApiParameterDescription> parameterDescriptions, string apiDocumentation, List<ApiDescription> apiDescriptions)
        {
            Contract.Requires(oDataActionDescriptor != null);
            Contract.Requires(apiDescriptions != null);

            // request formatters
            var bodyParameter = default(ApiParameterDescription);
            if (parameterDescriptions != null)
            {
                bodyParameter = parameterDescriptions.FirstOrDefault(description => description.Source == ApiParameterSource.FromBody);
            }

            var httpConfiguration = oDataActionDescriptor.ActionDescriptor.Configuration;
            Contract.Assume(httpConfiguration != null);
            var mediaTypeFormatterCollection = httpConfiguration.Formatters;
            var responseDescription = oDataActionDescriptor.ActionDescriptor.CreateResponseDescription();
            IEnumerable<MediaTypeFormatter> supportedRequestBodyFormatters = new List<MediaTypeFormatter>();
            IEnumerable<MediaTypeFormatter> supportedResponseFormatters = new List<MediaTypeFormatter>();
            if (mediaTypeFormatterCollection != null)
            {
                supportedRequestBodyFormatters = bodyParameter != null ? mediaTypeFormatterCollection.Where(CanReadODataType(oDataActionDescriptor, bodyParameter)) : Enumerable.Empty<MediaTypeFormatter>();

                // response formatters
                var returnType = responseDescription.ResponseType ?? responseDescription.DeclaredType;
                supportedResponseFormatters = returnType != null && returnType != typeof (void) ? mediaTypeFormatterCollection.Where(CanWriteODataType(oDataActionDescriptor, returnType)) : Enumerable.Empty<MediaTypeFormatter>();


                // Replacing the formatter tracers with formatters if tracers are present.
                supportedRequestBodyFormatters = GetInnerFormatters(supportedRequestBodyFormatters);
                supportedResponseFormatters = GetInnerFormatters(supportedResponseFormatters);
            }

            var supportedHttpMethods = GetHttpMethodsSupportedByAction(oDataActionDescriptor.Route, oDataActionDescriptor.ActionDescriptor);
            foreach (var supportedHttpMethod in supportedHttpMethods)
            {
                var apiDescription = new ApiDescription
                {
                    Documentation = apiDocumentation,
                    HttpMethod = supportedHttpMethod,
                    RelativePath = oDataActionDescriptor.RelativePathTemplate.TrimStart('/'),
                    ActionDescriptor = oDataActionDescriptor.ActionDescriptor,
                    Route = oDataActionDescriptor.Route
                };

                var apiSupportedResponseFormatters = apiDescription.SupportedResponseFormatters;
                Contract.Assume(apiSupportedResponseFormatters != null);
                apiSupportedResponseFormatters.AddRange(supportedResponseFormatters);

                var apiSupportedRequestBodyFormatters = apiDescription.SupportedRequestBodyFormatters;
                Contract.Assume(apiSupportedRequestBodyFormatters != null);
                apiSupportedRequestBodyFormatters.AddRange(supportedRequestBodyFormatters);

                if (parameterDescriptions != null)
                {
                    var apiParameterDescriptions = apiDescription.ParameterDescriptions;
                    Contract.Assume(apiParameterDescriptions != null);
                    apiParameterDescriptions.AddRange(parameterDescriptions);
                }

                // Have to set ResponseDescription because it's internal!??
                apiDescription.SetInstanceProperty("ResponseDescription", responseDescription);

                if (apiDescription.ParameterDescriptions != null)
                {
                    apiDescription.RelativePath = apiDescription.GetRelativePathForSwagger();
                }

                apiDescriptions.Add(apiDescription);
            }
        }
Esempio n. 54
0
 /// <summary>
 /// Remove item by id.
 /// </summary>
 public void Remove(Id id)
 {
     Contract.AssertNotNull(id, "id");
     items.Remove(id);
 }
Esempio n. 55
0
 //
 // Summary:
 //     Writes this node to an System.Xml.XmlWriter.
 //
 // Parameters:
 //   writer:
 //     An System.Xml.XmlWriter into which this method will write.
 public virtual void WriteTo(XmlWriter writer)
 {
     Contract.Requires(writer != null);
 }
Esempio n. 56
0
 /// <summary>
 /// Add item to the collection.
 /// </summary>
 public void Add(T item)
 {
     Contract.AssertNotNull(item, "item");
     items.Add(item.Id, item);
 }
Esempio n. 57
0
 internal void AdaugaRAM(RAM ram)
 {
     Contract.Requires(ram != null, "ram");
     rami.Add(ram);
 }
        private static IEnumerable<MediaTypeFormatter> GetInnerFormatters(IEnumerable<MediaTypeFormatter> mediaTypeFormatters)
        {
            Contract.Requires(mediaTypeFormatters != null);

            return mediaTypeFormatters.Select(Decorator.GetInner);
        }
Esempio n. 59
0
 private void CheckSupportedOnCurrentPlatform() {
     if( !supportedOnCurrentPlatform) {
         throw new NotSupportedException(Environment.GetResourceString("Arg_PlatformSecureString"));
     }                            
     Contract.EndContractBlock();
 }
Esempio n. 60
0
 public string ToString(SaveOptions options)
 {
     Contract.Ensures(Contract.Result <string>() != null);
     return(default(string));
 }