text
stringlengths
43
2.01M
Imports System.ComponentModel Public Class Form1 #Region "Private members" Private _RowErrors As Integer Private Property RowErrors() As Integer Get Return _RowErrors End Get Set(ByVal value As Integer) _RowErrors = value Me.LinkLabel_RowErrors.Text = value.ToString & " Errors" End Set End Property Private _ColumnErrors As Integer Private Property ColumnErrors() As Integer Get Return _ColumnErrors End Get Set(ByVal value As Integer) _ColumnErrors = value Me.LinkLabel_ColumnErrors.Text = value.ToString & " Errors" End Set End Property Private _QuadrantErrors As Integer Private Property QuadrantErrors() As Integer Get Return _QuadrantErrors End Get Set(ByVal value As Integer) _QuadrantErrors = value Me.LinkLabel_QuarterErrors.Text = value.ToString & " Errors" End Set End Property #End Region #Region "Menu handling" Private Sub ExitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click Me.Close() End Sub Private Sub SaveGridToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveGridToolStripMenuItem.Click If Me.SaveFileDialog_HexcellGrid.ShowDialog = Windows.Forms.DialogResult.OK Then '\\ A filename was selected Call SaveGrid(Me.SaveFileDialog_HexcellGrid.FileName) End If End Sub Private Sub LoadGridToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoadGridToolStripMenuItem.Click If Me.OpenFileDialog_HexcellGrid.ShowDialog = Windows.Forms.DialogResult.OK Then '\\ A file was selected to load Call LoadGrid(Me.OpenFileDialog_HexcellGrid.FileName) End If End Sub #End Region #Region "Grid control events" Private Sub HexGrid1_SelectedCellChanged(ByVal Sender As Object, ByVal e As CellSelectedEventArgs) Handles HexGrid1.SelectedCellChanged With e.SelectedCell Me.LinkLabel_Column.Text = .Column.ToString Me.LinkLabel_Row.Text = .Row.ToString End With Me.HexGridCellCtrl1.CellValue = e.SelectedCell.CellValue '\\ Re-calculate the feedback cells Call RefreshFeedback() End Sub #End Region Private Sub HexGridCellCtrl1_ValueChanged(ByVal Sender As Object, ByVal e As HexGridValueChangedEventArgs) Handles HexGridCellCtrl1.ValueChanged Me.HexGrid1.SelectedCell.CellValue = e.Value Me.Refresh() If HexGrid1.SelectedCell.SingleValueSelected Then Call RefreshFeedback() End If End Sub #Region "Hex Cell Context Menu" Private Sub ToolStripContextMenuItem_Cell1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell1.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_0) End Sub Private Sub ToolStripContextMenuItem_Cell2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell2.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_1) End Sub Private Sub ToolStripContextMenuItem_Cell3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell3.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_2) End Sub Private Sub ToolStripContextMenuItem_Cell4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell4.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_3) End Sub Private Sub ToolStripContextMenuItem_Cell5_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell5.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_4) End Sub Private Sub ToolStripContextMenuItem_Cell6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell6.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_5) End Sub Private Sub ToolStripContextMenuItem_Cell7_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell7.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_6) End Sub Private Sub ToolStripContextMenuItem_Cell8_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell8.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_7) End Sub Private Sub ToolStripContextMenuItem_Cell9_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell9.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_8) End Sub Private Sub ToolStripContextMenuItem_Cell10_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell10.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_9) End Sub Private Sub ToolStripContextMenuItem_Cell11_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell11.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_A) End Sub Private Sub ToolStripContextMenuItem_Cell12_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell12.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_B) End Sub Private Sub ToolStripContextMenuItem_Cell13_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell13.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_C) End Sub Private Sub ToolStripContextMenuItem_Cell14_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell14.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_D) End Sub Private Sub ToolStripContextMenuItem_Cell15_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell15.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_E) End Sub Private Sub ToolStripContextMenuItem_Cell16_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripContextMenuItem_Cell16.Click Me.HexGridCellCtrl1.CellValue = CInt(HexGridCellCtrl.CellPossibleValues.CellValue_F) End Sub Private Sub ResetCellToolStripContextMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ResetCellToolStripContextMenuItem.Click Me.HexGridCellCtrl1.CellValue = HexGridCellCtrl.AllPossibleValues End Sub #End Region #Region "Background worker events" Private Sub BackgroundWorker_ValidateColumns_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker_ValidateColumns.ProgressChanged '\\ Update the progress bar Me.ToolStripProgressBar_Columns.Value = e.ProgressPercentage End Sub Private Sub BackgroundWorker_ValidateQuarters_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker_ValidateQuarters.ProgressChanged '\\ Update the progress bar Me.ToolStripProgressBar_Quarters.Value = e.ProgressPercentage End Sub Private Sub BackgroundWorker_ValidateRows_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker_ValidateRows.ProgressChanged '\\ Update the progress bar Me.ToolStripProgressBar_Rows.Value = e.ProgressPercentage End Sub Private Sub BackgroundWorker_ValidateColumns_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker_ValidateColumns.DoWork 'todo: Validate the columns ... Dim bw As BackgroundWorker = CType(sender, BackgroundWorker) ' Extract the argument. Dim arg As Integer = CType(e.Argument, Integer) ' Start the column validation 'e.Result = ''' ' If the operation was canceled by the user, ' set the DoWorkEventArgs.Cancel property to true. If bw.CancellationPending Then e.Cancel = True End If End Sub Private Sub BackgroundWorker_ValidateQuarters_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker_ValidateQuarters.DoWork 'todo: validate the quarters... End Sub Private Sub BackgroundWorker_ValidateRows_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker_ValidateRows.DoWork 'todo: validate the rows... End Sub Private Sub BackgroundWorker_ValidateColumns_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker_ValidateColumns.RunWorkerCompleted '\\ Update with the number of errors found If Not e.Cancelled Then Me.LinkLabel_ColumnErrors.Text = CType(e.Result, Integer).ToString & " Errors" End If End Sub Private Sub BackgroundWorker_ValidateQuarters_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker_ValidateQuarters.RunWorkerCompleted '\\ Update with the number of errors found If Not e.Cancelled Then Me.LinkLabel_QuarterErrors.Text = CType(e.Result, Integer).ToString & " Errors" End If End Sub Private Sub BackgroundWorker_ValidateRows_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker_ValidateRows.RunWorkerCompleted '\\ Update with the number of errors found If Not e.Cancelled Then Me.LinkLabel_RowErrors.Text = CType(e.Result, Integer).ToString & " Errors" End If End Sub #End Region #Region "Private methods" ''' <summary> ''' Restarts the process of checking through the grid to see if any cells are in error ''' </summary> ''' <remarks></remarks> Private Sub RestartGridChecking() Me.LinkLabel_ColumnErrors.Text = "0 Errors" Me.LinkLabel_QuarterErrors.Text = "0 Errors" Me.LinkLabel_RowErrors.Text = "0 Errors" '\\ Kick off the background thread workers If Me.BackgroundWorker_ValidateColumns.IsBusy Then Me.BackgroundWorker_ValidateColumns.CancelAsync() End If If Me.BackgroundWorker_ValidateRows.IsBusy Then Me.BackgroundWorker_ValidateRows.CancelAsync() End If If Me.BackgroundWorker_ValidateQuarters.IsBusy Then Me.BackgroundWorker_ValidateQuarters.CancelAsync() End If Me.BackgroundWorker_ValidateColumns.RunWorkerAsync() Me.BackgroundWorker_ValidateQuarters.RunWorkerAsync() Me.BackgroundWorker_ValidateRows.RunWorkerAsync() End Sub ''' <summary> ''' Refresh the three feedback cells to show the current state of the grid column, row and quadrant ''' </summary> ''' <remarks></remarks> Private Sub RefreshFeedback() ColumnErrors = 0 Me.HexGridCellCtrl_ColumnFeedback.CellValue = HexGridCellCtrl.AllPossibleValues For Each c As HexGridCellCtrl In HexGrid1.Column(HexGrid1.SelectedCellLocation.X) If c.SingleValueSelected Then If HexGridCellCtrl_ColumnFeedback.IsValuePossible(CType(c.CellValue, HexGridCellCtrl.CellPossibleValues)) Then Me.HexGridCellCtrl_ColumnFeedback.UnsetValue(CType(c.CellValue, HexGridCellCtrl.CellPossibleValues)) Else '\\ There are two of the same colour in this quadrant... ColumnErrors += 1 End If End If Next RowErrors = 0 Me.HexGridCellCtrl_RowFeedback.CellValue = HexGridCellCtrl.AllPossibleValues For Each c As HexGridCellCtrl In HexGrid1.Row(HexGrid1.SelectedCellLocation.Y) If c.SingleValueSelected Then If HexGridCellCtrl_RowFeedback.IsValuePossible(CType(c.CellValue, HexGridCellCtrl.CellPossibleValues)) Then Me.HexGridCellCtrl_RowFeedback.UnsetValue(CType(c.CellValue, HexGridCellCtrl.CellPossibleValues)) Else '\\ There are two of the same colour in this quadrant... RowErrors += 1 End If End If Next QuadrantErrors = 0 Me.HexGridCellCtrl_QuadrantFeedback.CellValue = HexGridCellCtrl.AllPossibleValues For Each c As HexGridCellCtrl In HexGrid1.Quadrant(1 + ((HexGrid1.SelectedCellLocation.Y - 1) \ 4), 1 + ((HexGrid1.SelectedCellLocation.X - 1) \ 4)) If c.SingleValueSelected Then If HexGridCellCtrl_QuadrantFeedback.IsValuePossible(CType(c.CellValue, HexGridCellCtrl.CellPossibleValues)) Then Me.HexGridCellCtrl_QuadrantFeedback.UnsetValue(CType(c.CellValue, HexGridCellCtrl.CellPossibleValues)) Else '\\ There are two of the same colour in this quadrant... QuadrantErrors += 1 End If End If Next End Sub Private Sub SaveGrid(ByVal Filename As String) Dim fs As New System.IO.FileStream(Filename, System.IO.FileMode.Create) Dim writer As New System.Xml.XmlTextWriter(fs, New System.Text.UTF8Encoding()) With writer .WriteStartDocument() .WriteComment("HexGrid cell collection - Serialised " & Date.Now.ToShortDateString) .WriteStartElement("GridValues") For nRow As Integer = 1 To 16 For ncolumn As Integer = 1 To 16 .WriteStartElement("GridCell") .WriteAttributeString("Column", ncolumn.ToString) .WriteAttributeString("Row", nRow.ToString) .WriteAttributeString("Value", Me.HexGrid1.CellValue(nRow, ncolumn).ToString) .WriteEndElement() 'GridCell Next Next .WriteEndElement() 'GridValues .WriteComment("(c) 2006 - Merrion Computing Ltd") End With writer.Close() End Sub Private Sub LoadGrid(ByVal Filename As String) Dim fs As New System.IO.FileStream(Filename, System.IO.FileMode.Open) Dim reader As New System.Xml.XmlTextReader(fs) With reader .ReadStartElement("GridValues") For nrow As Integer = 1 To 16 For ncolumn As Integer = 1 To 16 Dim value As Integer = Integer.Parse(.GetAttribute("Value")) Me.HexGrid1.CellValue(nrow, ncolumn) = value .ReadStartElement("GridCell") Next Next .ReadEndElement() End With reader.Close() Me.HexGrid1.Refresh() End Sub #End Region End Class
Namespace TalentBasketFees <Serializable()> _ Friend Class TalentBasketFeesBooking Inherits TalentBasketFees Private Const SOURCECLASS As String = "TalentBasketFeesBooking" Private _validFeesCardTypeForBasket As New Dictionary(Of String, List(Of DEFees)) Private _totalTicketValue As Decimal = 0 Private _totalExceptionValue As Decimal = 0 Private _totalFeeValue As Decimal = 0 Private _totalRetailValue As Decimal = 0 Private _totalBasket As Decimal = 0 Private _IsPercentageBasedProcess As Boolean = False Public Property BookingFeesList As List(Of DEFees) = Nothing Public Property DeliveryChargeEntity() As DEDeliveryCharges.DEDeliveryCharge = Nothing Public Function ProcessBookingFeesForBasket() As ErrorObj Dim errObj As New ErrorObj Try PopulateValidFeesBooking() If BasketEntity.CAT_MODE.Trim.Length > 0 AndAlso ConsiderCATDetailsOnCATTypeStatus <> GlobalConstants.FEE_CONSIDER_CAT_STATUS_STANDARD Then ProcessValidBookingFeesForCATBasket() Else ProcessValidBookingFeesForBasket() End If Catch ex As Exception errObj.HasError = True errObj.ErrorNumber = "TCTBFBOK-001" errObj.ErrorStatus = "While processing booking fees for basket" LogError(SOURCECLASS, "", errObj.ErrorNumber, errObj.ErrorStatus, ex) End Try Return errObj End Function Private Sub GetPartPayment(ByRef patPayWithoutFee As Decimal, ByRef partPayFee As Decimal) Dim dtPartPayments As DataTable = Utilities.RetrievePartPayments(Settings, BasketEntity.Basket_Header_ID) If dtPartPayments IsNot Nothing AndAlso dtPartPayments.Rows.Count > 0 Then For rowIndex As Integer = 0 To dtPartPayments.Rows.Count - 1 partPayFee += Utilities.CheckForDBNull_Decimal(dtPartPayments.Rows(rowIndex)("FeeValue")) patPayWithoutFee += Utilities.CheckForDBNull_Decimal(dtPartPayments.Rows(rowIndex)("PaymentAmount")) - Utilities.CheckForDBNull_Decimal(dtPartPayments.Rows(rowIndex)("FeeValue")) Next End If End Sub Private Function GetPartPaymentWithoutFee() As Decimal Dim partPaymentWithoutFee As Decimal = 0 Dim dtPartPayments As DataTable = Utilities.RetrievePartPayments(Settings, BasketEntity.Basket_Header_ID) If dtPartPayments IsNot Nothing AndAlso dtPartPayments.Rows.Count > 0 Then For rowIndex As Integer = 0 To dtPartPayments.Rows.Count - 1 partPaymentWithoutFee += Utilities.CheckForDBNull_Decimal(dtPartPayments.Rows(rowIndex)("PaymentAmount")) - Utilities.CheckForDBNull_Decimal(dtPartPayments.Rows(rowIndex)("FeeValue")) Next End If Return partPaymentWithoutFee End Function Private Function GetPartPaymentFee() As Decimal Dim partPaymentFee As Decimal = 0 Dim dtPartPayments As DataTable = Utilities.RetrievePartPayments(Settings, BasketEntity.Basket_Header_ID) If dtPartPayments IsNot Nothing AndAlso dtPartPayments.Rows.Count > 0 Then For rowIndex As Integer = 0 To dtPartPayments.Rows.Count - 1 partPaymentFee += Utilities.CheckForDBNull_Decimal(dtPartPayments.Rows(rowIndex)("FeeValue")) Next End If Return partPaymentFee End Function Private Sub PopulateAllTotalValues() _totalTicketValue = 0 _totalExceptionValue = 0 _totalFeeValue = 0 _totalRetailValue = 0 _totalBasket = 0 Dim isFeeNotYetProcessed As Boolean = True For itemIndex As Integer = 0 To BasketItemEntityList.Count - 1 isFeeNotYetProcessed = True For basketItemIndex As Integer = 0 To BasketDetailMergedList.Count - 1 If (BasketDetailMergedList(basketItemIndex).Product = BasketItemEntityList(itemIndex).Product) AndAlso BasketDetailMergedList(basketItemIndex).IsProcessedForBookingFee Then isFeeNotYetProcessed = False _totalBasket += BasketItemEntityList(itemIndex).Gross_Price Exit For End If Next If isFeeNotYetProcessed Then If (Utilities.IsTicketingFee(Settings.EcommerceModuleDefaultsValues.CashBackFeeCode, BasketItemEntityList(itemIndex).MODULE_, BasketItemEntityList(itemIndex).Product, BasketItemEntityList(itemIndex).FEE_CATEGORY)) Then If (BasketItemEntityList(itemIndex).FEE_CATEGORY <> GlobalConstants.FEECATEGORY_BOOKING) Then If BasketItemEntityList(itemIndex).IS_INCLUDED Then 'fee product _totalFeeValue += BasketItemEntityList(itemIndex).Gross_Price End If End If ElseIf BasketItemEntityList(itemIndex).MODULE_.ToUpper = GlobalConstants.BASKETMODULETICKETING.ToUpper Then 'ticket product _totalTicketValue += BasketItemEntityList(itemIndex).Gross_Price Else 'retail product _totalRetailValue += (BasketItemEntityList(itemIndex).Gross_Price * BasketItemEntityList(itemIndex).Quantity) End If End If Next If _totalRetailValue <> 0 Then _totalRetailValue += Utilities.CheckForDBNull_Decimal(GetDeliveryGrossValue()) End If _totalBasket += _totalTicketValue + _totalFeeValue + _totalRetailValue - BasketEntity.CAT_PRICE 'total exception not included with total unless it is required in percentage fees calculation _totalExceptionValue = GetExceptionsTicketTotal() End Sub Private Sub PopulateValidFeesBooking() Dim feeEntityList As List(Of DEFees) = Nothing If BookingFeesList IsNot Nothing AndAlso BasketItemRequiresFees IsNot Nothing Then If CardTypeFeeCategory IsNot Nothing Then Dim tempFeeEntityList As List(Of DEFees) = BookingFeesList 'loop for each card type For Each cardType As KeyValuePair(Of String, String) In CardTypeFeeCategory feeEntityList = tempFeeEntityList For basketItemIndex As Integer = 0 To BasketItemRequiresFees.Count - 1 If IsProductNotExcludedFromFees(BasketItemRequiresFees(basketItemIndex).Product) Then Dim matchedItemIndex As Integer = GetMatchedIndexFromSelectionHierarchy(BasketItemRequiresFees(basketItemIndex), BookingFeesList, cardType.Key) 'fee found If matchedItemIndex > -1 Then AddValidFeesCardTypeForBasket(cardType.Key, feeEntityList(matchedItemIndex)) End If End If Next Next End If End If End Sub Private Sub AddValidFeesCardTypeForBasket(ByVal cardType As String, ByVal feeEntity As DEFees) Dim tempFeesEntityList As List(Of DEFees) = Nothing Dim canAddThisFeeEntity As Boolean = True If _validFeesCardTypeForBasket.TryGetValue(cardType, tempFeesEntityList) Then If tempFeesEntityList.Count > 0 Then For itemIndex As Integer = 0 To tempFeesEntityList.Count - 1 If feeEntity.Equal(tempFeesEntityList(itemIndex)) Then canAddThisFeeEntity = False Exit For End If Next End If Else tempFeesEntityList = New List(Of DEFees) End If If canAddThisFeeEntity Then tempFeesEntityList.Add(feeEntity) _validFeesCardTypeForBasket(cardType) = tempFeesEntityList If Not _IsPercentageBasedProcess Then _IsPercentageBasedProcess = (feeEntity.ChargeType = GlobalConstants.FEECHARGETYPE_PERCENTAGE) End If End Sub Private Sub ProcessValidBookingFeesForBasket() If _IsPercentageBasedProcess Then ProcessValidBookingFeesForBasketPercentage() Else ProcessValidBookingFeesForBasketFixed() End If End Sub Private Sub ProcessValidBookingFeesForBasketPercentage() If _validFeesCardTypeForBasket IsNot Nothing AndAlso _validFeesCardTypeForBasket.Count > 0 Then 'how much paid in part payment Dim partPaymentWithoutFee As Decimal = 0 Dim partPaymentFee As Decimal = 0 GetPartPayment(partPaymentWithoutFee, partPaymentFee) For Each cardTypeFeeEntites As KeyValuePair(Of String, List(Of DEFees)) In _validFeesCardTypeForBasket Dim feeValueForThisCardType As Decimal = 0 'ticket type and product type fees only applicable to ticketing For basketItemIndex As Integer = 0 To BasketDetailMergedList.Count - 1 BasketDetailMergedList(basketItemIndex).IsProcessedForBookingFee = False If BasketDetailMergedList(basketItemIndex).ModuleOfItem = GlobalConstants.BASKETMODULETICKETING AndAlso String.IsNullOrWhiteSpace(BasketDetailMergedList(basketItemIndex).FeeCategory) Then If IsProductNotExcludedFromFees(BasketDetailMergedList(basketItemIndex).Product) Then feeValueForThisCardType = GetFeeValueForBasketItem(True, cardTypeFeeEntites.Value, BasketDetailMergedList(basketItemIndex), feeValueForThisCardType, False, BasketHeaderMergedEntity, True, True) Else BasketDetailMergedList(basketItemIndex).IsProcessedForBookingFee = True End If End If Next PopulateAllTotalValues() 'highest transaction based fee value Dim isTransactionBased As Boolean = False For validFeeItemIndex As Integer = 0 To cardTypeFeeEntites.Value.Count - 1 If cardTypeFeeEntites.Value(validFeeItemIndex).ChargeType = GlobalConstants.FEECHARGETYPE_PERCENTAGE Then 'Percentage If cardTypeFeeEntites.Value(validFeeItemIndex).FeeType = GlobalConstants.FEETYPE_TRANSACTION Then feeValueForThisCardType += (_totalTicketValue + _totalFeeValue + _totalRetailValue + partPaymentFee + _totalExceptionValue) * (cardTypeFeeEntites.Value(validFeeItemIndex).FeeValue / 100) _totalBasket = _totalBasket + _totalExceptionValue isTransactionBased = True End If End If Next 'total basket _totalBasket = _totalBasket + partPaymentFee + feeValueForThisCardType 'actual fee value after taken the part partment + part payment fee feeValueForThisCardType = (((_totalBasket - (partPaymentFee + partPaymentWithoutFee)) / _totalBasket) * feeValueForThisCardType) + partPaymentFee Dim basketFeesEntity As DEBasketFees = CastDEFeesToDEBasketFees(cardTypeFeeEntites.Value(0)) 'now override required properties basketFeesEntity.BasketHeaderID = BasketEntity.Basket_Header_ID basketFeesEntity.CardType = cardTypeFeeEntites.Key basketFeesEntity.FeeApplyType = GlobalConstants.FEEAPPLYTYPE_BOOKING basketFeesEntity.FeeValue = feeValueForThisCardType basketFeesEntity.IsTransactional = isTransactionBased BasketFeesEntityList.Add(basketFeesEntity) Next End If End Sub Private Sub ProcessValidBookingFeesForBasketFixed() If _validFeesCardTypeForBasket IsNot Nothing AndAlso _validFeesCardTypeForBasket.Count > 0 Then For Each cardTypeFeeEntites As KeyValuePair(Of String, List(Of DEFees)) In _validFeesCardTypeForBasket Dim feeValueForThisCardType As Decimal = 0 'highest transaction based fee value Dim isTransactionBased As Boolean = False For validFeeItemIndex As Integer = 0 To cardTypeFeeEntites.Value.Count - 1 If cardTypeFeeEntites.Value(validFeeItemIndex).FeeType = GlobalConstants.FEETYPE_TRANSACTION _ AndAlso feeValueForThisCardType <= cardTypeFeeEntites.Value(validFeeItemIndex).FeeValue Then feeValueForThisCardType = cardTypeFeeEntites.Value(validFeeItemIndex).FeeValue isTransactionBased = True End If Next 'ticket type and product type fees For basketItemIndex As Integer = 0 To BasketDetailMergedList.Count - 1 If BasketDetailMergedList(basketItemIndex).ModuleOfItem = GlobalConstants.BASKETMODULETICKETING AndAlso String.IsNullOrWhiteSpace(BasketDetailMergedList(basketItemIndex).FeeCategory) Then If IsProductNotExcludedFromFees(BasketDetailMergedList(basketItemIndex).Product) Then feeValueForThisCardType = GetFeeValueForBasketItem(True, cardTypeFeeEntites.Value, BasketDetailMergedList(basketItemIndex), feeValueForThisCardType, False, BasketHeaderMergedEntity, True, True) End If End If Next Dim basketFeesEntity As DEBasketFees = CastDEFeesToDEBasketFees(cardTypeFeeEntites.Value(0)) 'now override required properties basketFeesEntity.BasketHeaderID = BasketEntity.Basket_Header_ID basketFeesEntity.CardType = cardTypeFeeEntites.Key basketFeesEntity.FeeApplyType = GlobalConstants.FEEAPPLYTYPE_BOOKING basketFeesEntity.FeeValue = feeValueForThisCardType basketFeesEntity.IsTransactional = isTransactionBased BasketFeesEntityList.Add(basketFeesEntity) Next End If End Sub Private Sub ProcessValidBookingFeesForCATBasket() If _IsPercentageBasedProcess Then ProcessValidBookingFeesForCATBasketPercentage() Else ProcessValidBookingFeesForCATBasketFixed() End If End Sub Private Sub ProcessValidBookingFeesForCATBasketPercentage() If _validFeesCardTypeForBasket IsNot Nothing AndAlso _validFeesCardTypeForBasket.Count > 0 Then Dim canChargeTransactionType As Boolean = False Dim canChargeProductType As Boolean = False Dim canChargeTicketType As Boolean = False AssignChargingFeeTypeOnCAT(canChargeTransactionType, canChargeProductType, canChargeTicketType, ConsiderCATDetailsOnCATTypeStatus) 'how much paid in part payment Dim partPaymentWithoutFee As Decimal = 0 Dim partPaymentFee As Decimal = 0 GetPartPayment(partPaymentWithoutFee, partPaymentFee) For Each cardTypeFeeEntites As KeyValuePair(Of String, List(Of DEFees)) In _validFeesCardTypeForBasket Dim feeValueForThisCardType As Decimal = 0 'ticket type and product type fees only applicable to ticketing For basketItemIndex As Integer = 0 To BasketDetailMergedList.Count - 1 BasketDetailMergedList(basketItemIndex).IsProcessedForBookingFee = False If BasketDetailMergedList(basketItemIndex).ModuleOfItem = GlobalConstants.BASKETMODULETICKETING AndAlso String.IsNullOrWhiteSpace(BasketDetailMergedList(basketItemIndex).FeeCategory) Then If IsProductNotExcludedFromFees(BasketDetailMergedList(basketItemIndex).Product) Then feeValueForThisCardType = GetFeeValueForBasketItem(True, cardTypeFeeEntites.Value, BasketDetailMergedList(basketItemIndex), feeValueForThisCardType, True, BasketHeaderMergedEntity, canChargeProductType, canChargeTicketType) Else BasketDetailMergedList(basketItemIndex).IsProcessedForBookingFee = True End If End If Next PopulateAllTotalValues() 'highest transaction based fee value Dim isTransactionBased As Boolean = False If canChargeTransactionType Then For validFeeItemIndex As Integer = 0 To cardTypeFeeEntites.Value.Count - 1 If cardTypeFeeEntites.Value(validFeeItemIndex).ChargeType = GlobalConstants.FEECHARGETYPE_PERCENTAGE Then 'Percentage If cardTypeFeeEntites.Value(validFeeItemIndex).FeeType = GlobalConstants.FEETYPE_TRANSACTION Then feeValueForThisCardType += (_totalTicketValue + _totalFeeValue + _totalRetailValue + partPaymentFee - BasketEntity.CAT_PRICE) * (cardTypeFeeEntites.Value(validFeeItemIndex).FeeValue / 100) isTransactionBased = True End If End If Next End If 'total basket _totalBasket = _totalBasket + partPaymentFee 'actual fee value after taken the part partment + part payment fee feeValueForThisCardType = (((_totalBasket - (partPaymentFee + partPaymentWithoutFee)) / _totalBasket) * feeValueForThisCardType) + partPaymentFee Dim basketFeesEntity As DEBasketFees = CastDEFeesToDEBasketFees(cardTypeFeeEntites.Value(0)) 'now override required properties basketFeesEntity.BasketHeaderID = BasketEntity.Basket_Header_ID basketFeesEntity.CardType = cardTypeFeeEntites.Key basketFeesEntity.FeeApplyType = GlobalConstants.FEEAPPLYTYPE_BOOKING basketFeesEntity.FeeValue = feeValueForThisCardType basketFeesEntity.IsTransactional = isTransactionBased BasketFeesEntityList.Add(basketFeesEntity) Next End If End Sub Private Sub ProcessValidBookingFeesForCATBasketFixed() If _validFeesCardTypeForBasket IsNot Nothing AndAlso _validFeesCardTypeForBasket.Count > 0 Then Dim canChargeTransactionType As Boolean = False Dim canChargeProductType As Boolean = False Dim canChargeTicketType As Boolean = False AssignChargingFeeTypeOnCAT(canChargeTransactionType, canChargeProductType, canChargeTicketType, ConsiderCATDetailsOnCATTypeStatus) For Each cardTypeFeeEntites As KeyValuePair(Of String, List(Of DEFees)) In _validFeesCardTypeForBasket Dim feeValueForThisCardType As Decimal = 0 'highest transaction based fee value Dim isTransactionBased As Boolean = False If canChargeTransactionType Then For validFeeItemIndex As Integer = 0 To cardTypeFeeEntites.Value.Count - 1 If cardTypeFeeEntites.Value(validFeeItemIndex).FeeType = GlobalConstants.FEETYPE_TRANSACTION _ AndAlso feeValueForThisCardType <= cardTypeFeeEntites.Value(validFeeItemIndex).FeeValue Then feeValueForThisCardType = cardTypeFeeEntites.Value(validFeeItemIndex).FeeValue isTransactionBased = True End If Next End If 'ticket type and product type fees If canChargeProductType OrElse canChargeTicketType Then For basketItemIndex As Integer = 0 To BasketDetailMergedList.Count - 1 If BasketDetailMergedList(basketItemIndex).ModuleOfItem = GlobalConstants.BASKETMODULETICKETING AndAlso String.IsNullOrWhiteSpace(BasketDetailMergedList(basketItemIndex).FeeCategory) Then If IsProductNotExcludedFromFees(BasketDetailMergedList(basketItemIndex).Product) Then feeValueForThisCardType = GetFeeValueForBasketItem(True, cardTypeFeeEntites.Value, BasketDetailMergedList(basketItemIndex), feeValueForThisCardType, True, BasketHeaderMergedEntity, canChargeProductType, canChargeTicketType) End If End If Next End If Dim basketFeesEntity As DEBasketFees = CastDEFeesToDEBasketFees(cardTypeFeeEntites.Value(0)) 'now override required properties basketFeesEntity.BasketHeaderID = BasketEntity.Basket_Header_ID basketFeesEntity.CardType = cardTypeFeeEntites.Key basketFeesEntity.FeeApplyType = GlobalConstants.FEEAPPLYTYPE_BOOKING basketFeesEntity.FeeValue = feeValueForThisCardType basketFeesEntity.IsTransactional = isTransactionBased BasketFeesEntityList.Add(basketFeesEntity) Next End If End Sub Private Function GetDeliveryGrossValue() As Decimal Dim delGrossValue As Decimal = 0 If DeliveryChargeEntity IsNot Nothing Then delGrossValue = Utilities.CheckForDBNull_Decimal(DeliveryChargeEntity.GROSS_VALUE) Else Dim dtOrderHeader As DataTable = TDataObjects.OrderSettings.TblOrderHeader.GetOrderHeaderByTempOrderID(BasketEntity.Temp_Order_Id) If dtOrderHeader IsNot Nothing AndAlso dtOrderHeader.Rows.Count > 0 Then delGrossValue = Utilities.CheckForDBNull_Decimal(dtOrderHeader.Rows(0)("TOTAL_DELIVERY_GROSS")) End If End If Return delGrossValue End Function Private Function GetExceptionsTicketTotal() As Decimal Dim totalExceptionValue As Decimal = 0 Dim isNegativePrice As Boolean = False Dim dtBasketDetailExceptions As DataTable = TDataObjects.BasketSettings.TblBasketDetailExceptions.GetByBasketDetailHeaderIDAndModule(BasketEntity.Basket_Header_ID, GlobalConstants.BASKETMODULETICKETING) If dtBasketDetailExceptions IsNot Nothing AndAlso dtBasketDetailExceptions.Rows.Count > 0 Then For Each row As DataRow In dtBasketDetailExceptions.Rows totalExceptionValue += Utilities.CheckForDBNull_Decimal(row("PRICE")) If Utilities.CheckForDBNull_String(row("CAT_FLAG")).Trim.Length > 0 AndAlso Utilities.CheckForDBNull_String(row("CAT_FLAG")) = GlobalConstants.CATMODE_CANCEL Then isNegativePrice = True End If Next End If If isNegativePrice Then totalExceptionValue = (totalExceptionValue * -1) End If Return totalExceptionValue End Function End Class End Namespace
Imports System.IO Public Class OptionsForm Public changesRequested As Boolean Private Sub Options_Load(sender As Object, e As EventArgs) Handles MyBase.Load If GetSetting("OpenCVB", "FastAccurate", "FastAccurate", True) Then FastProcessing.Checked = True Else AccurateProcessing.Checked = True End If If GetSetting("OpenCVB", "IntelCamera", "IntelCamera", True) Then IntelCamera.Checked = True Else Kinect4Azure.Checked = True End If MinimizeMemoryFootprint.Checked = GetSetting("OpenCVB", "MinimizeMemoryFootprint", "MinimizeMemoryFootprint", False) ShowLabels.Checked = GetSetting("OpenCVB", "ShowLabels", "ShowLabels", False) DecimationFilter.Checked = GetSetting("OpenCVB", "DecimationFilter", "DecimationFilter", False) ThresholdFilter.Checked = GetSetting("OpenCVB", "ThresholdFilter", "ThresholdFilter", False) DepthToDisparity.Checked = GetSetting("OpenCVB", "DepthToDisparity", "DepthToDisparity", True) SpatialFilter.Checked = GetSetting("OpenCVB", "SpatialFilter", "SpatialFilter", True) TemporalFilter.Checked = GetSetting("OpenCVB", "TemporalFilter", "TemporalFilter", False) HoleFillingFilter.Checked = GetSetting("OpenCVB", "HoleFillingFilter", "HoleFillingFilter", True) DisparityToDepth.Checked = GetSetting("OpenCVB", "DisparityToDepth", "DisparityToDepth", True) TestAllDuration.Value = GetSetting("OpenCVB", "TestAllDuration", "TestAllDuration", 10) SnapToGrid.Checked = GetSetting("OpenCVB", "SnapToGrid", "SnapToGrid", True) Dim pythonFileInfo As FileInfo = Nothing Dim pythonFolder As New IO.DirectoryInfo("C:\Program Files (x86)\Microsoft Visual Studio\") For Each File As IO.FileInfo In pythonFolder.GetFiles("python.exe", IO.SearchOption.AllDirectories) PythonExes.Items.Add(File.FullName) Next Dim selectionName = GetSetting("OpenCVB", "PythonExeName", "PythonExeName", "") Dim selectionInfo As FileInfo = Nothing If selectionName <> "" Then selectionInfo = New FileInfo(selectionName) Dim selectionIndex As Int32 = 0 If selectionName <> "" Then If selectionInfo.Exists Then selectionIndex = PythonExes.FindStringExact(selectionName) End If End If If PythonExes.Items.Count > selectionIndex Then PythonExes.SelectedIndex = selectionIndex End Sub Private Sub OptionsForm_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp changesRequested = False If e.KeyCode = Keys.Escape Then Me.Close() End Sub Private Sub OKbutton_Click(sender As Object, e As EventArgs) Handles OKbutton.Click SaveSetting("OpenCVB", "FastAccurate", "FastAccurate", FastProcessing.Checked) SaveSetting("OpenCVB", "IntelCamera", "IntelCamera", IntelCamera.Checked) SaveSetting("OpenCVB", "MinimizeMemoryFootprint", "MinimizeMemoryFootprint", MinimizeMemoryFootprint.Checked) SaveSetting("OpenCVB", "ShowLabels", "ShowLabels", ShowLabels.Checked) SaveSetting("OpenCVB", "DecimationFilter", "DecimationFilter", DecimationFilter.Checked) SaveSetting("OpenCVB", "ThresholdFilter", "ThresholdFilter", ThresholdFilter.Checked) SaveSetting("OpenCVB", "DepthToDisparity", "DepthToDisparity", DepthToDisparity.Checked) SaveSetting("OpenCVB", "SpatialFilter", "SpatialFilter", SpatialFilter.Checked) SaveSetting("OpenCVB", "TemporalFilter", "TemporalFilter", TemporalFilter.Checked) SaveSetting("OpenCVB", "HoleFillingFilter", "HoleFillingFilter", HoleFillingFilter.Checked) SaveSetting("OpenCVB", "DisparityToDepth", "DisparityToDepth", DisparityToDepth.Checked) SaveSetting("OpenCVB", "TestAllDuration", "TestAllDuration", TestAllDuration.Value) SaveSetting("OpenCVB", "SnapToGrid", "SnapToGrid", SnapToGrid.Checked) SaveSetting("OpenCVB", "PythonExeName", "PythonExeName", PythonExes.Text) Me.Hide() End Sub Private Sub CancelButton_Click(sender As Object, e As EventArgs) Handles Cancel.Click changesRequested = False Me.Hide() End Sub Private Sub IntelCamera_CheckedChanged(sender As Object, e As EventArgs) Handles IntelCamera.CheckedChanged DecimationFilter.Enabled = True ThresholdFilter.Enabled = True SpatialFilter.Enabled = True TemporalFilter.Enabled = True HoleFillingFilter.Enabled = True DisparityToDepth.Enabled = True End Sub Private Sub Kinect4Azure_CheckedChanged(sender As Object, e As EventArgs) Handles Kinect4Azure.CheckedChanged DecimationFilter.Enabled = False ThresholdFilter.Enabled = False SpatialFilter.Enabled = False TemporalFilter.Enabled = False HoleFillingFilter.Enabled = False DisparityToDepth.Enabled = False End Sub End Class
Imports System.ComponentModel.DataAnnotations Public Class clsWebTillLog <Required> Property Text As String <Required> <EnumDataType(GetType(LogTypeEnum))> Property LogType As LogTypeEnum <Required> Property MachineToken As String Enum LogTypeEnum UserActivity = 1 Hardware = 2 End Enum End Class
Imports System.Data.Entity Imports System.Data.Entity.ModelConfiguration Imports System.Data.Entity.ModelConfiguration.Conventions Imports domain_management.Entities Namespace DataAccess '<DbConfigurationType(GetType(MySql.Data.Entity.MySqlEFConfiguration))> _ Public Class DomainMgrContexts Inherits System.Data.Entity.DbContext Public Sub New() MyBase.New("DomainMgrConn") Me.Configuration.ValidateOnSaveEnabled = False End Sub Public Property BankAccounts As DbSet(Of BankAccount) Public Property Domains As DbSet(Of Domain) Public Property IdentityTypes As DbSet(Of IdentityType) Public Property Invoices As DbSet(Of Invoice) Public Property InvoiceAttachments As DbSet(Of InvoiceAttachment) Public Property NotificationLogs As DbSet(Of NotificationLog) Public Property Products As DbSet(Of Product) Public Property ProductCategories As DbSet(Of ProductCategory) Public Property Roles As DbSet(Of Role) Public Property TLDHosts As DbSet(Of TLDHost) Public Property Users As DbSet(Of User) Public Property UserRoles As DbSet(Of UserRole) Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder) MyBase.OnModelCreating(modelBuilder) modelBuilder.Conventions.Remove(Of PluralizingTableNameConvention)() modelBuilder.Conventions.Remove(Of OneToManyCascadeDeleteConvention)() End Sub End Class End Namespace
Public Class Indexed Public Property Items(ByVal index As Integer) As Integer Get Select Case index Case 0 Return valOne Case 1 Return valTwo Case 2 Return valThree Case 3 Return valFour End Select End Get Set(ByVal Value As Integer) Select Case index Case 0 valOne = Value Case 1 valTwo = Value Case 2 valThree = Value Case 3 valFour = Value End Select End Set End Property Private valOne, valTwo, valThree, valFour As Integer End Class
Class MainWindow Private pages As List(Of Page) Private requests As List(Of PageRequest) Public Sub New() InitializeComponent() pages = New List(Of Page) For i = 1 To 7 pages.Add(New Page With {.Name = i}) Next requests = New List(Of PageRequest) End Sub Private Sub GenerateRequests() Dim rnd As New Random ' Generate requests requests.Clear() Dim requestCount As Integer = CType(Resources("Requests"), IntegerSingleton).Value For i = 0 To requestCount - 1 requests.Add(New PageRequest() With {.Page = pages(rnd.Next(pages.Count))}) Next RequestsItemsControl.DataContext = requests RequestsItemsControl.Items.Refresh() End Sub Private Sub Compute() ' Generate frames Dim frames As New List(Of Frame) Dim frameCount As Integer = CType(Resources("FrameSize"), IntegerSingleton).Value For i = 0 To frameCount - 1 frames.Add(New Frame()) Next ' Get algorithm Dim algorithm As PageReplacementAlgorithm If OptimalRadioButton.IsChecked.HasValue AndAlso OptimalRadioButton.IsChecked.Value Then algorithm = PageReplacementAlgorithm.Optimal ElseIf LruRadioButton.IsChecked.HasValue AndAlso LruRadioButton.IsChecked.Value Then algorithm = PageReplacementAlgorithm.Lru Else algorithm = PageReplacementAlgorithm.Fifo End If ' Evaluate Dim eval As PageReplacementEvaluation eval = (New PageReplacementEvaluator()).Evaluate(requests, frames, algorithm) ' Output EvaluationContentControl.DataContext = eval PageFaultCountTextBlock.Text = eval.PageFaultCount End Sub Private Sub GenerateAndCompute() GenerateRequests() Compute() End Sub End Class
#Region "Microsoft.VisualBasic::99d36d5c3b3c5cd7dbe8fdc8aba3742f, mzkit\src\metadb\Massbank\Public\TMIC\HMDB\MetaReference\RepositoryExtensions.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Code Statistics: ' Total Lines: 37 ' Code Lines: 31 ' Comment Lines: 0 ' Blank Lines: 6 ' File Size: 1.48 KB ' Module RepositoryExtensions ' ' Function: EnumerateNames, GetMetabolite, PopulateHMDBMetaData ' ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic.ComponentModel.Collection Imports XmlLinq = Microsoft.VisualBasic.Text.Xml.Linq.Data Namespace TMIC.HMDB.Repository <HideModuleName> Public Module RepositoryExtensions ReadOnly web As New Dictionary(Of String, WebQuery) ''' <summary> ''' get hmdb metabolite data from online web services ''' </summary> ''' <param name="id"> ''' get data via this given hmdb metabolite id ''' </param> ''' <param name="cache"> ''' the local cache dir ''' </param> ''' <param name="offline"> ''' running the data query in offline mode? ''' </param> ''' <returns></returns> Public Function GetMetabolite(id As String, Optional cache$ = "./hmdb/", Optional offline As Boolean = False) As metabolite Dim engine As WebQuery = web.ComputeIfAbsent(cache, lazyValue:=Function() New WebQuery(cache,, offline)) engine.offlineMode = offline Return engine.Query(Of metabolite)(id) End Function <MethodImpl(MethodImplOptions.AggressiveInlining)> <Extension> Public Function PopulateHMDBMetaData(Xml As String) As IEnumerable(Of MetaReference) Return XmlLinq.LoadXmlDataSet(Of MetaReference)( XML:=Xml, typeName:=NameOf(metabolite), xmlns:="http://www.hmdb.ca", forceLargeMode:=True ) End Function <MethodImpl(MethodImplOptions.AggressiveInlining)> <Extension> Public Function EnumerateNames(metabolite As MetaReference) As IEnumerable(Of String) Return {metabolite.name}.AsList + metabolite.synonyms.synonym + metabolite.iupac_name End Function End Module End Namespace
Imports System.ComponentModel.DataAnnotations Imports TeamCollect.My.Resources Public Class LaCollecteViewModel <RegularExpression("^(\d+(((\,))\d+)?)$", ErrorMessageResourceName:="decimalType_error", ErrorMessageResourceType:=GetType(Resource))> <Required(ErrorMessageResourceType:=GetType(Resource), ErrorMessageResourceName:="champ_Manquant")> _ Public Property Montant As String <Required(ErrorMessageResourceType:=GetType(Resource), ErrorMessageResourceName:="champ_Manquant")> _ Public Property LeNumCompteClient As String Public Sub New() End Sub Public Function getEntity() As HistoriqueMouvement Dim entity As New HistoriqueMouvement With entity .Montant = Me.Montant 'le plus important c'est avoir un type string a qui mapper les données du viewmodel c'est n'est pas une erreur .Latitude = Me.LeNumCompteClient End With Return entity End Function End Class
' Converts a TrueType font string into curves, and then extrudes them Option Infer On Imports Snap, Snap.Create, Snap.UI.Input Imports System Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Windows.Forms Imports System.Collections.Generic Module MyProgram ' Global (module level) variables Private origin As Position ' Position where extrusion will be located Private path As GraphicsPath ' Graphics path holding the text string Private text As String ' The string to be extruded Private font As Font ' The Windows font to be used Private curves As New List(Of NX.Curve) ' List of curves to be extruded Private thickness As Double ' The thickness (distance) of the extrusion ' Prompt the user to select a font, returning True if successful ' The Module level variable 'font' is set to the resulting font. Function SelectFont() As Boolean Dim fontDlg As FontDialog = New FontDialog SelectFont = False If fontDlg.ShowDialog() = DialogResult.OK Then font = fontDlg.Font SelectFont = True End If End Function ' Prompt the user to specify a position, returning True if successful ' The Module level variable 'origin' is set to the resulting point. Function SelectPosition() As Boolean origin = GetPosition("Specify origin").Position SelectPosition = True End Function ' Prompt the user to input a text string to extrude, returning True if successful ' The Module level variable 'text' is set to the resulting string. Function SelectText() As Boolean text = GetString("Enter text to be extruded", "Enter Text", "Text", " ") SelectText = False If text.Length <> 0 Then SelectText = True End If End Function ' Prompt the user to input an extrusion thickness, returning True if successful ' The Module level variable 'thickness' is set to the resulting value. Function SelectThickness() As Boolean thickness = GetDouble ("Enter extrusion thickness", "Enter thickness", "Thickness", 1.0) SelectThickness = True End Function ' Given a subset of the graphics path between the given indices ' create lines between the points in the path. ' Assumes that caller has selected an appropriate section of the path. Sub CreateLinearPath(ByVal startIndex As Integer, ByVal endIndex As Integer) For j = startIndex To endIndex - 1 Dim p0 As Position = PathPointPosition(path.PathPoints(j)) Dim p1 As Position = PathPointPosition(path.PathPoints(j+1)) curves.Add(Line(p0, p1)) Next End Sub Function PathPointPosition(point As System.Drawing.PointF) As Snap.Position Return New Position(point.X + origin.X, -point.Y + origin.Y) End Function ' Given a subset of the graphics path between the given indices ' create splines (Bezier curves) between the points in the path. ' Assumes that caller has selected an appropriate section of the path. Sub CreateSplinePath(ByVal startIndex As Integer, ByVal endIndex As Integer) For j = startIndex To endIndex - 1 Step 3 Dim poles(3) As Position For k = 0 To 3 poles(k) = PathPointPosition(path.PathPoints(j + k)) Next curves.Add(BezierCurve(poles)) Next End Sub ' Main routine for this application Public Sub Main() If Not SelectFont() Then Return End If If Not SelectText() Then Return End If If Not SelectPosition() Then Return End If path = New GraphicsPath(FillMode.Alternate) Dim zero As New System.Drawing.Point(0, 0) Dim format As StringFormat = StringFormat.GenericDefault path.AddString(text, font.FontFamily, font.Style, font.SizeInPoints, zero, format) Dim bounds As RectangleF = path.GetBounds() Dim gpi As New GraphicsPathIterator(path) gpi.Rewind() origin.X -= bounds.Left origin.Y += bounds.Bottom Dim subPathCount As Integer = gpi.SubpathCount For iSubPath = 0 To subPathCount - 1 Dim mySubPaths As Integer Dim IsClosed As Boolean Dim subPathStartIndex, subPathEndIndex As Integer Dim stpt As New Position Dim endpt As New Position mySubPaths = gpi.NextSubpath(subPathStartIndex, subPathEndIndex, IsClosed) Dim pointTypeStartIndex, pointTypeEndIndex As Integer Do Dim subPathPointType As Byte Dim numPointsFound As Integer = gpi.NextPathType(subPathPointType, pointTypeStartIndex, pointTypeEndIndex) Dim type As PathPointType = CType(subPathPointType, PathPointType) If type = PathPointType.Line Then CreateLinearPath(pointTypeStartIndex, pointTypeEndIndex) ElseIf type = PathPointType.Bezier3 Then CreateSplinePath(pointTypeStartIndex, pointTypeEndIndex) End If Loop While subPathEndIndex <> pointTypeEndIndex If IsClosed Then stpt = PathPointPosition(path.PathPoints(subPathStartIndex)) endpt = PathPointPosition(path.PathPoints(subPathEndIndex)) ' Do not create zero length lines If Position.Distance(stpt, endpt) > 0.000001 Then curves.Add(Line(stpt, endpt)) End If End If Next If SelectThickness() Then ExtrudeSheet(curves.ToArray, Vector.AxisZ, thickness) End If End Sub Public Function GetUnloadOption(ByVal dummy As String) As Integer Dim unloadOption As Integer = NXOpen.Session.LibraryUnloadOption.Immediately ' After executing Return unloadOption End Function End Module
Imports ChartDirector Public Class FrmSimpleZoomScroll ' Data arrays Dim timeStamps As DateTime() Dim dataSeriesA As Double() Dim dataSeriesB As Double() Dim dataSeriesC As Double() Private Sub FrmSimpleZoomScroll_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load ' Load the data loadData() ' Initialize the WinChartViewer initChartViewer(winChartViewer1) ' Trigger the ViewPortChanged event to draw the chart winChartViewer1.updateViewPort(True, True) End Sub ' ' Load the data ' Private Sub loadData() ' In this example, we just use random numbers as data. Dim r As RanSeries = New RanSeries(127) timeStamps = r.getDateSeries(1827, New DateTime(2007, 1, 1), 86400) dataSeriesA = r.getSeries2(1827, 150, -10, 10) dataSeriesB = r.getSeries2(1827, 200, -10, 10) dataSeriesC = r.getSeries2(1827, 250, -8, 8) End Sub ' ' Initialize the WinChartViewer ' Private Sub initChartViewer(ByVal viewer As WinChartViewer) ' Set the full x range to be the duration of the data viewer.setFullRange("x", timeStamps(0), timeStamps(timeStamps.Length - 1)) ' Initialize the view port to show the latest 20% of the time range viewer.ViewPortWidth = 0.2 viewer.ViewPortLeft = 1 - viewer.ViewPortWidth ' Set the maximum zoom to 10 points viewer.ZoomInWidthLimit = 10.0 / timeStamps.Length '/ Initially set the mouse usage to "Pointer" mode (Drag to Scroll mode) pointerPB.Checked = True End Sub ' ' The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in ' or out the chart by dragging or clicking on the chart. It can also be triggered by ' calling WinChartViewer.updateViewPort. ' Private Sub winChartViewer1_ViewPortChanged(ByVal sender As Object, ByVal e As WinViewPortEventArgs) _ Handles winChartViewer1.ViewPortChanged If e.NeedUpdateChart Then drawChart(winChartViewer1) End If If e.NeedUpdateImageMap Then updateImageMap(winChartViewer1) End If End Sub ' ' Draw the chart. ' Private Sub drawChart(ByVal viewer As WinChartViewer) ' Get the start date and end date that are visible on the chart. Dim viewPortStartDate As DateTime = Chart.NTime(viewer.GetValueAtViewPort("x", viewer.ViewPortLeft)) Dim viewPortEndDate As DateTime = Chart.NTime(viewer.GetValueAtViewPort("x", viewer.ViewPortLeft + _ viewer.ViewPortWidth)) ' Get the array indexes that corresponds to the visible start and end dates Dim startIndex As Integer = Math.Floor(Chart.bSearch(timeStamps, viewPortStartDate)) Dim endIndex As Integer = Math.Ceiling(Chart.bSearch(timeStamps, viewPortEndDate)) Dim noOfPoints As Integer = endIndex - startIndex + 1 ' Extract the part of the data array that are visible. Dim viewPortTimeStamps As DateTime() = Chart.arraySlice(timeStamps, startIndex, noOfPoints) Dim viewPortDataSeriesA As Double() = Chart.arraySlice(dataSeriesA, startIndex, noOfPoints) Dim viewPortDataSeriesB As Double() = Chart.arraySlice(dataSeriesB, startIndex, noOfPoints) Dim viewPortDataSeriesC As Double() = Chart.arraySlice(dataSeriesC, startIndex, noOfPoints) ' ' At this stage, we have extracted the visible data. We can use those data to plot the chart. ' '================================================================================ ' Configure overall chart appearance. '================================================================================ ' Create an XYChart object 600 x 300 pixels in size, with pale blue (f0f0ff) ' background, black (000000) border, 1 pixel raised effect, and with a rounded frame. Dim c As XYChart = New XYChart(600, 300, &HF0F0FF, 0, 1) c.setRoundedFrame(Chart.CColor(BackColor)) ' Set the plotarea at (52, 60) and of size 520 x 205 pixels. Use white (ffffff) background. ' Enable both horizontal and vertical grids by setting their colors to grey (cccccc). Set ' clipping mode to clip the data lines to the plot area. c.setPlotArea(52, 60, 520, 205, &HFFFFFF, -1, -1, &HCCCCCC, &HCCCCCC) ' As the data can lie outside the plotarea in a zoomed chart, we need to enable clipping. c.setClipping() ' Add a top title to the chart using 15 pts Times New Roman Bold Italic font, with a light blue ' (ccccff) background, black (000000) border, and a glass like raised effect. c.addTitle("Simple Zooming and Scrolling", "Times New Roman Bold Italic", 15 _ ).setBackground(&HCCCCFF, &H0, Chart.glassEffect()) ' Add a legend box at the top of the plot area with 9pts Arial Bold font with flow layout. c.addLegend(50, 33, False, "Arial Bold", 9).setBackground(Chart.Transparent, Chart.Transparent) ' Set axes width to 2 pixels c.yAxis().setWidth(2) c.xAxis().setWidth(2) ' Add a title to the y-axis c.yAxis().setTitle("Price (USD)", "Arial Bold", 9) '================================================================================ ' Add data to chart '================================================================================ ' ' In this example, we represent the data by lines. You may modify the code below to use other ' representations (areas, scatter plot, etc). ' ' Add a line layer for the lines, using a line width of 2 pixels Dim layer As LineLayer = c.addLineLayer2() layer.setLineWidth(2) ' In this demo, we do not have too many data points. In real code, the chart may contain a lot ' of data points when fully zoomed out - much more than the number of horizontal pixels in this ' plot area. So it is a good idea to use fast line mode. layer.setFastLineMode() ' Now we add the 3 data series to a line layer, using the color red (ff0000), green (00cc00) ' and blue (0000ff) layer.setXData(viewPortTimeStamps) layer.addDataSet(viewPortDataSeriesA, &Hff0000, "Product Alpha") layer.addDataSet(viewPortDataSeriesB, &H00cc00, "Product Beta") layer.addDataSet(viewPortDataSeriesC, &H0000ff, "Product Gamma") '================================================================================ ' Configure axis scale and labelling '================================================================================ ' Set the x-axis as a date/time axis with the scale according to the view port x range. viewer.syncDateAxisWithViewPort("x", c.xAxis()) ' In this demo, we rely on ChartDirector to auto-label the axis. We ask ChartDirector to ensure ' the x-axis labels are at least 75 pixels apart to avoid too many labels. c.xAxis().setTickDensity(75) '================================================================================ ' Output the chart '================================================================================ viewer.Chart = c End Sub ' ' Update the image map ' Private Sub updateImageMap(ByVal viewer As WinChartViewer) ' Include tool tip for the chart If IsNothing(winChartViewer1.ImageMap) Then winChartViewer1.ImageMap = winChartViewer1.Chart.getHTMLImageMap("", "", _ "title='[{dataSetName}] {x|mmm dd, yyyy}: USD {value|2}'") End If End Sub ' ' Pointer (Drag to Scroll) button event handler ' Private Sub pointerPB_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _ Handles pointerPB.CheckedChanged If sender.Checked Then winChartViewer1.MouseUsage = WinChartMouseUsage.ScrollOnDrag End If End Sub ' ' Zoom In button event handler ' Private Sub zoomInPB_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _ Handles zoomInPB.CheckedChanged If sender.Checked Then winChartViewer1.MouseUsage = WinChartMouseUsage.ZoomIn End If End Sub ' ' Zoom Out button event handler ' Private Sub zoomOutPB_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _ Handles zoomOutPB.CheckedChanged If sender.Checked Then winChartViewer1.MouseUsage = WinChartMouseUsage.ZoomOut End If End Sub End Class
Imports System.Web Namespace BaseUserControl Public Module BaseControlCollection Public ReadOnly Property Controls As Dictionary(Of String, Dictionary(Of String, IBaseUserControl)) Get If (HttpContext.Current.Session("SS_BaseControlCollection_Key") Is Nothing) Then HttpContext.Current.Session("SS_BaseControlCollection_Key") = New Dictionary(Of String, Dictionary(Of String, IBaseUserControl))() End If Return CType(HttpContext.Current.Session("SS_BaseControlCollection_Key"), Dictionary(Of String, Dictionary(Of String, IBaseUserControl))) End Get End Property Public Sub Register(ByVal parentKey As String, ByVal key As String, ByVal control As IBaseUserControl) If Not String.IsNullOrEmpty(parentKey) Then SyncLock (Controls) If Controls.ContainsKey(parentKey) Then If (Controls(parentKey) Is Nothing) Then Controls(parentKey) = New Dictionary(Of String, IBaseUserControl) End If If (Controls(parentKey).ContainsKey(key)) Then Controls(parentKey)(key) = control Else Controls(parentKey).Add(key, control) End If Else Controls.Add(parentKey, New Dictionary(Of String, IBaseUserControl)()) Controls(parentKey).Add(key, control) End If End SyncLock End If End Sub End Module End Namespace
Imports System.Runtime.InteropServices Imports Microsoft.Win32 Imports System.Text Public Class LocalHostSQLInstancesReader ''' <summary> ''' get local sql server instance names from registry, search both WOW64 and WOW3264 hives ''' </summary> ''' <returns>a list of local sql server instance names</returns> Public Shared Function GetLocalSqlServerInstanceNames() As IList(Of String) Dim registryValueDataReader As New LocalHostSQLInstancesReader() Dim instances64Bit As String() = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow64, Registry.LocalMachine, "SOFTWARE\Microsoft\Microsoft SQL Server", "InstalledInstances") Dim instances32Bit As String() = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow6432, Registry.LocalMachine, "SOFTWARE\Microsoft\Microsoft SQL Server", "InstalledInstances") 'FormatLocalSqlInstanceNames(instances64Bit) 'FormatLocalSqlInstanceNames(instances32Bit) Dim localInstanceNames As IList(Of String) = New List(Of String)(instances64Bit) localInstanceNames = localInstanceNames.Union(instances32Bit).ToList() Return localInstanceNames End Function Private Shared ReadOnly KEY_WOW64_32KEY As Integer = &H200 Private Shared ReadOnly KEY_WOW64_64KEY As Integer = &H100 Private Shared ReadOnly HKEY_LOCAL_MACHINE As UIntPtr = CType(&H80000002UI, UIntPtr) Private Shared ReadOnly KEY_QUERY_VALUE As Integer = &H1 <DllImport("advapi32.dll", CharSet:=CharSet.Unicode, EntryPoint:="RegOpenKeyEx")> _ Private Shared Function RegOpenKeyEx(hKey As UIntPtr, subKey As String, options As UInteger, sam As Integer, ByRef phkResult As IntPtr) As Integer End Function <DllImport("advapi32.dll", SetLastError:=True)> _ Private Shared Function RegQueryValueEx(hKey As IntPtr, lpValueName As String, lpReserved As Integer, ByRef lpType As UInteger, lpData As IntPtr, ByRef lpcbData As UInteger) As Integer End Function Private Shared Function GetRegistryHiveKey(registryHive__1 As RegistryHive) As Integer Return If(registryHive__1 = RegistryHive.Wow64, KEY_WOW64_64KEY, KEY_WOW64_32KEY) End Function Private Shared Function GetRegistryKeyUIntPtr(registry__1 As RegistryKey) As UIntPtr If registry__1 Is Registry.LocalMachine Then Return HKEY_LOCAL_MACHINE End If Return UIntPtr.Zero End Function Public Function ReadRegistryValueData(registryHive As RegistryHive, registryKey As RegistryKey, subKey As String, valueName As String) As String() Dim instanceNames As String() = New String(-1) {} Dim key As Integer = GetRegistryHiveKey(registryHive) Dim registryKeyUIntPtr As UIntPtr = GetRegistryKeyUIntPtr(registryKey) Dim hResult As IntPtr Dim res As Integer = RegOpenKeyEx(registryKeyUIntPtr, subKey, 0, KEY_QUERY_VALUE Or key, hResult) If res = 0 Then Dim type As UInteger Dim dataLen As UInteger = 0 RegQueryValueEx(hResult, valueName, 0, type, IntPtr.Zero, dataLen) Dim databuff As Byte() = New Byte(dataLen - 1) {} Dim temp As Byte() = New Byte(dataLen - 1) {} Dim values As List(Of [String]) = New List(Of String)() Dim handle As GCHandle = GCHandle.Alloc(databuff, GCHandleType.Pinned) Try RegQueryValueEx(hResult, valueName, 0, type, handle.AddrOfPinnedObject(), dataLen) Finally handle.Free() End Try Dim i As Integer = 0 Dim j As Integer = 0 While i < databuff.Length If databuff(i) = Nothing Then j = 0 Dim str As String = Encoding.[Default].GetString(temp).Trim(ControlChars.NullChar) If Not String.IsNullOrEmpty(str) Then values.Add(str) End If temp = New Byte(dataLen - 1) {} Else temp(System.Math.Max(System.Threading.Interlocked.Increment(j), j - 1)) = databuff(i) End If i += 1 End While instanceNames = New String(values.Count - 1) {} values.CopyTo(instanceNames) End If Return instanceNames End Function End Class
Imports Aspose.Tasks.Saving ' 'This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference 'when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. 'If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from http://www.aspose.com/downloads, 'install it and then add its reference to this project. For any issues, questions or suggestions 'please feel free to contact us using http://www.aspose.com/community/forums/default.aspx ' Namespace WorkingWithProjects Public Class ReadOutlineCodes Public Shared Sub Run() ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName) ' ExStart:ReadOutlineCodes Dim project As New Project(dataDir & Convert.ToString("OutlineCodes.mpp")) For Each ocd As OutlineCodeDefinition In project.OutlineCodes Console.WriteLine("Alias = " + ocd.[Alias]) If ocd.AllLevelsRequired Then Console.WriteLine("It contains property: must have all levels") Else Console.WriteLine("It does not contain property: must have all levels") End If If ocd.Enterprise Then Console.WriteLine("It is an enterprise custom outline code.") Else Console.WriteLine("It is not an enterprise custom outline code.") End If Console.WriteLine("Reference to another custom field for which this outline code definition is an alias is = " + ocd.EnterpriseOutlineCodeAlias) Console.WriteLine("Field Id = " + ocd.FieldId) Console.WriteLine("Field Name = " + ocd.FieldName) Console.WriteLine("Phonetic Alias = " + ocd.PhoneticAlias) Console.WriteLine("Guid = " + ocd.Guid) ' Display outline code masks For Each outlineMask As OutlineMask In ocd.Masks Console.WriteLine("Level of a mask = " + outlineMask.Level) Console.WriteLine("Mask = " + outlineMask.ToString()) Next ' Display out line code values For Each outlineMask1 As OutlineValue In ocd.Values Console.WriteLine("Description of outline value = " + outlineMask1.Description) Console.WriteLine("Value Id = " + outlineMask1.ValueId) Console.WriteLine("Value = " + outlineMask1.Value) Console.WriteLine("Type = " + outlineMask1.Type) Next Next ' ExEnd:ReadOutlineCodes End Sub End Class End Namespace
Imports System.Configuration Imports UGPP.CobrosCoactivo.Entidades Imports UGPP.CobrosCoactivo.Datos Public Class InsertaTituloDAL Inherits AccesObject(Of TituloEjecutivo) ''' <summary> ''' Entidad de conección a la base de datos ''' </summary> Dim db As UGPPEntities Dim _auditLog As LogAuditoria Dim Parameters As List(Of SqlClient.SqlParameter) = New List(Of SqlClient.SqlParameter)() Public Sub New() ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString() db = New UGPPEntities() End Sub Public Sub New(ByVal auditLog As LogAuditoria) ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString() db = New UGPPEntities() _auditLog = auditLog End Sub Public Function Insert(ByVal Titulo As TituloEjecutivo, Optional ByVal prmObjExpedienteId As String = Nothing) As List(Of TituloEjecutivo) Parameters = New List(Of SqlClient.SqlParameter)() If Not IsNothing(prmObjExpedienteId) Then Parameters.Add(New SqlClient.SqlParameter("@MT_expediente", prmObjExpedienteId)) End If Parameters.Add(New SqlClient.SqlParameter("@MT_nro_titulo", Titulo.numeroTitulo)) Parameters.Add(New SqlClient.SqlParameter("@MT_tipo_titulo", Titulo.tipoTitulo)) Parameters.Add(New SqlClient.SqlParameter("@MT_fec_expedicion_titulo", Titulo.fechaTituloEjecutivo)) Parameters.Add(New SqlClient.SqlParameter("@MT_fec_notificacion_titulo", Titulo.fechaNotificacion)) Parameters.Add(New SqlClient.SqlParameter("@MT_for_notificacion_titulo", Titulo.formaNotificacion)) Parameters.Add(New SqlClient.SqlParameter("@MT_Tip_notificacion", Titulo.CodTipNotificacion)) 'Recursos If Not String.IsNullOrEmpty(Titulo.tituloEjecutivoRecursoReposicion.numeroTitulo) Then Parameters.Add(New SqlClient.SqlParameter("@MT_res_resuelve_reposicion", Titulo.tituloEjecutivoRecursoReposicion.numeroTitulo)) Else Parameters.Add(New SqlClient.SqlParameter("@MT_res_resuelve_reposicion", String.Empty)) End If If Not IsNothing(Titulo.tituloEjecutivoRecursoReposicion.fechaTituloEjecutivo) And Titulo.tituloEjecutivoRecursoReposicion.fechaTituloEjecutivo <> Date.MinValue.AddYears(1990) Then Parameters.Add(New SqlClient.SqlParameter("@MT_fec_expe_resolucion_reposicion", Titulo.tituloEjecutivoRecursoReposicion.fechaTituloEjecutivo)) Else Parameters.Add(New SqlClient.SqlParameter("@MT_fec_expe_resolucion_reposicion", String.Empty)) End If If Not String.IsNullOrEmpty(Titulo.tituloEjecutivoRecursoReconsideracion.numeroTitulo) Then Parameters.Add(New SqlClient.SqlParameter("@MT_reso_resu_apela_recon", Titulo.tituloEjecutivoRecursoReconsideracion.numeroTitulo)) Else Parameters.Add(New SqlClient.SqlParameter("@MT_reso_resu_apela_recon", String.Empty)) End If If Not IsNothing(Titulo.tituloEjecutivoRecursoReconsideracion.fechaTituloEjecutivo) And Titulo.tituloEjecutivoRecursoReconsideracion.fechaTituloEjecutivo <> Date.MinValue.AddYears(1990) Then Parameters.Add(New SqlClient.SqlParameter("@MT_fec_exp_reso_apela_recon", Titulo.tituloEjecutivoRecursoReconsideracion.fechaTituloEjecutivo)) Else Parameters.Add(New SqlClient.SqlParameter("@MT_fec_exp_reso_apela_recon", String.Empty)) End If 'Fin Recursos If Not IsNothing(Titulo.fechaEjecutoria) And Titulo.fechaEjecutoria <> Date.MinValue.AddYears(1990) Then Parameters.Add(New SqlClient.SqlParameter("@MT_fecha_ejecutoria", Titulo.fechaEjecutoria)) Else Parameters.Add(New SqlClient.SqlParameter("@MT_fecha_ejecutoria", String.Empty)) End If If Not IsNothing(Titulo.fechaExigibilidad) And Titulo.fechaExigibilidad <> Date.MinValue.AddYears(1990) Then Parameters.Add(New SqlClient.SqlParameter("@MT_fec_exi_liq", Titulo.fechaExigibilidad)) Else Parameters.Add(New SqlClient.SqlParameter("@MT_fec_exi_liq", String.Empty)) End If 'Parameters.Add(New SqlClient.SqlParameter("@MT_fec_exi_liq", Titulo.fechaExigibilidad)) Parameters.Add(New SqlClient.SqlParameter("@MT_procedencia", Titulo.areaOrigen)) Parameters.Add(New SqlClient.SqlParameter("@totaldeuda", IIf((Titulo.TotalSancion IsNot Nothing), Titulo.TotalSancion, 0) + IIf((Titulo.totalObligacion IsNot Nothing), Titulo.totalObligacion, 0) + IIf((Titulo.partidaGlobal IsNot Nothing), Titulo.partidaGlobal, 0))) Parameters.Add(New SqlClient.SqlParameter("@TotalRepartidor", IIf((Titulo.TotalSancion IsNot Nothing), Titulo.TotalSancion, 0) + IIf((Titulo.totalObligacion IsNot Nothing), Titulo.totalObligacion, 0) + IIf((Titulo.partidaGlobal IsNot Nothing), Titulo.partidaGlobal, 0))) Parameters.Add(New SqlClient.SqlParameter("@TotalSancion", IIf((Titulo.TotalSancion IsNot Nothing), Titulo.TotalSancion, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_valor_obligacion", IIf((Titulo.valorTitulo IsNot Nothing), Titulo.valorTitulo, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_partida_global", IIf((Titulo.partidaGlobal IsNot Nothing), Titulo.partidaGlobal, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_sancion_omision", IIf((Titulo.sancionOmision IsNot Nothing), Titulo.sancionOmision, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_sancion_mora", IIf((Titulo.sancionMora IsNot Nothing), Titulo.sancionMora, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_sancion_inexactitud", IIf((Titulo.sancionInexactitud IsNot Nothing), Titulo.sancionInexactitud, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_total_obligacion", IIf((Titulo.totalObligacion IsNot Nothing), Titulo.totalObligacion, 0))) Parameters.Add(New SqlClient.SqlParameter("@MT_total_partida_global", IIf((Titulo.partidaGlobal IsNot Nothing), Titulo.partidaGlobal, 0))) Parameters.Add(New SqlClient.SqlParameter("@CodTipSentencia", Titulo.CodTipSentencia)) Parameters.Add(New SqlClient.SqlParameter("@NoExpedienteOrigen", Titulo.numeroExpedienteOrigen)) Parameters.Add(New SqlClient.SqlParameter("@IdunicoTitulo", Titulo.IdunicoTitulo)) Parameters.Add(New SqlClient.SqlParameter("@Automatico", Titulo.Automatico)) Utils.ValidaLog(_auditLog, "SP_InsertaTituloEjecutivo", Parameters.ToArray) Return ExecuteList("SP_InsertaTituloEjecutivo", Parameters.ToArray()) End Function Public Function InsertDeudor(ByVal Deudor As Deudor, ByVal ED_IDUNICO_TITULO_MAESTRO As Int32) Parameters = New List(Of SqlClient.SqlParameter)() Parameters.Add(New SqlClient.SqlParameter("@ED_TipoId", Deudor.tipoIdentificacion)) Parameters.Add(New SqlClient.SqlParameter("@ED_Codigo_Nit", Deudor.numeroIdentificacion)) Parameters.Add(New SqlClient.SqlParameter("@ED_DigitoVerificacion", If(IsNothing(Deudor.digitoVerificacion), String.Empty, Deudor.digitoVerificacion))) Parameters.Add(New SqlClient.SqlParameter("@ED_TipoPersona", Deudor.tipoPersona)) Parameters.Add(New SqlClient.SqlParameter("@ED_Nombre", Deudor.nombreDeudor)) Parameters.Add(New SqlClient.SqlParameter("@ED_IDUNICO_TITULO_MAESTRO", ED_IDUNICO_TITULO_MAESTRO)) Parameters.Add(New SqlClient.SqlParameter("@TIPO_DEUDOR", Deudor.TipoEnte)) Parameters.Add(New SqlClient.SqlParameter("@PARTICIPACION", Deudor.PorcentajeParticipacion)) Parameters.Add(New SqlClient.SqlParameter("@ED_EstadoPersona", Deudor.EstadoPersona)) Parameters.Add(New SqlClient.SqlParameter("@ED_TipoAportante", Deudor.TipoAportante)) Parameters.Add(New SqlClient.SqlParameter("@ED_TarjetaProf", Deudor.TarjetaProfesional)) Utils.ValidaLog(_auditLog, "EXECUTE SP_InsertaDeudor ", Parameters.ToArray) Return ExecuteList("SP_InsertaDeudor", Parameters.ToArray()) End Function Public Function InsertDireccion(ByVal Direccion As DireccionUbicacion) Parameters = New List(Of SqlClient.SqlParameter)() If Direccion.otrasFuentesDirecciones Is Nothing Then Direccion.otrasFuentesDirecciones = String.Empty End If Parameters.Add(New SqlClient.SqlParameter("@deudor", Direccion.numeroidentificacionDeudor)) Parameters.Add(New SqlClient.SqlParameter("@Direccion", Direccion.direccionCompleta)) Parameters.Add(New SqlClient.SqlParameter("@Departamento", Direccion.idDepartamento)) Parameters.Add(New SqlClient.SqlParameter("@Ciudad", Direccion.idCiudad)) Parameters.Add(New SqlClient.SqlParameter("@Telefono", If(IsNothing(Direccion.telefono), String.Empty, Direccion.telefono))) Parameters.Add(New SqlClient.SqlParameter("@Email", If(IsNothing(Direccion.email), String.Empty, Direccion.email))) Parameters.Add(New SqlClient.SqlParameter("@Movil", If(IsNothing(Direccion.celular), String.Empty, Direccion.celular))) Parameters.Add(New SqlClient.SqlParameter("@ID_FUENTE", Direccion.fuentesDirecciones)) Parameters.Add(New SqlClient.SqlParameter("@OTRA_FUENTE", If(IsNothing(Direccion.otrasFuentesDirecciones), String.Empty, Direccion.otrasFuentesDirecciones))) Utils.ValidaLog(_auditLog, "SP_InsertaDireccion", Parameters.ToArray) Try Return ExecuteList("SP_InsertaDireccion", Parameters.ToArray) Catch ex As Exception End Try End Function Public Sub InsertDocumentos(ByVal Documento As DocumentoMaestroTitulo, ByVal Id As Int32) Parameters = New List(Of SqlClient.SqlParameter)() Parameters.Add(New SqlClient.SqlParameter("@ID_DOCUMENTO_TITULO", If(Documento.ID_DOCUMENTO_TITULO > 0, Documento.ID_DOCUMENTO_TITULO, String.Empty))) Parameters.Add(New SqlClient.SqlParameter("@ID_MAESTRO_TITULO", Id)) Parameters.Add(New SqlClient.SqlParameter("@DES_RUTA_DOCUMENTO", If(String.IsNullOrEmpty(Documento.DES_RUTA_DOCUMENTO), String.Empty, Documento.DES_RUTA_DOCUMENTO))) Parameters.Add(New SqlClient.SqlParameter("@TIPO_RUTA", Documento.TIPO_RUTA)) Parameters.Add(New SqlClient.SqlParameter("@COD_GUID", If(String.IsNullOrEmpty(Documento.COD_GUID), String.Empty, Documento.COD_GUID))) Parameters.Add(New SqlClient.SqlParameter("@COD_TIPO_DOCUMENTO_AO", If(String.IsNullOrEmpty(Documento.COD_TIPO_DOCUMENTO_AO), String.Empty, Documento.COD_TIPO_DOCUMENTO_AO))) Parameters.Add(New SqlClient.SqlParameter("@NOM_DOC_AO", If(String.IsNullOrEmpty(Documento.NOM_DOC_AO), String.Empty, Documento.NOM_DOC_AO))) Parameters.Add(New SqlClient.SqlParameter("@OBSERVA_LEGIBILIDAD", If(String.IsNullOrEmpty(Documento.OBSERVA_LEGIBILIDAD), String.Empty, Documento.OBSERVA_LEGIBILIDAD))) Parameters.Add(New SqlClient.SqlParameter("@NUM_PAGINAS", If(Documento.NUM_PAGINAS > 0, Documento.NUM_PAGINAS, String.Empty))) Utils.ValidaLog(_auditLog, "SP_InsertaDocumento", Parameters.ToArray) ExecuteCommand("SP_InsertaDocumento", Parameters.ToArray) End Sub Public Function InsertNotificacion(ByVal ID_UNICO_MAESTRO_TITULOS As Int32, ByVal FEC_NOTIFICACION As DateTime, ByVal COD_FOR_NOT As String, ByVal COD_TIPO_NOTIFICACION As Int32) Parameters = New List(Of SqlClient.SqlParameter)() Parameters.Add(New SqlClient.SqlParameter("@ID_UNICO_MAESTRO_TITULOS", ID_UNICO_MAESTRO_TITULOS)) Parameters.Add(New SqlClient.SqlParameter("@FEC_NOTIFICACION", FEC_NOTIFICACION)) Parameters.Add(New SqlClient.SqlParameter("@COD_FOR_NOT", COD_FOR_NOT)) Parameters.Add(New SqlClient.SqlParameter("@COD_TIPO_NOTIFICACION", COD_TIPO_NOTIFICACION)) Utils.ValidaLog(_auditLog, "SP_InsertaNotificacion", Parameters.ToArray) Return ExecuteList("SP_InsertaNotificacion", Parameters.ToArray) End Function Public Sub ActualizarNotificacionTitulo(NotificacionActualizar As NotificacionTitulo) Parameters = New List(Of SqlClient.SqlParameter)() Dim Notificacion = (From n In db.MAESTRO_TITULOS_FOR_NOTIFICACION Where n.ID_MAESTRO_TITULOS_FOR_NOTIFICACION = NotificacionActualizar.ID_MAESTRO_TITULOS_FOR_NOTIFICACION Select n).FirstOrDefault() Notificacion.COD_FOR_NOT = NotificacionActualizar.COD_FOR_NOT Notificacion.COD_TIPO_NOTIFICACION = NotificacionActualizar.COD_TIPO_NOTIFICACION Notificacion.FEC_NOTIFICACION = NotificacionActualizar.FEC_NOTIFICACION Parameters.Add(New SqlClient.SqlParameter("@COD_FOR_NOT", NotificacionActualizar.COD_FOR_NOT)) Parameters.Add(New SqlClient.SqlParameter("@COD_TIPO_NOTIFICACION", NotificacionActualizar.COD_TIPO_NOTIFICACION)) Parameters.Add(New SqlClient.SqlParameter("@FEC_NOTIFICACION", NotificacionActualizar.FEC_NOTIFICACION)) Utils.ValidaLog(_auditLog, "Update MAESTRO_TITULOS_FOR_NOTIFICACION", Parameters.ToArray) Utils.salvarDatos(db) End Sub End Class
'--------------------------------------------------------------------------- ' Author : Nguyen Khanh Tung ' Company : Thiên An ESS ' Created Date : Friday, May 02, 2008 '--------------------------------------------------------------------------- Imports System Namespace Entity Public Class Diem #Region "Constructor" #End Region #Region "Var" Private mID_diem As Integer = 0 Private mID_dv As String = "" Private mID_sv As Integer = 0 Private mID_mon As Integer = 0 Private mSo_tiet As Integer = 0 Private mSo_tiet_th As Integer = 0 'So tiet thuc hanh Private mID_dt As Integer = 0 Private mHoc_ky As Integer = 0 Private mNam_hoc As String = "" Private mNo_mon As Integer = 0 Private mDiemDanh As New DiemDanh Private mDiemThanhPhan As New DiemThanhPhan Private mDiemThi As New DiemThi Private mDiemKhongDuDKThi As New DiemKhongDuDieuKienThi Private mDiemHocLai As New DiemHocLai Private mDiemThiLai As New DiemThiLai #End Region #Region "Property" Public Property ID_diem() As Integer Get Return mID_diem End Get Set(ByVal Value As Integer) mID_diem = Value End Set End Property Public Property ID_dv() As String Get Return mID_dv End Get Set(ByVal Value As String) mID_dv = Value End Set End Property Public Property ID_sv() As Integer Get Return mID_sv End Get Set(ByVal Value As Integer) mID_sv = Value End Set End Property Public Property ID_mon() As Integer Get Return mID_mon End Get Set(ByVal Value As Integer) mID_mon = Value End Set End Property Public Property So_tiet() As Integer Get Return mSo_tiet End Get Set(ByVal Value As Integer) mSo_tiet = Value End Set End Property Public Property So_tiet_th() As Integer Get Return mSo_tiet_th End Get Set(ByVal Value As Integer) mSo_tiet_th = Value End Set End Property Public Property ID_dt() As Integer Get Return mID_dt End Get Set(ByVal Value As Integer) mID_dt = Value End Set End Property Public Property Hoc_ky() As Integer Get Return mHoc_ky End Get Set(ByVal Value As Integer) mHoc_ky = Value End Set End Property Public Property Nam_hoc() As String Get Return mNam_hoc End Get Set(ByVal Value As String) mNam_hoc = Value End Set End Property Public Property dsDiemDanh() As DiemDanh Get Return mDiemDanh End Get Set(ByVal Value As DiemDanh) mDiemDanh = Value End Set End Property Public Property dsDiemThanhPhan() As DiemThanhPhan Get Return mDiemThanhPhan End Get Set(ByVal Value As DiemThanhPhan) mDiemThanhPhan = Value End Set End Property Public Property dsDiemThi() As DiemThi Get Return mDiemThi End Get Set(ByVal Value As DiemThi) mDiemThi = Value End Set End Property Public Property dsDiemKhongDuDKThi() As DiemKhongDuDieuKienThi Get Return mDiemKhongDuDKThi End Get Set(ByVal Value As DiemKhongDuDieuKienThi) mDiemKhongDuDKThi = Value End Set End Property Public Property dsDiemHocLai() As DiemHocLai Get Return mDiemHocLai End Get Set(ByVal Value As DiemHocLai) mDiemHocLai = Value End Set End Property Public Property dsDiemThiLai() As DiemThiLai Get Return mDiemThiLai End Get Set(ByVal Value As DiemThiLai) mDiemThiLai = Value End Set End Property Public ReadOnly Property Check_hien_thi(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If Lan_hoc = 1 Then 'Chỉ hiển thị những sinh viên thi lại If Lan_thi > 1 Then If dsDiemThiLai.Thi_lai_lan(Lan_hoc, Lan_thi - 1) > 0 And dsDiemKhongDuDKThi.Khong_du_dieu_kien_thi_lan(Lan_hoc) = 0 Then If (dsDiemThiLai.Thi_lai_lan(Lan_hoc, Lan_thi - 1) > 0 And dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi - 1) <> "K") Then Return True End If End If End If Else 'Chỉ hiển thị những sinh viên học lại If dsDiemKhongDuDKThi.Khong_du_dieu_kien_thi_lan(Lan_hoc - 1) Or (Lan_thi > 1 AndAlso dsDiemThiLai.Thi_lai_lan(Lan_hoc, Lan_thi - 1) > 0 And dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi - 1) <> "K") Or (Lan_thi = 1 AndAlso dsDiemHocLai.Hoc_lai_lan(Lan_hoc - 1)) Then Return True End If End If Return False End Get End Property Public ReadOnly Property Check_hien_thi(ByVal Lan_hoc As Integer) As Boolean Get If dsDiemKhongDuDKThi.Khong_du_dieu_kien_thi_lan(Lan_hoc - 1) Or dsDiemHocLai.Hoc_lai_lan(Lan_hoc - 1) Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_R() As Boolean Get If dsDiemThi.Count > 0 Then If dsDiemThi.DiemThi(0).Ghi_chu.ToUpper = "R" Then Return True End If End If Return False End Get End Property '----------------Các ghi chú Fix, cần sửa khi đi triển khai-------------------------- Public ReadOnly Property GhiChu_KhongDuDKDT(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "K" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_CanhCao(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "C" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_BaoLuu(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "B" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_DinhChi(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "D" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_HSGioi(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "G" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_MienThi(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "M" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_ThiOlympic(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "O" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_VangThiCoPhep(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "P" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_VangThiKoPhep(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "V" Then Return True End If Return False End Get End Property Public ReadOnly Property GhiChu_KhienTrach(ByVal Lan_hoc As Integer, ByVal Lan_thi As Integer) As Boolean Get If dsDiemThi.Ghi_chu_lan(Lan_hoc, Lan_thi).ToUpper = "T" Then Return True End If Return False End Get End Property #End Region End Class End Namespace
Public Class ctlMap Implements IQueueListener Public CenterLat As Double = 33.8 Public CenterLon As Double = -84.3 ''' <summary> ''' Tile server for opaque background map ''' </summary> ''' <remarks></remarks> Public TileServer As New clsServer("OpenStreetMap", _ "http://openstreetmap.org/", _ "http://{abc}.tile.openstreetmap.org/{Zoom}/{X}/{Y}.png", _ "http://www.openstreetmap.org/?lat={Lat}&lon={Lon}&zoom={Zoom}", _ "© OpenStreetMap") Public TransparentTileServers As New Generic.List(Of clsServer) Public TransparentOpacity As Double = 0.5 Public LabelServer As clsServer = Nothing Public LatHeight As Double 'Height of map display area in latitude degrees Public LonWidth As Double 'Width of map display area in longitude degrees 'bounds of map display area Public LatMin As Double, LatMax As Double, LonMin As Double, LonMax As Double Public Event OpenedLayer(ByVal aLayer As clsLayer) Public Event ClosedLayer() Public Event Zoomed() Public Event Panned() Public Event CenterBehaviorChanged() Public Event TileServerChanged() Public Event StatusChanged(ByVal aStatusMessage As String) Private pMagnify As Double = 1 ' Stretch the image by this much: 1=no stretch, 2=double size Private pZoom As Integer = 10 'varies from g_TileServer.ZoomMin to g_TileServer.ZoomMax Public Enum EnumWheelAction Zoom = 0 TileServer = 1 Layer = 2 Transparency = 3 End Enum Public MouseWheelAction As EnumWheelAction = EnumWheelAction.Zoom 'Top-level tile cache folder. 'We name a folder inside here after the tile server, then zoom/x/y.png Private pTileCacheFolder As String = "" Private pShowTileImages As Boolean = True Private pShowTileNames As Boolean = False Private pShowTileOutlines As Boolean = False Private pShowGPSdetails As Boolean = False Private pUseMarkedTiles As Boolean = False Private pShowTransparentTiles As Boolean = False Private pClickWaypoint As Boolean = False ' True means a waypoint will be created when the map is clicked Public ControlsUse As Boolean = False ' True means that on-screen controls are in use so clicks in control areas are treated as control presses Public ControlsShow As Boolean = False Private pControlsMargin As Integer = 40 'This gets set on resize Public ClickedTileFilename As String = "" Private pBrushBlack As New SolidBrush(Color.Black) Private pBrushWhite As New SolidBrush(Color.White) Private pPenBlack As New Pen(Color.Black) Private pPenCursor As New Pen(Color.Red) Private pFontTileLabel As New Font("Arial", 10, FontStyle.Regular) Private pFontGpsDetails As New Font("Arial", 10, FontStyle.Regular) Private pFontCopyright As New Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular) Private pBrushCopyright As New SolidBrush(Color.Black) Private pShowCopyright As Boolean = True Private pShowDate As Boolean = False Public MouseDragging As Boolean = False Public MouseDragStartLocation As Point Public MouseDownLat As Double Public MouseDownLon As Double Private pLastKeyDown As Integer = 0 Private pBitmap As Bitmap Private pBitmapMutex As New Threading.Mutex() Public Layers As New Generic.List(Of clsLayer) Public LayersImportedByTime As New Generic.List(Of clsLayer) Public GPXPanTo As Boolean = True Public GPXZoomTo As Boolean = True Public GPXShow As Boolean = True Public GPXFolder As String Public GPXLabelField As String = "name" Private pBuddyTimer As System.Threading.Timer ' Check for new buddy information ' Alert when buddy location is within pBuddyAlarmMeters of (pBuddyAlarmLat, pBuddyAlarmLon) Private pBuddyAlarmEnabled As Boolean = False Private pBuddyAlarmLat As Double = 0 Private pBuddyAlarmLon As Double = 0 Private pBuddyAlarmMeters As Double = 0 'Must be greater than zero to get buddy alerts Public Buddies As New Generic.Dictionary(Of String, clsBuddy) Delegate Function OpenCallback(ByVal aFilename As String, ByVal aInsertAt As Integer) As clsLayerGPX Private pOpenGPXCallback As New OpenCallback(AddressOf OpenGPX) ' True to automatically start GPS when application starts Private pGPSAutoStart As Boolean = True ' 0=don't follow, 1=re-center only when GPS moves off screen, 2=keep centered, 3=zoom out if needed but keep current area visible Private pGPSCenterBehavior As Integer = 2 ' Symbol at GPS position Public GPSSymbolSize As Integer = 10 ' Symbol at each track point Public TrackSymbolSize As Integer = 3 ' True to record track information while GPS is on Public RecordTrack As Boolean = False ' True to save GSM cell tower identification in recorded track Private pRecordCellID As Boolean = True ' API key for use of OpenCellId.org, see http://www.opencellid.org/api ' Get location with http://www.opencellid.org/cell/get?key=&mcc=&mnc&cellid=&lac= ' Send location with http://www.opencellid.org/measure/add?key=&mnc=&mcc=&lac=&cellid=&lat=&lon= Private pOpenCellIdKey As String = "" ' User name and hash for use of celldb.org, see http://www.celldb.org/aboutapi.php ' Get location with http://celldb.org/api/?method=celldb.getcell&username=&hash=&mcc=&mnc=&lac=&cellid=&format=xml ' Send location with http://celldb.org/api/?method=celldb.addcell&username=&hash=&mcc=&mnc=&lac=&cellid=&latitude=&longitude=&signalstrength=&format=xml Private pCellDbUsername As String = "" Private pCellDbHash As String = "" ' True to display current track information while GPS is on Private pDisplayTrack As Boolean = False ' Wait at least this long before logging a new point Private pTrackMinInterval As New TimeSpan(0, 0, 2) ' Wait at least this long before uploading a new point Public UploadMinInterval As New TimeSpan(0, 2, 0) Public UploadOnStart As Boolean = False ' True to upload point when GPS starts Public UploadOnStop As Boolean = False ' True to upload point when GPS stops Public UploadTrackOnStop As Boolean = False ' True to upload track when GPS stops Public UploadPeriodic As Boolean = False ' True to upload point periodically Private pActive As Boolean = False ' False to disable all Redraw of control Private pDark As Boolean = False ' True to draw simple black background instead of map Delegate Sub RefreshCallback() Private pRefreshCallback As New RefreshCallback(AddressOf Refresh) Private pRedrawCallback As New RefreshCallback(AddressOf Redraw) Private pRedrawing As Boolean = False Private pRedrawPending As Boolean = False Private pRedrawWhenFinishedQueue As Boolean = False Private pRedrawTimer As System.Threading.Timer ' Redraw every so often to be sure any dates displayed are recent Private pLastRedrawTime As Date = Now ' Set to false when we have a first-guess background (e.g. when zooming from tiles we have to ones we don't) Private pClearDelayedTiles As Boolean = True Public Uploader As New clsUploader Public Downloader As New clsDownloader Public Servers As New Generic.Dictionary(Of String, clsServer) Private pImportOffsetFromUTC As TimeSpan = DateTime.UtcNow.Subtract(DateTime.Now) 'Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Integer Public Sub SharedNew(ByVal aTileCacheFolder As String) TileCacheFolder = aTileCacheFolder GPXFolder = g_PathChar & "My Documents" & g_PathChar & "gps" GetSettings() LoadCachedIcons() ' The main form registers itself as a listener so Me.DownloadedTile will be called when each tile is finished. ' Me.FinishedQueue and Me.DownloadedPoint are also called when appropriate Downloader.Listeners.Add(Me) 'Start the download queue runner Downloader.Enabled = True 'TODO: background refresh without disturbing other windows: pRedrawTimer = New System.Threading.Timer(New Threading.TimerCallback(AddressOf RedrawTimeout), Nothing, 0, 10000) End Sub ''' <summary> ''' Keep the device awake, also move map to a cell tower location if desired ''' </summary> ''' <remarks>Periodically called by pKeepAwakeTimer</remarks> Private Sub RedrawTimeout(ByVal o As Object) If Now.Subtract(pLastRedrawTime).TotalSeconds >= 10 Then NeedRedraw() End If End Sub Public Property ImportOffsetFromUTC() As TimeSpan Get Return pImportOffsetFromUTC End Get Set(ByVal value As TimeSpan) If Math.Floor(value.TotalSeconds) <> Math.Floor(pImportOffsetFromUTC.TotalSeconds) Then pImportOffsetFromUTC = value ReImportLayersByDate() NeedRedraw() End If End Set End Property Public Property TileCacheFolder() As String Get Return pTileCacheFolder End Get Set(ByVal value As String) If value Is Nothing Then value = "" If value.Length > 0 AndAlso Not value.EndsWith(g_PathChar) Then value &= g_PathChar End If pTileCacheFolder = value For Each lServer As clsServer In Me.Servers.Values SetServerCacheFolder(lServer) Next End Set End Property Public Property ShowDate() As Boolean Get Return pShowDate End Get Set(ByVal value As Boolean) If pShowDate <> value Then pShowDate = value NeedRedraw() End If End Set End Property Public Property ShowTileImages() As Boolean Get Return pShowTileImages End Get Set(ByVal value As Boolean) If pShowTileImages <> value Then pShowTileImages = value NeedRedraw() End If End Set End Property Public Property ShowTileNames() As Boolean Get Return pShowTileNames End Get Set(ByVal value As Boolean) If pShowTileNames <> value Then pShowTileNames = value NeedRedraw() End If End Set End Property Public Property ShowTileOutlines() As Boolean Get Return pShowTileOutlines End Get Set(ByVal value As Boolean) If pShowTileOutlines <> value Then pShowTileOutlines = value NeedRedraw() End If End Set End Property Public Property Dark() As Boolean Get Return pDark End Get Set(ByVal value As Boolean) pDark = value #If Smartphone Then If pDark Then StopKeepAwake() pFontGpsDetails = New Font(pFontGpsDetails.Name, 20, pFontGpsDetails.Style) Else StartKeepAwake() pFontGpsDetails = New Font(pFontGpsDetails.Name, 10, pFontGpsDetails.Style) End If #End If NeedRedraw() End Set End Property Private Sub LoadCachedIcons() Try Dim lIconFileExts() As String = {"gif", "png", "jpg", "bmp"} Dim lCacheIconFolder As String = pTileCacheFolder & "Icons" If IO.Directory.Exists(lCacheIconFolder) Then For Each lFolder As String In IO.Directory.GetDirectories(lCacheIconFolder) Dim lFolderName As String = IO.Path.GetFileName(lFolder).ToLower For Each lExt As String In lIconFileExts For Each lFilename As String In IO.Directory.GetFiles(lFolder, "*." & lExt) Try Dim lBitmap As New Drawing.Bitmap(lFilename) g_WaypointIcons.Add(lFolderName & "|" & IO.Path.GetFileNameWithoutExtension(lFilename).ToLower, lBitmap) Catch End Try Next Next Next End If Catch e As Exception MsgBox("Exception opening " & pTileCacheFolder & "Icons: " & e.Message, MsgBoxStyle.OkOnly, "LoadCachedIcons") End Try 'TODO: move this to only get geocaching icons when they are absent and user wants them 'If Not g_WaypointIcons.ContainsKey("geocache|webcam cache") Then ' 'get geocaching icons from http://www.geocaching.com/about/cache_types.aspx ' Dim lBaseURL As String = "http://www.geocaching.com/images/" ' Dim lTypeURL As String = lBaseURL & "WptTypes/" ' lCacheIconFolder &= g_PathChar & "Geocache" & g_PathChar ' With Downloader ' .Enqueue(lTypeURL & "2.gif", lCacheIconFolder & "Traditional Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "3.gif", lCacheIconFolder & "Multi-cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "8.gif", lCacheIconFolder & "Unknown Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "5.gif", lCacheIconFolder & "Letterbox Hybrid.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "1858.gif", lCacheIconFolder & "Wherigo Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "6.gif", lCacheIconFolder & "Event Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "mega.gif", lCacheIconFolder & "Mega-Event Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "13.gif", lCacheIconFolder & "Cache In Trash Out Event.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "earthcache.gif", lCacheIconFolder & "Earthcache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "4.gif", lCacheIconFolder & "Virtual Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "1304.gif", lCacheIconFolder & "GPS Adventures Exhibit.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "9.gif", lCacheIconFolder & "Project APE Cache.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lTypeURL & "11.gif", lCacheIconFolder & "Webcam Cache.gif", QueueItemType.IconItem, 2, False) ' Dim lIconURL As String = lBaseURL & "icons/" ' .Enqueue(lIconURL & "icon_smile.gif", lCacheIconFolder & "icon_smile.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_sad.gif", lCacheIconFolder & "icon_sad.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_note.gif", lCacheIconFolder & "icon_note.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_maint.gif", lCacheIconFolder & "icon_maint.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_needsmaint.gif", lCacheIconFolder & "icon_needsmaint.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_disabled.gif", lCacheIconFolder & "icon_disabled.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_enabled.gif", lCacheIconFolder & "icon_enabled.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_greenlight.gif", lCacheIconFolder & "icon_greenlight.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "coord_update.gif", lCacheIconFolder & "coord_update.gif", QueueItemType.IconItem, 2, False) ' .Enqueue(lIconURL & "icon_rsvp.gif", lCacheIconFolder & "icon_rsvp.gif", QueueItemType.IconItem, 2, False) ' End With 'End If End Sub Private Sub GetSettings() On Error Resume Next 'skip bad settings such as one that is not numeric but needs to be Dim lTileServerName As String = "" SetDefaultTileServers() Dim lSoftwareKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software") If lSoftwareKey IsNot Nothing Then Dim lAppKey As Microsoft.Win32.RegistryKey = lSoftwareKey.OpenSubKey(g_AppName) If lAppKey IsNot Nothing Then With lAppKey Dim lKeyIndex As Integer = 1 'Not currently saving servers in registry, saving in text file instead which is read in SetDefaultTileServers 'Do ' Dim lServerNameUrl() As String = CStr(.GetValue("Server" & lKeyIndex, "")).replace(vbcr, "").Split(vblf) ' If lServerNameUrl.Length > 1 Then ' Servers.Add(lServerNameUrl(0), clsServer.FromFields(lServerNameUrl)) ' lKeyIndex += 1 ' Else ' Exit Do ' End If 'Loop lKeyIndex = 1 Do Dim lBuddyNameUrl() As String = CStr(.GetValue("Buddy" & lKeyIndex, "")).Split("|") If lBuddyNameUrl.Length = 2 Then Dim lNewBuddy As New clsBuddy lNewBuddy.Name = lBuddyNameUrl(0) lNewBuddy.LocationURL = lBuddyNameUrl(1) Buddies.Add(lNewBuddy.Name, lNewBuddy) lKeyIndex += 1 Else Exit Do End If Loop 'TileCacheFolder gets set earlier lTileServerName = .GetValue("TileServer", TileServer.Name) TileServerName = lTileServerName g_UploadPointURL = .GetValue("UploadPointURL", g_UploadPointURL) g_UploadTrackURL = .GetValue("UploadTrackURL", g_UploadTrackURL) 'Tiles older than this will be downloaded again as needed. TileCacheDays = 0 to never refresh old tiles 'TODO: different expiration time for different tiles - satellite photos seldom updated, OSM tiles often Dim lTileCacheDays As Integer = .GetValue("TileCacheDays", 0) If lTileCacheDays > 0 Then Downloader.TileCacheOldest = DateTime.Now.ToUniversalTime.AddDays(-lTileCacheDays) Else Downloader.TileCacheOldest = Date.MinValue End If Zoom = .GetValue("Zoom", Zoom) GPXShow = .GetValue("GPXShow", GPXShow) GPXPanTo = .GetValue("GPXPanTo", GPXPanTo) GPXZoomTo = .GetValue("GPXZoomTo", GPXZoomTo) GPXFolder = .GetValue("GPXFolder", GPXFolder) GPXLabelField = .GetValue("GPXLabelField", GPXLabelField) Dark = .GetValue("Dark", pDark) pShowTileImages = .GetValue("TileImages", pShowTileImages) pShowTileNames = .GetValue("TileNames", pShowTileNames) pShowTileOutlines = .GetValue("TileOutlines", pShowTileOutlines) pShowGPSdetails = .GetValue("GPSdetails", pShowGPSdetails) pShowCopyright = .GetValue("ShowCopyright", pShowCopyright) ControlsUse = .GetValue("ControlsUse", ControlsUse) ControlsShow = .GetValue("ControlsShow", ControlsShow) 'TODO: pControlsMargin, but in pixels or percent? CenterLat = .GetValue("CenterLat", CenterLat) CenterLon = .GetValue("CenterLon", CenterLon) SanitizeCenterLatLon() pGPSAutoStart = .GetValue("GPSAutoStart", pGPSAutoStart) pGPSCenterBehavior = .GetValue("GPSFollow", pGPSCenterBehavior) GPSSymbolSize = .GetValue("GPSSymbolSize", GPSSymbolSize) TrackSymbolSize = .GetValue("TrackSymbolSize", TrackSymbolSize) RecordTrack = .GetValue("RecordTrack", RecordTrack) pRecordCellID = .GetValue("RecordCellID", pRecordCellID) pOpenCellIdKey = .GetValue("OpenCellIdKey", pOpenCellIdKey) pDisplayTrack = .GetValue("DisplayTrack", pDisplayTrack) UploadOnStart = .GetValue("UploadOnStart", UploadOnStart) UploadOnStop = .GetValue("UploadOnStop", UploadOnStop) UploadTrackOnStop = .GetValue("UploadTrackOnStop", UploadTrackOnStop) UploadPeriodic = .GetValue("UploadPeriodic", UploadPeriodic) UploadMinInterval = New TimeSpan(0, 0, .GetValue("UploadPeriodicSeconds", UploadMinInterval.TotalSeconds)) End With End If End If TileServerName = lTileServerName End Sub Public Sub SetDefaultTileServers() Dim lTileServersFilename As String = TileServersFilename() Dim lServersHTML As String = ReadTextFile(lTileServersFilename) If lServersHTML.ToLower.IndexOf("<table>") > 0 Then Servers = clsServer.ReadServers(lServersHTML) Else 'TODO: embed default version of servers.html? End If If Servers.Count = 0 Then Dim pDefaultTileServers() As String = {"OpenStreetMap", "http://tile.openstreetmap.org/mapnik/", _ "Maplint", "http://tah.openstreetmap.org/Tiles/maplint/", _ "Osmarender", "http://tah.openstreetmap.org/Tiles/tile/", _ "Cycle Map", "http://andy.sandbox.cloudmade.com/tiles/cycle/", _ "No Name", "http://tile.cloudmade.com/fd093e52f0965d46bb1c6c6281022199/3/256/"} Servers = New Dictionary(Of String, clsServer) For lIndex As Integer = 0 To pDefaultTileServers.Length - 1 Step 2 Servers.Add(pDefaultTileServers(lIndex), New clsServer(pDefaultTileServers(lIndex), , pDefaultTileServers(lIndex + 1))) Next ' Windows Mobile does not support Enum.GetValues or Enum.GetName, so we hard-code names to add below ' For Each lMapType As MapType In System.Enum.GetValues(GetType(MapType)) ' Dim lMapTypeName As String = System.Enum.GetName(GetType(MapType), lMapType) ' If lMapTypeName.IndexOf("OpenStreet") < 0 Then 'Only add non-OSM types ' pTileServers.Add(lMapTypeName, MakeImageUrl(lMapType, New Point(1, 2), 3)) ' End If ' Next 'Servers.Add("YahooMap", New clsServer("YahooMap", , MakeImageUrl(MapType.YahooMap, New Point(1, 2), 3))) 'Servers.Add("YahooSatellite", New clsServer("YahooSatellite", , MakeImageUrl(MapType.YahooSatellite, New Point(1, 2), 3))) 'Servers.Add("YahooLabels", MakeImageUrl(MapType.YahooLabels, New Point(1, 2), 3)) 'Servers.Add("VirtualEarthMap", MakeImageUrl(MapType.VirtualEarthMap, New Point(1, 2), 3)) 'Servers.Add("VirtualEarthSatellite", MakeImageUrl(MapType.VirtualEarthSatellite, New Point(1, 2), 3)) 'Servers.Add("VirtualEarthHybrid", MakeImageUrl(MapType.VirtualEarthHybrid, New Point(1, 2), 3)) End If TileCacheFolder = pTileCacheFolder End Sub Private Function TileServersFilename() As String Dim lTileServersFilename As String = pTileCacheFolder & "servers.html" If IO.File.Exists(lTileServersFilename) Then Return lTileServersFilename Dim lAdjacentFilename As String = IO.Path.Combine(IO.Directory.GetCurrentDirectory, "servers.html") If IO.File.Exists(lAdjacentFilename) Then Return lAdjacentFilename If Downloader.DownloadFile(Nothing, "http://vatavia.net/mark/VataviaMap/servers.html", lTileServersFilename, lTileServersFilename) Then Return lTileServersFilename End If Return "" End Function Public Sub SaveSettings() On Error Resume Next Dim lSoftwareKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software") If lSoftwareKey IsNot Nothing Then Dim lAppKey As Microsoft.Win32.RegistryKey = lSoftwareKey.CreateSubKey(g_AppName) If lAppKey IsNot Nothing Then With lAppKey 'TODO: .SetValue("TileCacheDays", lCacheDays) Dim lKeyIndex As Integer = 1 Dim lTileServersFilename As String = TileServersFilename() If Not String.IsNullOrEmpty(lTileServersFilename) Then Dim lNewServersHTML As String = clsServer.WriteServers(Servers) If lNewServersHTML <> ReadTextFile(lTileServersFilename) Then WriteTextFile(lTileServersFilename, lNewServersHTML) End If End If 'For Each lName As String In Servers.Keys ' .SetValue("Server" & lKeyIndex, Servers.Item(lName).ToString) ' lKeyIndex += 1 'Next 'lKeyIndex = 1 For Each lName As String In Buddies.Keys .SetValue("Buddy" & lKeyIndex, lName & "|" & Buddies.Item(lName).LocationURL) lKeyIndex += 1 Next If IO.Directory.Exists(pTileCacheFolder) Then .SetValue("TileCacheFolder", pTileCacheFolder) End If .SetValue("TileServer", TileServer.Name) .SetValue("Zoom", Zoom) .SetValue("GPXShow", GPXShow) .SetValue("GPXPanTo", GPXPanTo) .SetValue("GPXZoomTo", GPXZoomTo) .SetValue("GPXFolder", GPXFolder) .SetValue("GPXLabelField", GPXLabelField) .SetValue("Dark", pDark) .SetValue("TileImages", pShowTileImages) .SetValue("TileNames", pShowTileNames) .SetValue("TileOutlines", pShowTileOutlines) .SetValue("GPSdetails", pShowGPSdetails) .SetValue("ControlsUse", ControlsUse) .SetValue("ControlsShow", ControlsShow) 'TODO: pControlsMargin, but in pixels or percent? .SetValue("CenterLat", CenterLat) .SetValue("CenterLon", CenterLon) .SetValue("GPSAutoStart", pGPSAutoStart) .SetValue("GPSFollow", pGPSCenterBehavior) .SetValue("GPSSymbolSize", GPSSymbolSize) .SetValue("TrackSymbolSize", TrackSymbolSize) .SetValue("RecordTrack", RecordTrack) .SetValue("RecordCellID", pRecordCellID) .SetValue("OpenCellIdKey", pOpenCellIdKey) .SetValue("DisplayTrack", pDisplayTrack) .SetValue("UploadOnStart", UploadOnStart) .SetValue("UploadOnStop", UploadOnStop) .SetValue("UploadTrackOnStop", UploadTrackOnStop) .SetValue("UploadPeriodic", UploadPeriodic) .SetValue("UploadPeriodicSeconds", UploadMinInterval.TotalSeconds) .SetValue("UploadPointURL", g_UploadPointURL) .SetValue("UploadTrackURL", g_UploadTrackURL) End With End If End If End Sub Public Property TileServerName() As String Get Return TileServer.Name End Get Set(ByVal value As String) If Servers IsNot Nothing AndAlso Servers.ContainsKey(value) Then Dim lServer As clsServer = Servers(value) SetServerCacheFolder(lServer) TileServer = lServer If Downloader IsNot Nothing Then Downloader.ClearQueue(QueueItemType.TileItem, -1) 'If new server does not cover the area we were looking at, pan to center of area new server covers If CenterLat > TileServer.LatMax OrElse _ CenterLat < TileServer.LatMin Then CenterLat = TileServer.LatMin + (TileServer.LatMax - TileServer.LatMin) / 2 End If If CenterLon > TileServer.LonMax OrElse _ CenterLon < TileServer.LonMin Then CenterLon = TileServer.LonMin + (TileServer.LonMax - TileServer.LonMin) / 2 End If SanitizeCenterLatLon() Dim lTitle As String = g_AppName & " " & TileServer.Name For Each lServer In TransparentTileServers lTitle &= ", " & lServer.Name Next Me.Text = lTitle RaiseEvent TileServerChanged() End If End Set End Property Public Sub EnableTransparentTileServer(ByVal aServerName As String, ByVal aEnable As Boolean) Dim lServer As clsServer = Servers(aServerName) If lServer IsNot Nothing Then SetServerCacheFolder(TileServer) If aEnable Then If Not TransparentTileServers.Contains(lServer) Then TransparentTileServers.Add(lServer) FitToServer(lServer) End If Else If TransparentTileServers.Contains(lServer) Then TransparentTileServers.Remove(lServer) End If End If RaiseEvent TileServerChanged() End If End Sub Private Sub SetServerCacheFolder(ByVal aTileServer As clsServer) aTileServer.CacheFolder = pTileCacheFolder & SafeFilename(aTileServer.Name.Replace(" ", "")) If aTileServer.TilePattern Is Nothing OrElse aTileServer.TilePattern.Length = 0 OrElse aTileServer.TilePattern.IndexOf("cacheonly") > -1 Then aTileServer.CacheOnly = True Else 'If TilePattern is a folder, use it instead of the default cache location Dim lSplit() As String = aTileServer.TilePattern.Split("*") If IO.Directory.Exists(lSplit(0)) Then aTileServer.CacheOnly = True aTileServer.CacheFolder = lSplit(0) End If End If If Not aTileServer.CacheFolder.EndsWith(g_PathChar) Then aTileServer.CacheFolder &= g_PathChar aTileServer.BadTileSize = FileSize(aTileServer.CacheFolder & "unavailable") 'Look for example "bad tile" named "unavailable" in server's cache folder End Sub Public Function FollowWebsiteURL(ByVal aURL As String) As Boolean If aURL.IndexOf(":") >= 0 Then Dim lLat As Double = 0 Dim lLon As Double = 0 Dim lZoom As Integer = Zoom 'Default to current zoom in case we don't get a zoom value from URL Dim lNorth As Double = 0 Dim lWest As Double = 0 Dim lSouth As Double = 0 Dim lEast As Double = 0 If TileServer.ParseWebmapURL(aURL, lLat, lLon, lZoom, lNorth, lWest, lSouth, lEast) Then CenterLat = lLat CenterLon = lLon SanitizeCenterLatLon() 'pShowURL = aURL If lZoom <> Zoom Then Zoom = lZoom Else NeedRedraw() End If FollowWebsiteURL = True Else MsgBox("Did not recognize map website link:" & vbLf & aURL, MsgBoxStyle.OkOnly, "Web Map URL") End If Else MsgBox("Copy a map website permanent link to the clipboard before using this menu", MsgBoxStyle.OkOnly, "Web Map URL") End If End Function Public Property Magnify() As Double Get Return pMagnify End Get Set(ByVal value As Double) pMagnify = value NeedRedraw() End Set End Property ''' <summary> ''' OSM zoom level currently being displayed on the form ''' </summary> ''' <remarks>varies from g_TileServer.ZoomMin to g_TileServer.ZoomMax</remarks> Public Property Zoom() As Integer Get Return pZoom End Get Set(ByVal value As Integer) If value <> pZoom Then Downloader.ClearQueue(QueueItemType.TileItem, -1) If value > TileServer.ZoomMax Then pZoom = TileServer.ZoomMax ElseIf value < TileServer.ZoomMin Then pZoom = TileServer.ZoomMin Else 'ZoomPreview(value) pZoom = value End If NeedRedraw() RaiseEvent Zoomed() pClearDelayedTiles = True End If End Set End Property Private Sub ZoomPreview(ByVal aNewZoom As Integer) If aNewZoom = pZoom + 1 OrElse aNewZoom = pZoom - 1 Then Dim lGraphics As Graphics = GetBitmapGraphics() If lGraphics IsNot Nothing Then With pBitmap Dim lBitmap As New Bitmap(pBitmap) Dim lHalfHeight As Integer = .Height >> 1 Dim lHalfWidth As Integer = .Width >> 1 Dim lQuarterHeight As Integer = lHalfHeight >> 1 Dim lQuarterWidth As Integer = lHalfWidth >> 1 Dim lSourceRect As Rectangle Dim lDestRect As Rectangle If aNewZoom = pZoom + 1 Then lSourceRect = New Rectangle(lQuarterWidth, lQuarterHeight, lHalfWidth, lHalfHeight) lDestRect = New Rectangle(0, 0, .Width, .Height) Else lGraphics.Clear(Color.White) lSourceRect = New Rectangle(0, 0, .Width, .Height) lDestRect = New Rectangle(lQuarterWidth, lQuarterHeight, lHalfWidth, lHalfHeight) End If lGraphics.DrawImage(lBitmap, lDestRect, lSourceRect, GraphicsUnit.Pixel) ReleaseBitmapGraphics() pClearDelayedTiles = False 'We have provided something to to see at new zoom, no need to clear End With End If End If End Sub Private Function GetBitmapGraphics() As Graphics Try pBitmapMutex.WaitOne() If pBitmap Is Nothing Then pBitmapMutex.ReleaseMutex() Return Nothing Else Dim lGraphics As Graphics = Graphics.FromImage(pBitmap) lGraphics.Clip = New Drawing.Region(New Drawing.Rectangle(0, 0, pBitmap.Width, pBitmap.Height)) Return lGraphics End If Catch e As Exception Return Nothing End Try End Function Private Sub ReleaseBitmapGraphics() pBitmapMutex.ReleaseMutex() End Sub ''' <summary> ''' Calculate the top left and bottom right OSM tiles that will fit within aBounds ''' </summary> ''' <param name="aBounds">Rectangle containing the drawn tiles</param> ''' <param name="aOffsetToCenter">Pixel offset from corner of tile to allow accurate pCenterLat, pCenterLon</param> ''' <param name="aTopLeft">OSM coordinates of northwestmost visible tile</param> ''' <param name="aBotRight">OSM coordinates of southeastmost visible tile</param> ''' <remarks>Also sets LatHeight, LonWidth</remarks> Private Sub FindTileBounds(ByVal aServer As clsServer, _ ByVal aBounds As RectangleF, _ ByRef aOffsetToCenter As Point, _ ByRef aTopLeft As Point, ByRef aBotRight As Point) Dim lOffsetFromTileEdge As Point Dim lCentermostTile As Point = CalcTileXY(aServer, CenterLat, CenterLon, pZoom, lOffsetFromTileEdge) Dim lNorth As Double, lWest As Double, lSouth As Double, lEast As Double CalcLatLonFromTileXY(lCentermostTile, pZoom, lNorth, lWest, lSouth, lEast) LatHeight = (lNorth - lSouth) * aBounds.Height / aServer.TileSize LonWidth = (lEast - lWest) * aBounds.Width / aServer.TileSize SanitizeCenterLatLon() aTopLeft = New Point(lCentermostTile.X, lCentermostTile.Y) Dim x As Integer = (aBounds.Width / 2) - lOffsetFromTileEdge.X 'Move west until we find the edge of g, TODO: find faster with mod? While x > 0 aTopLeft.X -= 1 x -= aServer.TileSize End While aOffsetToCenter.X = x Dim y As Integer = (aBounds.Height / 2) - lOffsetFromTileEdge.Y 'Move north until we find the edge of g, TODO: find faster with mod? While y > 0 aTopLeft.Y -= 1 y -= aServer.TileSize End While aOffsetToCenter.Y = y aBotRight = New Point(lCentermostTile.X, lCentermostTile.Y) x = (aBounds.Width / 2) - lOffsetFromTileEdge.X + aServer.TileSize 'Move east until we find the edge of g, TODO: find faster with mod? While x < aBounds.Width aBotRight.X += 1 x += aServer.TileSize End While y = (aBounds.Height / 2) - lOffsetFromTileEdge.Y + aServer.TileSize 'Move south until we find the edge of g, TODO: find faster with mod? While y < aBounds.Height aBotRight.Y += 1 y += aServer.TileSize End While End Sub Private Function TilesPointsInView(ByVal aTopLeft As Point, ByVal aBotRight As Point) As SortedList(Of Single, Point) Dim lTilePoints As New SortedList(Of Single, Point) Dim x, y As Integer Dim lMidX As Integer = (aTopLeft.X + aBotRight.X) / 2 Dim lMidY As Integer = (aTopLeft.Y + aBotRight.Y) / 2 Dim lDistance As Single 'Loop through each visible tile For x = aTopLeft.X To aBotRight.X For y = aTopLeft.Y To aBotRight.Y Try lDistance = (x - lMidX) ^ 2 + (y - lMidY) ^ 2 While lTilePoints.ContainsKey(lDistance) lDistance += 0.1 End While lTilePoints.Add(lDistance, New Point(x, y)) Catch lDistance = 11 While lTilePoints.ContainsKey(lDistance) lDistance += 0.1 End While lTilePoints.Add(lDistance, New Point(x, y)) End Try Next Next Return lTilePoints End Function Public Sub ReDownloadAllVisibleTiles() Dim lOffsetToCenter As Point Dim lTopLeft As Point Dim lBotRight As Point FindTileBounds(TileServer, New RectangleF(0, 0, Width, Height), lOffsetToCenter, lTopLeft, lBotRight) For Each lTilePoint As Point In TilesPointsInView(lTopLeft, lBotRight).Values Dim lTileFilename As String = TileServer.TileFilename(lTilePoint, pZoom, False) If lTileFilename.Length > 0 Then Downloader.DeleteTile(lTileFilename) NeedRedraw() End If Next End Sub ''' <summary> ''' Draw all the visible tiles from all active tile servers ''' </summary> ''' <param name="g">Graphics object to be drawn into</param> Public Sub DrawTiles(ByVal g As Graphics) If TileServer.Transparent Then g.Clear(Color.White) TileServer.Opacity = 1 DrawTiles(TileServer, g) For Each lServer As clsServer In TransparentTileServers If Not lServer.Transparent AndAlso lServer.Opacity = 1 Then lServer.Opacity = TransparentOpacity DrawTiles(lServer, g) Next End Sub ''' <summary> ''' Draw all the visible tiles from the given tile server ''' </summary> ''' <param name="g">Graphics object to be drawn into</param> Private Sub DrawTiles(ByVal aServer As clsServer, ByVal g As Graphics) Dim lOffsetToCenter As Point Dim lTopLeft As Point Dim lBotRight As Point FindTileBounds(aServer, g.ClipBounds, lOffsetToCenter, lTopLeft, lBotRight) Dim x, y As Integer Dim lOffsetFromWindowCorner As Point 'TODO: check available memory before deciding how many tiles to keep in RAM Downloader.TileRAMcacheLimit = (lBotRight.X - lTopLeft.X + 1) * (lBotRight.Y - lTopLeft.Y + 1) * 2 For Each lTilePoint As Point In TilesPointsInView(lTopLeft, lBotRight).Values If pRedrawPending Then Exit Sub x = lTilePoint.X y = lTilePoint.Y lOffsetFromWindowCorner.X = (x - lTopLeft.X) * aServer.TileSize + lOffsetToCenter.X lOffsetFromWindowCorner.Y = (y - lTopLeft.Y) * aServer.TileSize + lOffsetToCenter.Y Dim lDrewTile As Boolean = DrawTile(aServer, lTilePoint, pZoom, g, lOffsetFromWindowCorner, 0) If Not lDrewTile Then ' search for cached tiles at other zoom levels to substitute 'First try tiles zoomed farther out Dim lZoom As Integer Dim lX As Integer = x Dim lY As Integer = y Dim lNextX As Integer Dim lNextY As Integer Dim lZoomedTilePortion As Integer = aServer.TileSize Dim lFromX As Integer = 0 Dim lFromY As Integer = 0 Dim lRectOrigTile As New Rectangle(lOffsetFromWindowCorner.X, lOffsetFromWindowCorner.Y, aServer.TileSize, aServer.TileSize) Dim lZoomMin As Integer = Math.Max(aServer.ZoomMin, pZoom - 4) For lZoom = pZoom - 1 To lZoomMin Step -1 'Tile coordinates of next zoom out are half lNextX = lX >> 1 lNextY = lY >> 1 'Half as much of next zoomed tile width and height will fit lZoomedTilePortion >>= 1 'Offset within the tile counts half as much in next zoom out lFromX >>= 1 lFromY >>= 1 'If zoomed from an odd-numbered tile, it was in the right and/or bottom half of next zoom out If lX > lNextX << 1 Then lFromX += aServer.HalfTileSize If lY > lNextY << 1 Then lFromY += aServer.HalfTileSize If DrawTile(aServer, New Drawing.Point(lNextX, lNextY), lZoom, g, lRectOrigTile, _ New Rectangle(lFromX, lFromY, lZoomedTilePortion, lZoomedTilePortion), -1) Then Exit For 'found a zoomed out tile to draw, don't keep looking for one zoomed out farther End If lX = lNextX lY = lNextY Next If pZoom < aServer.ZoomMax Then ' Try to draw tiles within this tile at finer zoom level lZoom = pZoom + 1 Dim lDoubleX As Integer = x << 1 Dim lFineTilePoint As New Drawing.Point(lDoubleX, y << 1) ' Portion of the tile covered by a finer zoom tile Dim lRectDestination As New Rectangle(lOffsetFromWindowCorner.X, _ lOffsetFromWindowCorner.Y, _ aServer.HalfTileSize, aServer.HalfTileSize) ' upper left tile If Not DrawTile(aServer, lFineTilePoint, lZoom, g, lRectDestination, aServer.TileSizeRect, -1) Then 'TODO: four tiles at next finer zoom level, at this and other three DrawTile below End If ' upper right tile lFineTilePoint.X += 1 lRectDestination.X = lOffsetFromWindowCorner.X + aServer.HalfTileSize DrawTile(aServer, lFineTilePoint, lZoom, g, lRectDestination, aServer.TileSizeRect, -1) ' lower right tile lFineTilePoint.Y += 1 lRectDestination.Y = lOffsetFromWindowCorner.Y + aServer.HalfTileSize DrawTile(aServer, lFineTilePoint, lZoom, g, lRectDestination, aServer.TileSizeRect, -1) ' lower left tile lFineTilePoint.X = lDoubleX lRectDestination.X = lOffsetFromWindowCorner.X DrawTile(aServer, lFineTilePoint, lZoom, g, lRectDestination, aServer.TileSizeRect, -1) End If End If Next If pRedrawPending Then Exit Sub If ControlsShow Then g.DrawLine(pPenBlack, pControlsMargin, 0, pControlsMargin, pBitmap.Height) g.DrawLine(pPenBlack, 0, pControlsMargin, pBitmap.Width, pControlsMargin) g.DrawLine(pPenBlack, pBitmap.Width - pControlsMargin, 0, pBitmap.Width - pControlsMargin, pBitmap.Height) g.DrawLine(pPenBlack, 0, pBitmap.Height - pControlsMargin, pBitmap.Width, pBitmap.Height - pControlsMargin) End If If GPXShow Then DrawLayers(g, lTopLeft, lOffsetToCenter) If pShowCopyright AndAlso pShowTileImages AndAlso Not String.IsNullOrEmpty(aServer.Copyright) Then g.DrawString(aServer.Copyright, pFontCopyright, pBrushCopyright, 3, pBitmap.Height - 20) End If If pShowDate OrElse LabelServer IsNot Nothing Then Dim lHeader As String = "" If pShowDate Then lHeader &= DateTime.Now.ToString("yyyy-MM-dd HH:mm ") If LabelServer IsNot Nothing Then lHeader &= LabelServer.BuildWebmapURL(CenterLat, CenterLon, Zoom, LatMax, LonMin, LatMin, LonMax) 'CenterLon.ToString("#.#######") & ", " & CenterLat.ToString("#.#######") g.DrawString(lHeader, pFontTileLabel, pBrushBlack, 3, 3) End If If pRedrawPending Then Exit Sub DrewTiles(g, lTopLeft, lOffsetToCenter) End Sub ''' <summary> ''' Find the tile at screen position aX, aY ''' </summary> ''' <param name="aBounds">Rectangle containing the drawn tiles</param> ''' <param name="aX">Screen-based X value for tile to search for</param> ''' <param name="aY">Screen-based Y value for tile to search for</param> ''' <returns>filename of tile at aX, aY</returns> Private Function FindTileFilename(ByVal aServer As clsServer, _ ByVal aBounds As RectangleF, _ Optional ByVal aX As Integer = -1, _ Optional ByVal aY As Integer = -1) As String Dim lOffsetToCenter As Point Dim lTopLeft As Point Dim lBotRight As Point FindTileBounds(aServer, aBounds, lOffsetToCenter, lTopLeft, lBotRight) Dim TilePoint As Point Dim lOffsetFromWindowCorner As Point 'Loop through each visible tile For x As Integer = lTopLeft.X To lBotRight.X For y As Integer = lTopLeft.Y To lBotRight.Y TilePoint = New Point(x, y) lOffsetFromWindowCorner.X = (x - lTopLeft.X) * TileServer.TileSize + lOffsetToCenter.X lOffsetFromWindowCorner.Y = (y - lTopLeft.Y) * TileServer.TileSize + lOffsetToCenter.Y With lOffsetFromWindowCorner If .X <= aX AndAlso .X + TileServer.TileSize >= aX AndAlso .Y <= aY AndAlso .Y + TileServer.TileSize >= aY Then Return TileServer.TileFilename(TilePoint, pZoom, False) End If End With Next Next Return "" End Function ''' <summary> ''' Callback is called when a tile has just finished downloading, draws the tile into the display ''' </summary> ''' <param name="aTilePoint">which tile</param> ''' <param name="aZoom">Zoom level of downloaded tile</param> ''' <param name="aTileFilename"></param> ''' <remarks></remarks> Public Sub DownloadedTile(ByVal aTilePoint As Point, ByVal aZoom As Integer, ByVal aTileFilename As String, ByVal aTileServerURL As String) Implements IQueueListener.DownloadedTile If aZoom = pZoom Then If aTileServerURL = TileServer.TilePattern Then NeedRedraw() Else For Each lServer As clsServer In TransparentTileServers If aTileServerURL = lServer.TilePattern Then NeedRedraw() Exit For End If Next End If End If 'pRedrawWhenFinishedQueue = True 'Just draw the tile downloaded, not the whole display 'Dim lGraphics As Graphics = GetBitmapGraphics() 'If lGraphics IsNot Nothing Then ' If aZoom = pZoom Then ' Dim lOffsetToCenter As Point ' Dim lTopLeft As Point ' Dim lBotRight As Point ' FindTileBounds(lGraphics.ClipBounds, lOffsetToCenter, lTopLeft, lBotRight) ' Dim lOffsetFromWindowCorner As Point ' lOffsetFromWindowCorner.X = (aTilePoint.X - lTopLeft.X) * g_TileServer.TileSize + lOffsetToCenter.X ' lOffsetFromWindowCorner.Y = (aTilePoint.Y - lTopLeft.Y) * g_TileServer.TileSize + lOffsetToCenter.Y ' DrawTile(aTilePoint, aZoom, lGraphics, lOffsetFromWindowCorner, -1) ' Else ' 'TODO: draw tiles at different zoom levels? ' 'Would be nice when doing DownloadDescendants to see progress, but would also be confusing when tile download completes after zoom ' End If ' ReleaseBitmapGraphics() ' Try 'This method will be running in another thread, so we need to call Refresh in a complicated way ' Me.Invoke(pRefreshCallback) ' Catch ' 'Ignore if we could not refresh, probably because form is closing ' End Try 'End If End Sub Private Sub RequestBuddyPoint(ByVal o As Object) If Buddies Is Nothing OrElse Buddies.Count = 0 Then MsgBox("Add Buddies Before Finding them", MsgBoxStyle.OkOnly, "No Buddies Found") Else For Each lBuddy As clsBuddy In Buddies.Values If lBuddy.Selected Then Downloader.Enqueue(lBuddy.LocationURL, IO.Path.GetTempPath & SafeFilename(lBuddy.Name), QueueItemType.PointItem, 0, True, lBuddy) Next End If End Sub Public Sub DownloadedItem(ByVal aItem As clsQueueItem) Implements IQueueListener.DownloadedItem Dim lNeedRedrawNow As Boolean = False Select Case aItem.ItemType Case QueueItemType.IconItem Try Dim lBitmap As New Drawing.Bitmap(aItem.Filename) Dim lCacheIconFolder As String = (pTileCacheFolder & "Icons").ToLower & g_PathChar If aItem.Filename.ToLower.StartsWith(lCacheIconFolder) Then 'Geocache or other icon that lives in "Icons" folder in pTileCacheFolder Dim lIconName As String = IO.Path.ChangeExtension(aItem.Filename, "").TrimEnd(".").Substring(lCacheIconFolder.Length).Replace(g_PathChar, "|") g_WaypointIcons.Add(lIconName.ToLower, lBitmap) Else g_WaypointIcons.Add(aItem.Filename.ToLower, lBitmap) End If pRedrawWhenFinishedQueue = True Catch e As Exception End Try Case QueueItemType.PointItem Try Dim lBuddy As clsBuddy = aItem.ItemObject If lBuddy IsNot Nothing Then If lBuddy.LoadFile(aItem.Filename, pTileCacheFolder & "Icons" & g_PathChar & "Buddy") Then If lBuddy.IconFilename.Length > 0 AndAlso Not IO.File.Exists(lBuddy.IconFilename) AndAlso lBuddy.IconURL.Length > 0 Then Downloader.Enqueue(lBuddy.IconURL, lBuddy.IconFilename, QueueItemType.IconItem, , False, lBuddy) End If 'Zoom out to include this buddy in the view SetCenterFromDevice(lBuddy.Waypoint.lat, lBuddy.Waypoint.lon, 3) NeedRedraw() If pBuddyAlarmEnabled AndAlso pBuddyAlarmMeters > 0 Then If MetersBetweenLatLon(pBuddyAlarmLat, pBuddyAlarmLon, lBuddy.Waypoint.lat, lBuddy.Waypoint.lon) < pBuddyAlarmMeters Then Windows.Forms.MessageBox.Show(lBuddy.Name & " approaches", "Nearby Buddy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) pBuddyAlarmEnabled = False End If End If End If End If Catch ex As Exception 'Maybe we could not parse lat and lon? Dbg("DownloadedPoint:Exception:" & ex.Message) End Try End Select End Sub Public Sub NeedRedraw() Try 'If running in another thread, can't call Refresh directly If Me.InvokeRequired Then Me.Invoke(pRedrawCallback) Else Redraw() End If Catch 'Ignore if we could not refresh, probably because form is closing End Try End Sub Sub FinishedQueue(ByVal aQueueIndex As Integer) Implements IQueueListener.FinishedQueue If pRedrawWhenFinishedQueue Then pRedrawWhenFinishedQueue = False NeedRedraw() End If End Sub Public Function LatLonInView(ByVal aLat As Double, ByVal aLon As Double) As Boolean Return (aLat < LatMax AndAlso _ aLat > LatMin AndAlso _ aLon < LonMax AndAlso _ aLon > LonMin) End Function Private Sub DrawLayers(ByVal g As Graphics, ByVal aTopLeftTile As Point, ByVal aOffsetToCenter As Point) If Layers IsNot Nothing AndAlso Layers.Count > 0 Then For Each lLayer As clsLayer In Layers If pRedrawPending Then Exit Sub lLayer.Render(TileServer, g, aTopLeftTile, aOffsetToCenter) Next End If If Buddies IsNot Nothing AndAlso Buddies.Count > 0 Then Dim lUtcNow As Date = Date.UtcNow Dim lWaypoints As New Generic.List(Of clsGPXwaypoint) For Each lBuddy As clsBuddy In Buddies.Values If lBuddy.Selected AndAlso lBuddy.Waypoint IsNot Nothing Then Dim lWaypoint As clsGPXwaypoint = lBuddy.Waypoint.Clone If lWaypoint.timeSpecified Then lWaypoint.name &= " " & TimeSpanString(lUtcNow.Subtract(lWaypoint.time)) End If lWaypoints.Add(lWaypoint) End If Next If lWaypoints.Count > 0 Then Dim lLayer As New clsLayerGPX(lWaypoints, Me) lLayer.LabelField = "name" lLayer.LabelMinZoom = 0 'Always label buddies lLayer.Render(TileServer, g, aTopLeftTile, aOffsetToCenter) End If End If End Sub ''' <summary> ''' Draw a tile into the graphics context at the offset ''' </summary> ''' <param name="aTilePoint">tile to draw</param> ''' <param name="aZoom">which zoom level</param> ''' <param name="g">Graphics context to draw in</param> ''' <param name="aOffset">distance from top left of Graphics to draw tile</param> ''' <param name="aPriority">download priority for getting tile if not present, -1 to skip download, 0 for highest priority</param> ''' <returns>True if tile was drawn or did not need to be drawn, False if needed but not drawn</returns> ''' <remarks></remarks> Private Function DrawTile(ByVal aServer As clsServer, ByVal aTilePoint As Point, ByVal aZoom As Integer, ByVal g As Graphics, ByVal aOffset As Point, ByVal aPriority As Integer) As Boolean Try Dim lDrewImage As Boolean = False If pShowTileImages Then Dim lDestRect As New Rectangle(aOffset.X, aOffset.Y, aServer.TileSize, aServer.TileSize) lDrewImage = DrawTile(aServer, aTilePoint, aZoom, g, lDestRect, aServer.TileSizeRect, 0) End If If pClearDelayedTiles AndAlso Not lDrewImage AndAlso Not aServer.Transparent Then g.FillRectangle(pBrushWhite, aOffset.X, aOffset.Y, aServer.TileSize, aServer.TileSize) End If If pShowTileOutlines Then g.DrawRectangle(pPenBlack, aOffset.X, aOffset.Y, aServer.TileSize, aServer.TileSize) If pShowTileNames Then Dim lTileFileName As String = aServer.TileFilename(aTilePoint, aZoom, False) If lTileFileName.Length > 0 Then g.DrawString(lTileFileName.Substring(aServer.CacheFolder.Length).Replace(aServer.FileExtension, ""), _ pFontTileLabel, _ pBrushBlack, aOffset.X, aOffset.Y) End If End If Return lDrewImage OrElse Not pShowTileImages Catch Return False End Try End Function ''' <summary> ''' Draw a tile into the graphics context, scaled/positioned with the given destination and source rectangles ''' </summary> ''' <param name="aTilePoint">tile to draw</param> ''' <param name="aZoom">which zoom level</param> ''' <param name="g">Graphics context to draw in</param> ''' <param name="aDrawRect">rectangle to fill with tile</param> ''' <param name="aImageRect">subset of tile image to draw</param> ''' <param name="aPriority">download priority for getting tile if not present, -1 to skip download, 0 for highest priority</param> ''' <returns>True if tile was drawn or did not need to be drawn, False if needed but not drawn</returns> ''' <remarks></remarks> Private Function DrawTile(ByVal aServer As clsServer, ByVal aTilePoint As Point, ByVal aZoom As Integer, ByVal g As Graphics, ByVal aDrawRect As Rectangle, ByVal aImageRect As Rectangle, ByVal aPriority As Integer) As Boolean Try If Not pShowTileImages Then Return True Dim lTileImage As Bitmap = TileBitmap(aServer, aTilePoint, aZoom, aPriority) If lTileImage IsNot Nothing AndAlso lTileImage.Width > 1 Then #If Smartphone Then If aServer.Transparent Then Dim imageAttr As New Drawing.Imaging.ImageAttributes imageAttr.SetColorKey(Color.White, Color.White) g.DrawImage(lTileImage, aDrawRect, aImageRect.X, aImageRect.Y, aImageRect.Width, aImageRect.Height, GraphicsUnit.Pixel, imageAttr) Else g.DrawImage(lTileImage, aDrawRect, aImageRect, GraphicsUnit.Pixel) End If #Else If aServer.Opacity < 1 Then Dim cm As New System.Drawing.Imaging.ColorMatrix cm.Matrix33 = TransparentOpacity Dim lAttrs As New System.Drawing.Imaging.ImageAttributes lAttrs.SetColorMatrix(cm) g.DrawImage(lTileImage, aDrawRect, aImageRect.X, aImageRect.Y, aImageRect.Width, aImageRect.Height, GraphicsUnit.Pixel, lAttrs) Else g.DrawImage(lTileImage, aDrawRect, aImageRect.X, aImageRect.Y, aImageRect.Width, aImageRect.Height, GraphicsUnit.Pixel) End If #End If Return True End If Catch End Try Return False End Function ''' <summary> ''' Get a tile image from pDownloader. ''' </summary> ''' <param name="aTilePoint">tile to draw</param> ''' <param name="aZoom">which zoom level</param> ''' <param name="aPriority">download priority for getting tile if not present, -1 to skip download, 0 for highest priority</param> ''' <returns>Bitmap of tile or Nothing if not yet available</returns> ''' <remarks> ''' If tile is found not found in local cache, Nothing is returned. If aPriority > -1, download of tile is queued ''' returns unmarked tile if marked was requested but not available ''' </remarks> Private Function TileBitmap(ByVal aServer As clsServer, ByVal aTilePoint As Point, ByVal aZoom As Integer, ByVal aPriority As Integer) As Bitmap Dim lTileFileName As String = aServer.TileFilename(aTilePoint, aZoom, pUseMarkedTiles) If lTileFileName.Length = 0 Then Return Nothing Else Dim lTileImage As Bitmap = Downloader.GetTileBitmap(aServer, lTileFileName, aTilePoint, aZoom, aPriority, False) 'Fall back to using unmarked tile if we have it but not a marked version If pUseMarkedTiles AndAlso lTileImage Is Nothing Then lTileFileName = aServer.TileFilename(aTilePoint, pZoom, False) lTileImage = Downloader.GetTileBitmap(aServer, lTileFileName, aTilePoint, aZoom, aPriority, False) End If Return lTileImage End If End Function Public Sub SanitizeCenterLatLon() If Math.Abs(CenterLat) > 1000 OrElse Math.Abs(CenterLon) > 1000 Then CenterLat = 33.8 CenterLon = -84.3 End If While CenterLon > 180 CenterLon -= 360 End While While CenterLon < -180 CenterLon += 360 End While FitToServer(TileServer) LatMin = CenterLat - LatHeight / 2 LatMax = CenterLat + LatHeight / 2 LonMin = CenterLon - LonWidth / 2 LonMax = CenterLon + LonWidth / 2 RaiseEvent Panned() End Sub Private Sub FitToServer(ByVal aServer As clsServer) If CenterLat > aServer.LatMax Then CenterLat = aServer.LatMax If CenterLat < aServer.LatMin Then CenterLat = aServer.LatMin If CenterLon > aServer.LonMax Then CenterLon = aServer.LonMax If CenterLon < aServer.LonMin Then CenterLon = aServer.LonMin If pZoom > aServer.ZoomMax Then Zoom = aServer.ZoomMax If pZoom < aServer.ZoomMin Then Zoom = aServer.ZoomMin End Sub Private Sub MouseDownLeft(ByVal e As System.Windows.Forms.MouseEventArgs) MouseDragging = True MouseDragStartLocation.X = e.X MouseDragStartLocation.Y = e.Y MouseDownLat = CenterLat MouseDownLon = CenterLon End Sub Private Sub ctlMap_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown pLastKeyDown = e.KeyCode If pLastKeyDown = 229 Then ' ProcessKey means we have to look harder to find actual key pressed 'For lKeyCode As Integer = 0 To 255 ' If GetAsyncKeyState(lKeyCode) And Windows.Forms.Keys.KeyCode Then ' pLastKeyDown = lKeyCode ' Exit Sub ' record the lowest numbered key code currently down, not necessarily the one triggering KeyDown ' End If 'Next End If End Sub Private Sub Event_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp e.Handled = True Dim lNeedRedraw As Boolean = True Select Case e.KeyCode Case Keys.Right : CenterLon += MetersPerPixel(Zoom, TileServer.TileSize) * Me.Width / g_CircumferenceOfEarth * 180 Case Keys.Left : CenterLon -= MetersPerPixel(Zoom, TileServer.TileSize) * Me.Width / g_CircumferenceOfEarth * 180 Case Keys.Up If pLastKeyDown = 131 Then 'using scroll wheel Zoom += 1 : lNeedRedraw = False Else CenterLat += MetersPerPixel(Zoom, TileServer.TileSize) * Me.Height / g_CircumferenceOfEarth * 90 End If Case Keys.Down If pLastKeyDown = 131 Then 'using scroll wheel Zoom -= 1 : lNeedRedraw = False Else CenterLat -= MetersPerPixel(Zoom, TileServer.TileSize) * Me.Height / g_CircumferenceOfEarth * 90 End If Case Keys.A : Zoom -= 1 : lNeedRedraw = False Case Keys.Q : Zoom += 1 : lNeedRedraw = False Case Else e.Handled = False lNeedRedraw = False End Select If lNeedRedraw Then ManuallyNavigated() End If End Sub Private Sub Event_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp MouseDragging = False If ControlsUse AndAlso _ Math.Abs(MouseDragStartLocation.X - e.X) < pControlsMargin / 2 AndAlso _ Math.Abs(MouseDragStartLocation.Y - e.Y) < pControlsMargin / 2 Then 'Count this as a tap/click and navigate if in a control area Dim lNeedRedraw As Boolean = True If e.X < pControlsMargin Then If e.Y < pControlsMargin Then 'Top Left Corner, zoom in Zoom += 1 : lNeedRedraw = False ElseIf e.Y > Me.Height - pControlsMargin Then Zoom -= 1 : lNeedRedraw = False 'Bottom Left Corner, zoom out Else 'Left Edge, pan left CenterLon -= MetersPerPixel(pZoom, TileServer.TileSize) * Me.Width / g_CircumferenceOfEarth * 180 End If ElseIf e.X > Me.Width - pControlsMargin Then If e.Y < pControlsMargin Then 'Top Right Corner, zoom in Zoom += 1 : lNeedRedraw = False ElseIf e.Y > Me.Height - pControlsMargin Then Zoom -= 1 : lNeedRedraw = False 'Bottom Right Corner, zoom out Else 'Right Edge, pan right CenterLon += MetersPerPixel(pZoom, TileServer.TileSize) * Me.Width / g_CircumferenceOfEarth * 180 End If ElseIf e.Y < pControlsMargin Then 'Top edge, pan up CenterLat += MetersPerPixel(pZoom, TileServer.TileSize) * Me.Height / g_CircumferenceOfEarth * 90 ElseIf e.Y > Me.Height - pControlsMargin Then 'Bottom edge, pan down CenterLat -= MetersPerPixel(pZoom, TileServer.TileSize) * Me.Height / g_CircumferenceOfEarth * 90 Else lNeedRedraw = False End If If lNeedRedraw Then ManuallyNavigated() End If Else ManuallyNavigated() End If End Sub Private Sub Event_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed Downloader.Enabled = False Uploader.Enabled = False Diagnostics.Process.GetCurrentProcess.Kill() 'Try to kill our own process, making sure all threads stop End Sub Private Sub Event_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint If pBitmap IsNot Nothing Then pBitmapMutex.WaitOne() Dim lMapRectangle As System.Drawing.Rectangle = MapRectangle() With lMapRectangle If pMagnify = 1 Then e.Graphics.DrawImage(pBitmap, .Left, .Top) Else Dim lMagnifiedWidth As Integer = .Width * pMagnify Dim lMagnifiedHeight As Integer = .Height * pMagnify Dim lMagnifiedLeft As Integer = .Left - (lMagnifiedWidth - .Width) / 2 Dim lMagnifiedTop As Integer = .Top - (lMagnifiedHeight - .Height) / 2 e.Graphics.DrawImage(pBitmap, New Rectangle(lMagnifiedLeft, lMagnifiedTop, lMagnifiedWidth, lMagnifiedHeight), lMapRectangle, GraphicsUnit.Pixel) End If End With pBitmapMutex.ReleaseMutex() End If End Sub ' Prevent flickering when default implementation redraws background Protected Overrides Sub OnPaintBackground(ByVal e As PaintEventArgs) End Sub Private Sub Event_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize With MapRectangle() If .Width > 0 AndAlso .Height > 0 Then pBitmapMutex.WaitOne() pBitmap = New Bitmap(.Width, .Height, Drawing.Imaging.PixelFormat.Format24bppRgb) pControlsMargin = Math.Min(pBitmap.Width, pBitmap.Height) / 4 pBitmapMutex.ReleaseMutex() End If End With NeedRedraw() End Sub Public Sub OpenFiles(ByVal aFilenames() As String) Dim lGPXPanTo As Boolean = GPXPanTo Dim lGPXZoomTo As Boolean = GPXZoomTo If aFilenames.Length > 1 Then GPXPanTo = False GPXZoomTo = False End If 'Dim lSaveTitle As String = Me.Text Dim lNumFiles As Integer = aFilenames.Length Dim lCurFile As Integer = 1 For Each lFilename As String In aFilenames If IO.Directory.Exists(lFilename) Then OpenFiles(IO.Directory.GetFileSystemEntries(lFilename)) Else RaiseEvent StatusChanged("Loading " & lCurFile & "/" & lNumFiles & " '" & IO.Path.GetFileNameWithoutExtension(lFilename) & "'") OpenFile(lFilename) lCurFile += 1 End If Next 'Me.Text = lSaveTitle If aFilenames.Length > 1 Then GPXPanTo = lGPXPanTo GPXZoomTo = lGPXZoomTo If GPXZoomTo Then ZoomToAll() End If If Not GPXPanTo AndAlso Not GPXZoomTo Then NeedRedraw() RaiseEvent StatusChanged(Nothing) End Sub Public Function OpenFile(ByVal aFilename As String) As clsLayer Dim lLayer As clsLayer = Nothing Select Case IO.Path.GetExtension(aFilename).ToLower Case ".cell" : lLayer = OpenCell(aFilename) Case ".jpg", ".jpeg" : lLayer = OpenPhoto(aFilename) Case Else : lLayer = OpenGPX(aFilename) End Select If lLayer IsNot Nothing Then RaiseEvent OpenedLayer(lLayer) End If Return lLayer End Function Public Function OpenCell(ByVal aFilename As String) As clsCellLayer Dim lLayer As New clsCellLayer(aFilename, Me) Layers.Add(lLayer) NeedRedraw() Return lLayer End Function Public Function OpenPhoto(ByVal aFilename As String) As clsLayer Dim lLayer As clsLayerGPX = Nothing #If Not Smartphone Then Dim lExif As New ExifWorks(aFilename) Dim lNeedToSearchTracks As Boolean = False Dim lLatitude As Double = lExif.Latitude Dim lLongitude As Double = lExif.Longitude Dim lStr As String = Nothing, lStrMinutes As String = Nothing, lStrSeconds As String = Nothing If Double.IsNaN(lLatitude) OrElse Double.IsNaN(lLongitude) Then lNeedToSearchTracks = True Else DegreesMinutesSeconds(lLatitude, lStr, lStrMinutes, lStrSeconds) lStr &= " " & lStrMinutes & "' " & lStrSeconds & """" If Not lStrSeconds.Contains(".") Then lNeedToSearchTracks = True End If Dim lPhotoDate As DateTime = lExif.GPSDateTime If lPhotoDate.Year < 2 Then lPhotoDate = lExif.DateTimeOriginal.Add(pImportOffsetFromUTC) End If If lNeedToSearchTracks Then Dim lClosestPoint As clsGPXwaypoint = ClosestPoint(lPhotoDate) If lClosestPoint IsNot Nothing Then Dim lMsg As String = "" If Not Double.IsNaN(lLatitude) Then DegreesMinutesSeconds(lLatitude, lStr, lStrMinutes, lStrSeconds) lMsg &= "ExifLat = " & lStr & " " & lStrMinutes & "' " & lStrSeconds & """" End If lLatitude = lClosestPoint.lat DegreesMinutesSeconds(lLatitude, lStr, lStrMinutes, lStrSeconds) lMsg &= "GPXLat = " & lStr & " " & lStrMinutes & "' " & lStrSeconds & """" If Not Double.IsNaN(lLongitude) Then DegreesMinutesSeconds(lLongitude, lStr, lStrMinutes, lStrSeconds) lMsg &= "ExifLon = " & lStr & " " & lStrMinutes & "' " & lStrSeconds & """" End If lLongitude = lClosestPoint.lon DegreesMinutesSeconds(lLongitude, lStr, lStrMinutes, lStrSeconds) lMsg &= "GPXLon = " & lStr & " " & lStrMinutes & "' " & lStrSeconds & """" Dbg(lMsg) End If End If If Not Double.IsNaN(lLatitude) AndAlso Not Double.IsNaN(lLongitude) Then Dim lWaypoints As New Generic.List(Of clsGPXwaypoint) Dim lWaypoint As New clsGPXwaypoint("wpt", lLatitude, lLongitude) With lWaypoint .name = IO.Path.GetFileNameWithoutExtension(aFilename) .sym = aFilename .url = aFilename .time = lPhotoDate .SetExtension("LocalTime", Format(lExif.DateTimeOriginal, "yyyy-MM-dd HH:mm:ss")) End With lWaypoints.Add(lWaypoint) lLayer = New clsLayerGPX(lWaypoints, Me) lLayer.Filename = aFilename lLayer.LabelField = "name" Dim lBounds As New clsGPXbounds() With lBounds .maxlat = lLatitude .minlat = lLatitude .maxlon = lLongitude .minlon = lLongitude End With lLayer.Bounds = lBounds Me.Layers.Add(lLayer) If lNeedToSearchTracks Then LayersImportedByTime.Add(lLayer) If GPXPanTo Then CenterLat = lLatitude CenterLon = lLongitude SanitizeCenterLatLon() End If NeedRedraw() End If #End If Return lLayer End Function Public Sub ReImportLayersByDate() For Each lLayer As clsLayerGPX In LayersImportedByTime lLayer.Bounds = New clsGPXbounds For Each lWaypoint As clsGPXwaypoint In lLayer.GPX.wpt Dim lLocalTime As Date = Date.Parse(lWaypoint.GetExtension("LocalTime") & "Z") Dim lUTC As Date = lLocalTime.Add(pImportOffsetFromUTC) Dim lClosestPoint As clsGPXwaypoint = ClosestPoint(lUTC) If lClosestPoint IsNot Nothing Then lWaypoint.lat = lClosestPoint.lat lWaypoint.lon = lClosestPoint.lon lLayer.Bounds.Expand(lWaypoint.lat, lWaypoint.lon) End If Next Next End Sub ''' <summary> ''' Find the GPS location closest to the given date ''' </summary> ''' <param name="aDate">Date to search for</param> ''' <returns></returns> ''' <remarks>searches all currently loaded GPX layers</remarks> Private Function ClosestPoint(ByVal aDate As Date) As clsGPXwaypoint Dim lTargetTicks As Long = aDate.Ticks Dim lClosestTicks As Long = Long.MaxValue Dim lClosestPoint As clsGPXwaypoint = Nothing If Layers IsNot Nothing AndAlso Layers.Count > 0 Then For Each lTrackLayer As clsLayer In Layers If lTrackLayer.GetType.Name.Equals("clsLayerGPX") Then Dim lGPX As clsLayerGPX = lTrackLayer For Each lGpxTrack As clsGPXtrack In lGPX.GPX.trk For Each lGpxTrackSeg As clsGPXtracksegment In lGpxTrack.trkseg For Each lGpxTrackPoint As clsGPXwaypoint In lGpxTrackSeg.trkpt If lGpxTrackPoint.timeSpecified Then Dim lTicksDiff As Long = Math.Abs(lGpxTrackPoint.time.Ticks - lTargetTicks) If lTicksDiff < lClosestTicks Then lClosestTicks = lTicksDiff lClosestPoint = lGpxTrackPoint End If End If Next Next Next End If Next End If Return lClosestPoint End Function Private Function OpenGPX(ByVal aFilename As String, Optional ByVal aInsertAt As Integer = -1) As clsLayerGPX Dim lNewLayer As clsLayerGPX = Nothing If IO.File.Exists(aFilename) Then CloseLayer(aFilename) Try lNewLayer = New clsLayerGPX(aFilename, Me) With lNewLayer .LabelField = GPXLabelField If Not GPXPanTo AndAlso Not GPXZoomTo AndAlso lNewLayer.GPX.bounds IsNot Nothing Then With lNewLayer.GPX.bounds 'Skip loading this one if it is not in view If .minlat > LatMax OrElse _ .maxlat < LatMin OrElse _ .minlon > LonMax OrElse _ .maxlon < LonMin Then Return Nothing End If End With End If End With If aInsertAt >= 0 Then Layers.Insert(aInsertAt, lNewLayer) Else Layers.Add(lNewLayer) End If If GPXPanTo OrElse GPXZoomTo AndAlso lNewLayer.Bounds IsNot Nothing Then If GPXPanTo Then PanTo(lNewLayer.Bounds) End If If GPXZoomTo AndAlso _ lNewLayer.Bounds.minlat < lNewLayer.Bounds.maxlat AndAlso _ lNewLayer.Bounds.minlon < lNewLayer.Bounds.maxlon Then Zoom = FindZoom(lNewLayer.Bounds) Else NeedRedraw() End If Application.DoEvents() End If Catch e As Exception MsgBox(e.Message, MsgBoxStyle.Critical, "Could not open '" & aFilename & "'") End Try End If Return lNewLayer End Function ''' <summary> ''' Center the view on the center of the given bounds ''' </summary> ''' <param name="aBounds">Bounds to center on</param> ''' <remarks>Does not redraw</remarks> Public Sub PanTo(ByVal aBounds As clsGPXbounds) If aBounds IsNot Nothing Then With aBounds CenterLat = .minlat + (.maxlat - .minlat) / 2 CenterLon = .minlon + (.maxlon - .minlon) / 2 SanitizeCenterLatLon() End With End If End Sub ''' <summary> ''' Find zoom that would include the given layer without changing the center point ''' </summary> ''' <param name="aBounds">Bounds to zoom to</param> ''' <param name="aZoomIn">True to zoom in to best fit layer</param> ''' <param name="aZoomOut">True to zoom out to fit layer</param> ''' <remarks> ''' Defaults to zooming in or out as needed to best fit layer ''' Does not redraw or set the zoom level of the map ''' </remarks> Private Function FindZoom(ByVal aBounds As clsGPXbounds, _ Optional ByVal aZoomIn As Boolean = True, _ Optional ByVal aZoomOut As Boolean = True) As Integer With aBounds Dim lDesiredZoom As Integer = pZoom Dim lNewLatHeight As Double = LatHeight Dim lNewLonWidth As Double = LonWidth If aZoomIn Then While lDesiredZoom < TileServer.ZoomMax AndAlso _ .maxlat < CenterLat + lNewLatHeight / 4 AndAlso _ .minlat > CenterLat - lNewLatHeight / 4 AndAlso _ .maxlon < CenterLon + lNewLonWidth / 4 AndAlso _ .minlon > CenterLon - lNewLonWidth / 4 lDesiredZoom += 1 lNewLonWidth /= 2 lNewLatHeight /= 2 End While End If If aZoomOut Then While lDesiredZoom > TileServer.ZoomMin AndAlso _ (.maxlat > CenterLat + lNewLatHeight / 2 OrElse _ .minlat < CenterLat - lNewLatHeight / 2 OrElse _ .maxlon > CenterLon + lNewLonWidth / 2 OrElse _ .minlon < CenterLon - lNewLonWidth / 2) lDesiredZoom -= 1 lNewLonWidth *= 2 lNewLatHeight *= 2 End While End If Return lDesiredZoom End With End Function ''' <summary> ''' Pan and zoom the view to best contain the given bounds ''' </summary> ''' <param name="aBounds">Bounds to center on and zoom to</param> ''' <remarks>Redraws map</remarks> Public Sub ZoomTo(ByVal aBounds As clsGPXbounds, _ Optional ByVal aZoomIn As Boolean = True, _ Optional ByVal aZoomOut As Boolean = True) PanTo(aBounds) Dim lZoom As Integer = FindZoom(aBounds, aZoomIn, aZoomOut) If lZoom = Zoom Then NeedRedraw() 'Don't need to change zoom, just redraw Else Zoom = lZoom 'Changing zoom will also redraw End If End Sub Public Sub ZoomToAll() Dim lFirstLayer As Boolean = True 'Zoom in on first layer, then zoom out to include all layers Dim lAllBounds As clsGPXbounds = Nothing For Each lLayer As clsLayer In Layers If lLayer.Bounds IsNot Nothing Then If lFirstLayer Then lAllBounds = lLayer.Bounds.Clone lFirstLayer = False Else lAllBounds.Expand(lLayer.Bounds.minlat, lLayer.Bounds.minlon) lAllBounds.Expand(lLayer.Bounds.maxlat, lLayer.Bounds.maxlon) End If End If Next If lAllBounds IsNot Nothing Then ZoomTo(lAllBounds) End If End Sub ''' <summary> ''' Close the existing file if already open ''' </summary> ''' <param name="aFilename">Name of file to close</param> ''' <returns>True if layer matching file name was found and closed</returns> Private Function CloseLayer(ByVal aFilename As String) As Boolean Dim lLayer As clsLayer aFilename = aFilename.ToLower For Each lLayer In Layers If aFilename.Equals(lLayer.Filename.ToLower) Then CloseLayer(lLayer) Return True End If Next Return False End Function Private Sub CloseLayer(ByVal aLayer As clsLayer) aLayer.Clear() Layers.Remove(aLayer) RaiseEvent ClosedLayer() End Sub Public Sub CloseAllLayers() For Each lLayer As clsLayer In Layers lLayer.Clear() Next Layers.Clear() RaiseEvent ClosedLayer() End Sub ''' <summary> ''' True to check for buddies, False to stop checking ''' </summary> ''' <value></value> Public Property FindBuddy() As Boolean Get Return pBuddyTimer IsNot Nothing End Get Set(ByVal value As Boolean) If value Then StartBuddyTimer() Else StopBuddyTimer() End If End Set End Property ''' <summary> ''' Start timer that refreshes buddy positions ''' </summary> ''' <remarks></remarks> Private Sub StartBuddyTimer() If pBuddyTimer Is Nothing Then pBuddyTimer = New System.Threading.Timer(New Threading.TimerCallback(AddressOf RequestBuddyPoint), Nothing, 0, 60000) End If End Sub Private Sub StopBuddyTimer() If pBuddyTimer IsNot Nothing Then Try pBuddyTimer.Dispose() Catch End Try pBuddyTimer = Nothing End If End Sub ''' <summary> ''' Set the map to make sure given location is in view ''' </summary> ''' <param name="aLatitude">Device Latitude</param> ''' <param name="aLongitude">Device Longitude</param> ''' <param name="aCenterBehavior">Whether / how to change view to include the given location</param> ''' <returns>True if map center was updated</returns> ''' <remarks></remarks> Private Function SetCenterFromDevice(ByVal aLatitude As Double, ByVal aLongitude As Double, ByVal aCenterBehavior As Integer) As Boolean If CenterLat <> aLatitude OrElse CenterLon <> aLongitude Then Select Case aCenterBehavior Case 0 'Do nothing Case 1 'Follow, only move center if it is off screen If Not LatLonInView(aLatitude, aLongitude) Then CenterLat = aLatitude CenterLon = aLongitude SanitizeCenterLatLon() Return True End If Case 2 'Always center CenterLat = aLatitude CenterLon = aLongitude SanitizeCenterLatLon() Return True Case 3 'Zoom out until location is in view While Zoom > 0 AndAlso Not LatLonInView(aLatitude, aLongitude) Zoom -= 1 End While End Select End If Return False End Function Public Function ClosestGeocache(ByVal aLatitude As Double, ByVal aLongitude As Double) As clsGPXwaypoint Dim lMiddlemostCache As clsGPXwaypoint = Nothing If Layers IsNot Nothing AndAlso Layers.Count > 0 Then Dim lClosestDistance As Double = Double.MaxValue Dim lThisDistance As Double For Each lLayer As clsLayer In Layers Try Dim lGPXLayer As clsLayerGPX = lLayer Dim lDrawThisOne As Boolean = True If lGPXLayer.GPX.bounds IsNot Nothing Then With lGPXLayer.GPX.bounds 'Skip if it is not in view If .minlat > CenterLat + LatHeight / 2 OrElse _ .maxlat < CenterLat - LatHeight / 2 OrElse _ .minlon > CenterLon + LonWidth / 2 OrElse _ .maxlon < CenterLon - LonWidth / 2 Then lDrawThisOne = False End If End With End If If lDrawThisOne Then For Each lWaypoint As clsGPXwaypoint In lGPXLayer.GPX.wpt lThisDistance = (lWaypoint.lat - CenterLat) ^ 2 + (lWaypoint.lon - CenterLon) ^ 2 If lThisDistance < lClosestDistance Then lMiddlemostCache = lWaypoint lClosestDistance = lThisDistance End If Next End If Catch End Try Next End If Return lMiddlemostCache End Function Public Sub ShowGeocacheHTML(ByVal aCache As clsGPXwaypoint) If aCache IsNot Nothing Then Dim lTempPath As String = IO.Path.GetTempPath With aCache Windows.Forms.Clipboard.SetDataObject(.name) Dim lText As String = "<html><head><title>" & .name & "</title></head><body>" lText &= "<b><a href=""" & .url & """>" & .name & "</a></b> " _ & FormattedDegrees(.lat, g_DegreeFormat) & ", " _ & FormattedDegrees(.lon, g_DegreeFormat) & "<br>" If .desc IsNot Nothing AndAlso .desc.Length > 0 Then lText &= .desc ElseIf .urlname IsNot Nothing AndAlso .urlname.Length > 0 Then lText &= .urlname If .cache IsNot Nothing Then lText &= " (" & Format(.cache.difficulty, "#.#") & "/" _ & Format(.cache.terrain, "#.#") & ")" End If End If Dim lType As String = Nothing If .type IsNot Nothing AndAlso .type.Length > 0 Then lType = .type If lType.StartsWith("Geocache|") Then lType = lType.Substring(9) End If If lType Is Nothing AndAlso .cache IsNot Nothing AndAlso .cache.cachetype IsNot Nothing AndAlso .cache.cachetype.Length > 0 Then lType = .cache.cachetype End If If lType IsNot Nothing AndAlso lText.IndexOf(lType) = -1 Then lText &= " <b>" & .type & "</b>" End If If .cache IsNot Nothing AndAlso .cache.container IsNot Nothing AndAlso .cache.container.Length > 0 Then lText &= " <b>" & .cache.container & "</b>" lText &= "<br>" If .cmt IsNot Nothing AndAlso .cmt.Length > 0 Then lText &= "<b>comment:</b> " & .cmt & "<br>" If .cache IsNot Nothing Then If .cache.archived Then lText &= "<h2>ARCHIVED</h2><br>" If .cache.short_description IsNot Nothing AndAlso .cache.short_description.Length > 0 Then lText &= .cache.short_description & "<br>" End If If .cache.long_description IsNot Nothing AndAlso .cache.long_description.Length > 0 Then lText &= .cache.long_description & "<br>" End If If .cache.encoded_hints IsNot Nothing AndAlso .cache.encoded_hints.Length > 0 Then lText &= "<b>Hint:</b> " & .cache.encoded_hints & "<br>" End If If .cache.logs IsNot Nothing AndAlso .cache.logs.Count > 0 Then 'T19:00:00 is the time for all logs? remove it and format the entries a bit Dim lIconPath As String = pTileCacheFolder & "Icons" & g_PathChar & "Geocache" & g_PathChar Dim lIconFilename As String lText &= "<b>Logs:</b><br>" For Each lLog As clsGroundspeakLog In .cache.logs Select Case lLog.logtype Case "Found it" : lIconFilename = "icon_smile.gif" Case "Didn't find it" : lIconFilename = "icon_sad.gif" Case "Write note" : lIconFilename = "icon_note.gif" Case "Enable Listing" : lIconFilename = "icon_enabled.gif" Case "Temporarily Disable Listing" : lIconFilename = "icon_disabled.gif" Case "Needs Maintenance" : lIconFilename = "icon_needsmaint.gif" Case "Owner Maintenance" : lIconFilename = "icon_maint.gif" Case "Publish Listing" : lIconFilename = "icon_greenlight.gif" Case "Update Coordinates" : lIconFilename = "coord_update.gif" Case "Will Attend" : lIconFilename = "icon_rsvp.gif" Case Else : lIconFilename = "" End Select If IO.File.Exists(lIconPath & lIconFilename) Then Dim lTempIcon As String = IO.Path.Combine(lTempPath, lIconFilename) If Not IO.File.Exists(lTempIcon) Then IO.File.Copy(lIconPath & lIconFilename, lTempIcon) End If lText &= "<img src=""" & lIconFilename & """>" Else lText &= lLog.logtype End If lText &= "<b>" & lLog.logdate.Replace("T19:00:00", "") & "</b> " & lLog.logfinder & ": " & lLog.logtext & "<br>" Next 'Dim lLastTimePos As Integer = 0 'Dim lTimePos As Integer = .cache.logs.IndexOf() 'While lTimePos > 0 ' lText &= .cache.logs.Substring(lLastTimePos, lTimePos - lLastTimePos - 10) & "<br><b>" & .cache.logs.Substring(lTimePos - 10, 10) & "</b> " ' lLastTimePos = lTimePos + 9 ' lTimePos = .cache.logs.IndexOf("T19:00:00", lTimePos + 10) 'End While 'lText &= .cache.logs.Substring(lLastTimePos + 9) & "<p>" End If If .cache.placed_by IsNot Nothing AndAlso .cache.placed_by.Length > 0 Then lText &= "<b>Placed by:</b> " & .cache.placed_by & "<br>" If .cache.owner IsNot Nothing AndAlso .cache.owner.Length > 0 Then lText &= "<b>Owner:</b> " & .cache.owner & "<br>" If .cache.travelbugs IsNot Nothing AndAlso .cache.travelbugs.Length > 0 Then lText &= "<b>Travellers:</b> " & .cache.travelbugs & "<br>" End If lText &= .extensionsString Dim lTempFilename As String = IO.Path.Combine(lTempPath, "cache.html") Dim lStream As IO.StreamWriter = IO.File.CreateText(lTempFilename) lStream.Write(lText) lStream.Write("<br><a href=""http://wap.geocaching.com/"">Official WAP</a><br>") lStream.Close() OpenFileOrURL(lTempFilename, False) End With End If End Sub Private Sub ManuallyNavigated() GPSCenterBehavior = 0 'Manual navigation overrides automatic following of GPS SanitizeCenterLatLon() NeedRedraw() End Sub Public Property GPSCenterBehavior() As Integer Get Return pGPSCenterBehavior End Get Set(ByVal value As Integer) 'If pGPSCenterBehavior <> value Then pGPSCenterBehavior = value RaiseEvent CenterBehaviorChanged() 'End If End Set End Property #If Smartphone Then #Region "Smartphone" Private GPS_Listen As Boolean = False Private WithEvents GPS As GPS_API.GPS Private GPS_DEVICE_STATE As GPS_API.GpsDeviceState Private GPS_POSITION As GPS_API.GpsPosition = Nothing <CLSCompliant(False)> _ Public Event LocationChanged(ByVal aPosition As GPS_API.GpsPosition) Private pLastCellTower As clsCell Private pCellLocationProviders As New Generic.List(Of clsCellLocationProvider) ' Synchronize access to track log file Private Shared pTrackMutex As New Threading.Mutex() Private pTrackWaypoints As New System.Text.StringBuilder() ' File name of waypoints currently being written Private pWaypointLogFilename As String = Nothing ' File name of track log currently being written Private pTrackLogFilename As String ' When we last uploaded a track point (UTC) Private pUploadLastTime As DateTime ' True if we want to upload when GPS starts and have not yet done so Private pPendingUploadStart As Boolean = False ' When we last logged a track point (UTC) Private pTrackLastTime As DateTime Private pTrackLastLatitude As Double = 0.0 ' Degrees latitude. North is positive Private pTrackLastLongitude As Double = 0.0 ' Degrees longitude. East is positive Private pClickRefreshTile As Boolean = False ' Always false on startup, not saved to registry Private pCursorLayer As clsLayerGPX Private pKeepAwakeTimer As System.Threading.Timer Public Sub New() InitializeComponent() 'Default to using these for mobile even though default to not in frmMapCommon ControlsUse = True ControlsShow = True pTrackLastTime = DateTime.UtcNow.Subtract(pTrackMinInterval) pUploadLastTime = New DateTime(1, 1, 1) updateDataHandler = New EventHandler(AddressOf UpdateData) pTileCacheFolder = GetAppSetting("TileCacheFolder", g_PathChar & "My Documents" & g_PathChar & "tiles" & g_PathChar) If pTileCacheFolder.Length > 0 AndAlso Not pTileCacheFolder.EndsWith(g_PathChar) Then pTileCacheFolder &= g_PathChar End If GPXFolder = IO.Path.GetDirectoryName(pTileCacheFolder) Try IO.Directory.CreateDirectory(pTileCacheFolder) IO.Directory.CreateDirectory(pTileCacheFolder & "WriteTest") IO.Directory.Delete(pTileCacheFolder & "WriteTest") Catch e As Exception pTileCacheFolder = IO.Path.Combine(IO.Path.GetTempPath, "tiles") End Try SharedNew(pTileCacheFolder) Uploader.Enabled = True pCellLocationProviders.Add(New clsCellLocationOpenCellID) pCellLocationProviders.Add(New clsCellLocationGoogle) pCursorLayer = New clsLayerGPX("cursor", Me) pCursorLayer.SymbolPen = New Pen(Color.Red, 2) 'TODO: make width user-configurable, allow drawing icon as cursor instead of arrow pCursorLayer.SymbolSize = GPSSymbolSize End Sub Public Property Active() As Boolean Get Return pActive End Get Set(ByVal value As Boolean) pActive = value If pActive Then Me.NeedRedraw() End Set End Property Private Sub Redraw() If pRedrawing Then pRedrawPending = True Else pRedrawing = True Dim lGraphics As Graphics = Nothing Dim lDetailsBrush As Brush = pBrushBlack RestartRedraw: If Active Then lGraphics = GetBitmapGraphics() If lGraphics IsNot Nothing Then If Dark Then lGraphics.Clear(Color.Black) lDetailsBrush = pBrushWhite Else DrawTiles(lGraphics) End If If pShowGPSdetails Then Dim lMaxWidth As Single = lGraphics.ClipBounds.Right - 10 Dim lDetails As String = "" If GPS Is Nothing Then lDetails = "GPS not initialized" ElseIf Not GPS.Opened Then lDetails = "GPS not opened" ElseIf GPS_POSITION Is Nothing Then lDetails = "No position" ElseIf Not GPS_POSITION.LatitudeValid OrElse Not GPS_POSITION.LongitudeValid Then lDetails = "Position not valid" Else lDetails = FormattedDegrees(GPS_POSITION.Latitude, g_DegreeFormat) & "," AppendStringSplitToFitWidth(lGraphics, pFontGpsDetails, lMaxWidth, lDetails, FormattedDegrees(GPS_POSITION.Longitude, g_DegreeFormat)) If (GPS_POSITION.SeaLevelAltitudeValid) Then AppendStringSplitToFitWidth(lGraphics, pFontGpsDetails, lMaxWidth, lDetails, Format(GPS_POSITION.SeaLevelAltitude * g_FeetPerMeter, "#,##0") & "ft") If (GPS_POSITION.SpeedValid AndAlso GPS_POSITION.Speed > 0) Then AppendStringSplitToFitWidth(lGraphics, pFontGpsDetails, lMaxWidth, lDetails, CInt(GPS_POSITION.Speed * g_MilesPerKnot) & "mph") If GPS_POSITION.TimeValid Then lDetails &= vbLf & GPS_POSITION.Time.ToString("yyyy-MM-dd") AppendStringSplitToFitWidth(lGraphics, pFontGpsDetails, lMaxWidth, lDetails, GPS_POSITION.Time.ToString("HH:mm:ss") & "Z") Dim lAgeOfPosition As TimeSpan = DateTime.UtcNow - GPS_POSITION.Time Dim lAgeString As String = "" If (Math.Abs(lAgeOfPosition.TotalSeconds) > 5) Then If Math.Abs(lAgeOfPosition.Days) > 1 Then lAgeString = Format(lAgeOfPosition.TotalDays, "0.#") & " days" Else If Math.Abs(lAgeOfPosition.Days) > 0 Then lAgeString = lAgeOfPosition.Days & "day" If Math.Abs(lAgeOfPosition.Hours) > 0 Then lAgeString &= lAgeOfPosition.Hours & "h" If Math.Abs(lAgeOfPosition.Minutes) > 0 Then lAgeString &= lAgeOfPosition.Minutes & "m" If lAgeOfPosition.Hours = 0 Then lAgeString &= lAgeOfPosition.Seconds & "s" End If AppendStringSplitToFitWidth(lGraphics, pFontGpsDetails, lMaxWidth, lDetails, "(" & lAgeString & " ago)") End If End If End If If pRecordCellID Then Dim lCurrentCellInfo As New clsCell(GPS_API.RIL.GetCellTowerInfo) If lCurrentCellInfo.IsValid Then lDetails &= vbLf & lCurrentCellInfo.ToString Else lDetails &= vbLf & "no cell" End If End If 'If pUsedCacheCount + pAddedCacheCount > 0 Then ' lDetails &= " Cache " & Format(pUsedCacheCount / (pUsedCacheCount + pAddedCacheCount), "0.0 %") & " " & pDownloader.TileRAMcacheLimit 'End If If Not RecordTrack Then lDetails &= vbLf & "Logging Off" lGraphics.DrawString(lDetails, pFontGpsDetails, lDetailsBrush, 5, 5) End If ReleaseBitmapGraphics() Refresh() pLastRedrawTime = Now End If End If Application.DoEvents() If pRedrawPending Then pRedrawPending = False GoTo RestartRedraw End If pRedrawing = False End If End Sub Private Sub AppendStringSplitToFitWidth(ByVal aGraphics As Graphics, _ ByVal aFont As Font, ByVal lMaxWidth As Single, _ ByRef aString As String, ByVal aAppend As String) Dim lLastNewline As Integer = aString.LastIndexOf(vbLf) Dim lLastLine As String = aString.Substring(lLastNewline + 1) Dim lWidth As Single = aGraphics.MeasureString(lLastLine & " " & aAppend, aFont).Width If lWidth > lMaxWidth Then aString &= vbLf & aAppend Else aString &= " " & aAppend End If End Sub Private Function EnsureCurrentTrack() As clsLayerGPX If Layers.Count = 0 OrElse Layers(0).Filename <> "current" Then Dim lCurrentTrack As New clsLayerGPX("current", Me) lCurrentTrack.Filename = "current" With lCurrentTrack.GPX .trk = New Generic.List(Of clsGPXtrack) .trk.Add(New clsGPXtrack("current")) .trk(0).trkseg.Add(New clsGPXtracksegment()) End With Layers.Insert(0, lCurrentTrack) End If Return Layers(0) End Function Private Function MapRectangle() As Rectangle Return ClientRectangle End Function Private Sub DrewTiles(ByVal g As Graphics, ByVal aTopLeft As Point, ByVal aOffsetToCenter As Point) If GPS IsNot Nothing AndAlso GPS.Opened AndAlso GPS_POSITION IsNot Nothing AndAlso GPS_POSITION.LatitudeValid AndAlso GPS_POSITION.LongitudeValid Then If GPSSymbolSize > 0 Then pCursorLayer.SymbolSize = GPSSymbolSize Dim lWaypoint As New clsGPXwaypoint("wpt", GPS_POSITION.Latitude, GPS_POSITION.Longitude) lWaypoint.sym = "cursor" lWaypoint.course = GPS_POSITION.Heading pCursorLayer.DrawTrackpoint(TileServer, g, lWaypoint, aTopLeft, aOffsetToCenter, -1, -1) End If End If End Sub Private Sub Event_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown Select Case e.Button Case Windows.Forms.MouseButtons.Left If pClickRefreshTile Then Dim lBounds As New RectangleF(0, 0, pBitmap.Width, pBitmap.Height) ClickedTileFilename = FindTileFilename(TileServer, lBounds, e.X, e.Y) Downloader.DeleteTile(ClickedTileFilename) NeedRedraw() ElseIf pClickWaypoint Then AddWaypoint(CenterLat - (e.Y - Me.ClientRectangle.Height / 2) * LatHeight / Me.ClientRectangle.Height, _ CenterLon + (e.X - Me.ClientRectangle.Width / 2) * LonWidth / Me.ClientRectangle.Width, _ Date.UtcNow, Now.ToString("yyyy-MM-dd HH:mm:ss")) Else MouseDownLeft(e) End If End Select End Sub Private Sub Event_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove If MouseDragging Then If Not ControlsUse OrElse _ (e.X > pControlsMargin AndAlso e.X < (Me.Width - pControlsMargin)) OrElse _ (e.Y > pControlsMargin AndAlso e.Y < (Me.Height - pControlsMargin)) OrElse _ Math.Abs(MouseDragStartLocation.X - e.X) > pControlsMargin / 2 OrElse _ Math.Abs(MouseDragStartLocation.Y - e.Y) > pControlsMargin / 2 Then CenterLat = MouseDownLat + (e.Y - MouseDragStartLocation.Y) * LatHeight / Me.ClientRectangle.Height CenterLon = MouseDownLon - (e.X - MouseDragStartLocation.X) * LonWidth / Me.ClientRectangle.Width ManuallyNavigated() End If End If End Sub Public Sub StartGPS() Application.DoEvents() If pGPSCenterBehavior = 0 Then GPSCenterBehavior = 2 'Center at GPS location when starting GPS End If If GPS Is Nothing Then GPS = New GPS_API.GPS If Not GPS.Opened Then If Not Dark Then StartKeepAwake() SetPowerRequirement(DeviceGPS, True) NewLogFilename() Application.DoEvents() GPS.Open() GPS_Listen = True pPendingUploadStart = UploadOnStart End If End Sub Private Sub NewLogFilename(Optional ByVal aNeedMutex As Boolean = True) If aNeedMutex Then pTrackMutex.WaitOne() CloseLog(pWaypointLogFilename, "</gpx>" & vbLf) CloseLog(pTrackLogFilename, "</trkseg>" & vbLf & "</trk>" & vbLf & "</gpx>" & vbLf) Dim lBaseFilename As String = IO.Path.Combine(GPXFolder, DateTime.Now.ToString("yyyy-MM-dd_HH-mm")) pTrackLogFilename = lBaseFilename & ".gpx" Dim lLogIndex As Integer = 1 While System.IO.File.Exists(pTrackLogFilename) pTrackLogFilename = lBaseFilename & "_" & ++lLogIndex & ".gpx" End While pWaypointLogFilename = IO.Path.ChangeExtension(pTrackLogFilename, ".wpt.gpx") If aNeedMutex Then pTrackMutex.ReleaseMutex() End Sub Public Sub StopGPS() GPS_Listen = False Threading.Thread.Sleep(100) Me.SaveSettings() 'In case of crash, at least we can start again with the same settings 'Try ' mnuStartStopGPS.Text = "Finishing Log..." ' Application.DoEvents() 'Catch 'End Try pTrackMutex.WaitOne() CloseLog(pWaypointLogFilename, "</gpx>" & vbLf) CloseLog(pTrackLogFilename, "</trkseg>" & vbLf & "</trk>" & vbLf & "</gpx>" & vbLf) pTrackMutex.ReleaseMutex() If GPS IsNot Nothing Then If GPS.Opened Then 'Try ' mnuStartStopGPS.Text = "Closing GPS..." ' Application.DoEvents() 'Catch 'End Try If UploadOnStop Then UploadGpsPosition() GPS.Close() End If GPS = Nothing End If SetPowerRequirement(DeviceGPS, False) StopKeepAwake() End Sub ''' <summary> ''' Close a GPX file ''' </summary> ''' <param name="aFilename">File to close</param> ''' <param name="aAppend">Closing tags to append at end of file</param> ''' <remarks>Only call between pTrackMutex.WaitOne and pTrackMutex.ReleaseMutex</remarks> Private Sub CloseLog(ByRef aFilename As String, ByVal aAppend As String) Try If IO.File.Exists(aFilename) Then If aAppend IsNot Nothing AndAlso aAppend.Length > 0 Then Dim lFile As System.IO.StreamWriter = System.IO.File.AppendText(aFilename) lFile.Write(aAppend) lFile.Close() End If If UploadTrackOnStop AndAlso Uploader.Enabled Then Uploader.Enqueue(g_UploadTrackURL, aFilename, QueueItemType.FileItem, 0) End If End If aFilename = "" Catch ex As System.IO.IOException End Try End Sub Private updateDataHandler As EventHandler Private Sub GPS_DEVICE_LocationChanged(ByVal sender As Object, ByVal args As GPS_API.LocationChangedEventArgs) Handles GPS.LocationChanged If GPS_Listen Then GPS_POSITION = args.Position Invoke(updateDataHandler) End If End Sub Private Sub UpdateData(ByVal sender As Object, ByVal args As System.EventArgs) Try If (GPS.Opened) Then Try RaiseEvent LocationChanged(GPS_POSITION) Catch End Try If (GPS_POSITION IsNot Nothing AndAlso GPS_POSITION.LatitudeValid AndAlso GPS_POSITION.LongitudeValid) Then Dim lNeedRedraw As Boolean = SetCenterFromDevice(GPS_POSITION.Latitude, GPS_POSITION.Longitude, pGPSCenterBehavior) If GPS_Listen AndAlso (RecordTrack OrElse pDisplayTrack) AndAlso DateTime.UtcNow.Subtract(pTrackMinInterval) >= pTrackLastTime Then TrackAddPoint() pTrackLastTime = DateTime.UtcNow End If If GPSSymbolSize > 0 OrElse lNeedRedraw Then NeedRedraw() End If If pPendingUploadStart OrElse (UploadPeriodic AndAlso DateTime.UtcNow.Subtract(UploadMinInterval) >= pUploadLastTime) Then UploadGpsPosition() End If End If End If Catch e As Exception 'MsgBox(e.Message & vbLf & e.StackTrace) End Try End Sub Private Function SetCenterFromCellLocation() As Boolean Dim lCurrentCellInfo As New clsCell(GPS_API.RIL.GetCellTowerInfo) If lCurrentCellInfo.IsValid AndAlso (pLastCellTower Is Nothing OrElse lCurrentCellInfo.ID <> pLastCellTower.ID) Then pLastCellTower = lCurrentCellInfo With lCurrentCellInfo If GetCellLocation(pTileCacheFolder & "cells", lCurrentCellInfo) Then If SetCenterFromDevice(lCurrentCellInfo.Latitude, lCurrentCellInfo.Longitude, pGPSCenterBehavior) Then Me.Invoke(pRedrawCallback) Return True End If End If End With End If Return False End Function Private Function GetCellLocation(ByVal aCellCacheFolder As String, ByVal aCell As clsCell) As Boolean 'Check for a cached location first For Each lLocationProvider As clsCellLocationProvider In pCellLocationProviders If lLocationProvider.GetCachedLocation(aCellCacheFolder, aCell) Then Return True End If Next 'Query for a new location and cache if found For Each lLocationProvider As clsCellLocationProvider In pCellLocationProviders If lLocationProvider.GetCellLocation(aCell) Then lLocationProvider.SaveCachedLocation(aCellCacheFolder, aCell) Return True End If Next Return False End Function Private Sub TrackAddPoint() Dim lTrackPoint As clsGPXwaypoint = LatestPositionWaypoint("trkpt") If lTrackPoint IsNot Nothing Then ' If subsequent track points vary this much, we don't believe it, don't log till they are closer If Math.Abs((GPS_POSITION.Latitude - pTrackLastLatitude)) + Math.Abs((GPS_POSITION.Longitude - pTrackLastLongitude)) < 0.5 Then If RecordTrack Then AppendLog(pTrackLogFilename, lTrackPoint.ToString, "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbLf & "<gpx xmlns=""http://www.topografix.com/GPX/1/1"" version=""1.1"" creator=""" & g_AppName & """ xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.topografix.com/GPX/gpx_overlay/0/3 http://www.topografix.com/GPX/gpx_overlay/0/3/gpx_overlay.xsd http://www.topografix.com/GPX/gpx_modified/0/1 http://www.topografix.com/GPX/gpx_modified/0/1/gpx_modified.xsd"">" & vbLf & "<trk>" & vbLf & "<name>" & g_AppName & " Log " & System.IO.Path.GetFileNameWithoutExtension(pTrackLogFilename) & " </name>" & vbLf & "<type>GPS Tracklog</type>" & vbLf & "<trkseg>" & vbLf) End If pTrackLastTime = DateTime.UtcNow If pDisplayTrack Then EnsureCurrentTrack.GPX.trk(0).trkseg(0).trkpt.Add(lTrackPoint) End If End If pTrackLastLatitude = GPS_POSITION.Latitude pTrackLastLongitude = GPS_POSITION.Longitude End If End Sub 'TrackAddPoint ''' <summary> ''' Create a GPX waypoint for the latest GPS position ''' </summary> ''' <param name="aTag">trkpt or wpt depending on whether this is part of a track or an independent waypoint</param> ''' <returns></returns> ''' <remarks></remarks> Public Function LatestPositionWaypoint(ByVal aTag As String) As clsGPXwaypoint Dim lTrackPoint As clsGPXwaypoint = Nothing With GPS_POSITION If GPS_POSITION IsNot Nothing _ AndAlso .TimeValid _ AndAlso .LatitudeValid _ AndAlso .LongitudeValid _ AndAlso .SatellitesInSolutionValid _ AndAlso .SatelliteCount > 2 Then Dim lGPXheader As String = Nothing lTrackPoint = New clsGPXwaypoint(aTag, GPS_POSITION.Latitude, GPS_POSITION.Longitude) If GPS_POSITION.SeaLevelAltitudeValid Then lTrackPoint.ele = GPS_POSITION.SeaLevelAltitude lTrackPoint.time = GPS_POSITION.Time lTrackPoint.sat = GPS_POSITION.SatelliteCount If GPS_POSITION.SpeedValid AndAlso GPS_POSITION.Speed > 0.01 Then lTrackPoint.speed = GPS_POSITION.Speed If GPS_POSITION.HeadingValid Then lTrackPoint.course = GPS_POSITION.Heading If pRecordCellID Then Dim lCurrentCellInfo As New clsCell(GPS_API.RIL.GetCellTowerInfo) If lCurrentCellInfo.IsValid Then lTrackPoint.SetExtension("cellid", lCurrentCellInfo.ToString) Dim lSignalStrength As Integer = Microsoft.WindowsMobile.Status.SystemState.PhoneSignalStrength If lSignalStrength > 0 Then lTrackPoint.SetExtension("phonesignal", lSignalStrength) End If End If End If End If End With Return lTrackPoint End Function Private Sub AppendLog(ByVal aFilename As String, ByVal aAppend As String, ByVal aHeader As String) pTrackMutex.WaitOne() Dim lTries As Integer = 0 TryAgain: Try Dim lNeedHeader As Boolean = Not IO.File.Exists(aFilename) If lNeedHeader Then IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(aFilename)) Dim lFile As System.IO.StreamWriter = System.IO.File.AppendText(aFilename) If lNeedHeader AndAlso aHeader IsNot Nothing Then lFile.Write(aHeader) lFile.Write(aAppend) lFile.Close() Catch ex As Exception 'Windows.Forms.MessageBox.Show("Could not save " & vbLf & pTrackLogFilename & vbLf & ex.Message) If lTries < 1 Then lTries += 1 NewLogFilename() GoTo TryAgain End If End Try pTrackMutex.ReleaseMutex() End Sub Public Sub UploadGpsPosition() If Uploader.Enabled _ AndAlso GPS_POSITION IsNot Nothing _ AndAlso GPS_POSITION.TimeValid _ AndAlso GPS_POSITION.LatitudeValid _ AndAlso GPS_POSITION.LongitudeValid _ AndAlso GPS_POSITION.SatellitesInSolutionValid _ AndAlso GPS_POSITION.SatelliteCount > 2 Then Try Dim lURL As String = g_UploadPointURL If lURL IsNot Nothing AndAlso lURL.Length > 0 Then BuildURL(lURL, "Time", timeZ(GPS_POSITION.Time), "", GPS_POSITION.TimeValid) BuildURL(lURL, "Lat", GPS_POSITION.Latitude.ToString("#.########"), "", GPS_POSITION.LatitudeValid) BuildURL(lURL, "Lon", GPS_POSITION.Longitude.ToString("#.########"), "", GPS_POSITION.LongitudeValid) BuildURL(lURL, "Alt", GPS_POSITION.SeaLevelAltitude, "", GPS_POSITION.SeaLevelAltitudeValid) BuildURL(lURL, "Speed", GPS_POSITION.Speed, "", GPS_POSITION.SpeedValid) BuildURL(lURL, "Heading", GPS_POSITION.Heading, "", GPS_POSITION.HeadingValid) If pPendingUploadStart Then BuildURL(lURL, "Label", g_AppName & "-Start", "", True) Else BuildURL(lURL, "Label", g_AppName, "", True) End If If lURL.IndexOf("CellID") > -1 Then Dim lCurrentCellInfo As New clsCell(GPS_API.RIL.GetCellTowerInfo) BuildURL(lURL, "CellID", lCurrentCellInfo.ToString, "", True) End If Uploader.ClearQueue(0) Uploader.Enqueue(lURL, "", QueueItemType.PointItem, 0) pUploadLastTime = DateTime.UtcNow pPendingUploadStart = False End If Catch End Try End If End Sub 'UploadPoint Private Sub BuildURL(ByRef aURL As String, ByVal aTag As String, ByVal aReplaceTrue As String, ByVal aReplaceFalse As String, ByVal aTest As Boolean) Dim lReplacement As String If aTest Then lReplacement = aReplaceTrue Else lReplacement = aReplaceFalse End If aURL = aURL.Replace("#" & aTag & "#", lReplacement) End Sub Public Property DisplayTrack() As Boolean Get Return pDisplayTrack End Get Set(ByVal value As Boolean) pDisplayTrack = value If Layers.Count > 0 AndAlso Layers(0).Filename = "current" Then Layers.RemoveAt(0) End If If pDisplayTrack Then pTrackMutex.WaitOne() If System.IO.File.Exists(pTrackLogFilename) Then Dim lLayer As clsLayerGPX = OpenGPX(pTrackLastTime, 0) If lLayer IsNot Nothing Then lLayer.SymbolSize = TrackSymbolSize End If End If pTrackMutex.ReleaseMutex() End If End Set End Property Public Property ShowGPSdetails() As Boolean Get Return pShowGPSdetails End Get Set(ByVal value As Boolean) pShowGPSdetails = value NeedRedraw() End Set End Property Public Property ViewTileOutlines() As Boolean Get Return pShowTileOutlines End Get Set(ByVal value As Boolean) pShowTileOutlines = value NeedRedraw() End Set End Property Public Property ViewTileNames() As Boolean Get Return pShowTileNames End Get Set(ByVal value As Boolean) pShowTileNames = value NeedRedraw() End Set End Property Public Property ClickRefreshTile() As Boolean Get Return pClickRefreshTile End Get Set(ByVal value As Boolean) pClickRefreshTile = value End Set End Property ''' <summary> ''' Start timer that keeps system idle from turning off device ''' </summary> Private Sub StartKeepAwake() SystemIdleTimerReset() If pKeepAwakeTimer Is Nothing Then pKeepAwakeTimer = New System.Threading.Timer(New Threading.TimerCallback(AddressOf IdleTimeout), Nothing, 0, 50000) End If End Sub ''' <summary> ''' Stop timer that keeps system idle from turning off device ''' </summary> Private Sub StopKeepAwake() If pKeepAwakeTimer IsNot Nothing Then pKeepAwakeTimer.Dispose() pKeepAwakeTimer = Nothing End If End Sub ''' <summary> ''' Keep the device awake, also move map to a cell tower location if desired ''' </summary> ''' <remarks>Periodically called by pKeepAwakeTimer</remarks> Private Sub IdleTimeout(ByVal o As Object) SystemIdleTimerReset() 'If the user requested some centering from GPS 'and the GPS has not given us a good location within the last minute 'then try to center on a cell tower location If pGPSCenterBehavior > 0 _ AndAlso (Not GPS_Listen _ OrElse GPS_POSITION Is Nothing _ OrElse Not GPS_POSITION.TimeValid _ OrElse Date.UtcNow.Subtract(GPS_POSITION.Time).TotalMinutes > 1) Then SetCenterFromCellLocation() End If End Sub Public Property AutoStart() As Boolean Get Return pGPSAutoStart End Get Set(ByVal value As Boolean) pGPSAutoStart = value End Set End Property Public Property ViewMapTiles() As Boolean Get Return pShowTileImages End Get Set(ByVal value As Boolean) pShowTileImages = value NeedRedraw() End Set End Property Public Property ViewControls() As Boolean Get Return ControlsShow End Get Set(ByVal value As Boolean) ControlsShow = value ControlsUse = value NeedRedraw() End Set End Property Public Property ClickMakeWaypoint() As Boolean Get Return pClickWaypoint End Get Set(ByVal value As Boolean) pClickWaypoint = value End Set End Property Private Sub AddWaypoint(ByVal aLatitude As Double, ByVal aLongitude As Double, ByVal aTime As Date, ByVal aName As String) Dim lWayPoint As New clsGPXwaypoint("wpt", aLatitude, aLongitude) lWayPoint.time = aTime lWayPoint.name = aName pTrackMutex.WaitOne() If pWaypointLogFilename Is Nothing OrElse pWaypointLogFilename.Length = 0 Then pWaypointLogFilename = IO.Path.Combine(GPXFolder, DateTime.Now.ToString("yyyy-MM-dd_HH-mm")) & ".wpt.gpx" End If pTrackMutex.ReleaseMutex() AppendLog(pWaypointLogFilename, lWayPoint.ToString, "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbLf & "<gpx xmlns=""http://www.topografix.com/GPX/1/1"" version=""1.1"" creator=""" & g_AppName & """ xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.topografix.com/GPX/gpx_overlay/0/3 http://www.topografix.com/GPX/gpx_overlay/0/3/gpx_overlay.xsd http://www.topografix.com/GPX/gpx_modified/0/1 http://www.topografix.com/GPX/gpx_modified/0/1/gpx_modified.xsd"">" & vbLf) End Sub #End Region 'Smartphone #Else #Region "Desktop" Friend WithEvents RightClickMenu As System.Windows.Forms.ContextMenuStrip Friend WithEvents RefreshFromServerToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ClosestGeocacheToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents TileCacheFolderToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Public Sub CopyToClipboard() pBitmapMutex.WaitOne() My.Computer.Clipboard.SetImage(pBitmap) pBitmapMutex.ReleaseMutex() End Sub Private Function ImageWorldFilename(ByVal aImageFilename As String) As String Dim lImageExt As String = IO.Path.GetExtension(aImageFilename) If lImageExt.Length > 1 Then lImageExt = lImageExt.Substring(1, 1) & lImageExt.Substring(lImageExt.Length - 1, 1) & "w" End If Return IO.Path.ChangeExtension(aImageFilename, lImageExt) End Function Public Sub SaveImageAs(ByVal aFilename As String) Dim lImageFormat As Imaging.ImageFormat = Imaging.ImageFormat.Png Select Case IO.Path.GetExtension(aFilename).ToLower Case ".bmp" : lImageFormat = Imaging.ImageFormat.Bmp Case ".emf" : lImageFormat = Imaging.ImageFormat.Emf Case ".gif" : lImageFormat = Imaging.ImageFormat.Gif Case ".ico" : lImageFormat = Imaging.ImageFormat.Icon Case ".jpg", ".jpeg" : lImageFormat = Imaging.ImageFormat.Jpeg Case ".tif", ".tiff" : lImageFormat = Imaging.ImageFormat.Tiff Case ".wmf" : lImageFormat = Imaging.ImageFormat.Wmf End Select pBitmapMutex.WaitOne() pBitmap.Save(aFilename, lImageFormat) 'SaveTiles(IO.Path.GetDirectoryName(.FileName) & g_PathChar & IO.Path.GetFileNameWithoutExtension(.FileName) & g_PathChar) pBitmapMutex.ReleaseMutex() 'CreateGeoReferenceFile(LatitudeToMeters(pCenterLat - pLatHeight * 1.66), _ CreateGeoReferenceFile(LatitudeToMeters(LatMax), _ LongitudeToMeters(LonMin), _ pZoom, ImageWorldFilename(aFilename)) IO.File.WriteAllText(IO.Path.ChangeExtension(aFilename, "prj"), g_TileProjection) 'IO.File.WriteAllText(IO.Path.ChangeExtension(.FileName, "prj"), "PROJCS[""unnamed"", GEOGCS[""unnamed ellipse"", DATUM[""unknown"", SPHEROID[""unnamed"",6378137,0]], PRIMEM[""Greenwich"",0], UNIT[""degree"",0.0174532925199433]], PROJECTION[""Mercator_2SP""], PARAMETER[""standard_parallel_1"",0], PARAMETER[""central_meridian"",0], PARAMETER[""false_easting"",0], PARAMETER[""false_northing"",0], UNIT[""Meter"",1], EXTENSION[""PROJ4"",""+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs""]]") ''IO.File.WriteAllText(IO.Path.ChangeExtension(.FileName, "prj"), "PROJCS[""Mercator"",GEOGCS[""unnamed ellipse"",DATUM[""D_unknown"",SPHEROID[""Unknown"",6371000,0]],PRIMEM[""Greenwich"",0],UNIT[""Degree"",0.017453292519943295]],PROJECTION[""Mercator""],PARAMETER[""standard_parallel_1"",0],PARAMETER[""central_meridian"",0],PARAMETER[""scale_factor"",1],PARAMETER[""false_easting"",0],PARAMETER[""false_northing"",0],UNIT[""Meter"",1]]") ''IO.File.WriteAllText(IO.Path.ChangeExtension(.FileName, "prj2"), "PROJCS[""Mercator Spheric"", GEOGCS[""WGS84basedSpheric_GCS"", DATUM[""WGS84basedSpheric_Datum"", SPHEROID[""WGS84based_Sphere"", 6378137, 0], TOWGS84[0, 0, 0, 0, 0, 0, 0]], PRIMEM[""Greenwich"", 0, AUTHORITY[""EPSG"", ""8901""]], UNIT[""degree"", 0.0174532925199433, AUTHORITY[""EPSG"", ""9102""]], AXIS[""E"", EAST], AXIS[""N"", NORTH]], PROJECTION[""Mercator""], PARAMETER[""False_Easting"", 0], PARAMETER[""False_Northing"", 0], PARAMETER[""Central_Meridian"", 0], PARAMETER[""Latitude_of_origin"", 0], UNIT[""metre"", 1, AUTHORITY[""EPSG"", ""9001""]], AXIS[""East"", EAST], AXIS[""North"", NORTH]]") ''IO.File.WriteAllText(IO.Path.ChangeExtension(.FileName, "prj3"), "PROJCS[""WGS84 / Simple Mercator"",GEOGCS[""WGS 84"",DATUM[""WGS_1984"",SPHEROID[""WGS_1984"", 6378137.0, 298.257223563]],PRIMEM[""Greenwich"", 0.0],UNIT[""degree"", 0.017453292519943295],AXIS[""Longitude"", EAST],AXIS[""Latitude"", NORTH]],PROJECTION[""Mercator_1SP_Google""],PARAMETER[""latitude_of_origin"", 0.0],PARAMETER[""central_meridian"", 0.0],PARAMETER[""scale_factor"", 1.0],PARAMETER[""false_easting"", 0.0],PARAMETER[""false_northing"", 0.0],UNIT[""m"", 1.0],AXIS[""x"", EAST],AXIS[""y"", NORTH],AUTHORITY[""EPSG"",""900913""]]") ''IO.File.WriteAllText(IO.Path.ChangeExtension(.FileName, "prj4"), "PROJCS[""Google Mercator"",GEOGCS[""WGS 84"",DATUM[""WGS_1984"",SPHEROID[""WGS84"",6378137,298.2572235630016,AUTHORITY[""EPSG"",""7030""]],AUTHORITY[""EPSG"",""6326""]],PRIMEM[""Greenwich"",0],UNIT[""degree"",0.0174532925199433],AUTHORITY[""EPSG"",""4326""]],PROJECTION[""Mercator_1SP""],PARAMETER[""central_meridian"",0],PARAMETER[""scale_factor"",1],PARAMETER[""false_easting"",0],PARAMETER[""false_northing"",0],UNIT[""metre"",1,AUTHORITY[""EPSG"",""9001""]]]") ''+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs ''+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over End Sub Public Function CreateGeoReferenceFile(ByVal aNorthEdge As Double, _ ByVal aWestEdge As Double, _ ByVal aZoom As Integer, _ ByVal aSaveAsFileName As String) As Boolean 'http://en.wikipedia.org/wiki/World_file 'http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=17489 ' and thanks to Bostjan for the idea Dim lFormat As String = "0.00000000000000000" Dim lMetersPerPixel As Double = MetersPerPixel(aZoom, TileServer.TileSize) Dim lFileWriter As New IO.StreamWriter(aSaveAsFileName) If lFileWriter IsNot Nothing Then With lFileWriter .WriteLine(Format(lMetersPerPixel, lFormat)) ' size of pixel in x direction .WriteLine(lFormat) .WriteLine(lFormat) .WriteLine(Format(-lMetersPerPixel, lFormat)) ' size of pixel in y direction (same x to be square, but negative) .WriteLine(Format(aWestEdge, lFormat)) .WriteLine(Format(aNorthEdge, lFormat)) .Close() Return True End With End If Return False End Function Private Sub DrewTiles(ByVal g As Graphics, ByVal aTopLeft As Point, ByVal aOffsetToCenter As Point) 'TODO: ' If pBuddyAlarmEnabled OrElse pBuddyAlarmForm IsNot Nothing Then ' Dim lWaypoint As New clsGPXwaypoint("wpt", pBuddyAlarmLat, pBuddyAlarmLon) ' lWaypoint.sym = "circle" ' Dim lBuddyAlarmLayer As clsLayerGPX = New clsLayerGPX("cursor", Me) ' lBuddyAlarmLayer.SymbolPen = New Pen(Color.Red) ' lBuddyAlarmLayer.SymbolSize = pBuddyAlarmMeters / MetersPerPixel(pZoom) ' lBuddyAlarmLayer.DrawTrackpoint(g, lWaypoint, aTopLeft, aOffsetToCenter, -1, -1) ' End If End Sub Private Function MapRectangle() As Rectangle 'Dim lMenuHeight As Integer = 27 'If Me.MainMenuStrip IsNot Nothing Then lMenuHeight = MainMenuStrip.Height 'With ClientRectangle 'Return New Rectangle(.X, .Y + lMenuHeight, .Width, .Height - lMenuHeight) 'End With Return ClientRectangle End Function Public Sub Redraw() 'If Me.Visible Then 'TODO: AndAlso WindowState <> FormWindowState.Minimized Then Dim lGraphics As Graphics = GetBitmapGraphics() If lGraphics IsNot Nothing Then DrawTiles(lGraphics) ReleaseBitmapGraphics() Refresh() pLastRedrawTime = Now 'TODO: If pCoordinatesForm IsNot Nothing Then pCoordinatesForm.Show(Me) End If Application.DoEvents() 'End If End Sub Private Sub Event_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown 'If pBuddyAlarmForm IsNot Nothing Then ' pBuddyAlarmLat = CenterLat - (e.Y - ClientRectangle.Height / 2) * LatHeight / ClientRectangle.Height ' pBuddyAlarmLon = CenterLon + (e.X - ClientRectangle.Width / 2) * LonWidth / ClientRectangle.Width ' pBuddyAlarmForm.AskUser(pBuddyAlarmLat, pBuddyAlarmLon) ' MouseDownLeft(e) 'Else Select Case e.Button Case Windows.Forms.MouseButtons.Left MouseDownLeft(e) Case Windows.Forms.MouseButtons.Right ClickedTileFilename = FindTileFilename(TileServer, pBitmap.GetBounds(Drawing.GraphicsUnit.Pixel), e.X, e.Y) If ClickedTileFilename.Length > 0 Then If RightClickMenu Is Nothing Then RefreshFromServerToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem("Refresh From Server") ClosestGeocacheToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem("Closest Geocache") TileCacheFolderToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem("Open Cache Folder") RightClickMenu = New System.Windows.Forms.ContextMenuStrip() RightClickMenu.Items.AddRange(New System.Windows.Forms.ToolStripItem() _ {RefreshFromServerToolStripMenuItem, ClosestGeocacheToolStripMenuItem, TileCacheFolderToolStripMenuItem}) ', GetAllDescendantsToolStripMenuItem}) End If RightClickMenu.Show(Me, e.Location) End If End Select 'End If End Sub Private Sub RefreshFromServerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshFromServerToolStripMenuItem.Click If ClickedTileFilename.Length > 0 Then Try Debug.WriteLine("Refreshing '" & ClickedTileFilename & "'") Downloader.DeleteTile(ClickedTileFilename) NeedRedraw() Catch ex As Exception MsgBox("Could not refresh '" & ClickedTileFilename & "'" & vbCrLf & ex.Message, MsgBoxStyle.Critical, "Error Refreshing Tile") End Try ClickedTileFilename = "" End If End Sub Private Sub ClosestGeocacheToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ClosestGeocacheToolStripMenuItem.Click 'TODO: use clicked location not center ShowGeocacheHTML(ClosestGeocache(CenterLat, CenterLon)) End Sub Private Sub TileCacheFolderToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TileCacheFolderToolStripMenuItem.Click If ClickedTileFilename.Length > 0 Then modGlobal.OpenFileOrURL(IO.Path.GetDirectoryName(ClickedTileFilename), False) Else modGlobal.OpenFileOrURL(pTileCacheFolder, False) End If End Sub Private Sub Event_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove If MouseDragging Then 'If pBuddyAlarmForm IsNot Nothing Then ' pBuddyAlarmMeters = MetersBetweenLatLon(pBuddyAlarmLat, pBuddyAlarmLon, _ ' pBuddyAlarmLat + (e.Y - pMouseDragStartLocation.Y) * LatHeight / Me.ClientRectangle.Height, _ ' pBuddyAlarmLon - (e.X - pMouseDragStartLocation.X) * LonWidth / Me.ClientRectangle.Width) ' pBuddyAlarmForm.SetDistance(pBuddyAlarmMeters) 'Else 'GPSFollow = 0 CenterLat = MouseDownLat + (e.Y - MouseDragStartLocation.Y) * LatHeight / Height CenterLon = MouseDownLon - (e.X - MouseDragStartLocation.X) * LonWidth / Width SanitizeCenterLatLon() 'End If NeedRedraw() End If End Sub Private Sub Event_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseWheel Select Case MouseWheelAction Case EnumWheelAction.Zoom If e.Delta > 0 Then Zoom += 1 Else Zoom -= 1 End If Case EnumWheelAction.TileServer Dim lTileServerNames As New Generic.List(Of String) For Each lServer As clsServer In Servers.Values If Not String.IsNullOrEmpty(lServer.TilePattern) Then lTileServerNames.Add(lServer.Name) End If Next If lTileServerNames.Count > 0 Then Dim lNextServerIndex As Integer = lTileServerNames.IndexOf(TileServer.Name) If e.Delta > 0 Then lNextServerIndex += 1 Else lNextServerIndex -= 1 End If If lNextServerIndex >= lTileServerNames.Count Then lNextServerIndex = 0 If lNextServerIndex < 0 Then lNextServerIndex = lTileServerNames.Count - 1 TileServerName = lTileServerNames(lNextServerIndex) End If Case EnumWheelAction.Layer Dim lVisibleIndex As Integer = -1 For lVisibleIndex = 0 To Layers.Count - 1 If Layers(lVisibleIndex).Visible Then Exit For End If Next If e.Delta > 0 Then lVisibleIndex += 1 If lVisibleIndex >= Layers.Count Then lVisibleIndex = 0 Else lVisibleIndex -= 1 If lVisibleIndex < 0 Then lVisibleIndex = Layers.Count - 1 End If For lIndex As Integer = 0 To Layers.Count - 1 If (lIndex = lVisibleIndex) Then Layers(lIndex).Visible = True Else Layers(lIndex).Visible = False End If Next NeedRedraw() Case EnumWheelAction.Transparency If e.Delta > 0 Then TransparentOpacity = Math.Min(TransparentOpacity + 0.1, 1) Else TransparentOpacity = Math.Max(TransparentOpacity - 0.1, 0) End If NeedRedraw() End Select End Sub #End Region 'Desktop #End If End Class
dim LogName as string="DoorBatteryCheck" Dim MinimumCharge as Integer=45 Public Sub Main(ByVal params As String) If params.Length = 0 Then hs.WriteLog(LogName,"No input value found. Exiting script") Exit Sub End If Dim arrInputs() as string arrInputs=params.Split(",") If arrInputs.Length < 4 Then hs.WriteLog(LogName,"Misssing parameters. Exiting script") Exit Sub End If Try hs.SetDeviceValueByRef(CInt(arrInputs(0)), 0, True) dim i,upper As Integer upper=UBound(arrInputs) For i=1 To upper Dim item as string item=arrInputs(i) 'hs.WriteLog(LogName ," " & item) Dim batteryPercent as double=hs.DeviceValueEx(CInt(item)) hs.WriteLog(LogName ,item & ":" & CStr(batteryPercent)) If(batteryPercent<MinimumCharge) Then hs.SetDeviceValueByRef(arrInputs(0), 100, True) End If Next Catch ex As Exception hs.WriteLog(LogName , "ERROR: Exception in script: " & ex.Message) End Try hs.WriteLog(LogName , "Battery report for doors done.") End Sub
Public Class Employee Dim strFName As String Dim strLName As String Dim strAddress1 As String Dim strAddress2 As String Dim strCity As String Dim strState As String Dim strZip As String Dim strPhone As String Dim strSSN As String Dim strUserId As String Dim strPassword As String Dim blnAdmin As Boolean Public Property fName() As String Get Return strFName End Get Set(value As String) strFName = value End Set End Property Public Property lName() As String Get Return strLName End Get Set(value As String) strLName = value End Set End Property Public Property address1() As String Get Return strAddress1 End Get Set(value As String) strAddress1 = value End Set End Property Public Property address2() As String Get Return strAddress2 End Get Set(value As String) strAddress2 = value End Set End Property Public Property city() As String Get Return strCity End Get Set(value As String) strCity = value End Set End Property Public Property state() As String Get Return strState End Get Set(value As String) strState = value End Set End Property Public Property zip() As String Get Return strZip End Get Set(value As String) strZip = value End Set End Property Public Property phone() As String Get Return strPhone End Get Set(value As String) strPhone = value End Set End Property Public Property SSN() As String Get Return strSSN End Get Set(value As String) strSSN = value End Set End Property Public Property userId() As String Get Return strUserId End Get Set(value As String) strUserId = value End Set End Property Public Property password() As String Get Return strPassword End Get Set(value As String) strPassword = value End Set End Property Public Property admin() As Boolean Get Return blnAdmin End Get Set(value As Boolean) blnAdmin = value End Set End Property End Class
Public Class ServiceParent Public Sub ClearProperties(obj As Object) If obj Is Nothing Then Return End If Dim type As Type = obj.GetType() For Each propertyInfo As Reflection.PropertyInfo In type.GetProperties() If propertyInfo.PropertyType.IsArray Then Dim vector = DirectCast(propertyInfo.GetValue(obj, Nothing), Array) If vector IsNot Nothing Then For index = 0 To vector.Length - 1 ClearProperties(vector(index)) Next End If ElseIf propertyInfo.CanWrite AndAlso (propertyInfo.PropertyType = GetType(System.String)) Then If (propertyInfo.GetValue(obj, Nothing) Is Nothing) Then propertyInfo.SetValue(obj, "") End If ElseIf propertyInfo.PropertyType.IsClass Then ClearProperties(propertyInfo.GetValue(obj, Nothing)) End If Next End Sub End Class
Namespace IO Public Interface IDirectory Function IsExists() As Boolean Function GetName() As String Function GetFullName() As String Function GetDirectories() As List(Of IDirectory) Function GetFiles() As List(Of IFile) Function GetFiles(searchPattern As String) As List(Of IFile) Sub Remove() Function Create() As Boolean Function CreateSubDirectory(subDirectoryName As String) As IDirectory Sub MoveTo(destDirName As String) End Interface End Namespace
Namespace Components Public Class Keyboard Inherits Component Private Property Key As UInt16 Private Property Mapping As Dictionary(Of Char, UInt16) Sub New(Parent As Processor) MyBase.New(Parent) Me.Mapping = New Dictionary(Of Char, UInt16) For i As UInt16 = Locations.Keys To Locations.KeysMax Step 4 Me.Mapping.Add(Strings.ChrW(Me.Parent.ReadUInt(i)), Me.Parent.ReadUInt(CUShort(i + 2))) Next End Sub Public Sub PressKey(key As Char) If Me.Mapping.ContainsKey(Char.ToUpper(key)) Then Me.Key = Me.Mapping(Char.ToUpper(key)) End If End Sub Public Sub ReleaseKey(key As Char) Me.Key = &H0 End Sub Public Function GetKeyValue() As UInt16 Try Return Me.Key Finally Me.Key = &H0 End Try End Function End Class End Namespace
Public Class frmWeekTimetable ' Array to store the year panels Public pnlYearPanel As Panel ' Array to store the week set up controls Public wsuWeekWSU(0) As WeekSetUp ' Boolean to tell whether the back button has been pressed or not Public bolBackPressed As Boolean ' Variables to store data from the first page to check for changes and to add to the database Public strTimetableName As String Public intYears As Integer ' The event that is run to load the default start values Public Sub DefaultLoad() ' Hide the error labels lblPage1Error.Visible = False lblPage2Error.Visible = False ' Clear the text boxes txtTimetableName.Text = Nothing txtYears.Text = Nothing ' Hide the page 2 panel and make the page one panel visible pnlPage2.Visible = False pnlPage1.Visible = True ' Set the page 2 panel to the same position as page one pnlPage2.Location = pnlPage1.Location ' Set the active control to the timetable name text box Me.ActiveControl = txtTimetableName ' Set the accept and cancel buttons Me.AcceptButton = btnToPage2 Me.CancelButton = btnPage1Cancel End Sub Private Sub txtYears_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtYears.KeyDown ' Call the allow only numbers event TextBoxEvents.AllowOnlyNumbers(sender, e) End Sub #Region "Form Inherited Events" Public Overridable Sub btnPage2Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPage2Cancel.Click ' Set the dialog result to cancel Me.DialogResult = Windows.Forms.DialogResult.Cancel ' Exit the form Me.Close() End Sub Public Overridable Function CheckPageOneValues() As Boolean ' Variables for contructing a reading statement and reading from the DB Dim cmdSelect As SqlClient.SqlCommand Dim rdrResults As SqlClient.SqlDataReader ' Constants for the error label Const strTimetableNameError As String = "Please enter a name for the timetable" Const strYearsError As String = "Please enter the number of years for the timetable" Const strTimetableNameExists As String = "Timetable name taken, please select another" ' Check to see if a timetable name has been entered If txtTimetableName.Text = Nothing Then ' Set the error label text lblPage1Error.Text = strTimetableNameError ' Set the position of the label LabelCentreX(lblPage1Error, Me) ' Make the label visible lblPage1Error.Visible = True Return True End If ' Construct the sql command cmdSelect = New SqlClient.SqlCommand("SELECT TimetableName FROM Timetable WHERE UserID = " & strUserInfo(intUserInfo.ID), ctnTimetable) ' Execute the command rdrResults = cmdSelect.ExecuteReader Do While rdrResults.Read ' Check to see if the username is taken If txtTimetableName.Text.Trim = rdrResults!TimetableName Then ' Set the text of the error label to the username taken constant lblPage1Error.Text = strTimetableNameExists ' Position the label LabelCentreX(lblPage1Error, Me) ' Show the error label lblPage1Error.Visible = True ' Reset the variables cmdSelect = Nothing rdrResults.Close() ' Exit the sub Return True End If Loop ' Reset the variables cmdSelect = Nothing rdrResults.Close() ' Check to see if a value for the year is entered and numeric If txtYears.Text = Nothing Then ' Set the error label text lblPage1Error.Text = strYearsError ' Set the position of the label LabelCentreX(lblPage1Error, Me) ' Make the label visible lblPage1Error.Visible = True Return True End If Return False End Function Public Overridable Function CheckPageTwoValues() As Boolean ' Constants for the error label Const strSeveralWeekError As String = "Please enter a duration for years " Const strOneWeekError As String = "Please enter a duration for year " ' Variable to hold the current entry in week set up array Dim intEntry As Integer ' Array to hold the weeks that have no duration Dim intWeekError(0) As Integer For intEntry = 1 To wsuWeekWSU.Length - 1 ' Check to see if a duration is entered If wsuWeekWSU(intEntry).Duration = 0 Then ' Resize the array Array.Resize(intWeekError, intWeekError.Length + 1) ' Add the year number to the array intWeekError(intWeekError.Length - 1) = wsuWeekWSU(intEntry).ControlYear End If Next ' Check to see if there are years without duration If intWeekError.Length = 2 Then ' Set the error label text lblPage2Error.Text = strOneWeekError & intWeekError(1) ' Set the position of the label LabelCentreX(lblPage2Error, Me) ' Make the label visible lblPage2Error.Visible = True Return True ElseIf intWeekError.Length > 2 Then ' Set the error label text to the constant lblPage2Error.Text = strSeveralWeekError ' Add the week to the error label lblPage2Error.Text &= intWeekError(1) For intEntry = 2 To intWeekError.Length - 2 ' Add the week to the error label lblPage2Error.Text &= ", " lblPage2Error.Text &= intWeekError(intEntry) Next ' Add the week to the error label lblPage2Error.Text &= " and " lblPage2Error.Text &= intWeekError(intWeekError.Length - 1) ' Set the position of the label LabelCentreX(lblPage2Error, Me) ' Make the label visible lblPage2Error.Visible = True Return True End If Return False End Function Public Overridable Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPage1Cancel.Click ' Set the dialog result to cancel Me.DialogResult = Windows.Forms.DialogResult.Cancel ' Exit the form Me.Close() End Sub ''' <summary> ''' Create a new panel to to store the week controls then adds the controls to the panel ''' </summary> ''' <param name="intStartYear">The year number to start adding from</param> ''' <param name="intEndYear">The year number to add to</param> ''' <remarks></remarks> Public Overridable Sub CreateNewYears(ByVal intStartYear As Integer, ByVal intEndYear As Integer) ' Create a new instance of the panel in the array to hold the week set up controls pnlYearPanel = New Panel ' Create the panel to hold the year controls for the timetable pnlYearPanel.Visible = False pnlYearPanel.AutoScroll = True pnlYearPanel.BackColor = System.Drawing.Color.Transparent pnlYearPanel.Location = New System.Drawing.Point(0, 10) pnlYearPanel.Name = "pnlYears" pnlYearPanel.Size = New System.Drawing.Size(477, 147) ' Add the new panel to the page panel pnlPage2.Controls.Add(pnlYearPanel) ' Add Years to the panel CreateNewYear(intStartYear, intEndYear) ' Make the panel visible pnlYearPanel.Visible = True End Sub ''' <summary> ''' Creates new week setup controls and adds them to the panel ''' </summary> ''' <param name="intStartYear">The year number to start adding from</param> ''' <param name="intEndYear">The year number to add to</param> ''' <remarks></remarks> Public Overridable Sub CreateNewYear(ByVal intStartYear As Integer, ByVal intEndYear As Integer) ' Variable for creating the week control Dim intCurrentYearEntry As Integer ' Create the week set up controls For intCurrentYearEntry = intStartYear To intEndYear ' Create a new instance of the week set up control wsuWeekWSU(intCurrentYearEntry) = New WeekSetUp ' Create the week set up control wsuWeekWSU(intCurrentYearEntry).ControlYear = intCurrentYearEntry wsuWeekWSU(intCurrentYearEntry).Dock = System.Windows.Forms.DockStyle.Top wsuWeekWSU(intCurrentYearEntry).Location = New System.Drawing.Point(0, 0) wsuWeekWSU(intCurrentYearEntry).Name = "wsuYear" & intCurrentYearEntry wsuWeekWSU(intCurrentYearEntry).Size = New System.Drawing.Size(477, 49) ' Add the week set up to the panel pnlYearPanel.Controls.Add(wsuWeekWSU(intCurrentYearEntry)) ' Send the control to the bottom of the panel wsuWeekWSU(intCurrentYearEntry).BringToFront() Next End Sub Public Overridable Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click ' Set the button back boolean to true bolBackPressed = True ' Hide the page two panel and show the page one panel pnlPage1.Visible = True pnlPage2.Visible = False ' Set the active control to the timetable name text box Me.ActiveControl = txtTimetableName ' Set the accept and cancel buttons Me.AcceptButton = btnToPage2 Me.CancelButton = btnPage1Cancel End Sub #End Region Private Sub txtTimetableName_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTimetableName.KeyDown ' Call the allow alpha numeric event TextBoxEvents.AllowAlphaNumeric(sender, e) End Sub End Class
Public Class FrmSelectItems Public Structure FrmSelectItemsResult Public SelectedItems As Collections.IList Public DlgResult As DialogResult End Structure Private m_fullItemsList As Collections.IList Private Sub New() InitializeComponent() End Sub Protected Overrides Sub Finalize() m_fullItemsList = Nothing MyBase.Finalize() End Sub Public Shared Function GetSelectedItems(itemsList As Collections.IList, selectedItemsList As Collections.IList, owner As IWin32Window) As FrmSelectItemsResult Dim result As FrmSelectItemsResult result.SelectedItems = Nothing Dim frm As New FrmSelectItems frm.SetItems(itemsList) frm.setSelectedItems(selectedItemsList) result.DlgResult = frm.ShowDialog(owner) If result.DlgResult = DialogResult.OK Then result.SelectedItems = frm.Lst_SelectionList.Items End If Return result End Function Private Sub SetItems(itemsList As Collections.IList) m_fullItemsList = itemsList Lst_InitList.Items.Clear() If itemsList IsNot Nothing Then For Each item As Object In itemsList Lst_InitList.Items.Add(item) Next End If End Sub Private Sub setSelectedItems(selectedItemsList As Collections.IList) Lst_SelectionList.Items.Clear() If selectedItemsList IsNot Nothing Then For Each item As Object In selectedItemsList Lst_SelectionList.Items.Add(item) Next End If End Sub Private Sub Btn_Add_MouseUp(sender As Object, e As MouseEventArgs) Handles Btn_Add.MouseUp If e.Button = Windows.Forms.MouseButtons.Left Then AddSelectedItem() End If End Sub Private Sub Btn_Remove_MouseUp(sender As Object, e As MouseEventArgs) Handles Btn_Remove.MouseUp If e.Button = Windows.Forms.MouseButtons.Left Then RemoveSelectedItem() End If End Sub Private Sub Btn_OK_MouseUp(sender As Object, e As MouseEventArgs) Handles Btn_OK.MouseUp If e.Button = Windows.Forms.MouseButtons.Left Then Me.DialogResult = DialogResult.OK End If End Sub Private Sub Btn_Cancel_MouseUp(sender As Object, e As MouseEventArgs) Handles Btn_Cancel.MouseUp If e.Button = Windows.Forms.MouseButtons.Left Then Me.DialogResult = DialogResult.Cancel End If End Sub Private Sub Txt_Filter_KeyUp(sender As Object, e As KeyEventArgs) Handles Txt_Filter.KeyUp 'If e.KeyCode = Keys.Enter Then Dim filteredList As New List(Of Object) Dim filter As String = "*" & Txt_Filter.Text.Trim.ToLower & "*" For Each o As Object In m_fullItemsList If o.ToString.ToLower Like filter Then filteredList.Add(o) End If Next Lst_InitList.Items.Clear() Lst_InitList.Items.AddRange(filteredList.ToArray) 'End If End Sub Private Sub frmSelectItems_Activated(sender As Object, e As EventArgs) Handles Me.Activated With Txt_Filter .TabIndex = 0 .Focus() End With End Sub Private Sub AddSelectedItem() If Lst_InitList.SelectedItem IsNot Nothing Then If Not Lst_SelectionList.Items.Contains(Lst_InitList.SelectedItem) Then Lst_SelectionList.Items.Add(Lst_InitList.SelectedItem) Else MsgBox(Lst_InitList.SelectedItem.ToString & " est déjà dans la liste.", MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, "Doublons...") End If End If End Sub Private Sub RemoveSelectedItem() If Lst_SelectionList.SelectedItem IsNot Nothing Then Lst_SelectionList.Items.Remove(Lst_SelectionList.SelectedItem) End If End Sub Private Sub Lst_InitList_DoubleClick(sender As Object, e As EventArgs) Handles Lst_InitList.DoubleClick AddSelectedItem() End Sub Private Sub Lst_SelectionList_DoubleClick(sender As Object, e As EventArgs) Handles Lst_SelectionList.DoubleClick RemoveSelectedItem() End Sub End Class
Imports Microsoft.VisualBasic Public Class Constants Public Enum OU Country = 1 Organize = 2 Person = 3 End Enum Public Enum Contact_Parent_Type Oraganize = 0 Person = 1 Project = 2 End Enum Public Enum Person_Type Officer = 0 Recipient = 1 End Enum Public Enum AgencyType FunddingAgency = 0 ExcutingAgency = 1 ImplementingAgency = 2 End Enum Public Enum Project_Type Project = 0 NonProject = 1 Loan = 2 Contribuition = 3 End Enum 'Structure Prefix_Language ' Const Thai = "T" ' Const English = "E" 'End Structure End Class
Public Class KobetuSentakuUtility ''' <summary> ''' 個別選択のチェック更新用データテーブルを作成します。 ''' </summary> ''' <param name="codeFieldName">CLASSCODE,TENCODE等を指定します。</param> ''' <param name="srcDataTable">コピー元のデータテーブルを指定します。</param> ''' <param name="AlwaysChecked">コピー元のCHKARIAにかかわらず-1に設定します。</param> ''' <returns>Updateの引数に指定可能なデータテーブル</returns> ''' <remarks>codeFieldNameで指定されたフィールド名でソースデータテーブルのアクセスと作成されるフィールド名を決定します。</remarks> Public Shared Function MakeSentakuUpdateDataTable(ByVal codeFieldName As String, ByVal srcDataTable As DataTable, ByVal AlwaysChecked As Boolean) As DataTable Dim dt As New System.Data.DataTable Dim dr As System.Data.DataRow dt.Columns.Add("CHKARIA", Type.GetType("System.Int32")) dt.Columns.Add(codeFieldName, Type.GetType("System.String")) For Each row As DataRow In srcDataTable.Rows If row.RowState <> DataRowState.Deleted Then dr = Nothing dr = dt.NewRow() dr.BeginEdit() If AlwaysChecked = False Then dr.Item("CHKARIA") = row("CHKARIA") Else dr.Item("CHKARIA") = -1 End If dr.Item(codeFieldName) = row(codeFieldName) dr.EndEdit() dt.Rows.Add(dr) End If Next Return dt End Function End Class
Imports Microsoft.VisualBasic Imports System.data Imports System.Web Imports Talent.Common <Serializable()> _ Public Class TalentPPS Inherits TalentBase Private _resultDataSet As DataSet Private _dePPS As DEPPS Private _dePPSEnrolmentScheme As DEPPSEnrolmentScheme Public Property ResultDataSet() As DataSet Get Return _resultDataSet End Get Set(ByVal value As DataSet) _resultDataSet = value End Set End Property Public Property DEPPS() As DEPPS Get Return _dePPS End Get Set(ByVal value As DEPPS) _dePPS = value End Set End Property Public Property DEPPSEnrolmentScheme() As DEPPSEnrolmentScheme Get Return _dePPSEnrolmentScheme End Get Set(ByVal value As DEPPSEnrolmentScheme) _dePPSEnrolmentScheme = value End Set End Property Public Function AddPPSRequest() As ErrorObj Const ModuleName As String = "AddPPSRequest" Dim err As New ErrorObj Dim dbPPS As New DBPPS Me.GetConnectionDetails(Settings.BusinessUnit, "", ModuleName) With dbPPS .Settings = Settings .Settings.ModuleName = ModuleName .dePPS = DEPPS err = .ValidateAgainstDatabase() If Not .ResultDataSet Is Nothing Then ResultDataSet = .ResultDataSet End If If Not err.HasError And ResultDataSet Is Nothing Then err = .AccessDatabase If Not err.HasError And Not .ResultDataSet Is Nothing Then ResultDataSet = .ResultDataSet End If End If End With Return err End Function Public Function AmendPPS() As ErrorObj Const ModuleName As String = "AmendPPS" Dim err As New ErrorObj Dim dbPPS As New DBPPS Me.GetConnectionDetails(Settings.BusinessUnit, "", ModuleName) With dbPPS .Settings = Settings .Settings.ModuleName = ModuleName .dePPSEnrolmentScheme = DEPPSEnrolmentScheme err = .ValidateAgainstDatabase() If Not .ResultDataSet Is Nothing Then ResultDataSet = .ResultDataSet End If If Not err.HasError And ResultDataSet Is Nothing Then err = .AccessDatabase If Not err.HasError And Not .ResultDataSet Is Nothing Then ResultDataSet = .ResultDataSet End If End If End With Return err End Function Public Function CancelPPSEnrollment() As ErrorObj Const ModuleName As String = "CancelPPSEnrollment" Dim err As New ErrorObj Dim dbPPS As New DBPPS Me.GetConnectionDetails(Settings.BusinessUnit, "", ModuleName) With dbPPS .Settings = Settings .Settings.ModuleName = ModuleName .dePPSEnrolmentScheme = DEPPSEnrolmentScheme .dePPS = DEPPS err = .ValidateAgainstDatabase() If Not .ResultDataSet Is Nothing Then ResultDataSet = .ResultDataSet End If If Not err.HasError And ResultDataSet Is Nothing Then err = .AccessDatabase If Not err.HasError And Not .ResultDataSet Is Nothing Then ResultDataSet = .ResultDataSet End If End If End With Return err End Function End Class
Imports DevExpress.Data Imports DevExpress.Xpf.Editors Imports DevExpress.Xpf.Editors.Settings Imports DevExpress.Xpf.Grid Imports System Imports System.Collections.Generic Imports System.Data Imports System.Drawing Imports System.Globalization Imports System.Linq Namespace GridDemo Partial Public Class MultiCellSelection Inherits GridDemoModule Public Sub New() InitializeComponent() AssignDataSource() SelectCells() End Sub Private Shared ReadOnly dxLogo() As String = { "dd ", "dd ", "ddd", "d d", "d d", "d d", "d d", "d d", "ddd", "dd ", "dd ", " ", "x x", "x x", "xxx", "xxx", " x ", " x ", " x ", "xxx", "xxx", "x x", "x x"} Private Sub SelectCells() grid.BeginSelection() Dim points = dxLogo.SelectMany(Function(s, y) s.Select(Function(c, x)If(c <> " "c, New Point(x, y), DirectCast(Nothing, Point?)))) For Each point In points.Where(Function(x) x IsNot Nothing) view.SelectCell(point.Value.Y, view.VisibleColumns(point.Value.X + 1)) Next point grid.EndSelection() End Sub Private Sub AssignDataSource() grid.ItemsSource = SalesByYearData.Data grid.Columns("Date").Visible = False grid.Columns("Date").ShowInColumnChooser = False For Each column As GridColumn In view.VisibleColumns grid.TotalSummary.Add(New GridSummaryItem() With {.FieldName = column.FieldName, .SummaryType = DevExpress.Data.SummaryItemType.Custom, .DisplayFormat = "${0:N}"}) column.EditSettings = New SpinEditSettings() With {.MaskType = MaskType.Numeric, .MaskUseAsDisplayFormat = True, .Mask = "c", .MaskCulture = New CultureInfo("en-US")} Next column End Sub Private sum As Integer = 0 Private Sub grid_CustomSummary(ByVal sender As Object, ByVal e As DevExpress.Data.CustomSummaryEventArgs) If Object.Equals(e.SummaryProcess, CustomSummaryProcess.Start) Then sum = 0 End If If e.SummaryProcess = CustomSummaryProcess.Calculate Then If grid.View IsNot Nothing Then If (Not checkEdit.IsChecked.Value) OrElse view.IsCellSelected(e.RowHandle, grid.Columns(CType(e.Item, GridSummaryItem).FieldName)) Then If e.FieldValue IsNot DBNull.Value AndAlso e.FieldValue IsNot Nothing Then sum += CInt((e.FieldValue)) End If End If End If End If If e.SummaryProcess = CustomSummaryProcess.Finalize Then e.TotalValue = sum End If End Sub Private Sub TableView_SelectionChanged(ByVal sender As Object, ByVal e As DevExpress.Xpf.Grid.GridSelectionChangedEventArgs) grid.UpdateTotalSummary() End Sub Private Sub CheckEdit_EditValueChanged(ByVal sender As Object, ByVal e As DevExpress.Xpf.Editors.EditValueChangedEventArgs) grid.UpdateTotalSummary() End Sub Private Sub Button_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) SelectCells(True) End Sub Private Sub Button_Click_1(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) SelectCells(False) End Sub Private Sub SelectCells(ByVal shouldSelectTopValues As Boolean) Dim list As New List(Of KeyValuePair(Of GridCell, Integer))() For i As Integer = 0 To grid.VisibleRowCount - 1 For j As Integer = 0 To view.VisibleColumns.Count - 1 list.Add(New KeyValuePair(Of GridCell, Integer)(New GridCell(i, view.VisibleColumns(j)), CInt((grid.GetCellValue(i, view.VisibleColumns(j)))))) Next j Next i list.Sort(Function(x As KeyValuePair(Of GridCell, Integer), y As KeyValuePair(Of GridCell, Integer)) Compare(x, y, shouldSelectTopValues)) grid.BeginSelection() view.DataControl.UnselectAll() For i As Integer = 0 To Math.Min(20, list.Count) - 1 view.SelectCell(list(list.Count - i - 1).Key.RowHandle, list(list.Count - i - 1).Key.Column) Next i grid.EndSelection() End Sub Private Shared Function Compare(ByVal x As KeyValuePair(Of GridCell, Integer), ByVal y As KeyValuePair(Of GridCell, Integer), ByVal shouldSelectTopValues As Boolean) As Integer If shouldSelectTopValues Then Return Comparer(Of Integer).Default.Compare(x.Value, y.Value) Else Return Comparer(Of Integer).Default.Compare(y.Value, x.Value) End If End Function End Class End Namespace
Public Enum Genero As Integer Masculino Femenino End Enum
Imports Motor3D.Espacio3D Namespace Primitivas3D Public Class OctreeGrafico Inherits ObjetoGeometrico3D Private mNiveles As Integer Private mSectorRaiz As SectorOctreeGrafico Public Property Espacio() As AABB3D Get Return mSectorRaiz.Espacio End Get Set(ByVal value As AABB3D) If mSectorRaiz.Espacio <> value Then mSectorRaiz = New SectorOctreeGrafico(mNiveles, value) End If End Set End Property Public Property Niveles() As Integer Get Return mNiveles End Get Set(ByVal value As Integer) If value > 0 Then mNiveles = value mSectorRaiz = New SectorOctreeGrafico(mNiveles, mSectorRaiz.Espacio) End If End Set End Property Public ReadOnly Property SectorRaiz() As SectorOctreeGrafico Get Return mSectorRaiz End Get End Property Public ReadOnly Property Pertenece(ByVal Punto As Punto3D) As Boolean Get Return mSectorRaiz.Espacio.Pertenece(Punto) End Get End Property Public ReadOnly Property Pertenece(ByVal AABB As AABB3D) As Boolean Get Return mSectorRaiz.Espacio.Colisionan(AABB) End Get End Property Public ReadOnly Property Pertenece(ByVal Recta As Recta3D) As Boolean Get Return mSectorRaiz.Espacio.Pertenece(Recta) End Get End Property Public Sub New(ByVal Niveles As Integer, ByVal AABB As AABB3D) If Niveles > 1 Then mNiveles = Niveles mSectorRaiz = New SectorOctreeGrafico(Niveles, AABB) Else Throw New ExcepcionGeometrica3D("OctreeGrafico (NEW): Un OctreeGrafico debe tener al menos dos niveles:" & vbNewLine _ & "Niveles=" & Niveles) End If End Sub Public Function Sector(ByVal Punto As Punto3D) As SectorOctreeGrafico Return Sector(Me, Punto) End Function Public Function Sector(ByVal Recta As Recta3D) As SectorOctreeGrafico Return Sector(Me, Recta) End Function Public Function Sector(ByVal AABB As AABB3D) As SectorOctreeGrafico Return Sector(Me, AABB) End Function Public Function Sectores(ByVal Recta As Recta3D) As SectorOctreeGrafico() Return Sectores(Me, Recta) End Function Public Shared Function Sector(ByVal OctreeGrafico As OctreeGrafico, ByVal Punto As Punto3D) As SectorOctreeGrafico Dim Resultado As Integer = OctreeGrafico.SectorRaiz.Pertenece(Punto) Dim S As SectorOctreeGrafico = OctreeGrafico.SectorRaiz If Resultado <> -2 Then If Resultado = -1 Then Return S Else Do While Resultado <> -2 AndAlso Resultado <> -1 Resultado = S.Pertenece(Punto) If Resultado <> -2 Then If Resultado = -1 Then Return S Else S = S.Hijos(Resultado) End If Else Return S.Padre End If Loop Return S End If Else Throw New ExcepcionGeometrica3D("OctreeGrafico (PERTENECE): El punto especificado no pertenece al espacio dominado por el quadtree." & vbNewLine _ & "Punto=" & Punto.ToString & vbNewLine _ & "Espacio=" & OctreeGrafico.Espacio.ToString) End If End Function Public Shared Function Sector(ByVal OctreeGrafico As OctreeGrafico, ByVal Recta As Recta3D) As SectorOctreeGrafico Dim Resultado As Integer = OctreeGrafico.SectorRaiz.Pertenece(Recta) Dim S As SectorOctreeGrafico = OctreeGrafico.SectorRaiz If Resultado <> -2 Then If Resultado = -1 Then Return S Else Do While Resultado <> -2 AndAlso Resultado <> -1 Resultado = S.Pertenece(Recta) If Resultado <> -2 Then If Resultado = -1 Then Return S Else S = S.Hijos(Resultado) End If Else Return S.Padre End If Loop Return S End If Else Throw New ExcepcionGeometrica3D("OctreeGrafico (PERTENECE): ELa recta especificada no pertenece al espacio dominado por el quadtree." & vbNewLine _ & "Punto=" & Recta.ToString & vbNewLine _ & "Espacio=" & OctreeGrafico.Espacio.ToString) End If End Function Public Shared Function Sectores(ByVal OctreeGrafico As OctreeGrafico, ByVal Recta As Recta3D) As SectorOctreeGrafico() Dim S As SectorOctreeGrafico = OctreeGrafico.SectorRaiz Dim Retorno As New List(Of SectorOctreeGrafico) If OctreeGrafico.SectorRaiz.Espacio.Pertenece(Recta) Then InterseccionRecta(Recta, S, Retorno) Return Retorno.ToArray Else Throw New ExcepcionGeometrica3D("OctreeGrafico (PERTENECE): La recta especificada no pertenece al espacio dominado por el quadtree." & vbNewLine _ & "Recta=" & Recta.ToString & vbNewLine _ & "Espacio=" & OctreeGrafico.Espacio.ToString) End If End Function Public Shared Sub InterseccionRecta(ByVal Recta As Recta3D, ByVal Sector As SectorOctreeGrafico, ByRef ListaRetorno As List(Of SectorOctreeGrafico)) If Not Sector.EsHoja Then For Each Hijo As SectorOctreeGrafico In Sector.Hijos If Hijo.Espacio.Pertenece(Recta) Then InterseccionRecta(Recta, Hijo, ListaRetorno) End If Next Else If Sector.Espacio.Pertenece(Recta) Then ListaRetorno.Add(Sector) End If End Sub Public Shared Function Sector(ByVal OctreeGrafico As OctreeGrafico, ByVal AABB As AABB3D) As SectorOctreeGrafico Dim Resultado As Integer = OctreeGrafico.SectorRaiz.Pertenece(AABB) Dim S As SectorOctreeGrafico = OctreeGrafico.SectorRaiz 'PARA ENTENDER EL ALGORITMO, IR A FUNCION PERTENECE DE SECTORQUADTREE. If Resultado <> -2 Then If Resultado = -1 Then Return OctreeGrafico.SectorRaiz Else Do If Resultado <> -2 Then If Resultado = -1 Then Return S Else S = S.Hijos(Resultado) End If Else Return S.Padre End If Resultado = S.Pertenece(AABB) Loop While Resultado <> -2 AndAlso Resultado <> -1 Return S End If Else Throw New ExcepcionGeometrica3D("OctreeGrafico (PERTENECE): La AABB especificada no pertenece al espacio dominado por el quadtree." & vbNewLine _ & "AABB=" & AABB.ToString & vbNewLine _ & "Espacio=" & OctreeGrafico.Espacio.ToString) End If End Function Public Overrides Function ToString() As String Return "{OctreeGrafico de espacio=" & mSectorRaiz.Espacio.ToString & "}" End Function End Class End Namespace
Imports System Imports System.Diagnostics Imports DevExpress.DevAV.Common.ViewModel Imports DevExpress.Mvvm Imports DevExpress.Mvvm.DataAnnotations Imports DevExpress.Mvvm.POCO Namespace DevExpress.DevAV.ViewModels Public Class EmployeeContactsViewModel Public Shared Function Create() As EmployeeContactsViewModel Return ViewModelSource.Create(Function() New EmployeeContactsViewModel()) End Function Protected Sub New() End Sub Public Overridable Property Entity() As Employee Protected ReadOnly Property MessageBoxService() As IMessageBoxService Get Return Me.GetRequiredService(Of IMessageBoxService)() End Get End Property Public Sub Message() MessageBoxService.Show("Send an IM to: " & Entity.Skype) End Sub Public Function CanMessage() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.Skype) End Function Public Sub Phone() MessageBoxService.Show("Phone Call: " & Entity.MobilePhone) End Sub Public Function CanPhone() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.MobilePhone) End Function Public Sub HomeCall() MessageBoxService.Show("Home Call: " & Entity.HomePhone) End Sub Public Function CanHomeCall() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.HomePhone) End Function Public Sub MobileCall() MessageBoxService.Show("Mobile Call: " & Entity.MobilePhone) End Sub Public Function CanMobileCall() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.MobilePhone) End Function Public Sub [Call]() MessageBoxService.Show("Call: " & Entity.Skype) End Sub Public Function CanCall() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.Skype) End Function Public Sub VideoCall() MessageBoxService.Show("Video Call: " & Entity.Skype) End Sub Public Function CanVideoCall() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.Skype) End Function Public Sub MailTo() ExecuteMailTo(MessageBoxService, Entity.Email) End Sub Public Function CanMailTo() As Boolean Return Entity IsNot Nothing AndAlso Not String.IsNullOrEmpty(Entity.Email) End Function Protected Overridable Sub OnEntityChanged() Me.RaiseCanExecuteChanged(Sub(x) x.Message()) Me.RaiseCanExecuteChanged(Sub(x) x.Phone()) Me.RaiseCanExecuteChanged(Sub(x) x.MobileCall()) Me.RaiseCanExecuteChanged(Sub(x) x.HomeCall()) Me.RaiseCanExecuteChanged(Sub(x) x.Call()) Me.RaiseCanExecuteChanged(Sub(x) x.VideoCall()) Me.RaiseCanExecuteChanged(Sub(x) x.MailTo()) End Sub Public Shared Sub ExecuteMailTo(ByVal messageBoxService As IMessageBoxService, ByVal email As String) Try Process.Start("mailto://" & email) Catch If messageBoxService IsNot Nothing Then messageBoxService.Show("Mail To: " & email) End If End Try End Sub End Class End Namespace
Imports cv = OpenCvSharp Imports System.Runtime.InteropServices Public Class Random_Points : Implements IDisposable Public sliders As New OptionsSliders Public Points() As cv.Point Public Points2f() As cv.Point2f Public externalUse As Boolean Public Sub New(ocvb As AlgorithmData) sliders.setupTrackBar1(ocvb, "Random Pixel Count", 1, 500, 20) If ocvb.parms.ShowOptions Then sliders.Show() ReDim Points(sliders.TrackBar1.Value - 1) ReDim Points2f(sliders.TrackBar1.Value - 1) ocvb.desc = "Create a random mask with a specificied number of pixels." End Sub Public Sub Run(ocvb As AlgorithmData) If Points.Length <> sliders.TrackBar1.Value Then ReDim Points(sliders.TrackBar1.Value - 1) ReDim Points2f(sliders.TrackBar1.Value - 1) End If If externalUse = False Then ocvb.result1.SetTo(0) For i = 0 To Points.Length - 1 Dim x = ocvb.rng.uniform(0, ocvb.color.Cols) Dim y = ocvb.rng.uniform(0, ocvb.color.Rows) Points(i) = New cv.Point2f(x, y) Points2f(i) = New cv.Point2f(x, y) If externalUse = False Then cv.Cv2.Circle(ocvb.result1, Points(i), 3, cv.Scalar.Gray, -1, cv.LineTypes.AntiAlias, 0) Next End Sub Public Sub Dispose() Implements IDisposable.Dispose sliders.Dispose() End Sub End Class Public Class Random_Shuffle : Implements IDisposable Public Sub New(ocvb As AlgorithmData) ocvb.desc = "Use randomShuffle to reorder an image." End Sub Public Sub Run(ocvb As AlgorithmData) ocvb.depthRGB.CopyTo(ocvb.result1) Dim myRNG As New cv.RNG cv.Cv2.RandShuffle(ocvb.result1, 1.0, myRNG) ' don't remove that myRNG! It will fail in RandShuffle. ocvb.label1 = "Random_shuffle - wave at camera" End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Public Class Random_LUTMask : Implements IDisposable Dim random As Random_Points Dim km As kMeans_Basics Public Sub New(ocvb As AlgorithmData) km = New kMeans_Basics(ocvb) random = New Random_Points(ocvb) ocvb.desc = "Use a random Look-Up-Table to modify few colors in a kmeans image. Note how interpolation impacts results" ocvb.label2 = "kmeans run To Get colors" End Sub Public Sub Run(ocvb As AlgorithmData) Static lutMat As cv.Mat If lutMat Is Nothing Or ocvb.frameCount Mod 10 = 0 Then random.Run(ocvb) lutMat = cv.Mat.Zeros(New cv.Size(1, 256), cv.MatType.CV_8UC3) Dim lutIndex = 0 km.Run(ocvb) ' sets result1 ocvb.result1.CopyTo(ocvb.result2) For i = 0 To random.Points.Length - 1 Dim x = random.Points(i).X Dim y = random.Points(i).Y If x >= ocvb.drawRect.X And x < ocvb.drawRect.X + ocvb.drawRect.Width Then If y >= ocvb.drawRect.Y And y < ocvb.drawRect.Y + ocvb.drawRect.Height Then lutMat.Set(lutIndex, 0, ocvb.result2.At(Of cv.Vec3b)(y, x)) lutIndex += 1 If lutIndex >= lutMat.Rows Then Exit For End If End If Next End If ocvb.result2 = ocvb.color.LUT(lutMat) ocvb.label1 = "Using kmeans colors with interpolation" End Sub Public Sub Dispose() Implements IDisposable.Dispose km.Dispose() random.Dispose() End Sub End Class Public Class Random_UniformDist : Implements IDisposable Public uDist As cv.Mat Public externalUse As Boolean Public Sub New(ocvb As AlgorithmData) uDist = New cv.Mat(ocvb.color.Size(), cv.MatType.CV_8UC1) ocvb.desc = "Create a uniform distribution." End Sub Public Sub Run(ocvb As AlgorithmData) cv.Cv2.Randu(uDist, 0, 255) If externalUse = False Then ocvb.result1 = uDist.CvtColor(cv.ColorConversionCodes.GRAY2BGR) End If End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Public Class Random_NormalDist : Implements IDisposable Public sliders As New OptionsSliders Public nDistImage As cv.Mat Public externalUse As Boolean Public Sub New(ocvb As AlgorithmData) sliders.setupTrackBar1(ocvb, "Random_NormalDist Blue Mean", 0, 255, 25) sliders.setupTrackBar2(ocvb, "Random_NormalDist Green Mean", 0, 255, 127) sliders.setupTrackBar3(ocvb, "Random_NormalDist Red Mean", 0, 255, 180) sliders.setupTrackBar4(ocvb, "Random_NormalDist Stdev", 0, 255, 50) If ocvb.parms.ShowOptions Then sliders.Show() ocvb.desc = "Create a normal distribution." End Sub Public Sub Run(ocvb As AlgorithmData) cv.Cv2.Randn(ocvb.result1, New cv.Scalar(sliders.TrackBar1.Value, sliders.TrackBar2.Value, sliders.TrackBar3.Value), cv.Scalar.All(sliders.TrackBar4.Value)) If externalUse Then nDistImage = ocvb.result1.CvtColor(cv.ColorConversionCodes.BGR2GRAY) End Sub Public Sub Dispose() Implements IDisposable.Dispose sliders.Dispose() End Sub End Class Public Class Random_CheckUniformDist : Implements IDisposable Dim histogram As Histogram_KalmanSmoothed Dim rUniform As Random_UniformDist Public Sub New(ocvb As AlgorithmData) histogram = New Histogram_KalmanSmoothed(ocvb) histogram.externalUse = True histogram.sliders.TrackBar1.Value = 255 histogram.gray = New cv.Mat rUniform = New Random_UniformDist(ocvb) rUniform.externalUse = True ocvb.desc = "Display the histogram for a uniform distribution." End Sub Public Sub Run(ocvb As AlgorithmData) rUniform.Run(ocvb) ocvb.result1 = rUniform.uDist.CvtColor(cv.ColorConversionCodes.gray2bgr) rUniform.uDist.CopyTo(histogram.gray) histogram.Run(ocvb) End Sub Public Sub Dispose() Implements IDisposable.Dispose rUniform.Dispose() histogram.Dispose() End Sub End Class Public Class Random_CheckNormalDist : Implements IDisposable Dim histogram As Histogram_KalmanSmoothed Dim normalDist As Random_NormalDist Public Sub New(ocvb As AlgorithmData) histogram = New Histogram_KalmanSmoothed(ocvb) histogram.externalUse = True histogram.sliders.TrackBar1.Value = 255 histogram.gray = New cv.Mat histogram.plotHist.minRange = 1 normalDist = New Random_NormalDist(ocvb) normalDist.externalUse = True ocvb.desc = "Display the histogram for a Normal distribution." End Sub Public Sub Run(ocvb As AlgorithmData) normalDist.Run(ocvb) ocvb.result1 = normalDist.nDistImage.CvtColor(cv.ColorConversionCodes.gray2bgr) normalDist.nDistImage.CopyTo(histogram.gray) histogram.Run(ocvb) End Sub Public Sub Dispose() Implements IDisposable.Dispose normalDist.Dispose() histogram.Dispose() End Sub End Class Module Random_PatternGenerator_CPP_Module <DllImport(("CPP_Classes.dll"), CallingConvention:=CallingConvention.Cdecl)> Public Function Random_PatternGenerator_Open() As IntPtr End Function <DllImport(("CPP_Classes.dll"), CallingConvention:=CallingConvention.Cdecl)> Public Sub Random_PatternGenerator_Close(Random_PatternGeneratorPtr As IntPtr) End Sub <DllImport(("CPP_Classes.dll"), CallingConvention:=CallingConvention.Cdecl)> Public Function Random_PatternGenerator_Run(Random_PatternGeneratorPtr As IntPtr, rows As Int32, cols As Int32, channels As Int32) As IntPtr End Function End Module Public Class Random_PatternGenerator_CPP : Implements IDisposable Dim Random_PatternGenerator As IntPtr Public Sub New(ocvb As AlgorithmData) Random_PatternGenerator = Random_PatternGenerator_Open() ocvb.desc = "Generate random patterns for use with 'Random Pattern Calibration'" End Sub Public Sub Run(ocvb As AlgorithmData) Dim src = ocvb.color Dim srcData(src.Total * src.ElemSize) As Byte Marshal.Copy(src.Data, srcData, 0, srcData.Length - 1) Dim imagePtr = Random_PatternGenerator_Run(Random_PatternGenerator, src.Rows, src.Cols, src.Channels) If imagePtr <> 0 Then Dim dstData(src.Total - 1) As Byte Marshal.Copy(imagePtr, dstData, 0, dstData.Length) ocvb.result1 = New cv.Mat(src.Rows, src.Cols, cv.MatType.CV_8UC1, dstData) End If End Sub Public Sub Dispose() Implements IDisposable.Dispose Random_PatternGenerator_Close(Random_PatternGenerator) End Sub End Class
Public Enum AthleteStatuses Active Retired End Enum
Imports System.ComponentModel Public Class Student Dim _firstName As String Dim _lastName As String Dim _studentNumber As String Dim _result As Integer Dim _id As Integer Dim _match As Single Dim _matchFirstName As String Dim _matchLastName As String Dim _matchStudentNumber As String Public Sub New() End Sub Public Sub New(firstName As String, lastName As String, studentNumber As String, result As Integer, id As Integer, match As Single, matchFirstName As String, matchLastName As String, matchStudentNumber As String) _firstName = firstName _lastName = lastName _studentNumber = studentNumber _result = result _id = id _match = match _matchFirstName = matchFirstName _matchLastName = matchLastName _matchStudentNumber = matchStudentNumber End Sub Public Sub New(student As Student) _firstName = student.FirstName _lastName = student.LastName _studentNumber = student.StudentNumber _result = student.Result _id = student.Id _match = student.Match _matchFirstName = student.MatchFirstName _matchLastName = MatchLastName _matchStudentNumber = MatchStudentNumber End Sub <DisplayName("First Name")> Public Property FirstName As String Get Return _firstName End Get Set(value As String) _firstName = value End Set End Property <DisplayName("Last Name")> Public Property LastName As String Get Return _lastName End Get Set(value As String) _lastName = value End Set End Property <DisplayName("Student Number")> Public Property StudentNumber As String Get Return _studentNumber End Get Set(value As String) _studentNumber = value End Set End Property Public Property Result As Integer Get Return _result End Get Set(value As Integer) _result = value End Set End Property <DisplayName("Match")> Public Property Match As Single Get Return _match End Get Set(value As Single) _match = value End Set End Property <Browsable(False)> Public Property Id As Integer Get Return _id End Get Set(value As Integer) _id = value End Set End Property <DisplayName("Match First Name")> Public Property MatchFirstName As String Get Return _matchFirstName End Get Set(value As String) _matchFirstName = value End Set End Property <DisplayName("Match Last Name")> Public Property MatchLastName As String Get Return _matchLastName End Get Set(value As String) _matchLastName = value End Set End Property <DisplayName("Match Student Number")> Public Property MatchStudentNumber As String Get Return _matchStudentNumber End Get Set(value As String) _matchStudentNumber = value End Set End Property End Class
<DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public Class StringEqualsAnalyzer Inherits VbCodingStandardsAnalyzerBase Public Const DiagnosticId = DiagnosticIdProvider.StringEquals Private Const Category = "Naming" Private Shared ReadOnly Title As New LocalizableResourceString(NameOf(My.Resources.StringEqualsRuleAnalyzerTitle), My.Resources.ResourceManager, GetType(My.Resources.Resources)) Private Shared ReadOnly MessageFormat As New LocalizableResourceString(NameOf(My.Resources.StringEqualsRuleAnalyzerMessageFormat), My.Resources.ResourceManager, GetType(My.Resources.Resources)) Private Shared ReadOnly Description As New LocalizableResourceString(NameOf(My.Resources.StringEqualsRuleAnalyzerDescription), My.Resources.ResourceManager, GetType(My.Resources.Resources)) Private Shared Rule As New DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Info, isEnabledByDefault:=True, description:=Description) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Rule) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf Analyze, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression) End Sub Protected Overrides Sub CheckSyntax(node As SyntaxNodeAnalysisContext) Dim equalsExpression = DirectCast(node.Node, BinaryExpressionSyntax) Dim leftPart = equalsExpression.Left Dim rightPart = equalsExpression.Right Dim leftTypeInfo = node.SemanticModel.GetTypeInfo(leftPart) Dim rightTypeInfo = node.SemanticModel.GetTypeInfo(rightPart) If (rightTypeInfo.Type Is Nothing OrElse leftTypeInfo.Type Is Nothing) Then Exit Sub If Not (leftTypeInfo.Type.SpecialType = SpecialType.System_String AndAlso rightTypeInfo.Type.SpecialType = SpecialType.System_String) Then Exit Sub Dim diag = Diagnostic.Create(Rule, node.Node.GetLocation(), node.Node.GetText()) node.ReportDiagnostic(diag) End Sub End Class
Public Class WebSiteVersion Private _version As Integer = 0 Private _subVersion As Integer = 0 Private _ptf As Integer = 0 Private _client As String = "" Public Property Version() As Integer Get Return _version End Get Set(ByVal value As Integer) _version = value End Set End Property Public Property SubVersion() As Integer Get Return _subVersion End Get Set(ByVal value As Integer) _subVersion = value End Set End Property Public Property PTF() As Integer Get Return _ptf End Get Set(ByVal value As Integer) _ptf = value End Set End Property Public Property Client() As String Get Return _client End Get Set(ByVal value As String) _client = value End Set End Property End Class
Imports System.Data Public Class SimpleCsvReader Public Shared Function Read(ByVal file As String) As DataTable Dim lines = IO.File.ReadLines(file).GetEnumerator() Dim result As DataTable = New DataTable() result.BeginLoadData() lines.MoveNext() Dim separator = ";"c Dim firstline = lines.Current.Split(separator) If firstline.Length = 1 Then If firstline(0).Contains(",") Then separator = ","c firstline = lines.Current.Split(separator) End If End If For Each s In firstline result.Columns.Add(s, GetType(String)) Next While lines.MoveNext() result.Rows.Add(lines.Current.Split(separator)) End While result.EndLoadData() Return result End Function Public Shared Function Read(ByVal file As String, _ ByVal separator As String, _ ByVal decimalCharacter As Char, _ ByVal colonneNames As String(), _ ByVal colonneTypes As String(), _ ByVal colonneFormats As String()) As DataTable Dim lines = IO.File.ReadLines(file).GetEnumerator() Dim result As DataTable = New DataTable() If decimalCharacter = "."c Then result.Locale = Globalization.CultureInfo.InvariantCulture ElseIf decimalCharacter = ","c Then result.Locale = Globalization.CultureInfo.GetCultureInfo("fr-FR") End If For i = 0 To colonneNames.Length - 1 If colonneTypes(i) = "Texte" Then result.Columns.Add(colonneNames(i), GetType(String)) ElseIf colonneTypes(i) = "Nombre" Then result.Columns.Add(colonneNames(i), GetType(Double)) ElseIf colonneTypes(i) = "Date" Then result.Columns.Add(colonneNames(i), GetType(DateTime)) End If Next lines.MoveNext() Dim firstline = lines.Current.Split(separator).ToList() Dim colonneIndexes(colonneNames.Length) As Integer For i = 0 To colonneNames.Length - 1 Dim colname = colonneNames(i) If colname.StartsWith("""") And colname.Trim().EndsWith("""") Then colname = colname.Trim().Substring(1, colname.Trim().Length - 2) End If colonneIndexes(i) = firstline.IndexOf(colname) If colonneIndexes(i) = -1 Then colonneIndexes(i) = firstline.IndexOf("""" & colname & """") End If Next result.BeginLoadData() While lines.MoveNext() Dim line = lines.Current.Split(separator) Dim nr = result.NewRow() For i = 0 To colonneNames.Length - 1 If colonneTypes(i) = "Texte" Then Dim colvalue = line(colonneIndexes(i)) If colvalue.StartsWith("""") And colvalue.Trim().EndsWith("""") Then colvalue = colvalue.Trim().Substring(1, colvalue.Trim().Length - 2) End If nr(i) = colvalue ElseIf colonneTypes(i) = "Nombre" Then Dim colvalue = line(colonneIndexes(i)) If colvalue.StartsWith("""") And colvalue.Trim().EndsWith("""") Then colvalue = colvalue.Trim().Substring(1, colvalue.Trim().Length - 2) End If If colvalue <> "" Then If decimalCharacter = "."c Then Dim doublevalue As Double If Double.TryParse(colvalue, Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, doublevalue) Then nr(i) = doublevalue Else If Double.TryParse(colvalue, Globalization.NumberStyles.Any, Globalization.CultureInfo.GetCultureInfo("fr-FR"), doublevalue) Then nr(i) = doublevalue Else nr(i) = DBNull.Value End If End If ElseIf decimalCharacter = ","c Then Dim doublevalue As Double If Double.TryParse(colvalue, Globalization.NumberStyles.Any, Globalization.CultureInfo.GetCultureInfo("fr-FR"), doublevalue) Then nr(i) = doublevalue Else If Double.TryParse(colvalue, Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, doublevalue) Then nr(i) = doublevalue Else nr(i) = DBNull.Value End If End If End If Else nr(i) = DBNull.Value ' 0.0 End If ElseIf colonneTypes(i) = "Date" Then 'result.Columns.Add(colonneNames(i), GetType(DateTime)) End If Next result.Rows.Add(nr) End While result.EndLoadData() Return result End Function Public Shared Sub ReadToDB(ByVal file As String, _ ByVal separator As String, _ ByVal decimalCharacter As Char, _ ByVal colonneNames As String(), _ ByVal colonneTypes As String(), _ ByVal colonneFormats As String(), _ ByVal tablename As String, _ ByVal connectionstring As String) 'Dim lines = IO.File.ReadLines(file).GetEnumerator() 'lines.MoveNext() 'Dim firstline = lines.Current.Split(separator).ToList() 'Dim colonneIndexes(colonneNames.Length) As Integer 'For i = 0 To colonneNames.Length - 1 ' colonneIndexes(i) = firstline.IndexOf(colonneNames(i)) 'Next 'Dim con = New SQLite.SQLiteConnection(connectionstring) 'Dim inserttextbase = "INSERT INTO " & tablename.ToUpper() & "(" & String.Join(",", colonneNames) & ") VALUES(" 'Dim cmd = New SQLite.SQLiteCommand() 'cmd.Connection = con 'con.Open() 'Dim trans = con.BeginTransaction() 'While lines.MoveNext() ' Dim line = lines.Current.Split(separator) ' Dim inserttext = inserttextbase ' For i = 0 To colonneNames.Length - 1 ' If colonneTypes(i) = "Texte" Then ' inserttext = inserttext & "'" & line(colonneIndexes(i)) & "'" ' ElseIf colonneTypes(i) = "Nombre" Then ' If line(colonneIndexes(i)) <> "" Then ' If decimalCharacter = "."c Then ' ' nr(i) = Double.Parse(line(colonneIndexes(i)), Globalization.CultureInfo.InvariantCulture) ' inserttext = inserttext & line(colonneIndexes(i)) ' ElseIf decimalCharacter = ","c Then ' inserttext = inserttext & Double.Parse(line(colonneIndexes(i)), Globalization.CultureInfo.GetCultureInfo("fr-FR")).ToString(Globalization.CultureInfo.InvariantCulture) ' End If ' Else ' inserttext = inserttext & "0.0" ' End If ' ElseIf colonneTypes(i) = "Date" Then ' 'Date.Parse(,,'result.Columns.Add(colonneNames(i), GetType(DateTime)) ' End If ' If i = colonneNames.Length - 1 Then ' inserttext = inserttext & ")" ' Else ' inserttext = inserttext & "," ' End If ' Next ' cmd.CommandText = inserttext ' cmd.ExecuteNonQuery() 'End While 'trans.Commit() 'con.Close() 'con.Dispose() End Sub Public Shared Function ReadFirstLine(ByVal file As String) As List(Of String) Dim lines = IO.File.ReadLines(file).GetEnumerator() lines.MoveNext() Dim separator = ";"c Dim linesCurrent = lines.Current Dim firstline = lines.Current.Split(separator) If firstline.Length = 1 Then If firstline(0).Contains(",") Then separator = ","c firstline = lines.Current.Split(separator) End If End If lines.Dispose() lines = Nothing Dim result = New List(Of String)() result.Add(separator) result.Add(linesCurrent) For Each l In firstline If l.Trim().StartsWith("""") And l.Trim().EndsWith("""") Then result.Add(l.Trim().Substring(1, l.Trim().Length - 2)) Else result.Add(l.Trim()) End If Next Return result End Function 'Public Shared Function ReadLineCount(ByVal file As String) As Integer ' ' Return IO.File.ReadLines(file).Count() 'End Function End Class
Imports System.ComponentModel Imports System.Linq Imports FrontWork Public Class EditableDataViewModel Implements IConfigurable Protected ViewOperator As New EditableDataViewOperator Protected _Configuration As Configuration Protected _Mode As String = "default" Protected _Model As IModel Public Overridable Property Configuration As Configuration Implements IConfigurable.Configuration Get Return Me._Configuration End Get Set(value As Configuration) Dim oldFields As Field() = {} If Me._Configuration IsNot Nothing Then oldFields = Me._Configuration.GetFields(Me.Mode) RemoveHandler Me._Configuration.Refreshed, AddressOf Me.ConfigurationRefreshedEvent RemoveHandler Me._Configuration.FieldAdded, AddressOf Me.ConfigurationFieldAddedEvent RemoveHandler Me._Configuration.FieldUpdated, AddressOf Me.ConfigurationFieldUpdatedEvent RemoveHandler Me._Configuration.FieldRemoved, AddressOf Me.ConfigurationFieldRemovedEvent End If Me._Configuration = value Dim newFields As Field() = {} If Me._Configuration IsNot Nothing Then newFields = Me._Configuration.GetFields(Me.Mode) AddHandler Me._Configuration.Refreshed, AddressOf Me.ConfigurationRefreshedEvent AddHandler Me._Configuration.FieldAdded, AddressOf Me.ConfigurationFieldAddedEvent AddHandler Me._Configuration.FieldUpdated, AddressOf Me.ConfigurationFieldUpdatedEvent AddHandler Me._Configuration.FieldRemoved, AddressOf Me.ConfigurationFieldRemovedEvent Call Me.ConfigurationRefreshedEvent(Me, Nothing) End If End Set End Property Private Sub ConfigurationFieldRemovedEvent(sender As Object, e As ConfigurationFieldRemovedEventArgs) Dim oldColumns = Me.ViewOperator.GetColumns Dim allFields = Me.Configuration.GetFields(Me.Mode) Dim visibleFields = (From f In allFields Where f.Visible Select f).ToArray Dim newColumns = Me.FieldConfigurationsToViewColumn(visibleFields) Call Me.RefreshViewSchema(oldColumns, newColumns) If Me.Model IsNot Nothing AndAlso Me.View IsNot Nothing AndAlso Me.View.GetRowCount > 0 Then Call Me.PushModelRow(Util.Range(0, Me.ViewOperator.GetRowCount)) End If End Sub Private Sub ConfigurationFieldUpdatedEvent(sender As Object, e As ConfigurationFieldUpdatedEventArgs) Dim oldColumns = Me.ViewOperator.GetColumns Dim allFields = Me.Configuration.GetFields(Me.Mode) Dim visibleFields = (From f In allFields Where f.Visible Select f).ToArray Dim newColumns = Me.FieldConfigurationsToViewColumn(visibleFields) Call Me.RefreshViewSchema(oldColumns, newColumns) If Me.Model IsNot Nothing AndAlso Me.View IsNot Nothing AndAlso Me.View.GetRowCount > 0 Then Call Me.PushModelRow(Util.Range(0, Me.ViewOperator.GetRowCount)) End If End Sub Private Sub ConfigurationFieldAddedEvent(sender As Object, e As ConfigurationFieldAddedEventArgs) Dim oldColumns = Me.ViewOperator.GetColumns Dim allFields = Me.Configuration.GetFields(Me.Mode) Dim visibleFields = (From f In allFields Where f.Visible Select f).ToArray Dim newColumns = Me.FieldConfigurationsToViewColumn(visibleFields) Call Me.RefreshViewSchema(oldColumns, newColumns) If Me.Model IsNot Nothing AndAlso Me.View IsNot Nothing AndAlso Me.View.GetRowCount > 0 Then Call Me.PushModelRow(Util.Range(0, Me.ViewOperator.GetRowCount)) End If End Sub Protected Overridable Sub ConfigurationRefreshedEvent(sender As Object, e As ConfigurationRefreshedEventArgs) If Me.Configuration Is Nothing Then Throw New FrontWorkException($"Configuration not set for view!") End If Dim oldColumns = Me.ViewOperator.GetColumns Dim allFields = Me.Configuration.GetFields(Me.Mode) Dim visibleFields = (From f In allFields Where f.Visible Select f).ToArray Dim newColumns = Me.FieldConfigurationsToViewColumn(visibleFields) Call Me.RefreshViewSchema(oldColumns, newColumns) If Me.Model IsNot Nothing AndAlso Me.View IsNot Nothing AndAlso Me.View.GetRowCount > 0 Then Call Me.PushModelRow(Util.Range(0, Me.ViewOperator.GetRowCount)) End If End Sub Public Overridable Property Mode As String Implements IConfigurable.Mode Get Return Me._Mode End Get Set(value As String) If Me._Mode IsNot Nothing AndAlso Me._Mode.Equals(value, StringComparison.OrdinalIgnoreCase) Then Return End If Me._Mode = value Call Me.ConfigurationRefreshedEvent(Me, Nothing) End Set End Property Public Sub New() End Sub Public Sub New(view As IEditableDataView) Me.View = view End Sub Public Sub New(model As IModel) Me.Model = model End Sub Public Sub New(model As IModel, view As IEditableDataView) Me.Model = model Me.View = view End Sub ''' <summary> ''' Model对象,用来存取数据 ''' </summary> ''' <returns>Model对象</returns> Public Overridable Property Model As IModel Get Return Me._Model End Get Set(value As IModel) If value Is Me._Model Then Return If Me._Model IsNot Nothing Then Call Me.UnbindModel() End If Me._Model = value If Me._Model IsNot Nothing Then Call Me.BindModel() End If End Set End Property ''' <summary> ''' ViewOperationsWrapper对象,用来代理View ''' </summary> ''' <returns>ViewOperationsWrapper对象</returns> Public Overridable Property View As IEditableDataView Get Return Me.ViewOperator.View End Get Set(value As IEditableDataView) If value Is Me.ViewOperator.View Then Return If Me.ViewOperator.View IsNot Nothing Then Call Me.UnbindView() End If Me.ViewOperator.View = value If Me.ViewOperator IsNot Nothing Then Call Me.BindView() End If End Set End Property ''' <summary> ''' 自动比对新视图与原视图的差别,并命令视图更新。 ''' 采用各字段位置不变,新视图字段改变更新,字段增加则增加,字段减少则删除的策略 ''' </summary> Protected Overridable Sub RefreshViewSchema(oldColumns As ViewColumn(), newColumns As ViewColumn()) If oldColumns.Length = 0 AndAlso newColumns.Length = 0 Then Return Dim updateColumns As New List(Of KeyValuePair(Of Integer, ViewColumn)) Dim addColumns As New List(Of ViewColumn) Dim removeColumns As New List(Of Integer) For i = 0 To Math.Max(oldColumns.Length, newColumns.Length) - 1 If oldColumns.Length > i AndAlso newColumns.Length > i Then If oldColumns(i) = newColumns(i) Then Continue For updateColumns.Add(New KeyValuePair(Of Integer, ViewColumn)(i, newColumns(i))) ElseIf oldColumns.Length > i AndAlso newColumns.Length <= i Then removeColumns.Add(i) ElseIf oldColumns.Length <= i AndAlso newColumns.Length > i Then addColumns.Add(newColumns(i)) Else Throw New FrontWorkException("Unexpected exception") End If Next If updateColumns.Count > 0 Then Call Me.ViewOperator.UpdateColumns((From kv In updateColumns Select kv.Key).ToArray, (From kv In updateColumns Select kv.Value).ToArray) End If If addColumns.Count > 0 Then Call Me.ViewOperator.AddColumns(addColumns.ToArray) End If If removeColumns.Count > 0 Then Call Me.ViewOperator.RemoveColumns(removeColumns.ToArray) End If End Sub Protected Overridable Function FieldConfigurationsToViewColumn(fields As Field()) As ViewColumn() Dim context = New ModelViewInvocationContext(Me.Model, Me.View) Dim result(fields.Length - 1) As ViewColumn For i = 0 To fields.Length - 1 Dim curField = fields(i) Dim newViewColumn = New ViewColumn(context, curField.PlaceHolder, curField.Values, curField.Name, curField.DisplayName, curField.Type.GetValue, curField.Editable) result(i) = newViewColumn Next Return result End Function ''' <summary> ''' 绑定新的Model,将本View的各种事件绑定到Model上以实现数据变化的同步 ''' </summary> Protected Overridable Sub BindModel() AddHandler Me.Model.RowUpdated, AddressOf Me.ModelRowUpdatedEvent AddHandler Me.Model.RowAdded, AddressOf Me.ModelRowAddedEvent AddHandler Me.Model.RowRemoved, AddressOf Me.ModelRowRemovedEvent AddHandler Me.Model.CellUpdated, AddressOf Me.ModelCellUpdatedEvent AddHandler Me.Model.CellStateChanged, AddressOf Me.ModelCellStateChanged AddHandler Me.Model.SelectionRangeChanged, AddressOf Me.ModelSelectionRangeChangedEvent AddHandler Me.Model.RowStateChanged, AddressOf Me.ModelRowStateChanged AddHandler Me.Model.Refreshed, AddressOf Me.ModelRefreshedEvent Call Me.ModelRefreshedEvent(Me, Nothing) End Sub ''' <summary> ''' 解绑Model,取消本视图绑定的所有事件 ''' </summary> Protected Overridable Sub UnbindModel() RemoveHandler Me.Model.CellUpdated, AddressOf Me.ModelCellUpdatedEvent RemoveHandler Me.Model.CellStateChanged, AddressOf Me.ModelCellStateChanged RemoveHandler Me.Model.RowUpdated, AddressOf Me.ModelRowUpdatedEvent RemoveHandler Me.Model.RowAdded, AddressOf Me.ModelRowAddedEvent RemoveHandler Me.Model.RowRemoved, AddressOf Me.ModelRowRemovedEvent RemoveHandler Me.Model.SelectionRangeChanged, AddressOf Me.ModelSelectionRangeChangedEvent RemoveHandler Me.Model.RowStateChanged, AddressOf Me.ModelRowStateChanged RemoveHandler Me.Model.Refreshed, AddressOf Me.ModelRefreshedEvent End Sub Private Sub ViewEditEndedEvent(sender As Object, e As ViewEditEndedEventArgs) Dim context As New ModelViewEditInvocationContext(Me.Model, Me.View, e.Row, e.ColumnName, e.CellData) Dim fieldName = e.ColumnName Dim curField = Me.Configuration.GetField(Me.Mode, fieldName) If curField.EditEnded IsNot Nothing Then curField.EditEnded.Invoke(context) End If End Sub Private Sub ViewContentChangedEvent(sender As Object, e As ViewContentChangedEventArgs) Dim context As New ModelViewEditInvocationContext(Me.Model, Me.View, e.Row, e.ColumnName, e.CellData) Dim fieldName = e.ColumnName Dim curField = Me.Configuration.GetField(Me.Mode, fieldName) If curField.ContentChanged IsNot Nothing Then curField.ContentChanged.Invoke(context) End If End Sub Protected Overridable Sub BindView() AddHandler Me.ViewOperator.CellUpdated, AddressOf Me.ViewCellUpdatedEvent AddHandler Me.ViewOperator.RowUpdated, AddressOf Me.ViewRowUpdatedEvent AddHandler Me.ViewOperator.RowAdded, AddressOf Me.ViewRowAddedEvent AddHandler Me.ViewOperator.RowRemoved, AddressOf Me.ViewRowRemovedEvent AddHandler Me.ViewOperator.SelectionRangeChanged, AddressOf Me.ViewSelectionRangeChangedEvent AddHandler Me.View.ContentChanged, AddressOf Me.ViewContentChangedEvent AddHandler Me.View.EditEnded, AddressOf Me.ViewEditEndedEvent If Me.Configuration IsNot Nothing Then Call Me.ConfigurationRefreshedEvent(Me, Nothing) Call Me.ModelRefreshedEvent(Me, Nothing) End If End Sub Protected Overridable Sub ViewSelectionRangeChangedEvent(sender As Object, e As ViewSelectionRangeChangedEventArgs) RemoveHandler Me.Model.SelectionRangeChanged, AddressOf Me.ModelSelectionRangeChangedEvent Me.Model.AllSelectionRanges = e.NewSelectionRanges AddHandler Me.Model.SelectionRangeChanged, AddressOf Me.ModelSelectionRangeChangedEvent End Sub Protected Overridable Sub ViewRowRemovedEvent(sender As Object, e As ViewRowRemovedEventArgs) Dim rows = (From r In e.Rows Select r.Row).ToArray Try RemoveHandler Me.Model.RowRemoved, AddressOf Me.ModelRowRemovedEvent Call Me.Model.RemoveRows(rows) AddHandler Me.Model.RowRemoved, AddressOf Me.ModelRowRemovedEvent Catch ex As FrontWorkException Call MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning) End Try End Sub Protected Overridable Sub ViewRowAddedEvent(sender As Object, e As ViewRowAddedEventArgs) Dim rows = (From r In e.Rows Select r.Row).ToArray Dim data = (From r In e.Rows Select r.RowData).ToArray For i = 0 To rows.Length - 1 data(i) = Me.GetBackwardMappedRowData(data(i), rows(i)) Next Try RemoveHandler Me.Model.RowAdded, AddressOf Me.ModelRowAddedEvent Call Me.Model.InsertRows(rows, data) AddHandler Me.Model.RowAdded, AddressOf Me.ModelRowAddedEvent Catch ex As FrontWorkException Call MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning) End Try End Sub Protected Overridable Sub ViewRowUpdatedEvent(sender As Object, e As ViewRowUpdatedEventArgs) Throw New NotImplementedException("Don't use this event! It will be soon deleted.") 'Dim rows = (From r In e.Rows Select r.Row).ToArray 'Dim data = (From r In e.Rows Select r.RowData).ToArray 'Dim fields = Me.Configuration.GetFields(Me.Mode) 'Dim uneditableFieldNames = (From f In fields ' Where f.Editable.GetValue = False ' Select f.Name.GetValue).ToArray 'For i = 0 To rows.Length - 1 ' Dim keys = data(i).Keys.ToArray ' For Each key In keys ' If uneditableFieldNames.Contains(key) Then ' data(i).Remove(key) ' End If ' Next ' data(i) = Me.GetBackwardMappedRowData(data(i), rows(i)) 'Next 'Try ' RemoveHandler Me.Model.RowUpdated, AddressOf Me.ModelRowUpdatedEvent ' Call Me.Model.UpdateRows(rows, data) ' AddHandler Me.Model.RowUpdated, AddressOf Me.ModelRowUpdatedEvent 'Catch ex As FrontWorkException ' Call MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning) 'End Try End Sub Protected Overridable Sub ViewCellUpdatedEvent(sender As Object, e As ViewCellUpdatedEventArgs) '删除所有不能编辑的单元格 Dim cellInfos As New List(Of ViewCellInfo)(e.Cells) cellInfos.RemoveAll( Function(cellInfo) Return Not Me.Configuration.GetField(Me.Mode, cellInfo.ColumnName).Editable.GetValue End Function) Dim columns = cellInfos.Select(Function(cellInfo) Return Me.Configuration.GetField(Me.Mode, cellInfo.ColumnName) End Function) Dim validationError As New List(Of CellPositionValidationStatePair) Dim updateCell As New List(Of ViewCellInfo) For i = 0 To cellInfos.Count - 1 Dim column = columns(i) Dim cellInfo = cellInfos(i) Dim rawData = cellInfo.CellData Try Dim convertedData As Object convertedData = Util.ChangeType(rawData, column.Type.GetValue) Dim mappedData = Me.GetBackwardMappedCellData(convertedData, columns(i).Name, cellInfo.Row) updateCell.Add(New ViewCellInfo(cellInfo.Row, cellInfo.ColumnName, mappedData)) Catch ex As Exception validationError.Add(New CellPositionValidationStatePair( cellInfo.Row, cellInfo.ColumnName, New ValidationState(ValidationStateType.ERROR, $"""{rawData}""不是有效的格式!")) ) End Try Next Try RemoveHandler Me.Model.CellUpdated, AddressOf Me.ModelCellUpdatedEvent Call Me.Model.UpdateCells(updateCell.Select( Function(item) item.Row).ToArray, updateCell.Select(Function(item) item.ColumnName).ToArray, updateCell.Select(Function(item) item.CellData).ToArray) AddHandler Me.Model.CellUpdated, AddressOf Me.ModelCellUpdatedEvent Catch ex As FrontWorkException Call MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning) End Try Call Me.Model.UpdateCellValidationStates( validationError.Select(Function(item) item.CellPosition.Row).ToArray, validationError.Select(Function(item) item.CellPosition.Field).ToArray, validationError.Select(Function(item) item.State).ToArray ) End Sub Protected Overridable Sub UnbindView() RemoveHandler Me.ViewOperator.CellUpdated, AddressOf Me.ViewCellUpdatedEvent RemoveHandler Me.ViewOperator.RowUpdated, AddressOf Me.ViewRowUpdatedEvent RemoveHandler Me.ViewOperator.RowAdded, AddressOf Me.ViewRowAddedEvent RemoveHandler Me.ViewOperator.RowRemoved, AddressOf Me.ViewRowRemovedEvent RemoveHandler Me.ViewOperator.SelectionRangeChanged, AddressOf Me.ViewSelectionRangeChangedEvent RemoveHandler Me.View.ContentChanged, AddressOf Me.ViewContentChangedEvent RemoveHandler Me.View.EditEnded, AddressOf Me.ViewEditEndedEvent End Sub Protected Overridable Sub ModelSelectionRangeChangedEvent(sender As Object, e As ModelSelectionRangeChangedEventArgs) RemoveHandler Me.ViewOperator.SelectionRangeChanged, AddressOf Me.ViewSelectionRangeChangedEvent Me.ViewOperator.SetSelectionRanges(e.NewSelectionRange) AddHandler Me.ViewOperator.SelectionRangeChanged, AddressOf Me.ViewSelectionRangeChangedEvent End Sub Protected Overridable Sub ModelRowAddedEvent(sender As Object, e As ModelRowAddedEventArgs) Dim indexes = (From r In e.AddedRows Select r.Row).ToArray Dim data = (From r In e.AddedRows Select r.RowData).ToArray For i = 0 To data.Length - 1 If data(i) Is Nothing Then data(i) = New Dictionary(Of String, Object) Else data(i) = Me.GetForwardMappedRowData(data(i), indexes(i)) End If Next RemoveHandler Me.ViewOperator.RowAdded, AddressOf Me.ViewRowAddedEvent Call Me.ViewOperator.InsertRows(indexes, data) AddHandler Me.ViewOperator.RowAdded, AddressOf Me.ViewRowAddedEvent End Sub Protected Overridable Sub ModelRowRemovedEvent(sender As Object, e As ModelRowRemovedEventArgs) Dim indexes = (From r In e.RemovedRows Select r.Row).ToArray RemoveHandler Me.ViewOperator.RowRemoved, AddressOf Me.ViewRowRemovedEvent Call Me.ViewOperator.RemoveRows(indexes) AddHandler Me.ViewOperator.RowRemoved, AddressOf Me.ViewRowRemovedEvent End Sub Private Sub ModelRowStateChanged(sender As Object, e As ModelRowStateChangedEventArgs) Dim rows = (From r In e.StateUpdatedRows Select r.Row).ToArray Dim states = (From r In e.StateUpdatedRows Select New ViewRowState(r.State)).ToArray Call Me.ViewOperator.UpdateRowStates(rows, states) End Sub Private Sub ModelCellStateChanged(sender As Object, e As ModelCellStateChangedEventArgs) Dim rows = (From c In e.StateUpdatedCells Select c.Row).ToArray Dim fields = (From c In e.StateUpdatedCells Select c.FieldName).ToArray Dim states = (From c In e.StateUpdatedCells Select New ViewCellState(c.State)).ToArray Call Me.ViewOperator.UpdateCellStates(rows, fields, states) End Sub Protected Overridable Sub ModelCellUpdatedEvent(sender As Object, e As ModelCellUpdatedEventArgs) If Me.Configuration Is Nothing Then Throw New FrontWorkException("Configuration is not setted") End If If Me.ViewOperator Is Nothing Then Throw New FrontWorkException("View is not set") End If Dim modelCellInfos = (From c In e.UpdatedCells Select CType(c.Clone, ModelCellInfo)).ToList modelCellInfos.RemoveAll(Function(cellInfo) Dim curField = Me.Configuration.GetField(Me.Mode, cellInfo.FieldName) Return Not curField.Visible.GetValue End Function) For i = 0 To modelCellInfos.Count - 1 Dim curCellInfo = modelCellInfos(i) Dim colName = curCellInfo.FieldName Dim row = curCellInfo.Row curCellInfo.CellData = Me.GetForwardMappedCellData(curCellInfo.CellData, colName, row) Next RemoveHandler Me.ViewOperator.CellUpdated, AddressOf Me.ViewCellUpdatedEvent Call Me.ViewOperator.UpdateCells(modelCellInfos.Select(Function(cellInfo) cellInfo.Row).ToArray, modelCellInfos.Select(Function(cellInfo) cellInfo.FieldName).ToArray, modelCellInfos.Select(Function(cellInfo) cellInfo.CellData).ToArray) AddHandler Me.ViewOperator.CellUpdated, AddressOf Me.ViewCellUpdatedEvent End Sub Protected Overridable Sub ModelRefreshedEvent(sender As Object, e As ModelRefreshedEventArgs) Dim data = Me.Model.GetRows(Util.Range(0, Me.Model.GetRowCount)) Dim newRowCount = data.Length Dim oriViewRowCount = Me.ViewOperator.GetRowCount For i = 0 To newRowCount - 1 data(i) = Me.GetForwardMappedRowData(data(i), i) Next RemoveHandler Me.ViewOperator.RowAdded, AddressOf Me.ViewRowAddedEvent RemoveHandler Me.ViewOperator.RowUpdated, AddressOf ViewRowUpdatedEvent RemoveHandler Me.ViewOperator.RowRemoved, AddressOf Me.ViewRowRemovedEvent RemoveHandler Me.ViewOperator.SelectionRangeChanged, AddressOf Me.ViewSelectionRangeChangedEvent RemoveHandler Me.ViewOperator.RowStateChanged, AddressOf Me.ViewRowStateChangedEvent If newRowCount < oriViewRowCount Then '原来视图行数大于新的行数,删除部分行 Call Me.ViewOperator.RemoveRows(Util.Range(newRowCount, oriViewRowCount)) ElseIf newRowCount > oriViewRowCount Then '原来视图行数小于新的行数,则增加部分行 Dim addData(newRowCount - oriViewRowCount - 1) As IDictionary(Of String, Object) For i = 0 To addData.Length - 1 addData(i) = data(oriViewRowCount + i) Next Call Me.ViewOperator.AddRows(addData) End If Dim commonRowCount = System.Math.Min(newRowCount, oriViewRowCount) If commonRowCount > 0 Then Dim updateData(commonRowCount - 1) As IDictionary(Of String, Object) For i = 0 To updateData.Length - 1 updateData(i) = data(i) Next Call Me.ViewOperator.UpdateRows(Util.Range(0, updateData.Length), updateData) End If Call Me.ViewOperator.SetSelectionRanges(Me.Model.AllSelectionRanges) '刷新行状态 Dim rowNums = Util.Range(0, newRowCount) Dim modelRowStates = Me.Model.GetRowStates(rowNums) Dim viewRowStates = (From s In modelRowStates Select New ViewRowState(s)).ToArray Call Me.ViewOperator.UpdateRowStates(rowNums, viewRowStates) AddHandler Me.ViewOperator.RowAdded, AddressOf Me.ViewRowAddedEvent AddHandler Me.ViewOperator.RowUpdated, AddressOf ViewRowUpdatedEvent AddHandler Me.ViewOperator.RowRemoved, AddressOf Me.ViewRowRemovedEvent AddHandler Me.ViewOperator.SelectionRangeChanged, AddressOf Me.ViewSelectionRangeChangedEvent AddHandler Me.ViewOperator.RowStateChanged, AddressOf Me.ViewRowStateChangedEvent End Sub Private Sub ViewRowStateChangedEvent(sender As Object, e As ViewRowStateChangedEventArgs) RemoveHandler Me.Model.RowStateChanged, AddressOf Me.ModelRowStateChanged Dim viewRowInfos = e.StateChangedRows Dim modelRowStates(viewRowInfos.Length - 1) As ModelRowState Dim rows(viewRowInfos.Length - 1) As Integer For i = 0 To modelRowStates.Length - 1 Dim viewRowInfo = viewRowInfos(i) modelRowStates(i) = New ModelRowState(viewRowInfo.RowState) rows(i) = viewRowInfo.Row Next Call Me.Model.UpdateRowStates(rows, modelRowStates) AddHandler Me.Model.RowStateChanged, AddressOf Me.ModelRowStateChanged End Sub Protected Overridable Sub ModelRowUpdatedEvent(sender As Object, e As ModelRowUpdatedEventArgs) Dim rows = (From r In e.UpdatedRows Select r.Row).ToArray Call Me.PushModelRow(rows) End Sub Protected Overridable Sub PushModelRow(rows As Integer()) If Me.Model Is Nothing Then Return Dim data = Me.Model.GetRows(rows) '遍历传入数据 For i = 0 To rows.Length - 1 Dim curRowNum = rows(i) data(i) = Me.GetForwardMappedRowData(data(i), curRowNum) Next RemoveHandler Me.ViewOperator.RowUpdated, AddressOf Me.ViewRowUpdatedEvent Call Me.ViewOperator.UpdateRows(rows, data) AddHandler Me.ViewOperator.RowUpdated, AddressOf Me.ViewRowUpdatedEvent End Sub Protected Overridable Function GetForwardMappedRowData(rowData As IDictionary(Of String, Object), rowNum As Integer) As IDictionary(Of String, Object) Dim result As New Dictionary(Of String, Object) For Each kv In rowData Dim key = kv.Key result.Add(key, Me.GetForwardMappedCellData(rowData(key), key, rowNum)) Next Return result End Function Protected Overridable Function GetForwardMappedCellData(cellData As Object, fieldName As String, rowNum As Integer) As Object Dim context As New ModelViewEditInvocationContext(Me.Model, Me.View, rowNum, fieldName, cellData) Dim fields = Me.Configuration.GetFields(Me.Mode) Dim curField = (From f In fields Where f.Name.GetValue?.ToString.Equals(fieldName, StringComparison.OrdinalIgnoreCase) Select f).FirstOrDefault Dim result = Nothing If curField Is Nothing Then result = cellData ElseIf curField.ForwardMapper IsNot Nothing Then result = curField.ForwardMapper.Invoke(context) Else result = cellData End If Return result End Function Protected Overridable Function GetBackwardMappedRowData(rowData As IDictionary(Of String, Object), rowNum As Integer) As IDictionary(Of String, Object) Dim keys = rowData.Keys.ToArray For Each key In keys rowData(key) = Me.GetBackwardMappedCellData(rowData(key), key, rowNum) Next Return rowData End Function Protected Overridable Function GetBackwardMappedCellData(cellData As Object, fieldName As String, rowNum As Integer) As Object Dim context As New ModelViewEditInvocationContext(Me.Model, Me.View, rowNum, fieldName, cellData) Dim fields = Me.Configuration.GetFields(Me.Mode) Dim curField = (From f In fields Where f.Name.GetValue?.ToString.Equals(fieldName, StringComparison.OrdinalIgnoreCase) Select f).First If curField Is Nothing Then Throw New FrontWorkException($"Field ""{fieldName}"" not found in Configuration!") End If Dim result = Nothing If curField.BackwardMapper IsNot Nothing Then result = curField.BackwardMapper.Invoke(context) Else result = cellData End If Return result End Function End Class
Module Module1 Sub printUsage() Const version = "0.2.2" Console.WriteLine("wia-cmd-scanner (version " & version & ") ") Console.WriteLine("License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> ") Console.WriteLine(" ") Console.WriteLine("Command-line scanner utility for WIA-compatible scanners ") Console.WriteLine("Online help, docs & bug reports: <https://github.com/nagimov/wia-cmd-scanner/> ") Console.WriteLine(" ") Console.WriteLine("Usage: wia-cmd-scanner [OPTIONS]... ") Console.WriteLine(" ") Console.WriteLine("All arguments are mandatory. Arguments must be ordered as follows: ") Console.WriteLine(" ") Console.WriteLine(" /w WIDTH width of the scan area, mm ") Console.WriteLine(" /h HEIGHT height of the scan area, mm ") Console.WriteLine(" /dpi RESOLUTION scan resolution, dots per inch ") Console.WriteLine(" /color {RGB,GRAY,BW} scan color mode ") Console.WriteLine(" /format {BMP,PNG,GIF,JPG,TIF} output image format ") Console.WriteLine(" /output FILEPATH path to output image file ") Console.WriteLine(" ") Console.WriteLine("Use /w 0 and /h 0 for scanner-defined values, e.g. for receipt scanners ") Console.WriteLine(" ") Console.WriteLine("e.g. for A4 size black and white scan at 300 dpi: ") Console.WriteLine("wia-cmd-scanner /w 210 /h 297 /dpi 300 /color BW /format PNG /output .\scan.png") End Sub Sub printExceptionMessage(ex As Exception) Dim exceptionDesc As New Dictionary(Of String, String)() ' see https://docs.microsoft.com/en-us/windows/desktop/wia/-wia-error-codes exceptionDesc.Add("0x80210006", "Scanner is busy") exceptionDesc.Add("0x80210016", "Cover is open") exceptionDesc.Add("0x8021000A", "Can't communicate with scanner") exceptionDesc.Add("0x8021000D", "Scanner is locked") exceptionDesc.Add("0x8021000E", "Exception in driver occured") exceptionDesc.Add("0x80210001", "Unknown error occured") exceptionDesc.Add("0x8021000C", "Incorrect scanner setting") exceptionDesc.Add("0x8021000F", "Unsupported scanner command") exceptionDesc.Add("0x80210009", "Scanner is deleted and no longer available") exceptionDesc.Add("0x80210017", "Scanner lamp is off") exceptionDesc.Add("0x80210021", "Maximum endorser value reached") exceptionDesc.Add("0x80210020", "Multiple page feed error") exceptionDesc.Add("0x80210005", "Scanner is offline") exceptionDesc.Add("0x80210003", "No document in document feeder") exceptionDesc.Add("0x80210002", "Paper jam in document feeder") exceptionDesc.Add("0x80210004", "Unspecified error with document feeder") exceptionDesc.Add("0x80210007", "Scanner is warming up") exceptionDesc.Add("0x80210008", "Unknown problem with scanner") exceptionDesc.Add("0x80210015", "No scanners found") For Each pair As KeyValuePair(Of String, String) In exceptionDesc If ex.Message.Contains(pair.Key) Then Console.WriteLine(pair.Value) Exit Sub End If Next Console.WriteLine("Exception occured: " & ex.Message) End Sub Sub Main() ' parse command line arguments Dim clArgs() As String = Environment.GetCommandLineArgs() If (clArgs.Length < 8) Then printUsage() Exit Sub End If If Not (clArgs(1) = "/w" And clArgs(3) = "/h" And clArgs(5) = "/dpi" And clArgs(7) = "/color" And clArgs(9) = "/format" And clArgs(11) = "/output") Then printUsage() Exit Sub End If ' receive cmd line parameters Dim w As Double = clArgs(2) Dim h As Double = clArgs(4) Dim dpi As Integer = clArgs(6) Dim color As String = clArgs(8) Dim format As String = clArgs(10) Dim output As String = clArgs(12) If Not ((w = 0 And h = 0) Or (w > 0 And h > 0)) Then printUsage() Exit Sub End If Dim colorcode As Integer Dim depth As Integer If color = "RGB" Then colorcode = 1 depth = 24 ElseIf color = "GRAY" Then colorcode = 2 depth = 8 ElseIf color = "BW" Then colorcode = 4 depth = 1 Else printUsage() Exit Sub End If Dim fileformat As String Const wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}" Const wiaFormatPNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}" Const wiaFormatGIF = "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}" Const wiaFormatJPG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}" Const wiaFormatTIF = "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}" ' these WIA properties are mandatory to set, quit if can't set any of them Dim mandatoryToSetWIA = New String() {"WIA_IPS_CUR_INTENT", _ "WIA_IPS_XRES", _ "WIA_IPS_YRES", _ "WIA_IPS_XEXTENT", _ "WIA_IPS_YEXTENT", _ "WIA_IPS_XPOS", _ "WIA_IPS_YPOS"} ' if can't set any of these WIA properties, do not ask user to try to change scan parameters Dim unknownErrorIfUnsetWIA = New String() {"WIA_IPS_XPOS", "WIA_IPS_YPOS"} If format = "BMP" Then fileformat = wiaFormatBMP ElseIf format = "PNG" Then fileformat = wiaFormatPNG ElseIf format = "GIF" Then fileformat = wiaFormatGIF ElseIf format = "JPG" Then fileformat = wiaFormatJPG ElseIf format = "TIF" Then fileformat = wiaFormatTIF Else printUsage() Exit Sub End If If System.IO.File.Exists(output) = True Then Console.WriteLine("Destination file exists!") Exit Sub End If ' scan the image Try Dim DeviceManager = CreateObject("WIA.DeviceManager") ' create device manager If DeviceManager.DeviceInfos.Count < 1 Then Console.WriteLine("No compatible scanners found") Exit Sub End If For i = 1 To DeviceManager.DeviceInfos.Count ' check all available devices If DeviceManager.DeviceInfos(i).Type = 1 Then ' find first device of type "scanner" (exclude webcams, etc.) Dim TimeStart = DateAndTime.Second(Now) + (DateAndTime.Minute(Now) * 60) + (DateAndTime.Hour(Now) * 3600) Dim Scanner As WIA.Device = DeviceManager.DeviceInfos(i).connect ' connect to scanner If IsNothing(Scanner) Then Console.WriteLine("Scanner " & i & " not recognized") Else Console.WriteLine("Scanning to file " & output & " (dpi = " & dpi & ", color mode '" & color & "', output format '" & format & "')") ' set scan parameters Dim props As New Dictionary(Of String(), Double)() props.Add({"6146", "WIA_IPS_CUR_INTENT", "color mode"}, colorcode) ' color mode props.Add({"4104", "WIA_IPA_DEPTH", "color depth"}, depth) ' color depth props.Add({"6147", "WIA_IPS_XRES", "resolution"}, dpi) ' horizontal dpi props.Add({"6148", "WIA_IPS_YRES", "resolution"}, dpi) ' vertical dpi If w > 0 Then props.Add({"6151", "WIA_IPS_XEXTENT", "width"}, w / 25.4 * dpi) ' width in pixels props.Add({"6152", "WIA_IPS_YEXTENT", "height"}, h / 25.4 * dpi) ' height in pixels props.Add({"6149", "WIA_IPS_XPOS", "x origin"}, 0) ' x origin of scan area props.Add({"6150", "WIA_IPS_YPOS", "y origin"}, 0) ' y origin of scan area End If For Each pair As KeyValuePair(Of String(), Double) In props Try With Scanner.Items(1) .Properties(pair.Key(0)).Value = pair.Value End With Catch ex As Exception Console.WriteLine("Can't set property " & pair.Key(1)) If mandatoryToSetWIA.Contains(pair.Key(1)) Then If unknownErrorIfUnsetWIA.Contains(pair.Key(1)) Then Console.WriteLine("Unknown error while setting " & pair.Key(2)) Else Console.WriteLine("Unsupported parameter, try scanning with different " & pair.Key(2)) End If Exit Sub End If End Try Next ' scan image as BMP... Dim Img As WIA.ImageFile = Scanner.Items(1).Transfer(wiaFormatBMP) ' ...and convert it to desired format Dim ImgProc As Object = CreateObject("WIA.ImageProcess") ImgProc.Filters.Add(ImgProc.FilterInfos("Convert").FilterID) ImgProc.Filters(1).Properties("FormatID") = fileformat ImgProc.Filters(1).Properties("Quality") = 75 Img = ImgProc.Apply(Img) ' ...and save it to file Img.SaveFile(output) End If Dim TimeEnd = DateAndTime.Second(Now) + (DateAndTime.Minute(Now) * 60) + (DateAndTime.Hour(Now) * 3600) Console.WriteLine("Scan finished in " & (TimeEnd - TimeStart) & " seconds") Exit Sub ' if successfully found and scanned, quit End If Next Catch ex As Exception printExceptionMessage(ex) Exit Sub End Try End Sub End Module
Public Class Form_Species_Delete Dim filename As String 'Loads the species, and displays information about it Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click Dim ofd As New OpenFileDialog Dim s As Species ofd.AddExtension = True ofd.DefaultExt = ".species" ofd.Title = "Save a species file" ofd.Filter = "Species (*.species)|*.species" ofd.FilterIndex = 1 ofd.RestoreDirectory = True If ofd.ShowDialog() = DialogResult.OK Then filename = ofd.FileName s = System.IO.File.ReadAllText(ofd.FileName) 'Update info nupGeneration.Value = s.m_iGeneration txtName.Text = s.m_sName nupMutation.Value = s.m_fMutationRate * 100 cbCrossovers.Checked = s.m_bCrossOver cbHits.Checked = ((s.m_iInputNeuronFlags And INFLAG_HITS) = INFLAG_HITS) cbOwnShip.Checked = ((s.m_iInputNeuronFlags And INFLAG_OWN_SHIP_POS) = INFLAG_OWN_SHIP_POS) cbEnemyShots.Checked = ((s.m_iInputNeuronFlags And INFLAG_ENEMY_SHOTS) = INFLAG_ENEMY_SHOTS) cbEnemyHits.Checked = ((s.m_iInputNeuronFlags And INFLAG_ENEMY_HITS) = INFLAG_ENEMY_HITS) 'Allow to delete btnDelete.Enabled = True End If End Sub 'Delete the species, after confirmation Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click If MsgBox("Are you sure you want to delete this species?", MsgBoxStyle.YesNoCancel, "Are you sure?") = MsgBoxResult.Yes Then 'They do want to delete, so delete My.Computer.FileSystem.DeleteFile(filename) MsgBox("The species is now extinct", MsgBoxStyle.Information, "Extinct") Form_Main.ShowFix() Me.Close() End If End Sub Private Sub Form_Species_Delete_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing 'Checks if the person pressed the back button, or if they pressed X If open_form Is Me Then If MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNoCancel, "Exit?") = MsgBoxResult.Yes Then Form_Main.Close() Else e.Cancel = True End If End If End Sub Private Sub Form_Species_Delete_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load open_form = Me 'Update main open form 'Disables resizing Me.MinimumSize = Me.Size Me.MaximumSize = Me.Size Me.MaximizeBox = False End Sub Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click Form_Main.ShowFix() Me.Close() End Sub End Class
' 'Author : Fahad Khan 'Purpose : Maintain Entity Person Role Type Information 'Creation date : 30-Sept-2013 'Stored Procedure(s): ' Imports CTR.Common Imports System.Data.Common Imports Microsoft.Practices.EnterpriseLibrary.Data.Sql Public Class FrmEntityPersonRoleDet #Region "Global Variables" Dim _formName As String = "MaintenanceEntityPersonRoleDet" Dim opt As SecForm = New SecForm(_formName) Dim _formMode As FormTransMode Dim _intModno As Integer = 0 Dim _strEnType_Code As String = "" Dim _mod_datetime As Date Dim _status As String = "" Dim log_message As String = "" Dim _EntityPersonRole As String = "" Dim _EntPersonRole As String = "" #End Region #Region "User defined Codes" Private Sub EnableUnlock() If opt.IsUnlock = True Then btnUnlock.Enabled = True Else DisableUnlock() End If End Sub Private Sub DisableUnlock() btnUnlock.Enabled = False End Sub Private Sub EnableNew() If opt.IsNew = True Then btnNew.Enabled = True Else DisableNew() End If End Sub Private Sub DisableNew() btnNew.Enabled = False End Sub Private Sub EnableSave() If opt.IsSave = True Then btnSave.Enabled = True Else DisableSave() End If End Sub Private Sub DisableSave() btnSave.Enabled = False End Sub Private Sub EnableDelete() If opt.IsDelete = True Then btnDelete.Enabled = True Else DisableDelete() End If End Sub Private Sub DisableDelete() btnDelete.Enabled = False End Sub Private Sub EnableAuth() If opt.IsAuth = True Then btnAuthorize.Enabled = True Else DisableAuth() End If End Sub Private Sub DisableAuth() btnAuthorize.Enabled = False End Sub Private Sub EnableClear() btnClear.Enabled = True End Sub Private Sub DisableClear() btnClear.Enabled = False End Sub Private Sub EnableRefresh() btnRefresh.Enabled = True End Sub Private Sub DisableRefresh() btnRefresh.Enabled = False End Sub Private Sub DisableFields() txtId.ReadOnly = True txtName.ReadOnly = True End Sub Private Sub EnableFields() If txtId.Text.Trim() = "" Then txtId.ReadOnly = False End If txtName.ReadOnly = False End Sub Private Sub ClearFields() If txtId.ReadOnly = False Then txtId.Clear() End If txtName.Clear() End Sub Private Sub ClearFieldsAll() txtId.Clear() txtName.Clear() _strEnType_Code = "" _intModno = 0 lblVerNo.Text = "" lblVerTot.Text = "" lblInputBy.Text = "" lblInputDate.Text = "" lblAuthBy.Text = "" lblAuthDate.Text = "" lblModNo.Text = "" End Sub Private Function CheckValidData() As Boolean If txtId.Text.Trim() = "" Then MessageBox.Show("Code required !!", "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtId.Focus() Return False ElseIf txtName.Text.Trim() = "" Then MessageBox.Show("Name required!!", "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtName.Focus() Return False End If Return True End Function Private Function SaveData() As TransState Dim tStatus As TransState tStatus = TransState.UnspecifiedError Dim db As New SqlDatabase(CommonAppSet.ConnStr) If _formMode = FormTransMode.Add Then Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_Add") commProc.Parameters.Clear() db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, txtId.Text.Trim()) db.AddInParameter(commProc, "@ENPR_NAME", DbType.String, txtName.Text.Trim()) db.AddParameter(commProc, "@PROC_RET_VAL", DbType.Int32, ParameterDirection.ReturnValue, DBNull.Value.ToString(), DataRowVersion.Default, DBNull.Value) Dim result As Integer db.ExecuteNonQuery(commProc) result = db.GetParameterValue(commProc, "@PROC_RET_VAL") If result = 0 Then tStatus = TransState.Add _strEnType_Code = txtId.Text.Trim() _intModno = 1 log_message = " Added : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + txtName.Text.ToString() Logger.system_log(log_message) Else tStatus = TransState.Exist End If ElseIf _formMode = FormTransMode.Update Then Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_Update") commProc.Parameters.Clear() db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, txtId.Text.Trim()) db.AddInParameter(commProc, "@ENPR_NAME", DbType.String, txtName.Text.Trim()) db.AddInParameter(commProc, "@MOD_NO", DbType.Int32, _intModno) db.AddOutParameter(commProc, "@RET_MOD_NO", DbType.Int32, 5) db.AddParameter(commProc, "@PROC_RET_VAL", DbType.Int32, ParameterDirection.ReturnValue, DBNull.Value.ToString(), DataRowVersion.Default, DBNull.Value) Dim result As Integer db.ExecuteNonQuery(commProc) result = db.GetParameterValue(commProc, "@PROC_RET_VAL") If result = 0 Then tStatus = TransState.Update _intModno = db.GetParameterValue(commProc, "@RET_MOD_NO") '----------Mizan Work (11-04-2016)--------------- If _EntityPersonRole <> txtName.Text.Trim() Then log_message = " Updated : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + _EntityPersonRole + " " + " To " + " " + txtName.Text.ToString() Logger.system_log(log_message) Else log_message = " Updated : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + txtName.Text.Trim() Logger.system_log(log_message) End If '----------Mizan Work (11-04-2016)--------------- ElseIf result = 1 Then tStatus = TransState.UnspecifiedError ElseIf result = 4 Then tStatus = TransState.NoRecord End If 'log_message = "Updated Entity Person Role Type " + txtId.Text.Trim() + " Name " + _EntityPersonRole + " To " + txtName.Text.ToString() 'Logger.system_log(log_message) End If Return tStatus End Function '----------Mizan Work (18-04-2016)--------------- Private Sub LoadEnTypeDataForAuth(ByVal strEnTypeCode As String) lblToolStatus.Text = "" Try Dim db As New SqlDatabase(CommonAppSet.ConnStr) Dim ds As New DataSet ds = db.ExecuteDataSet(CommandType.Text, "Select * From GO_ENTITY_PERSON Where ENPR_CODE ='" & strEnTypeCode & "' and STATUS= 'L' ") If ds.Tables(0).Rows.Count > 0 Then _strEnType_Code = strEnTypeCode _formMode = FormTransMode.Update txtId.Text = ds.Tables(0).Rows(0)("ENPR_CODE").ToString() txtName.Text = ds.Tables(0).Rows(0)("ENPR_NAME").ToString() _EntPersonRole = ds.Tables(0).Rows(0)("ENPR_NAME").ToString() Else ClearFieldsAll() End If Catch ex As Exception MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub LoadEnTypeData(ByVal strEnTypeCode As String, ByVal intMod As Integer) lblToolStatus.Text = "" Try Dim db As New SqlDatabase(CommonAppSet.ConnStr) Dim ds As New DataSet Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_GetDetail") commProc.Parameters.Clear() db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, strEnTypeCode) db.AddInParameter(commProc, "@MOD_NO", DbType.Int32, intMod) ds = db.ExecuteDataSet(commProc) If ds.Tables(0).Rows.Count > 0 Then _strEnType_Code = strEnTypeCode _intModno = intMod _formMode = FormTransMode.Update txtId.Text = ds.Tables(0).Rows(0)("ENPR_CODE").ToString() txtName.Text = ds.Tables(0).Rows(0)("ENPR_NAME").ToString() _EntityPersonRole = ds.Tables(0).Rows(0)("ENPR_NAME").ToString() lblInputBy.Text = ds.Tables(0).Rows(0)("INPUT_BY").ToString() lblInputDate.Text = ds.Tables(0).Rows(0)("INPUT_DATETIME").ToString() _mod_datetime = ds.Tables(0).Rows(0)("INPUT_DATETIME") lblAuthBy.Text = ds.Tables(0).Rows(0)("AUTH_BY").ToString() lblAuthDate.Text = ds.Tables(0).Rows(0)("AUTH_DATETIME").ToString() chkAuthorized.Checked = ds.Tables(0).Rows(0)("IS_AUTH") If ds.Tables(0).Rows(0)("STATUS") = "L" Or ds.Tables(0).Rows(0)("STATUS") = "U" Or ds.Tables(0).Rows(0)("STATUS") = "O" Then chkOpen.Checked = True Else chkOpen.Checked = False End If _status = ds.Tables(0).Rows(0)("STATUS") lblModNo.Text = ds.Tables(0).Rows(0)("MOD_NO").ToString() lblVerNo.Text = ds.Tables(0).Rows(0)("MOD_NO").ToString() Dim commProc2 As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_GetMaxMod") commProc2.Parameters.Clear() db.AddInParameter(commProc2, "@ENPR_CODE", DbType.String, strEnTypeCode) lblVerTot.Text = db.ExecuteDataSet(commProc2).Tables(0).Rows(0)(0).ToString() If _status = "L" Or _status = "U" _ Or (_status = "D" And chkAuthorized.Checked = False) Then If btnUnlock.Enabled = False Then EnableFields() EnableClear() EnableDelete() EnableNew() EnableRefresh() EnableSave() End If Else DisableAuth() DisableClear() DisableDelete() DisableRefresh() DisableSave() DisableFields() End If If chkAuthorized.Checked = False And (Not lblInputBy.Text.Trim = CommonAppSet.User) Then EnableAuth() End If Else ClearFieldsAll() End If Catch ex As Exception MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Public Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub Public Sub New(ByVal strEnTypeCode As String, ByVal intMod As Integer) ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. LoadEnTypeData(strEnTypeCode, intMod) _strEnType_Code = strEnTypeCode _intModno = intMod End Sub Private Function DeleteData() As TransState Dim tStatus As TransState Dim intModno As Integer = 0 tStatus = TransState.UnspecifiedError Dim db As New SqlDatabase(CommonAppSet.ConnStr) Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_Remove") commProc.Parameters.Clear() db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, _strEnType_Code) db.AddInParameter(commProc, "@MOD_NO", DbType.Int32, _intModno) db.AddOutParameter(commProc, "@RET_MOD_NO", DbType.Int32, 5) db.AddParameter(commProc, "@PROC_RET_VAL", DbType.Int32, ParameterDirection.ReturnValue, DBNull.Value.ToString(), DataRowVersion.Default, DBNull.Value) Dim result As Integer db.ExecuteNonQuery(commProc) result = db.GetParameterValue(commProc, "@PROC_RET_VAL") If result = 0 Then tStatus = TransState.Delete _intModno = db.GetParameterValue(commProc, "@RET_MOD_NO") ElseIf result = 1 Then tStatus = TransState.UpdateNotPossible ElseIf result = 3 Then tStatus = TransState.UpdateNotPossible ElseIf result = 4 Then tStatus = TransState.NoRecord ElseIf result = 5 Then tStatus = TransState.UpdateNotPossible ElseIf result = 6 Then tStatus = TransState.AlreadyDeleted Else tStatus = TransState.UpdateNotPossible End If log_message = "Delete Entity Person Role Type " + _strEnType_Code + " Name " + txtName.Text.ToString() Logger.system_log(log_message) Return tStatus End Function '----------Mizan Work (18-04-2016)--------------- Private Function AuthorizeData() As TransState If _intModno > 1 Then LoadEnTypeDataForAuth(_strEnType_Code) Dim tStatus As TransState tStatus = TransState.UnspecifiedError Dim db As New SqlDatabase(CommonAppSet.ConnStr) Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_Auth") commProc.Parameters.Clear() db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, _strEnType_Code) db.AddInParameter(commProc, "@MOD_NO", DbType.Int32, _intModno) db.AddInParameter(commProc, "@MOD_DATETIME", DbType.DateTime, _mod_datetime) db.AddParameter(commProc, "@PROC_RET_VAL", DbType.Int32, ParameterDirection.ReturnValue, DBNull.Value.ToString(), DataRowVersion.Default, DBNull.Value) Dim result As Integer db.ExecuteNonQuery(commProc) result = db.GetParameterValue(commProc, "@PROC_RET_VAL") If result = 0 Then tStatus = TransState.Update If _EntPersonRole <> _EntityPersonRole Then If _EntPersonRole = "" Then log_message = " Authorized : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + _EntityPersonRole Else log_message = " Authorized : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + _EntPersonRole + " " + " To " + " " + _EntityPersonRole End If Logger.system_log(log_message) Else log_message = " Authorized : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + txtName.Text.Trim() Logger.system_log(log_message) End If ElseIf result = 1 Then tStatus = TransState.UpdateNotPossible ElseIf result = 3 Then tStatus = TransState.AlreadyAuthorized ElseIf result = 4 Then tStatus = TransState.NoRecord ElseIf result = 5 Then tStatus = TransState.MakerCheckerSame ElseIf result = 7 Then tStatus = TransState.ModifiedOutside Else tStatus = TransState.UpdateNotPossible End If Return tStatus Else Dim tStatus As TransState tStatus = TransState.UnspecifiedError Dim db As New SqlDatabase(CommonAppSet.ConnStr) Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_Auth") commProc.Parameters.Clear() db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, _strEnType_Code) db.AddInParameter(commProc, "@MOD_NO", DbType.Int32, _intModno) db.AddInParameter(commProc, "@MOD_DATETIME", DbType.DateTime, _mod_datetime) db.AddParameter(commProc, "@PROC_RET_VAL", DbType.Int32, ParameterDirection.ReturnValue, DBNull.Value.ToString(), DataRowVersion.Default, DBNull.Value) Dim result As Integer db.ExecuteNonQuery(commProc) result = db.GetParameterValue(commProc, "@PROC_RET_VAL") If result = 0 Then tStatus = TransState.Update If _EntPersonRole <> _EntityPersonRole Then If _EntPersonRole = "" Then log_message = " Authorized : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + _EntityPersonRole Else log_message = " Authorized : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + _EntPersonRole + " " + " To " + " " + _EntityPersonRole End If Logger.system_log(log_message) Else log_message = " Authorized : Entity Person Role Type Code : " + txtId.Text.Trim() + "." + " " + " Entity Person Role Type Name : " + txtName.Text.Trim() Logger.system_log(log_message) End If ElseIf result = 1 Then tStatus = TransState.UpdateNotPossible ElseIf result = 3 Then tStatus = TransState.AlreadyAuthorized ElseIf result = 4 Then tStatus = TransState.NoRecord ElseIf result = 5 Then tStatus = TransState.MakerCheckerSame ElseIf result = 7 Then tStatus = TransState.ModifiedOutside Else tStatus = TransState.UpdateNotPossible End If Return tStatus End If '--------------------Commented By Mizan(18-04-16)------------------- 'Dim tStatus As TransState 'tStatus = TransState.UnspecifiedError 'Dim db As New SqlDatabase(CommonAppSet.ConnStr) 'Dim commProc As DbCommand = db.GetStoredProcCommand("GO_EntityPersonRoleType_Auth") 'commProc.Parameters.Clear() 'db.AddInParameter(commProc, "@ENPR_CODE", DbType.String, _strEnType_Code) 'db.AddInParameter(commProc, "@MOD_NO", DbType.Int32, _intModno) 'db.AddInParameter(commProc, "@MOD_DATETIME", DbType.DateTime, _mod_datetime) 'db.AddParameter(commProc, "@PROC_RET_VAL", DbType.Int32, ParameterDirection.ReturnValue, DBNull.Value.ToString(), DataRowVersion.Default, DBNull.Value) 'Dim result As Integer 'db.ExecuteNonQuery(commProc) 'result = db.GetParameterValue(commProc, "@PROC_RET_VAL") 'If result = 0 Then ' tStatus = TransState.Update 'ElseIf result = 1 Then ' tStatus = TransState.UpdateNotPossible 'ElseIf result = 3 Then ' tStatus = TransState.AlreadyAuthorized 'ElseIf result = 4 Then ' tStatus = TransState.NoRecord 'ElseIf result = 5 Then ' tStatus = TransState.MakerCheckerSame 'ElseIf result = 7 Then ' tStatus = TransState.ModifiedOutside 'Else ' tStatus = TransState.UpdateNotPossible 'End If 'log_message = "Authorized Entity Person Role Type " + _strEnType_Code + " Name " + txtName.Text.ToString() 'Logger.system_log(log_message) 'Return tStatus End Function #End Region Private Sub FrmEntityPersonRoleDet_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If opt.IsShow = False Then MessageBox.Show("You are not authorized", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.Close() End If If _intModno > 0 Then LoadEnTypeData(_strEnType_Code, _intModno) End If EnableUnlock() DisableNew() DisableSave() DisableDelete() DisableAuth() DisableClear() DisableRefresh() DisableFields() End Sub Private Sub btnUnlock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUnlock.Click EnableNew() If Not (_strEnType_Code.Trim() = "") Then If _status = "L" Or _status = "U" _ Or (_status = "D" And chkAuthorized.Checked = False) Then EnableFields() EnableClear() EnableDelete() EnableNew() EnableRefresh() EnableSave() Else DisableAuth() DisableClear() DisableDelete() DisableRefresh() DisableSave() DisableFields() End If If chkAuthorized.Checked = False And (Not lblInputBy.Text.Trim = CommonAppSet.User) Then EnableAuth() End If Else DisableFields() End If DisableUnlock() End Sub Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click lblToolStatus.Text = "" _formMode = FormTransMode.Add EnableSave() ClearFieldsAll() EnableFields() DisableRefresh() DisableDelete() If txtId.Enabled = True Then txtId.Focus() End If End Sub Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click Dim tState As TransState lblToolStatus.Text = "" Try If MessageBox.Show("Do you really want to Save?", "Confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then If CheckValidData() Then tState = SaveData() If tState = TransState.Add Then LoadEnTypeData(_strEnType_Code, _intModno) lblToolStatus.Text = "!! Information Added Successfully !!" _formMode = FormTransMode.Update EnableDelete() EnableRefresh() ElseIf tState = TransState.Update Then LoadEnTypeData(_strEnType_Code, _intModno) lblToolStatus.Text = "!! Information Updated Successfully !!" ElseIf tState = TransState.Exist Then lblToolStatus.Text = "!! Already Exist !!" ElseIf tState = TransState.NoRecord Then lblToolStatus.Text = "!! Nothing to Update !!" ElseIf tState = TransState.DBError Then lblToolStatus.Text = "!! Database error occured. Please, Try Again !!" ElseIf tState = TransState.UnspecifiedError Then lblToolStatus.Text = "!! Unpecified Error Occured !!" End If End If End If Catch ex As Exception MessageBox.Show(ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click ClearFields() End Sub Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click LoadEnTypeData(_strEnType_Code, _intModno) End Sub Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click Dim tState As TransState lblToolStatus.Text = "" Try If MessageBox.Show("Do you really want to delete?", "Confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then tState = DeleteData() If tState = TransState.Delete Then _formMode = FormTransMode.Add LoadEnTypeData(_strEnType_Code, _intModno) DisableAuth() If _strEnType_Code = "" Then DisableDelete() DisableSave() DisableRefresh() DisableFields() End If lblToolStatus.Text = "!! Information Deleted Successfully !!" ElseIf tState = TransState.AlreadyDeleted Then lblToolStatus.Text = "!! Failed. Data is already deleted !!" ElseIf tState = TransState.UpdateNotPossible Then lblToolStatus.Text = "!! Delete Not Possible !!" ElseIf tState = TransState.Exist Then lblToolStatus.Text = "!! New Delete status insertion failed !!" ElseIf tState = TransState.NoRecord Then lblToolStatus.Text = "!! Nothing to Delete !!" Else lblToolStatus.Text = "!! Unpecified Error Occured !!" End If End If Catch ex As Exception MessageBox.Show(ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub btnPrevVer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevVer.Click If _intModno - 1 > 0 Then LoadEnTypeData(_strEnType_Code, _intModno - 1) End If End Sub Private Sub btnNextVer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNextVer.Click Dim strEnTypeCode As String = _strEnType_Code Dim intModno As Integer = _intModno If intModno > 0 Then LoadEnTypeData(_strEnType_Code, _intModno + 1) If _intModno = 0 Then LoadEnTypeData(strEnTypeCode, intModno) End If End If End Sub Private Sub btnAuthorize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAuthorize.Click Dim tState As TransState lblToolStatus.Text = "" Try If MessageBox.Show("Do you really want to Authorize?", "Confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then tState = AuthorizeData() If tState = TransState.Update Then LoadEnTypeData(_strEnType_Code, _intModno) lblToolStatus.Text = "!! Authorized Successfully !!" EnableUnlock() DisableNew() DisableSave() DisableDelete() DisableAuth() DisableClear() DisableRefresh() DisableFields() ElseIf tState = TransState.AlreadyAuthorized Then lblToolStatus.Text = "!! Authorized Data cannot be authorized again !!" ElseIf tState = TransState.MakerCheckerSame Then lblToolStatus.Text = "!! You cannot authorize the transaction !!" ElseIf tState = TransState.UpdateNotPossible Then lblToolStatus.Text = "!! Failed! Authorization Failed !!" ElseIf tState = TransState.ModifiedOutside Then lblToolStatus.Text = "!! Failed! Data Mismatch. Reload, Check and Authorise again !!" ElseIf tState = TransState.DBError Then lblToolStatus.Text = "!! Database error occured. Please, Try Again !!" ElseIf tState = TransState.UnspecifiedError Then lblToolStatus.Text = "!! Unpecified Error Occured !!" End If End If Catch ex As Exception MessageBox.Show(ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click Me.Close() End Sub End Class
Module Module1 Sub Main() Dim data(9), count As Integer Console.WriteLine("Enter 10 numbers as follows : ") 'Getting 10 number inputs while validating them count = 0 While (count < data.Length) Try data(count) = Console.ReadLine() count = count + 1 Catch ex As Exception Console.WriteLine("Invalid input! Enter again...") End Try End While 'Calling the InsertionSort function data = InsertionSort(data) 'Displaying the sorted numbers of the data array For i As Integer = 0 To data.Length - 1 Console.WriteLine(data(i)) Next Console.ReadLine() End Sub 'Implementation of the insertion sort algorithm Function InsertionSort(data() As Integer) As Integer() Dim key, i, j As Integer For i = 1 To data.Length - 1 key = data(i) j = i - 1 While j >= 0 AndAlso data(j) > key data(j + 1) = data(j) j -= 1 End While data(j + 1) = key Next Return data End Function End Module
'filename: ImageUtils.vb 'This module contains various utility functions. 'Natacha Gabbamonte 0932340 '11/12/2011 Imports System.Drawing.Imaging Module ImageUtils 'This function checks to see if the filename has one of the following extensions: 'jpg/png/bmp/gif 'Parameter: 'fileName is the file name that will be validated. Public Function isValidExtension(ByVal fileName As String) As Boolean Dim allExtensions As String() = New String() {".jpg", ".gif", ".png", ".bmp"} Dim extension As String Dim indexOfDot As Integer = fileName.IndexOf(".") If (indexOfDot <> -1) Then extension = fileName.Substring(indexOfDot) For Each ext In allExtensions If extension.Equals(ext) Then Return True 'A match was found End If Next End If Return False 'No match found End Function 'This function determines the format in which the picture will be saved. 'Parameter: 'fileName is the name of the future image. Public Function DetermineFormat(ByVal fileName As String) As ImageFormat Dim aFormat As ImageFormat = Nothing Select Case fileName.Substring(fileName.IndexOf(".")) Case ".jpg" aFormat = ImageFormat.Jpeg Case ".gif" aFormat = ImageFormat.Gif Case ".png" aFormat = ImageFormat.Png Case ".bmp" aFormat = ImageFormat.Bmp End Select Return aFormat End Function 'This function invert the colors of eahc pixel in a Bitmap 'Parameters: 'bm is the Bitmap to be inverted Public Sub Invert(ByVal bm As Bitmap) Dim maxWidth As Integer = bm.Width - 1 Dim maxHeight As Integer = bm.Height - 1 For x As Integer = 0 To maxWidth For y As Integer = 0 To maxHeight Dim aColor As Color = bm.GetPixel(x, y) Dim newColor As Color = Color.FromArgb(255 - aColor.R, 255 - aColor.G, 255 - aColor.B) bm.SetPixel(x, y, newColor) Next Next End Sub '***BONUS 1 'This sub sets the colors of a Bitmap to grayscale. 'Parameters: 'bm is the Bitmap to be inverted Public Sub GrayScale(ByVal bm As Bitmap) Dim maxWidth As Integer = bm.Width - 1 Dim maxHeight As Integer = bm.Height - 1 Dim aPixel As Color Dim newColor As Integer For x As Integer = 0 To maxWidth For y As Integer = 0 To maxHeight aPixel = bm.GetPixel(x, y) newColor = (CInt(aPixel.R) + aPixel.B + aPixel.G) \ 3 bm.SetPixel(x, y, Color.FromArgb(newColor, newColor, newColor)) Next Next End Sub '***BONUS 1 'This sub blurs the Bitmap sent in. 'Parameters: 'bm is the Bitmap to be blurred 'degree represents the intensity of the blur, the higher it is, 'the more blurry the image becomes. Public Sub Blur(ByVal bm As Bitmap, ByVal degree As Integer) Dim maxWidth As Integer = bm.Width - 1 - degree Dim maxHeight As Integer = bm.Height - 1 - degree Dim pixel1 As Color Dim otherPixel As Color Dim redValues As Integer Dim greenValues As Integer Dim blueValues As Integer Dim counter As Integer For x As Integer = degree To maxWidth For y As Integer = degree To maxHeight pixel1 = bm.GetPixel(x, y) redValues = pixel1.R greenValues = pixel1.G blueValues = pixel1.B counter = 1 For i As Integer = 1 To degree otherPixel = bm.GetPixel(x - i, y) redValues += otherPixel.R greenValues += otherPixel.G blueValues += otherPixel.B otherPixel = bm.GetPixel(x - i, y - i) redValues += otherPixel.R greenValues += otherPixel.G blueValues += pixel1.B otherPixel = bm.GetPixel(x, y - i) redValues += otherPixel.R greenValues += otherPixel.G blueValues += otherPixel.B otherPixel = bm.GetPixel(x - i, y + i) redValues += otherPixel.R greenValues += otherPixel.G blueValues += otherPixel.B otherPixel = bm.GetPixel(x + i, y) redValues += otherPixel.R greenValues += otherPixel.G blueValues += otherPixel.B otherPixel = bm.GetPixel(x + i, y + i) redValues += otherPixel.R greenValues += otherPixel.G blueValues += otherPixel.B otherPixel = bm.GetPixel(x, y + i) redValues += otherPixel.R greenValues += otherPixel.G blueValues += otherPixel.B counter += 7 Next redValues \= counter greenValues \= counter blueValues \= counter bm.SetPixel(x, y, Color.FromArgb(redValues, greenValues, blueValues)) For i As Integer = 1 To degree bm.SetPixel(x + i, y, Color.FromArgb(redValues, greenValues, blueValues)) bm.SetPixel(x + i, y + i, Color.FromArgb(redValues, greenValues, blueValues)) bm.SetPixel(x, y + i, Color.FromArgb(redValues, greenValues, blueValues)) bm.SetPixel(x - i, y, Color.FromArgb(redValues, greenValues, blueValues)) bm.SetPixel(x, y - i, Color.FromArgb(redValues, greenValues, blueValues)) bm.SetPixel(x + i, y - i, Color.FromArgb(redValues, greenValues, blueValues)) bm.SetPixel(x - i, y - i, Color.FromArgb(redValues, greenValues, blueValues)) Next Next Next End Sub End Module
'=================================================================================================================================== 'Projet : Vinicom 'Auteur : Marc Collin 'Création : 23/06/04 '=================================================================================================================================== ' Classe : lgFactColisage ' Description : Ligne de Facture de Colisage '=================================================================================================================================== 'Membres de Classes '================== 'Public 'Protected 'Private 'Membres d'instances '================== 'Public ' toString() : Rend 'objet sous forme de chaine ' Equals() : Test l'équivalence d'instance 'Protected 'Private '=================================================================================================================================== 'Historique : '============ ' '=================================================================================================================================== Public Class LgFactColisage Inherits LgCommande Public Sub New(ByVal pidFact As Integer) MyBase.New(pidFact, 0, 0) End Sub Public Property idFactColisage() As Integer Get Return idCmd End Get Private Set(ByVal value As Integer) idCmd = value End Set End Property End Class Public Class LgFactColisageOLDADEL Inherits Persist Private m_num As Integer 'Numéro d'ordre de ligne Private m_idFactColisage As Long Private m_dDeb As Date Private m_dFin As Date Private m_StockInitial As Integer Private m_Entrees As Integer Private m_Sorties As Integer Private m_StockFinal As Integer Private m_qte As Integer Private m_pu As Decimal Private m_Montant_HT As Decimal #Region "Accesseurs" Public Property num() As Integer Get Return m_num End Get Set(ByVal Value As Integer) If m_num <> Value Then m_num = Value bUpdated = True End If End Set End Property Public Sub New() m_typedonnee = vncEnums.vncTypeDonnee.LGFACTCOL m_idFactColisage = 0 m_dDeb = DATE_DEFAUT m_dFin = DATE_DEFAUT m_StockInitial = 0 m_Entrees = 0 m_Sorties = 0 m_StockFinal = 0 m_qte = 0 m_pu = 0.0 m_Montant_HT = 0.0 End Sub Public Property idFactColisage() As Long Get Return m_idFactColisage End Get Set(ByVal Value As Long) If Value <> m_idFactColisage Then m_idFactColisage = Value RaiseUpdated() End If End Set End Property Public Property dDeb() As Date Get Return m_dDeb End Get Set(ByVal Value As Date) If m_dDeb <> Value Then m_dDeb = Value RaiseUpdated() End If End Set End Property Public Property dFin() As Date Get Return m_dFin End Get Set(ByVal Value As Date) If m_dFin <> Value Then m_dFin = Value RaiseUpdated() End If End Set End Property Public Property StockInitial() As Integer Get Return m_StockInitial End Get Set(ByVal Value As Integer) If (Not Value.Equals(m_StockInitial)) Then m_StockInitial = Value RaiseUpdated() End If End Set End Property Public Property StockFinal() As Integer Get Return m_StockFinal End Get Set(ByVal Value As Integer) If (Not Value.Equals(m_StockFinal)) Then m_StockFinal = Value m_qte = Value RaiseUpdated() End If End Set End Property Public Property Entrees() As Integer Get Return m_Entrees End Get Set(ByVal Value As Integer) If (Not Value.Equals(m_Entrees)) Then m_Entrees = Value RaiseUpdated() End If End Set End Property Public Property Sorties() As Integer Get Return m_Sorties End Get Set(ByVal Value As Integer) If (Not Value.Equals(m_Sorties)) Then m_Sorties = Value RaiseUpdated() End If End Set End Property Public Property qte() As Integer Get Return m_qte End Get Set(ByVal Value As Integer) If (Not Value.Equals(m_qte)) Then m_qte = Value RaiseUpdated() End If End Set End Property Public Property pu() As Decimal Get Return m_pu End Get Set(ByVal Value As Decimal) If m_pu <> Value Then m_pu = Value RaiseUpdated() End If End Set End Property Public Property MontantHT() As Decimal Get Return m_Montant_HT End Get Set(ByVal Value As Decimal) If m_Montant_HT <> Value Then m_Montant_HT = Value RaiseUpdated() End If End Set End Property #End Region #Region "Méthodes Persist" '======================================================================= 'Fonction : DBLoad() 'Description : Chargement de l'objet 'Détails : 'Retour : Vrai di l'opération s'est bien déroulée '======================================================================= Protected Overrides Function DBLoad(Optional ByVal pid As Integer = 0) As Boolean Dim bReturn As Boolean bReturn = False Return bReturn End Function 'DBLoad '======================================================================= 'Fonction : delete() 'Description : Suppression de l'objet dans la base de l'objet 'Détails : 'Retour : Vrai si l'opération s'est bien déroulée '======================================================================= Friend Overrides Function delete() As Boolean Dim bReturn As Boolean bReturn = False Return bReturn End Function ' delete '======================================================================= 'Fonction : checkFordelete 'description : Controle si l'élément est supprimable ' table commandesClients '======================================================================= Public Overrides Function checkForDelete() As Boolean Dim bReturn As Boolean Try bReturn = True Catch ex As Exception bReturn = False End Try Return bReturn End Function 'checkForDelete '======================================================================= 'Fonction : insert() 'Description : insertion de l'objet dans la base de l'objet 'Détails : 'Retour : Vrai di l'opération s'est bien déroulée '======================================================================= Friend Overrides Function insert() As Boolean Dim bReturn As Boolean bReturn = False Return bReturn End Function 'insert '======================================================================= 'Fonction : Update() 'Description : Mise à jour de l'objet 'Détails : 'Retour : Vrai di l'opération s'est bien déroulée '======================================================================= Friend Overrides Function update() As Boolean Dim bReturn As Boolean bReturn = False Return bReturn End Function 'Update #End Region '======================================================================= 'Fonction : ToString() 'Description : Rend l'objet sous forme de String 'Détails : 'Retour : une Chaine '======================================================================= Public Overrides Function toString() As String Return "LGFACTCOLISAGE =(" & m_id & "," & m_idFactColisage & "," & m_Montant_HT & ")" End Function '======================================================================= 'Fonction : Equals() 'Description : Teste l'équivalence entre 2 objets 'Détails : 'Retour : Vari si l'objet passé en paramétre est equivalent à '======================================================================= Public Overrides Function Equals(ByVal obj As Object) As Boolean Dim bReturn As Boolean Dim objLgFactColisage As LgFactColisage Try objLgFactColisage = CType(obj, LgFactColisage) bReturn = True bReturn = bReturn And MyBase.Equals(objLgFactColisage) Catch ex As Exception bReturn = False End Try Return bReturn End Function 'Equals '======================================================================= 'Fonction : calculPrixTotal() 'Description : Calcul du prix total 'Détails : 'Retour : '======================================================================= Public Sub calculPrixTotal() m_Montant_HT = m_qte * pu End Sub Public Sub calculStockFinal() m_StockFinal = m_StockInitial + m_Entrees + m_Sorties m_qte = m_StockFinal End Sub Public Overrides ReadOnly Property shortResume() As String Get Return "LGCOLISAGE" End Get End Property End Class
Imports Motor3D.Espacio3D Imports Motor3D.Espacio2D Imports Motor3D.Escena Imports Motor3D.Escena.Shading Imports System.Drawing Imports System.Math Namespace Primitivas3D Public Class Cara Inherits ObjetoPrimitiva3D Private mNormalSUR As Vector3D Private mNormalSRC As Vector3D Private mVertices() As Integer Private mBaricentroSUR As Punto3D Private mBaricentroSRC As Punto3D Private mColor As Color Private mColorShading As Color Private mCargadaEnBuffer As Boolean Public Shadows Event Modificado(ByRef Sebder As Cara) Public Property CargadaEnBuffer As Boolean Get Return mCargadaEnBuffer End Get Set(value As Boolean) mCargadaEnBuffer = value End Set End Property Public Property NormalSUR() As Vector3D Get Return mNormalSUR End Get Set(ByVal value As Vector3D) mNormalSUR = value RaiseEvent Modificado(Me) End Set End Property Public Property NormalSRC() As Vector3D Get Return mNormalSRC End Get Set(ByVal value As Vector3D) mNormalSRC = value RaiseEvent Modificado(Me) End Set End Property Public Property BaricentroSUR() As Punto3D Get Return mBaricentroSUR End Get Set(ByVal value As Punto3D) mBaricentroSUR = value RaiseEvent Modificado(Me) End Set End Property Public Property BaricentroSRC() As Punto3D Get Return mBaricentroSRC End Get Set(ByVal value As Punto3D) mBaricentroSRC = value RaiseEvent Modificado(Me) End Set End Property Public Property Vertices() As Integer() Get Return mVertices End Get Set(ByVal value As Integer()) If value.GetUpperBound(0) = mVertices.GetUpperBound(0) Then mVertices = value RaiseEvent Modificado(Me) End If End Set End Property Public Property Vertices(ByVal Indice As Integer) As Integer Get If Indice >= 0 AndAlso Indice <= mVertices.GetUpperBound(0) Then Return mVertices(Indice) Else Return -1 End If End Get Set(ByVal value As Integer) If Indice >= 0 AndAlso Indice <= mVertices.GetUpperBound(0) Then mVertices(Indice) = value RaiseEvent Modificado(Me) End If End Set End Property Public ReadOnly Property Vertices(ByVal ArrayVertices() As Vertice) As Vertice() Get Dim Retorno(mVertices.GetUpperBound(0)) As Vertice For i As Integer = 0 To mVertices.GetUpperBound(0) Retorno(i) = ArrayVertices(mVertices(i)) Next Return Retorno End Get End Property Public ReadOnly Property PuntosSUR(ByVal Vertices() As Vertice) As Punto3D() Get Dim Retorno(mVertices.GetUpperBound(0)) As Punto3D For i As Integer = 0 To mVertices.GetUpperBound(0) Retorno(i) = Vertices(mVertices(i)).CoodenadasSUR Next Return Retorno End Get End Property Public ReadOnly Property PuntosSRC(ByVal Vertices() As Vertice) As Punto3D() Get Dim Retorno(mVertices.GetUpperBound(0)) As Punto3D For i As Integer = 0 To mVertices.GetUpperBound(0) Retorno(i) = Vertices(mVertices(i)).CoodenadasSRC Next Return Retorno End Get End Property Public ReadOnly Property Representacion(ByVal Vertices() As Vertice) As Punto2D() Get Dim Retorno(mVertices.GetUpperBound(0)) As Punto2D For i As Integer = 0 To mVertices.GetUpperBound(0) Retorno(i) = Vertices(mVertices(i)).Representacion Next Return Retorno End Get End Property Public ReadOnly Property RepresentacionToPoint(ByVal Vertices() As Vertice) As Point() Get Dim Retorno(mVertices.GetUpperBound(0)) As Point For i As Integer = 0 To mVertices.GetUpperBound(0) Retorno(i) = Vertices(mVertices(i)).Representacion.ToPoint Next Return Retorno End Get End Property Public ReadOnly Property NumeroVertices() As Integer Get Return mVertices.GetUpperBound(0) + 1 End Get End Property Public Property Color() As Color Get Return mColor End Get Set(ByVal value As Color) mColor = value RaiseEvent Modificado(Me) End Set End Property Public Property ColorShading() As Color Get Return mColorShading End Get Set(ByVal value As Color) mColorShading = value End Set End Property Public Sub New(ByVal ParamArray Vertices() As Integer) If Vertices.GetUpperBound(0) >= 2 Then mVertices = Vertices mNormalSUR = New Vector3D mBaricentroSUR = New Punto3D mColor = Color.White Else If Vertices.GetUpperBound(0) = 0 Then ReDim mVertices(Vertices(0) - 1) mNormalSUR = New Vector3D mBaricentroSUR = New Punto3D mColor = Color.White Else Throw New ExcepcionPrimitiva3D("CARA (NEW): Una cara debe tener al menos tres vértices." & vbNewLine _ & "Número de vértices: " & Vertices.GetUpperBound(0) + 1) End If End If End Sub Public Sub RecalcularNormalSUR(ByVal Vertices() As Vertice) mNormalSUR = Cara.VectorNormalSUR(Me, Vertices) RaiseEvent Modificado(Me) End Sub Public Sub RecalcularBaricentroSUR(ByVal Vertices() As Vertice) mBaricentroSUR = Cara.BaricentroCaraSUR(Me, Vertices) RaiseEvent Modificado(Me) End Sub Public Sub RecalcularDatosSUR(ByVal Vertices() As Vertice) mNormalSUR = Cara.VectorNormalSUR(Me, Vertices) mBaricentroSUR = Cara.BaricentroCaraSUR(Me, Vertices) RaiseEvent Modificado(Me) End Sub Public Sub RecalcularNormalSRC(ByVal Vertices() As Vertice) mNormalSRC = Cara.VectorNormalSRC(Me, Vertices) RaiseEvent Modificado(Me) End Sub Public Sub RecalcularBaricentroSRC(ByVal Vertices() As Vertice) mBaricentroSRC = Cara.BaricentroCaraSRC(Me, Vertices) RaiseEvent Modificado(Me) End Sub Public Sub RecalcularDatosSRC(ByVal Vertices() As Vertice) mNormalSRC = Cara.VectorNormalSRC(Me, Vertices) mBaricentroSRC = Cara.BaricentroCaraSRC(Me, Vertices) RaiseEvent Modificado(Me) End Sub Public Sub Shading(ByVal Constantes As PhongShader, ByVal Focos() As Foco3D, ByVal Camara As Camara3D) mColorShading = Constantes.EcuacionPhong(Focos, mNormalSUR, mBaricentroSUR, mColor, Camara) End Sub Public Sub RevertirVertices() Array.Reverse(mVertices) End Sub Public Function EsVisible(ByVal Camara As Camara3D, ByVal Vertices() As Vertice) As Boolean If mNormalSRC.Z <= 0.01 AndAlso Camara.Frustum.Pertenece(mBaricentroSRC) Then For i As Integer = 0 To mVertices.GetUpperBound(0) If Camara.Pantalla.Pertenece(Vertices(mVertices(i)).Representacion) Then Return True End If Next Return False Else Return False End If End Function Public Shared Function VectorNormalSUR(ByVal Cara As Cara, ByVal Vertices() As Vertice) As Vector3D Return (New Vector3D(Vertices(Cara.Vertices(0)).CoodenadasSUR, Vertices(Cara.Vertices(1)).CoodenadasSUR) & New Vector3D(Vertices(Cara.Vertices(0)).CoodenadasSUR, Vertices(Cara.Vertices(2)).CoodenadasSUR)).VectorUnitario End Function Public Shared Function VectorNormalSRC(ByVal Cara As Cara, ByVal Vertices() As Vertice) As Vector3D Return (New Vector3D(Vertices(Cara.Vertices(0)).CoodenadasSRC, Vertices(Cara.Vertices(1)).CoodenadasSRC) & New Vector3D(Vertices(Cara.Vertices(0)).CoodenadasSRC, Vertices(Cara.Vertices(2)).CoodenadasSRC)).VectorUnitario End Function Public Shared Function PlanoSUR(ByVal Cara As Cara, ByVal Vertices() As Vertice) As Plano3D Return New Plano3D(Vertices(Cara.Vertices(0)).CoodenadasSUR, Vertices(Cara.Vertices(1)).CoodenadasSUR, Vertices(Cara.Vertices(2)).CoodenadasSUR) End Function Public Shared Function PlanoSRC(ByVal Cara As Cara, ByVal Vertices() As Vertice) As Plano3D Return New Plano3D(Vertices(Cara.Vertices(0)).CoodenadasSRC, Vertices(Cara.Vertices(1)).CoodenadasSRC, Vertices(Cara.Vertices(2)).CoodenadasSRC) End Function Public Shared Function BaricentroCaraSUR(ByVal Cara As Cara, ByVal Vertices() As Vertice) As Punto3D Return Punto3D.Baricentro(Cara.PuntosSUR(Vertices)) End Function Public Shared Function BaricentroCaraSRC(ByVal Cara As Cara, ByVal Vertices() As Vertice) As Punto3D Return Punto3D.Baricentro(Cara.PuntosSRC(Vertices)) End Function Public Overrides Function ToString() As String Dim Retorno As String = "" For i As Integer = 0 To mVertices.GetUpperBound(0) If i < mVertices.GetUpperBound(0) Then Retorno &= mVertices(i).ToString & "," Else Retorno &= mVertices(i).ToString & ",Baricentro=" & mBaricentroSUR.ToString & ",Normal=" & mNormalSUR.ToString & "}" End If Next Return Retorno End Function End Class End Namespace
Imports System.Data.Linq Public Class PacienteDebitoManager Public Enum TipoDocumento Cita = 1 Factura = 2 Recibo = 3 N_Tickets = 4 N_Facturas = 5 PagoCuenta = 6 End Enum Public Paciente As PACIENTE Public Context As New CMLinqDataContext 'Esta clase es para PacienteDebito Public Filtro As FiltroGenericoDocumentos Public Sub New(paciente As PACIENTE, context As CMLinqDataContext, filter As FiltroGenericoDocumentos) Me.Paciente = paciente Me.Filtro = filter Me.Context = context End Sub Public ReadOnly Property CITAs As EntitySet(Of CITA) Get Dim dt As New EntitySet(Of CITA) If Not Paciente Is Nothing Then dt.AddRange(CitasManager.ListadoCitasDebitoPaciente(Context, Filtro)) End If Return dt End Get End Property Public ReadOnly Property FACTURAs As EntitySet(Of FACTURA) Get Dim dt As New EntitySet(Of FACTURA) If Not Paciente Is Nothing Then dt.AddRange(FacturasManager.ListadoFACTURAsDebitoPaciente(Context, Filtro)) End If Return dt End Get End Property 'ESTO de aqui hay que cambiarlo por la referencia a la lista de RecibosManager, N_Tickets Public ReadOnly Property RECIBOs As EntitySet(Of RECIBO) Get Dim dt As New System.Data.Linq.EntitySet(Of RECIBO) If Not Paciente Is Nothing Then dt.AddRange(Paciente.RECIBOs.Where(Function(o) o.COBRADO = "N" And (Not o.REFFACTURA.HasValue Or o.REFFACTURA = 0) And o.IMPORTE > 0)) End If Return dt End Get End Property Public ReadOnly Property N_Tickets As EntitySet(Of N_Ticket) Get Dim dt As New System.Data.Linq.EntitySet(Of N_Ticket) If Not Paciente Is Nothing Then dt.AddRange(Paciente.N_Tickets.Where(Function(o) (o.Eliminado = False Or Not o.Eliminado.HasValue) And (o.Pagado = False) And o.Total > 0)) End If Return dt End Get End Property Public ReadOnly Property N_Facturas As EntitySet(Of N_Factura) Get Dim dt As New System.Data.Linq.EntitySet(Of N_Factura) If Not Paciente Is Nothing Then dt.AddRange(Paciente.N_Facturas.Where(Function(o) o.Pagado = False And o.Total > 0)) End If Return dt End Get End Property Public ReadOnly Property PagosPacientes As EntitySet(Of PagosPaciente) Get Dim dt As New System.Data.Linq.EntitySet(Of PagosPaciente) If Not Paciente Is Nothing Then 'Return FacturasManager.ListadoFACTURAsDebitoPaciente(Context, Filtro) dt.AddRange(Paciente.PagosPacientes.AsQueryable()) End If Return dt End Get End Property Public ReadOnly Property EntregasCuentas As EntitySet(Of EntregasCuenta) Get Dim dt As New System.Data.Linq.EntitySet(Of EntregasCuenta) If Not Paciente Is Nothing Then dt.AddRange(Paciente.EntregasCuentas.Where(Function(o) o.Eliminado = False)) End If Return dt End Get End Property Public ReadOnly Property Debe As Double Get 'La suma de todos los documentos Dim _debe As Double = 0 _debe += CITAs.Sum(Function(o) o.TOTAL) _debe += FACTURAs.Sum(Function(o) o.TOTAL) _debe += RECIBOs.Sum(Function(o) o.IMPORTE) _debe += N_Tickets.Sum(Function(o) o.Total) _debe += N_Facturas.Sum(Function(o) o.Total) Return _debe End Get End Property Public ReadOnly Property Credito As Double Get 'La suma de todos los documentos Dim _credito As Double = 0 _credito = PagosPacientes.Sum(Function(o) o.Importe) - EntregasCuentas.Sum(Function(o) o.Importe And o.Eliminado = False) Return _credito End Get End Property Public Function PagarDocumentos(documentos As ICollection(Of IDocumentoPagable), formDocumentos As IFormDocumentosPendientes, idFormaPagoPreseleccionada As String, idUsuarioEfectua As Integer, context As CMLinqDataContext) As DialogResult 'Se muestran los documentos a pagar al usuario, y se obtiene su respuesta, la cual incluye la forma de pago, formDocumentos.DocumentosPendientes = documentos If Not String.IsNullOrEmpty(idFormaPagoPreseleccionada) Then formDocumentos.IdFormaPagoPreseleccionada = idFormaPagoPreseleccionada End If Dim res As DialogResult '= DialogResult.OK 'formDocumentos.Importe = documentos.Sum(Function(o) o.Importe) If formDocumentos.Muestra(Me.Credito) = DialogResult.OK Then For Each doc As IDocumentoPagable In documentos res = PagarDocumento(doc, formDocumentos.IdFormaPagoSeleccionada, New Date(formDocumentos.FechaPago.Year, formDocumentos.FechaPago.Month, formDocumentos.FechaPago.Day, formDocumentos.FechaPago.Hour, formDocumentos.FechaPago.Minute, formDocumentos.FechaPago.Second), idUsuarioEfectua, formDocumentos.UsarCredito, context) If res = DialogResult.Cancel Then Return res End If Next Else res = DialogResult.Cancel End If Return res End Function Public Function PagarDocumento(doc As IDocumentoPagable, idFormaPago As String, fechacobro As Date, idUsuarioEfectua As Integer, pagarConCredito As Boolean, context As CMLinqDataContext) As DialogResult ''Es necesario hacer una salvedad con las facturas ''ya que pueden proceder de citas pagadas. Lo correcto ''es que si pagamos una factura con citas ya pagadas solo ''se inserte la diferencia entre lo ya pagado y lo no pagado. 'Dim importe As Double = 0 'If doc.TipoDocumento = TipoDocumento.Factura Then ' Dim a = context.LINEASFACTURAs.Where(Function(o) o.REFFACTURA = doc.IDDocumento).ToList 'End If 'Validaciones If doc.Pagado Then MessageBox.Show("Error: El documento ya está marcado como pagado") Return DialogResult.Cancel End If If pagarConCredito And Globales.Configuracion.UsarPacienteDebitoAlPagar Then Dim credito As Double = DameCreditoPaciente(doc.IDPaciente, context) If credito < doc.Importe Then MessageBox.Show(String.Format("Error: Crédito {0} insuficiente para cubrir el importe {1}", credito, doc.Importe)) Return DialogResult.Cancel End If End If Dim res As DialogResult = DialogResult.OK doc.PagadoConCredito = pagarConCredito If Globales.Configuracion.UsarPacienteDebitoAlPagar Then If Not pagarConCredito Then Dim pago As New PagosPaciente With { .Fecha = fechacobro, .IDFormaPago = idFormaPago, .IDPaciente = doc.IDPaciente, .IDUsuario = idUsuarioEfectua, .Importe = doc.Importe, .Automatico = True, .Notas = "Pago para cubrir " & doc.DescripcionDocumento } context.PagosPacientes.InsertOnSubmit(pago) context.SubmitChanges() Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Insertar, RoleManager.Items.PagosPaciente, "Pago paciente", pago.IDEntrega, "Pago paciente para cubrir " & doc.DescripcionDocumento) End If Else 'Si el usuario no usa el PacienteDebito, entonces crear un pago ficticio Dim pago As New PagosPaciente With { .Fecha = fechacobro, .IDFormaPago = idFormaPago, .IDPaciente = doc.IDPaciente, .IDUsuario = idUsuarioEfectua, .Importe = doc.Importe, .Automatico = True, .Notas = "Pago de sistema para -> " & doc.DescripcionDocumento } context.PagosPacientes.InsertOnSubmit(pago) context.SubmitChanges() Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Insertar, RoleManager.Items.PagosPaciente, "Sistema, Pago paciente", pago.IDEntrega, "Pago para compensar entrega pq no se usa el Paciente Debito") End If Dim entrega As New EntregasCuenta With { .CodDocumento = doc.IDDocumento, .Descripcion = "Pago de " & doc.DescripcionDocumento, .Eliminado = False, .Fecha = fechacobro, .IDFormaPago = idFormaPago, .IDPaciente = doc.IDPaciente, .IDUsuarioEfectua = idUsuarioEfectua, .Importe = doc.Importe, .PagadoConCredito = pagarConCredito, .TipoDocumento = doc.TipoDocumento } context.EntregasCuentas.InsertOnSubmit(entrega) context.SubmitChanges() If res = DialogResult.OK Then doc.MarcarPagado(fechacobro, idFormaPago) context.SubmitChanges() Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Pagar, doc.TipoDocumento, doc.TipoDocumento.ToString(), doc.IDDocumento, doc.DescripcionDocumento) End If Return res End Function Public Shared Function DameImporteEntregasPaciente(ByVal idPaciente As Integer, context As CMLinqDataContext) As Double Dim importe As Double = 0 Dim entregas As List(Of EntregasCuenta) = (From e In context.EntregasCuentas Where e.IDPaciente = idPaciente And e.Eliminado = False Select e).ToList() If entregas.Count > 0 Then importe = entregas.Sum(Function(ob) ob.Importe).Value End If Return importe End Function Public Shared Function DamePagosPaciente(ByVal idPaciente As Integer, context As CMLinqDataContext) As Double Dim importe As Double = 0 Dim pagos As List(Of PagosPaciente) = (From p In context.PagosPacientes Where p.IDPaciente = idPaciente Select p).ToList() If pagos.Count > 0 Then importe = pagos.Sum(Function(ob) ob.Importe).Value End If Return importe End Function Public Shared Function DameCreditoPaciente(ByVal idPaciente As Integer, context As CMLinqDataContext) As Double Return DamePagosPaciente(idPaciente, context) - DameImporteEntregasPaciente(idPaciente, context) End Function Public Shared Sub Despagar(ByVal doc As IDocumentoPagable) Dim context As New CMLinqDataContext If (Not doc.PagadoConCredito) Then Dim pago As New PagosPaciente With { .Fecha = Now, .IDPaciente = doc.IDPaciente, .IDUsuario = Globales.Usuario.CODIGO, .Importe = doc.Importe * -1, .IDFormaPago = doc.IDFormaPago, .Automatico = True, .Notas = "Abono de sistema al cancelar pago de documento -> " & doc.DescripcionDocumento } context.PagosPacientes.InsertOnSubmit(pago) Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Despagar, doc.TipoDocumento, doc.TipoDocumento.ToString(), doc.IDDocumento, "Abono de crédito por cambiar estado de pago -> " & doc.DescripcionDocumento) End If Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Despagar, doc.TipoDocumento, doc.TipoDocumento.ToString(), doc.IDDocumento, "Eliminado pago -> " & doc.DescripcionDocumento) Dim entregas As List(Of EntregasCuenta) entregas = context.EntregasCuentas.Where(Function(o) o.TipoDocumento = doc.TipoDocumento And o.CodDocumento = doc.IDDocumento And o.Eliminado = False And o.Importe = doc.Importe).ToList For Each i As EntregasCuenta In entregas i.Eliminado = True Next context.SubmitChanges() End Sub End Class Partial Public Class CITA Implements IDocumentoPagable Public ReadOnly Property IDDocumento As String Implements IDocumentoPagable.IDDocumento Get Return Me.IDCITA.ToString End Get End Property Public ReadOnly Property DescripcionDocumento As String Implements IDocumentoPagable.DescripcionDocumento Get Return String.Format("Cita {0}-{1} Paciente: {2} Doctor: {3}", Me.FECHA.Value.ToShortDateString(), Me.HORA.Value.ToShortTimeString(), Me.PACIENTE, Me.MEDICO.NOMBRECOMPLETO) End Get End Property Public ReadOnly Property Importe As Double Implements IDocumentoPagable.Importe Get If Me.TOTAL Is Nothing Then Return 0 Else Return Me.TOTAL End If End Get End Property Public Sub MarcarDespagado() Implements IDocumentoPagable.MarcarDespagado Me.PAGADA = "N" PacienteDebitoManager.Despagar(Me) End Sub Public Sub MarcarPagado(fecha As Date, Optional idFormaPago As String = "") Implements IDocumentoPagable.MarcarPagado Me.PAGADA = "S" Me.FECHACOBRO = fecha If (Not idFormaPago Is Nothing) AndAlso idFormaPago.Trim.Length > 0 Then ' Se adopta esta formula deacuerdo con lo leido en 'http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/21/linq-to-sql-error-foreignkeyreferencealreadyhasvalueexception.aspx Me._FORMASPAGO = CType(Nothing, EntityRef(Of FORMASPAGO)) Me.REFFORMAPAGO = idFormaPago End If End Sub Function PagadoDoc() As Boolean Implements IDocumentoPagable.Pagado Return (Me.PAGADA = "S") End Function Public ReadOnly Property IDPaciente As Integer Implements IDocumentoPagable.IDPaciente Get Return Me.REFPACIENTE End Get End Property Public ReadOnly Property IDFormaPago As String Implements IDocumentoPagable.IDFormaPago Get Return Me.REFFORMAPAGO End Get End Property Public ReadOnly Property TipoDocumento As PacienteDebitoManager.TipoDocumento Implements IDocumentoPagable.TipoDocumento Get Return PacienteDebitoManager.TipoDocumento.Cita End Get End Property Public Property PagadoCredito() As Boolean Implements IDocumentoPagable.PagadoConCredito Get Return Me.PagadoConCredito End Get Set(ByVal value As Boolean) Me.PagadoConCredito = value End Set End Property End Class Partial Public Class FACTURA Implements IDocumentoPagable Private Function importeCitasPagadas() As Double Dim importeCitas As Double = 0 importeCitas = Me.LINEASFACTURAs.Where(Function(o) Not o.CITA Is Nothing AndAlso o.CITA.PAGADA = "S").Sum(Function(e) e.IMPORTE) Return importeCitas End Function Public ReadOnly Property IDDocumento As String Implements IDocumentoPagable.IDDocumento Get Return Me.IDFACTURA.ToString End Get End Property Public ReadOnly Property DescripcionDocumento As String Implements IDocumentoPagable.DescripcionDocumento Get Dim txt As String = "" If importeCitasPagadas() > 0 Then txt = "Resto " End If Return String.Format(txt & "Factura {0}-{1} Paciente: {2} ", Me.FEMISION.Value.ToShortDateString(), Me.NUMERO, Me.PACIENTE ) End Get End Property Public ReadOnly Property Importe As Double Implements IDocumentoPagable.Importe Get Return Me.TOTAL - importeCitasPagadas() End Get End Property Public Sub MarcarDespagado() Implements IDocumentoPagable.MarcarDespagado Me.PAGADA = "N" PacienteDebitoManager.Despagar(Me) End Sub Public Sub MarcarPagado(fecha As Date, Optional idFormaPago As String = "") Implements IDocumentoPagable.MarcarPagado Me.PAGADA = "S" Me.FECHACOBRO = fecha If (Not idFormaPago Is Nothing) AndAlso idFormaPago.Trim.Length > 0 Then 'Se opta por esta solución tal y como se explica en esta url 'http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/21/linq-to-sql-error-foreignkeyreferencealreadyhasvalueexception.aspx Me._FORMASPAGO = CType(Nothing, EntityRef(Of FORMASPAGO)) Me.REFFORMAPAGO = idFormaPago End If End Sub Function PagadoDoc() As Boolean Implements IDocumentoPagable.Pagado Return (Me.PAGADA = "S") End Function Public ReadOnly Property IDPaciente As Integer Implements IDocumentoPagable.IDPaciente Get Return Me.REFPACIENTE End Get End Property Public ReadOnly Property IDFormaPago As String Implements IDocumentoPagable.IDFormaPago Get Return Me.REFFORMAPAGO End Get End Property Public ReadOnly Property TipoDocumento As PacienteDebitoManager.TipoDocumento Implements IDocumentoPagable.TipoDocumento Get Return PacienteDebitoManager.TipoDocumento.Factura End Get End Property Public Property PagadoCredito() As Boolean Implements IDocumentoPagable.PagadoConCredito Get Return Me.PagadoConCredito End Get Set(ByVal value As Boolean) Me.PagadoConCredito = value End Set End Property End Class Partial Public Class N_TICKET Implements IDocumentoPagable Public ReadOnly Property IDDocumento As String Implements IDocumentoPagable.IDDocumento Get Return Me.ID_Ticket.ToString End Get End Property Public ReadOnly Property DescripcionDocumento As String Implements IDocumentoPagable.DescripcionDocumento Get Return String.Format("Ticket {0}-{1} Paciente: {2} ", Me.Fecha.ToShortDateString(), Me.ID_Ticket, Me.PACIENTE ) End Get End Property Public ReadOnly Property Importe As Double Implements IDocumentoPagable.Importe Get Return Me.TOTAL End Get End Property Public Sub MarcarDespagado() Implements IDocumentoPagable.MarcarDespagado Me.Pagado = False PacienteDebitoManager.Despagar(Me) End Sub Public Sub MarcarPagado(fecha As Date, Optional idFormaPago As String = "") Implements IDocumentoPagable.MarcarPagado Me.Pagado = True Me.FechaPagado = fecha If idFormaPago.Trim.Length > 0 Then 'Se opta por esta solución tal y como se explica en esta url 'http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/21/linq-to-sql-error-foreignkeyreferencealreadyhasvalueexception.aspx Me._FORMASPAGO = CType(Nothing, EntityRef(Of FORMASPAGO)) Me.ID_FormaPago = idFormaPago End If End Sub Function PagadoDoc() As Boolean Implements IDocumentoPagable.Pagado Return Me.Pagado = True End Function Public ReadOnly Property IDPaciente As Integer Implements IDocumentoPagable.IDPaciente Get Return Me.ID_Cliente End Get End Property Public ReadOnly Property IDFormaPago As String Implements IDocumentoPagable.IDFormaPago Get Return Me.ID_FormaPago End Get End Property Public ReadOnly Property TipoDocumento As PacienteDebitoManager.TipoDocumento Implements IDocumentoPagable.TipoDocumento Get Return PacienteDebitoManager.TipoDocumento.N_Tickets End Get End Property Public Property PagadoCredito() As Boolean Implements IDocumentoPagable.PagadoConCredito Get Return Me.PagadoConCredito End Get Set(ByVal value As Boolean) Me.PagadoConCredito = value End Set End Property End Class Partial Public Class N_Factura Implements IDocumentoPagable Public ReadOnly Property IDDocumento As String Implements IDocumentoPagable.IDDocumento Get Return Me.ID_Factura.ToString End Get End Property Public ReadOnly Property DescripcionDocumento As String Implements IDocumentoPagable.DescripcionDocumento Get Return String.Format("Factura TPV {0}-{1} Paciente: {2} ", Me.Fecha.Value.ToShortDateString(), Me.ID_TipoFactura & "-" & Me.Codigo, Me.PACIENTE.APELLIDO1 & " " & Me.PACIENTE.APELLIDO2 & " " & Me.PACIENTE.NOMBRE ) End Get End Property Public ReadOnly Property Importe As Double Implements IDocumentoPagable.Importe Get Return Me.Total End Get End Property Public Sub MarcarDespagado() Implements IDocumentoPagable.MarcarDespagado Me.Pagado = False PacienteDebitoManager.Despagar(Me) End Sub Public Sub MarcarPagado(fecha As Date, Optional idFormaPago As String = "") Implements IDocumentoPagable.MarcarPagado Me.Pagado = True Me.FechaPagado = fecha If idFormaPago.Trim.Length > 0 Then 'Se opta por esta solución tal y como se explica en esta url 'http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/21/linq-to-sql-error-foreignkeyreferencealreadyhasvalueexception.aspx Me._FORMASPAGO = CType(Nothing, EntityRef(Of FORMASPAGO)) Me.ID_FormaPago = idFormaPago End If End Sub Function PagadoDoc() As Boolean Implements IDocumentoPagable.Pagado Return (Me.Pagado = True) End Function Public ReadOnly Property IDPaciente As Integer Implements IDocumentoPagable.IDPaciente Get Return Me.ID_Cliente End Get End Property Public ReadOnly Property IDFormaPago As String Implements IDocumentoPagable.IDFormaPago Get Return Me.ID_FormaPago End Get End Property Public ReadOnly Property TipoDocumento As PacienteDebitoManager.TipoDocumento Implements IDocumentoPagable.TipoDocumento Get Return PacienteDebitoManager.TipoDocumento.N_Facturas End Get End Property Public Property PagadoCredito() As Boolean Implements IDocumentoPagable.PagadoConCredito Get Return Me.PagadoConCredito End Get Set(ByVal value As Boolean) Me.PagadoConCredito = value End Set End Property End Class Partial Class Liquidacion_Medico Public ReadOnly Property DescripcionText() As String Get Return "Liquidacion médico nº " & Me.ID_Liquidacion & " a " & Me.MEDICO.NOMBRECOMPLETO End Get End Property End Class Partial Class PagosPaciente Public ReadOnly Property NotasCompletas() As String Get Dim cadenas As String 'obtenemos solo los 15 primeros caracteres de notas en caso de ser mayor de 15 If Not Me.Notas Is Nothing AndAlso Me.Notas.Length >= 15 Then cadenas = Mid(Me.Notas, 1, 15) Else cadenas = Me.Notas End If Return "Entrega de " & Me.PACIENTE.NombreCompleto & " - Nota: " & cadenas End Get End Property End Class
#Region "License" ' The MIT License (MIT) ' ' Copyright (c) 2017 Richard L King (TradeWright Software Systems) ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. #End Region Public NotInheritable Class OrderSpecifier #Region "Interfaces" #End Region #Region "Events" #End Region #Region "Enums" #End Region #Region "Types" #End Region #Region "Constants" Private Const ModuleName As String = "OrderSpecifier" #End Region #Region "Member variables" Private mOrderRole As OrderRole Private mOrderType As Integer Private mPrice As Double Private mOffset As Integer Private mTriggerPrice As Double Private mTIF As Integer #End Region #Region "Constructors" Friend Sub New(pOrderRole As OrderRole, pOrderType As Integer, pPrice As Double, pOffset As Integer, pTriggerPrice As Double, pTIF As Integer) mOrderRole = pOrderRole mOrderType = pOrderType mPrice = pPrice mOffset = pOffset mTriggerPrice = pTriggerPrice mTIF = pTIF End Sub #End Region #Region "XXXX Interface Members" #End Region #Region "XXXX Event Handlers" #End Region #Region "Properties" Friend ReadOnly Property OrderRole() As OrderRole Get OrderRole = mOrderRole End Get End Property Friend ReadOnly Property OrderType() As Integer Get OrderType = mOrderType End Get End Property Friend ReadOnly Property Price() As Double Get Price = mPrice End Get End Property Friend ReadOnly Property Offset() As Integer Get Offset = mOffset End Get End Property Friend ReadOnly Property TriggerPrice() As Double Get TriggerPrice = mTriggerPrice End Get End Property Friend ReadOnly Property TIF() As Integer Get TIF = mTIF End Get End Property #End Region #Region "Methods" #End Region #Region "Helper Functions" #End Region End Class
Imports System.ComponentModel.DataAnnotations Public Class CarnetClientViewModel Public Property Id As Long <Required(ErrorMessageResourceType:=GetType(Resource), ErrorMessageResourceName:="champ_Manquant")> Public Property ClientId As Long Public Overridable Property IDsClient As List(Of SelectListItem) Public Overridable Property client As Client <Required(ErrorMessageResourceType:=GetType(Resource), ErrorMessageResourceName:="champ_Manquant")> Public Property TypeCarnetId As Long Public Overridable Property IDsTypeCarnet As List(Of SelectListItem) Public Overridable Property typeCarnet As TypeCarnet Public Property Etat As Boolean = False Public Property DateAffectation As DateTime? = Now Public Sub New() End Sub Public Sub New(entity As CarnetClient) With Me .Id = entity.Id .ClientId = entity.ClientId .TypeCarnetId = entity.TypeCarnetId .Etat = entity.Etat .DateAffectation = entity.DateAffectation End With End Sub Public Function getEntity() As CarnetClient Dim entity As New CarnetClient With entity .Id = Me.Id .ClientId = Me.ClientId .TypeCarnetId = Me.TypeCarnetId .Etat = Me.Etat .DateAffectation = Me.DateAffectation End With Return entity End Function End Class
Namespace data.dao Public Class EntityFiller(Of T) Inherits data.dao.OleDBConnectionObj Private _Entity As T Private _DataBase As String Public Property DataBase() As String Get Return _DataBase End Get Set(ByVal value As String) _DataBase = value End Set End Property Public ReadOnly Property Entity() Get Return _Entity End Get End Property Public Sub FillList(ByVal list As List(Of T), ByVal table As String, ByVal query As QueryBuilder(Of T)) Try OpenDB(_DataBase) connection.Command = New OleDb.OleDbCommand(query.Query, connection.Connection) connection.Adap = New OleDb.OleDbDataAdapter(connection.Command) Dim dts As New DataSet connection.Adap.Fill(dts) If dts.Tables.Count > 0 Then If dts.Tables(0).Rows.Count > 0 Then For Each row As DataRow In dts.Tables(0).Rows Dim _item = CreateNewItemAsT(Of T)() For Each member In _item.GetType.GetProperties If member.CanWrite Then 'If member.PropertyType.Name = "String" Or member.PropertyType.Name = "Int32" Or member.PropertyType.Name = "DateTime" Or member.PropertyType.Name = "Boolean" Then If Not IsDBNull(row(member.Name)) Then If member.PropertyType.Name = "String" Then member.SetValue(_item, row(member.Name).ToString, Nothing) End If If member.PropertyType.Name = "Int32" Then member.SetValue(_item, Integer.Parse(row(member.Name)), Nothing) End If If member.PropertyType.Name = "Double" Then member.SetValue(_item, Double.Parse(row(member.Name)), Nothing) End If If member.PropertyType.Name = "DateTime" Then member.SetValue(_item, Date.Parse(row(member.Name)), Nothing) End If If member.PropertyType.Name = "Boolean" Then member.SetValue(_item, Boolean.Parse(row(member.Name)), Nothing) End If End If 'End If End If Next list.Add(_item) Next End If End If Catch ex As Exception Throw Finally CloseDB() End Try End Sub Public Sub FillList(ByVal list As List(Of T), ByVal query As String) Try OpenDB(_DataBase) connection.Command = New OleDb.OleDbCommand(query, connection.Connection) connection.Adap = New OleDb.OleDbDataAdapter(connection.Command) Dim dts As New DataSet connection.Adap.Fill(dts) If dts.Tables.Count > 0 Then If dts.Tables(0).Rows.Count > 0 Then For Each row As DataRow In dts.Tables(0).Rows Dim _item = CreateNewItemAsT(Of T)() For Each member In _item.GetType.GetProperties If member.CanWrite Then If member.PropertyType.Name = "String" Or member.PropertyType.Name = "Int32" Or member.PropertyType.Name = "DateTime" Or member.PropertyType.Name = "Boolean" Then If Not IsDBNull(row(member.Name)) Then If member.PropertyType.Name = "String" Then member.SetValue(_item, row(member.Name).ToString, Nothing) End If If member.PropertyType.Name = "Int32" Then member.SetValue(_item, Integer.Parse(row(member.Name)), Nothing) End If End If End If End If Next list.Add(_item) Next End If End If Catch ex As Exception Throw Finally CloseDB() End Try End Sub Public Sub FillObj(ByVal _item As T, ByVal table As String, ByVal query As QueryBuilder(Of T)) Try OpenDB(_DataBase) connection.Command = New OleDb.OleDbCommand(query.Query, connection.Connection) connection.Adap = New OleDb.OleDbDataAdapter(connection.Command) Dim dts As New DataSet connection.Adap.Fill(dts) If dts.Tables.Count > 0 Then If dts.Tables(0).Rows.Count > 0 Then For Each row As DataRow In dts.Tables(0).Rows For Each member In _item.GetType.GetProperties If member.CanWrite Then If member.PropertyType.Name = "String" Or member.PropertyType.Name = "Int32" Or member.PropertyType.Name = "DateTime" Or member.PropertyType.Name = "Boolean" Then If Not IsDBNull(row(member.Name)) Then If member.PropertyType.Name = "String" Then member.SetValue(_item, row(member.Name).ToString, Nothing) End If If member.PropertyType.Name = "Int32" Then member.SetValue(_item, Integer.Parse(row(member.Name)), Nothing) End If End If End If End If Next Next End If End If Catch ex As Exception Throw Finally CloseDB() End Try End Sub Public Sub FillObj(ByVal _item As T, ByVal query As String) Try OpenDB(_DataBase) connection.Command = New OleDb.OleDbCommand(query, connection.Connection) connection.Adap = New OleDb.OleDbDataAdapter(connection.Command) Dim dts As New DataSet connection.Adap.Fill(dts) If dts.Tables.Count > 0 Then If dts.Tables(0).Rows.Count > 0 Then For Each row As DataRow In dts.Tables(0).Rows For Each member In _item.GetType.GetProperties If member.CanWrite Then If member.PropertyType.Name = "String" Or member.PropertyType.Name = "Int32" Or member.PropertyType.Name = "DateTime" Or member.PropertyType.Name = "Boolean" Then If Not IsDBNull(row(member.Name)) Then If member.PropertyType.Name = "String" Then member.SetValue(_item, row(member.Name).ToString, Nothing) End If If member.PropertyType.Name = "Int32" Then member.SetValue(_item, Integer.Parse(row(member.Name)), Nothing) End If End If End If End If Next Next End If End If Catch ex As Exception Throw Finally CloseDB() End Try End Sub Public Function CreateNewItemAsT(Of T)() As T Dim tmp As T = GetType(T).GetConstructor(New System.Type() {}).Invoke(New Object() {}) Return tmp End Function End Class End Namespace
Imports System.Reflection Imports SkyEditor.Core Imports SkyEditor.Core.Projects Imports SkyEditor.Core.UI Imports SkyEditor.Core.Utilities Imports SkyEditor.UI.WPF.ViewModels.Projects Namespace MenuActions.Context Public Class ProjectNewFile Inherits MenuAction Public Sub New(pluginManager As PluginManager, applicationViewModel As ApplicationViewModel) MyBase.New({My.Resources.Language.MenuCreateFile}) IsContextBased = True CurrentApplicationViewModel = applicationViewModel CurrentPluginManager = pluginManager End Sub Public Property CurrentApplicationViewModel As ApplicationViewModel Public Property CurrentPluginManager As PluginManager Public Overrides Sub DoAction(targets As IEnumerable(Of Object)) For Each item In targets Dim currentPath As String Dim parentProject As Project If TypeOf item Is SolutionHeiarchyItemViewModel Then currentPath = "" parentProject = DirectCast(item, SolutionHeiarchyItemViewModel).GetNodeProject ElseIf TypeOf item Is ProjectHeiarchyItemViewModel Then currentPath = DirectCast(item, ProjectHeiarchyItemViewModel).CurrentPath parentProject = DirectCast(item, ProjectHeiarchyItemViewModel).Project Else Throw New ArgumentException(String.Format(My.Resources.Language.ErrorUnsupportedType, item.GetType.Name)) End If Dim w As New NewFileWindow Dim types As New Dictionary(Of String, Type) For Each supported In parentProject.GetSupportedFileTypes(currentPath, CurrentPluginManager) types.Add(ReflectionHelpers.GetTypeFriendlyName(supported), supported) Next w.SetGames(types) If w.ShowDialog Then parentProject.CreateFile(currentPath, w.SelectedName, w.SelectedType) End If Next End Sub Public Overrides Function GetSupportedTypes() As IEnumerable(Of TypeInfo) Return {GetType(SolutionHeiarchyItemViewModel).GetTypeInfo, GetType(ProjectHeiarchyItemViewModel).GetTypeInfo} End Function Public Overrides Function SupportsObject(obj As Object) As Task(Of Boolean) If TypeOf obj Is ProjectHeiarchyItemViewModel Then Dim node As ProjectHeiarchyItemViewModel = obj Return Task.FromResult(node.IsDirectory AndAlso node.Project.CanCreateFile(node.CurrentPath)) ElseIf TypeOf obj Is SolutionHeiarchyItemViewModel Then Dim node As SolutionHeiarchyItemViewModel = obj Return Task.FromResult(Not node.IsDirectory AndAlso node.GetNodeProject.CanCreateFile("")) Else Return Task.FromResult(False) End If End Function End Class End Namespace
Imports System.ComponentModel.DataAnnotations Imports System.Text.RegularExpressions Namespace Route4MeSDK ''' <summary> ''' Validation of the class properties ''' </summary> Public NotInheritable Class PropertyValidation Private Shared CountryIDs As String() = { "US", "GB", "CA", "NL", "AU", "MX", "AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "BN", "BG", "BF", "BI", "KH", "CM", "CV", "KY", "TD", "CL", "CN", "CX", "CO", "KM", "CG", "CK", "CR", "HR", "CU", "CY", "CZ", "CD", "DK", "DJ", "DM", "DO", "TP", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP", "JO", "KZ", "KE", "KI", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "FM", "MD", "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "KP", "NO", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "KN", "LC", "WS", "SM", "SA", "SN", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "ES", "LK", "SH", "PM", "SD", "SR", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "UM", "UY", "UZ", "VU", "VA", "VE", "VN", "VG", "VI", "WF", "YE", "YU", "ZM", "ZW"} Private Shared UsaStateIDs As String() = { "AK", "AL", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY", "AE", "CA", "AB", "BC", "MB", "NB", "NL", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT"} Private Shared AddressStopTypes As String() = { "DELIVERY", "PICKUP", "BREAK", "MEETUP", "SERVICE", "VISIT", "DRIVEBY"} Public Shared Function ValidateMonthlyNthN(ByVal N As Integer) As ValidationResult Dim nList As Integer() = {1, 2, 3, 4, 5, -1} If Array.IndexOf(nList, N) >= 0 Then Return ValidationResult.Success Else Return New ValidationResult("The selected option is not available for this type of the schedule.") End If End Function Public Shared Function ValidateScheduleMode(ByVal sMode As String) As ValidationResult Dim sList As String() = {"daily", "weekly", "monthly", "annually"} If Array.IndexOf(sList, sMode) >= 0 Then Return ValidationResult.Success Else Return New ValidationResult("The selected option is not available for this type of the schedule.") End If End Function Public Shared Function ValidateScheduleMonthlyMode(ByVal sMode As String) As ValidationResult Dim sList As String() = {"dates", "nth"} If Array.IndexOf(sList, sMode) >= 0 Then Return ValidationResult.Success Else Return New ValidationResult("The selected option is not available for this type of the schedule.") End If End Function Public Shared Function ValidateEpochTime(ByVal value As Object) As ValidationResult Dim iTime As Integer = 0 If Integer.TryParse(value.ToString(), iTime) AndAlso value.[GetType]().ToString() <> "System.String" Then Return ValidationResult.Success Else Return New ValidationResult("The property time can not have the value " & value.ToString()) End If End Function Public Shared Function ValidateOverrideAddresses(ByVal value As Object) As ValidationResult Try Dim oaddr As Route4MeSDK.DataTypes.OverrideAddresses = CType(value, Route4MeSDK.DataTypes.OverrideAddresses) Return ValidationResult.Success Catch ex As Exception Console.WriteLine("Validation of the override_addresses's value failed. " & ex.Message) Return New ValidationResult("The property override_addresses can not have the value " & value.ToString()) End Try End Function Public Shared Function ValidateLatitude(ByVal value As Object) As ValidationResult If value Is Nothing Then Return Nothing Dim ___ As Double = Nothing Try If Double.TryParse(value.ToString(), ___) Then Dim lat As Double = Convert.ToDouble(value) Return If( lat >= -90 AndAlso lat <= 90, ValidationResult.Success, New ValidationResult("The latitude value is wrong: " & (If(value?.ToString(), "null"))) ) Else Return New ValidationResult("The latitude value is wrong: " & (If(value?.ToString(), "null"))) End If Catch ex As Exception Return New ValidationResult("The latitude value is wrong: " & (If(value?.ToString(), "null")) & $". Exception: {ex.Message}") End Try End Function Public Shared Function ValidateLongitude(ByVal value As Object) As ValidationResult If value Is Nothing Then Return Nothing Dim ___ As Double = Nothing Try If Double.TryParse(value.ToString(), ___) Then Dim lng As Double = Convert.ToDouble(value) Return If(lng >= -180 AndAlso lng <= 180, ValidationResult.Success, New ValidationResult("The longitude value is wrong: " & (If(value?.ToString(), "null")))) Else Return New ValidationResult("The longitude value is wrong: " & (If(value?.ToString(), "null"))) End If Catch ex As Exception Return New ValidationResult("The longitude value is wrong: " & (If(value?.ToString(), "null")) & $". Exception: {ex.Message}") End Try End Function Public Shared Function ValidateTimeWindow(ByVal value As Object) As ValidationResult If value Is Nothing Then Return Nothing Dim ___ As Long = Nothing Try If Long.TryParse(value.ToString(), ___) Then Dim tw As Long = Convert.ToInt64(value) Return If( tw >= 0 AndAlso tw <= 86400, ValidationResult.Success, New ValidationResult("The time window value is wrong: " & (If(value?.ToString(), "null"))) ) Else Return New ValidationResult("The time window value is wrong: " & (If(value?.ToString(), "null"))) End If Catch ex As Exception Return New ValidationResult("The time window value is wrong: " & (If(value?.ToString(), "null")) & $". Exception: {ex.Message}") End Try End Function Public Shared Function ValidateCsvTimeWindow(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing Dim pattern As String = "^[0-1]{0,1}[0-9]{1}\:[0-5]{1}[0-9]{1}$" Dim regex As Regex = New Regex(pattern) Dim match As Match = regex.Match(value.ToString()) Return If( match.Success, ValidationResult.Success, New ValidationResult("The CSV time window value is wrong: " & value.ToString()) ) End Function Public Shared Function ValidateServiceTime(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing Dim ___ As Long = Nothing If Not Long.TryParse(value.ToString(), ___) Then Return New ValidationResult("The csv service time must be integer: " & value.ToString()) End If Dim servtime As Integer = Convert.ToInt32(value) Return If( servtime >= 0 AndAlso servtime < 28800, ValidationResult.Success, New ValidationResult("The CSV service time value is wrong: " & value.ToString()) ) End Function Public Shared Function ValidateCsvServiceTime(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(Integer) Then Return New ValidationResult("The csv service time must be integer: " & value.ToString()) End If Dim servtime As Integer = Convert.ToInt32(value) Return If( servtime >= 0 AndAlso servtime < 480, ValidationResult.Success, New ValidationResult("The CSV service time value is wrong: " & value.ToString()) ) End Function Public Shared Function ValidateCountryId(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The country ID must be a string: " & value.ToString()) End If Dim v As String = value.ToString().ToUpper() Return If( CountryIDs.Contains(v), ValidationResult.Success, New ValidationResult("The country ID value is wrong: " & value.ToString()) ) End Function Public Shared Function ValidationStateId(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The state ID must be a string: " & value.ToString()) End If Dim v As String = value.ToString().ToUpper() Return If( UsaStateIDs.Contains(v), ValidationResult.Success, New ValidationResult("The state ID value is not USA state ID: " & value.ToString()) ) End Function Public Shared Function ValidateEmail(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The email must be a string: " & value.ToString()) End If Dim regex As Regex = New Regex("^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*" & "@" & "((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") Dim match As Match = regex.Match(value.ToString()) Return If( match.Success, ValidationResult.Success, New ValidationResult("The email is wrong: " & value.ToString()) ) End Function Public Shared Function ValidatePhone(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing Dim pattern As String = "^(\+\s{0,1}){0,1}(\(\d{1,3}\)|\d{1,3}){1}[ |-]{1}(\d{2,4}[ |.|-]{1})(\d{2,5}[ |.|-]{0,1}){1}(\d{2,5}[ |.|-]{0,1}){0,1}(\d{2,5}[ |.|-]{0,1}){0,1}$" If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The phone number must be a string: " & value.ToString()) End If Dim regex As Regex = New Regex(pattern) Dim match As Match = regex.Match(value.ToString()) Return If( match.Success, ValidationResult.Success, New ValidationResult("The phone number is wrong: " & value.ToString())) End Function Public Shared Function ValidateZipCode(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The zip code must be a string: " & value.ToString()) Dim regex As Regex = New Regex("^\d{4,5}(-\d{4})?$") Dim match As Match = regex.Match(value.ToString()) Return If( match.Success, ValidationResult.Success, New ValidationResult("The zip code is wrong: " & value.ToString()) ) End Function Public Shared Function ValidateAddressStopType(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The address stop type must be a string: " & value.ToString()) End If Dim v As String = value.ToString().ToUpper() Return If( AddressStopTypes.Contains(v), ValidationResult.Success, New ValidationResult("The address stop type value is wrong: " & value.ToString()) ) End Function Public Shared Function ValidateFirstName(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The first name must be a string: " & value.ToString()) End If Return If( value.ToString().Length <= 25, ValidationResult.Success, New ValidationResult("The first name length should be < 26: " & value.ToString()) ) End Function Public Shared Function ValidateLastName(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The last name must be a string: " & value.ToString()) End If Return If( value.ToString().Length <= 35, ValidationResult.Success, New ValidationResult("The last name length should be < 26: " & value.ToString()) ) End Function Public Shared Function ValidateColorValue(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing If value.[GetType]() <> GetType(String) Then Return New ValidationResult("The color must be a string: " & value.ToString()) End If Dim pattern As String = "^[a-fA-F0-9]{6}$" Dim regex As Regex = New Regex(pattern) Dim match As Match = regex.Match(value.ToString()) Return If( match.Success, ValidationResult.Success, New ValidationResult("The color value is wrong: " & value.ToString()) ) End Function Public Shared Function ValidateCustomData(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing Try Dim val = R4MeUtils.ReadObjectNew(Of Dictionary(Of String, String))(value.ToString()) Return If( val IsNot Nothing, ValidationResult.Success, New ValidationResult("The custom data is wrong: " & value.ToString()) ) Catch ex As Exception Return New ValidationResult("The custom data is wrong: " & value.ToString() & $". Exception: {ex.Message}") End Try End Function Public Shared Function ValidateIsNumber(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing Dim ___ As Double = Nothing Return If( Double.TryParse(value.ToString(), ___), ValidationResult.Success, New ValidationResult("The value is not number: " & value.ToString()) ) End Function Public Shared Function ValidateIsBoolean(ByVal value As Object) As ValidationResult If (If(value?.ToString().Length, 0)) < 1 Then Return Nothing Dim ___ As Boolean = Nothing Return If( Boolean.TryParse(value.ToString(), ___), ValidationResult.Success, New ValidationResult("The value is not boolean: " & value.ToString()) ) End Function End Class End Namespace
#Region "Microsoft.VisualBasic::f94471f9c1cc5012920cea85718421e0, mzkit\Rscript\Library\mzkit\annotations\Mummichog.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Code Statistics: ' Total Lines: 304 ' Code Lines: 218 ' Comment Lines: 47 ' Blank Lines: 39 ' File Size: 12.18 KB ' Module Mummichog ' ' Constructor: (+1 Overloads) Sub New ' Function: CreateKEGGBackground, createMzSet, fromGseaBackground, getResultTable, GroupPeaks ' mzScore, PeakListAnnotation, queryCandidateSet ' ' /********************************************************************************/ #End Region Imports BioNovoGene.Analytical.MassSpectrometry.Math Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1 Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1.PrecursorType Imports BioNovoGene.BioDeep.MSEngine Imports BioNovoGene.BioDeep.MSEngine.Mummichog Imports Microsoft.VisualBasic.CommandLine.Reflection Imports Microsoft.VisualBasic.ComponentModel.Collection Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel Imports Microsoft.VisualBasic.Data.visualize.Network.Graph Imports Microsoft.VisualBasic.Emit.Delegates Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Math Imports Microsoft.VisualBasic.Scripting.MetaData Imports SMRUCC.genomics.Analysis.HTS.GSEA Imports SMRUCC.genomics.Assembly.KEGG.DBGET.bGetObject Imports SMRUCC.genomics.Assembly.KEGG.WebServices Imports SMRUCC.genomics.Model.Network.KEGG.ReactionNetwork Imports SMRUCC.Rsharp.Runtime Imports SMRUCC.Rsharp.Runtime.Components Imports SMRUCC.Rsharp.Runtime.Internal.Object Imports SMRUCC.Rsharp.Runtime.Interop Imports stdNum = System.Math ''' <summary> ''' Mummichog searches for enrichment patterns on metabolic network, ''' bypassing metabolite identification, to generate high-quality ''' hypotheses directly from a LC-MS data table. ''' </summary> <Package("Mummichog")> Module Mummichog Sub New() Call Internal.Object.Converts.makeDataframe.addHandler(GetType(ActivityEnrichment()), AddressOf getResultTable) End Sub Private Function getResultTable(result As ActivityEnrichment(), args As list, env As Environment) As dataframe Dim output As New dataframe With { .columns = New Dictionary(Of String, Array), .rownames = result _ .Select(Function(i) i.Name) _ .ToArray } Call output.add("description", result.Select(Function(i) i.Description)) Call output.add("Q", result.Select(Function(i) i.Q)) Call output.add("input_size", result.Select(Function(i) i.Input)) Call output.add("background_size", result.Select(Function(i) i.Background)) Call output.add("activity", result.Select(Function(i) i.Activity)) Call output.add("p-value", result.Select(Function(i) i.Fisher.two_tail_pvalue)) Call output.add("hits", result.Select(Function(i) i.Hits.JoinBy("; "))) Return output End Function ''' <summary> ''' export of the annotation score result table ''' </summary> ''' <param name="result"> ''' the annotation result which is generated from the ''' ``peakList_annotation`` function. ''' </param> ''' <returns></returns> <ExportAPI("mzScore")> Public Function mzScore(result As ActivityEnrichment(), Optional minHits As Integer = -1, Optional ignore_topology As Boolean = False) As dataframe Dim resultSet As ActivityEnrichment() = result _ .Where(Function(a) a.Input >= minHits) _ .ToArray Dim allUnion As MzQuery() = resultSet _ .Select(Function(a) a.Hits.SafeQuery) _ .IteratesALL _ .GroupBy(Function(a) MzQuery.ReferenceKey(a)) _ .Select(Function(a) a.First) _ .ToArray Dim scores As New dataframe With {.columns = New Dictionary(Of String, Array)} Dim unionScore As New Dictionary(Of String, Double) For Each a As MzQuery In allUnion Call unionScore.Add(MzQuery.ReferenceKey(a), 0) Next For Each pathway As ActivityEnrichment In resultSet Dim score As Double = If(ignore_topology, 1, pathway.Activity) If pathway.Fisher.two_tail_pvalue < 1.0E-100 Then score *= 100 Else score *= -stdNum.Log10(pathway.Fisher.two_tail_pvalue) + 1 End If For Each hit In pathway.Hits.SafeQuery unionScore(MzQuery.ReferenceKey(hit)) += score Next Next Call scores.add("mz", allUnion.Select(Function(i) i.mz)) Call scores.add("mz_theoretical", allUnion.Select(Function(i) i.mz_ref)) Call scores.add("ppm", allUnion.Select(Function(i) i.ppm)) Call scores.add("unique_id", allUnion.Select(Function(i) i.unique_id)) Call scores.add("name", allUnion.Select(Function(i) i.name)) Call scores.add("precursor_type", allUnion.Select(Function(i) i.precursorType)) Call scores.add("score", allUnion.Select(Function(a) unionScore(MzQuery.ReferenceKey(a)))) Return scores End Function ''' <summary> ''' do ms1 peaks annotation ''' </summary> ''' <param name="background"> ''' the enrichment and network topology graph mode list ''' </param> ''' <param name="candidates"> ''' a set of m/z search result list based on the given background model ''' </param> ''' <param name="minhit"></param> ''' <param name="permutation"></param> ''' <param name="modelSize"></param> ''' <param name="env"></param> ''' <returns></returns> <ExportAPI("peakList_annotation")> <RApiReturn(GetType(ActivityEnrichment))> Public Function PeakListAnnotation(background As list, candidates As MzSet(), Optional minhit As Integer = 3, Optional permutation As Integer = 100, Optional modelSize As Integer = -1, Optional pinned As String() = Nothing, Optional ignore_topology As Boolean = False, Optional env As Environment = Nothing) As Object Dim models As New List(Of NamedValue(Of NetworkGraph)) Dim graph As NamedValue(Of NetworkGraph) Dim slot As list Dim println As Action(Of Object) = env.WriteLineHandler For Each name As String In background.getNames slot = background.getByName(name) graph = New NamedValue(Of NetworkGraph) With { .Name = name, .Description = slot.getValue({"desc", "description"}, env, "NA"), .Value = slot.getValue(Of NetworkGraph)({"model", "background", "graph"}, env) } If graph.Value.vertex.Count > 0 Then Call models.Add(graph) End If Next If Not pinned.IsNullOrEmpty Then Call println("a set of metabolites will pinned in the annotation loops:") Call println(pinned) End If Dim result As ActivityEnrichment() = candidates.PeakListAnnotation( background:=models, minhit:=minhit, permutation:=permutation, modelSize:=modelSize, pinned:=pinned, ignoreTopology:=ignore_topology ) Return result End Function ''' <summary> ''' ''' </summary> ''' <param name="mz"></param> ''' <param name="msData"> ''' the <see cref="IMzQuery"/> annotation engine ''' </param> ''' <param name="env"></param> ''' <returns></returns> <ExportAPI("queryCandidateSet")> <RApiReturn(GetType(MzSet))> Public Function queryCandidateSet(mz As Double(), msData As Object, Optional env As Environment = Nothing) As Object If msData Is Nothing Then Return Internal.debug.stop("the given ms compound annotation repository can not be nothing!", env) ElseIf msData.GetType.ImplementInterface(Of IMzQuery) Then Return DirectCast(msData, IMzQuery).GetCandidateSet(peaks:=mz).ToArray Else Return Message.InCompatibleType(GetType(IMzQuery), msData.GetType, env) End If End Function <ExportAPI("createMzset")> <RApiReturn(GetType(MzSet))> Public Function createMzSet(query As MzQuery(), Optional tolerance As Object = "ppm:20", Optional env As Environment = Nothing) As Object Dim mzdiff = Math.getTolerance(tolerance, env) If mzdiff Like GetType(Message) Then Return mzdiff.TryCast(Of Message) End If Dim mzgroup As NamedCollection(Of MzQuery)() = query _ .GroupBy(Function(i) i.mz, AddressOf mzdiff.TryCast(Of Tolerance).Equals) _ .ToArray Dim mzset As MzSet() = mzgroup _ .AsParallel _ .Select(Function(mz) Dim mzi As Double = mz.Select(Function(i) i.mz).Average Dim candidates = mz _ .GroupBy(Function(i) i.unique_id) _ .Select(Function(i) i.First) _ .ToArray Return New MzSet With { .mz = mzi, .query = candidates } End Function) _ .ToArray Return mzset End Function ''' <summary> ''' cast background models for ``peakList_annotation`` analysis based on ''' a given gsea background model object, this conversion will loose ''' all of the network topology information ''' </summary> ''' <param name="background"></param> ''' <returns></returns> <ExportAPI("fromGseaBackground")> Public Function fromGseaBackground(background As Background) As list Return New list With { .slots = background.clusters _ .Where(Function(c) c.members.Length > 2) _ .ToDictionary(Function(c) c.ID, Function(c) Dim slot As New list With {.slots = New Dictionary(Of String, Object)} slot.add("desc", c.names) slot.add("model", c.SingularGraph) Return CObj(slot) End Function) } End Function Friend Class MetabolicNetworkGraph : Inherits MapGraphPopulator ReadOnly reactions As ReactionTable() Sub New(reactions As IEnumerable(Of Reaction)) Me.reactions = ReactionTable.Load(reactions).ToArray End Sub Public Overrides Function CreateGraphModel(map As Map) As NetworkGraph Dim allIdSet = map.shapes _ .Select(Function(a) a.IDVector) _ .IteratesALL _ .Distinct _ .ToArray Dim compounds As NamedValue(Of String)() = allIdSet _ .Where(Function(id) id.IsPattern("C\d+")) _ .Select(Function(cid) New NamedValue(Of String)(cid, cid, cid)) _ .ToArray Dim currentReactionIdSet As Index(Of String) = allIdSet _ .Where(Function(id) id.IsPattern("R\d+")) _ .Indexing Dim reactions = Me.reactions _ .Where(Function(r) r.entry Like currentReactionIdSet) _ .ToArray Return reactions.BuildModel(compounds, enzymaticRelated:=False, ignoresCommonList:=False, enzymeBridged:=True) End Function End Class ''' <summary> ''' create kegg pathway network graph background model ''' </summary> ''' <param name="maps"></param> ''' <param name="reactions"></param> ''' <returns></returns> <ExportAPI("kegg_background")> Public Function CreateKEGGBackground(maps As Map(), reactions As Reaction(), Optional alternative As Boolean = False) As list Dim subgraphs As NamedValue(Of NetworkGraph)() Dim networkIndex = reactions _ .GroupBy(Function(r) r.ID) _ .ToDictionary(Function(r) r.Key, Function(r) Return r.First End Function) If alternative Then subgraphs = maps.CreateBackground(New MetabolicNetworkGraph(networkIndex.Values)).ToArray Else subgraphs = maps.CreateBackground(networkIndex).ToArray End If Dim graphSet As New list With { .slots = New Dictionary(Of String, Object) } Dim model As list For Each graph As NamedValue(Of NetworkGraph) In subgraphs model = New list With { .slots = New Dictionary(Of String, Object) From { {"name", graph.Name}, {"desc", graph.Description}, {"model", graph.Value} } } Call graphSet.add(graph.Name, model) Next Return graphSet End Function <ExportAPI("group_peaks")> Public Function GroupPeaks(<RRawVectorArgument> peaktable As Object, <RRawVectorArgument(GetType(String))> Optional adducts As Object = "[M]+|[M+H]+|[M+H2O]+|[M+H-H2O]+", Optional isotopic_max As Integer = 5, Optional mzdiff As Double = 0.01, Optional delta_rt As Double = 3, Optional env As Environment = Nothing) As Object Dim peakSet As [Variant](Of Message, Peaktable()) = Math.GetPeakList(peaktable, env) Dim precursors As MzCalculator() = Math.GetPrecursorTypes(adducts, env) If peakSet Like GetType(Message) Then Return peakSet.TryCast(Of Message) End If Dim alg As New PeakCorrelation(precursors, isotopic_max) Dim groups As PeakQuery(Of Peaktable)() = alg _ .FindExactMass(peakSet.TryCast(Of Peaktable()), delta_rt, mzdiff) _ .OrderByDescending(Function(m) m.size) _ .ToArray Return groups End Function End Module
Imports System.Net.Sockets Imports System.IO Imports System.Net Public Class LFEO32 Public Shared EnableConsole = True Public Shared EnableDebug = False Public Shared EnableStack = False Public Shared EnableFileLog = True Class LFEOLogEventArgs Inherits System.EventArgs Public Sub New(ByVal Message As String, ByVal TimeStamp As Double) Me.Message = Message Me.TimeStamp = TimeStamp End Sub Public ReadOnly Message As String Public ReadOnly TimeStamp As Double End Class End Class
Module FosterOfficeModule Public Enum RTBOperations Cut = 1 Copy = 2 Paste = 3 End Enum ' ----- Data object that interfaces with the mobile software Public ProgramDataObject As New PickupTransaction.CDataExtender Public Property CustomPrintQue As New List(Of CCustomerBill) Public Sub RichEditOperations(tsm As ToolStripMenuItem, oper As RTBOperations ) Dim myItem As ToolStripMenuItem = CType(tsm, ToolStripMenuItem) Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip) Dim rtb As RichTextBox = cms.SourceControl Select Case oper Case RTBOperations.Cut rtb.Cut Case RTBOperations.Copy rtb.Copy Case RTBOperations.Paste rtb.Paste End Select End Sub End Module
Imports DTIServerControls Imports System.Configuration.ConfigurationManager Imports BaseClasses ''' <summary> ''' A Control to add login ability for the content management system. ''' Default user is: DTIAdmin ''' Default Password is: DTIPass ''' User is prompted for a new user/pw after the first login. ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("A Control to add login ability for the content management system. Default user is: DTIAdmin Default Password is: DTIPass User is prompted for a new user/pw after the first login."), ToolboxData("<{0}:LoginControl ID=""LoginControl"" runat=""server"" />")> _ Public Class LoginControl Inherits DTIServerBase #Region "Properties" ''' <summary> ''' Eumeration of the login modes. ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("Eumeration of the login modes.")> _ Public Enum LoginModes EditOn = 0 LayoutOn = 1 Preview = 2 LoggedOut = 3 End Enum ''' <summary> ''' Gets or sets the different loging modes for editing text, changing layout, and logging out of ''' the admin panel ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Gets or sets the different loging modes for editing text, changing layout, and logging out of the admin panel")> _ Public Shared Property LoginMode() As LoginModes Get If DTIServerControls.DTISharedVariables.LoggedIn Then If DTIServerControls.DTISharedVariables.AdminOn Then DTIServerControls.DTISharedVariables.LayoutOn = False Return LoginModes.EditOn ElseIf DTIServerControls.DTISharedVariables.LayoutOn Then DTIServerControls.DTISharedVariables.AdminOn = False Return LoginModes.LayoutOn Else DTIServerControls.DTISharedVariables.AdminOn = False DTIServerControls.DTISharedVariables.LayoutOn = False Return LoginModes.Preview End If Else DTIServerControls.DTISharedVariables.AdminOn = False DTIServerControls.DTISharedVariables.LayoutOn = False Return LoginModes.LoggedOut End If End Get Set(ByVal value As LoginModes) Select Case value Case LoginModes.EditOn DTIServerControls.DTISharedVariables.LoggedIn = True DTIServerControls.DTISharedVariables.AdminOn = True DTIServerControls.DTISharedVariables.LayoutOn = False Case LoginModes.LayoutOn DTIServerControls.DTISharedVariables.LoggedIn = True DTIServerControls.DTISharedVariables.LayoutOn = True DTIServerControls.DTISharedVariables.AdminOn = False Case LoginModes.LoggedOut DTIServerControls.DTISharedVariables.LoggedIn = False DTIServerControls.DTISharedVariables.AdminOn = False DTIServerControls.DTISharedVariables.LayoutOn = False Case LoginModes.Preview DTIServerControls.DTISharedVariables.LayoutOn = False DTIServerControls.DTISharedVariables.AdminOn = False DTIServerControls.DTISharedVariables.LoggedIn = True End Select End Set End Property ''' <summary> ''' Gets or sets the login state ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Gets or sets the login state")> _ Public Shared Property isLoggedIn() As Boolean Get Return DTIServerControls.DTISharedVariables.LoggedIn End Get Set(ByVal value As Boolean) If Not value Then DTIServerControls.DTISharedVariables.LayoutOn = False DTIServerControls.DTISharedVariables.AdminOn = False End If DTIServerControls.DTISharedVariables.LoggedIn = value End Set End Property Private _maxLoginAttempts As Integer = 10 ''' <summary> ''' Number of consective login failures before account is locked ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Number of consective login failures before account is locked")> _ Public Property MaxLoginAttempts As Integer Get Return _maxLoginAttempts End Get Set(value As Integer) _maxLoginAttempts = value End Set End Property Private _loginFailureWaittime As Integer = 60 ''' <summary> ''' Number of minutes to wait before being able to log back in after account it locked ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Number of minutes to wait before being able to log back in after account it locked")> _ Public Property LoginFailureWaitTime As Integer Get Return _loginFailureWaittime End Get Set(value As Integer) _loginFailureWaittime = value End Set End Property Private _DisableDefaultStyle As Boolean ''' <summary> ''' Remove defualt style of login control ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Remove defualt style of login control")> _ Public Property DisableDefaultStyle As Boolean Get Return _DisableDefaultStyle End Get Set(value As Boolean) _DisableDefaultStyle = value End Set End Property Public ReadOnly Property login As String Get Try Return Me.logUser.tbUser.Text Catch ex As Exception Return Nothing End Try End Get End Property Public ReadOnly Property password As String Get Try Return Me.logUser.tbPass.Text Catch ex As Exception Return Nothing End Try End Get End Property #End Region #Region "User Control Properties" Private _isSiteEditLogin As Boolean = True ''' <summary> ''' If true all DTIControls items (editpanel, adminpanel, sortable) will be activated for site editing ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("If true all DTIControls items (editpanel, adminpanel, sortable) will be activated for site editing")> _ Public Property isSiteEditLogin() As Boolean Get Return _isSiteEditLogin End Get Set(ByVal value As Boolean) _isSiteEditLogin = value End Set End Property Private _autoRedirect As Boolean = True ''' <summary> ''' If set to true user will automatacally be redirected back to the current page after successfull login ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("If set to true user will automatacally be redirected back to the current page after successfull login")> _ Public Property AutoRedirect() As Boolean Get Return _autoRedirect End Get Set(ByVal value As Boolean) _autoRedirect = value End Set End Property Private _loginAndEditOn As Boolean = True ''' <summary> ''' If set to true the site will be placed into Edit Mode on successfull login ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("If set to true the site will be placed into Edit Mode on successfull login")> _ Public Property LoginAndEditOn() As Boolean Get Return _loginAndEditOn End Get Set(ByVal value As Boolean) _loginAndEditOn = value End Set End Property Private _EnablePasswordStrength As Boolean = True ''' <summary> ''' Determines if the Password Strength Text is shown on creating initial login ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Determines if the Password Strength Text is shown on creating initial login")> _ Public Property EnablePasswordStrength() As Boolean Get Return _EnablePasswordStrength End Get Set(ByVal value As Boolean) _EnablePasswordStrength = value End Set End Property Private _forgotPasswordText As String = "Forgot Password?" ''' <summary> ''' Text show for the forgot password link. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks>Must set ForgotPasswordLink</remarks> <System.ComponentModel.Description("Text show for the forgot password link.")> _ Public Property ForgotPasswordText() As String Get Return _forgotPasswordText End Get Set(ByVal value As String) _forgotPasswordText = value End Set End Property Private _forgotPasswordLink As String = "" ''' <summary> ''' Url for the forgot password page ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Url for the forgot password page")> _ Public Property ForgotPasswordURL() As String Get Return _forgotPasswordLink End Get Set(ByVal value As String) _forgotPasswordLink = value End Set End Property Private _enableRememberMe As Boolean = True ''' <summary> ''' Enables remember me checkbox for loging in with cookies ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Enables remember me checkbox for loging in with cookies")> _ Public Property EnableRememberMe As Boolean Get Return _enableRememberMe End Get Set(value As Boolean) _enableRememberMe = value End Set End Property Private _RememberMeText As String = "Remember Me" ''' <summary> ''' Text to display for the Remember me checkbox ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Text to display for the Remember me checkbox")> _ Public Property RememberMeText() As String Get Return _RememberMeText End Get Set(ByVal value As String) _RememberMeText = value End Set End Property Private _rememberMeTimeout As Integer = 30 ''' <summary> ''' Number of days past current time to set cookie expiration date ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Number of days past current time to set cookie expiration date")> _ Public Property RememberMeTimeout() As Integer Get Return _rememberMeTimeout End Get Set(ByVal value As Integer) _rememberMeTimeout = value End Set End Property Private _AccountLockedMessage As String = "You Account has been locked" ''' <summary> ''' Error message to display when a account has been locked due to failed logins ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Error message to display when a account has been locked due to failed logins")> _ Public Property AccountLockedMessage() As String Get Return _AccountLockedMessage End Get Set(ByVal value As String) _AccountLockedMessage = value End Set End Property Private _LoginFailedMessage As String = "Username and/or password is incorrect" ''' <summary> ''' Error message to display on unsuccessful login ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Error message to display on unsuccessful login")> _ Public Property LoginFailedMessage() As String Get Return _LoginFailedMessage End Get Set(ByVal value As String) _LoginFailedMessage = value End Set End Property #End Region #Region "Events" ''' <summary> ''' fires on a sucessfull login ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("fires on a sucessfull login")> Public Event LoggedIn(sender As Object, e As loginEventArgs) Public Class loginEventArgs : Inherits EventArgs Public loggedInUser As dsDTIAdminPanel.DTIUsersRow End Class ''' <summary> ''' fires after logout is pressed ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("fires after logout is pressed")> _ Public Event LoggedOut() ''' <summary> ''' fires on a failed login ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("fires on a failed login")> _ Public Event LoginFailed() #End Region Private WithEvents logUser As New LoginUserControl Private Sub LoginControl_typeFirstInitialized(ByVal t As System.Type) Handles Me.typeFirstInitialized If AppSettings("DTIAdminUser") Is Nothing AndAlso _ AppSettings("DTIAdminPass") Is Nothing Then sqlhelper.checkAndCreateTable(New dsDTIAdminPanel.DTIUsersDataTable) End If End Sub Private Sub LoginControl_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Dim pantheman As New Panel Me.Controls.Add(pantheman) logUser = CType(Me.Page.LoadControl("~/res/DTIAdminPanel/LoginUserControl.ascx"), LoginUserControl) With logUser .AutoRedirect = AutoRedirect .LoginAndEditOn = LoginAndEditOn .EnablePasswordStrength = EnablePasswordStrength .ForgotPasswordLink = ForgotPasswordURL .ForgotPasswordText = ForgotPasswordText .EnableRememberMe = EnableRememberMe .RememberMeText = RememberMeText .RememberMeTimeout = RememberMeTimeout .isSiteEditLogin = isSiteEditLogin .MaxLoginAttempts = MaxLoginAttempts .LoginFailureWaitTime = LoginFailureWaitTime .MainID = MainID End With pantheman.Controls.Add(logUser) If Not DisableDefaultStyle Then jQueryLibrary.jQueryInclude.addStyleBlock(Page, ".Kurk-login {width:240px} " & _ ".Kurk-Spacer {clear:both; height:10px} " & _ ".Kurk-Error {width: 240px} " & _ ".Kurk-tbUser {width: 240px} " & _ ".Kurk-tbPass { width: 240px} " & _ ".Kurk-Remember {font-size: .8em;float:left} " & _ ".Kurk-btnLogin {float:right} " & _ ".Kurk-Forgot {font-size: .8em} ") End If End Sub #Region "Event Handling" Private Sub logUser_LoggedIn(ByVal LoggedInUser As dsDTIAdminPanel.DTIUsersRow) Handles logUser.LoggedIn Dim e As New loginEventArgs e.loggedInUser = LoggedInUser RaiseEvent LoggedIn(Me, e) End Sub Private Sub logUser_LoginFailed() Handles logUser.LoginFailed RaiseEvent LoginFailed() End Sub Private Sub logUser_LoggedOut() Handles logUser.LoggedOut RaiseEvent LoggedOut() End Sub #End Region #Region "private shared" Private Shared Function isMemberLocked(ByRef user As dsDTIAdminPanel.DTIUsersRow, ByVal LoginFailureWaittime As Integer) As Boolean If LoginFailureWaittime = -1 Then Return False If user.IsLockoutDateTimeNull Then Return False Else Return user.LockoutDateTime > Now.AddMinutes(-1 * LoginFailureWaittime) End If End Function Private Shared Sub UpdateLastLogin(ByRef CurrentUser As dsDTIAdminPanel.DTIUsersRow) If CurrentUser IsNot Nothing Then 'CurrentUser.Guid = Guid.NewGuid.ToString CurrentUser.LastLoginDate = CurrentUser.LoginDate CurrentUser.LoginDate = Now CurrentUser.LastIpAddress = CurrentUser.IpAddress CurrentUser.IpAddress = HttpContext.Current.Request.UserHostAddress CurrentUser.LoginFailureCount = 0 CurrentUser.SetLockoutDateTimeNull() BaseClasses.BaseHelper.getHelper.Update(CurrentUser.Table) End If End Sub Private Shared Function UpdateLoginFailure(ByRef CurrentUser As dsDTIAdminPanel.DTIUsersRow, ByVal MaxLoginAttempts As Integer, Optional ByVal LoginFailureWaitTime As Integer = 60) As Boolean If MaxLoginAttempts > 0 Then If CurrentUser.LoginFailureCount = MaxLoginAttempts Then CurrentUser.LoginFailureCount = 0 CurrentUser.SetLockoutDateTimeNull() End If If CurrentUser IsNot Nothing Then CurrentUser.LoginFailureCount += 1 End If If CurrentUser.LoginFailureCount = MaxLoginAttempts Then CurrentUser.LockoutDateTime = Now End If BaseClasses.BaseHelper.getHelper.Update(CurrentUser.Table) End If End Function #End Region #Region "Depricated" ''' <summary> ''' Generates a MD5 hash of a given string ''' </summary> ''' <param name="input">String to hash</param> ''' <returns>MD5 hash of String</returns> ''' <remarks></remarks> <System.ComponentModel.Description("Generates a MD5 hash of a given string"), _ Obsolete("This method is deprecated, use BaseClasses.Hashing.GetHash() instead.")> _ Public Shared Function CreateMD5Hash(ByVal input As String) As String Dim hash As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create() Dim inputBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(input) Dim hashBytes As Byte() = hash.ComputeHash(inputBytes) Dim sb As New StringBuilder() For i As Integer = 0 To hashBytes.Length - 1 sb.Append(hashBytes(i).ToString("x2")) Next Return sb.ToString() End Function ''' <summary> ''' returns id of User if username and hashed password is in table. ''' Also hashes any passwords not generated by this method and replaces password. ''' </summary> ''' <param name="dtusers"></param> ''' <param name="Username"></param> ''' <param name="password"></param> ''' <param name="salt"></param> ''' <param name="UserNameField"></param> ''' <param name="PasswordField"></param> ''' <param name="IdField"></param> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("returns true if username and hashed password is in table. Also hashes any passwords not generated by this method and replaces password."), _ Obsolete("This method is Depricated. PasswordHasher is a better alorightm but requires database changes")> _ Public Shared Function isHashedValue(ByRef dtusers As DataTable, ByVal Username As String, ByVal password As String, Optional ByVal salt As String = "", _ Optional ByVal UserNameField As String = "username", Optional ByVal PasswordField As String = "password", Optional ByVal IdField As String = "Id") As Integer Dim dv As New DataView(dtusers, UserNameField & " = '" & Username & "'", "", DataViewRowState.CurrentRows) If dv.Count > 0 Then Dim userhash As String = CreateMD5Hash(dv(0)(IdField).ToString) Dim passToHash As String = password & salt & Username.ToLower Dim hash As String = CreateMD5Hash(passToHash) & userhash dv.RowFilter = UserNameField & " = '" & Username & "' AND " & PasswordField & "='" & hash & "'" If dv.Count > 0 Then If String.Equals(dv(0)(PasswordField).ToString, hash, StringComparison.InvariantCulture) Then Return DirectCast(dv(0)(IdField), Integer) Else : Return -1 End If Else dv.RowFilter = UserNameField & " = '" & Username & "' AND " & PasswordField & "='" & password & "'" If dv.Count > 0 AndAlso String.Equals(dv(0)(PasswordField).ToString, password, StringComparison.InvariantCulture) Then Dim drows As DataRow() = dtusers.Select(IdField & "=" & dv(0)(IdField).ToString) Dim pas As String = drows(0)(PasswordField).ToString If Not pas.EndsWith(userhash) Then drows(0)(PasswordField) = CreateMD5Hash(passToHash) & userhash BaseClasses.BaseHelper.getHelper.Update(dtusers) Return DirectCast(drows(0)(IdField), Integer) Else : Return -1 End If Else : Return -1 End If End If Else Return -1 End If End Function #End Region #Region "Shared Functions" ''' <summary> ''' Checks if Users Password is correct and hashed. If password is not hashed this function will hash the ''' password ''' </summary> ''' <param name="CurrentUser">User to check</param> ''' <param name="password">Password to check</param> ''' <param name="iterations">Iterations to make if password is not hashed</param> ''' <returns>Currentuser if login successfull, Nothing if login fails</returns> ''' <remarks></remarks> <System.ComponentModel.Description("Checks if Users Password is correct and hashed. If password is not hashed this function will hash the password")> _ Public Shared Function PasswordHashAndCheck(ByRef CurrentUser As dsDTIAdminPanel.DTIUsersRow, ByVal password As String, _ Optional ByVal iterations As Integer = 5000) As dsDTIAdminPanel.DTIUsersRow If CurrentUser.Password <> password Then If Hashing.CheckPBKDF2Hash(password & CurrentUser.Username, CurrentUser.Salt, CurrentUser.Password) Then Return CurrentUser Else : Return Nothing End If Else Dim passToHash As String = password & CurrentUser.Username Dim newSalt As String = "" Dim hash As String = Hashing.SecureHash(passToHash, newSalt, iterations) CurrentUser.Password = hash CurrentUser.Salt = newSalt CurrentUser.Guid = Guid.NewGuid.ToString BaseHelper.getHelper.Update(CurrentUser.Table) Return CurrentUser End If End Function ''' <summary> ''' returns id of User if username and hashed password is in table. ''' Also hashes any passwords not generated by this method and replaces password. ''' </summary> ''' <param name="dtusers"></param> ''' <param name="Username"></param> ''' <param name="password"></param> ''' <param name="UserNameField"></param> ''' <param name="PasswordField"></param> ''' <param name="IdField"></param> ''' <param name="SaltField"></param> ''' <param name="iterations"></param> ''' <returns></returns> ''' <remarks>Requires dtusers to contain user trying to login</remarks> <System.ComponentModel.Description("returns true if username and hashed password is in table. Also hashes any passwords not generated by this method and replaces password.")> _ Public Shared Function PasswordHashAndCheck(ByRef dtusers As DataTable, ByVal Username As String, ByVal password As String, _ Optional ByVal UserNameField As String = "username", Optional ByVal PasswordField As String = "password", _ Optional ByVal IdField As String = "Id", Optional ByVal SaltField As String = "Salt", _ Optional ByVal iterations As Integer = 5000) As Integer If Username Is Nothing OrElse Username = "" OrElse password Is Nothing OrElse password = "" Then Return -1 End If Dim dv As New DataView(dtusers, UserNameField & " = '" & Username & "'", "", DataViewRowState.CurrentRows) If dv.Count = 1 Then Dim StoredPassword As String = dv(0)(PasswordField).ToString Dim storedSalt As String = dv(0)(SaltField).ToString Dim id As Integer = DirectCast(dv(0)(IdField), Integer) Username = dv(0)(UserNameField).ToString 'Dim userhash As String = Hashing.GetHash(Username, Hashing.HashTypes.MD5) 'check if password is stored in plain text dv.RowFilter = UserNameField & " = '" & Username & "' AND " & PasswordField & "='" & password & "'" If dv.Count = 0 Then 'If Hashing.CheckPBKDF2Hash(password & Username, storedSalt, StoredPassword.Replace(userhash, "")) Then If Hashing.CheckPBKDF2Hash(password & Username, storedSalt, StoredPassword) Then Return id Else : Return -1 End If Else Dim drows As DataRow() = dtusers.Select(IdField & "=" & id.ToString) 'If Not StoredPassword.EndsWith(userhash) Then Dim passToHash As String = password & Username Dim newSalt As String = "" Dim hash As String = Hashing.SecureHash(passToHash, newSalt, iterations) drows(0)(PasswordField) = hash '& userhash drows(0)(SaltField) = newSalt BaseHelper.getHelper.Update(dtusers) Return DirectCast(drows(0)(IdField), Integer) 'Else : Return -1 'End If End If ElseIf dv.Count > 1 Then Throw New Exception("Multiple users with the same username exist in the database") Else Return -1 End If End Function ''' <summary> ''' Adds user to the DTIUsersDataTable. Takes care of hashing their password ''' </summary> ''' <param name="Username"></param> ''' <param name="password"></param> ''' <param name="email"></param> ''' <param name="isAdmin"></param> ''' <param name="isActive"></param> ''' <param name="MainID"></param> ''' <param name="iterations"></param> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Adds user to the DTIUsersDataTable. Takes care of hashing their password")> _ Public Shared Function createUser(ByVal Username As String, ByVal password As String, _ ByVal email As String, Optional ByVal isAdmin As Boolean = True, Optional ByVal isActive As Boolean = True, _ Optional ByVal MainID As Long = 0, _ Optional ByVal iterations As Integer = 5000) As dsDTIAdminPanel.DTIUsersRow Dim helper As BaseHelper = BaseHelper.getHelper Dim dtusers As New dsDTIAdminPanel.DTIUsersDataTable helper.checkAndCreateTable(dtusers) Dim newUser As dsDTIAdminPanel.DTIUsersRow = dtusers.NewDTIUsersRow Dim passtoHash As String = password & Username Dim Salt As String = "" Dim hash As String = Hashing.SecureHash(passtoHash, Salt, iterations) Dim ip As String = HttpContext.Current.Request.UserHostAddress With newUser .Username = Username .Password = hash .Salt = Salt .MainID = MainID .Email = email .Guid = Guid.NewGuid.ToString .isAdmin = isAdmin .IpAddress = ip .LastIpAddress = ip .isActive = isActive .DateAdded = Now .LoginDate = Now .LastLoginDate = Now .PasswordChange = False .PasswordChangeDate = Now .SetLockoutDateTimeNull() .LoginFailureCount = 0 End With dtusers.AddDTIUsersRow(newUser) helper.Update(CType(dtusers, DataTable)) Return newUser End Function ''' <summary> ''' Processes user's login request. Return row of user if successful or nothing if not successfull. ''' Throws exception if user is required to change thier password, if their account is ''' locked due to exceeding the max login attempts, or if user doesn't exist. ''' </summary> ''' <param name="username"></param> ''' <param name="password"></param> ''' <param name="mainID"></param> ''' <param name="MaxLoginAttempts"></param> ''' <param name="LoginFailureWaitTime"></param> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Processes user's login request. Return row of user if successful or nothing if not successfull. Throws exception if user is required to change thier password, if their account is locked due to exceeding the max login attempts, or if user doesn't exist.")> _ Public Shared Function loginUser(ByVal username As String, ByVal password As String, Optional MainID As Long = 0, _ Optional ByVal MaxLoginAttempts As Integer = 10, Optional ByVal LoginFailureWaitTime As Integer = 1) As dsDTIAdminPanel.DTIUsersRow Dim dtusers As New dsDTIAdminPanel.DTIUsersDataTable Dim mainIDStr As String = " AND (MainID=0 OR MainID=@mainid)" If MainID = -1 Then mainIDStr = "" End If BaseClasses.BaseHelper.getHelper.FillDataTable("Select * from DTIUsers where username like @username" & mainIDStr, dtusers, username, MainID) If dtusers.Count >= 1 Then Dim CurrentUser As dsDTIAdminPanel.DTIUsersRow = dtusers(0) If CurrentUser.isActive AndAlso Not isMemberLocked(CurrentUser, LoginFailureWaitTime) Then CurrentUser = LoginControl.PasswordHashAndCheck(CurrentUser, password) If CurrentUser IsNot Nothing Then If CurrentUser.PasswordChange Then Throw New ChangePasswordException End If UpdateLastLogin(CurrentUser) Return CurrentUser Else UpdateLoginFailure(CurrentUser, MaxLoginAttempts, LoginFailureWaitTime) Return Nothing End If ElseIf isMemberLocked(CurrentUser, LoginFailureWaitTime) Then Throw New AccountLockedException End If ElseIf dtusers.Count > 1 Then Throw New Exception("Usernames must be unique") Else Throw New NoUserException End If Return Nothing End Function ''' <summary> ''' Changes password to new hash ''' </summary> ''' <param name="CurrentUser"></param> ''' <param name="NewPassword"></param> ''' <param name="iterations"></param> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Changes password to new hash")> _ Public Shared Function ChangePassword(ByRef CurrentUser As dsDTIAdminPanel.DTIUsersRow, ByVal NewPassword As String, _ Optional ByVal iterations As Integer = 5000) As Boolean Dim passToHash As String = NewPassword & CurrentUser.Username Dim newSalt As String = "" Dim hash As String = Hashing.SecureHash(passToHash, newSalt, iterations) With CurrentUser .Password = hash .Salt = newSalt .Guid = Guid.NewGuid.ToString .PasswordChange = False .PasswordChangeDate = Now End With BaseHelper.getHelper.Update(CurrentUser.Table) Return True End Function ''' <summary> ''' Add encrypted LoginControl cookie for automatic logins ''' </summary> ''' <param name="username">Username to save</param> ''' <param name="password">Password to save</param> ''' <param name="DaysTilExpiration">Number of days until cookie expires</param> ''' <param name="cookieName">Name of cookie</param> ''' <param name="EncryptionKey">Key used to encrypt cookie data</param> ''' <remarks></remarks> <System.ComponentModel.Description("Add encrypted LoginControl cookie for automatic logins")> _ Public Shared Sub SetUserCookie(ByVal username As String, ByVal password As String, Optional ByVal DaysTilExpiration As Integer = 30, _ Optional ByVal cookieName As String = "DTIControls", _ Optional ByVal EncryptionKey As String = "x146:GnP.2g)$UVec}x,aZj:A1l7w%Om") Dim uname As String = BaseClasses.EncryptionHelper.Encrypt(username, EncryptionKey) Dim upass As String = BaseClasses.EncryptionHelper.Encrypt(password, EncryptionKey) Dim cookie As HttpCookie = New HttpCookie(BaseSecurityPage.ValidCookieName(cookieName)) With cookie .HttpOnly = True .Values.Add("5qWwYHoxEc", uname) .Values.Add("30dO4oY5o6", upass) .Expires = DateTime.Now.AddDays(DaysTilExpiration) End With HttpContext.Current.Response.Cookies.Add(cookie) End Sub ''' <summary> ''' Decrypts LoginControl cookie ''' </summary> ''' <param name="username">Stores user's username</param> ''' <param name="password">Stores user's password</param> ''' <param name="cookieName">Name of cookie</param> ''' <param name="DecryptionKey">Key used to decrypt cookie data</param> ''' <remarks>DecryptionKey must be the same as the EncryptionKey used in SetUserCookie</remarks> <System.ComponentModel.Description("Decrypts LoginControl cookie")> _ Public Shared Sub GetUserCookie(ByRef username As String, ByRef password As String, _ Optional ByVal cookieName As String = "DTIControls", _ Optional ByVal DecryptionKey As String = "x146:GnP.2g)$UVec}x,aZj:A1l7w%Om") Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(BaseSecurityPage.ValidCookieName(cookieName)) If cookie IsNot Nothing Then Dim u As String = cookie("5qWwYHoxEc") Dim p As String = cookie("30dO4oY5o6") If u IsNot Nothing And p IsNot Nothing Then username = BaseClasses.EncryptionHelper.Decrypt(u, DecryptionKey) password = BaseClasses.EncryptionHelper.Decrypt(p, DecryptionKey) End If End If End Sub ''' <summary> ''' Marks cookie as expired so the browser will delete it. ''' </summary> ''' <param name="cookieName"></param> ''' <remarks>You cannot directly delete a cookie on a user's computer. ''' However, you can direct the user's browser to delete the cookie by ''' setting the cookie's expiration date to a past date. ''' http://msdn.microsoft.com/en-us/library/ms178195.aspx ''' </remarks> <System.ComponentModel.Description("Marks cookie as expired so the browser will delete it.")> _ Public Shared Sub RemoveCookie(Optional ByVal cookieName As String = "DTIControls") Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(BaseSecurityPage.ValidCookieName(cookieName)) If cookie IsNot Nothing Then cookie.Expires = DateTime.Now.AddDays(-1) HttpContext.Current.Response.Cookies.Add(cookie) End If End Sub ''' <summary> ''' Attempts Loing using stored cookie (if it exists) ''' </summary> ''' <param name="MainId"></param> ''' <param name="cookieName"></param> ''' <returns>CurrentUser if successful otherwise Nothing</returns> ''' <remarks></remarks> <System.ComponentModel.Description("Attempts Loing using stored cookie (if it exists)")> _ Public Shared Function CookieLogin(Optional ByVal MainId As Long = 0, Optional ByVal cookieName As String = "DTIControls") As dsDTIAdminPanel.DTIUsersRow Dim username As String = Nothing Dim password As String = Nothing GetUserCookie(username, password) If username IsNot Nothing AndAlso password IsNot Nothing Then Try Return loginUser(username, password, MainId, 1, -1) Catch ex As Exception RemoveCookie(cookieName) Return Nothing End Try End If Return Nothing End Function #End Region End Class #Region "Exceptions" Public Class ChangePasswordException Inherits Exception Public Sub New() MyBase.New("Your password has expired and needs to be changed") End Sub End Class Public Class AccountLockedException Inherits Exception Public Sub New() MyBase.New("Your account has been locked for exceeding the max number of failed logins") End Sub End Class Public Class NoUserException Inherits Exception Public Sub New() MyBase.New("This User Does not exist") End Sub End Class #End Region
#Region "Microsoft.VisualBasic::8328f7fba997a5ccebcda762369f4eb8, mzkit\src\assembly\assembly\MarkupData\mzXML\Extensions.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Code Statistics: ' Total Lines: 103 ' Code Lines: 58 ' Comment Lines: 32 ' Blank Lines: 13 ' File Size: 3.75 KB ' Module Extensions ' ' Function: AsMs2, (+2 Overloads) ExtractMzI, getName, IsIntact ' ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports System.Text Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra Imports r = System.Text.RegularExpressions.Regex Namespace MarkupData.mzXML <HideModuleName> Public Module Extensions ''' <summary> ''' 解析出色谱峰数据 ''' </summary> ''' <param name="peaks"></param> ''' <returns></returns> ''' <remarks> ''' the encoded peaks data base64 string content: ''' ''' ``` ''' [intensity,mz][intensity,mz] ''' ``` ''' </remarks> <Extension> Public Function ExtractMzI(peaks As peaks) As ms2() Dim floats#() = peaks.Base64Decode(True) Dim peaksData As ms2() = floats.AsMs2.ToArray Return peaksData End Function ''' <summary> ''' [intensity, m/z] ''' </summary> ''' <param name="floats"></param> ''' <returns></returns> <Extension> Public Function AsMs2(floats As IEnumerable(Of Double)) As IEnumerable(Of ms2) Return floats _ .Split(2) _ .Select(Function(buffer, i) Return New ms2 With { .Annotation = i + 1S, .intensity = buffer(Scan0), ' 信号强度, 归一化为 0-100 之间的数值 .mz = buffer(1) ' m/z质核比数据 } End Function) End Function ''' <summary> ''' ''' </summary> ''' <param name="scan"> ''' 可以依据扫描信号结果数据<see cref="scan.msLevel"/>来获取相应的质谱信号数据 ''' ''' + 1, MS1 一级质谱信号数据 ''' + 2, MS/MS 二级质谱信号数据 ''' </param> ''' <returns></returns> <Extension> Public Function ExtractMzI(scan As scan) As (name$, peaks As ms2()) Dim name$ = scan.getName Dim peaks As ms2() If scan.peaksCount = 0 Then peaks = {} Else peaks = scan.peaks.ExtractMzI End If Return (name, peaks) End Function <Extension> Public Function getName(scan As scan) As String Dim level$ = If(scan.msLevel = 1, "MS1", "MS/MS") Dim empty As Boolean = scan.scanType.StringEmpty AndAlso scan.polarity.StringEmpty AndAlso scan.retentionTime.StringEmpty If scan.msLevel = 0 AndAlso empty Then Return Nothing End If Dim rt As Double = PeakMs2.RtInSecond(scan.retentionTime) If scan.msLevel = 1 Then Return $"[{level}] {scan.scanType} scan_{(rt / 60).ToString("F2")}min, ({scan.polarity}) basepeak_m/z={scan.basePeakMz.ToString("F4")},totalIons={scan.totIonCurrent}" Else Return $"[{level}] {scan.scanType} Scan, ({scan.polarity}) M{CInt(scan.precursorMz.value)}T{CInt(rt)}, {scan.precursorMz.value.ToString("F4")}@{(rt / 60).ToString("F2")}min" End If End Function ''' <summary> ''' Check if the given <paramref name="mzXML"/> raw data file is intact or not? ''' </summary> ''' <param name="mzXML">The file path of the mzXML raw data file.</param> ''' <returns></returns> Public Function IsIntact(mzXML As String) As Boolean Dim tails As String = LargeTextFile.Tails(mzXML, 1024, Encoding.UTF8).Trim Return InStr(tails, "</mzXML>", CompareMethod.Binary) > 0 AndAlso r.Match(tails, "[<]sha1[>].+?[<]/sha1[>]", RegexICSng).Success End Function End Module End Namespace
Public Class vw_cliente #Region "Atributos" Private control As Object Private idPersona As Integer Private idCliente As Integer Private _mregion As region_control Private _control As cliente_control Private validacion_General As New Validaciones_Generales_Controls Private validacion As New Guardar_Control Dim id As Integer #End Region #Region "Cargar Combo" Public Sub Cargar_Regiones() _mregion = New region_control cmbregion.DataSource = _mregion.REGIONES cmbregion.DisplayMember = "REGION" cmbregion.ValueMember = "ID" End Sub Public Sub Cargar_Departamento(ByVal i As Integer) _mregion = New region_control cmbdepartamento.DataSource = _mregion.DEPARTAMENTOS(i) cmbdepartamento.DisplayMember = "Departamento" cmbdepartamento.ValueMember = "ID" End Sub Public Sub Cargar_Municipio(ByVal i As Integer) _mregion = New region_control cmbMunicipio.DataSource = _mregion.MUNICIPIOS(i) cmbMunicipio.DisplayMember = "Municipio" cmbMunicipio.ValueMember = "ID" End Sub Public Sub Cargar_Localidad(ByVal i As Integer) _mregion = New region_control cmbLocalidad.DataSource = _mregion.LOCALIDADES(i) cmbLocalidad.DisplayMember = "Localidad" cmbLocalidad.ValueMember = "ID" End Sub #End Region #Region "Acciones Secundarias" Private Sub cmbregion_SelectedIndexChanged_1(sender As System.Object, e As System.EventArgs) Handles cmbregion.SelectedIndexChanged Try id = cmbregion.SelectedValue Cargar_Departamento(id) Catch ex As Exception ' MsgBox(ex.ToString) End Try End Sub Private Sub cmbdepartamento_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbdepartamento.SelectedIndexChanged Try id = cmbdepartamento.SelectedValue Cargar_Municipio(id) Catch ex As Exception ' MsgBox(ex.ToString) End Try End Sub Private Sub cmbMunicipio_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbMunicipio.SelectedIndexChanged Try id = cmbMunicipio.SelectedValue Cargar_Localidad(id) Catch ex As Exception ' MsgBox(ex.ToString) End Try End Sub Public Sub Nuevo() tpdatos.Parent = TabControl1 TabControl1.SelectedIndex = 1 tpClientes.Parent = Nothing tpdatosadicionales.Parent = Nothing tpdireccion.Parent = Nothing NombresTextBox.Text = "" ApellidosTextBox.Text = "" CedulaTextBox.Text = "" SexoComboBox.Text = "" End Sub Public Sub Ajustar_Columnas() Vw_datosMaterialDataGridView.Columns(1).Width = 200 Vw_datosMaterialDataGridView.Columns(2).Width = 200 Vw_datosMaterialDataGridView.Columns(3).Width = 200 Vw_datosMaterialDataGridView.Columns(4).Width = 200 Vw_datosMaterialDataGridView.Columns(5).Width = 500 Vw_datosMaterialDataGridView.Columns(6).Width = 250 Vw_datosMaterialDataGridView.Columns(7).Width = 200 Vw_datosMaterialDataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter End Sub Public Sub Listar() _control = New cliente_control Vw_datosMaterialDataGridView.DataSource = _control.Listar() Ajustar_Columnas() End Sub Private Sub vw_cliente_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load TabControl2.Alignment = TabAlignment.Bottom tpdatos.Parent = Nothing tpdatosadicionales.Parent = Nothing tpdireccion.Parent = Nothing Cargar_Regiones() Listar() End Sub Private Sub btnclose_Click(sender As System.Object, e As System.EventArgs) Handles btnclose.Click Me.Close() End Sub Private Sub btnmin_Click(sender As System.Object, e As System.EventArgs) Handles btnmin.Click Me.WindowState = FormWindowState.Minimized End Sub Private Sub NuevoToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles NuevoToolStripMenuItem.Click Nuevo() End Sub Private Sub btnsig01_Click(sender As System.Object, e As System.EventArgs) Handles btnsig01.Click tpdireccion.Parent = TabControl2 TabControl2.SelectedIndex = 1 End Sub Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click tpdatosadicionales.Parent = TabControl2 TabControl2.SelectedIndex = 2 End Sub Private Sub btncancelar_Click(sender As System.Object, e As System.EventArgs) Handles btncancelar.Click tpClientes.Parent = TabControl1 TabControl1.SelectedIndex = 1 tpdatos.Parent = Nothing tpdatosadicionales.Parent = Nothing tpdireccion.Parent = Nothing End Sub Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) End Sub #End Region #Region "Guardar" Private Sub GuardarToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles GuardarToolStripMenuItem.Click If (Not (ValidarControles())) Then guardar() Nuevo() End If End Sub Private Sub btnGuardar_Click(sender As System.Object, e As System.EventArgs) Handles btnGuardar.Click If (Not (ValidarControles())) Then guardar() Nuevo() End If End Sub Private Sub guardar() _control = New cliente_control _control.insert(NombresTextBox.Text, ApellidosTextBox.Text, CedulaTextBox.Text, cmbLocalidad.SelectedIndex, TextBox1.Text, SexoComboBox.Text, NomcompaniaTextBox.Text, CorreoTextBox.Text) 'Dim row As DataGridViewRow 'For i As Integer = 0 To dgvtelefono.Rows.Count - 1 ' row = dgvtelefono.Rows(i) ' Dim telefono As telefono_control = New telefono_control ' telefono.Insert(idpersona, row.Cells(0).Value, row.Cells(1).Value)w 'Next Listar() End Sub #End Region #Region "Validaciones" #Region "Validaciones KeyPress" Private Sub NombresTextBox_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles NombresTextBox.KeyPress validacion_General.letras(e) End Sub Private Sub ApellidosTextBox_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles ApellidosTextBox.KeyPress validacion_General.letras(e) End Sub 'Private Sub txttelefono_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txttelefono.KeyPress ' validacion_General.numeros(e) 'End Sub Private Sub CedulaTextBox_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles CedulaTextBox.KeyPress e.KeyChar = UCase(e.KeyChar) End Sub #End Region '#Region "Validaciones en Tiempo Real" ' Private Sub txtcedula_Leave(sender As System.Object, e As System.EventArgs) Handles txtcedula.Leave ' Dim cedula As String ' cedula = txtcedula.Text.Replace(" ", "") ' If (cedula.Length >= 3) Then ' lblError03.Visible = (validacion.val_Cedula(txtcedula.Text)) ' Else ' lblError03.Visible = False ' End If ' End Sub ' Private Sub txtnombre_Leave(sender As System.Object, e As System.EventArgs) Handles txtnombre.Leave ' If (txtnombre.Text <> "") Then ' lblerror01.Visible = validacion.val_nombre(txtnombre.Text) ' Else ' lblerror01.Visible = False ' End If ' End Sub ' Private Sub txtapellido_Leave(sender As System.Object, e As System.EventArgs) Handles txtapellido.Leave ' If (txtapellido.Text <> "") Then ' lblerror02.Visible = validacion.val_apellido(txtapellido.Text) ' Else ' lblerror02.Visible = False ' End If ' End Sub ' Private Sub txtdireccion_Leave(sender As System.Object, e As System.EventArgs) Handles txtdireccion.Leave ' If (txtdireccion.Text <> "") Then ' lblError08.Visible = validacion.val_direccion(txtdireccion.Text) ' Else ' lblError08.Visible = False ' End If ' End Sub ' Private Sub txtcorreo_Leave(sender As System.Object, e As System.EventArgs) Handles txtcorreo.Leave ' If (txtcorreo.Text <> "") Then ' lblerror09.Visible = validacion.val_correo(txtcorreo.Text) ' Else ' lblerror09.Visible = False ' End If ' End Sub '#End Region #Region "Validaciones Guardar" Private Function ValidarControles() As Boolean Dim Cadena As String = "" Dim band As Boolean = False If (validacion.val_nombre(NombresTextBox.Text)) Then '' lblerror01.Visible = True Cadena = Cadena + "1" Else '' lblerror01.Visible = False End If If (validacion.val_apellido(ApellidosTextBox.Text)) Then '' lblerror02.Visible = True Cadena = Cadena + "1" Else '' lblerror02.Visible = False End If If (validacion.val_Cedula(CedulaTextBox.Text)) Then '' lblError03.Visible = True Cadena = Cadena + "1" Else '' lblError03.Visible = False End If If (cmbregion.Text = "") Then '' lblError04.Visible = True Cadena = Cadena + "1" Else '' lblError04.Visible = False End If If (cmbdepartamento.Text = "") Then '' lblError05.Visible = True Cadena = Cadena + "1" Else '' lblError05.Visible = False End If If (cmbmunicipio.Text = "") Then '' lblError06.Visible = True Cadena = Cadena + "1" Else '' lblError06.Visible = False End If If (validacion.val_localidad(cmblocalidad.Text)) Then '' lblError07.Visible = True Cadena = Cadena + "1" Else '' lblError07.Visible = False End If If (validacion.val_direccion(TextBox1.Text)) Then '' lblError08.Visible = True Cadena = Cadena + "1" Else '' lblError08.Visible = False End If If (validacion.val_correo(CorreoTextBox.Text)) Then '' lblerror09.Visible = True Cadena = Cadena + "1" Else '' lblerror09.Visible = False End If 'If (dgvtelefono.Rows.Count = 0) Then ' '' lblerror11.Visible = True ' Cadena = Cadena + "1" 'Else ' lblerror11.Visible = False 'End If If (Cadena.Contains("1")) Then band = True End If Return band End Function 'Function Telefono_Grid() As Boolean ' Dim Cadena As String = "" ' Dim band As Boolean = False ' If (validacion.val_operadora(cmboperadora.Text)) Then ' lblerror10.Visible = True ' Cadena = Cadena + "1" ' Else ' lblerror10.Visible = False ' End If ' If (validacion.val_telefono(txttelefono.Text)) Then ' Label1.Visible = True ' Cadena = Cadena + "1" ' Else ' Label1.Visible = False ' End If ' If (Cadena.Contains("1")) Then ' band = True ' End If ' Return band 'End Function #End Region #End Region Private Sub btntelefono_Click(sender As System.Object, e As System.EventArgs) Handles btntelefono.Click vws_telefono.ShowDialog() End Sub Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click tpdatospersonales.Parent = TabControl2 TabControl2.SelectedIndex = 1 End Sub Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click tpdireccion.Parent = TabControl2 TabControl2.SelectedIndex = 0 End Sub End Class
Imports BUS Imports DTO Public Class ui_NhapSach Dim listSach As New List(Of SachDTO) Dim listNhapSach As New List(Of NhapSachDTO) Dim STT As Integer = 0 Dim nhapThanhCong As Boolean = False Dim NgayNhap As Date ''' <summary> ''' nhập sách ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub btnNhap_Click(sender As Object, e As RoutedEventArgs) Dim sln As Integer ' số lượng nhập If (txbMaSach.Text = String.Empty) Then MessageBox.Show("Đề nghị nhập mã sách", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Information) Return End If If (txbSoLuongNhap.Text = String.Empty) Then MessageBox.Show("Đề nghị chọn mã sách", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Information) Return Else Try sln = Integer.Parse(txbSoLuongNhap.Text) Catch ex As Exception MessageBox.Show("Số lượng nhập không hợp lệ. Xin kiểm tra lại!", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Error) Return End Try End If Try NgayNhap = Date.Parse(txbNgayNhap.Text) Catch ex As Exception MessageBox.Show("Ngày nhập không hợp lệ!", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Information) Return End Try Dim checkFound As Boolean ' kiểm tra sách có trong hệ thống hay không Dim Sach As SachDTO = New DTO.SachDTO Dim nhapsachDTO As NhapSachDTO = New NhapSachDTO ' dùng để binding dữ liệu cho datagrid Try Sach = BUS.NhapSachBLL.TimSach(txbMaSach.Text, checkFound) If checkFound = True Then If (Sach.SoLuong >= ThamSoDTO.SoLuongTonToiDaTruocKhiNhap) Then MessageBox.Show("Số lượng tồn lớn hơn " + ThamSoDTO.SoLuongTonToiDaTruocKhiNhap.ToString() + ". Xin kiểm tra lại!", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error) ElseIf sln < ThamSoDTO.SoLuongNhapToiThieu Then MessageBox.Show("Số lượng nhập nhỏ hơn " + ThamSoDTO.SoLuongNhapToiThieu.ToString() + ". Xin kiểm tra lại!", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error) Else listSach.Add(Sach) ' đưa sách nhập vào list nhập sách STT = STT + 1 nhapsachDTO.STT = STT nhapsachDTO.MaSach = Sach.MaSach nhapsachDTO.TenSach = Sach.TenSach nhapsachDTO.TacGia = Sach.TacGia nhapsachDTO.SoLuongTonCu = Sach.SoLuong nhapsachDTO.SoLuongNhap = sln nhapsachDTO.SoLuongTonMoi = nhapsachDTO.SoLuongTonCu + nhapsachDTO.SoLuongNhap If (BUS.NhapSachBLL.NhapSach(nhapsachDTO, nhapsachDTO.SoLuongTonCu) = True) Then listNhapSach.Add(nhapsachDTO) 'dtgNhapSach.Items.Add(nhapsachDTO) dtgNhapSach.ItemsSource = Nothing 'cập nhập lại datagrid dtgNhapSach.Items.Clear() dtgNhapSach.ItemsSource = listNhapSach Dim MaBaoCaoTon As String = BaoCaoTonBLL.Get_MaBaoCaoTon() Dim TonDau As Integer = ChiTietTonBLL.Get_TonDau(Sach.MaSach, MaBaoCaoTon) ' lấy tồn đầu Dim TonPhatSinh As Integer = ChiTietTonBLL.Get_TonPhatSinh(Sach.MaSach, MaBaoCaoTon) If ChiTietTonBLL.SuaTonPhatSinh(Sach.MaSach, MaBaoCaoTon, sln + TonPhatSinh, TonDau) = True Then ' sửa tồn phát sinh MessageBox.Show("Nhập thành công!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information) nhapThanhCong = True Else MessageBox.Show("Nhập không thành công!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information) End If End If End If End If Catch ex As Exception MessageBox.Show(ex.Message, "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error) End Try End Sub ''' <summary> ''' tạo phiếu nhập và chi tiết phiếu nhập ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub btnHoanThanh_Click(sender As Object, e As RoutedEventArgs) If (nhapThanhCong = True) Then Dim PhieuNhap As PhieuNhapDTO = New PhieuNhapDTO() PhieuNhap.MaPhieuNhap = GetMaPN() ' sinh mã phiếu nhập PhieuNhap.NgayNhap = NgayNhap If NhapSachBLL.ThemPhieuNhap(PhieuNhap) = True Then Dim i = 0 While i < listNhapSach.Count ' duyệt list thê, chi tiết phiếu nhập Dim CTPN As ChiTietPhieuNhapDTO = New ChiTietPhieuNhapDTO() CTPN.MaChiTietPhieuNhap = GetMaCTPN() CTPN.MaPhieuNhap = PhieuNhap.MaPhieuNhap CTPN.MaSach = listNhapSach.Item(i).MaSach CTPN.SoLuongNhap = listNhapSach.Item(i).SoLuongNhap NhapSachBLL.ThemChiTietPhieuNhap(CTPN) i = i + 1 End While End If listNhapSach.Clear() dtgNhapSach.ItemsSource = Nothing dtgNhapSach.Items.Clear() nhapThanhCong = False STT = 0 MessageBox.Show("Hoàn thành", "Thông Báo", MessageBoxButton.OK, MessageBoxImage.Information) End If End Sub ''' <summary> ''' hàm sinh mã phiếu nhập từ mã phiếu nhập mới nhất ''' </summary> ''' <returns></returns> Private Function GetMaPN() As String Dim temp = NhapSachBLL.GetMaPN() If (temp <> "") Then temp = temp.Substring(temp.Length - 4) temp = (Integer.Parse(temp) + 1).ToString() Dim MaPN As String = "0000" MaPN += temp MaPN = MaPN.Substring(MaPN.Length - 4) Return "PN" + MaPN Else Return "PN0000" End If End Function ''' <summary> ''' hàm sinh mã chi tiết phiếu nhập từ mã chi tiết phiếu nhập mới nhất ''' </summary> ''' <returns></returns> Private Function GetMaCTPN() As String Dim temp = NhapSachBLL.GetMaCTPN() If (temp <> "") Then temp = temp.Substring(temp.Length - 4) temp = (Integer.Parse(temp) + 1).ToString() Dim MaCTPN As String = "0000" MaCTPN += temp MaCTPN = MaCTPN.Substring(MaCTPN.Length - 4) Return "CTPN" + MaCTPN Else Return "CTPN0000" End If End Function ''' <summary> ''' nhập từ file excel ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub btnNhapExcel_Click(sender As Object, e As RoutedEventArgs) ImportFileExcel.ImportExcel(dtgNhapSach) End Sub ''' <summary> ''' load mã sách vào listview cho người dùng xem ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub txbMaSach_TextChanged(sender As Object, e As TextChangedEventArgs) If txbMaSach.Text.Length = 0 Then lsvMaSach.Visibility = Visibility.Hidden Else Dim listMaSach As List(Of SachDTO) = TimSachBLL.TimSach(txbMaSach.Text, "", "", "", 0, Integer.MaxValue, 0, Decimal.MaxValue) lsvMaSach.Items.Clear() If listMaSach.Count > 0 Then lsvMaSach.Visibility = Visibility.Visible For Each item In listMaSach Dim i As ListViewItem = New ListViewItem() i.Content = item.MaSach i.Background = New SolidColorBrush(Color.FromArgb(100, 49, 188, 183)) lsvMaSach.Items.Add(i) Next End If End If End Sub ''' <summary> ''' gán mã sách mà người dùng chọn vào textbox mả sách ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub lsvMaSach_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Dim MaSach As String = String.Empty Try MaSach = lsvMaSach.SelectedItem.ToString().Substring(lsvMaSach.SelectedItem.ToString().Length - 6) ' cắt chuỗi để lấy mã sách ra Catch ex As Exception End Try If MaSach <> String.Empty Then txbMaSach.Text = MaSach End If lsvMaSach.Visibility = Visibility.Hidden End Sub End Class
Imports BVSoftware.Bvc5.Core Partial Class BVAdmin_Controls_MonetaryModifierField Inherits Controls.ModificationControl(Of Decimal) Implements Controls.ITextBoxBasedControl Private Enum Modes SetTo = 0 IncreaseByAmount = 1 DecreaseByAmount = 2 IncreaseByPercent = 3 DecreaseByPercent = 4 End Enum Public Sub AddTextBoxAttribute(ByVal key As String, ByVal value As String) Implements BVSoftware.Bvc5.Core.Controls.ITextBoxBasedControl.AddTextBoxAttribute MonetaryTextBox.Attributes.Add(key, value) End Sub Public Overloads Overrides Function ApplyChanges(ByVal item As Decimal) As Decimal Dim val As Decimal = 0 If Decimal.TryParse(Me.MonetaryTextBox.Text, val) Then If Me.MonetaryDropDownList.SelectedIndex = Modes.SetTo Then Return val ElseIf Me.MonetaryDropDownList.SelectedIndex = Modes.IncreaseByAmount Then Return Utilities.Money.ApplyIncreasedAmount(item, val) ElseIf Me.MonetaryDropDownList.SelectedIndex = Modes.DecreaseByAmount Then Return Utilities.Money.ApplyDiscountAmount(item, val) ElseIf Me.MonetaryDropDownList.SelectedIndex = Modes.IncreaseByPercent Then Return Utilities.Money.ApplyIncreasedPercent(item, val) ElseIf Me.MonetaryDropDownList.SelectedIndex = Modes.DecreaseByPercent Then Return Utilities.Money.ApplyDiscountPercent(item, val) End If Else Return item End If End Function Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate End Sub End Class
Imports System.Windows.Controls.Primitives Imports System.Windows.Input Imports DevExpress.Mvvm.UI.Interactivity Imports DevExpress.Xpf.Core.Native Imports DevExpress.Xpf.Editors Namespace NavigationDemo.Utils Public Class HorizontalScrollingOnMouseWheelBehavior Inherits Behavior(Of ListBoxEdit) Protected Overrides Sub OnAttached() MyBase.OnAttached() AddHandler AssociatedObject.PreviewMouseWheel, AddressOf OnPreviewMouseWheel End Sub Protected Overrides Sub OnDetaching() MyBase.OnDetaching() RemoveHandler AssociatedObject.PreviewMouseWheel, AddressOf OnPreviewMouseWheel End Sub Private Sub OnPreviewMouseWheel(ByVal sender As Object, ByVal e As MouseWheelEventArgs) Dim scrollBar = CType(LayoutHelper.FindElementByName(AssociatedObject, "PART_HorizontalScrollBar"), ScrollBar) If e.Delta > 0 Then System.Windows.Controls.Primitives.ScrollBar.LineLeftCommand.Execute(Nothing, scrollBar) ElseIf e.Delta < 0 Then System.Windows.Controls.Primitives.ScrollBar.LineRightCommand.Execute(Nothing, scrollBar) End If End Sub End Class End Namespace
Imports System.Data.SqlClient Imports System.Text Imports System.Web Namespace DataObjects.TableObjects <Serializable()> _ Public Class tbl_agent_permission_categories Inherits DBObjectBase #Region "Constants" ''' <summary> ''' Class Name which is used in cache key construction ''' </summary> Const CACHEKEY_CLASSNAME As String = "tbl_agent_permission_categories" #End Region #Region "Class Level Fields" ''' <summary> ''' Instance of DESettings ''' </summary> Private _settings As New DESettings #End Region #Region "Constructors" Sub New() End Sub ''' <summary> ''' Initializes a new instance of the <see cref="tbl_agent_permission_categories" /> class. ''' </summary> ''' <param name="settings">The DESettings instance</param> Sub New(ByVal settings As DESettings) _settings = settings End Sub #End Region #Region "Public Methods" ''' <summary> ''' Get list of all Permission Categories ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetAllCategories(Optional ByVal cacheing As Boolean = True, Optional ByVal cacheTimeMinutes As Integer = 30) As DataTable Dim moduleName As String = "GetAllCategories" Dim dtOutput As DataTable = Nothing Dim cacheKey As String = GetCacheKeyPrefix(CACHEKEY_CLASSNAME, moduleName & _settings.BusinessUnit & _settings.Partner) Dim isCacheNotFound As Boolean = False Dim talentSqlAccessDetail As TalentDataAccess = Nothing Try Me.ResultDataSet = TryGetFromCache(Of DataSet)(isCacheNotFound, cacheing, cacheKey) If isCacheNotFound Then 'Construct The Call talentSqlAccessDetail = New TalentDataAccess talentSqlAccessDetail.Settings = _settings talentSqlAccessDetail.Settings.CacheStringExtension = cacheKey talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet talentSqlAccessDetail.CommandElements.CommandText = "SELECT a.CATEGORY_ID, a.CATEGORY_NAME FROM tbl_agent_permission_categories a ORDER BY a.CATEGORY_NAME" Dim err As New ErrorObj err = talentSqlAccessDetail.SQLAccess(DestinationDatabase.TALENT_DEFINITION, cacheing, cacheTimeMinutes) If (Not (err.HasError)) AndAlso (talentSqlAccessDetail.ResultDataSet IsNot Nothing) Then Me.ResultDataSet = talentSqlAccessDetail.ResultDataSet End If End If If Me.ResultDataSet IsNot Nothing AndAlso Me.ResultDataSet.Tables.Count > 0 Then dtOutput = Me.ResultDataSet.Tables(0) End If Catch ex As Exception Throw Finally talentSqlAccessDetail = Nothing End Try Return dtOutput End Function #End Region End Class End Namespace
Public Class DiversionBO Public Property PermitKey As Integer Public Property DiversionConstructed As Boolean? End Class
Imports Aspose.Tasks.Saving ' 'This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference 'when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. 'If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from http://www.aspose.com/downloads, 'install it and then add its reference to this project. For any issues, questions or suggestions 'please feel free to contact us using http://www.aspose.com/community/forums/default.aspx ' Namespace WorkingWithTasks Public Class WriteTaskCalendar Public Shared Sub Run() ' ExStart:WriteTaskCalendar ' Create project instance Dim project As New Project() ' Add task Dim tsk1 As Task = project.RootTask.Children.Add("Task1") ' Create calendar and assign to task Dim cal As Aspose.Tasks.Calendar = project.Calendars.Add("TaskCal1") tsk1.[Set](Tsk.Calendar, cal) ' ExEnd:WriteTaskCalendar End Sub End Class End Namespace
'************************************* 'DataGridViewに対する列挙型の定義 '************************************* '商品コード変換マスタ明細(DataGridView) Public Enum CPCMVColumnType As Integer ProductCode ChannelName ChannelProductCode ChannelProductName ChannelOptionNameAndValue End Enum '商品マスタ明細(DataGridView) Public Enum PPMVColumnType As Integer JANCode ProductCode ProductName OptionValue Price MakerName SupplierName End Enum Public Class fCnvProductCdMst Private Const DISP_ROW_MAX = 500 '------------------------------------ ' DBアクセス関連 '------------------------------------ Private oConn As OleDb.OleDbConnection Private oCommand As OleDb.OleDbCommand Private oDataReader As OleDb.OleDbDataReader Private oTool As cTool Private oConf() As cStructureLib.sConfig Private oMstConfigDBIO As cMstConfigDBIO Private oChannel() As cStructureLib.sChannel Private oMstChannelDBIO As cMstChannelDBIO Private oSupplier() As cStructureLib.sSupplier Private oSupplierDBIO As cMstSupplierDBIO Private oProduct() As cStructureLib.sProduct Private oMstProductDBIO As cMstProductDBIO Private oCnvProductCd() As cStructureLib.sViewCnvProductCd Private oPenddingCnvProduct() As cStructureLib.sViewPenddingCnvProduct Private oMstCnvProductCdDBIO As cMstCnvProductCdDBIO Private oRequestData() As cStructureLib.sRequestData Private oDataRequestDBIO As cDataRequestDBIO Private STAFF_CODE As String Private STAFF_NAME As String Private NowRowIndex As Integer Private OpenMode As Integer Private Tran As System.Data.OleDb.OleDbTransaction Sub New(ByRef iConn As OleDb.OleDbConnection, _ ByRef iCommand As OleDb.OleDbCommand, _ ByRef iDataReader As OleDb.OleDbDataReader, _ ByRef iRequestData() As cStructureLib.sRequestData, _ ByVal mode As Integer) ' この呼び出しは、Windows フォーム デザイナで必要です。 InitializeComponent() oConn = iConn oCommand = iCommand oDataReader = iDataReader oRequestData = iRequestData oTool = New cTool oMstChannelDBIO = New cMstChannelDBIO(oConn, oCommand, oDataReader) oSupplierDBIO = New cMstSupplierDBIO(oConn, oCommand, oDataReader) oMstProductDBIO = New cMstProductDBIO(oConn, oCommand, oDataReader) oMstCnvProductCdDBIO = New cMstCnvProductCdDBIO(oConn, oCommand, oDataReader) oDataRequestDBIO = New cDataRequestDBIO(oConn, oCommand, oDataReader) Me.OpenMode = mode End Sub Private Sub fConvProductCdMst_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim RecordCnt As Integer '----------------------- SoftGroupライセンス認証 ---------------------- Softgroup.NetButton.License.LicenseName = "Yooko Satoh" Softgroup.NetButton.License.LicenseUser = "yoko.satoh@ocf.co.jp" Softgroup.NetButton.License.LicenseKey = "DDADJEBQ3HL2AOBINJBDGZBFC" '---------------------------------------------------------------------- '環境マスタ読込み oMstConfigDBIO = New cMstConfigDBIO(oConn, oCommand, oDataReader) ReDim oConf(1) RecordCnt = oMstConfigDBIO.getConfMst(oConf, Tran) If RecordCnt < 1 Then 'メッセージウィンドウ表示 Dim Message_form As cMessageLib.fMessage Message_form = New cMessageLib.fMessage(1, "環境マスタの読込みに失敗しました", _ "開発元にお問い合わせ下さい", _ Nothing, Nothing) Message_form.ShowDialog() Application.DoEvents() Application.Exit() End If oMstConfigDBIO = Nothing 'チャネルリストボックスセット CHANNEL_SET() '仕入先リストボックスセット SUPPLIER_SET() '明細表示エリアタイトル行生成 CNV_PRODUCT_CD_MST_GRIDVIEW_CREATE() P_PRODUCT_MST_GRIDVIEW_CREATE() '表示初期化処理 INIT_PROC() '保留件数がゼロ件でない場合は、チェックして検索@@ If OpenMode = 2 Then PRODUCT_CD_ISNULL_C.Checked = True SEARCH_B_Click(Nothing, Nothing) End If End Sub Private Sub INIT_PROC() Dim i As Long '明細行クリア For i = 0 To CNV_PRODUCT_CD_MST_V.Rows.Count - 1 CNV_PRODUCT_CD_MST_V.Rows.Clear() Next i '明細行クリア For i = 0 To P_PRODUCT_MST_V.Rows.Count - 1 P_PRODUCT_MST_V.Rows.Clear() Next i End Sub '****************************************************************** 'システム・ショートカット・キーによるダイアログの終了を阻止する '****************************************************************** Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Const WM_SYSCOMMAND As Integer = &H112 Const SC_CLOSE As Integer = &HF060 If (m.Msg = WM_SYSCOMMAND) AndAlso (m.WParam.ToInt32() = SC_CLOSE) Then Return ' Windows標準の処理は行わない End If MyBase.WndProc(m) End Sub '****************************************************************** 'タイトルバーのないウィンドウに3Dの境界線を持たせる '****************************************************************** Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams Get Const WS_EX_DLGMODALFRAME As Integer = &H1 Dim cp As CreateParams = MyBase.CreateParams cp.ExStyle = cp.ExStyle Or WS_EX_DLGMODALFRAME Return cp End Get End Property <System.Runtime.InteropServices.DllImport("USER32.DLL", _ CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _ Private Shared Function HideCaret( _ ByVal hwnd As IntPtr) As Integer End Function '*************************** 'チャネル名称リストボックスセット '*************************** Private Sub CHANNEL_SET() Dim RecordCnt As Integer Dim i As Long 'チャネルコンボ内容設定 oChannel = Nothing RecordCnt = oMstChannelDBIO.getChannelMst(oChannel, Nothing, 2, Nothing, True, Tran) If RecordCnt < 1 Then 'メッセージウィンドウ表示 Dim Message_form As cMessageLib.fMessage If RecordCnt = 0 Then Message_form = New cMessageLib.fMessage(1, "チャネルマスタが登録されていません", _ "チャネルマスタを登録してください", _ Nothing, Nothing) Else Message_form = New cMessageLib.fMessage(1, "チャネルマスタの読込みに失敗しました", _ "開発元にお問い合わせ下さい", _ Nothing, Nothing) End If Message_form.ShowDialog() Application.DoEvents() Application.Exit() End If 'リストボックスへの値セット For i = 0 To RecordCnt - 1 CHANNEL_L.Items.Add(oChannel(i).sChannelName) Next End Sub '*************************** '仕入先リストボックスセット '*************************** Private Sub SUPPLIER_SET() Dim RecordCnt As Integer Dim i As Long '仕入先コンボ内容設定 oSupplier = Nothing RecordCnt = oSupplierDBIO.getSupplier(oSupplier, Nothing, Nothing, Tran) If RecordCnt < 1 Then 'メッセージウィンドウ表示 Dim Message_form As cMessageLib.fMessage If RecordCnt = 0 Then Message_form = New cMessageLib.fMessage(1, "仕入先マスタが登録されていません", _ "仕入先マスタを登録してください", _ Nothing, Nothing) Else Message_form = New cMessageLib.fMessage(1, "仕入先マスタの読込みに失敗しました", _ "開発元にお問い合わせ下さい", _ Nothing, Nothing) End If Message_form.ShowDialog() Application.DoEvents() Application.Exit() End If 'リストボックスへの値セット For i = 0 To RecordCnt - 1 P_SUPPLIER_L.Items.Add(oSupplier(i).sSupplierName) Next End Sub '****************************** ' DataGridViewの設定 ' ヘッダーおよび列幅設定 '****************************** '商品コード変換マスタ明細(DataGridView) Sub CNV_PRODUCT_CD_MST_GRIDVIEW_CREATE() 'レコードセレクタを非表示に設定 CNV_PRODUCT_CD_MST_V.RowHeadersVisible = False CNV_PRODUCT_CD_MST_V.MultiSelect = False CNV_PRODUCT_CD_MST_V.ReadOnly = True CNV_PRODUCT_CD_MST_V.RowsDefaultCellStyle.BackColor = Color.White CNV_PRODUCT_CD_MST_V.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon 'グリッドのヘッダーを作成します。 Dim column1 As New DataGridViewTextBoxColumn column1.Name = "商品コード" column1.Width = 100 CNV_PRODUCT_CD_MST_V.Columns.Add(column1) Dim column2 As New DataGridViewTextBoxColumn column2.Name = "チャネル名称" column2.Width = 100 CNV_PRODUCT_CD_MST_V.Columns.Add(column2) Dim column3 As New DataGridViewTextBoxColumn column3.Name = "チャネル商品コード" column3.Width = 150 CNV_PRODUCT_CD_MST_V.Columns.Add(column3) Dim column4 As New DataGridViewTextBoxColumn column4.Name = "チャネル商品名称" column4.Width = 320 CNV_PRODUCT_CD_MST_V.Columns.Add(column4) Dim column5 As New DataGridViewTextBoxColumn column5.Name = "チャネルオプション" column5.Width = 300 CNV_PRODUCT_CD_MST_V.Columns.Add(column5) End Sub '商品マスタ明細(DataGridView) Sub P_PRODUCT_MST_GRIDVIEW_CREATE() 'レコードセレクタを非表示に設定 P_PRODUCT_MST_V.RowHeadersVisible = False P_PRODUCT_MST_V.MultiSelect = False P_PRODUCT_MST_V.ReadOnly = True P_PRODUCT_MST_V.RowsDefaultCellStyle.BackColor = Color.White P_PRODUCT_MST_V.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon 'グリッドのヘッダーを作成します。 Dim column1 As New DataGridViewTextBoxColumn column1.Name = "JANコード" column1.Width = 80 P_PRODUCT_MST_V.Columns.Add(column1) Dim column2 As New DataGridViewTextBoxColumn column2.Name = "商品コード" column2.Width = 100 P_PRODUCT_MST_V.Columns.Add(column2) Dim column3 As New DataGridViewTextBoxColumn column3.Name = "商品名称" column3.Width = 220 P_PRODUCT_MST_V.Columns.Add(column3) Dim column4 As New DataGridViewTextBoxColumn column4.Name = "オプション値" column4.Width = 200 P_PRODUCT_MST_V.Columns.Add(column4) Dim column5 As New DataGridViewTextBoxColumn column5.Name = "定価" P_PRODUCT_MST_V.Columns.Add(column5) column5.Width = 100 column5.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Dim column6 As New DataGridViewTextBoxColumn column6.Name = "メーカー" column6.Width = 120 P_PRODUCT_MST_V.Columns.Add(column6) Dim column7 As New DataGridViewTextBoxColumn column7.Name = "仕入先" P_PRODUCT_MST_V.Columns.Add(column7) column7.Width = 115 End Sub '*********************************************** '検索結果を画面(商品コード変換マスタ明細)にセット '*********************************************** Sub CNV_PRODUCT_CD_MST_V_SEARCH_RESULT_SET() Dim i As Long For i = 0 To CNV_PRODUCT_CD_MST_V.Rows.Count CNV_PRODUCT_CD_MST_V.Rows.Clear() Next i '表示設定 For i = 0 To oPenddingCnvProduct.Length - 1 If oPenddingCnvProduct(i).sChannelProductCode.Substring(0, 5) <> "ZZZZZ" Then CNV_PRODUCT_CD_MST_V.Rows.Add( _ oPenddingCnvProduct(i).sProductCode, _ oPenddingCnvProduct(i).sChannelName, _ oPenddingCnvProduct(i).sChannelProductCode, _ oPenddingCnvProduct(i).sChannelProductName, _ oPenddingCnvProduct(i).sChannelOptionNameAndValue _ ) End If Next i End Sub '*********************************************** '検索結果を画面(商品マスタ明細)にセット '*********************************************** Sub P_PRODUCT_MST_V_SEARCH_RESULT_SET(ByVal isChecked As Boolean) Dim i As Long For i = 0 To P_PRODUCT_MST_V.Rows.Count P_PRODUCT_MST_V.Rows.Clear() Next i '表示設定 For i = 0 To oProduct.Length - 1 P_PRODUCT_MST_V.Rows.Add( _ oProduct(i).sJANCode, _ oProduct(i).sProductCode, _ oProduct(i).sProductName, _ oProduct(i).sOption1 & ":" & _ oProduct(i).sOption2 & ":" & _ oProduct(i).sOption3 & ":" & _ oProduct(i).sOption4 & ":" & _ oProduct(i).sOption5, _ oProduct(i).sListPrice, _ oProduct(i).sMakerName, _ "" _ ) Next i '@TODO (仕入先名の取得) 'oProduct(i).sSupplierName1 _ End Sub '*********************************************** 'イベント処理:商品コード変換マスタ明細セル選択 '*********************************************** Private Sub CNV_PRODUCT_CD_MST_V_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles CNV_PRODUCT_CD_MST_V.CellClick Dim RecordCnt As Long Dim KeyProductCode As String Dim KeyIsNotChannelProductCode As Boolean ' If e.RowIndex < 0 Then Exit Sub End If NowRowIndex = e.RowIndex '検索キーの判定 If (CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ProductCode, NowRowIndex).Value <> "") Then KeyIsNotChannelProductCode = True KeyProductCode = CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ProductCode, NowRowIndex).Value Else KeyIsNotChannelProductCode = False KeyProductCode = CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ChannelProductCode, NowRowIndex).Value End If '商品マスタの読み込みバッファ初期化 oProduct = Nothing '商品マスタの読み込み RecordCnt = oMstProductDBIO.getProduct( _ oProduct, _ Nothing, _ KeyProductCode, _ Nothing, _ Nothing, _ Nothing, _ Nothing, _ Nothing, _ Nothing, _ Nothing, _ Tran) '商品マスタ検索条件クリア P_JANCODE_T.Text = "" P_PRODUCT_CODE_T.Text = "" P_PRODUCT_NAME_T.Text = "" P_SUPPLIER_L.Text = "" P_MAKER_NAME_T.Text = "" '商品マスタ明細行クリア For i = 0 To P_PRODUCT_MST_V.Rows.Count - 1 P_PRODUCT_MST_V.Rows.Clear() Next i If RecordCnt > 0 Then '商品マスタ明細行セット If KeyIsNotChannelProductCode Then P_PRODUCT_CODE_T.Text = oProduct(0).sProductCode P_PRODUCT_MST_V_SEARCH_RESULT_SET(True) Else P_PRODUCT_NAME_T.Text = oProduct(0).sProductName P_SEARCH_PROD_B_Click(Nothing, Nothing) End If Else P_PRODUCT_NAME_T.Text = CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ChannelProductName, NowRowIndex).Value End If End Sub '*********************************************** 'イベント処理:商品マスタ明細セル選択(ダブルクリック) '*********************************************** Private Sub P_PRODUCT_MST_V_DoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles P_PRODUCT_MST_V.CellDoubleClick ' If e.RowIndex < 0 Then Return If oPenddingCnvProduct(NowRowIndex).sProductCode <> oProduct(e.RowIndex).sProductCode Then CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ProductCode, NowRowIndex).Value = oProduct(e.RowIndex).sProductCode CNV_PRODUCT_CD_MST_V.Rows(NowRowIndex).DefaultCellStyle.ForeColor = Color.Red Else CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ProductCode, NowRowIndex).Value = oProduct(e.RowIndex).sProductCode CNV_PRODUCT_CD_MST_V.Rows(NowRowIndex).DefaultCellStyle.ForeColor = Color.Black End If End Sub '*********************************************** 'イベント処理:終了ボタン押下 '*********************************************** Private Sub RETURN_B_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim RecordCnt As Long = 0D Dim i As Integer '未登録変更データの確認 For i = 0 To CNV_PRODUCT_CD_MST_V.Rows.Count - 1 If CNV_PRODUCT_CD_MST_V(0, i).Value = "" Then RecordCnt += 1 End If Next If RecordCnt > 0 Then Dim Message_form As cMessageLib.fMessage Message_form = New cMessageLib.fMessage(2, "未登録の変更データがあります。", _ "終了してもよろしいですか?", _ Nothing, Nothing) Message_form.ShowDialog() If Message_form.DialogResult = Windows.Forms.DialogResult.No Then Message_form.Dispose() Message_form = Nothing Exit Sub End If Message_form.Dispose() Message_form = Nothing End If 'MsgBox(CNV_PRODUCT_CD_MST_V.SelectedRows(0).Cells(CPCMVColumnType.ProductCode).Value) oConn = Nothing oTool = Nothing oMstConfigDBIO = Nothing oMstChannelDBIO = Nothing oSupplierDBIO = Nothing oMstProductDBIO = Nothing oMstCnvProductCdDBIO = Nothing oDataRequestDBIO = Nothing Me.DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub Private Sub SEARCH_B_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim RecordCnt As Long '明細行クリア CNV_PRODUCT_CD_MST_V.Rows.Clear() P_PRODUCT_MST_V.Rows.Clear() 'メッセージウィンドウ表示 Dim Message_form As cMessageLib.fMessage Message_form = New cMessageLib.fMessage(0, "データ読込み中", _ "しばらくお待ちください", _ Nothing, Nothing) Message_form.Show() Application.DoEvents() '商品在庫データの読み込みバッファ初期化 oPenddingCnvProduct = Nothing '商品情報変換マスタの読み込み RecordCnt = oMstCnvProductCdDBIO.getPenddingCnvProduct(oPenddingCnvProduct, Tran) If RecordCnt > 0 Then '検索MAX値の確認 If RecordCnt > DISP_ROW_MAX Then Message_form.Dispose() Message_form = Nothing Message_form = New cMessageLib.fMessage(1, "データ件数が500件を超えています", _ "条件を変更して再建策して下さい", _ Nothing, Nothing) Message_form.ShowDialog() Message_form = Nothing Exit Sub End If '検索結果の画面セット CNV_PRODUCT_CD_MST_V_SEARCH_RESULT_SET() If CNV_PRODUCT_CD_MST_V.Rows.Count = 0 Then oConn = Nothing oTool = Nothing oMstConfigDBIO = Nothing oMstChannelDBIO = Nothing oSupplierDBIO = Nothing oMstProductDBIO = Nothing oMstCnvProductCdDBIO = Nothing oDataRequestDBIO = Nothing Me.DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End If '検索結果に対応する商品マスタ明細をセット CNV_PRODUCT_CD_MST_V_CellClick(Nothing, New DataGridViewCellEventArgs(0, 0)) End If 'メッセージウィンドウのクリア Message_form.Dispose() Message_form = Nothing End Sub Private Sub UPDATE_B_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UPDATE_B.Click Dim RecordCnt As Long Dim i As Integer Dim Tran As System.Data.OleDb.OleDbTransaction Dim oPenddingData() As cStructureLib.sViewPenddingCnvProduct '---トランザクション開始 'Tran = oConn.BeginTransaction Tran = Nothing Dim UpdateCnt As Long = 0 For i = 0 To CNV_PRODUCT_CD_MST_V.Rows.Count - 1 If CNV_PRODUCT_CD_MST_V(0, i).Value <> "" Then oPenddingCnvProduct(i).sProductCode = CNV_PRODUCT_CD_MST_V(CPCMVColumnType.ProductCode, i).Value RecordCnt = oMstCnvProductCdDBIO.deleteCnvProductCdMst(oPenddingCnvProduct(i), Tran) RecordCnt = oMstCnvProductCdDBIO.insertCnvProductCdMst(oPenddingCnvProduct(i), Tran) CNV_PRODUCT_CD_MST_V.Rows(i).DefaultCellStyle.ForeColor = Color.Black UpdateCnt += 1 End If Next ''注文商品がすべて商品コード変換マスタに登録済のものを対象とし、 ''一時表から注文情報および注文情報明細をまとめて登録する 'oDataRequestDBIO.insertTmpToRequest(Tran) Dim Message_form As cMessageLib.fMessage Message_form = New cMessageLib.fMessage(1, Nothing, _ UpdateCnt.ToString & " 件のデータを登録しました。", _ Nothing, Nothing) Message_form.ShowDialog() Message_form.Dispose() Message_form = Nothing ReDim oPenddingData(0) RecordCnt = oMstCnvProductCdDBIO.getPenddingCnvProduct(oPenddingData, Tran).ToString If RecordCnt = 0 Then oConn = Nothing oTool = Nothing oMstConfigDBIO = Nothing oMstChannelDBIO = Nothing oSupplierDBIO = Nothing oMstProductDBIO = Nothing oMstCnvProductCdDBIO = Nothing oDataRequestDBIO = Nothing Me.DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End If End Sub Private Sub P_SEARCH_PROD_B_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles P_SEARCH_PROD_B.Click Dim RecordCnt As Long Dim i As Long '明細行クリア For i = 0 To P_PRODUCT_MST_V.Rows.Count - 1 P_PRODUCT_MST_V.Rows.Clear() Next i 'メッセージウィンドウ表示 Dim Message_form As cMessageLib.fMessage Message_form = New cMessageLib.fMessage(0, "データ読込み中", "しばらくお待ちください", Nothing, Nothing) Message_form.Show() Application.DoEvents() '商品在庫データの読み込みバッファ初期化 oProduct = Nothing '商品在庫データの読み込み RecordCnt = oMstProductDBIO.getProduct( _ oProduct, _ P_JANCODE_T.Text, _ P_PRODUCT_CODE_T.Text, _ P_PRODUCT_NAME_T.Text, _ Nothing, _ P_SUPPLIER_L.Text, _ P_MAKER_NAME_T.Text, _ Nothing, _ Nothing, _ Nothing, _ Tran) If RecordCnt > 0 Then '検索MAX値の確認 If RecordCnt > DISP_ROW_MAX Then Message_form.Dispose() Message_form = Nothing Message_form = New cMessageLib.fMessage(1, "データ件数が500件を超えています", _ "条件を変更して再建策して下さい", _ Nothing, Nothing) Message_form.ShowDialog() Message_form = Nothing Exit Sub End If '検索結果の画面セット P_PRODUCT_MST_V_SEARCH_RESULT_SET(False) End If 'メッセージウィンドウのクリア Message_form.Dispose() Message_form = Nothing End Sub Private Sub CLOSE_B_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CLOSE_B.Click Dim RecordCnt As Long = 0D Dim i As Integer '未登録変更データの確認 For i = 0 To CNV_PRODUCT_CD_MST_V.Rows.Count - 1 If CNV_PRODUCT_CD_MST_V(0, i).Value = "" Then RecordCnt += 1 End If Next If RecordCnt > 0 Then Dim Message_form As cMessageLib.fMessage Message_form = New cMessageLib.fMessage(2, "未登録の変更データがあります。", _ "終了してもよろしいですか?", _ Nothing, Nothing) Message_form.ShowDialog() If Message_form.DialogResult = Windows.Forms.DialogResult.No Then Message_form.Dispose() Message_form = Nothing Exit Sub End If Message_form.Dispose() Message_form = Nothing End If 'MsgBox(CNV_PRODUCT_CD_MST_V.SelectedRows(0).Cells(CPCMVColumnType.ProductCode).Value) oConn = Nothing oTool = Nothing oMstConfigDBIO = Nothing oMstChannelDBIO = Nothing oSupplierDBIO = Nothing oMstProductDBIO = Nothing oMstCnvProductCdDBIO = Nothing oDataRequestDBIO = Nothing Me.DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class
''' <summary> ''' Cooley-Tukey FFT algorithm. ''' </summary> Public NotInheritable Class FftAlgorithm Private Sub New() End Sub ''' <summary> ''' Calculates FFT using Cooley-Tukey FFT algorithm. ''' </summary> ''' <param name="x">input data</param> ''' <returns>spectrogram of the data</returns> ''' <remarks> ''' If amount of data items not equal a power of 2, then algorithm ''' automatically pad with 0s to the lowest amount of power of 2. ''' </remarks> Public Shared Function Calculate(x As Double()) As Double() Dim length As Integer Dim bitsInLength As Integer If IsPowerOfTwo(x.Length) Then length = x.Length bitsInLength = Log2(length) - 1 Else bitsInLength = Log2(x.Length) ' the items will be pad with zeros length = 1 << bitsInLength End If ' bit reversal Dim data As ComplexNumber() = New ComplexNumber(length - 1) {} For i As Integer = 0 To x.Length - 1 Dim j As Integer = ReverseBits(i, bitsInLength) data(j) = New ComplexNumber(x(i)) Next ' Cooley-Tukey For i As Integer = 0 To bitsInLength - 1 Dim m As Integer = 1 << i Dim n As Integer = m * 2 Dim alpha As Double = -(2 * Math.PI / n) For k As Integer = 0 To m - 1 ' e^(-2*pi/N*k) Dim oddPartMultiplier As ComplexNumber = New ComplexNumber(0, alpha * k).PoweredE() Dim j As Integer = k While j < length Dim evenPart As ComplexNumber = data(j) Dim oddPart As ComplexNumber = oddPartMultiplier * data(j + m) data(j) = evenPart + oddPart data(j + m) = evenPart - oddPart j += n End While Next Next ' calculate spectrogram Dim spectrogram As Double() = New Double(length - 1) {} For i As Integer = 0 To spectrogram.Length - 1 spectrogram(i) = data(i).AbsPower2() Next Return spectrogram End Function ''' <summary> ''' Gets number of significat bytes. ''' </summary> ''' <param name="n">Number</param> ''' <returns>Amount of minimal bits to store the number.</returns> Private Shared Function Log2(n As Integer) As Integer Dim i As Integer = 0 While n > 0 i += 1 n >>= 1 End While Return i End Function ''' <summary> ''' Reverses bits in the number. ''' </summary> ''' <param name="n">Number</param> ''' <param name="bitsCount">Significant bits in the number.</param> ''' <returns>Reversed binary number.</returns> Private Shared Function ReverseBits(n As Integer, bitsCount As Integer) As Integer Dim reversed As Integer = 0 For i As Integer = 0 To bitsCount - 1 Dim nextBit As Integer = n And 1 n >>= 1 reversed <<= 1 reversed = reversed Or nextBit Next Return reversed End Function ''' <summary> ''' Checks if number is power of 2. ''' </summary> ''' <param name="n">number</param> ''' <returns>true if n=2^k and k is positive integer</returns> Private Shared Function IsPowerOfTwo(n As Integer) As Boolean Return n > 1 AndAlso (n And (n - 1)) = 0 End Function End Class
'``` ' # Chapter 2: `For` loops ' ' There are 5 basic parts to a `For` loop; ' ' * The counter **variable** (`i`) ' * The initial **value** (`1`) ' * The final **value** (`10`) ' * The increment, which is _optional_ and is specified in the `Step` clause ' * The code you would like to repeat: ' ``` ' Console.WriteLine(i) ' ``` '``` For i = 1 To 10 Console.WriteLine(i) Next '``` ' ### Iterating backward ' ' You can loop backward by swapping the _initial_ and _final_ values using a **negative** `Step` value. '``` Stop For i = 10 To 1 Step -1 Console.WriteLine(i) Next '``` ' `For` loops are useful in combination with **arrays**. We'll look at arrays in the next chapter. '```
'--------------------------------------------------------------------------- ' Author : Nguyễn Khánh Tùng ' Company : Thiên An ESS ' Created Date : Tuesday, July 29, 2008 '--------------------------------------------------------------------------- Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Data.OracleClient Imports ESS.Machine Imports ESS.Entity.Entity Namespace DBManager Public Class BienLaiThu_DAL #Region "Constructor" Public Sub New() End Sub #End Region #Region "Function" Public Function Load_BienLaiChi(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal dsID_lop As String, ByVal ID_thu_chi As Integer, ByVal Thu_chi As Integer, ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(5) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@dsID_lop", dsID_lop) para(3) = New SqlParameter("@ID_thu_chi", ID_thu_chi) para(4) = New SqlParameter("@Thu_chi", Thu_chi) para(5) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiChi_Load_List", para) Else Dim para(5) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":dsID_lop", dsID_lop) para(3) = New OracleParameter(":ID_thu_chi", ID_thu_chi) para(4) = New OracleParameter("@Thu_chi", Thu_chi) para(5) = New OracleParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiChi_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_DanhSachSv(ByVal dsID_lop As String) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_lops", dsID_lop) Return UDB.SelectTableSP("STU_DanhSachSinhVien_DoiTuong_Load_List", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_lops", dsID_lop) Return UDB.SelectTableSP("STU_DanhSachSinhVien_DoiTuong_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_Lop_Khoa(ByVal Khoa_hoc As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@Khoa_hoc", Khoa_hoc) Return UDB.SelectTableSP("STU_Lop_Load_Khoa_hoc", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":Khoa_hoc", Khoa_hoc) Return UDB.SelectTableSP("STU_Lop_Load_Khoa_hoc", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_DanhSach_ThuChi_List(ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("STU_Load_DanhSach_ThuChi_List", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_sv", ID_sv) Return UDB.SelectTableSP("STU_Load_DanhSach_ThuChi_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThu(ByVal ID_bien_lai As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", ID_bien_lai) Return UDB.SelectTableSP("ACC_BienLaiThu_Load", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", ID_bien_lai) Return UDB.SelectTableSP("ACC_BienLaiThu_Load", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThu_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal dsID_lop As String, ByVal ID_thu_chi As Integer, ByVal Thu_chi As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(4) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@dsID_lop", dsID_lop) para(3) = New SqlParameter("@ID_thu_chi", ID_thu_chi) para(4) = New SqlParameter("@Thu_chi", Thu_chi) Return UDB.SelectTableSP("ACC_BienLaiThu_Load_List", para) Else Dim para(4) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":dsID_lop", dsID_lop) para(3) = New OracleParameter(":ID_thu_chi", ID_thu_chi) para(4) = New OracleParameter("@Thu_chi", Thu_chi) Return UDB.SelectTableSP("ACC_BienLaiThu_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThuChiTiet(ByVal ID_bien_lai As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", ID_bien_lai) Return UDB.SelectTableSP("ACC_BienLaiThuChiTiet_Load", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", ID_bien_lai) Return UDB.SelectTableSP("ACC_BienLaiThuChiTiet_Load", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThuChiTiet_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal dsID_lop As String, ByVal ID_thu_chi As Integer, ByVal Thu_chi As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(4) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@dsID_lop", dsID_lop) para(3) = New SqlParameter("@ID_thu_chi", ID_thu_chi) para(4) = New SqlParameter("@Thu_chi", Thu_chi) Return UDB.SelectTableSP("ACC_BienLaiThuChiTiet_Load_List", para) Else Dim para(4) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":dsID_lop", dsID_lop) para(3) = New OracleParameter(":ID_thu_chi", ID_thu_chi) para(4) = New OracleParameter("@Thu_chi", Thu_chi) Return UDB.SelectTableSP("ACC_BienLaiThuChiTiet_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_KhoanNop_HocKy_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(2) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("STU_KhoanNop_HocKy_SinhVien_Load_List", para) Else Dim para(2) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":ID_thu_chi", ID_sv) Return UDB.SelectTableSP("STU_KhoanNop_HocKy_SinhVien_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_DanhSachSinhVienKhoanNop_HocKy_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal dsID_lop As String) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(2) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@dsID_lop", dsID_lop) Return UDB.SelectTableSP("STU_KhoanNop_HocKy_Load_List", para) Else Dim para(2) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":dsID_lop", dsID_lop) Return UDB.SelectTableSP("STU_KhoanNop_HocKy_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThu_MonDaThu_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(2) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiThu_MonDangDaThu_Load_List", para) Else Dim para(2) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":ID_thu_chi", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiThu_MonDangDaThu_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThu_MonDangKy_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal Dot_thu As Integer, ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(3) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@Dot_thu", Dot_thu) para(3) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiThu_MonDangKy_Load_List", para) Else Dim para(3) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":dsID_lop", Dot_thu) para(3) = New OracleParameter(":ID_thu_chi", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiThu_MonDangKy_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_BienLaiThu_MonDangKyDanhSach_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal Dot_thu As Integer, ByVal dsID_lop As String) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(3) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@Dot_thu", Dot_thu) para(3) = New SqlParameter("@dsID_lop", dsID_lop) Return UDB.SelectTableSP("ACC_BienLaiThu_MonDangKyDanhSach_Load_List", para) Else Dim para(3) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":dsID_lop", Dot_thu) para(3) = New OracleParameter(":dsID_lop", dsID_lop) Return UDB.SelectTableSP("ACC_BienLaiThu_MonDangKyDanhSach_Load_List", para) End If Catch ex As Exception Throw ex End Try End Function Public Function getSo_phieu() As Long Dim intID_bien_lai As Integer = getMaxID_bien_lai() Dim dtdata As New DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", intID_bien_lai) dtdata = UDB.SelectTableSP("ACC_BienLaiThu_GetSoPhieu", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", intID_bien_lai) dtdata = UDB.SelectTableSP("ACC_BienLaiThu_GetSoPhieu", para) End If If dtdata.Rows.Count > 0 Then Return dtdata.Rows(0).Item(0) + 1 Else Return 1 End If Catch ex As Exception Throw New Exception(ex.Message) End Try End Function Private Function getMaxID_bien_lai() As Long Try Dim dtData As New DataTable If gDBType = DatabaseType.SQLServer Then dtData = UDB.SelectTableSP("ACC_BienLaiThu_GetMaxID") Else dtData = UDB.SelectTableSP("ACC_BienLaiThu_GetMaxID") End If If dtData.Rows(0).Item(0).ToString = "" Then Return 0 Else Return dtData.Rows(0).Item(0) End If Catch ex As Exception Throw New Exception(ex.Message) End Try End Function Public Function getID_sv(ByVal Ma_sv As String) As Long Dim dtData As New DataTable If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@Ma_sv", Ma_sv) dtData = UDB.SelectTableSP("STU_HoSoSinhVien_GetID_SV", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":Ma_sv", Ma_sv) dtData = UDB.SelectTableSP("STU_HoSoSinhVien_GetID_SV", para) End If If dtData.Rows.Count > 0 Then Return dtData.Rows(0).Item(0) Else Return 0 End If End Function Public Function getID_bien_lai(ByVal ID_sv As Integer, ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal Dot_thu As Integer, ByVal Lan_thu As Integer, ByVal ID_thu_chi As Integer, ByVal Thu_chi As Integer) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(6) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@Dot_thu", Dot_thu) para(3) = New SqlParameter("@Lan_thu", Lan_thu) para(4) = New SqlParameter("@ID_sv", ID_sv) para(5) = New SqlParameter("@Thu_chi", Thu_chi) para(6) = New SqlParameter("@ID_thu_chi", ID_thu_chi) Dim dt As DataTable = UDB.SelectTableSP("ACC_BienLaiThu_getID_bien_lai", para) If dt.Rows.Count > 0 Then Return CInt("0" + dt.Rows(0)(0).ToString()) Else Return 0 End If Else Dim para(6) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":Dot_thu", Dot_thu) para(3) = New OracleParameter(":Lan_thu", Lan_thu) para(4) = New OracleParameter(":ID_sv", ID_sv) para(5) = New OracleParameter(":Thu_chi", Thu_chi) para(6) = New OracleParameter(":ID_thu_chi", ID_thu_chi) Dim dt As DataTable = UDB.SelectTableSP("ACC_BienLaiThu_getID_bien_lai", para) If dt.Rows.Count > 0 Then Return CInt("0" + dt.Rows(0)(0).ToString()) Else Return 0 End If End If Catch ex As Exception Throw ex End Try End Function Public Function Insert_BienLaiThu(ByVal obj As BienLaiThu) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(15) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", obj.Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", obj.Nam_hoc) para(2) = New SqlParameter("@Dot_thu", obj.Dot_thu) para(3) = New SqlParameter("@Lan_thu", obj.Lan_thu) para(4) = New SqlParameter("@ID_sv", obj.ID_sv) para(5) = New SqlParameter("@Thu_chi", obj.Thu_chi) para(6) = New SqlParameter("@So_phieu", obj.So_phieu) para(7) = New SqlParameter("@Ngay_thu", obj.Ngay_thu) para(8) = New SqlParameter("@Noi_dung", obj.Noi_dung) para(9) = New SqlParameter("@So_tien", obj.So_tien) para(10) = New SqlParameter("@So_tien_chu", obj.So_tien_chu) para(11) = New SqlParameter("@Ngoai_te", obj.Ngoai_te) para(12) = New SqlParameter("@Huy_phieu", obj.Huy_phieu) para(13) = New SqlParameter("@Ghi_chu", obj.Ghi_chu) para(14) = New SqlParameter("@Nguoi_thu", obj.Nguoi_thu) para(15) = New SqlParameter("@Printed", obj.Printed) Dim dt As DataTable = UDB.SelectTableSP("ACC_BienLaiThu_Insert", para) If dt.Rows.Count > 0 Then Return CInt("0" + dt.Rows(0)(0).ToString()) Else Return 0 End If Else Dim para(15) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", obj.Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", obj.Nam_hoc) para(2) = New OracleParameter(":Dot_thu", obj.Dot_thu) para(3) = New OracleParameter(":Lan_thu", obj.Lan_thu) para(4) = New OracleParameter(":ID_sv", obj.ID_sv) para(5) = New OracleParameter(":Thu_chi", obj.Thu_chi) para(6) = New OracleParameter(":So_phieu", obj.So_phieu) para(7) = New OracleParameter(":Ngay_thu", obj.Ngay_thu) para(8) = New OracleParameter(":Noi_dung", obj.Noi_dung) para(9) = New OracleParameter(":So_tien", obj.So_tien) para(10) = New OracleParameter(":So_tien_chu", obj.So_tien_chu) para(11) = New OracleParameter(":Ngoai_te", obj.Ngoai_te) para(12) = New OracleParameter(":Huy_phieu", obj.Huy_phieu) para(13) = New OracleParameter(":Ghi_chu", obj.Ghi_chu) para(14) = New OracleParameter(":Nguoi_thu", obj.Nguoi_thu) para(15) = New OracleParameter(":Printed", obj.Printed) Dim dt As DataTable = UDB.SelectTableSP("ACC_BienLaiThu_Insert", para) If dt.Rows.Count > 0 Then Return CInt("0" + dt.Rows(0)(0).ToString()) Else Return 0 End If End If Catch ex As Exception Throw ex End Try End Function Public Function Update_BienLaiThu(ByVal obj As BienLaiThu, ByVal ID_bien_lai As Integer) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(16) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", ID_bien_lai) para(1) = New SqlParameter("@Hoc_ky", obj.Hoc_ky) para(2) = New SqlParameter("@Nam_hoc", obj.Nam_hoc) para(3) = New SqlParameter("@Dot_thu", obj.Dot_thu) para(4) = New SqlParameter("@Lan_thu", obj.Lan_thu) para(5) = New SqlParameter("@ID_sv", obj.ID_sv) para(6) = New SqlParameter("@Thu_chi", obj.Thu_chi) para(7) = New SqlParameter("@So_phieu", obj.So_phieu) para(8) = New SqlParameter("@Ngay_thu", obj.Ngay_thu) para(9) = New SqlParameter("@Noi_dung", obj.Noi_dung) para(10) = New SqlParameter("@So_tien", obj.So_tien) para(11) = New SqlParameter("@So_tien_chu", obj.So_tien_chu) para(12) = New SqlParameter("@Ngoai_te", obj.Ngoai_te) para(13) = New SqlParameter("@Huy_phieu", obj.Huy_phieu) para(14) = New SqlParameter("@Ghi_chu", obj.Ghi_chu) para(15) = New SqlParameter("@Nguoi_thu", obj.Nguoi_thu) para(16) = New SqlParameter("@Printed", obj.Printed) Return UDB.ExecuteSP("ACC_BienLaiThu_Update", para) Else Dim para(16) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", ID_bien_lai) para(1) = New OracleParameter(":Hoc_ky", obj.Hoc_ky) para(2) = New OracleParameter(":Nam_hoc", obj.Nam_hoc) para(3) = New OracleParameter(":Dot_thu", obj.Dot_thu) para(4) = New OracleParameter(":Lan_thu", obj.Lan_thu) para(5) = New OracleParameter(":ID_sv", obj.ID_sv) para(6) = New OracleParameter(":Thu_chi", obj.Thu_chi) para(7) = New OracleParameter(":So_phieu", obj.So_phieu) para(8) = New OracleParameter(":Ngay_thu", obj.Ngay_thu) para(9) = New OracleParameter(":Noi_dung", obj.Noi_dung) para(10) = New OracleParameter(":So_tien", obj.So_tien) para(11) = New OracleParameter(":So_tien_chu", obj.So_tien_chu) para(12) = New OracleParameter(":Ngoai_te", obj.Ngoai_te) para(13) = New OracleParameter(":Huy_phieu", obj.Huy_phieu) para(14) = New OracleParameter(":Ghi_chu", obj.Ghi_chu) para(15) = New OracleParameter(":Nguoi_thu", obj.Nguoi_thu) para(16) = New OracleParameter(":Printed", obj.Printed) Return UDB.ExecuteSP("ACC_BienLaiThu_Update", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Update_BienLaiThu_HuyPhieu(ByVal ID_bien_lai As Integer, ByVal Ly_do As String) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(1) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", ID_bien_lai) para(1) = New SqlParameter("@Ly_do", Ly_do) Return UDB.ExecuteSP("ACC_BienLaiThu_HuyPhieu_Update", para) Else Dim para(1) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", ID_bien_lai) para(1) = New OracleParameter(":Ly_do", Ly_do) Return UDB.ExecuteSP("ACC_BienLaiThu_HuyPhieu_Update", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Delete_BienLaiThu(ByVal ID_bien_lai As Integer) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", ID_bien_lai) Return UDB.ExecuteSP("ACC_BienLaiThu_Delete", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", ID_bien_lai) Return UDB.ExecuteSP("ACC_BienLaiThu_Delete", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Insert_BienLaiThuChiTiet(ByVal obj As BienLaiThuChiTiet) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(3) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", obj.ID_bien_lai) para(1) = New SqlParameter("@ID_thu_chi", obj.ID_thu_chi) para(2) = New SqlParameter("@ID_mon_tc", obj.ID_mon_tc) para(3) = New SqlParameter("@So_tien", obj.So_tien) Dim dt As DataTable = UDB.SelectTableSP("ACC_BienLaiThuChiTiet_Insert", para) If dt.Rows.Count > 0 Then Return CInt("0" + dt.Rows(0)(0).ToString()) Else Return 0 End If Else Dim para(3) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", obj.ID_bien_lai) para(1) = New OracleParameter(":ID_thu_chi", obj.ID_thu_chi) para(2) = New OracleParameter(":ID_mon_tc", obj.ID_mon_tc) para(3) = New OracleParameter(":So_tien", obj.So_tien) Dim dt As DataTable = UDB.SelectTableSP("ACC_BienLaiThuChiTiet_Insert", para) If dt.Rows.Count > 0 Then Return CInt("0" + dt.Rows(0)(0).ToString()) Else Return 0 End If End If Catch ex As Exception Throw ex End Try End Function Public Function Update_BienLaiThuChiTiet(ByVal obj As BienLaiThuChiTiet, ByVal ID_bien_lai_sub As Integer) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(4) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai_sub", ID_bien_lai_sub) para(1) = New SqlParameter("@ID_bien_lai", obj.ID_bien_lai) para(2) = New SqlParameter("@ID_thu_chi", obj.ID_thu_chi) para(3) = New SqlParameter("@ID_mon_tc", obj.ID_mon_tc) para(4) = New SqlParameter("@So_tien", obj.So_tien) Return UDB.ExecuteSP("ACC_BienLaiThuChiTiet_Update", para) Else Dim para(4) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai_sub", ID_bien_lai_sub) para(1) = New OracleParameter(":ID_bien_lai", obj.ID_bien_lai) para(2) = New OracleParameter(":ID_thu_chi", obj.ID_thu_chi) para(3) = New OracleParameter(":ID_mon_tc", obj.ID_mon_tc) para(4) = New OracleParameter(":So_tien", obj.So_tien) Return UDB.ExecuteSP("ACC_BienLaiThuChiTiet_Update", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Delete_BienLaiThuChiTiet(ByVal ID_bien_lai_sub As Integer) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai_sub", ID_bien_lai_sub) Return UDB.ExecuteSP("ACC_BienLaiThuChiTiet_Delete", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai_sub", ID_bien_lai_sub) Return UDB.ExecuteSP("ACC_BienLaiThuChiTiet_Delete", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Delete_BienLaiThuChiTiet_IDBienLai(ByVal ID_bien_lai As Integer) As Integer Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_bien_lai", ID_bien_lai) Return UDB.ExecuteSP("ACC_BienLaiThuChiTiet_IDBienLai_Delete", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_bien_lai", ID_bien_lai) Return UDB.ExecuteSP("ACC_BienLaiThuChiTiet_IDBienLai_Delete", para) End If Catch ex As Exception Throw ex End Try End Function Public Function Load_MucHocPhiTinChi_List(ByVal Hoc_ky As Integer, ByVal Nam_hoc As String, ByVal ID_he As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(2) As SqlParameter para(0) = New SqlParameter("@Hoc_ky", Hoc_ky) para(1) = New SqlParameter("@Nam_hoc", Nam_hoc) para(2) = New SqlParameter("@ID_he", ID_he) Return UDB.SelectTableSP("ACC_MucHocPhiTinChi_Load", para) Else Dim para(2) As OracleParameter para(0) = New OracleParameter(":Hoc_ky", Hoc_ky) para(1) = New OracleParameter(":Nam_hoc", Nam_hoc) para(2) = New OracleParameter(":ID_he", ID_he) Return UDB.SelectTableSP("ACC_MucHocPhiTinChi_Load", para) End If Catch ex As Exception Throw ex End Try End Function Public Function TongHopThuHocKy(ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopThuHocKy", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopThuHocKy", para) End If Catch ex As Exception Throw ex End Try End Function Public Function TongHopThuMonDangKy(ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopThuMonDangKy", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopThuMonDangKy", para) End If Catch ex As Exception Throw ex End Try End Function Public Function TongHopDaNopHocPhi(ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopDaNopHocPhi", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopDaNopHocPhi", para) End If Catch ex As Exception Throw ex End Try End Function Public Function TongHopDaNopHocPhi_TheoKy(ByVal ID_sv As Integer) As DataTable Try If gDBType = DatabaseType.SQLServer Then Dim para(0) As SqlParameter para(0) = New SqlParameter("@ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopDaNopHocPhi_TheoKy", para) Else Dim para(0) As OracleParameter para(0) = New OracleParameter(":ID_sv", ID_sv) Return UDB.SelectTableSP("ACC_BienLaiTongHopDaNopHocPhi_TheoKy", para) End If Catch ex As Exception Throw ex End Try End Function #End Region End Class End Namespace
Imports Microsoft.VisualStudio.TestTools.UnitTesting <TestClass()> _ Public Class TabuadaTest <TestMethod()> _ <ExpectedException(GetType(TypeInitializationException), "Membro compartilhado foi acessado.")> _ Public Sub CalcularTest() Const valor As Integer = 7 Tabuada.Calcular(valor) End Sub End Class
Imports System.Net.Http Imports Newtonsoft.Json.Linq Module RestDemo Async Function RunAsync() As Task Dim client As New HttpClient With {.BaseAddress = New Uri("https://api.github.com")} #Region " Initialize HttpClient headers " With client.DefaultRequestHeaders .UserAgent.Add("JsonDemo", "0.1") .Accept.Add("application/json") .Authorization.Set("Token", My.Settings.AccessToken) End With #End Region Dim gist = { "description": My.Application.Info.AssemblyName, "public": true, "files": { "RestDemo.vb": { "content": IO.File.ReadAllText("..\..\RestDemo.vb") } } } Dim response = Await client.PostJsonAsync("/gists", gist) Console.WriteLine(response) End Function End Module
'*************************************************************************************** '* UDPReceiver Class '* This class Recveives a UDP command from the Network Light Control Application '* and raises an event to update controls on the ReceiveForm when a command is received '* '* Created By Alex Behlen '* '*************************************************************************************** Imports System.IO Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Threading Public Class UDPReceiver Private _Port As Integer Private _Active As Boolean = True Private _udpServer As UdpClient Private _ipEndPoint As IPEndPoint Private _receiverThread As Thread Public Property Active() As Boolean Get Return _Active End Get Set(value As Boolean) _Active = value End Set End Property Public Sub New(ByVal port As Integer) _Port = port _ipEndPoint = New IPEndPoint(IPAddress.Any, _Port) Active = True End Sub Public Event UpdatePinStatus(ByVal sender As Object, ByVal e As UpdatePinStatusArgs) Public Sub Start() _udpServer = New UdpClient() _udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, True) _udpServer.Client.Bind(_ipEndPoint) ' Create new thread to receive udp packet _receiverThread = New System.Threading.Thread(AddressOf ReceiveMessage) _receiverThread.Start() End Sub Private Sub ReceiveMessage() Do While Active Dim incomingBytes As [Byte]() = _udpServer.Receive(_ipEndPoint) Dim data As String = Encoding.ASCII.GetChars(incomingBytes) Dim pin As Integer Dim status As Integer Integer.TryParse(data.Substring(0, 1), pin) Integer.TryParse(data.Substring(1, 1), status) 'Raise event to update form controls OnUpdatePinStatus(New UpdatePinStatusArgs(pin, status)) Loop End Sub Protected Overridable Sub OnUpdatePinStatus(ByVal e As UpdatePinStatusArgs) RaiseEvent UpdatePinStatus(Me, e) End Sub Public Sub Close() _receiverThread.Abort() _udpServer.Close() Active = False End Sub End Class
Imports Microsoft.VisualBasic Imports System.Data Imports System.Data.SqlClient Imports System.Collections.Generic Imports System.Web.Caching Namespace MB.TheBeerHouse.DAL.SqlClient Public Class SqlStoreProvider Inherits StoreProvider ' Returns a collection with all the departments Public Overrides Function GetDepartments() As System.Collections.Generic.List(Of DepartmentDetails) Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetDepartments", cn) cmd.CommandType = CommandType.StoredProcedure cn.Open() Return GetDepartmentCollectionFromReader(ExecuteReader(cmd)) End Using End Function ' Returns an existing department with the specified ID Public Overrides Function GetDepartmentByID(ByVal departmentID As Integer) As DepartmentDetails Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetDepartmentByID", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = departmentID cn.Open() Dim reader As IDataReader = ExecuteReader(cmd, CommandBehavior.SingleRow) If reader.Read() Then Return GetDepartmentFromReader(reader) Else Return Nothing End If End Using End Function ' Deletes a department Public Overrides Function DeleteDepartment(ByVal departmentID As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_DeleteDepartment", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = departmentID cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Updates a department Public Overrides Function UpdateDepartment(ByVal department As DepartmentDetails) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_UpdateDepartment", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = department.ID cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = department.Title cmd.Parameters.Add("@Importance", SqlDbType.Int).Value = department.Importance cmd.Parameters.Add("@ImageUrl", SqlDbType.NVarChar).Value = department.ImageUrl cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = department.Description cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Creates a new department Public Overrides Function InsertDepartment(ByVal department As DepartmentDetails) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertDepartment", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = department.AddedDate cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = department.AddedBy cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = department.Title cmd.Parameters.Add("@Importance", SqlDbType.Int).Value = department.Importance cmd.Parameters.Add("@ImageUrl", SqlDbType.NVarChar).Value = department.ImageUrl cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = department.Description cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Direction = ParameterDirection.Output cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return CInt(cmd.Parameters("@DepartmentID").Value) End Using End Function ' Returns a collection with all the order statuses Public Overrides Function GetOrderStatuses() As System.Collections.Generic.List(Of OrderStatusDetails) Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetOrderStatuses", cn) cmd.CommandType = CommandType.StoredProcedure cn.Open() Return GetOrderStatusCollectionFromReader(ExecuteReader(cmd)) End Using End Function ' Returns an existing order status with the specified ID Public Overrides Function GetOrderStatusByID(ByVal orderStatusID As Integer) As OrderStatusDetails Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetOrderStatusByID", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderStatusID", SqlDbType.Int).Value = orderStatusID cn.Open() Dim reader As IDataReader = ExecuteReader(cmd, CommandBehavior.SingleRow) If reader.Read() Then Return GetOrderStatusFromReader(reader) Else Return Nothing End If End Using End Function ' Deletes an order status Public Overrides Function DeleteOrderStatus(ByVal orderStatusID As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_DeleteOrderStatus", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderStatusID", SqlDbType.Int).Value = orderStatusID cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Updates an order status Public Overrides Function UpdateOrderStatus(ByVal orderStatus As OrderStatusDetails) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_UpdateOrderStatus", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderStatusID", SqlDbType.Int).Value = orderStatus.ID cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = orderStatus.Title cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Creates a new order status Public Overrides Function InsertOrderStatus(ByVal orderStatus As OrderStatusDetails) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertOrderStatus", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = orderStatus.AddedDate cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = orderStatus.AddedBy cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = orderStatus.Title cmd.Parameters.Add("@OrderStatusID", SqlDbType.Int).Direction = ParameterDirection.Output cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return CInt(cmd.Parameters("@OrderStatusID").Value) End Using End Function ' Returns a collection with all the shipping methods Public Overrides Function GetShippingMethods() As System.Collections.Generic.List(Of ShippingMethodDetails) Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetShippingMethods", cn) cmd.CommandType = CommandType.StoredProcedure cn.Open() Return GetShippingMethodCollectionFromReader(ExecuteReader(cmd)) End Using End Function ' Returns an existing shipping method with the specified ID Public Overrides Function GetShippingMethodByID(ByVal shippingMethodID As Integer) As ShippingMethodDetails Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetShippingMethodByID", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ShippingMethodID", SqlDbType.Int).Value = shippingMethodID cn.Open() Dim reader As IDataReader = ExecuteReader(cmd, CommandBehavior.SingleRow) If reader.Read() Then Return GetShippingMethodFromReader(reader) Else Return Nothing End If End Using End Function ' Deletes a shipping method Public Overrides Function DeleteShippingMethod(ByVal shippingMethodID As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_DeleteShippingMethod", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ShippingMethodID", SqlDbType.Int).Value = shippingMethodID cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Updates a shipping method Public Overrides Function UpdateShippingMethod(ByVal shippingMethod As ShippingMethodDetails) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_UpdateShippingMethod", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ShippingMethodID", SqlDbType.Int).Value = shippingMethod.ID cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = shippingMethod.Title cmd.Parameters.Add("@Price", SqlDbType.Money).Value = shippingMethod.Price cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Creates a new shipping method Public Overrides Function InsertShippingMethod(ByVal shippingMethod As ShippingMethodDetails) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertShippingMethod", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = shippingMethod.AddedDate cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = shippingMethod.AddedBy cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = shippingMethod.Title cmd.Parameters.Add("@Price", SqlDbType.Money).Value = shippingMethod.Price cmd.Parameters.Add("@ShippingMethodID", SqlDbType.Int).Direction = ParameterDirection.Output cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return CInt(cmd.Parameters("@ShippingMethodID").Value) End Using End Function ' Retrieves all products Public Overloads Overrides Function GetProducts(ByVal sortExpression As String, ByVal pageIndex As Integer, ByVal pageSize As Integer) As System.Collections.Generic.List(Of ProductDetails) Using cn As New SqlConnection(Me.ConnectionString) sortExpression = EnsureValidProductsSortExpression(sortExpression) Dim lowerBound As Integer = pageIndex * pageSize + 1 Dim upperBound As Integer = (pageIndex + 1) * pageSize Dim sql As String = String.Format("SELECT * FROM " & _ "(SELECT tbh_Products.ProductID, tbh_Products.AddedDate, tbh_Products.AddedBy, tbh_Products.DepartmentID, tbh_Products.Title, " & _ "tbh_Products.Description, tbh_Products.SKU, tbh_Products.UnitPrice, tbh_Products.DiscountPercentage, " & _ "tbh_Products.UnitsInStock, tbh_Products.SmallImageUrl, tbh_Products.FullImageUrl, tbh_Products.Votes, " & _ "tbh_Products.TotalRating, tbh_Departments.Title AS DepartmentTitle, " & _ "ROW_NUMBER() OVER (ORDER BY {0}) AS RowNum " & _ "FROM tbh_Products INNER JOIN " & _ "tbh_Departments ON tbh_Products.DepartmentID = tbh_Departments.DepartmentID " & _ ") AllProducts " & _ "WHERE AllProducts.RowNum BETWEEN {1} AND {2} " & _ "ORDER BY RowNum ASC", sortExpression, lowerBound, upperBound) Dim cmd As New SqlCommand(sql, cn) cn.Open() Return GetProductCollectionFromReader(ExecuteReader(cmd), False) End Using End Function ' Returns the total number of products Public Overloads Overrides Function GetProductCount() As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetProductCount", cn) cmd.CommandType = CommandType.StoredProcedure cn.Open() Return CInt(ExecuteScalar(cmd)) End Using End Function ' Retrieves all products for the specified department Public Overloads Overrides Function GetProducts(ByVal departmentID As Integer, ByVal sortExpression As String, ByVal pageIndex As Integer, ByVal pageSize As Integer) As System.Collections.Generic.List(Of ProductDetails) Using cn As New SqlConnection(Me.ConnectionString) sortExpression = EnsureValidProductsSortExpression(sortExpression) Dim lowerBound As Integer = pageIndex * pageSize + 1 Dim upperBound As Integer = (pageIndex + 1) * pageSize Dim sql As String = String.Format("SELECT * FROM " & _ "(SELECT tbh_Products.ProductID, tbh_Products.AddedDate, tbh_Products.AddedBy, tbh_Products.DepartmentID, tbh_Products.Title, " & _ "tbh_Products.Description, tbh_Products.SKU, tbh_Products.UnitPrice, tbh_Products.DiscountPercentage, " & _ "tbh_Products.UnitsInStock, tbh_Products.SmallImageUrl, tbh_Products.FullImageUrl, tbh_Products.Votes, " & _ "tbh_Products.TotalRating, tbh_Departments.Title AS DepartmentTitle, " & _ "ROW_NUMBER() OVER (ORDER BY {0}) AS RowNum " & _ "FROM tbh_Products INNER JOIN " & _ "tbh_Departments ON tbh_Products.DepartmentID = tbh_Departments.DepartmentID " & _ "WHERE tbh_Products.DepartmentID = {1} " & _ ") DepartmentProducts " & _ "WHERE DepartmentProducts.RowNum BETWEEN {2} AND {3} " & _ "ORDER BY RowNum ASC", sortExpression, departmentID, lowerBound, upperBound) Dim cmd As New SqlCommand(sql, cn) cn.Open() Return GetProductCollectionFromReader(ExecuteReader(cmd), False) End Using End Function ' Returns the total number of products for the specified department Public Overloads Overrides Function GetProductCount(ByVal departmentID As Integer) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetProductCountByDepartment", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = departmentID cn.Open() Return CInt(ExecuteScalar(cmd)) End Using End Function ' Retrieves the product with the specified ID Public Overrides Function GetProductByID(ByVal productID As Integer) As ProductDetails Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetProductByID", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID cn.Open() Dim reader As IDataReader = ExecuteReader(cmd, CommandBehavior.SingleRow) If reader.Read() Then Return GetProductFromReader(reader, True) Else Return Nothing End If End Using End Function ' Retrieves the description for the product with the specified ID Public Overrides Function GetProductDescription(ByVal productID As Integer) As String Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetProductDescription", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID cn.Open() Return CStr(ExecuteScalar(cmd)) End Using End Function ' Deletes a product Public Overrides Function DeleteProduct(ByVal productID As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_DeleteProduct", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Inserts a new product Public Overrides Function InsertProduct(ByVal product As ProductDetails) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertProduct", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = product.AddedDate cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = product.AddedBy cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = product.DepartmentID cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = product.Title cmd.Parameters.Add("@Description", SqlDbType.NText).Value = product.Description cmd.Parameters.Add("@SKU", SqlDbType.NVarChar).Value = product.SKU cmd.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = product.UnitPrice cmd.Parameters.Add("@DiscountPercentage", SqlDbType.Int).Value = product.DiscountPercentage cmd.Parameters.Add("@UnitsInStock", SqlDbType.Int).Value = product.UnitsInStock cmd.Parameters.Add("@SmallImageUrl", SqlDbType.NVarChar).Value = product.SmallImageURL cmd.Parameters.Add("@FullImageUrl", SqlDbType.NVarChar).Value = product.FullImageUrl cmd.Parameters.Add("@ProductID", SqlDbType.Int).Direction = ParameterDirection.Output cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return CInt(cmd.Parameters("@ProductID").Value) End Using End Function ' Updates a product Public Overrides Function UpdateProduct(ByVal product As ProductDetails) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_UpdateProduct", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = product.ID cmd.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = product.DepartmentID cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = product.Title cmd.Parameters.Add("@Description", SqlDbType.NText).Value = product.Description cmd.Parameters.Add("@SKU", SqlDbType.NVarChar).Value = product.SKU cmd.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = product.UnitPrice cmd.Parameters.Add("@DiscountPercentage", SqlDbType.Int).Value = product.DiscountPercentage cmd.Parameters.Add("@UnitsInStock", SqlDbType.Int).Value = product.UnitsInStock cmd.Parameters.Add("@SmallImageUrl", SqlDbType.NVarChar).Value = product.SmallImageURL cmd.Parameters.Add("@FullImageUrl", SqlDbType.NVarChar).Value = product.FullImageUrl cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Inserts a vote for the specified product Public Overrides Function RateProduct(ByVal productID As Integer, ByVal rating As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertVote", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID cmd.Parameters.Add("@Rating", SqlDbType.Int).Value = rating cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Decrements the UnitsInStock field of the specified quantity for the specified product Public Overrides Function DecrementProductUnitsInStock(ByVal productID As Integer, ByVal quantity As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_DecrementUnitsInStock", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID cmd.Parameters.Add("@Quantity", SqlDbType.Int).Value = quantity cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Retrieves the list of orders for the specified customer Public Overloads Overrides Function GetOrders(ByVal addedBy As String) As System.Collections.Generic.List(Of OrderDetails) Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetOrdersByCustomer", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = addedBy cn.Open() Return GetOrderCollectionFromReader(ExecuteReader(cmd)) End Using End Function ' Retrieves the list of orders in the specified state, and within the specified date range Public Overloads Overrides Function GetOrders(ByVal statusID As Integer, ByVal fromDate As Date, ByVal toDate As Date) As System.Collections.Generic.List(Of OrderDetails) Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetOrdersByStatus", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@StatusID", SqlDbType.Int).Value = statusID cmd.Parameters.Add("@FromDate", SqlDbType.DateTime).Value = fromDate cmd.Parameters.Add("@ToDate", SqlDbType.DateTime).Value = toDate cn.Open() Return GetOrderCollectionFromReader(ExecuteReader(cmd)) End Using End Function ' Retrieves the order with the specified ID Public Overrides Function GetOrderByID(ByVal orderID As Integer) As OrderDetails Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetOrderByID", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = orderID cn.Open() Dim reader As IDataReader = ExecuteReader(cmd, CommandBehavior.SingleRow) If reader.Read() Then Return GetOrderFromReader(reader) Else Return Nothing End If End Using End Function ' Deletes an order Public Overrides Function DeleteOrder(ByVal orderID As Integer) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_DeleteOrder", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = orderID cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Inserts a new order Public Overrides Function InsertOrder(ByVal order As OrderDetails) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertOrder", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = order.AddedDate cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = order.AddedBy cmd.Parameters.Add("@StatusID", SqlDbType.Int).Value = order.StatusID cmd.Parameters.Add("@ShippingMethod", SqlDbType.NVarChar).Value = order.ShippingMethod cmd.Parameters.Add("@SubTotal", SqlDbType.Money).Value = order.SubTotal cmd.Parameters.Add("@Shipping", SqlDbType.Money).Value = order.Shipping cmd.Parameters.Add("@ShippingFirstName", SqlDbType.NVarChar).Value = order.ShippingFirstName cmd.Parameters.Add("@ShippingLastName", SqlDbType.NVarChar).Value = order.ShippingLastName cmd.Parameters.Add("@ShippingStreet", SqlDbType.NVarChar).Value = order.ShippingStreet cmd.Parameters.Add("@ShippingPostalCode", SqlDbType.NVarChar).Value = order.ShippingPostalCode cmd.Parameters.Add("@ShippingCity", SqlDbType.NVarChar).Value = order.ShippingCity cmd.Parameters.Add("@ShippingState", SqlDbType.NVarChar).Value = order.ShippingState cmd.Parameters.Add("@ShippingCountry", SqlDbType.NVarChar).Value = order.ShippingCountry cmd.Parameters.Add("@CustomerEmail", SqlDbType.NVarChar).Value = order.CustomerEmail cmd.Parameters.Add("@CustomerPhone", SqlDbType.NVarChar).Value = order.CustomerPhone cmd.Parameters.Add("@CustomerFax", SqlDbType.NVarChar).Value = order.CustomerFax cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar).Value = order.TransactionID cmd.Parameters.Add("@OrderID", SqlDbType.Int).Direction = ParameterDirection.Output cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return CInt(cmd.Parameters("@OrderID").Value) End Using End Function ' Updates an existing order Public Overrides Function UpdateOrder(ByVal order As OrderDetails) As Boolean Using cn As New SqlConnection(Me.ConnectionString) Dim shippedDate As Object = order.ShippedDate If order.ShippedDate = DateTime.MinValue Then shippedDate = DBNull.Value End If Dim cmd As New SqlCommand("tbh_Store_UpdateOrder", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = order.ID cmd.Parameters.Add("@StatusID", SqlDbType.Int).Value = order.StatusID cmd.Parameters.Add("@ShippedDate", SqlDbType.DateTime).Value = shippedDate cmd.Parameters.Add("@TransactionID", SqlDbType.NVarChar).Value = order.TransactionID cmd.Parameters.Add("@TrackingID", SqlDbType.NVarChar).Value = order.TrackingID cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return (ret = 1) End Using End Function ' Get a collection with all order items for the specified order Public Overrides Function GetOrderItems(ByVal orderID As Integer) As System.Collections.Generic.List(Of OrderItemDetails) Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_GetOrderItems", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = orderID cn.Open() Return GetOrderItemCollectionFromReader(ExecuteReader(cmd)) End Using End Function ' Inserts a new order item Public Overrides Function InsertOrderItem(ByVal orderItem As OrderItemDetails) As Integer Using cn As New SqlConnection(Me.ConnectionString) Dim cmd As New SqlCommand("tbh_Store_InsertOrderItem", cn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = orderItem.AddedDate cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = orderItem.AddedBy cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = orderItem.OrderID cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = orderItem.ProductID cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = orderItem.Title cmd.Parameters.Add("@SKU", SqlDbType.NVarChar).Value = orderItem.SKU cmd.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = orderItem.UnitPrice cmd.Parameters.Add("@Quantity", SqlDbType.Int).Value = orderItem.Quantity cmd.Parameters.Add("@OrderItemID", SqlDbType.Int).Direction = ParameterDirection.Output cn.Open() Dim ret As Integer = ExecuteNonQuery(cmd) Return CInt(cmd.Parameters("@OrderItemID").Value) End Using End Function End Class End Namespace
Namespace Delphi Public Class Table Public Shared Function Names(owner As String) As DataTable Dim x = <x> select t.table_name as NAME, COALESCE(c.comments, '===') as DESCRIPTION, t.num_rows from all_tab_comments c inner JOIN sys.dba_tables t on c.table_name = t.table_name and c.owner = t.owner where Upper(t.owner)=<p><%= owner.ToUpper %></p> and not t.table_name like 'V45_%' and not t.table_name like 'TMP%' order by t.table_name </x> Return Query.ExecuteDatatable(x) End Function Public Shared Function Description(owner As String, tablename As String) As String Dim x = <x> select c.comments as DESCRIPTION from all_tab_comments c inner JOIN sys.dba_tables t on c.table_name = t.table_name and c.owner = t.owner where Upper(t.owner)=<p><%= owner.ToUpperInvariant %></p> and Upper(t.table_name)=<p><%= tablename.ToUpperInvariant %></p> </x> Dim ar = Query.ExecuteArray(x) Return ar.FirstOrDefault() End Function Public Shared Function Columns(owner As String, tablename As String) As DataTable Dim x = <x> select COLUMN_NAME as NAME, COMMENTS as DESCRIPTION from all_col_comments where owner=<p><%= owner %></p> and TABLE_NAME=<p><%= tablename %></p> </x> Return Query.ExecuteDatatable(x) End Function Public Shared Function HeapTables(owner As String) As String() Dim dt = Names(owner) Dim nameindex = dt.Columns("NAME").Ordinal Dim qy = From r In dt.Rows.Cast(Of DataRow) Select tablename = r.Item(nameindex).ToString Where Not PrimaryKeyColumns(owner, tablename).Any Select String.Concat(owner, ".", tablename) Return qy.ToArray End Function Public Shared Function PrimaryKeyColumns(owner As String, tablename As String) As String() Dim cached = PKCache.PKs(owner, tablename) If cached IsNot Nothing Then Return cached Dim x = <x> SELECT c_src.COLUMN_NAME FROM ALL_CONSTRAINTS c_list INNER JOIN ALL_CONS_COLUMNS c_src ON c_list.CONSTRAINT_NAME = c_src.CONSTRAINT_NAME AND c_list.OWNER = c_src.OWNER WHERE c_list.CONSTRAINT_TYPE = 'P' AND c_list.OWNER = <p><%= owner %></p> AND c_list.TABLE_NAME = <p><%= tablename %></p> ORDER BY c_src.POSITION </x> Return Query.ExecuteArray(x) End Function Public Shared Function PointersAndLists(owner As String, tablename As String) As DataTable Static cache As New Concurrent.ConcurrentDictionary(Of Tuple(Of String, String), DataTable) Return cache.GetOrAdd(Tuple.Create(owner, tablename), AddressOf PointersAndListsImpl) End Function Private Shared Function PointersAndListsImpl(Owner_Tablename As Tuple(Of String, String)) As DataTable Dim owner = Owner_Tablename.Item1 Dim tablename = Owner_Tablename.Item2 Query.AssertIdentifier(owner, NameOf(owner)) Query.AssertIdentifier(tablename, NameOf(tablename)) Dim cached = FKCache.FKs(owner, tablename) If cached IsNot Nothing Then Return cached Dim x = <x> SELECT c_list.CONSTRAINT_NAME as key, c_list.TABLE_NAME as srctable, c_src.COLUMN_NAME as srccolumn, c_dest.TABLE_NAME as desttable, c_dest.COLUMN_NAME as destcolumn, c_src.POSITION as position FROM ALL_CONSTRAINTS c_list INNER JOIN ALL_CONS_COLUMNS c_src ON c_list.CONSTRAINT_NAME = c_src.CONSTRAINT_NAME AND c_list.OWNER = c_src.OWNER INNER JOIN ALL_CONS_COLUMNS c_dest ON c_list.R_CONSTRAINT_NAME = c_dest.CONSTRAINT_NAME AND c_list.R_OWNER = c_dest.OWNER WHERE c_list.CONSTRAINT_TYPE = 'R' AND c_src.POSITION = c_dest.POSITION AND ( c_list.OWNER = <p><%= owner %></p> AND c_list.TABLE_NAME = <p><%= tablename %></p> OR c_dest.OWNER = <p><%= owner %></p> AND c_dest.TABLE_NAME = <p><%= tablename %></p> ) ORDER BY c_list.TABLE_NAME, c_dest.TABLE_NAME, c_list.CONSTRAINT_NAME, c_src.POSITION </x> Return Query.ExecuteDatatable(x) End Function Private Shared Function isEqual(d1 As DataTable, d2 As DataTable) As Boolean Dim a = asString(d1) Dim b = asString(d2) If a = b Then Return True Dim linesA = Split(a, ControlChars.CrLf) Dim linesB = Split(b, ControlChars.CrLf) For i = 0 To Math.Min(linesA.Count, linesB.Count) - 1 If linesA(i) = linesB(i) Then Continue For Console.WriteLine("line {0,4}: {1,-40} {2,-40}", i + 1, linesA(i), linesB(i)) Next Return False End Function Private Shared Function asString(d As DataTable) As String d.TableName = "d1" Dim sb = New Text.StringBuilder Using sw = New IO.StringWriter(sb) d.WriteXml(sw) End Using Return sb.ToString End Function End Class End Namespace
Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Drawing Imports devDept.Geometry Imports devDept.Eyeshot.Entities Imports devDept.Eyeshot Imports devDept.Graphics ''' <summary> ''' Contains all methods required to draw different entities interactively ''' </summary> Partial Class MyModel ' Draws interactive/elastic lines as per user clicks on mouse move Private Sub DrawInteractiveLines() If points.Count = 0 Then Return End If Dim screenPts() As Point2D = GetScreenVertices(points) renderContext.DrawLineStrip(screenPts) If ActionMode = actionType.None AndAlso Not GetToolBar().Contains(mouseLocation) AndAlso points.Count > 0 Then ' Draw elastic line renderContext.DrawLine(screenPts(screenPts.Length - 1), WorldToScreen(current)) End If End Sub Private Function GetScreenVertices(ByVal vertices As IList(Of Point3D)) As Point2D() Dim screenPts(vertices.Count - 1) As Point2D For i As Integer = 0 To vertices.Count - 1 screenPts(i) = WorldToScreen(vertices(i)) Next i Return screenPts End Function ' Draws interactive circle (rubber-band) on mouse move with fixed center Private Sub DrawInteractiveCircle() radius = points(0).DistanceTo(current) If radius > 1e-3 Then drawingPlane = GetPlane(current) DrawPositionMark(points(0)) Dim tempCircle As New Circle(drawingPlane, points(0), radius) Draw(tempCircle) End If End Sub ' Draws interactive leader Private Sub DrawInteractiveLeader() renderContext.EnableXOR(False) Dim text As String If points.Count = 0 Then text = "Select the first point" ElseIf points.Count = 1 Then text = "Select the second point" Else text = "Select the third point" End If DrawText(mouseLocation.X, CInt(Size.Height) - mouseLocation.Y + 10, text, New Font("Tahoma", 8.25F), DrawingColor, ContentAlignment.BottomLeft) renderContext.EnableXOR(True) DrawInteractiveLines() End Sub Private Function GetPlane(ByVal [next] As Point3D) As Plane Dim xAxis As New Vector3D(points(0), [next]) xAxis.Normalize() Dim yAxis As Vector3D = Vector3D.Cross(Vector3D.AxisZ, xAxis) yAxis.Normalize() Dim plane As New Plane(points(0), xAxis, yAxis) Return plane End Function ' Draws interactive arc with selected center point position and two end points Private Sub DrawInteractiveArc() Dim screenPts() As Point2D = GetScreenVertices(points) renderContext.DrawLineStrip(screenPts) If ActionMode = actionType.None AndAlso Not GetToolBar().Contains(mouseLocation) AndAlso points.Count > 0 Then ' Draw elastic line renderContext.DrawLine(WorldToScreen(points(0)), WorldToScreen(current)) 'draw three point arc If points.Count = 2 Then radius = points(0).DistanceTo(points(1)) If radius > 1e-3 Then drawingPlane = GetPlane(points(1)) Dim v1 As New Vector2D(points(0), points(1)) v1.Normalize() Dim v2 As New Vector2D(points(0), current) v2.Normalize() arcSpanAngle = Vector2D.SignedAngleBetween(v1, v2) If Math.Abs(arcSpanAngle) > 1e-3 Then Dim tempArc As New Arc(drawingPlane, drawingPlane.Origin, radius, 0, arcSpanAngle) Draw(tempArc) End If End If End If End If End Sub ' Draws interactive ellipse on mouse move with fixed center and given axis ends ' Inputs - Ellipse center, End of first axis, End of second axis Private Sub DrawInteractiveEllipse() If drawingEllipticalArc AndAlso points.Count > 2 Then Return End If If points.Count = 1 Then ' Draw elastic line renderContext.DrawLine(WorldToScreen(points(0)), WorldToScreen(current)) End If If points.Count < 2 Then Return End If radius = points(0).DistanceTo(points(1)) radiusY = current.DistanceTo(New Segment2D(points(0), points(1))) If radius > 1e-3 AndAlso radiusY > 1e-3 Then drawingPlane = GetPlane(points(1)) DrawPositionMark(points(0)) Dim tempEllipse As New Ellipse(drawingPlane, drawingPlane.Origin, radius, radiusY) Draw(tempEllipse) End If End Sub Private Sub Draw(ByVal theCurve As ICurve) If TypeOf theCurve Is CompositeCurve Then Dim compositeCurve As CompositeCurve = TryCast(theCurve, CompositeCurve) Dim explodedCurves() As Entity = compositeCurve.Explode() For Each ent As Entity In explodedCurves DrawScreenCurve(DirectCast(ent, ICurve)) Next ent Else DrawScreenCurve(theCurve) End If End Sub Private Sub DrawScreenCurve(ByVal curve As ICurve) Const subd As Integer = 100 Dim pts(subd) As Point3D For i As Integer = 0 To subd pts(i) = WorldToScreen(curve.PointAt(curve.Domain.ParameterAt(CDbl(i)/subd))) Next i renderContext.DrawLineStrip(pts) End Sub ' Draws interactive elliptical arc ' Inputs - Ellipse center, End of first axis, End of second axis, Start and End point Private Sub DrawInteractiveEllipticalArc() Dim center As Point3D = points(0) If points.Count <= 3 Then DrawInteractiveEllipse() End If ScreenToPlane(mouseLocation, plane, current) If points.Count = 3 Then ' ellipse completed, ask user to select start point 'start position line renderContext.DrawLine(WorldToScreen(center), WorldToScreen(points(1))) 'current position line renderContext.DrawLine(WorldToScreen(center), WorldToScreen(current)) 'arc portion radius = center.DistanceTo(points(1)) radiusY = points(2).DistanceTo(New Segment2D(center, points(1))) If radius > 1e-3 AndAlso radiusY > 1e-3 Then DrawPositionMark(points(0)) drawingPlane = GetPlane(points(1)) Dim v1 As New Vector2D(center, points(1)) v1.Normalize() Dim v2 As New Vector2D(center, current) v2.Normalize() arcSpanAngle = Vector2D.SignedAngleBetween(v1, v2) If Math.Abs(arcSpanAngle) > 1e-3 Then Dim tempArc As New EllipticalArc(drawingPlane, drawingPlane.Origin, radius, radiusY, 0, arcSpanAngle, True) Draw(tempArc) End If End If End If End Sub ' Draws interactive/elastic spline curve interpolated from selected points Private Sub DrawInteractiveCurve() #If NURBS Then Dim plusOne As New List(Of Point3D)(points) plusOne.Add(GetSnappedPoint(mouseLocation, plane, points, 0)) ' Cubic interpolation needs at least 3 points If points.Count > 1 Then Dim tempCurve As Curve = Curve.CubicSplineInterpolation(plusOne) Draw(tempCurve) Else renderContext.DrawLineStrip(GetScreenVertices(plusOne)) End If #End If End Sub Private Function GetSnappedPoint(ByVal mousePos As System.Drawing.Point, ByVal plane As Plane, ByVal pts As IList(Of Point3D), ByVal indexToCompare As Integer) As Point3D ' if the mouse in within 10 pixels of the first curve point, return the first point If pts.Count > 0 Then Dim ptToSnap As Point3D = pts(indexToCompare) Dim ptSnapScreen As Point3D = WorldToScreen(ptToSnap) Dim current As New Point2D(mousePos.X, Size.Height - mousePos.Y) If Point2D.Distance(current, ptSnapScreen) < 10 Then Return DirectCast(ptToSnap.Clone(), Point3D) End If End If Dim pt As Point3D = Nothing ScreenToPlane(mousePos, plane, pt) Return pt End Function 'Checks if polyline or curve can be closed polygon Public Function IsPolygonClosed() As Boolean If points.Count > 0 AndAlso (drawingCurve OrElse drawingPolyLine) AndAlso (points(0).DistanceTo(current) < magnetRange) Then Return True End If Return False End Function 'Draws pickbox at current mouse location Public Sub DrawSelectionMark(ByVal current As System.Drawing.Point) Dim mySize As Double = PickBoxSize Dim dim1 As Double = current.X + (mySize/2) Dim dim2 As Double = Size.Height - current.Y + (mySize / 2) Dim dim3 As Double = current.X - (mySize/2) Dim dim4 As Double = Size.Height - current.Y - (mySize / 2) Dim topLeftVertex As New Point3D(dim3, dim2) Dim topRightVertex As New Point3D(dim1, dim2) Dim bottomRightVertex As New Point3D(dim1, dim4) Dim bottomLeftVertex As New Point3D(dim3, dim4) renderContext.DrawLines(New Point3D() { bottomLeftVertex, bottomRightVertex, bottomRightVertex, topRightVertex, topRightVertex, topLeftVertex, topLeftVertex, bottomLeftVertex }) renderContext.SetLineSize(1) End Sub ' Draws a plus sign (+) at current mouse location Private Sub DrawPositionMark(ByVal current As Point3D, Optional ByVal crossSide As Double = 20.0) If IsPolygonClosed() Then current = points(0) End If If gridSnapEnabled Then If SnapToGrid(current) Then renderContext.SetLineSize(4) End If End If Dim currentScreen As Point3D = WorldToScreen(current) ' Compute the direction on screen of the horizontal line Dim left As Point2D = WorldToScreen(current.X - 1, current.Y, 0) Dim dirHorizontal As Vector2D = Vector2D.Subtract(left, currentScreen) dirHorizontal.Normalize() ' Compute the position on screen of the line endpoints left = currentScreen + dirHorizontal*crossSide Dim right As Point2D = currentScreen - dirHorizontal * crossSide renderContext.DrawLine(left, right) ' Compute the direction on screen of the vertical line Dim bottom As Point2D = WorldToScreen(current.X, current.Y - 1, 0) Dim dirVertical As Vector2D = Vector2D.Subtract(bottom, currentScreen) dirVertical.Normalize() ' Compute the position on screen of the line endpoints bottom = currentScreen + dirVertical * crossSide Dim top As Point2D = currentScreen - dirVertical * crossSide renderContext.DrawLine(bottom, top) renderContext.SetLineSize(1) End Sub #Region "Flags indicating current drawing mode" Public drawingPoints As Boolean Public drawingText As Boolean Public drawingLeader As Boolean Public drawingEllipse As Boolean Public drawingEllipticalArc As Boolean Public drawingLine As Boolean Public drawingCurve As Boolean Public drawingCircle As Boolean Public drawingArc As Boolean Public drawingPolyLine As Boolean #End Region End Class
#Region "Microsoft.VisualBasic::63770385240196eaeb181a8f7f496656, mzkit\src\mzmath\ms2_math-core\Spectra\Models\Xml\SSM2MatrixFragment.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Code Statistics: ' Total Lines: 58 ' Code Lines: 40 ' Comment Lines: 8 ' Blank Lines: 10 ' File Size: 1.75 KB ' Class SSM2MatrixFragment ' ' Properties: da, mz, query, ref ' ' Function: createFragment, FromXml, ToString ' ' ' /********************************************************************************/ #End Region Imports System.Xml Imports System.Xml.Serialization Namespace Spectra.Xml ''' <summary> ''' tuple data of [mz, query_intensity, reference_intensity] ''' </summary> Public Class SSM2MatrixFragment ''' <summary> ''' The m/z value of the query fragment ''' </summary> ''' <returns></returns> <XmlAttribute> Public Property mz As Double #Region "Fragment intensity" <XmlAttribute> Public Property query As Double <XmlAttribute> Public Property ref As Double #End Region ''' <summary> ''' Mass delta between the query and reference fragment in unit ``da`` ''' </summary> ''' <returns></returns> <XmlAttribute> Public Property da As String Public Shared Function FromXml(node As XmlNode, nodeName$) As SSM2MatrixFragment() Return (From child As XmlNode In node.ChildNodes Where child.Name = nodeName) _ _ .Select(AddressOf createFragment) _ .ToArray End Function Private Shared Function createFragment(feature As XmlNode) As SSM2MatrixFragment Dim data = feature.Attributes Dim mz, query, ref As Double Dim da As String With data mz = !mz.Value query = !query.Value.ParseDouble ref = !ref.Value.ParseDouble da = !da.Value End With Return New SSM2MatrixFragment With { .mz = mz, .query = query, .ref = ref, .da = da } End Function Public Overrides Function ToString() As String Return mz End Function End Class End Namespace
Imports Brilliantech.Packaging.Data Public Interface IWorkStationRepo Inherits IBaseRepo(Of WorkStation) Function GetByProdLineID(prodLineID As String) As IEnumerable(Of WorkStation) Function GetByProjectId(projectId As String) As IEnumerable(Of WorkStation) End Interface
Imports System.Collections.Specialized Imports System.Web Imports System.Text ''' <summary> ''' reads the query string, as well as setting it's values. Then forwards the responce to an apropriate query string url. ''' </summary> ''' <remarks></remarks> #If DEBUG Then Public Class QueryStringChanger Inherits System.Collections.Specialized.NameValueCollection #Else <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _ Public Class QueryStringChanger Inherits System.Collections.Specialized.NameValueCollection #End If ''' <summary> ''' Default constructor examins current request query string. ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("Default constructor examins current request query string.")> _ Public Sub New() For Each key As String In HttpContext.Current.Request.QueryString.AllKeys Add(key, HttpContext.Current.Request.QueryString(key)) Next End Sub ''' <summary> ''' Return the current query string. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Return the current query string.")> _ Public Overrides Function ToString() As String Dim sb As StringBuilder = New StringBuilder For Each key As String In Me.Keys If Keys(0) = key Then sb.Append("?" & key & "=" & HttpContext.Current.Server.UrlEncode(Me(key))) Else sb.Append("&" & key & "=" & HttpContext.Current.Server.UrlEncode(Me(key))) End If Next Return sb.ToString End Function ''' <summary> ''' Add a key/value string pair to the query ''' </summary> ''' <param name="key"></param> ''' <param name="value"></param> ''' <remarks></remarks> <System.ComponentModel.Description("Add a key/value string pair to the query")> _ Public Overrides Sub Add(ByVal key As String, ByVal value As String) Try If Me.GetValues(key).Length > 0 Then Me(key) = value Else MyBase.Add(key, value) End If Catch ex As Exception MyBase.Add(key, value) End Try End Sub ''' <summary> ''' Returns the full url with reformatted query. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("Returns the full url with reformatted query.")> _ Public ReadOnly Property FullUrl() As String Get Dim redirectstr As String Try redirectstr = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.Query, "") & Me.ToString Catch ex As Exception redirectstr = HttpContext.Current.Request.Url.AbsoluteUri & Me.ToString End Try Return redirectstr End Get End Property ''' <summary> ''' Redirects the responce to the formatted url/query ''' </summary> ''' <param name="endResponse"></param> ''' <remarks></remarks> <System.ComponentModel.Description("Redirects the responce to the formatted url/query")> _ Public Sub redirectToMyUrl(Optional ByVal endResponse As Boolean = False) HttpContext.Current.Response.Redirect(Me.FullUrl, endResponse) End Sub ''' <summary> ''' removes a given key ''' </summary> ''' <param name="name"></param> ''' <remarks></remarks> <System.ComponentModel.Description("removes a given key")> _ Public Overrides Sub Remove(ByVal name As String) Try MyBase.Remove(name) Catch ex As Exception End Try End Sub ''' <summary> ''' replaces an existing query value and redirects the url immediatly. ''' </summary> ''' <param name="key"></param> ''' <param name="value"></param> ''' <param name="endResponse"></param> ''' <remarks></remarks> <System.ComponentModel.Description("replaces an existing query value and redirects the url immediatly.")> _ Public Shared Sub ReplaceQuery(ByVal key As String, ByVal value As String, Optional ByVal endResponse As Boolean = False) Dim mqs As New QueryStringChanger mqs.Add(key, value) HttpContext.Current.Response.Redirect(mqs.FullUrl, endResponse) End Sub ''' <summary> ''' replace a query value and returns the new full url. ''' </summary> ''' <param name="key"></param> ''' <param name="value"></param> ''' <returns></returns> ''' <remarks></remarks> <System.ComponentModel.Description("replace a query value and returns the new full url.")> _ Public Shared Function ReturnReplaceQuery(ByVal key As String, ByVal value As String) As String Dim mqs As New QueryStringChanger mqs.Add(key, value) Return mqs.FullUrl End Function End Class
Imports System Imports Rhino Imports Rhino.Commands Namespace SampleVbCommands <System.Runtime.InteropServices.Guid("4a966a05-e5b8-4aaf-a098-5231b80d0a67")> _ Public Class SampleVbExplodeHatch Inherits Command ''' <returns> ''' The command name as it appears on the Rhino command line. ''' </returns> Public Overrides ReadOnly Property EnglishName() As String Get Return "SampleVbExplodeHatch" End Get End Property ''' <summary> ''' Called by Rhino to run the command. ''' </summary> Protected Overrides Function RunCommand(ByVal doc As RhinoDoc, ByVal mode As RunMode) As Result Dim filter As Rhino.DocObjects.ObjectType = Rhino.DocObjects.ObjectType.Hatch Dim objref As Rhino.DocObjects.ObjRef = Nothing Dim rc As Rhino.Commands.Result = Rhino.Input.RhinoGet.GetOneObject("Select hatch to explode", False, filter, objref) If rc <> Rhino.Commands.Result.Success OrElse objref Is Nothing Then Return rc End If Dim hatch As Rhino.Geometry.Hatch = DirectCast(objref.Geometry(), Rhino.Geometry.Hatch) If hatch Is Nothing Then Return Rhino.Commands.Result.Failure End If Dim hatch_geom As Rhino.Geometry.GeometryBase() = hatch.Explode() If hatch_geom IsNot Nothing Then For i As Integer = 0 To hatch_geom.Length - 1 Dim geom As Rhino.Geometry.GeometryBase = hatch_geom(i) If geom IsNot Nothing Then Select Case geom.ObjectType Case Rhino.DocObjects.ObjectType.Point If True Then Dim point As Rhino.Geometry.Point = DirectCast(geom, Rhino.Geometry.Point) If point IsNot Nothing Then doc.Objects.AddPoint(point.Location) End If End If Exit Select Case Rhino.DocObjects.ObjectType.Curve If True Then Dim curve As Rhino.Geometry.Curve = DirectCast(geom, Rhino.Geometry.Curve) If curve IsNot Nothing Then doc.Objects.AddCurve(curve) End If End If Exit Select Case Rhino.DocObjects.ObjectType.Brep If True Then Dim brep As Rhino.Geometry.Brep = DirectCast(geom, Rhino.Geometry.Brep) If brep IsNot Nothing Then doc.Objects.AddBrep(brep) End If End If Exit Select End Select End If Next End If Return Result.Success End Function End Class End Namespace
Public MustInherit Class Animal Protected _name As String Public ReadOnly Property Name As String Get Return _name End Get End Property Public Sub New(Name As String) _name = Name End Sub MustOverride Sub makeSound() Public Overrides Function ToString() As String Return Me.GetType().ToString & ":" & Name End Function End Class
Public Class LogAuditoria Public Property LOG_USER_ID As String Public Property LOG_USER_CC As String Public Property LOG_HOST As String Public Property LOG_IP As String Public Property LOG_FECHA As Date Public Property LOG_APLICACION As String Public Property LOG_MODULO As String Public Property LOG_DOC_AFEC As String Public Property LOG_CONSULTA As String Public Property LOG_CONSE As Integer Public Property LOG_NEGOCIO As String End Class
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' NotaCredito.vb '' Implementation of the Class NotaCredito '' Generated by Enterprise Architect '' Created on: 29-ago-2018 09:52:22 p.m. '' Original author: Hernan '' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' Modification history: '' '' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Option Explicit On Public Class NotaCredito 'Public m_DB As DAL.DB ''' ''' <param name="obj"></param> Public Shared Function add(ByVal obj As BE.Factura) As Boolean add = False End Function ''' ''' <param name="obj"></param> ''' <param name="pdf"></param> Public Shared Function savePdf(ByVal obj As BE.NotaCredito, ByVal pdf As Byte) As Boolean savePdf = False End Function End Class ' NotaCredito
Imports domain_management.Interfaces Imports domain_management.Entities Imports domain_management.DataAccess Namespace Repositories Public Class NotificationLogRepository Inherits GenericRepository(Of NotificationLog) Implements INotificationLogRepository Public Sub New(ByVal context As DomainMgrContexts) MyBase.New(context) End Sub End Class End Namespace
Imports RTIS.CommonVB Imports RTIS.DataLayer Public Class dsoProductAdmin : Inherits dsoBase '' Private pDBConn As clsDBConnBase Public Sub New(ByRef rDBConn As clsDBConnBase) MyBase.New(rDBConn) End Sub Public Function LoadProductConstructionTypesAll(ByRef rProductConstructionTypes As colProductConstructionTypes) As Boolean Dim mdto As dtoProductConstructionType Dim mRetVal As Boolean = False Try pDBConn.Connect() mdto = New dtoProductConstructionType(pDBConn) mdto.LoadProductConstructionTypeCollection(rProductConstructionTypes) mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try Return mRetVal End Function Public Sub LoadProductStructureDown(ByRef rProductStructure As dmProductStructure, ByVal vProductID As Integer) Dim mdtoProduct As dtoProductBase Dim mdtoProductBOM As dtoProductBOM Dim mdtoPOFiles As dtoFileTracker Dim mRetVal As Boolean = False Try pDBConn.Connect() mdtoProduct = dtoProductBase.GetNewInstance(eProductType.StructureAF, pDBConn) mdtoProduct.LoadProduct(rProductStructure, vProductID) If rProductStructure IsNot Nothing Then mdtoProductBOM = New dtoProductBOM(pDBConn) mdtoProductBOM.LoadProductBOMCollection(rProductStructure.ProductStockItemBOMs, rProductStructure.ID, eProductBOMObjectType.StockItems) mdtoProductBOM.LoadProductBOMCollection(rProductStructure.ProductWoodBOMs, rProductStructure.ID, eProductBOMObjectType.Wood) mdtoPOFiles = New dtoFileTracker(pDBConn) mdtoPOFiles.LoadFileTrackerCollection(rProductStructure.POFiles, eObjectType.ProductStructure, rProductStructure.ID) End If mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try End Sub Public Sub SaveProductStructureDown(ByRef rProductStructure As dmProductStructure) Dim mdtoProduct As dtoProductBase Dim mdtoProductBOM As New dtoProductBOM(pDBConn) Dim mdtoPOFiles As dtoFileTracker Dim mRetVal As Boolean = False Try pDBConn.Connect() mdtoProduct = dtoProductBase.GetNewInstance(eProductType.StructureAF, pDBConn) mdtoProduct.SaveProduct(rProductStructure) If rProductStructure IsNot Nothing Then mdtoProductBOM = New dtoProductBOM(pDBConn) mdtoProductBOM.SaveProductBOMCollection(rProductStructure.ProductStockItemBOMs, rProductStructure.ID, eProductBOMObjectType.StockItems) mdtoProductBOM.SaveProductBOMCollection(rProductStructure.ProductWoodBOMs, rProductStructure.ID, eProductBOMObjectType.Wood) mdtoPOFiles = New dtoFileTracker(pDBConn) mdtoPOFiles.SaveFileTrackerCollection(rProductStructure.POFiles, eObjectType.ProductStructure, rProductStructure.ID) 'mdtoComponents = New dtoProductFurnitureComponent(pDBConn) 'mdtoComponents.SaveProductFurnitureComponentCollection(mProductStructure.ProductFurnitureComponents, mProductStructure.ProductFurnitureID) End If mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try End Sub Public Function LoadProductConstructionSubTypesAll(ByRef rProductConstructionSubTypes As colProductConstructionSubTypes) As Boolean Dim mdto As dtoProductConstructionSubType Dim mRetVal As Boolean = False Try pDBConn.Connect() mdto = New dtoProductConstructionSubType(pDBConn) mdto.LoadAllProductConstructionSubTypeCollection(rProductConstructionSubTypes) mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try Return mRetVal End Function Public Function LoadProductConstructionSubTypesByTypeID(ByRef rProductConstructionSubTypes As colProductConstructionSubTypes, ByVal vProductConstructionItemType As Integer) As Boolean Dim mdto As dtoProductConstructionSubType Dim mRetVal As Boolean = False Try pDBConn.Connect() mdto = New dtoProductConstructionSubType(pDBConn) mdto.LoadProductConstructionSubTypeCollectionByItemTypeID(rProductConstructionSubTypes, vProductConstructionItemType) mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try Return mRetVal End Function Public Function LoadHouseTypeDown(ByRef rHouseType As dmHouseType, ByVal vHouseTypeID As Integer) As Boolean Dim mdto As dtoHouseType Dim mdtoSIA As dtoSalesItemAssembly Dim mdtoHouseTypeSalesItems As dtoHouseTypeSalesItem Dim mRetVal As Boolean = False Try pDBConn.Connect() mdto = New dtoHouseType(pDBConn) mdto.LoadHouseType(rHouseType, vHouseTypeID) mdtoSIA = New dtoSalesItemAssembly(pDBConn, dtoSalesItemAssembly.eMode.HouseTypeSalesItemAssembly) mdtoSIA.LoadSalesItemAssemblyCollection(rHouseType.SalesItemAssemblys, rHouseType.HouseTypeID) mdtoHouseTypeSalesItems = New dtoHouseTypeSalesItem(pDBConn) mdtoHouseTypeSalesItems.LoadHouseTypeSalesItemsCollection(rHouseType.HTSalesItems, rHouseType.HouseTypeID) mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try Return mRetVal End Function Public Function SaveHouseTypeDown(ByRef rHouseType As dmHouseType) As Boolean Dim mdto As dtoHouseType Dim mdtoSIA As dtoSalesItemAssembly Dim mdtoHouseTypeSalesItems As dtoHouseTypeSalesItem Dim mRetVal As Boolean = False Try pDBConn.Connect() mdto = New dtoHouseType(pDBConn) mdto.SaveHouseType(rHouseType) mdtoSIA = New dtoSalesItemAssembly(pDBConn, dtoSalesItemAssembly.eMode.HouseTypeSalesItemAssembly) mdtoSIA.SaveSalesItemAssemblyCollection(rHouseType.SalesItemAssemblys, rHouseType.HouseTypeID) mdtoHouseTypeSalesItems = New dtoHouseTypeSalesItem(pDBConn) mdtoHouseTypeSalesItems.SaveHouseTypeSalesItemsCollection(rHouseType.HTSalesItems, rHouseType.HouseTypeID) mRetVal = True Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Connect() End Try Return mRetVal End Function Public Function LoadHouseTypeInfos(ByRef rHouseTypeInfos As colHouseTypeInfos) As Boolean Dim mdto As dtoHouseTypeInfo Dim mRetval As Boolean Try pDBConn.Connect() mdto = New dtoHouseTypeInfo(pDBConn) mdto.LoadHouseTypeInfoCollectionByWhere(rHouseTypeInfos, "") Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try Return mRetval End Function Public Function LockHouseTypeDisconnected(ByVal vPrimaryKeyID As Integer) As Boolean Dim mOK As Boolean Try pDBConn.Connect() mOK = MyBase.LockTableRecord(appLockEntitys.cCustomer, vPrimaryKeyID) Catch ex As Exception mOK = False If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try Return mOK End Function Public Function UnlockHouseTypeDisconnected(ByVal vPrimaryKeyID As Integer) As Boolean Dim mOK As Boolean Try pDBConn.Connect() mOK = MyBase.UnlockTableRecord(appLockEntitys.cCustomer, vPrimaryKeyID) Catch ex As Exception mOK = False If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try Return mOK End Function Public Function GetNextProductConstructionCodeNo(ByVal vProductCode As String, ByVal vProductType As Integer) As Integer Dim mRetVal As Integer Try pDBConn.Connect() mRetVal = GetNextProductCodeNoConnected(vProductCode, vProductType) Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try Return mRetVal End Function Public Sub LoadHouseTypes(ByRef rHouseTypes As colHouseTypes) Try Dim mdto As New dtoHouseType(pDBConn) pDBConn.Connect() mdto.LoadHouseTypeCollection(rHouseTypes) Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Function SaveProductBase(ByRef rProductBase As clsProductBaseInfo) As Boolean Dim mdtoProductBase As dtoProductBase Dim mdtoProductBOM As dtoProductBOM Try pDBConn.Connect() If rProductBase.Product IsNot Nothing Then mdtoProductBase = dtoProductBase.GetNewInstance(rProductBase.Product.ProductTypeID, pDBConn) mdtoProductBase.SaveProduct(rProductBase.Product) If rProductBase.Product IsNot Nothing Then mdtoProductBOM = New dtoProductBOM(pDBConn) End If End If Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Function Public Sub LoadProductInfosByWhere(ByRef rProductInfos As colProductBaseInfos, ByVal vWhere As String) Dim mdto As dtoProductInfo Try pDBConn.Connect() 'mdto = New dtoProductInfo(pDBConn, dtoProductInfo.eMode.Installation) 'mdto.LoadProductInfosCollection(rProductInfos) mdto = New dtoProductInfo(pDBConn, dtoProductInfo.eMode.AFStructure) mdto.LoadProductInfosCollection(rProductInfos, vWhere) Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Sub LoadProductInfosStructureOnly(ByRef rProductInfos As colProductBaseInfos) Dim mdto As dtoProductInfo Try pDBConn.Connect() mdto = New dtoProductInfo(pDBConn, dtoProductInfo.eMode.AFStructure) mdto.LoadProductInfosCollection(rProductInfos, "") Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Sub LoadProductInstallations(ByRef rProducts As colProductBases) Dim mdtoInstallation As dtoProductInstallation Dim mProductInstallations As New colProductInstallations Try pDBConn.Connect() mdtoInstallation = New dtoProductInstallation(pDBConn) mdtoInstallation.LoadProductInstallationCollection(mProductInstallations) For Each mProduct As dmProductBase In mProductInstallations rProducts.Add(mProduct) Next Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Sub LoadProductStructures(ByRef rProducts As colProductBases) Dim mdtoProductStructure As dtoProductStructure Dim mProductStructures As New colProductStructures Try pDBConn.Connect() mdtoProductStructure = New dtoProductStructure(pDBConn) mdtoProductStructure.LoadProductStructureCollection(mProductStructures) For Each mProduct As dmProductBase In mProductStructures rProducts.Add(mProduct) Next Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Sub LoadProductBOMS(ByRef rProductBOMInfos As colProductBOMInfos, ByVal vWhere As String) Dim mdto As dtoProductBOMInfo Try pDBConn.Connect() mdto = New dtoProductBOMInfo(pDBConn) mdto.LoadProductBOMInfoCollectionByWhere(rProductBOMInfos, vWhere) Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Function GetNextProductCodeNoConnected(ByVal vProductCode As String, ByVal vProductType As Integer) As Integer Dim mReader As IDataReader Dim mSQL As String = "" Dim mRetVal As Integer = -1 Dim mExistingCode As String Dim mLastDotPos As Integer Try Select Case vProductType Case eProductType.ProductInstallation mSQL = "Select Top 1 Code from ProductInstallation where Code Like '" & vProductCode & "%' Order By Code Desc" Case eProductType.StructureAF mSQL = "Select Top 1 Code from ProductStructure where Code Like '" & vProductCode & "%' Order By Code Desc" End Select If mSQL <> "" Then mReader = pDBConn.LoadReader(mSQL) If mReader.Read Then mExistingCode = RTIS.DataLayer.clsDBConnBase.DBReadString(mReader, "Code") mLastDotPos = mExistingCode.LastIndexOf("-") If mLastDotPos <> -1 And mExistingCode.Length >= mLastDotPos + 1 Then mRetVal = Val(mExistingCode.Substring(mLastDotPos + 1)) + 1 Else '// invalid code mRetVal = -1 End If Else mRetVal = 1 End If End If Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If mReader IsNot Nothing Then If mReader.IsClosed = False Then mReader.Close() mReader.Dispose() mReader = Nothing End If End Try Return mRetVal End Function Public Sub LoadProductCostDown(ByRef rProductCostBook As dmProductCostBook, ByVal vProductCostBookID As Integer) Dim mdtoProductCostBook As dtoProductCostBook Dim mdtoProductCostBookEntry As dtoProductCostBookEntry Try pDBConn.Connect() mdtoProductCostBook = New dtoProductCostBook(pDBConn) mdtoProductCostBook.LoadProductCostBook(rProductCostBook, vProductCostBookID) If rProductCostBook IsNot Nothing Then mdtoProductCostBookEntry = New dtoProductCostBookEntry(pDBConn) mdtoProductCostBookEntry.LoadProductCostBookEntryCollection(rProductCostBook.ProductCostBookEntrys, vProductCostBookID) End If Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try End Sub Public Function LoadHouseType(ByRef rHouseType As dmHouseType, ByVal vHouseTypeID As Integer) As Boolean Dim mdto As New dtoHouseType(DBConn) Dim mOK As Boolean Try pDBConn.Connect() mOK = mdto.LoadHouseType(rHouseType, vHouseTypeID) Catch ex As Exception If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyDataLayer) Then Throw Finally If pDBConn.IsConnected Then pDBConn.Disconnect() End Try Return mOK End Function End Class
'----------------------------------------- ' HtmlDump.vb (c) 2002 by Charles Petzold '----------------------------------------- Imports System Imports System.IO Imports System.Net Module HtmlDump Function Main(ByVal astrArgs() As String) As Integer Dim strUri As String ' If there's no argument, display syntax and ask for URI. If astrArgs.Length = 0 Then Console.WriteLine("Syntax: HtmlDump URI") Console.Write("Enter URI: ") strUri = Console.ReadLine() Else strUri = astrArgs(0) End If ' If the user enters a blank string, dive out. If strUri.Length = 0 Then Return 1 End If Dim webreq As WebRequest Dim webres As WebResponse Try webreq = WebRequest.Create(strUri) webres = webreq.GetResponse() Catch exc As Exception Console.WriteLine("HtmlDump: {0}", exc.Message) Return 1 End Try If webres.ContentType.Substring(0, 4) <> "text" Then Console.WriteLine("HtmlDump: URI must be a text type.") Return 1 End If Dim strm As Stream = webres.GetResponseStream() Dim sr As New StreamReader(strm) Dim strLine As String Dim iLine As Integer = 1 strLine = sr.ReadLine() While Not strLine Is Nothing Console.WriteLine("{0:D5}: {1}", iLine, strLine) iLine += 1 strLine = sr.ReadLine() End While strm.Close() Return 0 End Function End Module
Imports AMC.DNN.Modules.CertRecert.Business.BaseControl Imports AMC.DNN.Modules.CertRecert.Business.EnumItems Imports AMC.DNN.Modules.CertRecert.Business.Helpers Imports AMC.DNN.Modules.CertRecert.Controls.Reusable Imports AMC.DNN.Modules.CertRecert.Business.BusinessValidation Imports AMC.DNN.Modules.CertRecert.Business.Controller Imports TIMSS.API.User.UserDefinedInfo Imports TIMSS.API.Core.Validation Namespace Controls.Common ''' <summary> ''' Prepresent GUI for BoardCertification tab ''' </summary> Public Class BoardCertificationUC Inherits SectionBaseUserControl #Region "Private Member" #End Region #Region "Event Handle" ''' <summary> ''' override save method of SectionBaseUserControl control for committing data ''' </summary> ''' <remarks></remarks> Public Overrides Function Save() As IIssuesCollection Try hdIsIncomplete.Value = CommonConstants.TAB_INCOMPLETED Dim customerExternalDocuments = amcCertRecertController.GetCustomerExternalDocuments( DocumentationType.BRDCRT.ToString(), MasterCustomerId, SubCustomerId) If customerExternalDocuments IsNot Nothing Then For Each customerExternalDocument As IUserDefinedCustomerExternalDocumentation In customerExternalDocuments UploadFileIssue.Assert(False, customerExternalDocument) Next End If Dim results = amcCertRecertController.CommitCustomerExternalDocuments(DocumentationType.BRDCRT.ToString(), MasterCustomerId, SubCustomerId) If results Is Nothing OrElse results.Count <= 0 Then MoveFileToApproriateDirectory(DocumentationType.BRDCRT.ToString()) hdIsIncomplete.Value = CommonConstants.TAB_COMPLETED AMCCertRecertController.RefreshCustomerExternalDocuments(DocumentationType.BRDCRT.ToString(), MasterCustomerId, SubCustomerId) End If BindingDataToList() If customerExternalDocuments.Count <= 0 Then hdIsIncomplete.Value = CommonConstants.TAB_INCOMPLETED End If Return results Catch ex As Exception ProcessException(ex) End Try Return Nothing End Function Protected Sub BtnSaveClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click Try Dim customerExternals As New UserDefinedCustomerExternalDocumentations Dim customerExternalDocumentItem As IUserDefinedCustomerExternalDocumentation Dim issueCollection As IIssuesCollection 'Edit If (Me.hdCurrentObjectUniqueId.Value <> String.Empty) Then customerExternalDocumentItem = amcCertRecertController.GetCustomerExternalDocumentationByGUID( Me.hdCurrentObjectUniqueId.Value, DocumentationType.BRDCRT.ToString(), Me.MasterCustomerId, Me.SubCustomerId) If SetPropertiesForObject(customerExternalDocumentItem) Then issueCollection = amcCertRecertController.UpdateCustomerExternalDocument(customerExternalDocumentItem) Else issueCollection = customerExternalDocumentItem.ValidationIssues End If Else 'Insert customerExternalDocumentItem = customerExternals.CreateNew() customerExternalDocumentItem.DocumentationTypeString = DocumentationType.BRDCRT.ToString() customerExternalDocumentItem.IssuingBody.FillList() customerExternalDocumentItem.IsNewObjectFlag = True ''call insert fucntion of amc controller If SetPropertiesForObject(customerExternalDocumentItem) Then issueCollection = amcCertRecertController.InsertCustomerExternalDocument(customerExternalDocumentItem) Else issueCollection = customerExternalDocumentItem.ValidationIssues End If End If If (issueCollection Is Nothing OrElse issueCollection.Count < 1) AndAlso customerExternalDocumentItem IsNot Nothing Then If Me.hfDeleteFile.Value.Equals("YES") Then ''Delete file DeleteAttachDocument(DocumentationType.BRDCRT.ToString(), customerExternalDocumentItem.Guid, customerExternalDocumentItem.DocumentationId.ToString()) End If If fuUploadFileAttachment.FileContent.Length > 0 Then ''upload file Dim fileLocation As String = String.Empty fileLocation = UploadTempFile(Me.fuUploadFileAttachment, customerExternalDocumentItem.DocumentationTypeString, customerExternalDocumentItem.Guid) If fileLocation <> String.Empty Then customerExternalDocumentItem.DocumentLocation = fileLocation customerExternalDocumentItem.DocumentTitle = fuUploadFileAttachment.FileName issueCollection = AMCCertRecertController.UpdateCustomerExternalDocument(customerExternalDocumentItem) End If End If End If If issueCollection IsNot Nothing AndAlso issueCollection.Count > 0 Then ShowError(issueCollection, lblPopupMessage) hdIsValidateFailed.Value = CommonConstants.TAB_INCOMPLETED Else hdIsValidateFailed.Value = CommonConstants.TAB_COMPLETED End If BindingDataToList() hdIsIncomplete.Value = CommonConstants.TAB_INCOMPLETED Catch ex As System.Exception ProcessException(ex) hdIsIncomplete.Value = CommonConstants.TAB_INCOMPLETED End Try End Sub Protected Sub rptSubCertificate_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptSubCertificate.ItemCommand Try If e.CommandName.Equals("Delete") Then hdIsIncomplete.Value = CommonConstants.TAB_INCOMPLETED Dim customerExternalDocumentItem As IUserDefinedCustomerExternalDocumentation customerExternalDocumentItem = amcCertRecertController.GetCustomerExternalDocumentationByGUID(e.CommandArgument.ToString(), DocumentationType.BRDCRT.ToString(), Me.MasterCustomerId, Me.SubCustomerId) amcCertRecertController.DeleteCustomerExternalDocument(customerExternalDocumentItem) End If BindingDataToList() Catch ex As Exception ProcessException(ex) End Try End Sub Protected Sub rptSubCertificate_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptSubCertificate.ItemDataBound Try If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then Dim customerExternalDocument As UserDefinedCustomerExternalDocumentation = CType(e.Item.DataItem, UserDefinedCustomerExternalDocumentation) Dim lblBoard = CType(e.Item.FindControl("lblBoard"), Label) Dim lblBoardCertification = CType(e.Item.FindControl("lblBoardCertification"), Label) If String.IsNullOrEmpty(customerExternalDocument.IssuingBodyText) Then lblBoard.Text = customerExternalDocument.IssuingBody.List( customerExternalDocument.IssuingBodyString).Description Else lblBoard.Text = String.Format("{0} - {1}", customerExternalDocument.IssuingBody.List(customerExternalDocument.IssuingBodyString).Description, customerExternalDocument.IssuingBodyText) lblBoardCertification.Text = customerExternalDocument.IssuingBodyText End If Dim fileName As String = String.Empty Dim linkLocation As String = String.Empty If customerExternalDocument IsNot Nothing Then fileName = GetFileNameOfDocument(customerExternalDocument.DocumentationTypeString, customerExternalDocument.Guid.ToString(), customerExternalDocument.DocumentationId.ToString(), linkLocation) If fileName <> String.Empty Then Dim hlAttachedDocumentName = CType(e.Item.FindControl("hlAttachedDocumentName"), HyperLink) hlAttachedDocumentName.Text = fileName hlAttachedDocumentName.NavigateUrl = linkLocation Dim hdAttachedDocumentName = CType(e.Item.FindControl("hdAttachedDocumentName"), HiddenField) hdAttachedDocumentName.Value = fileName End If End If Dim hdNoneRecertDate = CType(e.Item.FindControl("hdNoneRecertDate"), HiddenField) Dim lblCertificateDate = CType(e.Item.FindControl("lblCertificateDate"), Label) Dim lblRecertificateDate = CType(e.Item.FindControl("lblRecertificateDate"), Label) If customerExternalDocument.CycleBeginDate <> DateTime.MinValue Then lblCertificateDate.Text = customerExternalDocument.CycleBeginDate.ToString(CommonConstants.DATE_FORMAT) End If If customerExternalDocument.CycleEndDate.Date <> DateTime.MaxValue.Date Then hdNoneRecertDate.Value = Boolean.FalseString If customerExternalDocument.CycleEndDate <> DateTime.MinValue Then lblRecertificateDate.Text = customerExternalDocument.CycleEndDate.ToString(CommonConstants.DATE_FORMAT) End If Else hdNoneRecertDate.Value = Boolean.TrueString lblRecertificateDate.Text = Localization.GetString("NoneRecertDateValue.Text", LocalResourceFile) End If End If Catch ex As Exception ProcessException(ex) End Try End Sub #End Region #Region "Private Method" ''' <summary> ''' Validates usercontrol has completed data fill ''' </summary> Public Overrides Sub ValidateFormFillCompleted() AMCCertRecertController.RefreshCustomerExternalDocuments(DocumentationType.BRDCRT.ToString(), MasterCustomerId, SubCustomerId) BindingDataToList() If Not Page.IsPostBack Then CommonHelper.BindIssuingBodyType(Me.ddlBoardCertificate, DocumentationType.BRDCRT.ToString()) End If End Sub Private Sub BindingDataToList() Dim customerExternals As IUserDefinedCustomerExternalDocumentations customerExternals = amcCertRecertController.GetCustomerExternalDocuments(DocumentationType.BRDCRT.ToString(), Me.MasterCustomerId, Me.SubCustomerId) If customerExternals.Count > 0 AndAlso Not Page.IsPostBack Then hdIsIncomplete.Value = CommonConstants.TAB_COMPLETED End If rptSubCertificate.DataSource = customerExternals rptSubCertificate.DataBind() End Sub Private Function SetPropertiesForObject(ByRef customerExternalDocumentItem As IUserDefinedCustomerExternalDocumentation) As Boolean If customerExternalDocumentItem Is Nothing Then Return False End If Dim isIssue As Boolean = True Try UploadFileIssue.Assert(False, customerExternalDocumentItem) With customerExternalDocumentItem .RelatedMasterCustomerId = Me.MasterCustomerId .RelatedSubcustomerId = Me.SubCustomerId .IssuingBodyString = ddlBoardCertificate.SelectedValue .IssuedNumber = Me.txtCertificateNumber.Text If .IssuingBodyString.Equals(CommonConstants.OtherBoardValue.ToString()) OrElse .IssuingBodyString.Equals(CommonConstants.OtherSubBoardValue.ToString()) Then .IssuingBodyText = Me.txtBoardCertification.Text Else .IssuingBodyText = String.Empty End If If CType(Me.txtCertificateDate, AMCDatetime).Text <> String.Empty Then .CycleBeginDate = DateTime.Parse(CType(Me.txtCertificateDate, AMCDatetime).Text) Else .CycleBeginDate = DateTime.MinValue End If If Not chkNoneRecertDate.Checked Then If CType(Me.txtRecertificateDate, AMCDatetime).Text <> String.Empty Then .CycleEndDate = DateTime.Parse(CType(Me.txtRecertificateDate, AMCDatetime).Text) Else .CycleEndDate = DateTime.MinValue End If Else .CycleEndDate = DateTime.MaxValue End If End With If fuUploadFileAttachment.FileContent.Length > 1 Then UploadFileIssue.Assert(UploadFileIssue.IsNotPdfFile(fuUploadFileAttachment.FileContent), customerExternalDocumentItem) End If For Each issue As IIssue In customerExternalDocumentItem.ValidationIssues If TypeOf issue Is UploadFileIssue Then isIssue = False Exit For End If Next Catch ex As Exception Me.ProcessException(ex) End Try Return isIssue End Function #End Region Private Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub End Class End Namespace
Imports Model Imports Data Public Class LogicDetailKategori Public datadkg As New DataDetailKategori Public Function insert(ByVal modeldkg As ModelDetailKategori) As Boolean Return datadkg.insert(modeldkg) End Function Public Function update(ByVal modeldkg As ModelDetailKategori) As Boolean Return datadkg.update(modeldkg) End Function Public Function delete(ByVal modeldkg As ModelDetailKategori) As Boolean Return datadkg.delete(modeldkg) End Function Public Function undelete(ByVal modeldkg As ModelDetailKategori) As Boolean Return datadkg.undelete(modeldkg) End Function Public Function selectall() As List(Of ModelDetailKategori) Return datadkg.selectall End Function Public Function selectbykode(ByVal kd_buku As String, ByVal kd_volume As String) As ModelDetailKategori Return datadkg.selectbykode(kd_buku, kd_volume) End Function Public Function selectbyKategori(ByVal kd_kategori As String) As List(Of ModelDetailKategori) Return datadkg.selectbykategori(kd_kategori) End Function Public Function selectbyBuku(ByVal kd_buku As String) As List(Of ModelDetailKategori) Return datadkg.selectbyBuku(kd_buku) End Function End Class
Public Class frm_traspaso_articulo_prov Private articulo As New func_articulos Private dt As New DataTable Private util As New utilidades Private TITULO_MSJ As String = "<Transpaso de Articulos>" Private ACCION As String = "" Private ID_PROVEEDOR As Integer = 0 Private ID_TRASPASO As Integer = 0 Private Sub frm_traspaso_articulo_prov_Load(sender As Object, e As EventArgs) Handles MyBase.Load lbl_total_registros.Text = "" End Sub Private Sub limpiar() txt_proveedor.Text = "" txt_traspaso.Text = "" txt_proveedor.Focus() dt = Nothing lbl_total_registros.Text = "" End Sub Private Sub traspaso() If dt.Rows.Count <= 0 Then util.mensajes("No se registran Articulos para traspaso", TITULO_MSJ, "WAR") txt_proveedor.Focus() Return End If If articulo.traspaso(ID_PROVEEDOR, ID_TRASPASO) = False Then util.mensajes("Articulo no traspasado", TITULO_MSJ, "WAR") Return End If util.mensajes("Traspaso realizado", TITULO_MSJ, "INF") limpiar() End Sub Public Sub obtener_proveedor(id As Integer) Dim dt As New DataTable dt = articulo.listar("SELECT id_proveedor, nombre FROM proveedores WHERE id_proveedor=" + id.ToString() + "") If ACCION = "P" Then ID_PROVEEDOR = CInt(dt.Rows(0).Item(0)) txt_proveedor.Text = CStr(dt.Rows(0).Item(1)) End If If ACCION = "T" Then ID_TRASPASO = CInt(dt.Rows(0).Item(0)) txt_traspaso.Text = CStr(dt.Rows(0).Item(1)) End If End Sub Private Sub obtener_articulos() If txt_proveedor.Text = "" Then util.mensajes("Debe seleccionar Proveedor", TITULO_MSJ, "WAR") Return End If dt = articulo.listar("SELECT nombre, id_proveedor FROM articulos WHERE id_proveedor=" + ID_PROVEEDOR.ToString) lbl_total_registros.Text = "Registros recuperados: " & CStr(dt.Rows.Count) If dt.Rows.Count <= 0 Then txt_proveedor.Focus() Else btn_confirmar.Focus() End If End Sub Private Sub txt_proveedor_KeyDown(sender As Object, e As KeyEventArgs) Handles txt_proveedor.KeyDown If e.KeyCode = Keys.Space Or e.KeyCode = Keys.F9 Then Dim frm As New frm_vista_proveedores frm.FRM_ACTIVO = "frm_traspaso_articulo_prov" frm.Show() ACCION = "P" End If If e.KeyCode = Keys.Enter Then If txt_proveedor.Text = "" Then Else txt_traspaso.Focus() End If End If End Sub Private Sub txt_traspaso_KeyDown(sender As Object, e As KeyEventArgs) Handles txt_traspaso.KeyDown If e.KeyCode = Keys.Space Or e.KeyCode = Keys.F9 Then Dim frm As New frm_vista_proveedores frm.FRM_ACTIVO = "frm_traspaso_articulo_prov" frm.Show() ACCION = "T" End If If e.KeyCode = Keys.Enter Then If txt_traspaso.Text = "" Then Else btn_consultar.Focus() End If End If End Sub Private Sub btn_proveedor_Click(sender As Object, e As EventArgs) Handles btn_proveedor.Click Dim frm As New frm_vista_proveedores frm.FRM_ACTIVO = "frm_traspaso_articulo_prov" frm.Show() ACCION = "P" End Sub Private Sub btn_traspaso_Click(sender As Object, e As EventArgs) Handles btn_traspaso.Click Dim frm As New frm_vista_proveedores frm.FRM_ACTIVO = "frm_traspaso_articulo_prov" frm.Show() ACCION = "P" End Sub Private Sub btn_confirmar_Click(sender As Object, e As EventArgs) Handles btn_confirmar.Click traspaso() End Sub Private Sub btn_consultar_Click(sender As Object, e As EventArgs) Handles btn_consultar.Click obtener_articulos() End Sub End Class
Public Class Pump Public Property Name As String Public Property State As Integer Public Property Voltage As Double Public Property StateStr As String End Class
Imports Microsoft.VisualBasic Imports System Imports System.IO Imports System.Media Imports System.Windows.Forms Imports Neurotec.IO Partial Public Class MediaPlayerControl Inherits UserControl #Region "Public constructor" Public Sub New() InitializeComponent() End Sub #End Region #Region "Private fields" Private _soundBuffer As NBuffer Private _soundPlayer As New SoundPlayer() #End Region #Region "Public properties" Public Property SoundBuffer() As NBuffer Get Return _soundBuffer End Get Set(ByVal value As NBuffer) Me.Stop() _soundBuffer = value btnPlay.Enabled = value IsNot Nothing AndAlso value IsNot NBuffer.Empty btnStop.Enabled = btnPlay.Enabled End Set End Property #End Region #Region "Private methods" Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) _soundPlayer.Stop() If disposing AndAlso (components IsNot Nothing) Then components.Dispose() End If MyBase.Dispose(disposing) End Sub Public Sub [Stop]() _soundPlayer.Stop() End Sub Public Sub Start() Me.Stop() _soundPlayer.Stream = New MemoryStream(_soundBuffer.ToArray()) _soundPlayer.Play() End Sub Private Sub BtnPlayClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnPlay.Click Start() End Sub Private Sub BtnStopClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnStop.Click Me.Stop() End Sub Private Sub MediaPlayerControlVisibleChanged(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.VisibleChanged If (Not Visible) Then Me.Stop() End If End Sub #End Region End Class
Namespace Entidad Public Class Inscripcion Implements IInscripcion ''Método que se permite el pago en línea con una tarjeta de crédito ó débito VISA, MasterCard ó Amex. Public Function RealizarPago(surfista As Dominios.Usuario, Categoria As Dominios.CategoriasTorneo) As Moneda Implements IInscripcion.RealizarPago Dim servicio As New Servicios.Inscripcion() Dim tarjeta As New Servicios.Tarjeta() If (tarjeta.ValidarTipoTarjeta(surfista.Tarjeta)) Then Dim categoriaInscripcion = servicio.BuscarCategoria(Categoria) If Not categoriaInscripcion Is Nothing Then Dim cobro As New Entidad.Moneda(categoriaInscripcion.PrecioInscripcion, Transaccion.Cobro) Return cobro End If End If Return Nothing End Function Public Function SolicitarInscripcion(surfista As Dominios.Usuario, Categoria As Dominios.CategoriasTorneo) As Moneda Implements IInscripcion.SolicitarInscripcion Dim servicio As New Servicios.Inscripcion() If servicio.ValidarCampoDisponible(Categoria) Then Dim categoriaInscripcion = servicio.BuscarCategoria(Categoria) If Not categoriaInscripcion Is Nothing Then Dim cupos = categoriaInscripcion.CuposDisponibles - 1 Dim resultado = New Dominios.CategoriasTorneo With {.Categoria = categoriaInscripcion.Categoria, .CuposDisponibles = cupos, .PrecioInscripcion = categoriaInscripcion.PrecioInscripcion} Dim servicioCategorias As New Servicios.CategoriasTorneo servicioCategorias.GuardarCategoria(resultado) Dim cobro As New Entidad.Moneda(categoriaInscripcion.PrecioInscripcion, Transaccion.Cobro) Return cobro End If End If Return Nothing End Function End Class End Namespace
Public Class mwGroupBox Inherits GroupBox Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. SetStyle(ControlStyles.SupportsTransparentBackColor, True) Me.DoubleBuffered = True 'BackColor = System.Drawing.Color.FromArgb(130, 0, 0, 0) 'Color.Transparent End Sub Protected Overrides ReadOnly Property CreateParams() As CreateParams Get Dim cp As CreateParams = MyBase.CreateParams cp.ExStyle = cp.ExStyle Or &H20 Return cp End Get End Property End Class
Public Class clsSetting 'Public Shared AppSettingsFile As String = Nothing Public Const Delimiter As String = ">><<" Public Structure AppSettingName Public Const ProjectName As String = "ProjectName" Public Const WebsitePath As String = "WebsitePath" Public Const LocationDatabase As String = "LocationDatabase" Public Const BlankImage As String = "BlankImage" ' Use target blank image link in results. Public Const BlankImagePathRemember As String = "BlankImagePathRemember" ' Remember last custom target blank image folder for dialog. Public Const NameBlank As String = "NameBlank" ' Target blank image name. Public Const LocationBlank As String = "LocationBlank" ' Output folder for target blank image. Public Const NameSearch As String = "NameSearch" ' Search script name. Public Const LocationSearch As String = "LocationSearch" ' Search script output location. Public Const ExclusionFolder As String = "FolderExclusions" Public Const ExclusionFile As String = "FileExclusions" End Structure Public Shared Sub LoadSettings() modVar.AppDataFolder = clsRegistry.GetSetting("", clsRegistry.RegKey.SettingsFolder) If modVar.AppDataFolder Is Nothing Then modVar.AppDataFolder = modVar.GetDefaultDataFolder If System.IO.Directory.Exists(modVar.AppDataFolder) = False Then If System.IO.Directory.Exists(System.IO.Path.GetPathRoot(modVar.AppDataFolder)) = False Then modVar.AppDataFolder = modVar.GetDefaultDataFolder Call clsRegistry.SetSetting("", clsRegistry.RegKey.SettingsFolder, modVar.AppDataFolder) Else System.IO.Directory.CreateDirectory(modVar.AppDataFolder) End If End If LoadProject() Call clsRegistry.GetAllKeyValues(clsRegistry.RegKey.Root & "\" & clsRegistry.RegKey.RecentProjects, modVar.RecentProjects) End Sub Public Shared Sub LoadProject() modVar.OpenProjectFile = clsRegistry.GetSetting("", clsRegistry.RegKey.OpenProject) If modVar.OpenProjectFile Is Nothing Or ValidPath(modVar.OpenProjectFile) = False Then modVar.OpenProjectFile = Nothing Call clsRegistry.SetSetting("", clsRegistry.RegKey.OpenProject, "") End If modVar.AppSettings = Nothing If modVar.OpenProjectFile IsNot Nothing Then EnsureDataFileExists() modVar.AppSettings = clsFix.RemoveDeprecatedSetting(System.IO.File.ReadAllLines(modVar.OpenProjectFile)) SettingsArraysIntegrityCheck() If clsFix.FixFullPathRemoval() = True Then SaveSettings() End If End Sub Public Shared Sub SaveSettings() EnsureDataFileExists() Dim WriteFileContent As String = "" Dim TheNewLine As String = "" For Count = 0 To modVar.AppSettings.Length - 1 If Count > 0 Then TheNewLine = vbNewLine WriteFileContent += TheNewLine & modVar.AppSettings(Count) Next Count System.IO.File.WriteAllText(modVar.OpenProjectFile, WriteFileContent) End Sub Public Shared Function GetSetting(ByVal SettingIn As String) As String Dim RetVal As String = Nothing Dim ArrayLength As Integer If modVar.AppSettings Is Nothing Then ArrayLength = 0 Else ArrayLength = modVar.AppSettings.Count End If If ArrayLength <> 0 Then Dim TheSetting() As String For Count = 0 To modVar.AppSettings.Count - 1 TheSetting = modVar.AppSettings(Count).Split(New String() {Delimiter}, StringSplitOptions.RemoveEmptyEntries) If TheSetting(0).ToLower = SettingIn.ToLower Then If TheSetting.Length <> 1 Then RetVal = TheSetting(1) End If Exit For End If Next Count End If Return RetVal End Function Public Shared Sub SetSetting(ByVal SettingNameIn As String, ByVal SettingValueIn As String, ByVal DontSaveSettingsIn As Boolean) Dim Found As Integer = -1 Dim TheSetting() As String = Nothing For Count = 0 To modVar.AppSettings.Length - 1 TheSetting = modVar.AppSettings(Count).Split(New String() {Delimiter}, StringSplitOptions.RemoveEmptyEntries) If TheSetting(0) = SettingNameIn Then Found = Count : Exit For Next Count Dim TheNewSetting As String = SettingNameIn & Delimiter & SettingValueIn If Found = -1 Then Dim NewIndex As Integer = modVar.AppSettings.Length ReDim Preserve modVar.AppSettings(NewIndex) modVar.AppSettings(NewIndex) = TheNewSetting Else modVar.AppSettings(Found) = TheNewSetting End If If DontSaveSettingsIn <> True Then SaveSettings() End Sub Private Shared Sub EnsureDataFileExists() If System.IO.File.Exists(modVar.OpenProjectFile) = False Then System.IO.File.WriteAllText(modVar.OpenProjectFile, "") End Sub Private Shared Function ValidPath(ByVal PathIn As String) As Boolean Dim RetVal As Boolean = True Try Dim TestPath As String = System.IO.Path.GetFullPath(PathIn) Catch ex As Exception RetVal = False End Try Return RetVal End Function Public Shared Sub SaveProjectAs(ByVal FilePath As String) modVar.OpenProjectFile = FilePath Call clsRegistry.SetSetting("", clsRegistry.RegKey.OpenProject, modVar.OpenProjectFile) SaveSettings() End Sub Public Shared Sub RemoveArrayAndIndex(ByVal PrefixIn As String) Dim NewArray As New ArrayList For Count = 0 To modVar.AppSettings.Length - 1 If InStr(1, modVar.AppSettings(Count), PrefixIn) <> 1 Then NewArray.Add(modVar.AppSettings(Count)) Next Dim Output(NewArray.Count - 1) As String For Count = 0 To NewArray.Count - 1 Output(Count) = NewArray(Count) Next modVar.AppSettings = Output SaveSettings() End Sub Public Shared Sub SettingsArraysIntegrityCheck() ' This function fixes arrays in two ways ' 1 = Check that the index is the right number by counting entries ' 2 = Orders the array entries in ascending order. Dim NoArrays As Integer = 1 Dim TheArrays(NoArrays) As String Dim IndexFound(NoArrays) As Boolean Dim RemoveArray(NoArrays) As Boolean Dim IndexValue(NoArrays) As String Dim NoItems(NoArrays) As Integer Dim ValidOrder(NoArrays) As Boolean Dim IndexLeft As String = "" Dim LastIndexNumber As String Dim CurrentIndexNumber As String Dim Spot1, Spot2 As Integer Dim Recount(NoArrays) As String Dim Rebuild As String Dim DoSave As Boolean Dim Path As String Dim RebuildCount As Integer Dim FirstFound As Boolean TheArrays(0) = clsSetting.AppSettingName.ExclusionFile TheArrays(1) = clsSetting.AppSettingName.ExclusionFolder For Count1 = 0 To TheArrays.Length - 1 IndexFound(Count1) = False NoItems(Count1) = 0 LastIndexNumber = 0 ValidOrder(Count1) = True For Count2 = 0 To modVar.AppSettings.Length - 1 If InStr(1, modVar.AppSettings(Count2), TheArrays(Count1)) = 1 Then IndexLeft = TheArrays(Count1) & clsSetting.Delimiter CurrentIndexNumber = "0" If InStr(1, modVar.AppSettings(Count2), IndexLeft) = 1 Then IndexFound(Count1) = True IndexValue(Count1) = modVar.AppSettings(Count2).Substring(IndexLeft.Length, modVar.AppSettings(Count2).Length - IndexLeft.Length) FirstFound = False ElseIf InStr(1, modVar.AppSettings(Count2), TheArrays(Count1)) = 1 Then Spot1 = TheArrays(Count1).Length Spot2 = InStr(1, modVar.AppSettings(Count2), clsSetting.Delimiter) If Spot2 = -1 Then ValidOrder(Count1) = False Else CurrentIndexNumber = modVar.AppSettings(Count2).Substring(Spot1, Spot2 - Spot1 - 1) If LastIndexNumber <> 0 And IsNumeric(CurrentIndexNumber) = True Then If CInt(CurrentIndexNumber) <> CInt(LastIndexNumber) + 1 Then ValidOrder(Count1) = False End If If IsNumeric(CurrentIndexNumber) = True Then CurrentIndexNumber = "0" LastIndexNumber = CurrentIndexNumber End If If FirstFound = False And CInt(CurrentIndexNumber) <> 1 Then ValidOrder(Count1) = False : FirstFound = True NoItems(Count1) += 1 End If End If Next Count2 Next Count1 For Count = 0 To NoArrays If IndexFound(Count) = True Then If IndexValue(Count) <> NoItems(Count) Then clsSetting.SetSetting(TheArrays(Count), NoItems(Count), False) End If End If Next Count For Count1 = 0 To NoArrays If ValidOrder(Count1) = False Then RebuildCount = 0 For Count2 = 0 To modVar.AppSettings.Length - 1 If InStr(1, modVar.AppSettings(Count2), TheArrays(Count1)) = 1 Then If InStr(1, modVar.AppSettings(Count2), TheArrays(Count1) & clsSetting.Delimiter) <> 1 Then Spot1 = InStr(1, modVar.AppSettings(Count2), clsSetting.Delimiter) If Spot1 = -1 Then Path = "" Else Path = modVar.AppSettings(Count2).Substring(Spot1 + 3, modVar.AppSettings(Count2).Length - Spot1 - 3) End If RebuildCount += 1 Rebuild = TheArrays(Count1) & RebuildCount & clsSetting.Delimiter & Path modVar.AppSettings(Count2) = Rebuild DoSave = True End If End If Next Count2 End If Next Count1 If DoSave = True Then SaveSettings() End Sub End Class
Public Interface IFormatNormal ''' <summary> ''' Return True if break page ''' </summary> ''' <param name="pLabel"></param> ''' <param name="g"></param> ''' <param name="maxWidth"></param> ''' <param name="maxHeight"></param> ''' <param name="x"></param> ''' <param name="y"></param> ''' <returns></returns> Function DrawLabel(ByRef pLabel As PrintLabel, ByRef g As Graphics, ByRef maxWidth As Integer, ByRef maxHeight As Integer, ByRef x As Integer, ByRef y As Integer) As Boolean End Interface
'Based on FBRToss code 'Copyright R. Demidov & M. Irgiznov 2006-2007 Option Strict Off Option Explicit On Imports System.Runtime.InteropServices Imports System.IO Imports System.Text Public Module PKT #Region "Structures" <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure Addr Dim Zone As Short Dim Net As Short Dim Node As Short Dim Point As Short Public Overrides Function ToString() As String Return Me.Zone & ":" & Me.Net & "/" & Me.Node & "." & Me.Point End Function End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure Packet <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=23)> Public From As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=23)> Public [To] As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)> Public [Date] As String Dim PType As Short <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=8)> Public Password As String Dim Size As Integer Dim Records As Short Public Function ToByteArray() As Byte() Dim buff(Marshal.SizeOf(GetType(Packet))) As Byte Dim Handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Marshal.StructureToPtr(Me, Handle.AddrOfPinnedObject(), False) Handle.Free() Return buff End Function Public Function FromBinaryReaderBlock(ByVal br As BinaryReader) As Packet Dim buff() As Byte = br.ReadBytes(Marshal.SizeOf(GetType(Packet))) Dim handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Dim st As Packet = CType(Marshal.PtrToStructure(handle.AddrOfPinnedObject(), GetType(Packet)), Packet) handle.Free() Return st End Function End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure MsgInfo Dim FromAdr As Addr <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=36)> Public FromName As String Dim ToAdr As Addr <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=36)> Public ToName As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=72)> Public Subject As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)> Public [Date] As String '?? ??? ?? ??:??:?? Public Function ToByteArray() As Byte() Dim buff(Marshal.SizeOf(GetType(MsgInfo))) As Byte Dim Handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Marshal.StructureToPtr(Me, Handle.AddrOfPinnedObject(), False) Handle.Free() Return buff End Function Public Function FromBinaryReaderBlock(ByVal br As BinaryReader) As MsgInfo Dim buff() As Byte = br.ReadBytes(Marshal.SizeOf(GetType(MsgInfo))) Dim handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Dim st As MsgInfo = CType(Marshal.PtrToStructure(handle.AddrOfPinnedObject(), GetType(MsgInfo)), MsgInfo) handle.Free() Return st End Function End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure PktHeader Dim oNode As Short Dim dNode As Short Dim Year As Short Dim Month As Short Dim Day As Short Dim Hour As Short Dim Minute As Short Dim Second As Short Dim Baud As Short Dim PacketType As Short Dim oNet As Short Dim dNet As Short <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public prodCode As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public serNo As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=8)> Public Password As String Dim QoZone As Short Dim QdZone As Short Dim AuxNet As Short Dim cw1 As Short <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public pCode As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public PRMinor As String Dim CW2 As Short Dim oZone As Short Dim dZone As Short Dim oPoint As Short Dim dPoint As Short Dim LongData As Integer Public Function ToByteArray() As Byte() Dim buff(Marshal.SizeOf(GetType(PktHeader))) As Byte Dim Handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Marshal.StructureToPtr(Me, Handle.AddrOfPinnedObject(), False) Handle.Free() Return buff End Function Public Function FromBinaryReaderBlock(ByVal br As BinaryReader) As PktHeader Dim buff() As Byte = br.ReadBytes(Marshal.SizeOf(GetType(PktHeader))) Dim handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Dim st As PktHeader = CType(Marshal.PtrToStructure(handle.AddrOfPinnedObject(), GetType(PktHeader)), PktHeader) handle.Free() Return st End Function Public Function GetFromAddr() As String Return Me.oZone & ":" & Me.oNet & "/" & Me.oNode & "." & Me.oPoint End Function Public Function GetToAddr() As String Return Me.dZone & ":" & Me.dNet & "/" & Me.dNode & "." & Me.dPoint End Function End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure PKThdr20Type Dim OrigNode As Short '0 Dim DestNode As Short '2 Dim Year As Short '4 Dim Month As Short '6 Dim Day As Short '8 Dim Hour As Short '10 Dim Minute As Short '12 Dim Second As Short '14 Dim Baud As Short '16 Dim NoName As Short '18 Dim OrigNet As Short '20 - Set to -1 if from point Dim DestNet As Short '22 Dim ProductCode As Short '24 - ProductCode(low order) | Revision (major) | <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=8)> Public Password As String '26 - password Dim OrigZone As Short '34 Dim DestZone As Short '36 Dim AuxNet As Short '38 Dim CWvalidationCopy As Short '40 Dim ProductCode1 As Short '42 - ProductCode (high order) | Revision (minor) | Dim CapabilWord As Short '44 Dim OrigZone1 As Short '46 Dim DestZone1 As Short '48 Dim OrigPoint As Short '50 Dim DestPoint As Short '52 Dim ProductSpecificData As Integer '54 4 Bytes Public Function ToByteArray() As Byte() Dim buff(Marshal.SizeOf(GetType(PKThdr20Type))) As Byte Dim Handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Marshal.StructureToPtr(Me, Handle.AddrOfPinnedObject(), False) Handle.Free() Return buff End Function Public Function FromBinaryReaderBlock(ByVal br As BinaryReader) As PKThdr20Type Dim buff() As Byte = br.ReadBytes(Marshal.SizeOf(GetType(PKThdr20Type))) Dim handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Dim st As PKThdr20Type = CType(Marshal.PtrToStructure(handle.AddrOfPinnedObject(), GetType(PKThdr20Type)), PKThdr20Type) handle.Free() Return st End Function End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure PktMsgHeader Dim PType As Short Dim oNode As Short Dim dNode As Short Dim oNet As Short Dim dNet As Short Dim Attr As Short Dim cost As Short <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)> Public datetime As String Public Function ToByteArray() As Byte() Dim buff(Marshal.SizeOf(GetType(PktMsgHeader))) As Byte Dim Handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Marshal.StructureToPtr(Me, Handle.AddrOfPinnedObject(), False) Handle.Free() Return buff End Function Public Function FromBinaryReaderBlock(ByVal br As BinaryReader) As PktMsgHeader Dim buff() As Byte = br.ReadBytes(Marshal.SizeOf(GetType(PktMsgHeader))) Dim handle As GCHandle = GCHandle.Alloc(buff, GCHandleType.Pinned) Dim st As PktMsgHeader = CType(Marshal.PtrToStructure(handle.AddrOfPinnedObject(), GetType(PktMsgHeader)), PktMsgHeader) handle.Free() Return st End Function End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _ Public Structure MessStruct Dim Pkt As PktHeader Dim Hdr As MsgInfo Dim Msg() As String End Structure #End Region Public Messages() As MessStruct Public Months() As String = {" ", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} ''' <summary> ''' 'Процедура удаляет заданную мессагу из заданного файла. ''' </summary> ''' <param name="Wich"></param> ''' <param name="FileName"></param> ''' <remarks>'Если она последняя, просто получается пустой пакет!!!</remarks> Public Sub DelPKT(ByRef Wich As Short, ByRef FileName As String) Dim Head As New PktHeader Dim tmp As Short Dim Tmp2 As String, Tmp3() As Byte Dim MsgHead As New PktMsgHeader Dim m, i As Integer Dim Offset1, Offset2, LastSeek As Integer Dim TmpFile As String = "" Dim fs1, fs2 As FileStream, br As BinaryReader, bw As BinaryWriter Tmp2 = Space$(1) fs1 = New FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite) br = New BinaryReader(fs1) 'FileOpen(fNum, FileName, OpenMode.Binary) 'FileGet(fNum, Head) Head = Head.FromBinaryReaderBlock(br) 'Проверка на тип пакета If Head.PacketType <> 2 Or Head.cw1 <> 256 Or Head.CW2 <> 1 Then fs1.Close() Exit Sub End If 'FileGet(fNum, tmp) tmp = br.ReadInt16() If tmp = 0 Then fs1.Close() Exit Sub End If 'Seek(fNum, Seek(1) - 2) fs1.Seek(-2, SeekOrigin.Current) For i = 1 To Wich If i = Wich Then Offset1 = fs1.Position End If 'FileGet(fNum, MsgHead) MsgHead = MsgHead.FromBinaryReaderBlock(br) If MsgHead.PType <> 2 Then fs1.Close() Exit Sub End If 'Прокручиваем имена, сабж и текст сообщения... For j As Integer = 1 To 4 ReDim Tmp3(1024) Do LastSeek = fs1.Position 'FileGet(fNum, Tmp3) Tmp3 = br.ReadBytes(1024) m = InStr(Encoding.GetEncoding(866).GetString(Tmp3), Chr(0)) Loop Until m <> 0 'Seek(fNum, LastSeek + m) fs1.Seek(-1024 + m, SeekOrigin.Current) Next Next 'Теперь указатель указывает на начало следующей мессаги. 'Типа... Круто! ;-) Offset2 = fs1.Position 'Ну а теперь, перекидываем все байтики 'Поздняя приписка: мляяяяяяяяя.... Бейсик - лажа! Нельзя даже файл 'закрыть на любой позиции... Короче: перекидываем всю инфу в новый файл, 'старый удаляем и пишем поверх него. Иначе пока нельзя. :-((( For i = FileName.Length To 1 Step -1 If Mid(FileName, i, 1) = "." Then TmpFile = Left(FileName, i) & "k-q" : Exit For Next 'FileOpen(fNum2, TmpFile, OpenMode.Binary) fs2 = New FileStream(TmpFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite) bw = New BinaryWriter(fs2) 'Тягаем куски блоками по 16 кб. ReDim Tmp3(16384) fs1.Seek(0, SeekOrigin.Begin) 'Seek(fNum, 1) For i = 1 To ((Offset1 - 1) \ 16384) Tmp3 = br.ReadBytes(16384) bw.Write(Tmp3) Next ReDim Tmp3((Offset1 - 1) Mod 16384) Tmp3 = br.ReadBytes(Tmp3.Length) 'FileGet(fNum, Tmp3) bw.Write(Tmp3) 'Теперь тянем все тоже самое до конца файла, но со следующего смещения... ReDim Tmp3(16384) fs1.Seek(Offset2, SeekOrigin.Begin) 'Seek(fNum, Offset2) For i = 1 To ((fs1.Length - Offset2 + 1) \ 16384) Tmp3 = br.ReadBytes(16384) bw.Write(Tmp3) Next 'Перекидываем остатки ReDim Tmp3((fs1.Length - Offset2 + 1) Mod 16384) Tmp3 = br.ReadBytes(Tmp3.Length) 'FileGet(fNum, Tmp3) bw.Write(Tmp3) bw.Flush() bw.Close() fs2.Close() br.Close() fs1.Close() 'Теперь просто удаляем первый файл и переименовываем второй... My.Computer.FileSystem.DeleteFile(FileName) My.Computer.FileSystem.MoveFile(TmpFile, FileName) End Sub ''' <summary> ''' 'Вытаскивает и текстовой строки адрес и раскидывает в переменную ''' </summary> Public Sub GetAddress(ByRef AdrString As String, ByRef Adres As Addr) AdrString = LTrim(RTrim(AdrString)) If AdrString.Length = 0 Then Exit Sub If InStr(AdrString, ":") = 0 Or InStr(AdrString, "/") = 0 Or InStr(AdrString, "/") < InStr(AdrString, ":") Or ((InStr(AdrString, ".") < InStr(AdrString, "/")) And InStr(AdrString, ".")) Then Exit Sub Adres.Zone = CShort(Val(Left(AdrString, InStr(AdrString, ":") - 1))) Adres.Net = CShort(Val(Mid(AdrString, InStr(AdrString, ":") + 1, InStr(AdrString, "/") - InStr(AdrString, ":") - 1))) If InStr(AdrString, ".") <> 0 Then Adres.Node = CShort(Val(Mid(AdrString, InStr(AdrString, "/") + 1, InStr(AdrString, ".") - InStr(AdrString, "/") - 1))) Adres.Point = CShort(Val(Right(AdrString, Len(AdrString) - InStr(AdrString, ".")))) Else Adres.Node = CShort(Val(Right(AdrString, Len(AdrString) - InStr(AdrString, "/")))) Adres.Point = 0 End If End Sub ''' <summary> ''' Выводит инфу по пакету. ''' </summary> ''' <param name="pkt"></param> ''' <param name="FileName"></param> ''' <remarks>Поддерживает только пакеты типа 2+</remarks> Public Sub PktInfo(ByRef pkt As Packet, ByRef FileName As String) Dim m As Integer Dim Head As New PktHeader Dim tmp, i As Short Dim Tmp2, Tmp3 As String Dim MsgHead As New PktMsgHeader Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) Dim br As New BinaryReader(fs) Tmp2 = Space$(1) pkt.Size = fs.Length Head = Head.FromBinaryReaderBlock(br) 'Проверка на тип пакета If Head.PacketType <> 2 Or Head.cw1 <> 256 Or Head.CW2 <> 1 Then fs.Close() Exit Sub End If If Head.oPoint <> 0 And Head.oNet = -1 Then Head.oNet = Head.AuxNet End If 'Собирание инфы Tmp3 = LTrim(Str(Head.oZone)) & ":" & LTrim(Str(Head.oNet)) & "/" & LTrim(Str(Head.oNode)) If Head.oPoint <> 0 Then Tmp3 = Tmp3 & "." & LTrim(Str(Head.oPoint)) pkt.From = Tmp3 Tmp3 = LTrim(Str(Head.dZone)) & ":" & LTrim(Str(Head.dNet)) & "/" & LTrim(Str(Head.dNode)) If Head.dPoint <> 0 Then Tmp3 = Tmp3 & "." & LTrim(Str(Head.dPoint)) With pkt .To = Tmp3 .Date = LTrim(Str(Head.Day)) & " " & _ Months(Head.Month) & " " & _ LTrim(Str(Head.Year)) & ", " & _ LTrim(Str(Head.Hour)) & ":" & _ LTrim(Str(Head.Minute)) .PType = Head.PacketType .Password = Head.Password End With tmp = br.ReadInt16 If tmp = 0 Then pkt.Records = 0 br.Close() fs.Close() Exit Sub End If 'Seek(ff, Seek(ff) - 2) fs.Seek(-2, SeekOrigin.Current) Do MsgHead = MsgHead.FromBinaryReaderBlock(br) If MsgHead.PType <> 2 Then fs.Close() Exit Sub End If pkt.Records += 1 'Прокручиваем имена, сабж и текст сообщения... For i = 1 To 4 Tmp3 = Space$(1024) Do 'FileGet(ff, Tmp3) Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(Tmp3, Chr(0)) Loop Until m <> 0 fs.Seek(-1024 + m, SeekOrigin.Current) Next Loop br.Close() fs.Close() End Sub ''' <summary> ''' Выводит список заголовков мессаг в пакете. ''' </summary> ''' <param name="a"></param> ''' <param name="FileName"></param> ''' <remarks>Поддерживает только пакеты типа 2+</remarks> Public Sub PktMsgList(ByRef a() As MsgInfo, ByRef FileName As String) Dim Head As New PktHeader Dim tmp As Short, LastSeek As Integer Dim Tmp2 As Char, Tmp3 As String Dim MsgHead As New PktMsgHeader Dim Id, m As Integer Dim MsgId As String Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) Dim br As New BinaryReader(fs) Tmp2 = Space$(1) Head = Head.FromBinaryReaderBlock(br) 'Проверка на тип пакета If Head.PacketType <> 2 Or Head.cw1 <> 256 Or Head.CW2 <> 1 Then fs.Close() Exit Sub End If If Head.oPoint <> 0 And Head.oNet = -1 Then Head.oNet = Head.AuxNet tmp = br.ReadInt16 If tmp = 0 Then fs.Close() Exit Sub End If fs.Seek(-2, SeekOrigin.Current) Do MsgHead = MsgHead.FromBinaryReaderBlock(br) If MsgHead.PType <> 2 Then fs.Close() Exit Sub End If ReDim Preserve a(UBound(a) + 1) 'Это все ЛАЖОВЫЕ имена. Настоящие берутся только в MSGID!!!!!! a(UBound(a)).Date = MsgHead.datetime 'Теперь потихоньку читаем имена и сабж... Tmp3 = "" Do 'FileGet(fNum, Tmp2) Tmp2 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1)) If Tmp2 <> Chr(0) Then Tmp3 &= Tmp2 Else Exit Do Loop a(UBound(a)).ToName = Tmp3 Tmp3 = "" Do Tmp2 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1)) If Tmp2 <> Chr(0) Then Tmp3 &= Tmp2 Else Exit Do Loop a(UBound(a)).FromName = Tmp3 Tmp3 = "" Do Tmp2 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1)) If Tmp2 <> Chr(0) Then Tmp3 &= Tmp2 Else Exit Do Loop a(UBound(a)).Subject = Tmp3 'Прокручиваем текст сообщения... 'Ищем MSGID и REPLY и смотрим реальные адреса 'С вероятностью сто процентов в первых 64 байтах будет Tmp3 = Space(1024) Do LastSeek = fs.Position 'Смещение начала этой мессаги 'FileGet(fNum, Tmp3) Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) 'Определаем полный адрес From Id = InStr(Left(Tmp3, 128), Chr(1) & "MSGID: ") If Id <> 0 Then 'Выкусываем имя из MSGID MsgId = Mid(Tmp3, Id + 8, InStr(Id + 8, Tmp3, " ") - (Id + 8)) GetAddress(MsgId, a(UBound(a)).FromAdr) End If 'Определаем полный адрес To Id = InStr(Left(Tmp3, 64), Chr(1) & "REPLY: ") If Id <> 0 Then 'Выкусываем имя из REPLY MsgId = Mid(Tmp3, Id + 8, InStr(Id + 8, Tmp3, " ") - (Id + 8)) GetAddress(MsgId, a(UBound(a)).ToAdr) Else Id = InStr(Left(Tmp3, 64), Chr(1) & "INTL ") If Id <> 0 Then 'Выкусываем имя из INTL MsgId = Mid(Tmp3, Id + 6, InStr(Id + 6, Tmp3, " ") - (Id + 6)) Id = InStr(Left(Tmp3, 64), Chr(1) & "TOPT ") If Id <> 0 Then MsgId = MsgId & "." & Mid(Tmp3, Id + 6, InStr(Id + 6, Tmp3, " ") - (Id + 6)) GetAddress(MsgId, a(UBound(a)).ToAdr) End If End If m = InStr(Tmp3, Chr(0)) Loop Until m <> 0 'Seek(fNum, LastSeek + m) fs.Seek(LastSeek + m, SeekOrigin.Begin) Loop br.Close() fs.Close() End Sub ''' <summary> ''' Читает сообщение с номером Wich из pkt'шника ''' </summary> ''' <param name="Wich"></param> ''' <param name="Message"></param> ''' <param name="FileName"></param> ''' <remarks></remarks> Public Sub PktMsgRead(ByRef Wich As Integer, ByRef Message() As String, ByRef FileName As String) Dim Head As New PktHeader Dim tmp As Short, Tmp3 As String Dim MsgHead As New PktMsgHeader Dim m, i, m1 As Integer, LastSeek As Integer Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) Dim br As New BinaryReader(fs) Head = Head.FromBinaryReaderBlock(br) 'Проверка на тип пакета If Head.PacketType <> 2 Or Head.cw1 <> 256 Or Head.CW2 <> 1 Then fs.Close() Exit Sub End If tmp = br.ReadInt16() If tmp = 0 Then fs.Close() Exit Sub End If fs.Seek(-2, SeekOrigin.Current) For i = 1 To Wich MsgHead = MsgHead.FromBinaryReaderBlock(br) 'FileGet(fNum, MsgHead) If MsgHead.PType <> 2 Then fs.Close() Exit Sub End If 'Прокручиваем имена, сабж и текст сообщения... For j As Integer = 1 To 4 Tmp3 = Space(1024) Do Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(Tmp3, Chr(0)) Loop Until m <> 0 fs.Seek(m, SeekOrigin.Current) 'Seek(fNum, LastSeek + m) If i = Wich And j = 3 Then Exit For End If Next Next 'Читаем само сообщение... Tmp3 = Space(1024) Do LastSeek = fs.Position 'FileGet(fNum, Tmp3) Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(Tmp3, Chr(13)) m1 = InStr(Tmp3, Chr(0)) If (m <> 0 And m1 = 0) Or (m < m1 And m1 <> 0 And m <> 0) Then 'Читаем очередную строчку ReDim Preserve Message(UBound(Message) + 1) Message(UBound(Message)) = Left(Tmp3, m - 1) 'Seek(fNum, LastSeek + m) fs.Seek(-LastSeek + m, SeekOrigin.Current) ElseIf m1 <> 0 Then 'Последняя строчка ReDim Preserve Message(UBound(Message) + 1) Message(UBound(Message)) = Left(Tmp3, m1 - 1) Exit Do End If Loop br.Close() fs.Close() End Sub ''' <summary> ''' Тоссинг пакета ''' </summary> ''' <param name="FileName">полный путь к pkt файлу</param> ''' <remarks></remarks> Public Sub PktTossPacket(ByRef FileName As String) Dim Head As New PktHeader Dim tmp, m, i As Integer Dim Tmp3 As String = "", tmpText As String Dim MsgHead As New PktMsgHeader Dim LastSeek As Integer Dim Message() As String Dim tmpMess As New MessStruct Dim nPacket As New Packet Dim PktMsgInfo() As MsgInfo Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read) Dim br As New BinaryReader(fs) 'Читает сообщение с номером Wich из pkt'шника PktInfo(nPacket, FileName) ReDim Messages(nPacket.Records) ReDim PktMsgInfo(0) PktMsgList(PktMsgInfo, FileName) Head = Head.FromBinaryReaderBlock(br) tmpMess.Pkt = Head 'Проверка на тип пакета If Head.PacketType <> 2 Or Head.cw1 <> 256 Or Head.CW2 <> 1 Then fs.Close() Exit Sub End If tmp = br.ReadInt16 If tmp = 0 Then fs.Close() Exit Sub End If 'Seek(fNum, Seek(fNum) - 2) fs.Seek(-2, SeekOrigin.Current) MsgHead = MsgHead.FromBinaryReaderBlock(br) If MsgHead.PType <> 2 Then fs.Close() Exit Sub End If For i = 1 To UBound(Messages) 'Прокручиваем имена, сабж и текст сообщения... For j As Integer = 1 To 4 Tmp3 = Space(1024) Do LastSeek = fs.Position Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(Tmp3, Chr(0)) If j = 3 Then 'LastSeek = LastSeek + m 'Get FNum, , Tmp3 Exit Do End If 'fs.Seek(LastSeek + m, SeekOrigin.Begin) Loop Until m <> 0 If j < 3 Then 'Seek(fNum, LastSeek + m) fs.Seek(LastSeek + m, SeekOrigin.Begin) Else fs.Seek(LastSeek, SeekOrigin.Begin) Exit For End If Next tmpMess.Hdr = PktMsgInfo(i) ReDim Message(0) 'Читаем само сообщение... tmpText = vbNullString m = InStr(Tmp3, Chr(0)) LastSeek = LastSeek + m 'Seek(fNum, LastSeek) fs.Seek(LastSeek, SeekOrigin.Begin) Tmp3 = Space(1024) Do LastSeek = fs.Position 'FileGet(fNum, Tmp3) Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(1, Tmp3, Chr(0)) If m > 0 Then tmpText = tmpText & Left(Tmp3, m - 1) LastSeek += Left(Tmp3, m - 1).Length Exit Do Else tmpText &= Tmp3 LastSeek += Tmp3.Length End If Loop tmpMess.Msg = Split(tmpText, Chr(13)) Messages(i) = tmpMess 'Seek(fNum, LastSeek) fs.Seek(LastSeek, SeekOrigin.Begin) 'FileGet(fNum, Tmp3) Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(1, Tmp3, New String(Chr(0), 2)) If InStr(1, Tmp3, New String(Chr(0), 2)) <> m Then m += 1 End If If InStr(1, Tmp3, New String(Chr(0), 4)) = m Then m += 1 End If If m > 0 Then LastSeek += +m + 3 'Seek(fNum, LastSeek) 'FileGet(fNum, Tmp3) fs.Seek(LastSeek, SeekOrigin.Begin) Tmp3 = Encoding.GetEncoding(866).GetString(br.ReadBytes(1024)) m = InStr(1, Tmp3, Chr(0)) If m > 0 Then LastSeek += m End If End If 'Seek(fNum, LastSeek) fs.Seek(LastSeek, SeekOrigin.Begin) Next 'i br.Close() fs.Close() End Sub End Module
Public Class IniVar Public Section As String Public VarName As String Public Value As String Public Desc As String Public Visible As Boolean Public IconFullPath As String = "" Public ValueOptions As New List(Of String) End Class
'****************************************************************************' ' ' ' Download evaluation version: https://bytescout.com/download/web-installer ' ' ' ' Signup Cloud API free trial: https://secure.bytescout.com/users/sign_up ' ' ' ' Copyright © 2017 ByteScout Inc. All rights reserved. ' ' http://www.bytescout.com ' ' ' '****************************************************************************' Imports System.Diagnostics Imports Bytescout.BarCode Class Program Friend Shared Sub Main(args As String()) ' Create new barcode Dim barcode As New Barcode() ' Set symbology barcode.Symbology = SymbologyType.Code39 ' Set value barcode.Value = "Sample" ' Specify barcode size by bounds to fit into. ' You can use any measure units. barcode.FitInto(5, 3, UnitOfMeasure.Inch) ' Save barcode to image barcode.SaveImage("result.png") ' Show image in default image viewer Process.Start("result.png") End Sub End Class
Public Class TarjetaRegistradaENT Private vId As Integer Public Property Id() As Integer Get Return vId End Get Set(ByVal value As Integer) vId = value End Set End Property Private vNombre As String Public Property Nombre() As String Get Return vNombre End Get Set(ByVal value As String) vNombre = value End Set End Property Private vNumero As String Public Property Numero() As String Get Return vNumero End Get Set(ByVal value As String) vNumero = value End Set End Property Private vCodigoSeguridad As String Public Property CodigoSeguridad() As String Get Return vCodigoSeguridad End Get Set(ByVal value As String) vCodigoSeguridad = value End Set End Property Private vMesVencimiento As String Public Property MesVencimiento() As String Get Return vMesVencimiento End Get Set(ByVal value As String) vMesVencimiento = value End Set End Property Private vAnoVencimiento As String Public Property AnoVencimiento() As String Get Return vAnoVencimiento End Get Set(ByVal value As String) vAnoVencimiento = value End Set End Property Private vIdTarjeta As Integer Public Property IdTarjeta() As Integer Get Return vIdTarjeta End Get Set(ByVal value As Integer) vIdTarjeta = value End Set End Property Private vBaja As Boolean Public Property Baja() As Boolean Get Return vBaja End Get Set(ByVal value As Boolean) vBaja = value End Set End Property End Class
'=============================================================================== ' EntitySpaces Studio by EntitySpaces, LLC ' Persistence Layer and Business Objects for Microsoft .NET ' EntitySpaces(TM) is a legal trademark of EntitySpaces, LLC ' http://www.entityspaces.net '=============================================================================== ' EntitySpaces Version : 2012.1.0319.0 ' EntitySpaces Driver : MySql ' Date Generated : 3/17/2012 4:52:09 AM '=============================================================================== Imports System Imports System.Collections.Generic Imports System.Text Imports System.Data Imports EntitySpaces.Interfaces Imports EntitySpaces.Core Namespace BusinessObjects Partial Public Class ConcurrencyTestChildMetadata Inherits esMetadata Implements IMetadata Private Shared Function RegisterDelegateesMySQL() As Integer ' This is only executed once per the life of the application SyncLock GetType(ConcurrencyTestChildMetadata) If ConcurrencyTestChildMetadata.mapDelegates Is Nothing Then ConcurrencyTestChildMetadata.mapDelegates = New Dictionary(Of String, MapToMeta) End If If ConcurrencyTestChildMetadata._meta Is Nothing Then ConcurrencyTestChildMetadata._meta = New ConcurrencyTestChildMetadata() End If Dim mapMethod As New MapToMeta(AddressOf _meta.esMySQL) mapDelegates.Add("esMySQL", mapMethod) mapMethod("esMySQL") Return 0 End SyncLock End Function Private Function esMySQL(ByVal mapName As String) As esProviderSpecificMetadata If (Not m_providerMetadataMaps.ContainsKey(mapName)) Then Dim meta As esProviderSpecificMetadata = new esProviderSpecificMetadata() meta.AddTypeMap("Id", new esTypeMap("BIGINT", "System.Int64")) meta.AddTypeMap("Name", new esTypeMap("VARCHAR", "System.String")) meta.AddTypeMap("Parent", new esTypeMap("BIGINT", "System.Int64")) meta.AddTypeMap("ConcurrencyCheck", new esTypeMap("BIGINT", "System.Int64")) meta.AddTypeMap("DefaultTest", new esTypeMap("TIMESTAMP", "System.DateTime")) meta.AddTypeMap("ColumnA", new esTypeMap("SMALLINT", "System.Int16")) meta.AddTypeMap("ColumnB", new esTypeMap("SMALLINT", "System.Int16")) meta.AddTypeMap("ComputedAB", new esTypeMap("SMALLINT", "System.Int16")) meta.Catalog = "aggregatedb" meta.Source = "concurrencytestchild" meta.Destination = "concurrencytestchild" meta.spInsert = "proc_concurrencytestchildInsert" meta.spUpdate = "proc_concurrencytestchildUpdate" meta.spDelete = "proc_concurrencytestchildDelete" meta.spLoadAll = "proc_concurrencytestchildLoadAll" meta.spLoadByPrimaryKey = "proc_concurrencytestchildLoadByPrimaryKey" m_providerMetadataMaps.Add("esMySQL", meta) End If Return m_providerMetadataMaps("esMySQL") End Function Private Shared _esMySQL As Integer = RegisterDelegateesMySQL() End Class End Namespace
Imports FredCK.FCKeditorV2 Imports System.Threading Imports MB.TheBeerHouse Imports MB.TheBeerHouse.BLL.Newsletters Namespace MB.TheBeerHouse.UI.Admin Partial Class SendingNewsletter Inherits BasePage Implements ICallbackEventHandler Dim callbackResult As String = "" Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim isSending As Boolean = False Newsletter.Lock.AcquireReaderLock(Timeout.Infinite) isSending = Newsletter.IsSending Newsletter.Lock.ReleaseReaderLock() ' If no newsletter is currently being sent, show a panel with a message saying so. ' Otherwise register the server-side callback procedure to update the progressbar If Not (Me.IsPostBack) AndAlso Not (isSending) Then panNoNewsletter.Visible = True panProgress.Visible = False Else Dim callbackRef As String = Me.ClientScript.GetCallbackEventReference( _ Me, "", "UpdateProgress", "null") lblScriptName.Text = callbackRef Me.ClientScript.RegisterStartupScript(Me.GetType(), "StartUpdateProgress", _ "<script type=""text/javascript"">CallUpdateProgress();</script>") End If End Sub Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult Return callbackResult End Function Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent Newsletter.Lock.AcquireReaderLock(Timeout.Infinite) callbackResult = Newsletter.PercentageCompleted.ToString("N0") & ";" & _ Newsletter.SentMails.ToString() & ";" & Newsletter.TotalMails.ToString() Newsletter.Lock.ReleaseReaderLock() End Sub End Class End Namespace
Imports Microsoft.VisualBasic Imports System.Data.SqlClient Imports System.Data Namespace Madam Public Class Services 'Declarations Private m_ServiceID As Integer Private m_ServiceImage As String Private m_ServiceHeadline As String Private m_ServiceBody As String Private m_ServicePrice As String Private m_ServiceDateUploaded As DateTime Private Shared con As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyDB").ToString()) 'Attributes Public Property ID As Integer Get Return m_ServiceID End Get Set(value As Integer) m_ServiceID = value End Set End Property Public Property Image As String Get Return m_ServiceImage End Get Set(value As String) m_ServiceImage = value End Set End Property Public Property Headline As String Get Return m_ServiceHeadline End Get Set(value As String) m_ServiceHeadline = value End Set End Property Public Property Body As String Get Return m_ServiceBody End Get Set(value As String) m_ServiceBody = value End Set End Property Public Property DateUploaded As DateTime Get Return m_ServiceDateUploaded End Get Set(value As DateTime) m_ServiceDateUploaded = value End Set End Property Public Property Price As String Get Return m_ServicePrice End Get Set(value As String) m_ServicePrice = value End Set End Property 'Constructors Public Sub New() End Sub Public Sub New(ID As Integer) Dim newServices As Services = GetServices(ID).Item(0) m_ServiceID = newServices.ID m_ServiceImage = newServices.Image m_ServiceHeadline = newServices.Headline m_ServiceBody = newServices.Body m_ServiceDateUploaded = newServices.DateUploaded m_ServicePrice = newServices.Price End Sub 'Methods Public Shared Function GetServices(ID As Integer) As List(Of Services) Dim getSingleServicesCommand As New SqlCommand("SELECT * FROM Services WHERE ID = @ID", con) getSingleServicesCommand.Parameters.Add("@ID", SqlDbType.Int).Value = ID Dim dt As New DataTable Dim da As New SqlDataAdapter(getSingleServicesCommand) con.Open() da.Fill(dt) con.Close() Dim singleServices As List(Of Services) = ConvertServicesDS(dt) Return singleServices End Function Public Shared Function GetServicesList() As List(Of Services) Dim getSingleServicesCommand As New SqlCommand("SELECT * FROM Services ORDER BY DateUpload DESC", con) Dim dt As New DataTable Dim da As New SqlDataAdapter(getSingleServicesCommand) con.Open() da.Fill(dt) con.Close() Dim singleServices As List(Of Services) = ConvertServicesDS(dt) 'Sorting example 'singleServices = singleServices.OrderBy(Function(x) x.ServicesID).ToList() Return singleServices End Function Private Shared Function ConvertServicesDS(ServicessTable As DataTable) As List(Of Services) Dim ServicesList As New List(Of Services) For Each row As DataRow In ServicessTable.Rows Dim tempServices As New Services tempServices.ID = CType(row.Item("ID"), Integer) tempServices.Image = row.Item("Image").ToString() tempServices.Headline = row.Item("Headline").ToString() tempServices.Body = row.Item("Body").ToString() tempServices.DateUploaded = CType(row.Item("DateUpload"), DateTime) tempServices.Price = row.Item("Price").ToString() ServicesList.Add(tempServices) Next Return ServicesList End Function Public Function Insert() As Integer Dim insertServicesCommand As New SqlCommand("INSERT INTO Services (Image, Headline, Price, Body, DateUpload) OUTPUT Inserted.ID VALUES (@Image, @Headline, @Price, @Body, @DateUpload)", con) insertServicesCommand.Parameters.Add("@Image", SqlDbType.VarChar).Value = m_ServiceImage insertServicesCommand.Parameters.Add("@Headline", SqlDbType.NVarChar).Value = m_ServiceHeadline insertServicesCommand.Parameters.Add("@Price", SqlDbType.VarChar).Value = m_ServicePrice insertServicesCommand.Parameters.Add("@Body", SqlDbType.NVarChar).Value = m_ServiceBody insertServicesCommand.Parameters.Add("@DateUpload", SqlDbType.SmallDateTime).Value = m_ServiceDateUploaded con.Open() Dim result As Integer = insertServicesCommand.ExecuteScalar con.Close() Return result End Function Public Function Update() As Boolean Dim updateServicesCommand As New SqlCommand("UPDATE Services SET Image = @Image, Headline = @Headline, Price = @Price, Body = @Body, DateUpload = @DateUpload WHERE ID = @ID", con) updateServicesCommand.Parameters.Add("@ID", SqlDbType.Int).Value = m_ServiceID updateServicesCommand.Parameters.Add("@Image", SqlDbType.VarChar).Value = m_ServiceImage updateServicesCommand.Parameters.Add("@Headline", SqlDbType.NVarChar).Value = m_ServiceHeadline updateServicesCommand.Parameters.Add("@Price", SqlDbType.VarChar).Value = m_ServicePrice updateServicesCommand.Parameters.Add("@Body", SqlDbType.NVarChar).Value = m_ServiceBody updateServicesCommand.Parameters.Add("@DateUpload", SqlDbType.SmallDateTime).Value = m_ServiceDateUploaded con.Open() Dim result As Boolean = Convert.ToBoolean(updateServicesCommand.ExecuteNonQuery()) con.Close() Return result End Function Public Function Delete() As Boolean Dim deleteServicesCommand As New SqlCommand("DELETE FROM Services WHERE ID = @ID", con) deleteServicesCommand.Parameters.Add("@ID", SqlDbType.Int).Value = m_ServiceID con.Open() Dim result As Boolean = Convert.ToBoolean(deleteServicesCommand.ExecuteNonQuery()) con.Close() Return result End Function End Class End Namespace
Imports DTIServerControls ''' <summary> ''' A menu item used in a menu. Can be added in code, to the aspx page or from data. ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("A menu item used in a menu. Can be added in code, to the aspx page or from data."),ToolboxData("<{0}:MenuItem ID=""MenuItem"" runat=""server""> </{0}:MenuItem>"),ComponentModel.ToolboxItem(False)> _ Public Class MenuItem Inherits DTIServerBase #Region "properties" Private Property selectedParentPage() As String Get If Page.Session("ParentPageOfTheCurrentlySelectedPageIfItIsAChildPage") Is Nothing Then Page.Session("ParentPageOfTheCurrentlySelectedPageIfItIsAChildPage") = "" End If Return Page.Session("ParentPageOfTheCurrentlySelectedPageIfItIsAChildPage") End Get Set(ByVal value As String) Page.Session("ParentPageOfTheCurrentlySelectedPageIfItIsAChildPage") = value End Set End Property Private _phTable As dsDTIAdminPanel.MenuItemDataTable Private ReadOnly Property phTable() As dsDTIAdminPanel.MenuItemDataTable Get If _phTable Is Nothing Then _phTable = CType(BaseClasses.Spider.spiderUpforType(Me, GetType(Menu)), Menu).MenuItems End If Return _phTable End Get End Property Private ReadOnly Property dsi() As dsDTIAdminPanel Get If Page.Session("DTIAdminPanel.Pagelist") Is Nothing Then Page.Session("DTIAdminPanel.Pagelist") = New dsDTIAdminPanel End If Return Page.Session("DTIAdminPanel.Pagelist") End Get End Property Private _DepthOfMenu As Integer = 2 <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)> _ Public Property DepthOfMenu() As Integer Get Return _DepthOfMenu End Get Set(ByVal value As Integer) _DepthOfMenu = value End Set End Property Private ReadOnly Property loggedin() As Boolean Get Return DTISharedVariables.LoggedIn End Get End Property #End Region Private currentDepth As Integer = 0 <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)> _ Public Function RenderMenuItem(ByVal selectedCss As String, ByVal selectParent As Boolean, Optional ByVal id As Integer = -1) As LiteralControl Dim options As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.Multiline Or RegexOptions.CultureInvariant Or RegexOptions.IgnorePatternWhitespace Or RegexOptions.Compiled Dim txt As New LiteralControl Dim dv As New DataView(phTable, "ParentId = " & id, "SortOrder", DataViewRowState.CurrentRows) Dim hasChildren As Regex = New Regex("<hasChildren>(?<Name>.*?)</hasChildren>", options) Dim hasNoChildren As Regex = New Regex("<hasNoChildren>(?<Name>.*?)</hasNoChildren>", options) 'Dim selectedLI As Regex = New Regex("<li>", options) Dim selectedLI As Regex Dim linkreg As Regex = New Regex("\#\#link\#\#", options) Dim namereg As Regex = New Regex("\#\#name\#\#", options) Dim idreg As Regex = New Regex("\#\#id\#\#", options) Dim selectedClass As Regex = New Regex("\#\#selected\#\#", options) Dim link As String = "" Dim name As String = "" txt.Text = "" For Each itm As Control In Me.Controls If TypeOf itm Is LiteralControl Then txt.Text &= CType(itm, LiteralControl).Text ElseIf itm.GetType Is GetType(MenuItem) Then Dim currentitem As MenuItem = CType(itm, MenuItem) currentitem.DepthOfMenu = DepthOfMenu currentDepth += 1 If currentDepth < DepthOfMenu OrElse DepthOfMenu = -1 Then For Each crow As DataRowView In dv Dim ht As Hashtable = CType(BaseClasses.Spider.spiderUpforType(Me, GetType(Menu)), Menu).ItemToData If ht.Contains(crow("id")) Then txt.Text &= CType(ht(crow("id")), MenuItem).RenderMenuItem(selectedCss, selectParent, crow.Item("id")).Text Else txt.Text &= currentitem.RenderMenuItem(selectedCss, selectParent, crow.Item("id")).Text End If Next End If currentDepth -= 1 Else Dim sb As New StringBuilder() Using sw As New IO.StringWriter(sb) Using textWriter As New HtmlTextWriter(sw) itm.RenderControl(textWriter) End Using End Using txt.Text &= sb.ToString() End If Next Dim phtRow As dsDTIAdminPanel.MenuItemRow = phTable.FindByid(id) If phtRow Is Nothing Then _phTable = Nothing phtRow = phTable.FindByid(id) End If If phtRow IsNot Nothing Then If phtRow.IsAdminOnlyNull OrElse Not phtRow.AdminOnly OrElse (phtRow.AdminOnly AndAlso loggedin) Then link = getPageLink(phtRow) If phtRow.IsDisplayNameNull OrElse phtRow.DisplayName = "" Then name = "Unknown" Else name = phtRow.DisplayName txt.Text = txt.Text.Replace(vbCrLf, "") txt.Text = txt.Text.Replace(vbTab, "") dv.RowFilter = "ParentId = " & id & " AND isHidden = 0" If dv.Count = 0 OrElse currentDepth = DepthOfMenu - 1 Then txt.Text = hasChildren.Replace(txt.Text, "") txt.Text = hasNoChildren.Replace(txt.Text, "$1") Else txt.Text = hasChildren.Replace(txt.Text, "$1") txt.Text = hasNoChildren.Replace(txt.Text, "") End If txt.Text = linkreg.Replace(txt.Text, link) txt.Text = namereg.Replace(txt.Text, name) txt.Text = idreg.Replace(txt.Text, id) Dim page As String = Me.Page.Request.Url.LocalPath page = page.Substring(page.LastIndexOf("/")) page = page.TrimStart("/").Replace(".aspx", "") If page.ToLower = "page" Then page = Me.Page.Request.QueryString("pagename") End If page = page.ToLower selectedLI = New Regex("<a\s+href=\""" & link.Replace(" ", "\s"), options) If (Not phtRow.IsPageNameNull AndAlso phtRow.PageName.ToLower = page) _ OrElse (Not phtRow.IsLinkNull AndAlso phtRow.Link.ToLower.Replace("/", "").Replace(".aspx", "") = page) Then If selectedLI.IsMatch(txt.Text) Then If selectParent AndAlso Not phtRow.IsparentIDNull Then 'if we wanted to select more parents like 2 parents high this is where we would do it selectedParentPage = "href=""" & getPageLink(phTable.FindByid(phtRow.parentID)) & """" Else txt.Text = selectedLI.Replace(txt.Text, "<a href=""" & link & """ class=""" & selectedCss, 1) selectedParentPage = "" End If End If End If If selectedParentPage <> "" AndAlso txt.Text.Contains(selectedParentPage) Then txt.Text = txt.Text.Replace(selectedParentPage, selectedParentPage & " class=""" & selectedCss & """") selectedParentPage = "" End If If Not phtRow.Visible Then txt.Text = "" End If Else txt.Text = "" End If End If txt.Text &= vbCrLf Return txt End Function Private Function getPageLink(ByRef phtrow As dsDTIAdminPanel.MenuItemRow) As String If phtrow.IsDTIDynamicPageNull Then Return "#" ElseIf phtrow.IsLinkNull OrElse phtrow.Link = "" Then Return "/page/" & phtrow.PageName & ".aspx" ElseIf phtrow.Link.StartsWith("http://") Then Return phtrow.Link Else : Return "/" & phtrow.Link End If End Function Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) End Sub End Class