private static void MapRow(DbDataReader dr, int numberOfColumns, ResultSet table) {
			var row = new object[numberOfColumns];
			for (int i = 0; i < numberOfColumns; i++) {
				row[i] = (DBNull.Value.Equals(dr[i])) ? null : dr[i];
			}
			table.AddRow(row);
		}
        public JsonResult DataHandler(DTParameters param)
        {
            try
            {
                var dtsource = new List<Customer>();
                using (dataSetEntities dc = new dataSetEntities())
                {
                    dtsource = dc.Customers.ToList();
                }

                List<String> columnSearch = new List<string>();

                foreach (var col in param.Columns)
                {
                    columnSearch.Add(col.Search.Value);
                }

                List<Customer> data = new ResultSet().GetResult(param.Search.Value, param.SortOrder, param.Start, param.Length, dtsource, columnSearch);
                int count = new ResultSet().Count(param.Search.Value, dtsource, columnSearch);
                DTResult<Customer> result = new DTResult<Customer>
                {
                    draw = param.Draw,
                    data = data,
                    recordsFiltered = count,
                    recordsTotal = count
                };
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new { error = ex.Message });
            }
        }
Ejemplo n.º 3
0
 internal DataReader(ResultSet resultSet)
 {
     ResultIndex = -1;
     m_resultSet = resultSet;
     NextResult();
     
 }
Ejemplo n.º 4
0
        private ResultSet reportedResultSet; // Stores the result set that is reported by this report

        #endregion Fields

        #region Constructors

        // Create a new report form with a Variable Number of column names
        public ReportForm(ResultSet reportedResults, params string[] names)
        {
            InitializeComponent();
            reportedResultSet = reportedResults; // Store the result set
            columnNames = names; // Store the column names
            CreateTable(); // Create the table from the column names and the result set
        }
Ejemplo n.º 5
0
		public void Constructor_ResultsModifiedAfter_ResultSetNotModified()
		{
			ResultSet<PalasoTestItem> resultSet = new ResultSet<PalasoTestItem>(_dataMapper, _results);
			_results.Add(new RecordToken<PalasoTestItem>(_dataMapper, _resultSet[2].Id));
			Assert.AreNotEqual(_results.Count, resultSet.Count);

		}
Ejemplo n.º 6
0
        private void ChangeBooking(string customerName)
        {
            bookingResults = new ResultSet(dal.GetDataReader("BookingTable", "CustomerID = " + CustomerIDComboBox.Text));

            ClearExpensesLabels(); // Remove any labels explaining expenses

            //Obtain prices from all aspect of the database. Calculating price through C# prevents data duplication / redundancy
            float equipmentLoansPrice = dal.ReadPrice("EquipmentLoansTable JOIN EquipmentTable ON EquipmentLoansTable.EquipmentID = EquipmentTable.EquipmentID", "CustomerID = " + CustomerIDComboBox.Text, "(RentalPrice * Duration)");
            float sightseeingBusPrice = dal.ReadPrice("[Customer-BusTripTable]", "CustomerID = " + CustomerIDComboBox.Text, "Price");
            float cyclingTourPrice = dal.ReadPrice("[Customer-CyclingTourTable]", "CustomerID = " + CustomerIDComboBox.Text, "Price");
            float cyclingLessonPrice = dal.ReadPrice("[Child-CyclingLessonTable] JOIN [ChildTable] ON [Child-CyclingLessonTable].ChildID = ChildTable.ChildID", "ChildTable.CustomerID = " + CustomerIDComboBox.Text, "[Child-CyclingLessonTable].Price");
            float cyclingCertificationPrice = dal.ReadPrice("CertificationBookingsTable JOIN ChildTable ON CertificationBookingsTable.ChildID = ChildTable.ChildID", "ChildTable.CustomerID = " + CustomerIDComboBox.Text, "[CertificationBookingsTable].Price");
            dal.OpenConnection(); // Connection is opened and closed manually for a GetCount call because this can save on lag caused by connecting to database.
            float cyclingAwardPrice = dal.GetCount("[CyclingAwardsTable] JOIN ChildTable ON CyclingAwardsTable.ChildID = ChildTable.ChildID", "CustomerID = " + CustomerIDComboBox.Text) * 20.0f;
            dal.CloseConnection();

            // For each expense, if it is relevant display a label explaining the expense
            if (equipmentLoansPrice > 0)
            {
                AddExpensesLabel("Charge for Hiring Equipment: £" + Program.ToCurrency(equipmentLoansPrice));
            }
            if (sightseeingBusPrice > 0)
            {
                AddExpensesLabel("Charge for Sightseeing Trip(s): £" + Program.ToCurrency(sightseeingBusPrice));
            }
            if (cyclingTourPrice > 0)
            {
                AddExpensesLabel("Charge for Cycling Tour(s): £" + Program.ToCurrency(cyclingTourPrice));
            }
            if (cyclingLessonPrice > 0)
            {
                AddExpensesLabel("Charge for Cycling Lesson(s): £" + Program.ToCurrency(cyclingLessonPrice));
            }
            if (cyclingCertificationPrice > 0)
            {
                AddExpensesLabel("Charge for Cycling Certification(s): £" + Program.ToCurrency(cyclingCertificationPrice));
            }
            if (cyclingAwardPrice > 0)
            {
                AddExpensesLabel("Charge for Cycling Award(s): £" + Program.ToCurrency(cyclingAwardPrice));
            }

            //Set the chosen customer name and id straight from the SuggestiveTextBox and ComboBox
            CustomerNameLabel.Text = "Customer Name: " + customerName;
            CustomerIDLabel.Text = "Customer ID: " + CustomerIDComboBox.Text + "";
            try
            {
                BookingIDLabel.Text = "Booking ID: " + bookingResults.GetData<int>(0, 0); // Retrieve and display the bookingID
            }
            catch (Exception e)
            {
                Console.WriteLine("No data found for this customer. Check "); // Should never be called.
            }

            // Sum all of the prices to give a total price
            float totalPrice = equipmentLoansPrice + sightseeingBusPrice + cyclingTourPrice + cyclingLessonPrice + cyclingCertificationPrice + cyclingAwardPrice;

            TotalPriceLabel.Text = "Total Price: £" + Program.ToCurrency(totalPrice);
        }
Ejemplo n.º 7
0
 internal static MessagePagingInfo FromResultSet(ResultSet resultSet)
 {
     return new MessagePagingInfo
         {
             PagingCookig = resultSet.PagingCookie,
             HasMoreRecords = Convert.ToBoolean(resultSet.MoreRecords, CultureInfo.InvariantCulture)
         };
 }
Ejemplo n.º 8
0
 private void CampingBookingsHistoryReport_Click(object sender, EventArgs e)
 {
     ResultSet rs = new ResultSet(dal.GetDataReader("BookingHistoryTable JOIN CustomerTable ON BookingHistoryTable.CustomerID = CustomerTable.CustomerID", "1=1", "BookingID, CustomerTable.CustomerID, CustomerName, StartDate, GroupSize, PricePerNight, TotalPrice, NightsStayed"));
     ReportForm reportForm = new ReportForm(rs, "Booking ID", "Customer ID", "Customer Name", "Start Date", "Group Size", "Price per Night", "Total Price", "Nights Stayed");
     reportForm.SetFormTitle("Booking History Report");
     reportForm.SetDateFilterColumn(3);
     OpenForm(reportForm);
 }
Ejemplo n.º 9
0
 // When the cancel booking button is pressed
 private void CancelBookingButton_Click(object sender, EventArgs e)
 {
     bookingDAL.MoveBookingToHistory(bookingID); // Move the cancelled booking to history
     bookingResults = UpdateResultSet("[dbo].[BookingTable]");
     UpdateDisplayedResults(UpdateResultSet("BookingTable JOIN CustomerTable ON BookingTable.CustomerID = CustomerTable.CustomerID", "1=1", "BookingID, BookingTable.CustomerID, CustomerName, StartDate, NightsStayed, PricePerNight, TotalPrice")); // Display all of the booking results as we are not yet filtering them
     CustomerNameSuggestingTextBox.Text = ""; // Reset the display to show all booking still not cancelled
     ShowRecord(0);
 }
Ejemplo n.º 10
0
        public void Yahoo_PlaceFinder_ResultSetQualityCategory_ShouldBeArea_WhenQualityIsLessThan70()
        {
            var model = new ResultSet
            {
                Quality = 69,
            };

            model.QualityCategory().ShouldEqual(QualityCategory.Area);
        }
		public static ResultSet Map(DbDataReader dr) {
			int numberOfColumns = dr.FieldCount;
			string[] colNames = GetColumnNames(dr, numberOfColumns);
			var table = new ResultSet(colNames);
			while (dr.Read()) {
				MapRow(dr, numberOfColumns, table);
			}
			return table;
		}
Ejemplo n.º 12
0
 public DataReader ExecuteReader()
 {
     var cursor = MongoConnection.MongoDatabase.GetCollection(CollectionName).FindAll();            
     Result result = new Result(cursor);
     ResultSet resultSet = new ResultSet();
     resultSet.Add(result);
     DataReader reader = new DataReader(resultSet);
     return reader;
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Create a new Item with a result set from the database
 /// </summary>
 /// <param name="set"></param>
 public Item(ResultSet set)
 {
     this.Id = set.Read<Int32>("ItemId");
     this.CreatorId = set.Read<Int32>("CreatorId");
     this.Slot = (Byte)set.Read<Int32>("Slot");
     this.Quantity = (UInt32)set.Read<Int32>("Quantity");
     this.Equiped = set.Read<Boolean>("Equiped");
     Attributes = new Byte[17];
     Attributes[0] = 0x40;
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Gets the result set as list of string arrays.
 /// </summary>
 /// <param name="resultSet">The result set to convert to a string array list.</param>
 /// <returns>A list of string arrays representing the result set.</returns>
 public static List<String[]> ResultSetToStringArrayList(ResultSet resultSet) {
   List<string[]> stringArrayList = new List<string[]>();
   stringArrayList.Add(GetColumnLabels(resultSet));
   if (resultSet.rows != null) {
     foreach (Row row in resultSet.rows) {
       stringArrayList.Add(GetRowStringValues(row));
     }
   }
   return stringArrayList;
 }
Ejemplo n.º 15
0
		public void Setup()
		{
			_repository = new MemoryRepository<TestItem>();
			PopulateRepositoryWithItemsForQuerying(_repository);
			_queryToCache = new QueryAdapter<TestItem>();
			_queryToCache.Show("StoredString");
			_results = _repository.GetItemsMatching(_queryToCache);
			_sortDefinitions = new SortDefinition[1];
			_sortDefinitions[0] = new SortDefinition("StoredString", Comparer<string>.Default);
		}
        public ResultSet BuildResultSet(SqlQuery query, IEnumerable<Entity> entities)
        {
            var entityType = Type.GetType(String.Format("{0}.{1}", typeof(Entity).Namespace, query.Entity), true, true);
            var columnHeaders = GetColumnHeaders(query, entityType);

            var set = new ResultSet(columnHeaders);
            foreach (var entity in entities)
                set.Add(BuildResultSetRow(columnHeaders, entity).ToList());

            return set;
        }
Ejemplo n.º 17
0
      internal void Handle(GetTrafficEvents input) {
         var output = new ResultSet<TrafficEvent>();

         BplCollection<TrafficEventInfo> dbEvents;

         using (var dbConn = DatabaseManager.DbConn()) {
            if ((input.Region == null) || (input.Region.IsEmpty)) {
               dbEvents = dbConn.ExecuteBpl(new TrafficEventGetByOperator { Operator = input.Operator });
            } else {
               dbEvents = dbConn.ExecuteBpl(
                  new TrafficEventGetByOperatorRegion {
                     Operator = input.Operator,
                     North = input.Region.North,
                     South = input.Region.South,
                     West = input.Region.West,
                     East = input.Region.East
                  });
            }

            foreach (var ei in dbEvents) {
               var oe = new Mpcr.Model.Vehicles.TrafficEvent();

               oe.Id = ei.EventId;
               oe.Codes = ei.Codes;
               oe.Direction = ei.Direction;
               oe.Extent = ei.Extent;
               oe.IsTwoWay = ei.IsTwoWay;

               oe.Origin = new TrafficLocation();
               oe.Origin.LocationCode = ei.OriginLocationCode;
               oe.Origin.CountryCode = ei.OriginCountryCode;
               oe.Origin.LocationTableNumber = ei.OriginLocationTableNumber;
               oe.Origin.Location = ei.OriginLocation;

               if (ei.DestinationLocation != ei.OriginLocation) {
                  oe.Destination = new TrafficLocation();
                  oe.Destination.LocationCode = ei.DestinationLocationCode;
                  oe.Destination.CountryCode = ei.DestinationCountryCode;
                  oe.Destination.LocationTableNumber = ei.DestinationLocationTableNumber;
                  oe.Destination.Location = ei.DestinationLocation;
               }

               oe.ApproximatedDelay = ei.ApproximatedDelay;
               oe.ApproximatedSpeed = ei.ApproximatedSpeed;
               oe.LastUpdate = ei.LastUpdate.DateTime;
               oe.Length = ei.Length;
               oe.Load = ei.Load;

               output.result.Add(oe);
            }
         }

         Reply(output);
      }
Ejemplo n.º 18
0
      internal void Handle(GetDiagnosticsTasks input) {
         var result = new ResultSet<DiagnosticsTask>();

         using (var dbConn = DatabaseManager.DbConn()) {
            var dtasks = dbConn.ExecuteBpl(new DiagnosticsTaskDeviceGetByDeviceId { DeviceId = input.DeviceId });
            foreach (var dtask in dtasks) {
               result.result.Add(dtask.ToDiagnosticsTask());
            }
         }

         Reply(result.result);
      }
Ejemplo n.º 19
0
 void Fill(ResultSet resultSet)
 {
     foreach (var result in resultSet.Results)
     {
         if ((result.SdkMessageId != Guid.Empty) && !MessageCollection.ContainsKey(result.SdkMessageId))
         {
             var message = new SdkMessage(result.SdkMessageId, result.Name, result.IsPrivate);
             MessageCollection.Add(result.SdkMessageId, message);
         }
         MessageCollection[result.SdkMessageId].Fill(result);
     }
 }
Ejemplo n.º 20
0
		public void Setup()
		{
			_repository = new MemoryRepository<TestItem>();
			_results = new List<RecordToken<TestItem>>();

			_results.Add(new RecordToken<TestItem>(_repository, new TestRepositoryId(8)));
			_results.Add(new RecordToken<TestItem>(_repository, new TestRepositoryId(12)));
			_results.Add(new RecordToken<TestItem>(_repository, new TestRepositoryId(1)));
			_results.Add(new RecordToken<TestItem>(_repository, new TestRepositoryId(3)));

			_resultSet = new ResultSet<TestItem>(_repository, _results);
		}
Ejemplo n.º 21
0
		public void Setup()
		{
			_dataMapper = new MemoryDataMapper<PalasoTestItem>();
			_results = new List<RecordToken<PalasoTestItem>>();

			_results.Add(new RecordToken<PalasoTestItem>(_dataMapper, new TestRepositoryId(8)));
			_results.Add(new RecordToken<PalasoTestItem>(_dataMapper, new TestRepositoryId(12)));
			_results.Add(new RecordToken<PalasoTestItem>(_dataMapper, new TestRepositoryId(1)));
			_results.Add(new RecordToken<PalasoTestItem>(_dataMapper, new TestRepositoryId(3)));

			_resultSet = new ResultSet<PalasoTestItem>(_dataMapper, _results);
		}
Ejemplo n.º 22
0
        // Schedules a new Cycling Certification for a child
        public void AddNewCyclingCertification(string childName, int customerID, string level, float price)
        {
            // Store the specified child's details
            string query = string.Format("CustomerID = {0} AND ChildName = '{1}'", customerID, childName);
            ResultSet childrenResults = new ResultSet(GetDataReader("[ChildTable]", query, "ChildID"));
            int childID = childrenResults.GetData<int>(0, 0);

            OpenConnection();
            int certBookingID = GetCount("[CertificationBookingsTable]"); // Get the next available ID for a Certification Booking
            CloseConnection();

            // Add the record to the CertificationBookingsTable
            string command = string.Format("INSERT INTO [CertificationBookingsTable] VALUES ({0}, {1}, '{2}', {3})", certBookingID, childID, level, price);
            UpdateByQuery(command);
        }
Ejemplo n.º 23
0
 // Returns the number of bicycles that have not yet been hired for a specific lesson
 public int GetBicyclesLeft(DateTime date, string timeSlot)
 {
     // Run a query to find the number of bicylces left for the lesson at the specified date and time slot
     string query = string.Format("[Date] = '{0}' AND TimeSlot = '{1}'", string.Format("{0:MM-dd-yy}", date), timeSlot);
     ResultSet tourResults = new ResultSet(GetDataReader("[CyclingTourTable]", query, "NumberBicycles"));
     CloseConnection();
     if (tourResults.GetSize() == 0)
     {
         return 15;
     }
     else
     {
         return (15 - tourResults.GetData<int>(0, 0));
     }
 }
Ejemplo n.º 24
0
		public void Constructor_HasNoDuplicate_OrderRetained()
		{
			List<RecordToken<PalasoTestItem>> results = new List<RecordToken<PalasoTestItem>>();

			results.Add(new RecordToken<PalasoTestItem>(_dataMapper, new TestRepositoryId(8)));
			results.Add(new RecordToken<PalasoTestItem>(_dataMapper, new TestRepositoryId(2)));

			ResultSet<PalasoTestItem> resultSet = new ResultSet<PalasoTestItem>(_dataMapper, results);
			Assert.AreEqual(2, resultSet.Count);

			int i = 0;
			foreach (RecordToken<PalasoTestItem> token in resultSet)
			{
				Assert.AreEqual(results[i], token);
				++i;
			}
		}
Ejemplo n.º 25
0
        // Used to get a dictionary of timetable details from the database
        public Dictionary<string, TimetableDetails> GetTimetableDetails(DateTime date)
        {
            string query = string.Format("Date = '{0}'", string.Format("{0:MM-dd-yy}", date));
            ResultSet timetableResults = new ResultSet(GetDataReader("[BusTripTable]", query)); // Search the database for all details relating to the specified date
            CloseConnection();

            Dictionary<string, TimetableDetails> details = new Dictionary<string, TimetableDetails>();

            string[] timeSlots = { "8.30 - 10.15", "2.00 - 3.45 ", "10.45 - 1.45", "4.00 - 7.00 " };

            for(int i = 0; i < timeSlots.Length; i++){ // Go through each possible timeslot and add the details about it to the details Dictionary

                TimetableDetails timetableDetails = new TimetableDetails();

                int row = timetableResults.FindRow<string>(2, timeSlots[i]); // Find the row which stores the data for this time slot

                if (row == -1) // If there is no-one registered for this time slot use the small bus
                {
                    timetableDetails.busUsed = "9 Person";
                    timetableDetails.seatsLeft = 24;
                    details.Add(timeSlots[i], timetableDetails);
                    continue;
                }

                if(timetableResults.GetData<int>(4, row) < 9) // If there are less than 9 people registered for this bus use the small bus
                {
                    timetableDetails.busUsed = "9 Person";
                }
                else if (timetableResults.GetData<int>(4, row) < 17) // If there are >= 9 and < 17 people use the bigger bus
                {
                    timetableDetails.busUsed = "17 Person";
                }
                else // If there are >= 17 people use both busses
                {
                    timetableDetails.busUsed = "Both";
                }

                timetableDetails.seatsLeft = 24 - timetableResults.GetData<int>(4, row); // calculate the seats left now that we have found the number of seats

                details.Add(timeSlots[i], timetableDetails); // Add these details to the dictionary

            } // End of the loop through all of the time slots

            return details;
        }
Ejemplo n.º 26
0
        public void Yahoo_PlaceFinder_ResultSet_ShouldImplementGenericIEnumerable()
        {
            var model = new ResultSet
            {
                ResultsList = new List<Result>
                {
                    new Result(), new Result(), new Result(),
                },
            };

            model.ShouldImplement(typeof(IEnumerable<Result>));
            model.GetEnumerator().ShouldNotBeNull();
            ((IEnumerable)model).GetEnumerator().ShouldNotBeNull();
            foreach (var item in model)
            {
                item.ShouldNotBeNull();
            }
        }
        public AwardCertificationForm()
        {
            InitializeComponent();

            customerResults = new ResultSet(cyclingDAL.GetDataReader("[CustomerTable]"));

            // Set the suggestions of the SuggestingTextBox to the Customer Names and add a Suggestion clicked listener to call SuggestionChosen
            CustomerNameSuggestingTextBox.SetSuggestions(customerResults.GetColumnData(1));
            CustomerNameSuggestingTextBox.SuggestionClickedEvent += new SuggestingTextBox.SuggestionClickedEventArgs(SuggestionChosen);
            CustomerNameSuggestingTextBox.textBox.TextChanged += new EventHandler(CustomerNameSuggestingTextBox_TextChanged);

            // Read and store the displayedResultSet data
            displayedResults = UpdateResultSet("CertificationBookingsTable JOIN ChildTable ON CertificationBookingsTable.ChildID = ChildTable.ChildID JOIN CustomerTable ON ChildTable.CustomerID = CustomerTable.CustomerID ", "1=1", "[CustomerTable].CustomerID, CustomerName, [ChildTable].ChildID, ChildName, CertificationBookingID, Level, Price");

            if (displayedResults.GetSize() > 0)
            {
                ShowRecord(0); // Shows the first record of this ResultSet.
            }
        }
Ejemplo n.º 28
0
        bool settingSuggestedText = false; // Used to prevent the built in WinForms event call of TextChanged changing the Displayed Results

        #endregion Fields

        #region Constructors

        public CancelBookingForm()
        {
            InitializeComponent();

            bookingResults = UpdateResultSet("[dbo].[BookingTable]"); // Extract data from different tables and save them as ResultSets
            customerResults = UpdateResultSet("[dbo].[CustomerTable]");
            campingResults = UpdateResultSet("[dbo].[CampingBookingsTable]");
            pitchResults = UpdateResultSet("[dbo].[PitchBookingsTable]");

            displayedResultSet = UpdateResultSet("BookingTable JOIN CustomerTable ON BookingTable.CustomerID = CustomerTable.CustomerID", "1=1", "BookingID, BookingTable.CustomerID, CustomerName, StartDate, NightsStayed, PricePerNight, TotalPrice"); // Display all of the booking results as we are not yet filtering them

            CustomerNameSuggestingTextBox.SetSuggestions(customerResults.GetColumnData(1)); // Set the customer names as the suggestions for the SuggestingTextBox
            CustomerNameSuggestingTextBox.SuggestionClickedEvent += new SuggestingTextBox.SuggestionClickedEventArgs(CustomerNameSuggestingTextBox_SuggestionChosen); // When a suggestion is chosen run the CustomerNameSuggestingTextBox_SuggestionChosen method
            CustomerNameSuggestingTextBox.textBox.TextChanged += new EventHandler(CustomerNameSuggestingTextBox_TextChanged);

            if (customerResults.GetSize() > 0)
            {
                ShowRecord(0); // Shows the first record of this ResultSet. Does not depend on a bookingID
            }
        }
Ejemplo n.º 29
0
        public ReturnEquipmentForm()
        {
            InitializeComponent();

            equipmentLoansResults = UpdateResultSet("[dbo].[EquipmentLoansTable]"); // Read and store the data from the EquipmentLoansTable

            // Read and store the displayedResultSet data
            displayedResultSet = UpdateResultSet("[dbo].[EquipmentLoansTable] JOIN [dbo].[CustomerTable] ON EquipmentLoansTable.CustomerID = CustomerTable.CustomerID JOIN [dbo].[EquipmentTable] ON EquipmentLoansTable.EquipmentID = EquipmentTable.EquipmentID", "1=1", "EquipmentLoanID, EquipmentLoansTable.EquipmentID, EquipmentName, CustomerTable.CustomerID, CustomerName, StartDate, Duration, Quantity, RentalPrice, StockLevel");

            originalDisplayedResults = displayedResultSet;

            // Set the suggestions of the SuggestingTextBox to the Customer Names and add a Suggestion clicked listener to call CustomerNameSuggestingTextBox_SuggestionChosen
            CustomerNameSuggestingTextBox.SetSuggestions(displayedResultSet.GetColumnData(4));
            CustomerNameSuggestingTextBox.SuggestionClickedEvent += new SuggestingTextBox.SuggestionClickedEventArgs(CustomerNameSuggestingTextBox_SuggestionChosen);
            CustomerNameSuggestingTextBox.textBox.TextChanged += new EventHandler(CustomerNameSuggestingTextBox_TextChanged);

            if (equipmentLoansResults.GetSize() > 0)
            {
                ShowRecord(0); // Shows the first record of this ResultSet.
            }
        }
Ejemplo n.º 30
0
        public void VerifyQueries()
        {
            bool ErrorOccurred = false;

            QueryHelper <object, object> qh = QueryHelper <object, object> .GetHelper(CacheHelper.DCache);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries)
            {
                if (qrystr.Category == QueryCategory.Unsupported)
                {
                    Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
                    qryIdx++;
                    continue;
                }

                if (qryIdx == 2 || qryIdx == 3 || qryIdx == 4)
                {
                    Util.Log("Skipping query index {0} for Pdx because it is function type.", qryIdx);
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating query index {0}. Query string {1}", qryIdx, qrystr.Query);

                Query <object> query = qs.NewQuery <object>(qrystr.Query);

                ISelectResults <object> results = query.Execute();

                int expectedRowCount = qh.IsExpectedRowsConstantRS(qryIdx) ?
                                       QueryStatics.ResultSetRowCounts[qryIdx] : QueryStatics.ResultSetRowCounts[qryIdx] * qh.PortfolioNumSets;

                if (!qh.VerifyRS(results, expectedRowCount))
                {
                    ErrorOccurred = true;
                    Util.Log("Query verify failed for query index {0}.", qryIdx);
                    qryIdx++;
                    continue;
                }

                ResultSet <object> rs = results as ResultSet <object>;

                foreach (object item in rs)
                {
                    PortfolioPdx port = item as PortfolioPdx;
                    if (port == null)
                    {
                        PositionPdx pos = item as PositionPdx;
                        if (pos == null)
                        {
                            string cs = item.ToString();
                            if (cs == null)
                            {
                                Util.Log("Query got other/unknown object.");
                            }
                            else
                            {
                                Util.Log("Query got string : {0}.", cs);
                            }
                        }
                        else
                        {
                            Util.Log("Query got Position object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding);
                        }
                    }
                    else
                    {
                        Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
                    }
                }

                qryIdx++;
            }

            Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
        }
Ejemplo n.º 31
0
 public override void SignResult(ResultSet rs)
 {
     rs.signature = "M.A.C.D. Trade";
 }
Ejemplo n.º 32
0
        //#EXPORT EXCEL
        public void ExportExcel()
        {
            if ((sesion = SessionDB.start(Request, Response, false, db)) == null)
            {
                return;
            }

            try
            {
                System.Data.DataTable tbl = new System.Data.DataTable();
                tbl.Columns.Add("IDSIU", typeof(string));
                tbl.Columns.Add("Nombre", typeof(string));
                tbl.Columns.Add("Apellidos", typeof(string));
                tbl.Columns.Add("Origen de pago", typeof(string));
                tbl.Columns.Add("Campus", typeof(string));
                tbl.Columns.Add("Periodo", typeof(string));
                tbl.Columns.Add("Contrato", typeof(string));
                tbl.Columns.Add("Concepto", typeof(string));
                tbl.Columns.Add("Monto", typeof(string));
                tbl.Columns.Add("IVA", typeof(string));
                tbl.Columns.Add("IVA Ret", typeof(string));
                tbl.Columns.Add("ISR Ret", typeof(string));
                tbl.Columns.Add("Fecha Pago", typeof(string));
                tbl.Columns.Add("Cta Contable", typeof(string));
                tbl.Columns.Add("Tipo de pago", typeof(string));

                List <string> filtros = new List <string>();

                if (Request.Params["sedes"] != "" && Request.Params["sedes"] != null)
                {
                    filtros.Add("CVE_SEDE = '" + Request.Params["sedes"] + "'");
                }

                if (Request.Params["periodos"] != "" && Request.Params["periodos"] != null)
                {
                    filtros.Add("PERIODO = '" + Request.Params["periodos"] + "'");
                }

                if (Request.Params["tipospago"] != "" && Request.Params["tipospago"] != null)
                {
                    filtros.Add("CVE_TIPODEPAGO = '" + Request.Params["tipospago"] + "'");
                }

                if (Request.Params["escuelas"] != "" && Request.Params["escuelas"] != null)
                {
                    filtros.Add("CVE_ESCUELA = '" + Request.Params["escuelas"] + "'");
                }

                string conditions = string.Join <string>(" AND ", filtros.ToArray());

                string union = "";
                if (conditions.Length != 0)
                {
                    union = " WHERE ";
                }

                ResultSet res = db.getTable("SELECT * FROM VESTADO_CUENTA_DETALLE " + union + " " + conditions);

                while (res.Next())
                {
                    // Here we add five DataRows.
                    tbl.Rows.Add(res.Get("IDSIU"), res.Get("NOMBRES")
                                 , res.Get("APELLIDOS"), res.Get("CVE_ORIGENPAGO")
                                 , res.Get("CVE_SEDE"), res.Get("PERIODO")
                                 , res.Get("ID_ESQUEMA"), res.Get("CONCEPTO"), res.Get("MONTO")
                                 , res.Get("MONTO_IVA"), res.Get("MONTO_IVARET")
                                 , res.Get("MONTO_ISRRET"), res.Get("FECHAPAGO")
                                 , res.Get("CUENTACONTABLE")
                                 , res.Get("TIPODEPAGO"));
                }

                using (ExcelPackage pck = new ExcelPackage())
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Detalle de Pagos");

                    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                    ws.Cells["A1"].LoadFromDataTable(tbl, true);
                    ws.Cells["A1:O1"].AutoFitColumns();

                    //Format the header for column 1-3
                    using (ExcelRange rng = ws.Cells["A1:O1"])
                    {
                        rng.Style.Font.Bold        = true;
                        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(Color.White);
                    }

                    //Example how to Format Column 1 as numeric
                    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
                    {
                        col.Style.Numberformat.Format = "#,##0.00";
                        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                    }

                    //Write it back to the client
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=DetallePagos.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                }

                Log.write(this, "Start", LOG.CONSULTA, "Exporta Excel Detalle Pagos", sesion);
            }
            catch (Exception e)
            {
                ViewBag.Notification = Notification.Error(e.Message);
                Log.write(this, "Start", LOG.ERROR, "Exporta Excel Detalle Pagos" + e.Message, sesion);
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 値セット.
        /// </summary>
        public void Set(int index, ResultSet resultSet)
        {
            if (null == resultSet)
            {
                return;
            }

            // 結果セットを反映.
            this.ResultSet = resultSet;

            // ステータス.
            this.lblStatus.Text = "({0}) 防:{1}".Fmt(index, this.GetStatusText());

            var ctrolColor    = Color.White;
            var abstractColor = Color.Gainsboro;

            // 武器.
            this.lblWepon.Text = resultSet.Wepon.GetText();

            // 防具.
            this.lblHead.Tag  = resultSet.Head;
            this.lblHead.Text = resultSet.Head.GetText();
            this.toolTipArmor.SetToolTip(this.lblHead, this.GetArmorToolTipText(resultSet.Head));
            this.lblHead.BackColor = resultSet.Head.IsAbstract()
                ? abstractColor
                : ctrolColor;
            this.lblBody.Tag  = resultSet.Body;
            this.lblBody.Text = resultSet.Body.GetText();
            this.toolTipArmor.SetToolTip(this.lblBody, this.GetArmorToolTipText(resultSet.Body));
            this.lblBody.BackColor = resultSet.Body.IsAbstract()
                ? abstractColor
                : ctrolColor;
            this.lblArm.Tag  = resultSet.Arm;
            this.lblArm.Text = resultSet.Arm.GetText();
            this.toolTipArmor.SetToolTip(this.lblArm, this.GetArmorToolTipText(resultSet.Arm));
            this.lblArm.BackColor = resultSet.Arm.IsAbstract()
                ? abstractColor
                : ctrolColor;
            this.lblWaist.Tag  = resultSet.Waist;
            this.lblWaist.Text = resultSet.Waist.GetText();
            this.toolTipArmor.SetToolTip(this.lblWaist, this.GetArmorToolTipText(resultSet.Waist));
            this.lblWaist.BackColor = resultSet.Waist.IsAbstract()
                ? abstractColor
                : ctrolColor;
            this.lblLeg.Tag  = resultSet.Leg;
            this.lblLeg.Text = resultSet.Leg.GetText();
            this.toolTipArmor.SetToolTip(this.lblLeg, this.GetArmorToolTipText(resultSet.Leg));
            this.lblLeg.BackColor = resultSet.Leg.IsAbstract()
                ? abstractColor
                : ctrolColor;

            // 護石.
            this.lblAmulet.Text = resultSet.Amulet.GetText();

            // 空きスロット.
            this.lblSlot.Text = "空: {0}".Fmt(this.GetBlankSlotText());

            // 装飾品
            this.txtbAccessory.Text = this.GetAccessoryText();

            // スキル.
            this.txtbSkill.Text = this.GetSkillText();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Gets a ResultSet containing all entries sorted by definition and gloss. It will return both the definition
        /// and the gloss if both exist and are different.
        /// Use "Form" to access the Definition/Gloss in RecordToken.
        /// </summary>
        /// <param name="writingSystem"></param>
        /// <returns>Definition and gloss in "Form" field of RecordToken</returns>
        public ResultSet <LexEntry> GetAllEntriesSortedByDefinitionOrGloss(IWritingSystemDefinition writingSystem)
        {
            if (writingSystem == null)
            {
                throw new ArgumentNullException("writingSystem");
            }

            string cacheName = String.Format("SortByDefinition_{0}", writingSystem.Id);

            if (_caches[cacheName] == null)
            {
                DelegateQuery <LexEntry> definitionQuery = new DelegateQuery <LexEntry>(
                    delegate(LexEntry entryToQuery)
                {
                    List <IDictionary <string, object> > fieldsandValuesForRecordTokens = new List <IDictionary <string, object> >();

                    int senseNumber = 0;
                    foreach (LexSense sense in entryToQuery.Senses)
                    {
                        List <string> definitions = new List <string>();
                        List <string> glosses     = new List <string>();

                        string rawDefinition = sense.Definition[writingSystem.Id];
                        string rawGloss      = sense.Gloss[writingSystem.Id];

                        if (writingSystem.IsUnicodeEncoded)
                        {
                            definitions = GetTrimmedElementsSeperatedBySemiColon(rawDefinition);
                            glosses     = GetTrimmedElementsSeperatedBySemiColon(rawGloss);
                        }
                        else
                        {
                            definitions.Add(rawDefinition);
                            glosses.Add(rawGloss);
                        }

                        List <string> definitionAndGlosses = new List <string>();
                        definitionAndGlosses = MergeListsWhileExcludingDoublesAndEmptyStrings(definitions, glosses);

                        if (definitionAndGlosses.Count == 0)
                        {
                            IDictionary <string, object> tokenFieldsAndValues = new Dictionary <string, object>();
                            tokenFieldsAndValues.Add("Form", null);
                            tokenFieldsAndValues.Add("Sense", senseNumber);
                            fieldsandValuesForRecordTokens.Add(tokenFieldsAndValues);
                        }
                        else
                        {
                            foreach (string definition in definitionAndGlosses)
                            {
                                IDictionary <string, object> tokenFieldsAndValues = new Dictionary <string, object>();
                                tokenFieldsAndValues.Add("Form", definition);
                                tokenFieldsAndValues.Add("Sense", senseNumber);
                                fieldsandValuesForRecordTokens.Add(tokenFieldsAndValues);
                            }
                        }

                        senseNumber++;
                    }
                    return(fieldsandValuesForRecordTokens);
                });
                ResultSet <LexEntry> itemsMatching = _decoratedDataMapper.GetItemsMatching(definitionQuery);

                SortDefinition[] sortOrder = new SortDefinition[2];
                sortOrder[0] = new SortDefinition("Form", writingSystem.Collator);
                sortOrder[1] = new SortDefinition("Sense", Comparer <int> .Default);
                _caches.Add(cacheName, new ResultSetCache <LexEntry>(this, sortOrder, itemsMatching, definitionQuery));
            }
            return(_caches[cacheName].GetResultSet());
        }
Ejemplo n.º 35
0
        public void Should_return_empty()
        {
            var res = new ResultSet("c1");

            Assert.True(res.IsEmpty);
        }
        public static DatabaseQueryResult RunCombos(string storedProcedureName, List <Parameter> parameters)
        {
            try
            {
                var r = new DatabaseQueryResult();

                using (var conn = new SqlConnection(connectionString))
                {
                    try
                    {
                        conn.Open();
                        using (SqlCommand cmd = GetCommand(conn, storedProcedureName))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            buildParameters(parameters, cmd);

                            using (var dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                            {
                                var resultSetCount = 0;

                                do
                                {
                                    var resultSetData = new ArrayList(100);

                                    while (dr.Read())
                                    {
                                        var row = new ArrayList(dr.FieldCount);

                                        for (var i = 0; i < dr.FieldCount; i++)
                                        {
                                            var colValue = dr[i];

                                            row.Add(colValue);
                                            if (dr[i].GetType().Name.Equals("Byte[]"))
                                            {
                                                row[i] = BitConverter.ToString((byte[])colValue, 0);
                                            }
                                        }

                                        resultSetData.Add(row);
                                    }

                                    var rs = new ResultSet(resultSetCount.ToString());
                                    rs.Data    = resultSetData;
                                    rs.Columns = getColumnNames(dr);
                                    r.ResultSets.Add(rs);
                                    resultSetCount++;
                                } while (dr.NextResult());

                                return(r);
                            }
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch (Exception e)
            {
                LoggingHelper.Instance.AgregarLog(new LogSqlEntity("RunCombos", storedProcedureName, buildParametrosToLog(parameters), e));
                LoggingHelper.HandleException(e);
                return(null);
            }
        }
Ejemplo n.º 37
0
 internal H2DataReader(H2Connection connection, ResultSet set)
 {
     this.set        = set;
     this.connection = connection;
 }
Ejemplo n.º 38
0
    /// <summary>
    /// Executes the RegisterOperation.
    /// </summary>
    /// <returns>A RegisterOperationResult containing the result of the operation.</returns>
    public RegisterOperationResult Execute()
    {
        ResultSet resultSet = WebOperation.Execute(new WebOperationCriteria(WebOperationURLs.GetURL(GetType()), CreateFieldDictionaryFromCriteria(_criteria)));

        return(CreateResultFromResultSet(resultSet));
    }
Ejemplo n.º 39
0
 private Builder()
 {
     _resultSet = new ResultSet();
 }
Ejemplo n.º 40
0
        public void OBTENERDESTINOS()
        {
            try
            {
                datagridlistaprecios.Rows.Clear();
                datagridlistaprecios.Columns.Clear();

                IDictionary <string, int> pasajesdiccionario = new Dictionary <string, int>();
                int    count = 1;
                string sql   = "SELECT PASAJE FROM TIPODEPASAJE WHERE PKLINEA=@LINEA AND BORRADO=0";
                db.PreparedSQL(sql);
                db.command.Parameters.AddWithValue("@LINEA", linea);


                datagridlistaprecios.Columns.Add("Destinos", "Destinos");

                res = db.getTable();

                while (res.Next())
                {
                    pasajesdiccionario.Add(res.Get("PASAJE"), count);
                    datagridlistaprecios.Columns.Add(res.Get("PASAJE"), res.Get("PASAJE"));


                    count++;
                }

                IDictionary <string, int> destinodiccionario = new Dictionary <string, int>();
                count = 0;
                sql   = "SELECT DESTINO FROM DESTINOS where borrado=0";

                db.PreparedSQL(sql);


                res = db.getTable();

                while (res.Next())
                {
                    pasajesdiccionario.Add(res.Get("DESTINO"), count);
                    datagridlistaprecios.Rows.Add(res.Get("DESTINO"));


                    count++;
                }
                sql = "SELECT PASAJE,DESTINO,PRECIOCONDESCUENTO FROM VLISTAPRECIO WHERE LINEA_PK=@LINEA AND PK_ORIGEN=@ORIGEN AND BORRADO=0";
                db.PreparedSQL(sql);
                db.command.Parameters.AddWithValue("@LINEA", linea);


                db.command.Parameters.AddWithValue("@ORIGEN", origen);



                res = db.getTable();

                while (res.Next())
                {
                    int col  = pasajesdiccionario[res.Get("PASAJE")];
                    int fila = pasajesdiccionario[res.Get("DESTINO")];
                    datagridlistaprecios.Rows[fila].Cells[col].Value = res.Get("PRECIOCONDESCUENTO");


                    count++;
                }



                datagridlistaprecios.Columns[0].DefaultCellStyle.BackColor = Color.LightSlateGray;

                datagridlistaprecios.Columns[0].Width = 180;
                datagridlistaprecios.Columns[0].DefaultCellStyle.ForeColor = Color.White;
            }

            catch (Exception err)
            {
                string error = err.Message;
                MessageBox.Show("Ocurrio un Error, intente de nuevo.");
                string funcion = "getRows";
                Utilerias.LOG.write(_clase, funcion, error);
            }
        }
Ejemplo n.º 41
0
 /// <summary>
 /// Creates a RegisterOperationResult from the WWW returned by the WebOperation.
 /// </summary>
 /// <param name="www">The WWW containing the result of the web operation.</param>
 /// <returns>A RegisterOperationResult containing the result of the operation.</returns>
 private static RegisterOperationResult CreateResultFromResultSet(ResultSet resultSet)
 {
     return(new RegisterOperationResult(resultSet));
 }
Ejemplo n.º 42
0
 private ValueTask <int> ScanResultSetAsync(IOBehavior ioBehavior, ResultSet resultSet, CancellationToken cancellationToken)
 {
     if (!m_hasMoreResults)
     {
         return(default);
Ejemplo n.º 43
0
        public void PrepareToMoveWordToEditArea(WordDisplay wordDisplay)
        {
            VerifyTaskActivated();
            _savedSensesDuringMoveToEditArea = null;

            if (wordDisplay == null)
            {
                throw new ArgumentNullException();
            }
            // this task was coded to have a list of word-forms, not actual entries.
            //so we have to go searching for possible matches at this point.
            ResultSet <LexEntry> matchingEntries =
                LexEntryRepository.GetEntriesWithMatchingLexicalForm(wordDisplay.Vernacular.Form, FormWritingSystem);

            foreach (RecordToken <LexEntry> recordToken in matchingEntries)
            {
                if (_savedSensesDuringMoveToEditArea == null)
                {
                    _savedSensesDuringMoveToEditArea = new List <LexSense>();
                }
                // have to iterate through these in reverse order since they might get modified
                LexEntry entry = recordToken.RealObject;
                //If we aren't showing the meaning field then we are going let any edits effect all matching Senses
                if (!ShowMeaningField)
                {
                    for (int i = entry.Senses.Count - 1; i >= 0; i--)
                    {
                        LexSense sense           = entry.Senses[i];
                        var      semanticDomains = sense.GetProperty <OptionRefCollection>(_semanticDomainField.FieldName);
                        if (semanticDomains != null)
                        {
                            if (semanticDomains.Contains(CurrentDomainKey))
                            {
                                RememberMeaningOfDissociatedWord(sense);
                                entry.Senses.Remove(sense);
                                //if we don't do this and it has a meaning, we'll fail to delete the word when the user is trying to correct the spelling. (WS-34245)
                            }
                        }
                    }
                }
                //If we are showing the meaning field then we only let edits effect the sense that matches the shown meaning (definition or gloss)
                else
                {
                    var firstSenseMatchingSemDomAndMeaning =
                        entry.Senses.
                        Where(s => s.GetProperty <OptionRefCollection>(LexSense.WellKnownProperties.SemanticDomainDdp4) != null).
                        FirstOrDefault(s => s.GetProperty <OptionRefCollection>(LexSense.WellKnownProperties.SemanticDomainDdp4).Contains(CurrentDomainKey) &&
                                       (_glossMeaningField ? s.Gloss.GetBestAlternative(new[] { DefinitionWritingSystem.Id }) :
                                        s.Definition.GetBestAlternative(new[] { DefinitionWritingSystem.Id })) == wordDisplay.Meaning);
                    if (firstSenseMatchingSemDomAndMeaning != null)
                    {
                        RememberMeaningOfDissociatedWord(firstSenseMatchingSemDomAndMeaning);
                        entry.Senses.Remove(firstSenseMatchingSemDomAndMeaning);
                    }
                }
                entry.CleanUpAfterEditting();
                if (entry.IsEmptyExceptForLexemeFormForPurposesOfDeletion)
                {
                    LexEntryRepository.DeleteItem(entry);                     // if there are no senses left, get rid of it
                }
                else
                {
                    LexEntryRepository.SaveItem(entry);
                }
            }

            UpdateCurrentWords();
        }
Ejemplo n.º 44
0
 public void Save(ResultSet resultSet)
 {
     SaveDataTables(resultSet.DataTable);
 }
Ejemplo n.º 45
0
        private void textBoxbuscar_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar == (char)Keys.Enter))
            {
                try
                {
                    textBoxsum.Text = "";
                    string _searchtool = Convert.ToString(textBoxbuscar.Text);

                    string sql = "SELECT FOLIO,LINEA,ORIGEN,DESTINOBOLETO,SALIDA,TARIFA,ASIENTO,PRECIO, " +
                                 "STATUS,ECO,FORMADEPAGO,FOLIOTARJETA,DIGITOSTARJETA FROM VENDIDOS WHERE CORTE = 1 AND VENDEDOR =@VENDEDOR and " +
                                 "FECHAC BETWEEN CONVERT(datetime, @FECHAINI, 121) AND CONVERT(datetime, @FECHAFINAL,121) ";

                    dataGridViewBOLETOS.Rows.Clear();

                    if (!string.IsNullOrEmpty(_searchtool))
                    {
                        sql += " AND ((FOLIO LIKE @SEARCH OR TARIFA LIKE @SEARCH OR STATUS LIKE @SEARCH OR FORMADEPAGO LIKE @SEARCH) OR (ASIENTO LIKE @SEARCH) )";
                    }
                    sql += " ORDER BY FOLIO ASC";
                    db.PreparedSQL(sql);
                    db.command.Parameters.AddWithValue("@SEARCH", "%" + _searchtool + "%");
                    db.command.Parameters.AddWithValue("@VENDEDOR", usuario);
                    db.command.Parameters.AddWithValue("@FECHAFINAL", fechafinal);
                    db.command.Parameters.AddWithValue("@FECHAINI", fechainicio);
                    res = db.getTable();
                    int    count = 0;
                    int    n     = 0;
                    double sum   = 0;
                    while (res.Next())

                    {
                        string canc = res.Get("STATUS");
                        if (_searchtool == "CANCELADO")
                        {
                            canc = "100";
                        }
                        if (canc != "CANCELADO")
                        {
                            n = dataGridViewBOLETOS.Rows.Add();

                            dataGridViewBOLETOS.Rows[n].Cells["folioname"].Value   = res.Get("FOLIO");
                            dataGridViewBOLETOS.Rows[n].Cells["lineaname"].Value   = res.Get("LINEA");
                            dataGridViewBOLETOS.Rows[n].Cells["origename"].Value   = res.Get("ORIGEN");
                            dataGridViewBOLETOS.Rows[n].Cells["destinoname"].Value = res.Get("DESTINOBOLETO");
                            dataGridViewBOLETOS.Rows[n].Cells["salidaname"].Value  = res.Get("SALIDA");
                            dataGridViewBOLETOS.Rows[n].Cells["asientoname"].Value = res.Get("ASIENTO");
                            dataGridViewBOLETOS.Rows[n].Cells["tarifaname"].Value  = res.Get("TARIFA");
                            dataGridViewBOLETOS.Rows[n].Cells["precionname"].Value = res.Get("PRECIO");
                            dataGridViewBOLETOS.Rows[n].Cells["statusname"].Value  = res.Get("STATUS");
                            dataGridViewBOLETOS.Rows[n].Cells["autobusname"].Value = res.Get("ECO");

                            dataGridViewBOLETOS.Rows[n].Cells["pagoname"].Value         = res.Get("FORMADEPAGO");
                            dataGridViewBOLETOS.Rows[n].Cells["foliotarjetaname"].Value = res.Get("FOLIOTARJETA");
                            dataGridViewBOLETOS.Rows[n].Cells["digitoname"].Value       = res.Get("DIGITOSTARJETA");
                            if (dataGridViewBOLETOS.Rows[n].Cells["statusname"].Value.ToString() == "CANCELADO")
                            {
                                dataGridViewBOLETOS.Rows[n].DefaultCellStyle.BackColor = Color.DarkRed;
                            }
                            if (dataGridViewBOLETOS.Rows[n].Cells["statusname"].Value.ToString() != "CANCELADO")
                            {
                                sum += (double.TryParse(res.Get("PRECIO"), out double aux1)) ? res.GetDouble("PRECIO") : 0.0;
                            }
                            if (canc == "100")
                            {
                                sum += (double.TryParse(res.Get("PRECIO"), out double aux1)) ? res.GetDouble("PRECIO") : 0.0;
                            }
                            textBoxsum.Text = Utilerias.Utilerias.formatCurrency(sum);
                            //textBoxcancelados.Text = cancelados.ToString();
                            //textBoxtotal.Text = "$" + sum.ToString();
                        }
                    }
                }
                catch (Exception err)
                {
                    string error   = err.Message;
                    string funcion = "buscador";
                    Utilerias.LOG.write(_clase, funcion, error);
                    MessageBox.Show("Ocurrio un Error, intente de nuevo.");
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Handle an IDbCommand (Query and ConnectionString) and check it with the expectation (Another IDbCommand or a ResultSet)
        /// </summary>
        /// <param name="actual">IDbCommand</param>
        /// <returns></returns>
        public bool Process(IDbCommand actual)
        {
            ResultSet rsActual = GetResultSet(actual);

            return(this.Matches(rsActual));
        }
        //#EXPORT EXCEL
        public void ExportExcel()
        {
            if (sesion == null)
            {
                sesion = SessionDB.start(Request, Response, false, db);
            }

            try
            {
                System.Data.DataTable tbl = new System.Data.DataTable();
                tbl.Columns.Add("Clave", typeof(string));
                tbl.Columns.Add("Nombre", typeof(string));


                ResultSet res = db.getTable("SELECT * FROM FORMATORETENCIONES");

                while (res.Next())
                {
                    // Here we add five DataRows.
                    tbl.Rows.Add(res.Get("CVE_RETENCION"), res.Get("RETENCION"));
                }

                using (ExcelPackage pck = new ExcelPackage())
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Catalogo Constancias Retenciones");

                    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                    ws.Cells["A1"].LoadFromDataTable(tbl, true);
                    //ws.Cells["A1:B1"].AutoFitColumns();
                    ws.Column(1).Width = 20;
                    ws.Column(2).Width = 80;

                    //Format the header for column 1-3
                    using (ExcelRange rng = ws.Cells["A1:B1"])
                    {
                        rng.Style.Font.Bold        = true;
                        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(Color.White);
                    }

                    //Example how to Format Column 1 as numeric
                    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
                    {
                        col.Style.Numberformat.Format = "#,##0.00";
                        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                    }

                    //Write it back to the client
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=ContratosWeb.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                }

                Log.write(this, "Start", LOG.CONSULTA, "Exporta Excel Catalogo Constancias Retenciones", sesion);
            }
            catch (Exception e)
            {
                ViewBag.Notification = Notification.Error(e.Message);
                Log.write(this, "Start", LOG.ERROR, "Exporta  Excel Catalogo Constancias Retenciones" + e.Message, sesion);
            }
        }
Ejemplo n.º 48
0
        //#EXPORT EXCEL
        public void ExportExcel()
        {
            ImportarDatosSIUModel model = new ImportarDatosSIUModel();

            if (sesion == null)
            {
                sesion = SessionDB.start(Request, Response, false, db);
            }

            try
            {
                System.Data.DataTable tbl = new System.Data.DataTable();
                tbl.Columns.Add("Registro", typeof(string));
                tbl.Columns.Add("ID", typeof(string));
                tbl.Columns.Add("Nombre", typeof(string));
                tbl.Columns.Add("Apellidos", typeof(string));
                tbl.Columns.Add("RFC", typeof(string));
                tbl.Columns.Add("CURP", typeof(string));
                tbl.Columns.Add("Pais", typeof(string));
                tbl.Columns.Add("Estado", typeof(string));
                tbl.Columns.Add("Ciudad", typeof(string));
                tbl.Columns.Add("Del/Mun", typeof(string));
                tbl.Columns.Add("Colonia", typeof(string));
                tbl.Columns.Add("Calle", typeof(string));
                tbl.Columns.Add("CP", typeof(string));
                //tbl.Columns.Add("ESCUELA SEDE", typeof(string));
                //tbl.Columns.Add("CLAVE TÍTULO", typeof(string));
                //tbl.Columns.Add("TÍTULO PROFESIONAL", typeof(string));
                //tbl.Columns.Add("LICENCIATURA", typeof(string));
                //tbl.Columns.Add("MAESTRIA", typeof(string));
                //tbl.Columns.Add("CVE. PROFESIÓN", typeof(string));
                //tbl.Columns.Add("PROFESIÓN", typeof(string));
                //tbl.Columns.Add("CÉDULA PROFESIONAL", typeof(string));
                //tbl.Columns.Add("FEC. CÉDULA", typeof(string));
                //tbl.Columns.Add("NSS", typeof(string));

                ResultSet res      = db.getTable("SELECT * FROM QPersonasTMP WHERE USUARIO = " + sesion.pkUser + " ORDER BY IDSIU");
                string    registro = "";

                while (res.Next())
                {
                    model.IDSIU = res.Get("IDSIU");
                    model.TMP   = false;
                    registro    = model.exist() ? "Sí" : "No";

                    // Here we add five DataRows.
                    tbl.Rows.Add(registro, res.Get("IDSIU"), res.Get("NOMBRES"), res.Get("APELLIDOS"), res.Get("RFC")
                                 , res.Get("CURP"), res.Get("DIRECCION_PAIS"), res.Get("DIRECCION_ESTADO"), res.Get("DIRECCION_CIUDAD")
                                 , res.Get("DIRECCION_ENTIDAD"), res.Get("DIRECCION_COLONIA"), res.Get("DIRECCION_CALLE")
                                 , res.Get("DIRECCION_CP"));
                }

                using (ExcelPackage pck = new ExcelPackage())
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Importar Datos SIU");

                    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                    ws.Cells["A1"].LoadFromDataTable(tbl, true);

                    //Format the header for column 1-3
                    using (ExcelRange rng = ws.Cells["A1:M1"])
                    {
                        rng.Style.Font.Bold        = true;
                        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(Color.White);
                    }

                    //Example how to Format Column 1 as numeric
                    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
                    {
                        col.Style.Numberformat.Format = "#,##0.00";
                        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                    }

                    //Write it back to the client
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=ImportarDatos_SIU.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                }
                Log.write(this, "Start", LOG.CONSULTA, "Exporta Excel Importar Datos SIU", sesion);
            }
            catch (Exception e)
            {
                ViewBag.Notification = Notification.Error(e.Message);
                Log.write(this, "Start", LOG.ERROR, "Exporta Excel Importar Datos SIU" + e.Message, sesion);
            }
        }
Ejemplo n.º 49
0
        private void PopulateSmartTargetRegions(SmartTargetPageModel smartTargetPageModel, Localization localization)
        {
            // Execute a ST Query for all SmartTargetRegions on the Page.
            ResultSet resultSet = ExecuteSmartTargetQuery(smartTargetPageModel, localization);

            Log.Debug($"SmartTarget query returned {resultSet.Promotions.Count} Promotions.");

            string promotionViewName = localization.GetConfigValue(PromotionViewNameConfig);

            if (String.IsNullOrEmpty(promotionViewName))
            {
                Log.Warn($"No View name for SmartTarget Promotions is configured on CM-side ({PromotionViewNameConfig})");
                promotionViewName = "SmartTarget:Entity:Promotion";
            }
            Log.Debug($"Using Promotion View '{promotionViewName}'");

            // TODO: we shouldn't access HttpContext in a Model Builder.
            HttpContext httpContext = HttpContext.Current;

            if (httpContext == null)
            {
                throw new DxaException("HttpContext is not available.");
            }

            List <string>     itemsAlreadyOnPage        = new List <string>();
            ExperimentCookies existingExperimentCookies = CookieProcessor.GetExperimentCookies(httpContext.Request);
            ExperimentCookies newExperimentCookies      = new ExperimentCookies();

            // Filter the Promotions for each SmartTargetRegion
            foreach (SmartTargetRegion smartTargetRegion in smartTargetPageModel.Regions.OfType <SmartTargetRegion>())
            {
                string regionName = smartTargetRegion.Name;

                List <string>        itemsOutputInRegion = new List <string>();
                ExperimentDimensions experimentDimensions;
                List <Promotion>     promotions = new List <Promotion>(resultSet.Promotions);
                ResultSet.FilterPromotions(promotions, regionName, smartTargetRegion.MaxItems, smartTargetPageModel.AllowDuplicates, itemsOutputInRegion,
                                           itemsAlreadyOnPage, ref existingExperimentCookies, ref newExperimentCookies,
                                           out experimentDimensions);

                if (experimentDimensions != null)
                {
                    // The SmartTarget API doesn't set all ExperimentDimensions properties, but they are required by the ExperimentTrackingHandler (see CRQ-1667).
                    experimentDimensions.PublicationId = localization.GetCmUri();
                    experimentDimensions.PageId        = localization.GetCmUri(smartTargetPageModel.Id, (int)ItemType.Page);
                    experimentDimensions.Region        = smartTargetRegion.Name;
                }

                if (localization.IsXpmEnabled)
                {
                    // The SmartTarget API provides the entire XPM markup tag; put it in XpmMetadata["Query"]. See SmartTargetRegion.GetStartQueryXpmMarkup.
                    smartTargetRegion.XpmMetadata = new Dictionary <string, object>
                    {
                        { "Query", ResultSet.GetExperienceManagerMarkup(smartTargetRegion.Name, smartTargetRegion.MaxItems, promotions) }
                    };
                }

                // Create SmartTargetPromotion Entity Models for visible Promotions in the current SmartTargetRegion.
                // It seems that ResultSet.FilterPromotions doesn't really filter on Region name, so we do post-filtering here.
                foreach (Promotion promotion in promotions.Where(promotion => promotion.Visible && promotion.Regions.Contains(regionName)))
                {
                    SmartTargetPromotion smartTargetPromotion = CreatePromotionEntity(promotion, promotionViewName, smartTargetRegion.Name, localization, experimentDimensions);

                    if (!smartTargetRegion.HasSmartTargetContent)
                    {
                        // Discard any fallback content coming from Content Manager
                        smartTargetRegion.Entities.Clear();
                        smartTargetRegion.HasSmartTargetContent = true;
                    }

                    smartTargetRegion.Entities.Add(smartTargetPromotion);
                }
            }

            if (newExperimentCookies.Count > 0)
            {
                smartTargetPageModel.ExperimentCookies = newExperimentCookies;
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Gets a ResultSet containing all entries sorted by citation if one exists and otherwise
        /// by lexical form.
        /// Use "Form" to access the headword in a RecordToken.
        /// </summary>
        /// <param name="writingSystem"></param>
        /// <returns></returns>
        public ResultSet <LexEntry> GetAllEntriesSortedByHeadword(IWritingSystemDefinition writingSystem)
        {
            if (writingSystem == null)
            {
                throw new ArgumentNullException("writingSystem");
            }

            string cacheName = String.Format("sortedByHeadWord_{0}", writingSystem.Id);

            if (_caches[cacheName] == null)
            {
                DelegateQuery <LexEntry> headWordQuery = new DelegateQuery <LexEntry>(
                    delegate(LexEntry entryToQuery)
                {
                    IDictionary <string, object> tokenFieldsAndValues = new Dictionary <string, object>();
                    string headWord = entryToQuery.VirtualHeadWord[writingSystem.Id];
                    if (String.IsNullOrEmpty(headWord))
                    {
                        headWord = null;
                    }
                    tokenFieldsAndValues.Add("Form", headWord);
                    return(new[] { tokenFieldsAndValues });
                });

                ResultSet <LexEntry> itemsMatching = _decoratedDataMapper.GetItemsMatching(headWordQuery);
                var sortOrder = new SortDefinition[4];
                sortOrder[0] = new SortDefinition("Form", writingSystem.Collator);
                sortOrder[1] = new SortDefinition("OrderForRoundTripping", Comparer <int> .Default);
                sortOrder[2] = new SortDefinition("OrderInFile", Comparer <int> .Default);
                sortOrder[3] = new SortDefinition("CreationTime", Comparer <DateTime> .Default);

                _caches.Add(cacheName, new ResultSetCache <LexEntry>(this, sortOrder, itemsMatching, headWordQuery));
                // _caches.Add(headWordQuery, /* itemsMatching */ results); // review cp Refactor caches to this signature.
            }
            ResultSet <LexEntry> resultsFromCache = _caches[cacheName].GetResultSet();

            string previousHeadWord = null;
            int    homographNumber  = 1;
            RecordToken <LexEntry> previousToken = null;

            foreach (RecordToken <LexEntry> token in resultsFromCache)
            {
                // A null Form indicates there is no HeadWord in this writing system.
                // However, we need to ensure that we return all entries, so the AtLeastOne in the query
                // above ensures that we keep it in the result set with a null Form and null WritingSystemId.
                string currentHeadWord = (string)token["Form"];
                if (string.IsNullOrEmpty(currentHeadWord))
                {
                    token["HasHomograph"]    = false;
                    token["HomographNumber"] = 0;
                    continue;
                }
                if (currentHeadWord == previousHeadWord)
                {
                    homographNumber++;
                }
                else
                {
                    previousHeadWord = currentHeadWord;
                    homographNumber  = 1;
                }
                // only used to get our sort correct --This comment seems nonsensical --TA 2008-08-14!!!
                token["HomographNumber"] = homographNumber;
                switch (homographNumber)
                {
                case 1:
                    token["HasHomograph"] = false;
                    break;

                case 2:
                    Debug.Assert(previousToken != null);
                    previousToken["HasHomograph"] = true;
                    token["HasHomograph"]         = true;
                    break;

                default:
                    token["HasHomograph"] = true;
                    break;
                }
                previousToken = token;
            }

            return(resultsFromCache);
        }
Ejemplo n.º 51
0
        public object Transform(ResultSet <DataTable> resultSet)
        {
            Assert.ArgumentNotNull(resultSet, "resultSet");

            return(resultSet);
        }
Ejemplo n.º 52
0
 /// <exception cref="Java.Sql.SQLException"/>
 public virtual void ReadFields(ResultSet resultSet)
 {
     this.url      = resultSet.GetString(1);
     this.pageview = resultSet.GetLong(2);
 }
Ejemplo n.º 53
0
        public JsonResult DataHandler(DTParameters param, Dictionary <string, string> args)
        {
            try
            {
                var dtsource         = new List <ProductVariantsViewModel>();
                var product_Variants = db.Product_Variants;
                if (args != null)
                {
                    foreach (var arg in args)
                    {
                        int number;
                        if (int.TryParse(arg.Value, out number))
                        {
                            if (arg.Key == ((int)CategoryTypes.ProductVariant).ToString())
                            {
                                foreach (var variant in product_Variants)
                                {
                                    if (variant.VariantType == (ProductVarianTypes)number)
                                    {
                                        dtsource.Add(new ProductVariantsViewModel
                                        {
                                            Id   = variant.Id,
                                            Name = variant.Name
                                        });
                                    }
                                }
                            }
                        }
                    }
                }

                List <String> columnSearch = new List <string>();

                foreach (var col in param.Columns)
                {
                    columnSearch.Add(col.Search.Value);
                }
                var search = param.Search.Value;

                Expression <Func <ProductVariantsViewModel, bool> > pre = (p => (search == null || (p.Name != null && p.Name.ToLower().Contains(search.ToLower()))) &&
                                                                           (columnSearch[0] == null || (p.Name != null && p.Name.ToLower().Contains(columnSearch[1].ToLower()))));

                var resultSet = new ResultSet();
                List <ProductVariantsViewModel> data = resultSet.GetResult(pre, param.SortOrder, param.Start, param.Length, dtsource);

                var jsonResult = new List <object>();
                int count      = new ResultSet().Count(pre, dtsource);
                DTResult <ProductVariantsViewModel> result = new DTResult <ProductVariantsViewModel>
                {
                    draw            = param.Draw,
                    data            = data,
                    recordsFiltered = count,
                    recordsTotal    = count
                };
                return(Json(result));
            }
            catch (Exception ex)
            {
                return(Json(new { error = ex.Message }));
            }
        }
Ejemplo n.º 54
0
 /// <exception cref="Java.Sql.SQLException"/>
 public virtual void ReadFields(ResultSet resultSet)
 {
     this.url      = resultSet.GetString(1);
     this.referrer = resultSet.GetString(2);
     this.time     = resultSet.GetLong(3);
 }
Ejemplo n.º 55
0
 public GetGroupsOperationResult(ResultSet resultSet)
 {
     _resultSet = resultSet;
 }
Ejemplo n.º 56
0
        protected void DoOp(OperationCode op, int[] indices,
                            OpFlags flags, ExpectedResult expectedResult, Properties <string, string> creds, bool isMultiuser)
        {
            IRegion <object, object> region;

            if (isMultiuser)
            {
                region = CacheHelper.GetRegion <object, object>(RegionName, creds);
            }
            else
            {
                region = CacheHelper.GetRegion <object, object>(RegionName);
            }

            if (CheckFlags(flags, OpFlags.UseSubRegion))
            {
                IRegion <object, object> subregion = null;
                if (CheckFlags(flags, OpFlags.NoCreateSubRegion))
                {
                    subregion = region.GetSubRegion(SubregionName);
                    if (CheckFlags(flags, OpFlags.CheckNoRegion))
                    {
                        Assert.IsNull(subregion);
                        return;
                    }
                    else
                    {
                        Assert.IsNotNull(subregion);
                    }
                }
                else
                {
                    subregion = CreateSubregion(region);
                    if (isMultiuser)
                    {
                        subregion = region.GetSubRegion(SubregionName);
                    }
                }
                Assert.IsNotNull(subregion);
                region = subregion;
            }
            else if (CheckFlags(flags, OpFlags.CheckNoRegion))
            {
                Assert.IsNull(region);
                return;
            }
            else
            {
                Assert.IsNotNull(region);
            }
            string valPrefix;

            if (CheckFlags(flags, OpFlags.UseNewVal))
            {
                valPrefix = NValuePrefix;
            }
            else
            {
                valPrefix = ValuePrefix;
            }
            int numOps = indices.Length;

            Util.Log("Got DoOp for op: " + op + ", numOps: " + numOps
                     + ", indices: " + IndicesToString(indices));
            bool exceptionOccured = false;
            bool breakLoop        = false;

            for (int indexIndex = 0; indexIndex < indices.Length; ++indexIndex)
            {
                if (breakLoop)
                {
                    break;
                }
                int    index         = indices[indexIndex];
                string key           = KeyPrefix + index;
                string expectedValue = (valPrefix + index);
                try
                {
                    switch (op)
                    {
                    case OperationCode.Get:
                        Object value = null;
                        if (CheckFlags(flags, OpFlags.LocalOp))
                        {
                            int  sleepMillis = 100;
                            int  numTries    = 30;
                            bool success     = false;
                            while (!success && numTries-- > 0)
                            {
                                if (!isMultiuser && region.ContainsValueForKey(key))
                                {
                                    value   = region[key];
                                    success = expectedValue.Equals(value.ToString());
                                    if (CheckFlags(flags, OpFlags.CheckFail))
                                    {
                                        success = !success;
                                    }
                                }
                                else
                                {
                                    value   = null;
                                    success = CheckFlags(flags, OpFlags.CheckFail);
                                }
                                if (!success)
                                {
                                    Thread.Sleep(sleepMillis);
                                }
                            }
                        }
                        else
                        {
                            if (!isMultiuser)
                            {
                                if (CheckFlags(flags, OpFlags.CheckNoKey))
                                {
                                    Assert.IsFalse(region.GetLocalView().ContainsKey(key));
                                }
                                else
                                {
                                    Assert.IsTrue(region.GetLocalView().ContainsKey(key));
                                    region.GetLocalView().Invalidate(key);
                                }
                            }
                            try
                            {
                                value = region[key];
                            }
                            catch (Client.KeyNotFoundException)
                            {
                                Util.Log("KeyNotFoundException while getting key. should be ok as we are just testing auth");
                            }
                        }
                        if (!isMultiuser && value != null)
                        {
                            if (CheckFlags(flags, OpFlags.CheckFail))
                            {
                                Assert.AreNotEqual(expectedValue, value.ToString());
                            }
                            else
                            {
                                Assert.AreEqual(expectedValue, value.ToString());
                            }
                        }
                        break;

                    case OperationCode.Put:
                        region[key] = expectedValue;
                        break;

                    case OperationCode.Destroy:
                        if (!isMultiuser && !region.GetLocalView().ContainsKey(key))
                        {
                            // Since DESTROY will fail unless the value is present
                            // in the local cache, this is a workaround for two cases:
                            // 1. When the operation is supposed to succeed then in
                            // the current AuthzCredentialGenerators the clients having
                            // DESTROY permission also has CREATE/UPDATE permission
                            // so that calling region.Put() will work for that case.
                            // 2. When the operation is supposed to fail with
                            // NotAuthorizedException then in the current
                            // AuthzCredentialGenerators the clients not
                            // having DESTROY permission are those with reader role that have
                            // GET permission.
                            //
                            // If either of these assumptions fails, then this has to be
                            // adjusted or reworked accordingly.
                            if (CheckFlags(flags, OpFlags.CheckNotAuthz))
                            {
                                value = region[key];
                                Assert.AreEqual(expectedValue, value.ToString());
                            }
                            else
                            {
                                region[key] = expectedValue;
                            }
                        }
                        if (!isMultiuser && CheckFlags(flags, OpFlags.LocalOp))
                        {
                            region.GetLocalView().Remove(key); //Destroyed replaced by Remove() API
                        }
                        else
                        {
                            region.Remove(key); //Destroyed replaced by Remove API
                        }
                        break;

                    //TODO: Need to fix Stack overflow exception..
                    case OperationCode.RegisterInterest:
                        if (CheckFlags(flags, OpFlags.UseList))
                        {
                            breakLoop = true;
                            // Register interest list in this case
                            List <CacheableKey> keyList = new List <CacheableKey>(numOps);
                            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex)
                            {
                                int keyNum = indices[keyNumIndex];
                                keyList.Add(KeyPrefix + keyNum);
                            }
                            region.GetSubscriptionService().RegisterKeys(keyList.ToArray());
                        }
                        else if (CheckFlags(flags, OpFlags.UseRegex))
                        {
                            breakLoop = true;
                            region.GetSubscriptionService().RegisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']');
                        }
                        else if (CheckFlags(flags, OpFlags.UseAllKeys))
                        {
                            breakLoop = true;
                            region.GetSubscriptionService().RegisterAllKeys();
                        }
                        break;

                    //TODO: Need to fix Stack overflow exception..
                    case OperationCode.UnregisterInterest:
                        if (CheckFlags(flags, OpFlags.UseList))
                        {
                            breakLoop = true;
                            // Register interest list in this case
                            List <CacheableKey> keyList = new List <CacheableKey>(numOps);
                            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex)
                            {
                                int keyNum = indices[keyNumIndex];
                                keyList.Add(KeyPrefix + keyNum);
                            }
                            region.GetSubscriptionService().UnregisterKeys(keyList.ToArray());
                        }
                        else if (CheckFlags(flags, OpFlags.UseRegex))
                        {
                            breakLoop = true;
                            region.GetSubscriptionService().UnregisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']');
                        }
                        else if (CheckFlags(flags, OpFlags.UseAllKeys))
                        {
                            breakLoop = true;
                            region.GetSubscriptionService().UnregisterAllKeys();
                        }
                        break;

                    case OperationCode.Query:
                        breakLoop = true;
                        ISelectResults <object> queryResults;

                        if (!isMultiuser)
                        {
                            queryResults = (ResultSet <object>)region.Query <object>(
                                "SELECT DISTINCT * FROM " + region.FullPath);
                        }
                        else
                        {
                            queryResults = CacheHelper.getMultiuserCache(creds).GetQueryService <object, object>().NewQuery("SELECT DISTINCT * FROM " + region.FullPath).Execute();
                        }
                        Assert.IsNotNull(queryResults);
                        if (!CheckFlags(flags, OpFlags.CheckFail))
                        {
                            Assert.AreEqual(numOps, queryResults.Size);
                        }
                        //CacheableHashSet querySet = new CacheableHashSet(queryResults.Size);
                        List <string>      querySet = new List <string>(queryResults.Size);
                        ResultSet <object> rs       = queryResults as ResultSet <object>;
                        foreach (object result in  rs)
                        {
                            querySet.Add(result.ToString());
                        }
                        for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex)
                        {
                            int    keyNum      = indices[keyNumIndex];
                            string expectedVal = valPrefix + keyNumIndex;
                            if (CheckFlags(flags, OpFlags.CheckFail))
                            {
                                Assert.IsFalse(querySet.Contains(expectedVal));
                            }
                            else
                            {
                                Assert.IsTrue(querySet.Contains(expectedVal));
                            }
                        }
                        break;

                    case OperationCode.RegionDestroy:
                        breakLoop = true;
                        if (!isMultiuser && CheckFlags(flags, OpFlags.LocalOp))
                        {
                            region.GetLocalView().DestroyRegion();
                        }
                        else
                        {
                            region.DestroyRegion();
                        }
                        break;

                    case OperationCode.GetServerKeys:
                        breakLoop = true;
                        ICollection <object> serverKeys = region.Keys;
                        break;

                    //TODO: Need to fix System.ArgumentOutOfRangeException: Index was out of range. Know issue with GetAll()
                    case OperationCode.GetAll:
                        //ICacheableKey[] keymap = new ICacheableKey[5];
                        List <object> keymap = new List <object>();
                        for (int i = 0; i < 5; i++)
                        {
                            keymap.Add(i);
                            //CacheableInt32 item = CacheableInt32.Create(i);
                            //Int32 item = i;
                            // NOTE: GetAll should operate right after PutAll
                            //keymap[i] = item;
                        }
                        Dictionary <Object, Object> entrymap = new Dictionary <Object, Object>();
                        //CacheableHashMap entrymap = CacheableHashMap.Create();
                        region.GetAll(keymap, entrymap, null, false);
                        if (entrymap.Count < 5)
                        {
                            Assert.Fail("DoOp: Got fewer entries for op " + op);
                        }
                        break;

                    case OperationCode.PutAll:
                        // NOTE: PutAll should operate right before GetAll
                        //CacheableHashMap entrymap2 = CacheableHashMap.Create();
                        Dictionary <Object, Object> entrymap2 = new Dictionary <object, object>();
                        for (int i = 0; i < 5; i++)
                        {
                            //CacheableInt32 item = CacheableInt32.Create(i);
                            Int32 item = i;
                            entrymap2.Add(item, item);
                        }
                        region.PutAll(entrymap2);
                        break;

                    case OperationCode.RemoveAll:
                        Dictionary <Object, Object> entrymap3 = new Dictionary <object, object>();
                        for (int i = 0; i < 5; i++)
                        {
                            //CacheableInt32 item = CacheableInt32.Create(i);
                            Int32 item = i;
                            entrymap3.Add(item, item);
                        }
                        region.PutAll(entrymap3);
                        ICollection <object> keys = new LinkedList <object>();
                        for (int i = 0; i < 5; i++)
                        {
                            Int32 item = i;
                            keys.Add(item);
                        }
                        region.RemoveAll(keys);
                        break;

                    case OperationCode.ExecuteCQ:
                        Pool /*<object, object>*/     pool = PoolManager /*<object, object>*/.Find("__TESTPOOL1_");
                        QueryService <object, object> qs;
                        if (pool != null)
                        {
                            qs = pool.GetQueryService <object, object>();
                        }
                        else
                        {
                            //qs = CacheHelper.DCache.GetQueryService<object, object>();
                            qs = null;
                        }
                        CqAttributesFactory <object, object> cqattrsfact = new CqAttributesFactory <object, object>();
                        CqAttributes <object, object>        cqattrs     = cqattrsfact.Create();
                        CqQuery <object, object>             cq          = qs.NewCq("cq_security", "SELECT * FROM /" + region.Name, cqattrs, false);
                        qs.ExecuteCqs();
                        qs.StopCqs();
                        qs.CloseCqs();
                        break;

                    case OperationCode.ExecuteFunction:
                        if (!isMultiuser)
                        {
                            Pool /*<object, object>*/ pool2 = PoolManager /*<object, object>*/.Find("__TESTPOOL1_");
                            if (pool2 != null)
                            {
                                Client.FunctionService <object> .OnServer(pool2).Execute("securityTest");

                                Client.FunctionService <object> .OnRegion <object, object>(region).Execute("FireNForget");
                            }
                            else
                            {
                                expectedResult = ExpectedResult.Success;
                            }
                        }
                        else
                        {
                            //FunctionService fs = CacheHelper.getMultiuserCache(creds).GetFunctionService();
                            //Execution exe =  fs.OnServer();
                            IRegionService userCache = CacheHelper.getMultiuserCache(creds);
                            Apache.Geode.Client.Execution <object> exe = Client.FunctionService <object> .OnServer(userCache);

                            exe.Execute("securityTest");
                            exe = Client.FunctionService <object> .OnServers(userCache);

                            Client.FunctionService <object> .OnRegion <object, object>(region);

                            Client.FunctionService <object> .OnRegion <object, object>(userCache.GetRegion <object, object>(region.Name)).Execute("FireNForget");
                        }
                        break;

                    default:
                        Assert.Fail("DoOp: Unhandled operation " + op);
                        break;
                    }

                    if (expectedResult != ExpectedResult.Success)
                    {
                        Assert.Fail("Expected an exception while performing operation");
                    }
                }
                catch (AssertionException ex)
                {
                    Util.Log("DoOp: failed assertion: {0}", ex);
                    throw;
                }
                catch (NotAuthorizedException ex)
                {
                    exceptionOccured = true;
                    if (expectedResult == ExpectedResult.NotAuthorizedException)
                    {
                        Util.Log(
                            "DoOp: Got expected NotAuthorizedException when doing operation ["
                            + op + "] with flags [" + flags + "]: " + ex.Message);
                        continue;
                    }
                    else
                    {
                        Assert.Fail("DoOp: Got unexpected NotAuthorizedException when " +
                                    "doing operation: " + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    exceptionOccured = true;
                    if (expectedResult == ExpectedResult.OtherException)
                    {
                        Util.Log("DoOp: Got expected exception when doing operation: " +
                                 ex.GetType() + "::" + ex.Message);
                        continue;
                    }
                    else
                    {
                        Assert.Fail("DoOp: Got unexpected exception when doing operation: " + ex);
                    }
                }
            }

            if (!exceptionOccured &&
                expectedResult != ExpectedResult.Success)
            {
                Assert.Fail("Expected an exception while performing operation");
            }
            Util.Log(" doop done");
        }
Ejemplo n.º 57
0
        //#EXPORT EXCEL
        public void ExportExcel()
        {
            if (sesion == null)
            {
                sesion = SessionDB.start(Request, Response, false, db);
            }

            try
            {
                System.Data.DataTable tbl = new System.Data.DataTable();
                tbl.Columns.Add("IDSIU", typeof(string));
                tbl.Columns.Add("Timbrado", typeof(string));
                tbl.Columns.Add("EmisorRazonSocial", typeof(string));
                tbl.Columns.Add("MENSAJE_ERROR_ULTIMO_TIMBRADO", typeof(string));
                tbl.Columns.Add("PDF", typeof(string));
                tbl.Columns.Add("XML", typeof(string));

                var sede   = Request.Params["sedes"];
                var fechai = Request.Params["fechai"];
                var fechaf = Request.Params["fechaf"];

                ResultSet res = db.getTable("SELECT * FROM V_TIMBRADO_ASIMILADOS WHERE CVE_SEDE = '" + sede + "' AND FILTROFECHA  >='" + fechai + "' AND FILTROFECHA  <='" + fechaf + "'");

                while (res.Next())
                {
                    // Here we add five DataRows.
                    tbl.Rows.Add(res.Get("IDSIU"), res.Get("Timbrado"), res.Get("EmisorRazonSocial")
                                 , res.Get("MENSAJE_ERROR_ULTIMO_TIMBRADO"), res.Get("PDF"), res.Get("XML"));
                }

                using (ExcelPackage pck = new ExcelPackage())
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Timbrado");

                    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                    ws.Cells["A1"].LoadFromDataTable(tbl, true);
                    ws.Cells["A1:F1"].AutoFitColumns();

                    //Format the header for column 1-3
                    using (ExcelRange rng = ws.Cells["A1:F1"])
                    {
                        rng.Style.Font.Bold        = true;
                        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(Color.White);
                    }

                    //Example how to Format Column 1 as numeric
                    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
                    {
                        col.Style.Numberformat.Format = "#,##0.00";
                        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                    }

                    //Write it back to the client
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=Timbrado.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                }
                Log.write(this, "Start", LOG.CONSULTA, "Exporta Excel Timbrado", sesion);
            }
            catch (Exception e)
            {
                ViewBag.Notification = Notification.Error(e.Message);
                Log.write(this, "Start", LOG.ERROR, "Exporta Excel Timbrado" + e.Message, sesion);
            }
        }
Ejemplo n.º 58
0
        private static Result _LoadAll(Connectable connectable, SqlDataReader reader)
        {
            Result result     = null;
            int    tableIndex = 0;
            Type   resultType = typeof(Result);

            try
            {
                do
                {
                    if (reader.GetName(0) == Text.Reserved.ReturnValueColumnName)
                    {
                        if (result == null)
                        {
                            result = new Result(connectable);
                        }

                        result.TableCount  = tableIndex;
                        result.ReturnValue = Reader.ReadOutputDataOnFound(reader, connectable);

                        if (reader.NextResult())
                        {
                            Reader.ThrowQueryTalkReservedNameException();
                        }

                        return(result);  // the code is supposed to always exit the method here
                    }

                    var    table     = _LoadTable <dynamic>(connectable, reader);
                    string tableName = String.Format("{0}{1}", Text.Free.Table, tableIndex + 1);

                    // Table1
                    if (tableIndex == 0)
                    {
                        result = new Result(connectable, table);
                    }
                    // Table2..
                    else
                    {
                        var ptable = new ResultSet <dynamic>(table);

                        // Table2..Table9
                        if (tableIndex < 9)
                        {
                            resultType.GetProperty(tableName).SetValue(result, ptable, null);
                        }
                        // Table10..
                        else
                        {
                            if (result.OtherTables == null)
                            {
                                result.OtherTables = new ExpandoObject();
                            }
                            ((IDictionary <string, object>)result.OtherTables)[tableName] = ptable;
                        }
                    }

                    ++tableIndex;
                }while (reader.NextResult());
            }
            catch (System.InvalidCastException)  // "Specified cast is not valid."
            {
                var mismatchData = Loader.AnalyseInvalidCastException(connectable, typeof(object), tableIndex);

                // throw exception with more accurate report
                if (mismatchData != null)
                {
                    var exception = Reader.TypeMismatchException(((IName)connectable.Executable).Name, Text.Method.Go, typeof(object), mismatchData);
                    throw exception;
                }
                // throw exception with less accurate report (not likely to happen)
                else
                {
                    var exception = Reader.TypeMismatchException(
                        ((IName)connectable.Executable).Name, Text.Method.Go, typeof(object), new Row <string, string, string>());
                    throw exception;
                }
            }

            return(result);    // the code is not supposed to ever reach this line
        }
 public GraphResult(ResultSet <JToken> resultSet)
 {
     ResultSet = resultSet ?? throw new System.ArgumentNullException(nameof(resultSet));
 }