Ejemplo n.º 1
0
 public TaxiPath(Record rec)
 {
     Id = rec[0];
     From = rec[1];
     To = rec[2];
     Cost = rec[3];
 }
Ejemplo n.º 2
0
 public PageInfo()
 {
     Page = 1;
     PageSize = 10;
     RecordCollection a = new RecordCollection();
     Record b = new Record();
 }
Ejemplo n.º 3
0
 void CollectEntityByID(MooDB db, int id)
 {
     record = (from r in db.Records
             where r.ID == id
             select r).SingleOrDefault<Record>();
     info = record == null ? null : record.JudgeInfo;
 }
Ejemplo n.º 4
0
 public void TestGetBalance()
 {
     CategoryModel categoryModel = new CategoryModel(); // TODO: 初始化為適當值
     Category categoryMovie = new Category(CATEGORY_NAME_MOVIE);
     Category categoryWork = new Category(CATEGORY_NAME_WORK);
     categoryModel.AddCategory(categoryMovie);
     categoryModel.AddCategory(categoryWork);
     RecordModel recordModel = new RecordModel(categoryModel); // TODO: 初始化為適當值
     DateTime now = DateTime.Now;
     DateTime date = new DateTime(now.Year, now.Month, now.Day);
     Record movieRecord = new Record(date, categoryMovie, -1000);
     recordModel.AddRecord(movieRecord);
     movieRecord = new Record(date, categoryMovie, -2000);
     recordModel.AddRecord(movieRecord);
     movieRecord = new Record(date, categoryMovie, -3000);
     recordModel.AddRecord(movieRecord);
     Record workRecord = new Record(date, categoryWork, 1000);
     recordModel.AddRecord(workRecord);
     workRecord = new Record(date, categoryWork, 2000);
     recordModel.AddRecord(workRecord);
     workRecord = new Record(date, categoryWork, 3000);
     recordModel.AddRecord(workRecord);
     workRecord = new Record(date, categoryWork, 4000);
     recordModel.AddRecord(workRecord);
     StatisticModel statisticModel = new StatisticModel(categoryModel, recordModel); // TODO: 初始化為適當值
     int balance = statisticModel.GetBalance(recordModel.Records);
     Assert.AreEqual(4000, balance);
 }
Ejemplo n.º 5
0
 public void Approve(int MLJRecordID, int userID)
 {
     using (MLJRecordAccessClient _MLJAccessClient = new MLJRecordAccessClient(EndpointName.MLJRecordAccess))
     {
         //First get all JournalCollection in this period
         MLJRecord _MLJ = new MLJRecordCollection(_MLJAccessClient.QueryByRecordID(MLJRecordID))[0];
         //New Record
         Record _re = new Record();
         _re.Period = _MLJ.Period;
         _re.RecordStatus = RecordStatus.Normal;
         _re.Type = RecordType.WinAndLoss;
         foreach (MLJJournal _MLJjur in _MLJ.MLJJournalCollection)
         {
             Journal _jur = new Journal();
             decimal _baseamount = _MLJjur.Mon + _MLJjur.Tue + _MLJjur.Wed + _MLJjur.Thu + _MLJjur.Fri + _MLJjur.Sat + _MLJjur.Sun;
             _jur.BaseAmount = _baseamount;
             _jur.BaseCurrency = _MLJjur.BaseCurrency;
             _jur.ExchangeRate = _MLJjur.ExchangeRate;
             _jur.SGDAmount = _baseamount * _MLJjur.ExchangeRate;
             _jur.EntityID = _MLJjur.EntityID;
             _jur.EntryUser.UserID = userID;
             _re.JournalCollection.Add(_jur);
         }
         //Second insert Record
         using (RecordAccessClient _RecordClient = new RecordAccessClient(EndpointName.RecordAccess))
         {
             _RecordClient.Insert(_re, _re.JournalCollection.ToArray());
         }
         //Third Change MLJ_Record Status
         _MLJAccessClient.ChangeStatus(MLJRecordID, RecordStatus.Confirm, userID);
     }
 }
Ejemplo n.º 6
0
 public void create_line()
 {
     Record record = new Record();
     record["test"] = "sample";
     record["foo"] = "bar";
     Assert.That(record.ToString(), Is.EqualTo("test:sample\tfoo:bar"));
 }
Ejemplo n.º 7
0
 private void buttonNewTask_Click(object sender, EventArgs e)
 {
     var r = new Record();
     r.Start = DateTime.Now;
     panelListView.Controls.Add(RecordViewer(r));
     panelListView.AutoScroll = true;
 }
Ejemplo n.º 8
0
 public TableHeader(Record R)
     : base(RECORD_LEN)
 {
     if (R.Count != RECORD_LEN) 
         throw new Exception("Header-Record supplied has an invalid length");
     this._data = R.BaseArray;
 }
Ejemplo n.º 9
0
        public static Bitmap RecordToMonoChromeBitmap(int X, int Y, double Threshold, Record Datum)
        {

            if (Datum.Count != X * Y)
                throw new Exception(string.Format("Bitmap dimensions are invalid for record lenght"));

            Bitmap map = new Bitmap(X, Y);

            int index = 0;

            for (int x = 0; x < X; x++)
            {

                for (int y = 0; y < Y; y++)
                {

                    if (Datum[index].DOUBLE >= Threshold)
                    {
                        map.SetPixel(x, y, Color.Black);
                    }

                    index++;

                }

            }

            return map;

        }
        /// <summary>
        /// Saves content to UGC (new and existing) and return RecordID
        /// </summary>
        /// <param name="record"></param>
        public static int SaveUGCContentToAgility(Record record)
        {
            int recordID = -1;

            using (Agility_UGC_API_WCFClient client = UGCAPIUtil.APIClient)
            {
                DataServiceAuthorization auth = UGCAPIUtil.GetDataServiceAuthorization(-1);

                try
                {
                    recordID = client.SaveRecord(auth, record);

                    if (record.State == RecordState.Published)
                        client.SetRecordState(auth, recordID, 1, "");

                    Utilities.LogEvent(string.Format("Saved - {0}", recordID));
                }
                catch (Exception e)
                {
                    Utilities.LogEvent(string.Format("{0}:{1} - {2}", record.RecordTypeName, record.ID, e.Message));
                }
            }

            return recordID;
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Record an object-to-copy mapping into the current serialization context.
 /// Used for maintaining the .NET object graph during serialization operations.
 /// Used in generated code.
 /// </summary>
 /// <param name="original">Original object.</param>
 /// <param name="copy">Copy object that will be the serialized form of the original.</param>
 public void RecordObject(object original, object copy)
 {
     if (!processedObjects.ContainsKey(original))
     {
         processedObjects[original] = new Record(copy);                
     }
 }
Ejemplo n.º 12
0
    protected void onAddRecord(object sender, EventArgs e)
    {
        Record record = new Record
        {
            number = 1,
            firstName = firstNameInput.Text,
            lastName = lastNameInput.Text,
            sport = sportInput.Text,
            era = playingEraInput.Text,
            primaryTeam = primaryTeamInput.Text,
            professionalisation = professionalisationInput.Text,
            birthPlace = placeOfBirthInput.Text,
            lifeStatus = LifeStatus.Alive,
            timePeriod = timePeriodInput.Text,
            position = positionInput.Text,
            recordType = itemTypeInput.Text,
            condition = Condition.Average,
            dedication = Dedication.Inscription,
            cost = decimal.Parse(costInput.Text.Equals("") ? "0" : costInput.Text),
            estimatedValue = decimal.Parse(valueInput.Text.Equals("") ? "0" : valueInput.Text)
        };

        Storage.storeRecord(record);
        List<Record> records = Storage.grabRecords();
    }
Ejemplo n.º 13
0
        public Record DeserializeRecord(ArraySegment<byte> segment) {
            var text = Encoding.UTF8.GetString(segment.Array, segment.Offset, segment.Count);
            var fields = this.GetFields(text);

            var attributes = this.AttributeMappings;

            var record = new Record {
                Logger = SafeGetFieldByIndex(fields, this.LoggerFieldIndex),
                Level = this.GetLevel(fields),
                Message = SafeGetFieldByIndex(fields, this.MessageFieldIndex),
                Exception = SafeGetFieldByIndex(fields, this.ExceptionFieldIndex)
            };

            DateTime timestamp;

            if (DateTime.TryParse(SafeGetFieldByIndex(fields, this.TimestampFieldIndex), out timestamp))
                record.Timestamp = timestamp;

            if (attributes != null)
                record.Attributes = attributes
                    .Select(x => new KeyValuePair<string, string>(x.Item2, SafeGetFieldByIndex(fields, x.Item1)))
                    .ToArray();

            return record;
        }
Ejemplo n.º 14
0
        public bool AddRecord(string tableName, Record record)
        {
            try
            {
                string pathTable = databasePath + '/' + tableName + ".dat";
                string pathHash = databasePath + '/' + tableName + "_hash.dat";
                string pathFreeSpace = databasePath + '/' + tableName + "_freespace.dat";

                if (File.Exists(pathTable) && File.Exists(pathHash) && File.Exists(pathFreeSpace))
                {
                    long position = SeekEmptySpace(pathFreeSpace);

                    WriteData(tableName, ref position, record);
                    WriteHash(tableName, position, record.data[0].ToString());

                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return false;
            }
        }
Ejemplo n.º 15
0
        public NesuiLocation(Record record)
        {
            dynamic self = record;

            this.Id = self.internalId;
            this.Name = self.name;
        }
Ejemplo n.º 16
0
 public override bool Evaluate(Record r, SubRecord sr)
 {
     if (this.Type == BatchCondRecordType.Create)
     {
         if (sr == null)
         {
             // guess the best insert location
             int idx = -1;
             RecordStructure rs;
             if ( RecordStructure.Records.TryGetValue(r.Name, out rs) )
             {
                 for ( int i = Array.FindIndex(rs.subrecords, structure => structure.name == this.Record.name) - 1; i >= 0; --i)
                 {
                     var srsname = rs.subrecords[i].name;
                     idx = r.SubRecords.IndexOf(r.SubRecords.FirstOrDefault(x => x.Name == srsname));
                 }
             }
             sr = new SubRecord(this.Record);
             if (idx < 0) r.SubRecords.Add(sr); 
             else r.SubRecords.Insert(idx+1, sr); 
         }
     }
     else if (this.Type == BatchCondRecordType.Delete)
     {
         while (sr != null)
         {
             r.SubRecords.Remove(sr);
             sr = r.SubRecords.FirstOrDefault(x => x.Name == this.Record.name);
         }
     }
     return true;
 }
Ejemplo n.º 17
0
 public Explosion(CoordDouble pos)
 {
     Position = pos;
     Radius = 2;
     Records = new Record[0];
     PlayerMotion = new float[3];
 }
Ejemplo n.º 18
0
        public NesuiPriceLevel(Record record)
        {
            dynamic self = record;

            this.Id = self.internalId;
            this.Name = self.name;
        }
Ejemplo n.º 19
0
 //This function is called by the recorder in order to store data for rewind.
 public Record getRecord()
 {
     Record record = new Record ();
     record.position = transform.position;
     record.time = GlobalTime.GameTime;
     return record;
 }
        public bool Write(Dictionary<Guid,string> source, Adam.Core.Application app)
        {
            Record r = new Record(app);
            Excel.Application EApp;
            Excel.Workbook EWorkbook;
            Excel.Worksheet EWorksheet;
            Excel.Range Rng;
            EApp = new Excel.Application();
            object misValue = System.Reflection.Missing.Value;
            EWorkbook = EApp.Workbooks.Add(misValue);
            EWorksheet = (Excel.Worksheet)EWorkbook.Worksheets.Item[1];                         
            EWorksheet.get_Range("A1", misValue).Formula = "UPC code";
            EWorksheet.get_Range("B1", misValue).Formula = "Link";            
            Rng = EWorksheet.get_Range("A2", misValue).get_Resize(source.Count,misValue);
            Rng.NumberFormat = "00000000000000";
            int row = 2;
            foreach(KeyValuePair<Guid,string> pair in source)
            {              
                EWorksheet.Cells[row,1] = pair.Value;                
                r.Load(pair.Key);
                Rng = EWorksheet.get_Range("B"+row, misValue);
                EWorksheet.Hyperlinks.Add(Rng, r.Fields.GetField<TextField>("Content Url").Value);               
                //myExcelWorksheet.Cells[row, 2] = r.Fields.GetField<TextField>("Content Url").Value;                                
                row++;
            }
            ((Excel.Range)EWorksheet.Cells[2, 1]).EntireColumn.AutoFit();
            ((Excel.Range)EWorksheet.Cells[2, 2]).EntireColumn.AutoFit();
            EWorkbook.SaveAs(_fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
                Excel.XlSaveAsAccessMode.xlExclusive,
                misValue, misValue, misValue, misValue, misValue);

            EWorkbook.Close(true, misValue, misValue);
            EApp.Quit();
            return true;
        }
Ejemplo n.º 21
0
 public void TestGetAmounts()
 {
     CategoryModel categoryModel = new CategoryModel(); // TODO: 初始化為適當值
     Category categoryMovie = new Category(CATEGORY_NAME_MOVIE);
     Category categoryWork = new Category(CATEGORY_NAME_WORK);
     categoryModel.AddCategory(categoryMovie);
     categoryModel.AddCategory(categoryWork);
     RecordModel recordModel = new RecordModel(categoryModel); // TODO: 初始化為適當值
     DateTime now = DateTime.Now;
     DateTime date = new DateTime(now.Year, now.Month, now.Day);
     Record movieRecord = new Record(date, categoryMovie, -1000);
     recordModel.AddRecord(movieRecord);
     movieRecord = new Record(date, categoryMovie, -2000);
     recordModel.AddRecord(movieRecord);
     movieRecord = new Record(date, categoryMovie, -3000);
     recordModel.AddRecord(movieRecord);
     Record workRecord = new Record(date, categoryWork, 1000);
     recordModel.AddRecord(workRecord);
     workRecord = new Record(date, categoryWork, 2000);
     recordModel.AddRecord(workRecord);
     workRecord = new Record(date, categoryWork, 3000);
     recordModel.AddRecord(workRecord);
     workRecord = new Record(date, categoryWork, 4000);
     recordModel.AddRecord(workRecord);
     StatisticModel statisticModel = new StatisticModel(categoryModel, recordModel); // TODO: 初始化為適當值
     int income = statisticModel.GetAmounts(recordModel.Records, true);
     Assert.AreEqual(10000, income);
     int expense = statisticModel.GetAmounts(recordModel.Records, false);
     Assert.AreEqual(-6000, expense);
 }
Ejemplo n.º 22
0
 public void Given_an_invalid_heading_name__should_throw_an_exception()
 {
     var record = new Record(new string[] { }, new Dictionary<string, int>());
     // ReSharper disable ReturnValueOfPureMethodIsNotUsed
     record.GetField("foo");
     // ReSharper restore ReturnValueOfPureMethodIsNotUsed
 }
 public Record WriteToReceptionDoctor(int id_Doctor, Pacient thePacient)
 {
     AddPacient(thePacient);
     Record theRecord = new Record(id_Doctor, thePacient.Id, GetTimeDoctor(id_Doctor));
     AddRecord(theRecord);
     return theRecord;
 }
Ejemplo n.º 24
0
        public void Save_a_copy_of_a_record_when_no_history_record_exists()
        {
            var stringDef = new FieldDescriptorRef { ItemType = typeof(string), FieldName = "StringDef" };
            var intDef = new FieldDescriptorRef { ItemType = typeof(int), FieldName = "IntDef" };

            var fieldString = new FieldValue { FieldDescriptorRef = stringDef, Value = "1" };
            var fieldInt = new FieldValue { FieldDescriptorRef = intDef, Value = 2 };

            var record = new Record
            {
                Id = "Record1",
                Fields = new List<FieldValue> { fieldString, fieldInt }
            };

            session.Store(record);
            session.SaveChanges();

            using (var newSession = ds.OpenSession())
            {
                var history = newSession.Load<RecordHistory>("recordHistory/Record1");
                //var recordInner = JsonConvert.DeserializeObject<Record>(history.Record.ToString());

                Assert.IsNotNull(history);
            }
        }
Ejemplo n.º 25
0
    public static void Master(int port, bool async, bool ack)
    {
        ReplicationMasterStorage db = StorageFactory.Instance.CreateReplicationMasterStorage(new string[] { "localhost:" + port }, async ? asyncBufSize : 0);
        db.SetProperty("perst.file.noflush", true);
        db.SetProperty("perst.replication.ack", ack);
        db.Open("master.dbs", pagePoolSize);

        FieldIndex root = (FieldIndex)db.GetRoot();
        if (root == null)
        {
            root = db.CreateFieldIndex(typeof(Record), "key", true);
            db.SetRoot(root);
        }

        long start = (DateTime.Now.Ticks - 621355968000000000) / 10000;
        for (int i = 0; i < nIterations; i++)
        {
            if (i >= nRecords)
                root.Remove(new Key(i - nRecords));

            Record rec = new Record();
            rec.key = i;
            root.Put(rec);
            if (i >= nRecords && i % transSize == 0)
                db.Commit();
        }

        db.Close();
        Console.Out.WriteLine("Elapsed time for " + nIterations + " iterations: " + ((DateTime.Now.Ticks - 621355968000000000) / 10000 - start) + " milliseconds");
    }
 public void TestClickDataGridView()
 {
     EZMoneyModel ezMoneyModel = new EZMoneyModel(); // TODO: 初始化為適當值
     StatisticPresentationModel statisticPModel = new StatisticPresentationModel(ezMoneyModel); // TODO: 初始化為適當值
     CategoryModel categoryModel = ezMoneyModel.CategoryModel;
     RecordModel recordModel = ezMoneyModel.RecordModel;
     Category category1 = new Category(CATEGORY_NAME_WORK);
     Category category2 = new Category(CATEGORY_NAME_MOVIE);
     categoryModel.AddCategory(category1);
     categoryModel.AddCategory(category2);
     DateTime date = DateTime.Now;
     Record record1 = new Record(date, category1, 100);
     Record record2 = new Record(date, category1, 200);
     Record record3 = new Record(date, category1, 300);
     Record record4 = new Record(date, category1, 400);
     Record record5 = new Record(date, category2, -100);
     Record record6 = new Record(date, category2, -200);
     Record record7 = new Record(date, category2, -300);
     recordModel.AddRecord(record1);
     recordModel.AddRecord(record2);
     recordModel.AddRecord(record3);
     recordModel.AddRecord(record4);
     recordModel.AddRecord(record5);
     recordModel.AddRecord(record6);
     recordModel.AddRecord(record7);
     statisticPModel.InitializeState();
     BindingList<Record> records = statisticPModel.ClickDataGridView(category1);
     Assert.AreEqual(4, statisticPModel.RecordList.Count);
     Assert.AreEqual(records, statisticPModel.RecordList);
     statisticPModel.ChangeRadioButton(false);
     statisticPModel.ClickDataGridView(category2);
     Assert.AreEqual(3, statisticPModel.RecordList.Count);
 }
Ejemplo n.º 27
0
 public void Add(Record record)
 {
     XElement element = new XElement("Record");
     element.Add(new XAttribute("When",record.When));
     element.Add(new XAttribute("What", record.What));
     Document.Root.Add(element);
 }
Ejemplo n.º 28
0
        public void MapToType_Should_Return_Mapped_Instance()
        {
            var expected = new Record
            {
                Prop1 = 5,
                Prop2 = "prop2",
                Prop3 = new DateTime(2000, 4, 2),
                Prop4 = true
            };

            var type = typeof(Record);
            var properties = type.GetProperties();

            var dataRecordMock = new Mock<IDataRecord>();

            var fieldNames = properties.Select(p => p.Name).ToArray();
            var fieldValues = properties.Select(p => p.GetValue(expected)).ToArray();

            dataRecordMock.Setup(r => r.FieldCount).Returns(4);

            for (int i = 0; i < fieldNames.Length; i++)
            {
                dataRecordMock.Setup(r => r.GetName(i)).Returns(fieldNames[i]);
                dataRecordMock.Setup(r => r.GetValue(i)).Returns(fieldValues[i]);
            }

            var dataRecord = dataRecordMock.Object;

            var actual = dataRecord.MapToType<Record>();

            actual.Prop1.Should().Be(expected.Prop1);
            actual.Prop2.Should().Be(expected.Prop2);
            actual.Prop3.Should().Be(expected.Prop3);
            actual.Prop4.Should().Be(expected.Prop4);
        }
Ejemplo n.º 29
0
        private void button1_Click(object sender, EventArgs e)
        {
            Record entries = new Record();

            #region Database Handling
            list.Clear();
            var id = StudentID.Text;
            // Open a connection to the database...
            MySqlConnection conn = new MySqlConnection("server=localhost;user=root;database=students;port=3306;password=;");
            conn.Open();
            // Perform the first query...
            String sql = "SELECT * FROM students.demographics WHERE id = '" + id + "'";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            MySqlDataReader sqlReader = cmd.ExecuteReader();
            #endregion

            // Parse through results and store in a list...
            while (sqlReader.Read())
            {
                entries.AddRecord(Convert.ToInt32(sqlReader.GetValue(0)), sqlReader.GetValue(1).ToString(), sqlReader.GetValue(2).ToString(), sqlReader.GetValue(3).ToString());
                // Add the record to the list of records...
                list.Add(entries);
            }

            // If we have an empty list, let the user know.
            if (list.Count == 0)
            {
                MessageBox.Show("ID returned no matches", "No results");
            }
            else
            {
                MessageBox.Show("Confirm:\nYour name is: " + entries.FirstName + " " + entries.LastName, "Confirmation", MessageBoxButtons.YesNo);
            }
        }
        public Account Parse(Record record)
        {
            DashPipeDigitParser dashPipeNumberExtractor = new DashPipeDigitParser();

            char[] line1, line2, line3;
            int initialPosition = 0;
            string recordContent = record.Content;
            int lineLength = record.LineLength;
            
            string accountNumber = "";
            for (int currentDigit = 0; currentDigit < 9; currentDigit++)
            {
                initialPosition = currentDigit * DigitWidth;
                line1 = recordContent.Substring(initialPosition, DigitWidth).ToCharArray();
                line2 = recordContent.Substring(initialPosition + lineLength, DigitWidth).ToCharArray();
                line3 = recordContent.Substring(initialPosition + (2 * lineLength), DigitWidth).ToCharArray();

                accountNumber += dashPipeNumberExtractor.Parse(line1, line2, line3);
            }

            return new Account
            {
                Number = accountNumber,
                OriginalPreParsed = recordContent
            };
        }
Ejemplo n.º 31
0
        public static void ReturnThenCallsBaseMethod(
            IFoo fake,
            IReturnValueArgumentValidationConfiguration <int> configuration,
            Exception exception)
        {
            "Given a fake"
            .x(() => fake = A.Fake <IFoo>());

            "And I configure the return value for the method"
            .x(() =>
            {
                configuration = A.CallTo(() => fake.Baz());
                configuration.Returns(42);
            });

            "When I use the same configuration object to have the method call the base method"
            .x(() => exception = Record.Exception(() => configuration.CallsBaseMethod()));

            "Then it throws an invalid operation exception"
            .x(() => exception.Should().BeAnExceptionOfType <InvalidOperationException>());
        }
Ejemplo n.º 32
0
        public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigChangedInBetween()
        {
            EventHandler <LoggingConfigurationChangedEventArgs> testChanged = null;

            try
            {
                LogManager.Configuration = null;

                var loggingConfiguration = new LoggingConfiguration();
                LogManager.Configuration = loggingConfiguration;

                var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment);
                var logFactory   = new LogFactory(configLoader);
                logFactory.Configuration = loggingConfiguration;

                var differentConfiguration = new LoggingConfiguration();

                // Verify that the random configuration change is ignored (Only the final reset is reacted upon)
                bool called = false;
                LoggingConfiguration oldConfiguration = null, newConfiguration = null;
                testChanged = (s, e) => { called = true; oldConfiguration = e.DeactivatedConfiguration; newConfiguration = e.ActivatedConfiguration; };
                LogManager.LogFactory.ConfigurationChanged += testChanged;

                var exRecorded = Record.Exception(() => configLoader.ReloadConfigOnTimer(differentConfiguration));
                Assert.Null(exRecorded);

                // Final reset clears the configuration, so it is changed to null
                LogManager.Configuration = null;
                Assert.True(called);
                Assert.Equal(loggingConfiguration, oldConfiguration);
                Assert.Null(newConfiguration);
            }
            finally
            {
                if (testChanged != null)
                {
                    LogManager.LogFactory.ConfigurationChanged -= testChanged;
                }
            }
        }
Ejemplo n.º 33
0
        public void MissingControlIdElementTest()
        {
            string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<response>
      <control>
            <status>success</status>
            <senderid>testsenderid</senderid>
            <controlid>ControlIdHere</controlid>
            <uniqueid>false</uniqueid>
            <dtdversion>3.0</dtdversion>
      </control>
      <operation>
            <authentication>
                  <status>success</status>
                  <userid>fakeuser</userid>
                  <companyid>fakecompany</companyid>
                  <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp>
            </authentication>
            <result>
                  <status>success</status>
                  <function>readByQuery</function>
                  <!--<controlid>testControlId</controlid>-->
                  <data listtype=""department"" count=""0"" totalcount=""0"" numremaining=""0"" resultId=""""/>
            </result>
      </operation>
</response>";

            Stream       stream       = new MemoryStream();
            StreamWriter streamWriter = new StreamWriter(stream);

            streamWriter.Write(xml);
            streamWriter.Flush();

            stream.Position = 0;

            var ex = Record.Exception(() => new OnlineResponse(stream));

            Assert.IsType <IntacctException>(ex);
            Assert.Equal("Result block is missing controlid element", ex.Message);
        }
Ejemplo n.º 34
0
        public override void BuildContents()
        {
            try
            {
                string spde_SalePlanDetailid = Dispatch.EitherField("spde_SalePlanDetailid");

                Record SalePlanDetail   = FindRecord("SalePlanDetail", "spde_SalePlanDetailid=" + spde_SalePlanDetailid);
                string spde_monthplanid = SalePlanDetail.GetFieldAsString("spde_monthplanid");


                int userid = CurrentUser.UserId;

                string urledit = base.UrlDotNet(base.ThisDotNetDll, "RunSalePlanDetailEdit") + "&spde_SalePlanDetailid=" + spde_SalePlanDetailid;
                Dispatch.Redirect(urledit);


                EntryGroup DecoratePersonNewEntry = new EntryGroup("SalePlanDetailNewEntry");

                DecoratePersonNewEntry.Title = "SalePlanDetail";
                DecoratePersonNewEntry.Fill(SalePlanDetail);

                VerticalPanel vpMainPanel = new VerticalPanel();
                vpMainPanel.AddAttribute("width", "100%");
                vpMainPanel.Add(DecoratePersonNewEntry);
                AddContent(vpMainPanel);

                string urldelete = base.UrlDotNet(base.ThisDotNetDll, "RunSalePlanDetailDelete") + "&spde_SalePlanDetailid=" + spde_SalePlanDetailid;
                base.AddUrlButton("Delete", "Delete.gif", urldelete);


                string url = UrlDotNet(ThisDotNetDll, "RunDataPage") + "&mopl_MonthPlanId=" + spde_monthplanid;
                url = url.Replace("Key37", "SalePlanDetailid");
                url = url + "&Key37=" + spde_monthplanid;
                this.AddUrlButton("cancel", "PrevCircle.gif", url);
            }
            catch (Exception error)
            {
                this.AddError(error.Message);
            }
        }
Ejemplo n.º 35
0
        public static Node FindTheMostNegative(List <Node> childNodeList, Dictionary <string, Record> recordListOfNodes, List <int> dependencyMatrixAsList)
        {
            Node theMostNegative     = null;
            int  yesCount            = 0;
            int  noCount             = 0;
            int  theLargestNoCount   = 0;
            int  theSmallestYesCount = 0;

            foreach (Node node in childNodeList)
            {
                String prefix         = "";
                int?   dependencyType = dependencyMatrixAsList[node.GetNodeId()];
                if ((dependencyType & DependencyType.GetKnown()) == DependencyType.GetKnown())
                {
                    prefix = "known ";
                }
                else if ((dependencyType & DependencyType.GetNot()) == DependencyType.GetNot())
                {
                    prefix = "not ";
                }
                else if ((dependencyType & (DependencyType.GetNot() | DependencyType.GetKnown())) == (DependencyType.GetNot() | DependencyType.GetKnown()))
                {
                    prefix = "not known ";
                }

                Record recordOfNode = recordListOfNodes[prefix + node.GetNodeName()];
                yesCount = recordOfNode != null?recordOfNode.GetTrueCount() : 0;

                noCount = recordOfNode != null?recordOfNode.GetFalseCount() : 0;

                if ((noCount > theLargestNoCount) || (noCount == theLargestNoCount && yesCount < theSmallestYesCount))
                {
                    theSmallestYesCount = yesCount;
                    theLargestNoCount   = noCount;
                    theMostNegative     = node;
                }
            }
            childNodeList.Remove(theMostNegative);
            return(theMostNegative);
        }
        public IActionResult Index()
        {
            AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);

            // Initialize policy.
            WritePolicy policy = new WritePolicy();

            policy.SetTimeout(50);  // 50 millisecond timeout.

            // Write single or multiple values.
            Key key  = new Key("test", "myset", "mykey");
            Bin bin1 = new Bin("name", "John");
            Bin bin2 = new Bin("age", 25);

            client.Put(policy, key, bin1, bin2);

            //Reading a Single or Multiple  Value
            Record record = client.Get(policy, key, "name");

            if (record != null)
            {
                Console.WriteLine("Got name: " + record.GetValue("name"));
            }

            Record recordMultiple = client.Get(policy, key);

            if (record != null)
            {
                foreach (KeyValuePair <string, object> entry in record.bins)
                {
                    Console.WriteLine("Name=" + entry.Key + " Value=" + entry.Value);
                }
            }


            client.Close();


            return(View());
        }
        //ERFListener
        public bool ProcessRecord(Record rec)
        {
            if (rec.Sid == BOFRecord.sid)
            {
                if (lastEOF != true)
                {
                    throw new Exception("Not yet handled embedded models");
                }
                else
                {
                    BOFRecord bof = (BOFRecord)rec;
                    switch (bof.Type)
                    {
                    case BOFRecord.TYPE_WORKBOOK:
                        currentmodel = new InternalWorkbook();
                        break;

                    case BOFRecord.TYPE_WORKSHEET:
                        currentmodel = InternalSheet.CreateSheet();
                        break;

                    default:
                        throw new Exception("Unsupported model type " + bof.GetType());
                    }
                }
            }

            if (rec.Sid == EOFRecord.sid)
            {
                lastEOF = true;
                ThrowEvent(currentmodel);
            }
            else
            {
                lastEOF = false;
            }


            return(true);
        }
Ejemplo n.º 38
0
        public void Parse_Handles_Files_With_No_Attributes()
        {
            var name = Guid.NewGuid().ToString();

            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Peer.BrowseResponse)
                      .WriteInteger(1)    // directory count
                      .WriteString(name)  // first directory name
                      .WriteInteger(1)    // first directory file count
                      .WriteByte(0x0)     // file code
                      .WriteString("foo") // name
                      .WriteLong(12)      // size
                      .WriteString("bar") // extension
                      .WriteInteger(0)    // attribute count
                      .Compress()
                      .Build();

            BrowseResponse r = default(BrowseResponse);

            var ex = Record.Exception(() => r = BrowseResponse.FromByteArray(msg));

            Assert.Null(ex);
            Assert.Equal(1, r.DirectoryCount);
            Assert.Single(r.Directories);

            var d = r.Directories.ToList();

            Assert.Equal(name, d[0].Directoryname);
            Assert.Equal(1, d[0].FileCount);
            Assert.Single(d[0].Files);

            var f = d[0].Files.ToList();

            Assert.Equal(0x0, f[0].Code);
            Assert.Equal("foo", f[0].Filename);
            Assert.Equal(12, f[0].Size);
            Assert.Equal("bar", f[0].Extension);
            Assert.Equal(0, f[0].AttributeCount);
            Assert.Empty(f[0].Attributes);
        }
        public void Execute_with_hint_should_throw_when_hint_is_not_supported(
            [Values(0, 1)] int w,
            [Values(false, true)] bool async)
        {
            var writeConcern  = new WriteConcern(w);
            var serverVersion = CoreTestConfiguration.ServerVersion;
            var requests      = new List <UpdateRequest>
            {
                new UpdateRequest(
                    UpdateType.Update,
                    new BsonDocument("x", 1),
                    new BsonDocument("$set", new BsonDocument("x", 2)))
                {
                    Hint = new BsonDocument("_id", 1)
                }
            };
            var subject = new BulkUpdateOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                WriteConcern = writeConcern
            };

            var exception = Record.Exception(() => ExecuteOperation(subject, async, useImplicitSession: true));

            if (Feature.HintForUpdateAndReplaceOperations.IsSupported(serverVersion))
            {
                exception.Should().BeNull();
            }
            else if (!writeConcern.IsAcknowledged)
            {
                exception.Should().BeOfType <NotSupportedException>();
            }
            else if (Feature.HintForUpdateAndReplaceOperations.DriverMustThrowIfNotSupported(serverVersion))
            {
                exception.Should().BeOfType <NotSupportedException>();
            }
            else
            {
                exception.Should().BeOfType <MongoCommandException>();
            }
        }
Ejemplo n.º 40
0
        public override void BuildContents()
        {
            try
            {
                string vico_VisitComponyid = Dispatch.EitherField("vico_VisitComponyid");

                Record VisitCompony     = FindRecord("VisitCompony", "vico_VisitComponyid=" + vico_VisitComponyid);
                string vico_monthplanid = VisitCompony.GetFieldAsString("vico_monthplanid");


                int userid = CurrentUser.UserId;

                string urledit = base.UrlDotNet(base.ThisDotNetDll, "RunVisitComponyEdit") + "&vico_VisitComponyid=" + vico_VisitComponyid;
                Dispatch.Redirect(urledit);


                EntryGroup VisitComponyNewEntry = new EntryGroup("VisitComponyNewEntry");

                VisitComponyNewEntry.Title = "VisitCompony";
                VisitComponyNewEntry.Fill(VisitCompony);

                VerticalPanel vpMainPanel = new VerticalPanel();
                vpMainPanel.AddAttribute("width", "100%");
                vpMainPanel.Add(VisitComponyNewEntry);
                AddContent(vpMainPanel);

                string urldelete = base.UrlDotNet(base.ThisDotNetDll, "RunVisitComponyDelete") + "&vico_VisitComponyid=" + vico_VisitComponyid;
                base.AddUrlButton("Delete", "Delete.gif", urldelete);


                string url = UrlDotNet(ThisDotNetDll, "RunDataPage") + "&mopl_MonthPlanId=" + vico_monthplanid;
                url = url.Replace("Key37", "VisitComponyid");
                url = url + "&Key37=" + vico_monthplanid;
                this.AddUrlButton("cancel", "PrevCircle.gif", url);
            }
            catch (Exception error)
            {
                this.AddError(error.Message);
            }
        }
Ejemplo n.º 41
0
        public async Task AfterFirstTryCancellationTest()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect("/test")
            .Respond(HttpStatusCode.InternalServerError);
            var client = mockHttp.ToHttpClient();

            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(500);

            var exception = await Record.ExceptionAsync(async() =>
                                                        await AsyncHelpers.GetStringWithRetries(client,
                                                                                                "https://local/test",
                                                                                                token: cts.Token));

            Assert.NotNull(exception);
            Assert.IsAssignableFrom <OperationCanceledException>(exception);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Ejemplo n.º 42
0
        private IEnumerator<T> InvokeQuery(string query)
        {
            TextWriter log = this.db.Log;
            if (log != null)
            {
                log.WriteLine();
                log.WriteLine(query);
            }

            using (View queryView = this.db.OpenView(query))
            {
                if (this.whereParameters != null && this.whereParameters.Count > 0)
                {
                    using (Record paramsRec = this.db.CreateRecord(this.whereParameters.Count))
                    {
                        for (int i = 0; i < this.whereParameters.Count; i++)
                        {
                            paramsRec[i + 1] = this.whereParameters[i];

                            if (log != null)
                            {
                                log.WriteLine("    ? = " + this.whereParameters[i]);
                            }
                        }

                        queryView.Execute(paramsRec);
                    }
                }
                else
                {
                    queryView.Execute();
                }

                foreach (Record resultRec in queryView) using (resultRec)
                {
                    yield return this.GetResult(resultRec);
                }
            }
        }
        public async Task GetDownloadPlaceInQueueAsync_Throws_OperationCanceledException_On_Cancellation(string username, string filename)
        {
            var waiter = new Mock <IWaiter>();

            waiter.Setup(m => m.Wait <PlaceInQueueResponse>(It.IsAny <WaitKey>(), null, It.IsAny <CancellationToken>()))
            .Throws(new OperationCanceledException());
            waiter.Setup(m => m.Wait <UserAddressResponse>(It.IsAny <WaitKey>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock <IMessageConnection>();

            serverConn.Setup(m => m.WriteAsync(It.IsAny <IOutgoingMessage>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            var conn = new Mock <IMessageConnection>();

            conn.Setup(m => m.WriteAsync(It.IsAny <IOutgoingMessage>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            var connManager = new Mock <IPeerConnectionManager>();

            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny <IPEndPoint>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var dict = new ConcurrentDictionary <int, TransferInternal>();
                dict.GetOrAdd(0, new TransferInternal(TransferDirection.Download, username, filename, 0));

                s.SetProperty("Downloads", dict);

                var ex = await Record.ExceptionAsync(() => s.GetDownloadPlaceInQueueAsync(username, filename));

                Assert.NotNull(ex);
                Assert.IsType <OperationCanceledException>(ex);
            }
        }
        public void Fail_InvalidProtectionLevelString(ProtectionLevel protectionLevel, int versionMajor, int versionMinor, string versionComments, int versionBuild, string description, string[] packages, string[] connectionManagers, ParameterSetupData[] parameters)
        {
            // Setup
            var projectManifestXmlDoc = new XmlDocument();
            var xml = XmlGenerators.ProjectManifestFile(protectionLevel, versionMajor, versionMinor, versionComments, versionBuild, description, packages, connectionManagers, parameters);

            projectManifestXmlDoc.LoadXml(xml);
            projectManifestXmlDoc.DocumentElement.Attributes["SSIS:ProtectionLevel"].Value = Fakes.RandomString();

            var path = Path.Combine(_workingFolder, Guid.NewGuid().ToString("N"));

            File.WriteAllText(path, projectManifestXmlDoc.OuterXml);

            // Execute
            var projectManifest = new ProjectManifest();
            var exception       = Record.Exception(() => projectManifest.Initialize(path, null));

            // Assert
            Assert.NotNull(exception);
            Assert.IsType <InvalidXmlException>(exception);
            Assert.True(exception.Message.Contains("Invalid Protection Level"));
        }
Ejemplo n.º 45
0
        public void AddFile_InvalidUIDInExistingFileShouldNotThrow()
        {
            // first create a file with invalid UIDs
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(TestData.Resolve(filename));

            var invalidDs = dicomFile.Dataset.NotValidated();

            invalidDs.AddOrUpdate(DicomTag.SOPInstanceUID, "1.2.4.100000.94849.4239.32.00121");
            invalidDs.AddOrUpdate(DicomTag.SeriesInstanceUID, "1.2.4.100000.94849.4239.32.00122");
            invalidDs.AddOrUpdate(DicomTag.StudyInstanceUID, "1.2.4.100000.94849.4239.32.00123");

            var invalidFile = new DicomFile(invalidDs);

            var ex = Record.Exception(() =>
            {
                var dicomDir = new DicomDirectory();
                dicomDir.AddFile(invalidFile, "FILE1");
            });

            Assert.Null(ex);
        }
Ejemplo n.º 46
0
        // Static Methods

        /// <summary>
        /// Creates a new monitor settings record from scratch.
        /// </summary>
        /// <returns>The new monitor settings record.</returns>
        public static MonitorSettingsRecord CreateMonitorSettingsRecord()
        {
            Guid   recordTypeTag  = Record.GetTypeAsTag(RecordType.MonitorSettings);
            Record physicalRecord = new Record(recordTypeTag);
            MonitorSettingsRecord monitorSettingsRecord = new MonitorSettingsRecord(physicalRecord);

            DateTime now = DateTime.UtcNow;

            monitorSettingsRecord.Effective      = now;
            monitorSettingsRecord.TimeInstalled  = now;
            monitorSettingsRecord.UseCalibration = false;
            monitorSettingsRecord.UseTransducer  = false;

            CollectionElement bodyElement = physicalRecord.Body.Collection;

            bodyElement.AddElement(new CollectionElement()
            {
                TagOfElement = ChannelSettingsArrayTag
            });

            return(monitorSettingsRecord);
        }
Ejemplo n.º 47
0
        public void Wait_Throws_And_Is_Dequeued_When_Thrown()
        {
            var key = new WaitKey(MessageCode.Server.Login);

            using (var waiter = new Waiter(0))
            {
                Task <object> task   = waiter.Wait <object>(key, 999999);
                object        result = null;

                waiter.Throw(key, new InvalidOperationException("error"));

                var ex = Record.Exception(() => result = task.Result);

                var waits = waiter.GetProperty <ConcurrentDictionary <WaitKey, ConcurrentQueue <PendingWait> > >("Waits");

                Assert.NotNull(ex);
                Assert.IsType <InvalidOperationException>(ex.InnerException);
                Assert.Equal("error", ex.InnerException.Message);

                Assert.False(waits.TryGetValue(key, out _));
            }
        }
Ejemplo n.º 48
0
        public void added_same_contact_info_should_throw_an_exception()
        {
            // Arrange
            var    id          = new AggregateId();
            string name        = "Ahmet";
            string surname     = "Korkmaz";
            string companyName = "CITS";
            var    createdAt   = DateTime.Now;

            string infoContent = "5453771435";

            var contact = Act(id, name, surname, companyName, createdAt);

            contact.AddContactInfo(new ContactInfo(infoContent, InfoType.PhoneNumber, DateTime.Now));

            //Act
            var exception = Record.Exception(() => contact.AddContactInfo(new ContactInfo(infoContent, InfoType.PhoneNumber, DateTime.Now)));

            //Assert
            exception.Should().NotBeNull();
            exception.Should().BeOfType <ContactInfoAlreadyExistException>();
        }
Ejemplo n.º 49
0
        public void AddContentKey_WithVariousValidData_Succeeds()
        {
            var document = new CpixDocument();

            Assert.Null(Record.Exception(() => document.ContentKeys.Add(new ContentKey
            {
                Id    = Guid.NewGuid(),
                Value = new byte[Constants.ContentKeyLengthInBytes],
            })));
            Assert.Null(Record.Exception(() => document.ContentKeys.Add(new ContentKey
            {
                Id         = Guid.NewGuid(),
                Value      = new byte[Constants.ContentKeyLengthInBytes],
                ExplicitIv = new byte[Constants.ContentKeyExplicitIvLengthInBytes]
            })));
            Assert.Null(Record.Exception(() => document.ContentKeys.Add(new ContentKey
            {
                Id         = Guid.NewGuid(),
                Value      = new byte[Constants.ContentKeyLengthInBytes],
                ExplicitIv = null
            })));
        }
Ejemplo n.º 50
0
        static void Main(string[] args)
        {
            using (RecordsRepository repository = new RecordsRepository())
            {
                foreach (var rec in repository.GetAll())
                {
                    ShowRecordInfo(rec);
                }
                Console.WriteLine(new String('=', 70));

                List <Record> records        = repository.GetAll().ToList();
                Record        recordToUpdate = records[0];
                recordToUpdate.Author = "Vasya";

                repository.Update(recordToUpdate);

                foreach (var rec in repository.GetAll())
                {
                    ShowRecordInfo(rec);
                }
                Console.WriteLine(new String('=', 70));

                repository.Delete(6);

                foreach (var rec in repository.GetAll())
                {
                    ShowRecordInfo(rec);
                }
                Console.WriteLine(new String('=', 70));

                repository.Add(new Record("Hello GlobalLogic", "Sweet kitty"));

                foreach (var rec in repository.GetAll())
                {
                    ShowRecordInfo(rec);
                }
                Console.WriteLine(new String('=', 70));
            }
        }
Ejemplo n.º 51
0
        private void parseDirectory()
        {
            WindowsInstaller.View view = null;
            try
            {
                view = database.OpenView("SELECT * FROM `Directory`");
                view.Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to query msi, " + ex.Message);
            }
            directoryTable = new Hashtable();

            Record properties = view.Fetch();

            while (properties != null)
            {
                directoryTable.Add(properties.get_StringData(1).ToLower(), new MsiDirectory(properties.get_StringData(1), properties.get_StringData(2), properties.get_StringData(3)));
                properties = view.Fetch();
            }
        }
Ejemplo n.º 52
0
        public void DisposeConcurrentMethodRunnerQueueThenEnqueueInvocation()
        {
            var methodInvocation = new MethodInvocation(1, 1, 1, "Testing", 1);

            methodInvocation.Parameters.Add("Echo Me!");

            var objectRepository = new JavascriptObjectRepository
            {
                NameConverter = null
            };

            var methodRunnerQueue = new ConcurrentMethodRunnerQueue(objectRepository);

            //Dispose
            methodRunnerQueue.Dispose();

            //Enqueue
            var ex = Record.Exception(() => methodRunnerQueue.Enqueue(methodInvocation));

            //Ensure no exception thrown
            Assert.Null(ex);
        }
Ejemplo n.º 53
0
        public void RenderSnippetAsyncWithSuccess(ISnippetRenderer renderer, AzureIntegrationServicesModel model, ProcessManager processManager, TargetResourceTemplate resourceTemplate, TargetResourceSnippet resourceSnippet, WorkflowObject workflowObject, string snippetContent, string renderedContent, Exception e)
        {
            "Given a snippet renderer"
            .x(() => renderer = new LiquidSnippetRenderer(_mockLogger.Object));

            "And a model"
            .x(() => model = _model);

            "And a process manager"
            .x(() =>
            {
                var messagingObject = model.FindMessagingObject("ContosoMessageBus:AppA:FtpTransformWorkflow");
                messagingObject.messagingObject.Should().NotBeNull().And.BeOfType(typeof(ProcessManager));
                processManager   = (ProcessManager)messagingObject.messagingObject;
                resourceTemplate = processManager.Resources.First();
                resourceSnippet  = processManager.Snippets.First();
            });

            "And a workflow object"
            .x(() =>
            {
                workflowObject = processManager.WorkflowModel.Activities.First();
            });

            "And a snippet content"
            .x(() => snippetContent = _snippetContent);

            "When rendering the snippet"
            .x(async() => e = await Record.ExceptionAsync(async() => renderedContent = await renderer.RenderSnippetAsync(snippetContent, model, processManager, resourceTemplate, resourceSnippet, workflowObject)));

            "Then the render should succeed"
            .x(() => e.Should().BeNull());

            "And the rendered content should have expected values from the model"
            .x(() =>
            {
                renderedContent.Should().NotBeNull().And.ContainAny($"StepName:_{workflowObject.Name.Replace(" ", "_", StringComparison.InvariantCulture)}").And.NotContainAny("{{").And.NotContainAny("}}");
            });
        }
Ejemplo n.º 54
0
        public void Load_SelectWithSummary_NoDoubleEnumeration()
        {
            var data = new[] {
                new { f = 1 }
            };

            var loadOptions = new SampleLoadOptions {
                Select       = new[] { "f" },
                TotalSummary = new[] {
                    new SummaryInfo {
                        Selector = "f", SummaryType = "sum"
                    }
                }
            };

            var x = Record.Exception(delegate {
                var loadResult = DataSourceLoader.Load(data, loadOptions);
                loadResult.data.Cast <object>().ToArray();
            });

            Assert.Null(x);
        }
Ejemplo n.º 55
0
        /// <summary>
        /// perform the operation in the timer tick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void t_Tick(object sender, EventArgs e)
        {
            // Give feedback about current element
            Point pt = this.gridGroupingControl1.TableControl.PointToClient(Control.MousePosition);

            if (this.gridGroupingControl1.TableControl.ClientRectangle.Contains(pt))
            {
                Element el = this.gridGroupingControl1.TableControl.PointToNestedDisplayElement(pt);
                if (el != null)
                {
                    Record r = el.GetRecord();
                    if (r != null)
                    {
                        this.lblElement.Text = r.ToString();
                    }
                    else
                    {
                        this.lblElement.Text = el.ToString();
                    }
                }
            }
        }
Ejemplo n.º 56
0
        public string ToString(uint depth)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("{0}PersistDirectoryEntry: ", Record.IndentationForDepth(depth));

            bool isFirst = true;

            foreach (uint entry in this.PersistOffsetEntries)
            {
                if (!isFirst)
                {
                    sb.Append(", ");
                }

                sb.Append(entry);

                isFirst = false;
            }

            return(sb.ToString());
        }
Ejemplo n.º 57
0
        private static void SetupRecording(Workflow workflow)
        {
            var id = Guid.NewGuid().ToString();

            var prompt = GetPromptForText(IvrOptions.NoConsultants);
            var record = new Record
            {
                OperationId                    = id,
                PlayPrompt                     = prompt,
                MaxDurationInSeconds           = 10,
                InitialSilenceTimeoutInSeconds = 5,
                MaxSilenceTimeoutInSeconds     = 2,
                PlayBeep  = true,
                StopTones = new List <char> {
                    '#'
                }
            };

            workflow.Actions = new List <ActionBase> {
                record
            };
        }
Ejemplo n.º 58
0
        public static bool ExtractBinaryToFile(Session session, string name, string path)
        {
            try
            {
                string sql = "SELECT `Binary`.`Data` FROM `Binary` WHERE `Name` = '" + name + "'";
                using (View binView = session.Database.OpenView(sql))
                {
                    binView.Execute();
                    using (Record binRecord = binView.Fetch())
                    {
                        binRecord.GetStream(1, path);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                session.Log("Extracting binary data {0} to file {1} failed: {2}", name, path, ex.Message);
                return(false);
            }
        }
Ejemplo n.º 59
0
        public void Write_Leaves_Slack_2()
        {
            var headers = new Dictionary <string, int>()
            {
                { "one", 0 },
                { "two", 1 },
                { "three", 2 }
            };

            // length = 147
            var line = new LazyCsvLine("Lorem ipsum dolor sit amet consectetur adipiscing elit.,Nunc a massa sit amet augue lacinia lacinia.,Aliquam scelerisque placerat turpis ut mollis.", headers, 0, false);

            var ex1 = Record.Exception(() => line[0] = "1");
            var ex2 = Record.Exception(() => line[1] = "2");
            var ex3 = Record.Exception(() => line[2] = "3");

            Assert.Null(ex1);
            Assert.Null(ex2);
            Assert.Null(ex3);
            Assert.Equal("1,2,3", line.ToString()); // length = 5
            Assert.Equal(142, line.Slack);          // 147 - 5
        }
Ejemplo n.º 60
0
            public void Should_Log_All_Analyzer_Errors_And_Throw()
            {
                // Given
                var fixture = new ScriptRunnerFixture();

                fixture.ScriptAnalyzer = Substitute.For <IScriptAnalyzer>();
                fixture.ScriptAnalyzer.Analyze(Arg.Any <FilePath>())
                .Returns(new ScriptAnalyzerResult(new ScriptInformation(fixture.Script), new List <string>(), new List <ScriptAnalyzerError>
                {
                    new ScriptAnalyzerError("/Working/script1.cake", 2, "Error in script 1"),
                    new ScriptAnalyzerError("/Working/script2.cake", 7, "Error in script 2")
                }));
                var runner = fixture.CreateScriptRunner();

                // When
                var exception = Record.Exception(() => runner.Run(fixture.Host, fixture.Script));

                // Then
                AssertEx.IsCakeException(exception, "Errors occurred while analyzing script.");
                Assert.Contains(fixture.Log.Entries, x => x.Level == LogLevel.Error && x.Message == "/Working/script1.cake:2: Error in script 1");
                Assert.Contains(fixture.Log.Entries, x => x.Level == LogLevel.Error && x.Message == "/Working/script2.cake:7: Error in script 2");
            }