text
stringlengths
43
2.01M
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class glasslightbar Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "Glass Bar Shading" End Function 'Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 1 End Function 'Main code for creating chart. 'Note: the argument chartIndex is unused because this demo only has 1 chart. Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _ Implements DemoModule.createChart ' The data for the bar chart Dim data() As Double = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700} ' The labels for the bar chart Dim labels() As String = {"1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", _ "2004", "2005"} ' Create a XYChart object of size 600 x 360 pixels Dim c As XYChart = New XYChart(600, 360) ' Set the plotarea at (60, 40) and of size 480 x 280 pixels. Use a vertical gradient color ' from light blue (eeeeff) to deep blue (0000cc) as background. Set border and grid lines to ' white (ffffff). c.setPlotArea(60, 40, 480, 280, c.linearGradientColor(60, 40, 60, 280, &Heeeeff, &H0000cc _ ), -1, &Hffffff, &Hffffff) ' Add a title to the chart using 18pt Times Bold Italic font c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18) ' Add a multi-color bar chart layer using the supplied data. Use glass lighting effect with ' light direction from the left. c.addBarLayer3(data).setBorderColor(Chart.Transparent, Chart.glassEffect( _ Chart.NormalGlare, Chart.Left)) ' Set the x axis labels c.xAxis().setLabels(labels) ' Show the same scale on the left and right y-axes c.syncYAxis() ' Set the left y-axis and right y-axis title using 10pt Arial Bold font c.yAxis().setTitle("USD (millions)", "Arial Bold", 10) c.yAxis2().setTitle("USD (millions)", "Arial Bold", 10) ' Set all axes to transparent c.xAxis().setColors(Chart.Transparent) c.yAxis().setColors(Chart.Transparent) c.yAxis2().setColors(Chart.Transparent) ' Set the label styles of all axes to 8pt Arial Bold font c.xAxis().setLabelStyle("Arial Bold", 8) c.yAxis().setLabelStyle("Arial Bold", 8) c.yAxis2().setLabelStyle("Arial Bold", 8) ' Output the chart viewer.Chart = c 'include tool tip for the chart viewer.ImageMap = c.getHTMLImageMap("clickable", "", "title='Year {xLabel}: US$ {value}M'") End Sub End Class
Imports Microsoft.VisualBasic Imports System Imports System.Data Imports System.Configuration Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Imports System.IO Imports System.Text Imports System.Collections Imports System.Xml Imports System.Xml.Serialization ''' <summary> ''' Summary description for Utility ''' </summary> Public Class Utility Public Shared Function ParseString(ByVal sVal As String, ByVal startTag As String, ByVal EndTag As String) As String Dim sIn As String = sVal Dim sOut As String = "" Dim tagStart As Integer = sIn.ToLower().IndexOf(startTag.ToLower()) Try sIn = sIn.Remove(0, tagStart) sIn = sIn.Replace(startTag, "") Dim tagEnd As Integer = sIn.ToLower().IndexOf(EndTag.ToLower()) Dim sName As String = sIn.Substring(0, tagEnd) sOut = sName Catch End Try Return sOut End Function ''' <summary> ''' Returns the Xml representation of object-specific data as a string ''' </summary> ''' <returns></returns> Public Shared Function ObjectToXML(ByVal type As Type, ByVal obby As Object) As String 'Create the serializer Dim ser As XmlSerializer = New XmlSerializer(type) Using stm As System.IO.MemoryStream = New System.IO.MemoryStream() 'serialize to a memory stream ser.Serialize(stm, obby) 'reset to beginning so we can read it. stm.Position = 0 'Convert a string. Using stmReader As System.IO.StreamReader = New System.IO.StreamReader(stm) Dim xmlData As String = stmReader.ReadToEnd() Return xmlData End Using End Using End Function Public Shared Function XmlToObject(ByVal type As Type, ByVal xml As String) As Object Dim oOut As Object = Nothing 'hydrate based on private string var If xml IsNot Nothing Then If xml.Length > 0 Then Try Dim serializer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(type) Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder() sb.Append(xml) Dim sReader As System.IO.StringReader = New System.IO.StringReader(xml) oOut = serializer.Deserialize(sReader) sb = Nothing sReader.Close() Catch ex As Exception End Try End If End If Return oOut End Function ''' <summary> ''' This method will examine the current URL for use of https. If https:// isn't present, ''' the page will reset itself to the secure url. This does NOT happen for localhost. ''' </summary> Public Shared Sub TestForSSL() 'this is the current url Dim currentUrl As System.Uri = System.Web.HttpContext.Current.Request.Url 'don't redirect if this is localhost If (Not currentUrl.IsLoopback) Then If (Not currentUrl.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase)) Then '//show a warning '//System.Web.HttpContext.Current.Response.Write("<div style='height:30px; border:1px red solid;background-color:#ffffcc; font-weight:bold'>SSL is NOT enabled for this page which is a critical security issue. Please enable SSL on this page.</div>"); '//build the secure uri Dim secureUrlBuilder As System.UriBuilder = New UriBuilder(currentUrl) secureUrlBuilder.Scheme = "https" secureUrlBuilder.Port = -1 'redirect and end the response. System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString(), True) 'System.Web.HttpContext.Current.Response.Status = "301 Moved Permanently"; 'System.Web.HttpContext.Current.Response.AddHeader("Location", secureUrlBuilder.Uri.ToString()); End If End If End Sub ''' <summary> ''' Returns an SSL-enabled URL ''' </summary> ''' <returns></returns> Public Shared Function GetSecureRoot() As String 'this is the current url Dim siteUrl As String = Utility.GetSiteRoot() If (Not siteUrl.ToLower().StartsWith("https://")) Then siteUrl = siteUrl.Replace("http:", "https:") End If Return siteUrl End Function ''' <summary> ''' Returns a regular URL ''' </summary> ''' <returns></returns> Public Shared Function GetNonSSLRoot() As String 'this is the current url Return Utility.GetSiteRoot() End Function ''' <summary> ''' Rewrites an internal url like Product.aspx?id=1 to a nicely formatted URL ''' that can be used for site navigation. These rules are simple; if you want to ''' do more complex rewriting, UrlRewriter.NET is a very nice option. ''' </summary> ''' <param name="pageTo">This is a page where the request is going</param> ''' <param name="paramValue">The querystring param value, usually the ID</param> ''' <returns></returns> Public Shared Function GetRewriterUrl(ByVal pageTo As String, ByVal paramValue As String, ByVal extendedQString As String) As String Dim sOut As String = "" Try paramValue = paramValue.ToLower().Replace(" ", "") If extendedQString <> String.Empty Then extendedQString = "?" & extendedQString End If Catch End Try If pageTo.ToLower().Contains("catalog") Then 'for the catalog, the name is passed along as a page sOut = Utility.GetSiteRoot() & "/catalog/" & paramValue & ".aspx" & extendedQString ElseIf pageTo.ToLower().Contains("product") Then 'for the product, the sku is passed along sOut = Utility.GetSiteRoot() & "/product/" & paramValue & ".aspx" & extendedQString End If Return sOut End Function Public Shared Function ParseCamelToProper(ByVal sIn As String) As String Dim letters As Char() = sIn.ToCharArray() Dim sOut As String = "" For Each c As Char In letters If c.ToString() <> c.ToString().ToLower() Then 'it's uppercase, add a space sOut &= " " & c.ToString() Else sOut &= c.ToString() End If Next c Return sOut End Function Public Shared Function MaskCreditCard(ByVal cardNumber As String) As String If String.IsNullOrEmpty(cardNumber) Then Return String.Empty End If Dim lastFour As String = "XXXX" If cardNumber.Length > 4 Then 'get the last 4 digits lastFour = cardNumber.Substring(cardNumber.Length - 4, 4) Else End If Dim ccNumReplaced As String = "" Dim i As Integer = 0 Do While i < cardNumber.Length - 4 ccNumReplaced &= "X" i += 1 Loop ccNumReplaced &= lastFour Return ccNumReplaced End Function Public Shared Function StringToEnum(ByVal t As Type, ByVal Value As String) As Object Dim oOut As Object = Nothing For Each fi As System.Reflection.FieldInfo In t.GetFields() If fi.Name.ToLower() = Value.ToLower() Then oOut = fi.GetValue(Nothing) End If Next fi Return oOut End Function Public Shared Function GetRandomString() As String Dim builder As StringBuilder = New StringBuilder() builder.Append(RandomString(4, False)) builder.Append(RandomInt(1000, 9999)) builder.Append(RandomString(2, False)) Return builder.ToString() End Function Private Shared Function RandomInt(ByVal min As Integer, ByVal max As Integer) As Integer Dim random As Random = New Random() Return random.Next(min, max) End Function Private Shared Function RandomString(ByVal size As Integer, ByVal lowerCase As Boolean) As String Dim builder As StringBuilder = New StringBuilder() Dim random As Random = New Random() Dim ch As Char Dim i As Integer = 0 Do While i < size ch = Convert.ToChar(Convert.ToInt32(26 * random.NextDouble() + 65)) builder.Append(ch) i += 1 Loop If lowerCase Then Return builder.ToString().ToLower() End If Return builder.ToString() End Function Public Shared Function GetSiteRoot() As String Dim Port As String = System.Web.HttpContext.Current.Request.ServerVariables("SERVER_PORT") If Port Is Nothing OrElse Port = "80" OrElse Port = "443" Then Port = "" Else Port = ":" & Port End If Dim Protocol As String = System.Web.HttpContext.Current.Request.ServerVariables("SERVER_PORT_SECURE") If Protocol Is Nothing OrElse Protocol = "0" Then Protocol = "http://" Else Protocol = "https://" End If Dim appPath As String = System.Web.HttpContext.Current.Request.ApplicationPath If appPath = "/" Then appPath = "" End If Dim sOut As String = Protocol & System.Web.HttpContext.Current.Request.ServerVariables("SERVER_NAME") & Port & appPath Return sOut End Function Public Shared Function GetParameter(ByVal sParam As String) As String If Not System.Web.HttpContext.Current.Request.QueryString(sParam) Is Nothing Then Return System.Web.HttpContext.Current.Request(sParam).ToString() Else Return "" End If End Function Public Shared Function GetUrlFromQueryString(ByVal UrlParam As String) As String If Not System.Web.HttpContext.Current.Request.QueryString(UrlParam) Is Nothing Then Dim excludeParam As String = System.Web.HttpContext.Current.Request(UrlParam).ToString() Dim sbNewQuery As String = excludeParam & "?" For Each paramValue As String In System.Web.HttpContext.Current.Request.QueryString If paramValue <> excludeParam Then sbNewQuery = String.Concat(sbNewQuery, paramValue, "&") End If Next Return sbNewQuery.TrimEnd("&"c) Else Return "" End If End Function Public Shared Function GetUrlFromQueryString(ByVal UrlParam As String, ByVal Context As System.Web.HttpContext) As String If Not Context.Request.QueryString(UrlParam) Is Nothing Then Dim excludeParam As String = Context.Request(UrlParam).ToString() Dim sbNewQuery As String = excludeParam & "?" For Each paramValue As String In Context.Request.QueryString If paramValue <> excludeParam Then sbNewQuery = String.Concat(sbNewQuery, paramValue, "&") End If Next Return sbNewQuery.TrimEnd("&"c) Else Return "" End If End Function Public Shared Function GetIntParameter(ByVal sParam As String) As Integer Dim iOut As Integer = 0 If Not System.Web.HttpContext.Current.Request.QueryString(sParam) Is Nothing Then Dim sOut As String = System.Web.HttpContext.Current.Request(sParam).ToString() If (Not String.IsNullOrEmpty(sOut)) Then Integer.TryParse(sOut, iOut) End If End If Return iOut End Function Public Shared Function ShortenText(ByVal sIn As Object, ByVal length As Integer) As String Dim sOut As String = sIn.ToString() If sOut.Length > length Then sOut = sOut.Substring(0, length) & " ..." End If Return sOut End Function Public Shared Sub LoadDropDown(ByVal ddl As DropDownList, ByVal collection As ICollection, ByVal textField As String, ByVal valueField As String, ByVal initialSelection As String) ddl.DataSource = collection ddl.DataTextField = textField ddl.DataValueField = valueField ddl.DataBind() ddl.SelectedValue = initialSelection End Sub Public Shared Sub LoadListItems(ByVal list As System.Web.UI.WebControls.ListItemCollection, ByVal tblBind As DataTable, ByVal tblVals As DataTable, ByVal textField As String, ByVal valField As String) Dim l As ListItem Dim i As Integer = 0 Do While i < tblBind.Rows.Count l = New ListItem(tblBind.Rows(i)(textField).ToString(), tblBind.Rows(i)(valField).ToString()) Dim dr As DataRow Dim x As Integer = 0 Do While x < tblVals.Rows.Count dr = tblVals.Rows(x) If dr(valField).ToString().ToLower().Equals(l.Value.ToLower()) Then l.Selected = True End If x += 1 Loop list.Add(l) i += 1 Loop End Sub Public Shared Sub LoadListItems(ByVal list As System.Web.UI.WebControls.ListItemCollection, ByVal rdr As IDataReader, ByVal textField As String, ByVal valField As String, ByVal selectedValue As String, ByVal closeReader As Boolean) Dim l As ListItem Dim sText As String = "" Dim sVal As String = "" list.Clear() Do While rdr.Read() sText = rdr(textField).ToString() sVal = rdr(valField).ToString() l = New ListItem(sText, sVal) If selectedValue <> String.Empty Then If selectedValue.ToLower() = sVal.ToLower() Then l.Selected = True End If End If list.Add(l) Loop If closeReader Then rdr.Close() End If End Sub Public Shared Function GetFileText(ByVal virtualPath As String) As String 'Read from file Dim sr As StreamReader = Nothing Try sr = New StreamReader(System.Web.HttpContext.Current.Server.MapPath(virtualPath)) Catch sr = New StreamReader(virtualPath) End Try Dim strOut As String = sr.ReadToEnd() sr.Close() Return strOut End Function ''' <summary> ''' Updates the text in a file with the passed in values ''' </summary> ''' <param name="AbsoluteFilePath"></param> ''' <param name="LookFor"></param> ''' <param name="ReplaceWith"></param> Public Shared Sub UpdateFileText(ByVal AbsoluteFilePath As String, ByVal LookFor As String, ByVal ReplaceWith As String) Dim sIn As String = GetFileText(AbsoluteFilePath) Dim sOut As String = sIn.Replace(LookFor, ReplaceWith) WriteToFile(AbsoluteFilePath, sOut) End Sub ''' <summary> ''' Writes out a file ''' </summary> ''' <param name="AbsoluteFilePath"></param> ''' <param name="fileText"></param> Public Shared Sub WriteToFile(ByVal AbsoluteFilePath As String, ByVal fileText As String) Dim sw As StreamWriter = New StreamWriter(AbsoluteFilePath, False) sw.Write(fileText) sw.Close() End Sub Public Shared Sub SetListSelection(ByVal lc As System.Web.UI.WebControls.ListItemCollection, ByVal Selection As String) Dim i As Integer = 0 Do While i < lc.Count If lc(i).Value = Selection Then lc(i).Selected = True Exit Do End If i += 1 Loop End Sub Public Shared Function GetUserName() As String Dim sUserName As String = "" If HttpContext.Current.User.Identity.IsAuthenticated Then sUserName = HttpContext.Current.User.Identity.Name Else 'we'll tag them with an anon userName until they register If Not HttpContext.Current.Request.Cookies("shopperID") Is Nothing Then sUserName = HttpContext.Current.Request.Cookies("shopperID").Value Else 'if we have never seen them, return the current anonymous ID for the user sUserName = HttpContext.Current.Profile.UserName End If End If HttpContext.Current.Response.Cookies("shopperID").Value = sUserName HttpContext.Current.Response.Cookies("shopperID").Expires = DateTime.Today.AddDays(365) Return sUserName End Function #Region "Formatting bits" #Region "IsNullOrEmpty" Public Shared Function IsNullOrEmpty(ByVal text As String) As Boolean If text Is Nothing OrElse (Not text Is Nothing AndAlso text.Length = 0) Then Return True End If Return False End Function #End Region #Region "CheckStringLength" Public Shared Function CheckStringLength(ByVal stringToCheck As String, ByVal maxLength As Integer) As String Dim checkedString As String = Nothing If stringToCheck.Length <= maxLength Then Return stringToCheck End If ' If the string to check is longer than maxLength ' and has no whitespace we need to trim it down. If (stringToCheck.Length > maxLength) AndAlso (stringToCheck.IndexOf(" ") = -1) Then checkedString = stringToCheck.Substring(0, maxLength) & "..." ElseIf stringToCheck.Length > 0 Then Dim words As String() Dim expectedWhitespace As Integer = CType(stringToCheck.Length / 8, Integer) ' How much whitespace is there? words = stringToCheck.Split(" "c) checkedString = stringToCheck.Substring(0, maxLength) & "..." Else checkedString = stringToCheck End If Return checkedString End Function #End Region #Region "FormatDate" Public Shared Function FormatDate(ByVal theDate As DateTime) As String Return FormatDate(theDate, False, Nothing) End Function Public Shared Function FormatDate(ByVal theDate As DateTime, ByVal showTime As Boolean) As String Return FormatDate(theDate, showTime, Nothing) End Function Public Shared Function FormatDate(ByVal theDate As DateTime, ByVal showTime As Boolean, ByVal pattern As String) As String Dim defaultDatePattern As String = "MMMM d, yyyy" Dim defaultTimePattern As String = "hh:mm tt" If pattern Is Nothing Then If showTime Then pattern = defaultDatePattern & " " & defaultTimePattern Else pattern = defaultDatePattern End If End If Return theDate.ToString(pattern) End Function #End Region #Region "UserIsAuthenticated" Public Shared Function UserIsAuthenticated() As Boolean Dim context As HttpContext = HttpContext.Current If Not context.User Is Nothing AndAlso Not context.User.Identity Is Nothing AndAlso (Not Utility.IsNullOrEmpty(context.User.Identity.Name)) Then Return True End If Return False End Function #End Region #Region "StripHTML" Public Shared Function StripHTML(ByVal htmlString As String) As String Return StripHTML(htmlString, "", True) End Function Public Shared Function StripHTML(ByVal htmlString As String, ByVal htmlPlaceHolder As String) As String Return StripHTML(htmlString, htmlPlaceHolder, True) End Function Public Shared Function StripHTML(ByVal htmlString As String, ByVal htmlPlaceHolder As String, ByVal stripExcessSpaces As Boolean) As String Dim pattern As String = "<(.|\n)*?>" Dim sOut As String = System.Text.RegularExpressions.Regex.Replace(htmlString, pattern, htmlPlaceHolder) sOut = sOut.Replace("&nbsp;", "") sOut = sOut.Replace("&amp;", "&") If stripExcessSpaces Then ' If there is excess whitespace, this will remove ' like "THE WORD". Dim delim As Char() = {" "c} Dim lines As String() = sOut.Split(delim, StringSplitOptions.RemoveEmptyEntries) sOut = "" Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder() For Each s As String In lines sb.Append(s) sb.Append(" ") Next s Return sb.ToString().Trim() Else Return sOut End If End Function #End Region #Region "ToggleHtmlBR" Public Shared Function ToggleHtmlBR(ByVal text As String, ByVal isOn As Boolean) As String Dim outS As String = "" If isOn Then outS = text.Replace(Constants.vbLf, "<br />") Else ' TODO: do this with via regex ' outS = text.Replace("<br />", Constants.vbLf) outS = text.Replace("<br>", Constants.vbLf) outS = text.Replace("<br >", Constants.vbLf) End If Return outS End Function #End Region #End Region End Class
Imports System.IO Imports System.Drawing.Imaging Imports SoftLogik.Win.UI Namespace UI Public Class RecordFormBk 'Navigation Events Public Event NavigationChanged(ByVal sender As System.Object, ByVal e As SPFormNavigateEventArgs) Public Event RecordBinding(ByVal sender As System.Object, ByVal e As SPFormRecordBindingEventArgs) Public Event Databound(ByVal sender As System.Object, ByVal e As System.EventArgs) Public Event RecordChanged(ByVal sender As System.Object, ByVal e As SPFormRecordUpdateEventArgs) Public Event RecordValidating(ByVal sender As System.Object, ByVal e As SPFormValidatingEventArgs) #Region "Properties" Protected _DataSource As DataTable = Nothing Protected _BindingSettings As SPRecordBindingSettings Protected _RecordState As SPFormRecordStateManager = New SPFormRecordStateManager() Protected _LookupForm As LookupForm Protected _FirstField As Control = Nothing Protected _NewRecordProc As NewRecordCallback Public WriteOnly Property LookupForm() As LookupForm Set(ByVal value As LookupForm) _LookupForm = value End Set End Property #End Region #Region "Form Overrides" Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) MyBase.OnLoad(e) 'WindowState = FormWindowState.Maximized If Not DesignMode Then Dim dataBindSettings As New SPFormRecordBindingEventArgs() OnRecordBinding(dataBindSettings) Me._RecordState.CurrentState = SPFormRecordModes.EditMode 'By Default Form is in Edit Mode Me._RecordState.BindingData = True _DataSource = dataBindSettings.DataSource _BindingSettings = dataBindSettings.BindingSettings _NewRecordProc = _BindingSettings.NewRecordProc CreateSetupView(_DataSource, _BindingSettings) BindControls(Me.tbcMain.Controls, DetailBinding, _RecordState, AddressOf OnFieldChanged) ToolbarToggleDefault(tbrMain, tvwName) MyTabOrderManager = New UI.SPTabOrderManager(Me) MyTabOrderManager.SetTabOrder(UI.SPTabOrderManager.TabScheme.DownFirst) ' set tab order End If End Sub Protected Overrides Sub OnActivated(ByVal e As System.EventArgs) MyBase.OnActivated(e) End Sub Protected Overrides Sub OnFormClosing(ByVal e As System.Windows.Forms.FormClosingEventArgs) If _RecordState.CurrentState = SPFormRecordModes.DirtyMode Or _ _RecordState.CurrentState = SPFormRecordModes.InsertMode Then Dim msgResult As DialogResult = MessageBox.Show("Save Changes made to " & Me.Text & "?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) Select Case msgResult Case Windows.Forms.DialogResult.Yes OnSaveRecord() 'Save Changes Case Windows.Forms.DialogResult.No Case Windows.Forms.DialogResult.Cancel e.Cancel = True End Select End If MyBase.OnFormClosing(e) End Sub Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs) MyBase.OnKeyDown(e) If e.Control Then Select Case e.KeyCode Case Keys.N NewRecord.PerformClick() Case Keys.S SaveRecord.PerformClick() Case Keys.Delete DeleteRecord.PerformClick() End Select End If If e.KeyCode = Keys.Escape Then If _RecordState.CurrentState = SPFormRecordModes.DirtyMode Then UndoRecord.PerformClick() Else CloseWindow.PerformClick() End If End If End Sub #End Region #Region "Protected Overrides" Protected Overridable Sub OnRecordBinding(ByVal e As SPFormRecordBindingEventArgs) RaiseEvent RecordBinding(Me, e) 'let client respond End Sub Protected Overridable Sub OnRecordChanged(ByVal e As SPFormRecordUpdateEventArgs) RaiseEvent RecordChanged(Me, e) End Sub #End Region #Region "Private Methods" Protected Overridable Sub OnFieldChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) If _RecordState.ShowingData = False Then If _RecordState.CurrentState = SPFormRecordModes.EditMode AndAlso _ _RecordState.CurrentState <> SPFormRecordModes.DirtyMode AndAlso (Not _RecordState.BindingData) Then _RecordState.CurrentState = SPFormRecordModes.DirtyMode UpdateFormCaption() ToolbarToggleSave(tbrMain, tvwName) End If End If _RecordState.BindingData = False End Sub Protected Overridable Sub OnNewRecord() Try DetailBinding.AddNew() DetailBinding.MoveFirst() Me._RecordState.CurrentState = SPFormRecordModes.InsertMode ToolbarToggleSave(tbrMain, tvwName) FirstFieldFocus() Catch ex As Exception End Try End Sub Protected Overridable Sub OnSaveRecord() Me.Validate() Try _RecordState.ShowingData = True DetailBinding.EndEdit() _RecordState.ShowingData = False Catch ex As Exception Exit Sub End Try If DetailBinding.Current IsNot Nothing Then If Me._RecordState.CurrentState = SPFormRecordModes.InsertMode Then OnRecordChanged(New SPFormRecordUpdateEventArgs(_RecordState.NewRecordData, SPFormDataStates.[New])) _RecordState.NewRecordData = Nothing Else OnRecordChanged(New SPFormRecordUpdateEventArgs(CType(DetailBinding.Current, DataRowView).Row, SPFormDataStates.Edited)) End If RefreshMaster() ToolbarToggleDefault(tbrMain, tvwName) _RecordState.CurrentState = SPFormRecordModes.EditMode UpdateFormCaption(True) End If End Sub Protected Overridable Sub OnUndoRecord() On Error Resume Next If DetailBinding.Current IsNot Nothing Then If CType(DetailBinding.Current, DataRowView).IsNew Then DetailBinding.RemoveCurrent() Else DetailBinding.CancelEdit() End If End If _RecordState.CurrentState = SPFormRecordModes.EditMode ToolbarToggleDefault(tbrMain, tvwName) UpdateFormCaption(True) End Sub Protected Overridable Sub OnDeleteRecord() Try If MessageBox.Show("Are you sure you want to Delete '" & CType(DetailBinding.Current, DataRowView).Row(_BindingSettings.DisplayMember).ToString & "' ?", "Delete Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then OnRecordChanged(New SPFormRecordUpdateEventArgs(CType(DetailBinding.Current, DataRowView).Row, SPFormDataStates.Deleted)) _RecordState.ShowingData = True DetailBinding.RemoveCurrent() RefreshMaster() _RecordState.ShowingData = False End If Catch ex As Exception End Try End Sub Protected Overridable Sub OnSearchRecord() If _LookupForm IsNot Nothing Then With _LookupForm .ShowDialog(Me) '.SearchResults() End With End If End Sub Protected Overridable Sub OnCopyRecord() If DetailBinding.Current IsNot Nothing Then '_RecordState.ShowingData = True Dim clonedDataRow As DataRowView = CType(DetailBinding.Current, DataRowView) Dim newDataRow As DataRowView = CType(DetailBinding.AddNew(), DataRowView) DuplicateRecord(clonedDataRow, newDataRow) DetailBinding.ResetBindings(False) _RecordState.CurrentState = SPFormRecordModes.InsertMode '_RecordState.ShowingData = False End If End Sub Protected Overridable Sub OnNavigate(ByVal direction As SPRecordNavigateDirections) Dim lastRecord As DataRow, currentRecord As DataRow On Error Resume Next _RecordState.ShowingData = True lastRecord = CType(DetailBinding.Current, DataRowView).Row Select Case direction Case SPRecordNavigateDirections.First SelectNameInList(0) Case SPRecordNavigateDirections.Last SelectNameInList(DetailBinding.Count - 1) Case SPRecordNavigateDirections.Next SelectNameInList(DetailBinding.Position + 1) Case SPRecordNavigateDirections.Previous SelectNameInList(DetailBinding.Position - 1) End Select SyncNameList() _RecordState.ShowingData = False currentRecord = CType(DetailBinding.Current, DataRowView).Row RaiseEvent NavigationChanged(tbrMain, New SPFormNavigateEventArgs(direction, lastRecord, currentRecord)) End Sub Protected Overridable Sub SyncNameList() For Each node As SPTreeNode In tvwName.Nodes If (node.Index = DetailBinding.Position) Then tvwName.SelectedNode = node Return Else If (node.Nodes.Count > 0) Then If (SyncNameList(node)) Then Return End If Next End Sub Protected Overridable Function SyncNameList(ByVal InnerNode As SPTreeNode) As Boolean For Each node As SPTreeNode In InnerNode.Nodes If (node.Index = DetailBinding.Position) Then tvwName.SelectedNode = node Return True Else SyncNameList(node) End If Next Return False End Function Protected Overridable Sub OnCloseWindow() Me.Close() End Sub #End Region #Region "Support Methods" Protected Overridable Sub CreateSetupView(ByRef DataSource As DataTable, ByVal bindingSettings As SPRecordBindingSettings) If DataSource IsNot Nothing Then With tvwName .DataSource = DataSource.DefaultView .DisplayMember = bindingSettings.DisplayMember .ValueMember = bindingSettings.ValueMember DetailBinding.DataSource = DataSource DataSource.DefaultView.Sort = bindingSettings.DisplayMember & " ASC " .SetLeafData(bindingSettings.DisplayMember, bindingSettings.DisplayMember, bindingSettings.ValueMember, 0, -1) For Each itm As SPTreeNodeGroup In bindingSettings.NodeGroups .AddGroup(itm.Name, itm.GroupBy, itm.DisplayMember, itm.ValueMember, itm.ImageIndex, itm.SelectedImageIndex) Next .BuildTree() End With End If End Sub Private Sub RefreshMaster() If _DataSource IsNot Nothing Then tvwName.BuildTree() End If DetailBinding.ResetBindings(False) End Sub Private Sub UpdateFormCaption(Optional ByVal Clear As Boolean = False) Dim strText As String = Me.Text If Not Clear Then strText &= CStr(IIf(strText.EndsWith("*"), vbNullString, "*")) Me.Text = strText Else Me.Text = strText.Replace("*", vbNullString) End If End Sub Private Sub FirstFieldFocus() Dim lastTabIndex As Integer Try Dim firstControl As Control = tabGeneral.GetNextControl(tabGeneral, True) If firstControl IsNot Nothing Then lastTabIndex = firstControl.TabIndex FindFirstField(firstControl, lastTabIndex) End If Catch ex As Exception Exit Sub End Try End Sub Private Sub FindFirstField(ByRef OuterControl As Control, ByRef lastTabIndex As Integer) Dim ctl As Control = OuterControl While Not ctl Is Nothing If (Not ctl.HasChildren) AndAlso (ctl.CanFocus AndAlso ctl.CanSelect) Then ctl.Focus() Exit Sub Else ctl = ctl.GetNextControl(ctl, True) FindFirstField(ctl, lastTabIndex) End If End While End Sub Private Sub DuplicateRecord(ByVal SourceRow As DataRowView, ByRef TargetRow As DataRowView) _RecordState.DuplicatingData = True TargetRow.Row.ItemArray = SourceRow.Row.ItemArray For Each itm As DataColumn In TargetRow.Row.Table.Columns If itm.ReadOnly Then If itm.AutoIncrement Then TargetRow(itm.ColumnName) = 0 End If End If Next _RecordState.DuplicatingData = False End Sub #End Region #Region "List and Toolbar Events" Protected Overridable Sub ToolbarOperation(ByVal sender As System.Object, ByVal e As System.EventArgs) Select Case CType(sender, ToolStripItem).Name Case "NewRecord" OnNewRecord() Case "SaveRecord" OnSaveRecord() Case "DeleteRecord" OnDeleteRecord() Case "UndoRecord" OnUndoRecord() Case "SearchRecord" OnSearchRecord() Case "CopyRecord" OnCopyRecord() Case "FirstRecord" OnNavigate(SPRecordNavigateDirections.First) Case "PreviousRecord" OnNavigate(SPRecordNavigateDirections.Previous) Case "NextRecord" OnNavigate(SPRecordNavigateDirections.Next) Case "LastRecord" OnNavigate(SPRecordNavigateDirections.Last) Case "CloseWindow" 'Close Window OnCloseWindow() End Select End Sub Private Sub tbrMain_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tbrMain.ItemClicked ToolbarOperation(e.ClickedItem, e) End Sub Private Sub tvwName_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) SelectNameInList(e.Node.Index) End Sub Protected Overridable Sub SelectNameInList(ByVal Index As Integer) Dim selectedRow As Integer = Index Dim lastRecord As DataRow = Nothing, currentRecord As DataRow = Nothing If selectedRow <> -1 Then _RecordState.ShowingData = True If DetailBinding.Current IsNot Nothing Then lastRecord = CType(DetailBinding.Current, DataRowView).Row End If DetailBinding.Position = selectedRow _RecordState.ShowingData = False If DetailBinding.Current IsNot Nothing Then currentRecord = CType(DetailBinding.Current, DataRowView).Row End If RaiseEvent NavigationChanged(tbrMain, New SPFormNavigateEventArgs(SPRecordNavigateDirections.None, lastRecord, currentRecord)) End If End Sub #End Region Private Sub DetailBinding_BindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.BindingCompleteEventArgs) Handles DetailBinding.BindingComplete Me._RecordState.BindingData = False End Sub Private Sub DetailBinding_DataSourceChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DetailBinding.DataSourceChanged Me._RecordState.BindingData = True End Sub Private Sub DetailBinding_ListChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ListChangedEventArgs) Handles DetailBinding.ListChanged If e.ListChangedType = System.ComponentModel.ListChangedType.ItemAdded Then If _NewRecordProc IsNot Nothing AndAlso _RecordState.DuplicatingData = False _ AndAlso _RecordState.ShowingData = False Then CType(DetailBinding.Item(e.NewIndex), DataRowView).Row.ItemArray = _NewRecordProc.Invoke.Row.ItemArray _RecordState.NewRecordData = CType(DetailBinding.Item(e.NewIndex), DataRowView).Row End If End If End Sub End Class End Namespace
Option Explicit Dim Efile, objFSO, myFile, myFilePath, objFolder, myFolder Const ForWriting = 2 myFilePath = "text.txt"' your text file myFolder = "Folder\"'your folder make sure you add/ to the end otherwise you may have some trouble running the script eFile = InputBox ( _ "Statement in the input box header", _ "Statement in the input box", _ "Default text in the textbox" _ ) Set objFSO = CreateObject("Scritpting.FileSystemObject") If objFSO.FolderExists(myFolder) Then 'nothing Else Set objFolder = objFSO.CreateFolder("Foler\")'Folder location or where it should be. End If Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(myFilePath) Then Set myFile = objFSO.OpenTextFile("Text.txt",ForWriting)'text location myFile.WriteLine(eFile) myFile.Close Else Set objFSO = CreateObject("Scripting.FileSystemObject") Set myFile = objFSO.CreateTextFile("text.txt",ForWriting) myFile.WriteLine(eFile) myFile.Close End If
Imports Ladle.Utils Public Class AppSettings Private _testMode As Boolean = False Private _allowSnap As Boolean = True Private _name As String = "" Private _size As Single = 0 Private _style As FontStyle = FontStyle.Regular Private Sub AppSettings_Load(sender As Object, e As EventArgs) Handles MyBase.Load _name = LayoutSettings.Instance.DefaultFontName _size = LayoutSettings.Instance.DefaultFontSize _style = LayoutSettings.Instance.DefaultFontStyle _allowSnap = LayoutSettings.Instance.AllowSnapToToolbar CheckBoxAllowSnap.Checked = _allowSnap _testMode = SharedAppSettings.Instance.TestMode CheckBoxTestMode.Checked = _testMode UpdateSelectedFont() End Sub Private Sub TextBoxFont_Click(sender As Object, e As EventArgs) Handles TextBoxFont.Click Using fd As FontDialog = New FontDialog() fd.Font = New Font(LayoutSettings.Instance.DefaultFontName, LayoutSettings.Instance.DefaultFontSize, LayoutSettings.Instance.DefaultFontStyle) If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then LayoutSettings.Instance.DefaultFontName = fd.Font.Name LayoutSettings.Instance.DefaultFontSize = fd.Font.Size LayoutSettings.Instance.DefaultFontStyle = fd.Font.Style UpdateSelectedFont() End If End Using End Sub Private Sub UpdateSelectedFont() TextBoxFont.Text = String.Format("{0}, {1} {2}", LayoutSettings.Instance.DefaultFontName, LayoutSettings.Instance.DefaultFontSize, LayoutSettings.Instance.DefaultFontStyle) LabelDemo.Font = LayoutSettings.Instance.GetFont() End Sub Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click ' Save changes and close DialogResult = Windows.Forms.DialogResult.OK If _testMode <> SharedAppSettings.Instance.TestMode Then MessageBox.Show("Application will now close for changes to take effect, please restart it manually.") SharedAppSettings.Instance.Save() DialogResult = Windows.Forms.DialogResult.Abort End If End Sub Private Sub ButtonClose_Click(sender As Object, e As EventArgs) Handles ButtonClose.Click ' Undo changes and close LayoutSettings.Instance.DefaultFontName = _name LayoutSettings.Instance.DefaultFontSize = _size LayoutSettings.Instance.DefaultFontStyle = _style LayoutSettings.Instance.AllowSnapToToolbar = _allowSnap DialogResult = Windows.Forms.DialogResult.Cancel End Sub Private Sub CheckBoxAllowSnap_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBoxAllowSnap.CheckedChanged LayoutSettings.Instance.AllowSnapToToolbar = CheckBoxAllowSnap.Checked End Sub Private Sub CheckBoxTestMode_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBoxTestMode.CheckedChanged SharedAppSettings.Instance.TestMode = CheckBoxTestMode.Checked End Sub Private Sub ButtonResetLayout_Click(sender As Object, e As EventArgs) Handles ButtonResetLayout.Click MessageBox.Show("Application will now close for changes to take effect, please restart it manually.") SharedAppSettings.Instance.Save() DialogResult = Windows.Forms.DialogResult.Retry End Sub End Class
 Imports VBChess.Shared Public Class Knight Inherits ChessPiece Public Sub New(owner As Player, board As ChessBoard, position As Point) MyBase.New(owner, board, position) End Sub Public Overrides ReadOnly Property PawnType As PawnTypes Get Return PawnTypes.Knight End Get End Property Friend Overrides Function IsMoveValid(newPosition As Point) As Boolean If Not MyBase.IsMoveValid(newPosition) Then Return False If Position.Value.X = newPosition.X OrElse Position.Value.Y = newPosition.Y Then Return False Return Math.Abs(Position.Value.X - newPosition.X) + Math.Abs(Position.Value.Y - newPosition.Y) = 3 End Function End Class
Public Enum TaskState Disabled Ok Warning Fault End Enum Public Interface ITask ReadOnly Property ID As String Property Description As String Property State As TaskState ReadOnly Property Info As String Property ExternalInfo As String Property Checks As ChecksList Property FaultActions As FaultActionsList Property CheckStats As CheckStats Property ShortName As String Property ShortState As String Property AutoStart As Boolean End Interface
Imports System Imports Neurotec.Biometrics Imports Neurotec.Biometrics.Client Imports Neurotec.Biometrics.Standards Imports Neurotec.Licensing Imports System.Linq Imports Microsoft.VisualBasic Imports Neurotec.Images Friend Class Program Private Shared Function Usage() As Integer Console.WriteLine("usage:") Console.WriteLine(Constants.vbTab & "{0} [NImage] [ANTemplate] [Tot] [Dai] [Ori] [Tcn]", TutorialUtils.GetAssemblyName()) Console.WriteLine("") Console.WriteLine(Constants.vbTab & "[NImage] - filename with image file.") Console.WriteLine(Constants.vbTab & "[ANTemplate] - filename for ANTemplate.") Console.WriteLine(Constants.vbTab & "[Tot] - specifies type of transaction.") Console.WriteLine(Constants.vbTab & "[Dai] - specifies destination agency identifier.") Console.WriteLine(Constants.vbTab & "[Ori] - specifies originating agency identifier.") Console.WriteLine(Constants.vbTab & "[Tcn] - specifies transaction control number.") Console.WriteLine("") Return 1 End Function Shared Function Main(ByVal args() As String) As Integer Const Components As String = "Biometrics.FingerExtraction,Biometrics.Standards.FingerTemplates" TutorialUtils.PrintTutorialHeader(args) If args.Length <> 6 Then Return Usage() End If Try If (Not NLicense.ObtainComponents("/local", 5000, Components)) Then Throw New NotActivatedException(String.Format("Could not obtain licenses for components: {0}", Components)) End If Dim tot As String = args(2) ' type of transaction Dim dai As String = args(3) ' destination agency identifier Dim ori As String = args(4) ' originating agency identifier Dim tcn As String = args(5) ' transaction control number If (tot.Length < 3) OrElse (tot.Length > 4) Then Console.WriteLine("Tot parameter should be 3 or 4 characters length.") Return -1 End If Using biometricClient = New NBiometricClient() Using subject = New NSubject() Using finger = New NFinger() ' Create empty ANTemplate object with only type 1 record in it Using template = New ANTemplate(ANTemplate.VersionCurrent, tot, dai, ori, tcn, 0) 'Read finger image from file and add it to NFinger object finger.FileName = args(0) 'Read finger image from file and add it NSubject subject.Fingers.Add(finger) 'Create template from added finger image Dim status = biometricClient.CreateTemplate(subject) If status = NBiometricStatus.Ok Then Console.WriteLine("Template extracted") ' Create Type 9 record Dim record = New ANType9Record(ANTemplate.VersionCurrent, 0, True, subject.GetTemplate().Fingers.Records.First()) ' Add Type 9 record to ANTemplate object template.Records.Add(record) ' Store ANTemplate object with type 9 record in file template.Save(args(1)) Else Console.WriteLine("Extraction failed: {0}", status) End If End Using End Using End Using End Using Return 0 Catch ex As Exception Return TutorialUtils.PrintException(ex) Finally NLicense.ReleaseComponents(Components) End Try End Function End Class
Imports System.Collections.Generic Imports DevExpress.Mvvm.DataAnnotations Imports DevExpress.Xpf.Map Namespace MapDemo <POCOViewModel> Public Class ShopInfoViewModel Public Overridable Property Name() As String Public Overridable Property Phone() As String Public Overridable Property Fax() As String Public Overridable Property Address() As String Public Overridable Property Sales() As Double Public Overridable Property ShopLocation() As GeoPoint Private Shared Function ConvertShopNameToFilePath(ByVal ShopName As String) As String Dim result As String = ShopName.Replace(" ", "") result = "../Images/Shops/" & result.Replace("-", "") & ".png" Return result End Function Private statistics As New Dictionary(Of String, Double)() Private ReadOnly imagePath_Renamed As String Public Sub New(ByVal Name As String, ByVal Address As String, ByVal Phone As String, ByVal Fax As String) Me.Name = Name Me.Address = Address Me.Phone = Phone Me.Fax = Fax Me.imagePath_Renamed = ConvertShopNameToFilePath(Name) End Sub Public ReadOnly Property ImagePath() As String Get Return imagePath_Renamed End Get End Property Public Sub AddProductGroup(ByVal groupName As String, ByVal sales As Double) If statistics.ContainsKey(groupName) Then statistics(groupName) = sales Else statistics.Add(groupName, sales) End If Me.Sales += sales End Sub Public Function GetSalesByProductGroup(ByVal groupName As String) As Double Return If(statistics.ContainsKey(groupName), statistics(groupName), 0.0) End Function End Class End Namespace
Imports System '1.7. Crear un proyecto llamado “EquivalenciasPies”. Se debe ingresar una distancia medidas en 'pies y calcular su equivalente en pulgadas, yarda, cms y metros. Utilizar únicamente las 'equivalencias conocidas : 1 pie = 12 pulgadas, 1 yarda = 3 pies, 1 pulgada = 2.54 cm, 1 metro '= 100 cm. Module EquivalenciasPies Sub Main(args As String()) Dim datos As Integer = ingresoDatos() Console.WriteLine(equivalencias(datos)) End Sub Function ingresoDatos() As UInt32 Console.Write("Ingrese un valor en pies : ") Return Console.ReadLine() End Function Function equivalencias(datos As Integer) As String Dim opcion As Byte Console.WriteLine("Ingrese el valor a convertir") Console.WriteLine("1 - Pulgada") Console.WriteLine("2 - Yarda") Console.WriteLine("3 - Centimetros ") Console.WriteLine("4 - Metro ") Console.Write("Seleccione una opción : ") opcion = Console.ReadLine Select Case opcion Case 1 Return "Pulgadas : " & datos * 12 Case 2 Return "Yarda : " & datos / 3 Case 3 Return "Centimetros : " & datos * 12 * 2.54 Case 4 Return "Metro : " & (datos * 12 * 2.54) / 100 Case Else Return "Error en la elección" End Select End Function End Module
Imports System.Data.SqlClient Public Class TipoHabitacion Dim conexion As Conexion = New Conexion() Dim tabla As New DataTable Private Sub btnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click If txtNombre.Text = String.Empty Or txtCapacidad.Text = String.Empty Then MessageBox.Show("Debe llenar todas las casillas ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If Dim Nombre As String Dim Capacidad As Integer Nombre = txtNombre.Text Capacidad = Int(Val(txtCapacidad.Text)) Dim temporal As Boolean = conexion.IngresarTipoHabitacion(Nombre, Capacidad) Try If temporal = True Then MsgBox("Ingresado correctamente") Else MsgBox("Error al Ingresar") End If Catch ex As Exception MsgBox(ex.Message) Finally Limpiar() End Try End Sub Private Sub Limpiar() txtNombre.Clear() txtCapacidad.Clear() End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BtnActualizar.Click If txtNombre.Text = String.Empty Or txtCapacidad.Text = String.Empty Then MessageBox.Show("Seleccione un Tipo de Habitacion de la Tabla ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If Dim Nombre As String Dim Capacidad As Integer Nombre = txtNombre.Text Capacidad = Int(Val(txtCapacidad.Text)) Dim temporal As Boolean = conexion.actualizarTipoHabitacion(Variables.Id, Nombre, Capacidad) Try If temporal = True Then MsgBox("Ingresado correctamente") Else MsgBox("Error al Ingresar") End If Catch ex As Exception MsgBox(ex.Message) Finally Limpiar() End Try End Sub Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click Try tabla = conexion.ConsultarTipoHabitaciones() If tabla.Rows.Count <> 0 Then dtgTipoHabitacion.DataSource = tabla Else dtgTipoHabitacion.DataSource = Nothing End If Catch ex As Exception MsgBox("Error al Listar") End Try End Sub Private Sub dtgTipoHabitacion_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dtgTipoHabitacion.CellContentClick Variables.Id = dtgTipoHabitacion.CurrentRow.Cells(0).Value.ToString txtNombre.Text = dtgTipoHabitacion.CurrentRow.Cells(1).Value.ToString txtCapacidad.Text = dtgTipoHabitacion.CurrentRow.Cells(2).Value.ToString End Sub End Class
 Imports AW.Services Namespace AW.Types Partial Public Class Store Inherits BusinessEntity Implements ITitledObject, INotEditableOncePersistent #Region "Name" Public Property mappedName As String Friend myName As TextString <DemoProperty(Order:=20)> Public ReadOnly Property Name As TextString Get myName = If(myName, New TextString(mappedName, Sub(v) mappedName = v)) Return myName End Get End Property Public Sub AboutName(a As FieldAbout, Name As TextString) Select Case a.TypeCode Case AboutTypeCodes.Name a.Name = "Store Name" Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region ''<Hidden> Public Property Demographics() As String 'TODO: <MultiLine(10)> <DemoProperty(Order:=30)> Public ReadOnly Property FormattedDemographics() As TextString Get Return New TextString("TODO") 'TODO Utilities.FormatXML(Demographics) End Get End Property Public Sub AboutFormattedDemographics(a As FieldAbout) Select Case a.TypeCode Case AboutTypeCodes.Name a.Name = "Demographics" Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub ''<Hidden> Public Property SalesPersonID() As Integer? <DemoProperty(Order:=40)> Public Overridable Property SalesPerson() As SalesPerson #Region "ModifiedDate" Public Property mappedModifiedDate As Date Friend myModifiedDate As TimeStamp <DemoProperty(Order:=99)> Public ReadOnly Property ModifiedDate As TimeStamp Get myModifiedDate = If(myModifiedDate, New TimeStamp(mappedModifiedDate, Sub(v) mappedModifiedDate = v)) Return myModifiedDate End Get End Property Public Sub AboutModifiedDate(a As FieldAbout) Select Case a.TypeCode Case AboutTypeCodes.Usable a.Usable = False End Select End Sub #End Region ''<Hidden> Public Property RowGuid() As Guid Public Function Title() As Title Implements ITitledObject.Title Return New Title(ToString()) End Function Public Overrides Function ToString() As String Return mappedName End Function End Class End Namespace
 Public Class frmPrincipal Const mc_strNombre_Modulo As String = "frmPrincipal" Enum ActualForm Detalles Historial Presupuesto End Enum Private Sub frmIncidencia_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Const strNombre_Funcion As String = "frmIncidencia_Load" Try CargarAplicacion() frmListadoIncidencias.WindowState = FormWindowState.Minimized frmListadoIncidencias.WindowState = FormWindowState.Maximized frmListadoIncidencias.Ajustar() HabilitarBotonesIncidencias() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub CargarAplicacion() Const strNombre_Funcion As String = "CargarAplicacion" Try 'CARGAR ARCHIVO DE CONFIGURACION CargarConfiguracionINI() EstablecerFiltrosEstados() If ComprobarDatosAplicacion() Then CargarFormularios() Else MsgBox("Alguna de las bases de datos seleccionada no es correcta. Por favor revise su configuración", MsgBoxStyle.Exclamation + vbOKOnly, "Error de acceso") CargarFormularioConfiguracion() End If Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub CargarFormularios() Const strNombre_Funcion As String = "CargarFormularios" Try frmListadoClientes.MdiParent = Me frmListadoClientes.Show() CargarFiltrosToolStripComboBox(cbxCamposC, frmListadoClientes.DataGridClientes) frmListadoClientes.Ajustar() frmListadoIncidencias.MdiParent = Me frmListadoIncidencias.Show() CargarFiltrosToolStripComboBox(cbxCamposI, frmListadoIncidencias.DataGridIncidencias) frmListadoIncidencias.Ajustar() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub HabilitarBotonesIncidencias() Const strNombre_Funcion As String = "HabilitarBotonesIncidencias" Try If frmListadoIncidencias.DataGridIncidencias.Rows.Count > 0 Then frmListadoIncidencias.DataGridIncidencias.Rows(0).Selected = True btnModificarI.Enabled = True btnEliminarI.Enabled = True btnImprimir.Enabled = True Else btnModificarI.Enabled = False btnEliminarI.Enabled = False btnImprimir.Enabled = False End If Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub HabilitarBotonesClientes() Const strNombre_Funcion As String = "HabilitarBotonesClientes" Try If frmListadoClientes.DataGridClientes.Rows.Count > 0 Then frmListadoClientes.DataGridClientes.Rows(0).Selected = True btnModificarC.Enabled = True If gv_blnDBLocal Then btnEliminarC.Enabled = True Else btnEliminarC.Enabled = False End If Else btnModificarC.Enabled = False btnEliminarC.Enabled = False End If Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub EstablecerFiltrosEstados() Const strNombre_Funcion As String = "EstablecerFiltrosEstados" Try chbAbierta.Checked = gv_blnAbierta chbEnproceso.Checked = gv_blnEnproceso chbTerminada.Checked = gv_blnTerminada chbAvisado.Checked = gv_blnAvisado chbCerrada.Checked = gv_blnCerrada chbEngarantia.Checked = gv_blnEngarantia Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub GuardarFiltrosEstados() Const strNombre_Funcion As String = "GuardarFiltrosEstados" Try gv_blnAbierta = chbAbierta.Checked gv_blnEnproceso = chbEnproceso.Checked gv_blnTerminada = chbTerminada.Checked gv_blnAvisado = chbAvisado.Checked gv_blnCerrada = chbCerrada.Checked gv_blnEngarantia = chbEngarantia.Checked Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub Incidencias_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNueva.Click, btnModificarI.Click, btnEliminarI.Click, btnImprimir.Click, btnQuitarI.Click, btnActualizarI.Click Const strNombre_Funcion As String = "Incidencias_Click" Dim objBoton As ToolStripButton Dim blnResultado As Boolean Dim lngIncidencia As Long Try objBoton = sender Select Case objBoton.Name Case btnNueva.Name blnResultado = frmFichaIncidencia.blnCargarIncidencia() If blnResultado Then frmFichaIncidencia.ShowDialog() End If ActualizarIncidencias() Case btnModificarI.Name blnResultado = frmFichaIncidencia.blnCargarIncidencia(frmListadoIncidencias.LineaSeleccionada) If blnResultado Then frmFichaIncidencia.ShowDialog() End If ActualizarIncidencias() Case btnEliminarI.Name lngIncidencia = frmListadoIncidencias.DataGridIncidencias.SelectedRows(0).Cells(gc_strLP_I_Incidencia).Value If MsgBox("¿Estas seguro de eliminar la incidencia " & lngIncidencia & "?" & vbCrLf & _ "No se podrán volver a recuperar los datos asociados a esta incidencia", MsgBoxStyle.Question + MsgBoxStyle.OkCancel, "Eliminar incidencia") = MsgBoxResult.Ok Then If Not Inci_EliminarIncidencia(lngIncidencia) Then MsgBox("Ha ocurrido un error durante la eliminacion de la incidencia. Por favor, intentelo de nuevo", MsgBoxStyle.Critical, "Eliminar incidencia") End If End If ActualizarIncidencias() Case btnImprimir.Name lngIncidencia = frmListadoIncidencias.DataGridIncidencias.SelectedRows(0).Cells(gc_strLP_I_Incidencia).Value If frmImprimirIncidencia.CargarFormulario(lngIncidencia, gv_lngTipoImpresoIncidencia) Then frmImprimirIncidencia.ShowDialog() Else MsgBox("Ha ocurrido un error al cargar la impresion", MsgBoxStyle.Critical, "Imprimir incidencia") End If Case btnBuscarI.Name AplicarFiltroIncidencias() Case btnQuitarI.Name txtFiltroI.Text = "" cbxCamposI.SelectedItem = Nothing AplicarFiltroIncidencias() Case btnActualizarI.Name ActualizarIncidencias() End Select Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub Clientes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNuevo.Click, btnModificarC.Click, btnEliminarC.Click, btnQuitarC.Click, btnActualizarC.Click Const strNombre_Funcion As String = "Clientes_Click" Dim objBoton As ToolStripButton Dim blnResultado As Boolean Dim objCliente As clsCliente Try objBoton = sender Select Case objBoton.Name Case btnNuevo.Name objCliente = New clsCliente blnResultado = frmFichaCliente.blnCargarCliente(objCliente) If blnResultado Then frmFichaCliente.ShowDialog() End If ActualizarClientes() Case btnModificarC.Name objCliente = New clsCliente(frmListadoClientes.LineaSeleccionada) blnResultado = frmFichaCliente.blnCargarCliente(objCliente) If blnResultado Then frmFichaCliente.ShowDialog() End If ActualizarClientes() Case btnEliminarC.Name objCliente = New clsCliente(frmListadoClientes.LineaSeleccionada) If MsgBox("¿Estas seguro de eliminar el cliente " & objCliente.Id & "-" & objCliente.NombreFiscal & "?" & vbCrLf & _ "No se podrán volver a recuperar los datos asociados a este cliente", MsgBoxStyle.Question + MsgBoxStyle.OkCancel, "Eliminar cliente") = MsgBoxResult.Ok Then If Not Clie_EliminarCliente(objCliente.Id) Then MsgBox("Ha ocurrido un error durante la eliminacion del cliente. Por favor, intentelo de nuevo", MsgBoxStyle.Critical, "Eliminar cliente") End If End If ActualizarClientes() Case btnBuscarC.Name AplicarFiltroClientes() Case btnQuitarC.Name txtFiltroC.Text = "" cbxCamposC.SelectedItem = Nothing AplicarFiltroClientes() Case btnActualizarC.Name ActualizarClientes() End Select Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub Estados_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbAbierta.CheckedChanged, chbEnproceso.CheckedChanged, _ chbTerminada.CheckedChanged, chbAvisado.CheckedChanged, _ chbCerrada.CheckedChanged, chbEngarantia.CheckedChanged Const strNombre_Funcion As String = "Estados_CheckedChanged" Try AplicarFiltroIncidencias() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub txtFiltros_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltroC.KeyDown, txtFiltroI.KeyDown Const strNombre_Funcion As String = "txtFiltros_KeyDown" Dim objTexto As ToolStripTextBox Try If e.KeyCode = Keys.Enter Then objTexto = sender Select Case objTexto.Name Case txtFiltroC.Name AplicarFiltroClientes() Case txtFiltroI.Name AplicarFiltroIncidencias() End Select End If Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub AplicarFiltroIncidencias() Const strNombre_Funcion As String = "AplicarFiltroIncidencias" Dim strFiltro As String Try strFiltro = Config_strGenerarFiltroDataGridView(txtFiltroI.Text, cbxCamposI.SelectedItem) GenerarFiltroEstados(strFiltro) frmListadoIncidencias.AplicarFiltro(strFiltro) HabilitarBotonesIncidencias() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub AplicarFiltroClientes() Const strNombre_Funcion As String = "AplicarFiltroClientes" Dim strFiltro As String Try strFiltro = Config_strGenerarFiltroDataGridView(txtFiltroC.Text, cbxCamposC.SelectedItem) frmListadoClientes.AplicarFiltro(strFiltro) HabilitarBotonesClientes() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub '<CABECERA>----------------------------------------------- 'Nombre...........: GenerarFiltroEstados 'Descripcion......: Filtra el DataGridView por los estados de las incidencias 'Fecha............: 24/05/2014 '<FIN CABECERA>------------------------------------------- Public Sub GenerarFiltroEstados(ByRef strFiltro As String) Const strNombre_Funcion As String = "GenerarFiltroEstados" Dim blnError As Boolean Dim strFiltroOriginal As String = "" Dim strListaEstados As String = "" Dim strFiltroLocal As String = "" Try strFiltroOriginal = strFiltro strListaEstados = "0" If chbAbierta.Checked Then If strListaEstados <> "" Then strListaEstados &= ", " End If strListaEstados = "1" End If If chbEnproceso.Checked Then If strListaEstados <> "" Then strListaEstados &= ", " End If strListaEstados &= "2" End If If chbTerminada.Checked Then If strListaEstados <> "" Then strListaEstados &= ", " End If strListaEstados &= "3" End If If chbAvisado.Checked Then If strListaEstados <> "" Then strListaEstados &= ", " End If strListaEstados &= "4" End If If chbCerrada.Checked Then If strListaEstados <> "" Then strListaEstados &= ", " End If strListaEstados &= "5" End If If chbEngarantia.Checked Then If strListaEstados <> "" Then strListaEstados &= ", " End If strListaEstados &= "6" End If If strListaEstados <> "" Then strFiltroLocal = gc_strDB_C_Estado & " IN (" & strListaEstados & ")" If strFiltro <> "" Then strFiltroLocal = " AND " & strFiltroLocal End If strFiltro &= strFiltroLocal End If Catch ex As Exception blnError = True AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) Finally If blnError Then strFiltro = strFiltroOriginal End If End Try End Sub '<CABECERA>----------------------------------------------- 'Descripcion......: Configura el cambio de pestaña 'Fecha............: 27/05/2014 '<FIN CABECERA>------------------------------------------- Private Sub tbcPrincipal_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbcPrincipal.SelectedIndexChanged Const strNombre_Funcion As String = "tbcPrincipal_SelectedIndexChanged" Try Select Case tbcPrincipal.SelectedTab.Name Case tbpIncidencias.Name frmListadoIncidencias.BringToFront() frmListadoIncidencias.Ajustar() Case tbpClientes.Name frmListadoClientes.BringToFront() frmListadoClientes.Ajustar() End Select Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub ActualizarClientes() Const strNombre_Funcion As String = "ActualizarClientes" Dim strFiltro As String Try strFiltro = Config_strGenerarFiltroDataGridView(txtFiltroC.Text, cbxCamposC.SelectedItem) frmListadoClientes.Actualizar(strFiltro) HabilitarBotonesClientes() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub ActualizarIncidencias() Const strNombre_Funcion As String = "ActualizarIncidencias" Dim strFiltro As String Try strFiltro = Config_strGenerarFiltroDataGridView(txtFiltroI.Text, cbxCamposI.SelectedItem) GenerarFiltroEstados(strFiltro) frmListadoIncidencias.Actualizar(strFiltro) HabilitarBotonesIncidencias() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub btnConfigC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfigI.Click, btnConfigC.Click Const strNombre_Funcion As String = "btnConfigC_Click" Try CargarFormularioConfiguracion() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub CargarFormularioConfiguracion() Const strNombre_Funcion As String = "CargarFormularioConfiguracion" Try frmCondiguracion.ShowDialog() If frmCondiguracion.Guardado Then CargarAplicacion() End If Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub Acercade_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAcercade1.Click, btnAcercade2.Click Const strNombre_Funcion As String = "Acercade_Click" Try frmAcercade.ShowDialog() Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub frmPrincipal_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing Const strNombre_Funcion As String = "frmPrincipal_FormClosing" Try CerrarAplicacion Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Private Sub CerrarAplicacion() Const strNombre_Funcion As String = "CerrarAplicacion" Dim objForm As Windows.Forms.Form Try GuardarFiltrosEstados() GuardarConfiguracionINI() For Each objForm In Me.MdiChildren objForm.Close() Next tspLin1.Items(0).Enabled = True tspLin2.Items(0).Enabled = True tspLin2.Items(1).Enabled = True tspLin2.Items(2).Enabled = True Catch ex As Exception AddLog(ex.Message, mc_strNombre_Modulo, strNombre_Funcion) End Try End Sub Public ReadOnly Property FiltroClientes As String Get Return Config_strGenerarFiltroDataGridView(txtFiltroC.Text, cbxCamposC.SelectedItem) End Get End Property Public ReadOnly Property FiltroIncidencias As String Get Return Config_strGenerarFiltroDataGridView(txtFiltroI.Text, cbxCamposI.SelectedItem) End Get End Property End Class
Imports SPIN.PropTrading.Common_VB Public Class ServiceDetail Public Property ServiceName As String Public Property MachineName As String Public Property ServiceResponsibilities As String Public Property ServiceStatus As Enums.ServiceStatus Public Property LastChecked As Date End Class
Imports BVSoftware.Bvc5.Core Imports System.Collections.ObjectModel Partial Class BVAdmin_Content_CustomUrl Inherits BaseAdminPage Protected Sub Page_PreInit1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.PageTitle = "Custom Urls" Me.CurrentTab = AdminTabType.Content ValidateCurrentUserHasPermission(Membership.SystemPermissions.ContentView) End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then GridView1.PageSize = WebAppSettings.RowsPerPage LoadUrls() End If End Sub Private Sub LoadUrls() Me.GridView1.DataBind() End Sub Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting msg.ClearMessage() If Membership.UserAccount.DoesUserHavePermission(SessionManager.GetCurrentUserId, Membership.SystemPermissions.ContentEdit) = True Then Dim bvin As String = CType(GridView1.DataKeys(e.RowIndex).Value, String) If Content.CustomUrl.Delete(bvin) = False Then Me.msg.ShowWarning("Unable to delete this custom Url.") End If End If LoadUrls() e.Cancel = True End Sub Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing Dim bvin As String = CType(GridView1.DataKeys(e.NewEditIndex).Value, String) Response.Redirect("CustomUrl_Edit.aspx?id=" & bvin) End Sub Protected Sub ObjectDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) Handles ObjectDataSource1.Selecting If e.ExecutingSelectCount Then e.InputParameters("rowCount") = HttpContext.Current.Items("RowCount") Me.lblResults.Text = CInt(HttpContext.Current.Items("RowCount")) & " Urls found" HttpContext.Current.Items("RowCount") = Nothing End If End Sub Protected Sub ObjectDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs) Handles ObjectDataSource1.Selected If e.OutputParameters("RowCount") IsNot Nothing Then HttpContext.Current.Items("RowCount") = e.OutputParameters("RowCount") End If End Sub End Class
Imports System.Collections.ObjectModel Module modVar Public PathWebsite As String Public AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\GyroGits\" & My.Application.Info.Title Public Delimiter As String = ">><<" Structure Coll Public Shared Alphabet As ObservableCollection(Of DataStructure.Alphabet) = New ObservableCollection(Of DataStructure.Alphabet) End Structure End Module
Imports Windows.Devices.Enumeration Imports Windows.Devices.Spi Imports System.Collections.Generic ''' <summary> ''' Defines an interface to the MCP3008 ADC via the SPI interface. ''' </summary> Public Class MCP3008_CLASS Implements IDisposable Private SPI_SETTINGS As SpiConnectionSettings = Nothing Private SPI_DEVICE As SpiDevice = Nothing ''' <summary> ''' Gets the settings used on the SPI interface to communicate to the MCP3008. ''' </summary> ''' <returns></returns> Public Property Settings As SpiConnectionSettings Get Return SPI_SETTINGS End Get Private Set(ByVal value As SpiConnectionSettings) SPI_SETTINGS = value End Set End Property ''' <summary> ''' Gets the underlying SpiDevice instance used by this instance ''' of Windows.Devices.Sensors.Mcp3008. ''' </summary> ''' <returns></returns> Public Property Device As SpiDevice Get If SPI_DEVICE Is Nothing Then 'Throw New NotInitializedException() End If Return SPI_DEVICE End Get Private Set(ByVal value As SpiDevice) SPI_DEVICE = value End Set End Property Public Enum InputConfiguration SingleEnded = 1 Differential = 0 End Enum Public Class Channel Public Property CH_ID As Integer Public Property InputConfiguration As InputConfiguration Friend Sub New(ByVal selection As InputConfiguration, ByVal id As Integer) CH_ID = id InputConfiguration = selection End Sub End Class ''' <summary> ''' Initializes a new instance of the Windows.Devices.Sensors.Mcp3008 with ''' the specified Chip Select Line (0 or 1). ''' </summary> ''' <param name="chipSelectLine">The Chip Select Line the MCP3008 ''' is physically connected to. This value is either 0 or 1 on the ''' Raspberry Pi.</param> Public Sub New(ByVal chipSelectLine As Integer) Settings = New SpiConnectionSettings(chipSelectLine) With {.ClockFrequency = 1000000, .Mode = SpiMode.Mode0, .SharingMode = SpiSharingMode.Exclusive} End Sub ''' <summary> ''' Initializes a new instance of the Windows.Devices.Sensors.Mcp3008 with ''' the specified SpiConnectionSettings. ''' </summary> ''' <param name="settings">An instance of SpiConnectionSettings that specifies ''' the parameters of the SPI connection for the MCP3008.</param> Public Sub New(ByVal settings As SpiConnectionSettings) Me.Settings = settings End Sub ''' <summary> ''' Defines all available channels on the MCP3008. ''' </summary> Class Channels ''' <summary> ''' A list of all available channels on the MCP3008. Single0 is the first item ''' followed by Single1, Single 2 and so on. Differential0 is the 8th item followed by ''' Differential1, Differential2 and so on. ''' </summary> Public ReadOnly All As IList(Of Channel) = New List(Of Channel)(New Channel() {Single0, Single1, Single2, Single3, Single4, Single5, Single6, Single7, Differential0, Differential1, Differential2, Differential3, Differential4, Differential5, Differential6, Differential7}) ''' <summary> ''' Specifies the single Channel 0 (pin 1). ''' </summary> Public Shared Single0 As Channel = New Channel(InputConfiguration.SingleEnded, 0) ''' <summary> ''' Specifies the single Channel 1 (pin 2). ''' </summary> Public Shared Single1 As Channel = New Channel(InputConfiguration.SingleEnded, 1) ''' <summary> ''' Specifies the single Channel 2 (pin 3). ''' </summary> Public Shared Single2 As Channel = New Channel(InputConfiguration.SingleEnded, 2) ''' <summary> ''' Specifies the single Channel 3 (pin 4). ''' </summary> Public Shared Single3 As Channel = New Channel(InputConfiguration.SingleEnded, 3) ''' <summary> ''' Specifies the single Channel 4 (pin 5). ''' </summary> Public Shared Single4 As Channel = New Channel(InputConfiguration.SingleEnded, 4) ''' <summary> ''' Specifies the single Channel 5 (pin 6). ''' </summary> Public Shared Single5 As Channel = New Channel(InputConfiguration.SingleEnded, 5) ''' <summary> ''' Specifies the single Channel6 (pin 7). ''' </summary> Public Shared Single6 As Channel = New Channel(InputConfiguration.SingleEnded, 6) ''' <summary> ''' Specifies the single Channel 7 (pin 8). ''' </summary> Public Shared Single7 As Channel = New Channel(InputConfiguration.SingleEnded, 7) ''' <summary> ''' Specifies the differential Channel 0 (+) and Channel 1 (-) ''' </summary> Public Shared Differential0 As Channel = New Channel(InputConfiguration.Differential, 0) ''' <summary> ''' Specifies the differential Channel 0 (-) and Channel 1 (+) ''' </summary> Public Shared Differential1 As Channel = New Channel(InputConfiguration.Differential, 1) ''' <summary> ''' Specifies the differential Channel 2 (+) and Channel 3 (-) ''' </summary> Public Shared Differential2 As Channel = New Channel(InputConfiguration.Differential, 2) ''' <summary> ''' Specifies the differential Channel 2 (-) and Channel 3 (+) ''' </summary> Public Shared Differential3 As Channel = New Channel(InputConfiguration.Differential, 3) ''' <summary> ''' Specifies the differential Channel 4 (+) and Channel 5 (-) ''' </summary> Public Shared Differential4 As Channel = New Channel(InputConfiguration.Differential, 4) ''' <summary> ''' Specifies the differential Channel 4 (-) and Channel 5 (+) ''' </summary> Public Shared Differential5 As Channel = New Channel(InputConfiguration.Differential, 5) ''' <summary> ''' Specifies the differential Channel 6 (+) and Channel 7 (-) ''' </summary> Public Shared Differential6 As Channel = New Channel(InputConfiguration.Differential, 6) ''' <summary> ''' Specifies the differential Channel 6 (-) and Channel 7 (+) ''' </summary> Public Shared Differential7 As Channel = New Channel(InputConfiguration.Differential, 7) End Class ''' <summary> ''' Initializes the MCP3008 by establishing a connection on the SPI interface. ''' </summary> ''' <returns></returns> Public Async Function Initialize() As Task If SPI_DEVICE Is Nothing Then Dim selector As String = SpiDevice.GetDeviceSelector(String.Format("SPI{0}", Me.Settings.ChipSelectLine)) Dim deviceInfo = Await DeviceInformation.FindAllAsync(selector) SPI_DEVICE = Await SpiDevice.FromIdAsync(deviceInfo(0).Id, Settings) Else 'Throw New AlreadyInitializedException() End If End Function ''' <summary> ''' Reads an integer value from the specified port. The value of the port can ''' be a number from0 to 7. ''' </summary> ''' <param name="channel">An integer specifying the port to read from. This is ''' a value from 0 to 7.</param> ''' <returns>The integer value of the specified port.</returns> Public Function Read(ByVal channel As Channel) As MCP3008_READING Dim returnValue As MCP3008_READING = New MCP3008_READING(0) If SPI_DEVICE IsNot Nothing Then Dim readBuffer As Byte() = New Byte(2) {} Dim writeBuffer As Byte() = New Byte(2) {channel.InputConfiguration, channel.CH_ID + 8 << 4, &H0} SPI_DEVICE.TransferFullDuplex(writeBuffer, readBuffer) 'returnValue.RAW_VALUE = (readBuffer(2) + (readBuffer(1) * 255)) - 255 returnValue.RAW_VALUE = Convert.ToInt32(BitConverter.ToString(readBuffer, 0).Replace("-", ""), 16) 'returnValue.RAW_VALUE = readBuffer(2) + ((readBuffer(1) & &H3) << 8) 'returnValue.RAW_VALUE = (readBuffer(0) & &H1) << 9 Or readBuffer(1) << 1 Or readBuffer(2) >> 7 Else 'Throw New NotInitializedException() End If Return returnValue End Function Public Sub Dispose() Implements IDisposable.Dispose If SPI_DEVICE IsNot Nothing Then SPI_DEVICE.Dispose() End If End Sub End Class
Namespace AW.Types Partial Public Class Vendor Implements ITitledObject, INotEditableOncePersistent Public Shared Function FieldOrder() As String Return "Accountnumber, NAME, CreditRating, PreferredVendorStatus, " + "ActiveFlag,purchasingWebServiceURL, ModifiedDate, Products" 'spacing and casing for testing End Function #Region "Name" Public Property mappedName As String Friend myName As TextString Public ReadOnly Property Name As TextString Get myName = If(myName, New TextString(mappedName, Sub(v) mappedName = v)) Return myName End Get End Property Public Sub AboutName(a As FieldAbout, Name As TextString) Select Case a.TypeCode Case AboutTypeCodes.Name Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region #Region "AccountNumber" Public Property mappedAccountNumber As String Friend myAccountNumber As TextString Public ReadOnly Property AccountNumber As TextString Get myAccountNumber = If(myAccountNumber, New TextString(mappedAccountNumber, Sub(v) mappedAccountNumber = v)) Return myAccountNumber End Get End Property Public Sub AboutAccountNumber(a As FieldAbout, AccountNumber As TextString) Select Case a.TypeCode Case AboutTypeCodes.Name Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region #Region "CreditRating" Public Property mappedCreditRating As Byte Friend myCreditRating As WholeNumber Public ReadOnly Property CreditRating As WholeNumber Get myCreditRating = If(myCreditRating, New WholeNumber(mappedCreditRating, Sub(v) mappedCreditRating = CType(v, Byte))) Return myCreditRating End Get End Property Public Sub AboutCreditRating(a As FieldAbout, CreditRating As WholeNumber) Select Case a.TypeCode Case AboutTypeCodes.Name Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region #Region "PreferredVendorStatus" Public Property mappedPreferredVendorStatus As Boolean Friend myPreferredVendorStatus As Logical Public ReadOnly Property PreferredVendorStatus As Logical Get myPreferredVendorStatus = If(myPreferredVendorStatus, New Logical(mappedPreferredVendorStatus, Sub(v) mappedPreferredVendorStatus = v)) Return myPreferredVendorStatus End Get End Property Public Sub AboutPreferredVendorStatus(a As FieldAbout, PreferredVendorStatus As Logical) Select Case a.TypeCode Case AboutTypeCodes.Name Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region #Region "ActiveFlag" Public Property mappedActiveFlag As Boolean Friend myActiveFlag As Logical Public ReadOnly Property ActiveFlag As Logical Get myActiveFlag = If(myActiveFlag, New Logical(mappedActiveFlag, Sub(v) mappedActiveFlag = v)) Return myActiveFlag End Get End Property Public Sub AboutActiveFlag(a As FieldAbout, ActiveFlag As Logical) Select Case a.TypeCode Case AboutTypeCodes.Name Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region #Region "PurchasingWebServiceURL" Public Property mappedPurchasingWebServiceURL As String Friend myPurchasingWebServiceURL As TextString Public ReadOnly Property PurchasingWebServiceURL As TextString Get myPurchasingWebServiceURL = If(myPurchasingWebServiceURL, New TextString(mappedPurchasingWebServiceURL, Sub(v) mappedPurchasingWebServiceURL = v)) Return myPurchasingWebServiceURL End Get End Property Public Sub AboutPurchasingWebServiceURL(a As FieldAbout, PurchasingWebServiceURL As TextString) Select Case a.TypeCode Case AboutTypeCodes.Name Case AboutTypeCodes.Usable Case AboutTypeCodes.Valid Case Else End Select End Sub #End Region #Region "Products (Collection)" Public Overridable Property mappedProducts As ICollection(Of ProductVendor) = New List(Of ProductVendor)() Private myProducts As InternalCollection Public ReadOnly Property Products As InternalCollection Get myProducts = If(myProducts, New InternalCollection(Of ProductVendor)(mappedProducts)) Return myProducts End Get End Property Public Sub AboutProducts(a As FieldAbout) Select Case a.TypeCode Case AboutTypeCodes.Name a.Name = "Product - Order Info" End Select End Sub #End Region #Region "ModifiedDate" Public Property mappedModifiedDate As Date Friend myModifiedDate As TimeStamp Public ReadOnly Property ModifiedDate As TimeStamp Get myModifiedDate = If(myModifiedDate, New TimeStamp(mappedModifiedDate, Sub(v) mappedModifiedDate = v)) Return myModifiedDate End Get End Property Public Sub AboutModifiedDate(a As FieldAbout) Select Case a.TypeCode Case AboutTypeCodes.Usable a.Usable = False End Select End Sub #End Region '<Hidden> Public Property BusinessEntityID() As Integer Public Function Title() As Title Implements ITitledObject.Title Return New Title(ToString()) End Function Public Overrides Function ToString() As String Return mappedName End Function End Class End Namespace
Imports Autodesk.AutoCAD.ApplicationServices Imports Autodesk.AutoCAD.DatabaseServices Imports Autodesk.AutoCAD.EditorInput Imports Autodesk.AutoCAD.Runtime Imports Autodesk.Civil.DatabaseServices <Assembly: CommandClass(GetType(Autodesk.CivilizedDevelopment.SurfacePropertiesDemo))> Namespace Autodesk.CivilizedDevelopment Public Class SurfacePropertiesDemo Inherits SimpleDrawingCommand <CommandMethod("CDS_TinSurfacePropertiesDemo")> _ Public Sub CDS_TinSurfacePropertiesDemo() Dim surfaceId As ObjectId = promptForTinSurface() If ObjectId.Null = surfaceId Then write(vbLf & "No TIN Surface object was selected.") ' We don't have a surface; we can't continue. Return End If Using tr As Transaction = startTransaction() Dim surface As TinSurface = TryCast(surfaceId.GetObject(OpenMode.ForRead), TinSurface) write(vbLf & "Information for TIN Surface: " + surface.Name) writeGeneralProperites(surface.GetGeneralProperties()) writeTerrainProperties(surface.GetTerrainProperties()) writeTinSurfaceProperties(surface.GetTinProperties()) End Using End Sub ''' <summary> ''' Prompts the user to select a TIN Surface, and returns its ''' ObjectId. ''' </summary> ''' <returns>The method returns the ObjectId of the selected ''' surface, or ObjectId.Null if no surface was selected (usually, ''' because the user canceled the operation). ''' </returns> Private Function promptForTinSurface() As ObjectId Dim options As New PromptEntityOptions( vbLf & "Select a TIN Surface: ") options.SetRejectMessage( vbLf & "The selected object is not a TIN Surface.") options.AddAllowedClass(GetType(TinSurface), True) Dim result As PromptEntityResult = _editor.GetEntity(options) If result.Status = PromptStatus.OK Then ' Everything is cool; we return the selected ' surface ObjectId. Return result.ObjectId End If Return ObjectId.Null ' Indicating error. End Function ''' <summary> ''' Displays general properties that apply to all Surface objects. ''' </summary> ''' <param name="props">General properties from surface.</param> Private Sub writeGeneralProperites(p As GeneralSurfaceProperties) write(vbLf & "General Properties:") write(vbLf & "-------------------") write(vbLf & "Min X: " & Convert.ToString(p.MinimumCoordinateX)) write(vbLf & "Min Y: " & Convert.ToString(p.MinimumCoordinateY)) write(vbLf & "Min Z: " & Convert.ToString(p.MinimumElevation)) write(vbLf & "Max X: " & Convert.ToString(p.MaximumCoordinateX)) write(vbLf & "Max Y: " & Convert.ToString(p.MaximumCoordinateY)) write(vbLf & "Max Z: " & Convert.ToString(p.MaximumElevation)) write(vbLf & "Mean Elevation: " & Convert.ToString(p.MeanElevation)) write(vbLf & "Number of Points: " & Convert.ToString(p.NumberOfPoints)) write(vbLf & "--") End Sub Private Sub writeTerrainProperties(p As TerrainSurfaceProperties) write(vbLf & "Terrain Surface Properties:") write(vbLf & "---------------------------") write(vbLf & "Min Grade/Slope: " & Convert.ToString(p.MinimumGradeOrSlope)) write(vbLf & "Max Grade/Slope: " & Convert.ToString(p.MaximumGradeOrSlope)) write(vbLf & "Mean Grade/Slope: " & Convert.ToString(p.MeanGradeOrSlope)) write(vbLf & "2D Area: " & Convert.ToString(p.SurfaceArea2D)) write(vbLf & "3D Area: " & Convert.ToString(p.SurfaceArea3D)) write(vbLf & "--") End Sub Private Sub writeTinSurfaceProperties(p As TinSurfaceProperties) write(vbLf & "TIN Surface Properties:") write(vbLf & "-----------------------") write(vbLf & "Min Triangle Area: " & Convert.ToString(p.MinimumTriangleArea)) write(vbLf & "Min Triangle Length: " & Convert.ToString(p.MinimumTriangleLength)) write(vbLf & "Max Triangle Area: " & Convert.ToString(p.MaximumTriangleArea)) write(vbLf & "Max Triangle Length: " & Convert.ToString(p.MaximumTriangleLength)) write(vbLf & "Number of Triangles: " & Convert.ToString(p.NumberOfTriangles)) write(vbLf & "--") End Sub End Class End Namespace
Imports System.Collections.Generic Imports System Imports BudgeteerObjects Imports Microsoft.VisualStudio.TestTools.UnitTesting Imports BudgeteerBusiness '''<summary> '''This is a test class for AccountTest and is intended '''to contain all AccountTest Unit Tests '''</summary> <TestClass()> _ Public Class BankAccountTest Private testContextInstance As TestContext '''<summary> '''Gets or sets the test context which provides '''information about and functionality for the current test run. '''</summary> Public Property TestContext() As TestContext Get Return testContextInstance End Get Set(ByVal value As TestContext) testContextInstance = value End Set End Property #Region "Additional test attributes" ' 'You can use the following additional attributes as you write your tests: ' 'Use ClassInitialize to run code before running the first test in the class '<ClassInitialize()> _ 'Public Shared Sub MyClassInitialize(ByVal testContext As TestContext) 'End Sub ' 'Use ClassCleanup to run code after all tests in a class have run '<ClassCleanup()> _ 'Public Shared Sub MyClassCleanup() 'End Sub ' 'Use TestInitialize to run code before running each test '<TestInitialize()> _ 'Public Sub MyTestInitialize() 'End Sub ' 'Use TestCleanup to run code after each test has run '<TestCleanup()> _ 'Public Sub MyTestCleanup() 'End Sub ' #End Region '''<summary> '''A test for GetAccounts '''</summary> <TestMethod()> _ Public Sub GetAccountsTest() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim userID As String = "JTurner" Dim expected As List(Of BudgeteerObjects.BankAccount) = Nothing Dim actual As List(Of BudgeteerObjects.BankAccount) actual = target.GetAccounts(userID) Assert.AreNotEqual(expected, actual) userID = "NonExistingAcc" actual = target.GetAccounts(userID) Assert.AreEqual(expected, actual) End Sub '''<summary> '''A test for GetAccounts '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "A null user ID was inappropriately allowed")> _ Public Sub GetAccountsUserIDNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim userID As String = Nothing Dim expected As List(Of BudgeteerObjects.BankAccount) = Nothing Dim actual As List(Of BudgeteerObjects.BankAccount) actual = target.GetAccounts(userID) End Sub '''<summary> '''A test for GetAccount '''</summary> <TestMethod()> _ Public Sub GetAccountTest() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim accountID As Int64 = 1 Dim expected As BudgeteerObjects.BankAccount = Nothing Dim actual As BudgeteerObjects.BankAccount actual = target.GetAccount(accountID) Assert.AreNotEqual(expected, actual) accountID = -1 actual = target.GetAccount(accountID) Assert.AreEqual(expected, actual) End Sub '''<summary> '''A test for GetAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "A null account ID was inappropriately allowed")> _ Public Sub GetAccountAccountIDNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim accountID As Int64 = Nothing Dim expected As BudgeteerObjects.BankAccount = Nothing Dim actual As BudgeteerObjects.BankAccount actual = target.GetAccount(accountID) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ Public Sub AddAccountTest() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expected As Integer = 1 Dim actual As Integer account.Number = Nothing account.Name = Date.UtcNow.ToString & " " & Date.UtcNow.Millisecond.ToString account.Type = Nothing account.Balance = Nothing account.Active = "Y" account.UserID = "JTurner" actual = target.AddAccount(account) Assert.IsTrue(actual > 0) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account of Nothing was inappropriately allowed")> _ Public Sub AddAccountAccountNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = Nothing target.AddAccount(account) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account Name exeeceded the maximum length of characters allowed")> _ Public Sub AddAccountAccountNumberMaxLen() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount account.Number = "12345" account.Name = "Test Account" account.Type = "Test Type" account.Balance = 0.0 account.Active = "Y" account.UserID = "JTurner" target.AddAccount(account) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "A null Account Name was inappropriately allowed")> _ Public Sub AddAccountAccountNameNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount account.Number = "" account.Name = Nothing account.Type = "Test Type" account.Balance = 0.0 account.Active = "Y" account.UserID = "JTurner" target.AddAccount(account) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account Name exeeceded the maximum length of characters allowed")> _ Public Sub AddAccountAccountNameMaxLen() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount account.Number = "" account.Name = "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." account.Type = "Test Type" account.Balance = 0.0 account.Active = "Y" account.UserID = "JTurner" target.AddAccount(account) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account Name exeeceded the maximum length of characters allowed")> _ Public Sub AddAccountAccountTypeMaxLen() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount account.Number = "" account.Name = "Account Name" account.Type = "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." account.Balance = 0.0 account.Active = "Y" account.UserID = "JTurner" target.AddAccount(account) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account Type not 'Y' or 'N'")> _ Public Sub AddAccountActiveStatusNotYN() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount account.Number = "" account.Name = "Account Name" account.Type = "Account Type" account.Balance = 0.0 account.Active = "A" 'Not Y or N account.UserID = "JTurner" target.AddAccount(account) End Sub '''<summary> '''A test for AddAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account User ID set to nothing")> _ Public Sub AddAccountUserIDNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount account.Number = "" account.Name = "Account Name" account.Type = "Account Type" account.Balance = 0.0 account.Active = "Y" account.UserID = Nothing target.AddAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ Public Sub AccountUpdateTest() Dim target As BankAccount = New BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expecting As Integer = 1 Dim actual As Integer account.AccountID = 1 account.Number = "6115" account.Name = Date.UtcNow.ToString & " " & Date.UtcNow.Millisecond.ToString account.Type = "Credit Card" account.Balance = 4.22 account.Active = "Y" account.UserID = "JTurner" actual = target.UpdateAccount(account) Assert.AreEqual(expecting, actual) expecting = 0 actual = target.UpdateAccount(account) Assert.AreEqual(expecting, actual) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "An account of nothing was inappropriately allowed")> _ Public Sub AccountUpdateAccountNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = Nothing Dim actual As Integer actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "An accountID of nothing was inappropriately allowed")> _ Public Sub AccountUpdateAccountIDNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim actual As Integer account.AccountID = Nothing account.Number = "6115" account.Name = "Amazon CC" account.Type = "Credit Card" account.Balance = 4.22 account.Active = "Y" account.UserID = "JTurner" actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "An accountID of nothing was inappropriately allowed")> _ Public Sub AccountUpdateAccountNumberMaxLen() Dim target As BankAccount = New BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expecting As Integer = 0 Dim actual As Integer account.AccountID = 1 account.Number = "61157" 'Account Number should only be 4 digits account.Name = "Amazon CC" account.Type = "Credit Card" account.Balance = 4.22 account.Active = "Y" account.UserID = "JTurner" actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "A blank account name was inappropriately allowed")> _ Public Sub AccountUpdateAccountNameNothing() Dim target As BankAccount = New BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expecting As Integer = 0 Dim actual As Integer account.AccountID = 1 account.Number = "6115" account.Name = Nothing account.Type = "Credit Card" account.Balance = 4.22 account.Active = "Y" account.UserID = "JTurner" actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account Name exeeceded the maximum length of characters allowed")> _ Public Sub AccountUpdateAccountNameMaxLen() Dim target As BankAccount = New BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expecting As Integer = 0 Dim actual As Integer account.AccountID = 1 account.Number = "6115" account.Name = "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." account.Type = "Credit Card" account.Balance = 4.22 account.Active = "Y" account.UserID = "JTurner" actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "Account Name exeeceded the maximum length of characters allowed")> _ Public Sub AccountUpdateAccountTypeMaxLen() Dim target As BankAccount = New BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expecting As Integer = 0 Dim actual As Integer account.AccountID = 1 account.Number = "6115" account.Name = "Amazon CC" account.Type = "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." & _ "THIS IS GOING TO BE AN ABNOXIOUSLY LONG STRING OF TEXT." account.Balance = 4.22 account.Active = "Y" account.UserID = "JTurner" actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for AccountUpdate '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "An active status other than Y or N was inappropriately allowed")> _ Public Sub AccountUpdateActiveStatusNotYN() Dim target As BankAccount = New BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expecting As Integer = 0 Dim actual As Integer account.AccountID = 1 account.Number = "6115" account.Name = "Amazon CC" account.Type = "Credit Card" account.Balance = 4.22 account.Active = Nothing 'Something other than Y or N account.UserID = "JTurner" actual = target.UpdateAccount(account) End Sub '''<summary> '''A test for DeleteAccount '''</summary> <TestMethod()> _ Public Sub DeleteAccountTest() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount Dim expected As Integer = 1 Dim actual As Integer account.Number = "1234" account.Name = Date.UtcNow.ToString & " " & Date.UtcNow.Millisecond.ToString account.Type = "Test Type" account.Balance = 0.0 account.Active = "Y" account.UserID = "JTurner" ' First add the account Dim accountID As Long = target.AddAccount(account) If accountID = 0 Then Assert.Fail() 'Couldn't add account End If actual = target.DeleteAccount(accountID) Assert.AreEqual(expected, actual) End Sub '''<summary> '''A test for DeleteAccount '''</summary> <TestMethod()> _ <ExpectedException(GetType(ArgumentException), "An account ID of nothing was inappropriately allowed")> _ Public Sub DeleteAccountAccountIDNothing() Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount Dim accountID As Long = Nothing Dim expected As Integer = 1 Dim actual As Integer actual = target.DeleteAccount(accountID) End Sub 'No longer a public function ''''<summary> ''''A test for AdjustBalance ''''</summary> '<TestMethod()> _ 'Public Sub AdjustBalancePositiveAmount() ' Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount ' Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount ' Dim amount As [Decimal] = New [Decimal](5.5) ' Dim expected As [Decimal] = New [Decimal](65.5) ' Dim actual As [Decimal] = New [Decimal] ' account.AccountID = 1 ' account.Number = "6115" ' account.Name = "Amazon CC" ' account.Type = "Credit Card" ' account.Balance = 60.0 ' account.Active = "Y" ' account.UserID = "JTurner" ' Using dTran As BudgeteerDAL.DistributedTransaction = New BudgeteerDAL.DistributedTransaction(Utils.ConnectionString) ' target.AdjustBalance(dTran, account, amount) ' End Using ' 'Re-Retrieve the account ' account = target.GetAccount(account.AccountID) ' actual = account.Balance ' Assert.AreEqual(expected, actual) 'End Sub 'No longer a public function ''''<summary> ''''A test for AdjustBalance ''''</summary> '<TestMethod()> _ 'Public Sub AdjustBalanceNegativeAmount() ' Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount ' Dim account As BudgeteerObjects.BankAccount = New BudgeteerObjects.BankAccount ' Dim amount As [Decimal] = New [Decimal](-5.5) ' Dim expected As [Decimal] = New [Decimal](54.5) ' Dim actual As [Decimal] = New [Decimal] ' account.AccountID = 1 ' account.Number = "6115" ' account.Name = "Amazon CC" ' account.Type = "Credit Card" ' account.Balance = 60.0 ' account.Active = "Y" ' account.UserID = "JTurner" ' target.AdjustBalance(account, amount) ' 'Re-Retrieve the account ' account = target.GetAccount(account.AccountID) ' actual = account.Balance ' Assert.AreEqual(expected, actual) 'End Sub 'No longer a public function ''''<summary> ''''A test for AdjustBalance ''''</summary> '<TestMethod()> _ '<ExpectedException(GetType(ArgumentException), "An empty account was inappropriately allowed")> _ ' Public Sub AdjustBalanceAccountNothing() ' Dim target As BudgeteerBusiness.BankAccount = New BudgeteerBusiness.BankAccount ' Dim account As BudgeteerObjects.BankAccount = Nothing ' Dim amount As [Decimal] = New [Decimal] ' target.AdjustBalance(account, amount) 'End Sub End Class
Module Database ' Database Private Const DATABASE_FILE = "Theatre.accdb" ' Database Connection Friend dbConnection As New OleDb.OleDbConnection ' Seating Data Adapter Friend dbSeatingDataAdapter As New OleDb.OleDbDataAdapter("SELECT * FROM seating", dbConnection) ' Seating Data Set Friend dbSeatingDataSet As New DataSet ' Performances Data Adapter Friend dbPerformancesDataAdapter As New OleDb.OleDbDataAdapter("SELECT * FROM performances", dbConnection) ' Performances Data Set Friend dbPerformancesDataSet As New DataSet Sub New() ' Connect to Database (Access File) dbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\" & DATABASE_FILE & ";Persist Security Info=False" ' Open Database dbConnection.Open() ' Fill Data Adapter dbSeatingDataSet.Clear() dbSeatingDataAdapter.Fill(dbSeatingDataSet) ' Fill Data Adapter dbPerformancesDataSet.Clear() dbPerformancesDataAdapter.Fill(dbPerformancesDataSet) End Sub ' Determine if seat taken or not Public Function isSeatAvailable(seatNumber As Integer, performanceDate As String) As Boolean Dim available As Boolean = True ' Query table with seat number & date ' Set Select Command dbSeatingDataAdapter.SelectCommand.CommandText = "SELECT * FROM seating WHERE seat_no = " & seatNumber & " AND perf_date = '" & performanceDate & "'" ' Clear Previous Data dbSeatingDataSet.Clear() ' Fill Data dbSeatingDataAdapter.Fill(dbSeatingDataSet) ' if record found If dbSeatingDataSet.Tables(0).Rows.Count = 1 Then ' Seat Taken available = False End If Return available End Function ' Filter DataSet to just the performence on the given date Public Sub filterPerformance(performanceDate As String) ' Query table with date ' Set Select Command dbPerformancesDataAdapter.SelectCommand.CommandText = "SELECT * FROM Performances WHERE perf_date = '" & performanceDate & "'" ' Clear Previous Data dbPerformancesDataSet.Clear() ' Fill Data dbPerformancesDataAdapter.Fill(dbPerformancesDataSet) End Sub End Module
Imports System.ComponentModel Imports System.Configuration Imports System.IO Namespace My Partial Class MySettings ''' <summary> ''' User configuration folder path on the current computer. ''' </summary> ''' <returns>The current user's user configuration folder path</returns> <Category("Local"), Browsable(True), DescriptionAttribute("User configuration folder path")> Public ReadOnly Property ConfigurationFolder() As String Get Dim config = ConfigurationManager. OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal) Return config.FilePath.Replace("\user.config", "") End Get End Property ''' <summary> ''' Determines if the current user's configuration folder exists ''' </summary> ''' <returns>True if folder exists, False if the folder does not exits</returns> <Category("Local"), Browsable(True), DescriptionAttribute("User configuration folder exists")> Public ReadOnly Property ConfigurationFolderExists() As Boolean Get Return Directory.Exists(ConfigurationFolder) End Get End Property ''' <summary> ''' Provides name of current user's configuration file name ''' </summary> ''' <returns></returns> <Category("Local"), Browsable(True), DescriptionAttribute("User configuration file name")> Public Function ConfigurationFile() As String Return Path.GetFileName(ConfigurationManager. OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath) End Function ''' <summary> ''' Get shared folder ''' </summary> ''' <returns>Shared folder path</returns> <Category("Local"), Browsable(True), DescriptionAttribute("Folder where common settings are stored")> Public ReadOnly Property SharedFolder() As String Get Return Path.Combine(Environment. GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyData") End Get End Property <Category("Local"), Browsable(True), DescriptionAttribute("Indicates common settings folder exists")> Public ReadOnly Property SharedFolderExists() As Boolean Get Return Directory.Exists(SharedFolder) End Get End Property <Category("Local"), Browsable(True), DescriptionAttribute("Indicates common file name")> Public ReadOnly Property CommonConfigurationFileName() As String Get Return Path.Combine(SharedFolder, "common.xml") End Get End Property <Category("Local"), Browsable(True), DescriptionAttribute("Indicates common settings file exists")> Public ReadOnly Property CommonFigurationFileExists() As Boolean Get Return File.Exists(CommonConfigurationFileName) End Get End Property Private _fileMap As ConfigurationFileMap Private _configuration As Configuration Private _fileName As String ''' <summary> ''' Get shared server name ''' </summary> ''' <returns>shared server name from common configuration file</returns> <Category("Shared"), Browsable(False)> Public ReadOnly Property GetServerName() As String Get Return _configuration.AppSettings.Settings("ServerName").Value End Get End Property ''' <summary> ''' Set shared server name to common configuration file ''' </summary> ''' <param name="pValue">Server name</param> <Category("Shared"), Browsable(False)> Public Sub SetServerName(pValue As String) _configuration.AppSettings.Settings("ServerName").Value = pValue _configuration.Save() End Sub <Category("Shared"), Browsable(True), DescriptionAttribute("Default server")> Public Property ServerInGrid() As String Get Return _configuration.AppSettings.Settings("ServerName").Value End Get Set _configuration.AppSettings.Settings("ServerName").Value = Value _configuration.Save() End Set End Property <Category("Shared"), Browsable(True), DescriptionAttribute("Default server")> Public Property DatabaseInGrid() As String Get Return _configuration.AppSettings.Settings("DefaultCatalog").Value End Get Set _configuration.AppSettings.Settings("DefaultCatalog").Value = Value _configuration.Save() End Set End Property ''' <summary> ''' Get default catalog ''' </summary> ''' <returns>Default catalog from common configuration file</returns> <Category("Shared"), Browsable(False)> Public ReadOnly Property GetDefaultCatalog() As String Get Return _configuration.AppSettings.Settings("DefaultCatalog").Value End Get End Property <Category("Shared"), Browsable(True), DescriptionAttribute("Default database")> Public ReadOnly Property Database() As String Get Return GetDefaultCatalog() End Get End Property <Category("Shared"), Browsable(True), DescriptionAttribute("Default server")> Public ReadOnly Property Server() As String Get Return GetServerName() End Get End Property ''' <summary> ''' Set default catalog to common configuration file ''' </summary> ''' <param name="pValue">Server name</param> <Category("Shared"), Browsable(True)> Public Sub SetDefaultCatalog(pValue As String) _configuration.AppSettings.Settings("DefaultCatalog").Value = pValue _configuration.Save() End Sub Public Sub New() _fileName = CommonConfigurationFileName _fileMap = New ConfigurationFileMap(_fileName) _configuration = ConfigurationManager.OpenMappedMachineConfiguration(_fileMap) End Sub End Class End Namespace
Public Class Form1 'this is now a git managed file Public Const MAX_MISSILES As Integer = 20 'this many missiles at one time Public Const MAX_SHIPS As Integer = 10 'this many ships at one time Public Structure missile_struct Dim img As Label 'the missile object Dim available As Boolean 'if true, the missile can be launched Dim shift_x As Integer 'the amount to shift left/right Dim shift_y As Integer 'the amount to shift up/down Dim speed As Integer 'how many pixels we want to move in our direction for each tick Dim angle As Integer 'the angle of missile: from 0 to 180, with 90 being straight up and 0 being to the right End Structure Public Structure ship_struct Dim img As Label 'the ship object Dim available As Boolean 'if true, the ship can be sent out Dim shift_x As Integer 'the amount to shift left/right Dim shift_y As Integer 'the amount to shift up/down Dim speed As Integer 'how many pixels we want to move in our direction for each tick End Structure 'Globals Public missiles() As missile_struct 'our array of missiles Public ships() As ship_struct 'our array of ships Public launcher_angle As Integer 'our current launcher angle Function random_int(ByVal lowerbound, ByVal upperbound) 'returns random number integer inclusive between lowerbound and upperbound Return (CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))) End Function Private Sub initialize_missiles() Dim i As Integer ReDim missiles(MAX_MISSILES) For i = 0 To MAX_MISSILES missiles(i).available = True 'all are available Next End Sub Private Sub initialize_ships() Dim i As Integer ReDim ships(MAX_SHIPS) For i = 0 To MAX_SHIPS ships(i).available = True 'all are available Next End Sub Private Sub tick_missile_move(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer_missile_move.Tick Dim i, j As Integer Dim img_mid_x, img_mid_y As Integer For i = 0 To MAX_MISSILES If missiles(i).available = False Then 'the missile is launched, move it missiles(i).img.Left += missiles(i).shift_x missiles(i).img.Top += missiles(i).shift_y Debug.Print(String.Format("mnum={0}, sx={1}, sy={2}", i, missiles(i).shift_x, missiles(i).shift_y)) Debug.Print(String.Format("mnum={0}, L={1}, T={2}", i, missiles(i).img.Left, missiles(i).img.Top)) 'if we are out of range of the form, then release the missile by setting its availability back to True If missiles(i).img.Left > Me.Width + missiles(i).img.Image.Width Or _ missiles(i).img.Left < (0 - missiles(i).img.Image.Width) Or _ missiles(i).img.Top < (0 - missiles(i).img.Image.Height) Then missiles(i).available = True missiles(i).img = Nothing End If End If Next 'now check to see if any missile has hit a ship For i = 0 To MAX_MISSILES If missiles(i).available = False Then 'the missile is launched, check it 'check each ship to see if we have hit that ship For j = 0 To MAX_SHIPS 'only check ships that are launched and only use missiles that are fired and not already blowed up If ships(j).available = False And missiles(i).available = False Then img_mid_x = missiles(i).img.Left + missiles(i).img.Size.Width / 2 img_mid_y = missiles(i).img.Top + missiles(i).img.Size.Height / 2 If img_mid_y > ships(j).img.Top And _ img_mid_y < ships(j).img.Top + ships(j).img.Size.Height Then If img_mid_x > ships(j).img.Left And _ img_mid_x < ships(j).img.Left + ships(j).img.Size.Width Then 'we have a hit Debug.Print(String.Format("hit at {0}:{1}", img_mid_x, img_mid_y)) 'blow up missile missiles(i).img.Visible = False missiles(i).available = True 'blow up ship ships(j).img.Visible = False ships(j).available = True 'now add to score? End If End If End If Next End If Next End Sub Private Sub create_missile(ByVal i As Integer) 'pass in the missile number to calculate for in the missile array 'make sure the angle and speed are already filled in for this array entry 'then this routine fills in the shift_ values and creates the missile object and marks it for launch Dim xx, yy As Integer 'note that xx and yy are passed in ByRef so they will be changed to the new values when this routine returns calculate_coordinates(missiles(i).angle, missiles(i).speed, xx, yy) 'xx and yy have the shift values, put them in to the array missiles(i).shift_x = xx missiles(i).shift_y = -yy 'we are going up 'create missile object label and position it for launch on our form missiles(i).img = New Label missiles(i).img.Parent = PictureBox1 missiles(i).img.Image = My.Resources.fireball missiles(i).img.Width = My.Resources.fireball.Width missiles(i).img.Height = My.Resources.fireball.Height missiles(i).img.BackColor = Color.Transparent 'launch the missile from the bottom middle of the 'PictureBox1' object missiles(i).img.Left = Me.PictureBox1.Left + (Me.PictureBox1.Size.Width / 2) missiles(i).img.Top = Me.PictureBox1.Bottom - missiles(i).img.Size.Height missiles(i).img.Visible = True 'now mark the missile as launched missiles(i).available = False End Sub Private Sub create_ship(ByVal i As Integer) 'pass in the ship number to create 'make sure speed is already filled in for this array entry 'create ship object label and position it on our form ships(i).img = New Label ships(i).img.Parent = PictureBox1 ships(i).img.Image = My.Resources.Spaceship1 ships(i).img.Width = My.Resources.Spaceship1.Width ships(i).img.Height = My.Resources.Spaceship1.Height ships(i).img.BackColor = Color.Transparent 'position the ship at far left of screen ships(i).img.Left = Me.PictureBox1.Left - ships(i).img.Size.Width 'create the ship in the full picturebox1 frame but less than 2 image heights from the bottom ships(i).img.Top = Me.Top + random_int(1, PictureBox1.Height - 2 * ships(i).img.Size.Height) ships(i).speed = random_int(10, 30) ships(i).shift_x = ships(i).speed ships(i).shift_y = 0 ships(i).img.Visible = True 'now mark the ship as launched ships(i).available = False End Sub Private Sub fire_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) fire_missile() End Sub Private Sub fire_missile() 'launch a new missile Dim i As Integer 'find first available missile slot and use it, then return For i = 0 To MAX_MISSILES If missiles(i).available Then 'use this slot for the missile 'launch with current speed setting from slider and with current launcher_angle missiles(i).speed = Me.speed_slider.Value missiles(i).angle = launcher_angle create_missile(i) Return End If Next End Sub Private Sub initialize_form(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Randomize() launcher_angle = 0 initialize_missiles() initialize_ships() 'PictureBox1.BackColor = Color.Transparent 'PictureBox1.BackColor = Color.FromArgb(0, 0, 0, 0) End Sub Private Sub tick_create_ship(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer_create_ship.Tick Dim i As Integer 'randomly create a new ship '10% chance to create a new ship If random_int(1, 10) = 1 Then 'find first available ship slot and use it, then return For i = 0 To MAX_SHIPS If ships(i).available Then 'use this slot for the ship create_ship(i) Return End If Next End If End Sub Private Sub tick_ship_move(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer_ship_move.Tick Dim i As Integer For i = 0 To MAX_SHIPS If ships(i).available = False Then 'the ship is launched, move it ships(i).img.Left += ships(i).shift_x ships(i).img.Top += ships(i).shift_y 'if we are out of range of the form, then release the ship by setting its availability back to True If ships(i).img.Left > Me.Width + ships(i).img.Image.Width Or _ ships(i).img.Left < (0 - ships(i).img.Image.Width) Or _ ships(i).img.Top < (0 - ships(i).img.Image.Height) Then ships(i).available = True ships(i).img = Nothing End If End If Next End Sub Private Sub show_crosshairs() Dim height As Integer = 150 Dim new_x, new_y As Integer 'get new coordinates from launcher_angle and height calculate_coordinates(launcher_angle, height, new_x, new_y) launcher_crosshairs.Left = (launcher_silo.Left + launcher_silo.Size.Width / 2) + new_x - launcher_crosshairs.Size.Width / 2 launcher_crosshairs.Top = (launcher_silo.Top - launcher_silo.Size.Height / 2) - new_y - launcher_crosshairs.Size.Height / 2 End Sub Private Sub calculate_coordinates(ByVal angle As Integer, ByVal hyp As Integer, ByRef x As Integer, ByRef y As Integer) Dim a As Double 'adjacent Dim o As Double 'opposite Dim angle_ratio As Double 'tan of angle 'To calculate for new coordinates for movement: ' 'for a right angled triangle, the following methods apply: ' ' * ' h * * ' * * o = opposite ' * A * ' *************** ' a = adjacent ' ' h = hypotenuse ' o = opposite side ' a = adjacent side ' A = angle between adjacent and hypotenuse ' ' From trigonometry, the Tan of the angle is the ratio between the opposite and the adjacent ' e.g. tan A = o / a ' ' We know the angle.. it ranges from ' 0 (going directly to the right) ' to 90 (going straight up) ' to 180 (going directly to the left) ' We also know the value of h, the hypotenuse ' Knowing angle and hyp, we can calculate for o and a and then add them to the label position to ' get the new coordinate 'First, get the ratio of opposite to adjacent using trig 'convert angle to radians first (multiply by PI and divide by 180.0) 'Always keep the ratio positive (Abs). We will determine direction later in this routine angle_ratio = Math.Abs(Math.Tan(angle * Math.PI / 180.0)) 'now solve for a and o using Pythagoras and substitution 'h*h = o*o + a*a, therefore a = Math.Sqrt(h*h)/o*o). 'Substitute for o in equation in order to isolate a 'o = angle_ratio * a ' a = Math.Sqrt((hyp * hyp) / (1 + (angle_ratio * angle_ratio))) o = angle_ratio * a 'now we have our new lengths, make sure direction is correct If angle > 90 Then 'we are angled to the left a = -a Else a = a End If 'returns coordinate values as integers back to the calling routine 'round the doubles to integers to be as accurate as possible x = Math.Round(a) y = Math.Round(o) End Sub Private Sub slider_key_down(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles launcher_trackbar.KeyDown If e.KeyData = Keys.Space Then fire_missile() End If End Sub Private Sub event_launcher_trackbar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles launcher_trackbar.ValueChanged If launcher_trackbar.Value <> launcher_angle Then launcher_angle = launcher_trackbar.Value show_crosshairs() End If End Sub End Class
'***************************************************** '* Copyright 2017, SportingApp, all rights reserved. * '* Author: Shih Peiting * '* mailto: sportingapp@gmail.com * '***************************************************** Imports System.Drawing Imports System.Windows.Forms Namespace SaWindows.Forms Partial Public Class SaTabControlSU Inherits TabControl Private _tabHeaderVisible As Boolean = True Private _tabAddButton As Boolean = False Public Property TabHeaderVisible As Boolean Get Return _tabHeaderVisible End Get Set(value As Boolean) If value Then MyBase.Appearance = TabAppearance.Normal MyBase.ItemSize = New Size(58, 18) MyBase.SizeMode = TabSizeMode.Normal Else MyBase.Appearance = TabAppearance.FlatButtons MyBase.ItemSize = New Size(0, 1) MyBase.SizeMode = TabSizeMode.Fixed End If _tabHeaderVisible = value End Set End Property Public Overloads Property Appearance As TabAppearance Get Return MyBase.Appearance End Get Set(value As TabAppearance) If TabHeaderVisible Then MyBase.Appearance = value End If End Set End Property Public Overloads Property SizeMode As TabSizeMode Get Return MyBase.SizeMode End Get Set(value As TabSizeMode) If TabHeaderVisible Then MyBase.SizeMode = value End If End Set End Property Public Overloads Property ItemSize As Size Get Return MyBase.ItemSize End Get Set(value As Size) If TabHeaderVisible Then MyBase.ItemSize = value End If End Set End Property 'Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs) ' MyBase.OnDrawItem(e) ' Dim tabTextArea As RectangleF = Rectangle.Empty ' For nIndex As Integer = 0 To Me.TabCount - 1 ' tabTextArea = Me.GetTabRect(nIndex) ' If (nIndex <> Me.SelectedIndex) Then ' Using bmp As Bitmap = New Bitmap(My.Resources.if_Gnome_Window_Close_32_55183) ' e.Graphics.DrawImage(bmp, tabTextArea.X + tabTextArea.Width - 16, 5, 13, 13) ' End Using ' Else ' Dim br As LinearGradientBrush = New LinearGradientBrush(tabTextArea, SystemColors.ControlLightLight, SystemColors.Control, LinearGradientMode.Vertical) ' e.Graphics.FillRectangle(br, tabTextArea) ' Using bmp As Bitmap = New Bitmap(My.Resources.if_Gnome_Window_Close_32_55183) ' e.Graphics.DrawImage(bmp, tabTextArea.X + tabTextArea.Width - 16, 5, 13, 13) ' End Using ' br.Dispose() ' End If ' Dim str As String = Me.TabPages(nIndex).Text ' Dim strFormat As StringFormat = New StringFormat() ' strFormat.Alignment = StringAlignment.Center ' Using brush As SolidBrush = New SolidBrush(Me.TabPages(nIndex).ForeColor) ' e.Graphics.DrawString(str, Me.Font, brush, tabTextArea, strFormat) ' End Using ' Next 'End Sub 'Private _addTabPage As TabPage 'Public Property TabAddButtonVisible As Boolean ' Get ' Return _tabAddButton ' End Get ' Set(value As Boolean) ' _tabAddButton = value ' If value Then ' _addTabPage = New TabPage("+") ' Me.TabPages.Add(_addTabPage) ' AddHandler Me.TabIndexChanged, AddressOf AddNewTab ' Else ' If _addTabPage IsNot Nothing Then ' Me.TabPages.Remove(_addTabPage) ' _addTabPage = Nothing ' End If ' End If ' End Set 'End Property 'Public Delegate Sub BeforeAddNewTabEventHandler(ByVal sender As Object, ByVal e As EventArgs) 'Public Delegate Sub AfterAddNewTabEventHandler(ByVal sender As Object, ByVal e As EventArgs) 'Public Event BeforeTabAddButtonClick As BeforeAddNewTabEventHandler 'Public Event AfterTabAddButtonClick As AfterAddNewTabEventHandler 'Private Sub AddNewTab(ByVal sender As Object, ByVal e As EventArgs) ' If _tabAddButton Then ' If Me.TabCount > 0 Then ' RaiseEvent BeforeTabAddButtonClick(sender, e) ' Me.TabPages.Insert(Me.TabCount - 1, "NewTab") ' RaiseEvent AfterTabAddButtonClick(sender, e) ' End If ' End If 'End Sub End Class End Namespace
Imports System.Data Imports System.Data.SqlClient Imports System.Xml Imports System.IO Public Class NWDSASqlFactory : Inherits NWDSAAbstractFactory Private m_conSQL As New SqlConnection() Protected Overrides Sub Finalize() If Not (m_conSQL.State = ConnectionState.Closed) Or _ Not (m_conSQL.State = ConnectionState.Broken) Then m_conSQL.Close() End If MyBase.Finalize() End Sub Public Overrides Function ExecuteDataReader(ByRef Request As NWDSARequest) As NWDSADataReader ' Returns a NWDSADataReader object, which wraps an object of type IDataReader ' Uses SQL Server .NET data provider, hence the wrapped object is a SqlDataReader object ' A SqlDataReader object is a read-only, forward-only data stream. ' NOTE: DataReaders won't be used in queries that perform transactions. Dim sConnectStr As String Dim cmdSQL As New SqlCommand() Dim prmSQL As SqlParameter Dim oParam As NWDSARequest.Parameter Dim colSQLParams As SqlParameterCollection Dim drSQL As SqlDataReader Dim oDataReaderSQL As New NWDSASqlDataReader() Try m_conSQL.ConnectionString = g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role) ' open connection, and begin to set properties of command m_conSQL.Open() cmdSQL.Connection = m_conSQL cmdSQL.CommandText = Request.Command cmdSQL.CommandType = Request.CommandType ' add parameters if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmSQL = cmdSQL.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If drSQL = cmdSQL.ExecuteReader() oDataReaderSQL.ReturnedDataReader = drSQL Return oDataReaderSQL Catch exSQL As SqlException Debug.WriteLine(exSQL.Message) Request.Exception = exSQL Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex Finally End Try End Function Public Overrides Function ExecuteDataSet(ByRef Request As NWDSARequest) As NWDSADataSet ' Returns a NWDSADataSet object, which wraps an object of type DataSet ' Uses SQL Server .NET data provider if a data provider is necessary ' - hence uses a SqlDataAdapter to fill the DataSet Dim sConnectStr As String Dim conSQL As New SqlConnection() Dim cmdSQL As New SqlCommand() Dim prmSQL As SqlParameter Dim oParam As NWDSARequest.Parameter Dim colSQLParams As SqlParameterCollection Dim daSQL As SqlDataAdapter Dim oDataSetSQL As New NWDSASqlDataSet() Dim tranSQL As SqlTransaction Try conSQL.ConnectionString = g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role) ' open connection, and begin to set properties of command conSQL.Open() cmdSQL.Connection = conSQL cmdSQL.CommandText = Request.Command cmdSQL.CommandType = Request.CommandType ' add parameters if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmSQL = cmdSQL.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If If Request.Transactional Then tranSQL = conSQL.BeginTransaction() End If daSQL = New SqlDataAdapter(cmdSQL) ' allow generic naming - NewDataSet daSQL.Fill(oDataSetSQL.ReturnedDataSet) Return oDataSetSQL Catch exSQL As SqlException Debug.WriteLine(exSQL.Message) Request.Exception = exSQL If Request.Transactional Then tranSQL.Rollback() End If Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex If Request.Transactional Then tranSQL.Rollback() End If Finally If Request.Transactional Then tranSQL.Commit() End If If conSQL.State = ConnectionState.Open Then conSQL.Close() End If End Try End Function Public Overrides Function ExecuteXMLDocument(ByRef Request As NWDSARequest) As NWDSAXmlDoc Dim sConnectStr As String Dim cmdSQL As New SqlCommand() Dim prmSQL As SqlParameter Dim oParam As NWDSARequest.Parameter Dim colSQLParams As SqlParameterCollection Dim daSQL As SqlDataAdapter Dim dsSQL As New DataSet() Dim xmlDoc As New XmlDocument() Dim oXmlDocSQL As New NWDSASqlXmlDoc() Dim tranSQL As SqlTransaction Try m_conSQL = New SqlConnection(g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role)) ' open connection, and begin to set properties of command m_conSQL.Open() cmdSQL.Connection = m_conSQL cmdSQL.CommandText = Request.Command cmdSQL.CommandType = Request.CommandType ' add parameters if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmSQL = cmdSQL.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If If Request.Transactional Then tranSQL = m_conSQL.BeginTransaction() End If daSQL = New SqlDataAdapter(cmdSQL) daSQL.Fill(dsSQL) xmlDoc.LoadXml(dsSQL.GetXml) oXmlDocSQL.ReturnedXmlDoc = xmlDoc Return oXmlDocSQL Catch exSQL As SqlException Debug.WriteLine(exSQL.Message) Request.Exception = exSQL tranSQL.Rollback() Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex tranSQL.Rollback() Finally If Request.Transactional Then tranSQL.Commit() End If End Try End Function Public Overrides Function ExecuteXmlReader(ByRef Request As NWDSARequest) As NWDSAXmlReader Dim sConnectStr As String Dim cmdSQL As New SqlCommand() Dim prmSQL As SqlParameter Dim oParam As NWDSARequest.Parameter Dim colSQLParams As SqlParameterCollection Dim daSQL As SqlDataAdapter Dim dsSQL As New DataSet() Dim xmlDoc As New XmlDocument() Dim xmlReader As XmlReader Dim oXmlReaderSQL As New NWDSASqlXmlReader() Dim tranSQL As SqlTransaction Dim dsDataSet As New DataSet() Try m_conSQL = New SqlConnection(g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role)) ' open connection, and begin to set properties of command m_conSQL.Open() cmdSQL.Connection = m_conSQL cmdSQL.CommandText = Request.Command cmdSQL.CommandType = Request.CommandType ' add parameters if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmSQL = cmdSQL.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If If Request.Transactional Then tranSQL = m_conSQL.BeginTransaction() End If daSQL = New SqlDataAdapter(cmdSQL) daSQL.Fill(dsDataSet) Dim strmStream As New MemoryStream() dsDataSet.WriteXml(strmStream, XmlWriteMode.IgnoreSchema) dsDataSet.WriteXml("output.xml", XmlWriteMode.IgnoreSchema) 'xmlReader = New XmlTextReader(strmStream) xmlReader = New XmlTextReader("output.xml") oXmlReaderSQL.ReturnedXmlReader = xmlReader Return oXmlReaderSQL Catch exSQL As SqlException Debug.WriteLine(exSQL.Message) Request.Exception = exSQL tranSQL.Rollback() Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex tranSQL.Rollback() Finally If Request.Transactional Then tranSQL.Commit() End If End Try End Function Public Overrides Function ExecuteScalar(ByRef Request As NWDSARequest) As NWDSAScalar Dim sConnectStr As String Dim cmdSQL As New SqlCommand() Dim prmSQL As SqlParameter Dim oParam As NWDSARequest.Parameter Dim colSQLParams As SqlParameterCollection Dim iRows As Integer Dim oReturnScalar As New NWDSASqlScalar() Dim tranSQL As SqlTransaction Try m_conSQL.ConnectionString = g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role) ' attempt to open sql connection and exec command m_conSQL.Open() cmdSQL.Connection = m_conSQL cmdSQL.CommandText = Request.Command cmdSQL.CommandType = Request.CommandType ' add parameters if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmSQL = cmdSQL.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If If Request.Transactional Then tranSQL = m_conSQL.BeginTransaction() End If Dim drSQL As SqlDataReader drSQL = cmdSQL.ExecuteReader() drSQL.Read() oReturnScalar.ReturnedScalar = drSQL.GetValue(0) Return oReturnScalar Catch exSQL As SqlException Debug.WriteLine(exSQL.Message) Request.Exception = exSQL tranSQL.Rollback() Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex tranSQL.Rollback() Finally If Request.Transactional Then tranSQL.Commit() End If End Try End Function Public Overrides Function ExecuteNonQuery(ByRef Request As NWDSARequest) As NWDSANonQuery Dim sConnectStr As String Dim cmdSQL As New SqlCommand() Dim prmSQL As SqlParameter Dim oParam As NWDSARequest.Parameter Dim colSQLParams As SqlParameterCollection Dim iRows As Integer Dim oReturnNonQuery As New NWDSASqlNonQuery() Dim tranSQL As SqlTransaction Try m_conSQL.ConnectionString = g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role) ' attempt to open sql connection and exec command m_conSQL.Open() cmdSQL.Connection = m_conSQL cmdSQL.CommandText = Request.Command cmdSQL.CommandType = Request.CommandType ' add parameters if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmSQL = cmdSQL.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If If Request.Transactional Then tranSQL = m_conSQL.BeginTransaction() End If oReturnNonQuery.AffectedRecords = cmdSQL.ExecuteNonQuery() Return oReturnNonQuery Catch exSQL As SqlException Debug.WriteLine(exSQL.Message) Request.Exception = exSQL tranSQL.Rollback() Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex tranSQL.Rollback() Finally If Request.Transactional Then tranSQL.Commit() End If End Try End Function End Class
Option Strict Off Option Explicit On Friend Class Motion ' motion components ' properties ' Move: total movement (ft) ' Surge: move in surge direction (ft) ' Sway: move in sway direction (ft) ' Yaw: yaw movement (rad) Private msngSurge As Double Private msngSway As Double Private msngYaw As Double Public ReadOnly Property Move() As Double Get Move = System.Math.Sqrt(msngSurge ^ 2 + msngSway ^ 2) End Get End Property Public Property Surge() As Double Get Surge = msngSurge End Get Set(ByVal Value As Double) msngSurge = Value End Set End Property Public Property Sway() As Double Get Sway = msngSway End Get Set(ByVal Value As Double) msngSway = Value End Set End Property Public Property Yaw() As Double Get Yaw = msngYaw End Get Set(ByVal Value As Double) msngYaw = Value End Set End Property End Class
''' <summary> ''' Provides the properties to build sql paramater object ''' </summary> <Serializable()> _ Public Class DESQLParameter #Region "Class Level Fields" ''' <summary> ''' Paramater Name ''' </summary> Private _paramName As String ''' <summary> ''' Parameter Value ''' </summary> Private _paramValue As Object ''' <summary> ''' Parameter Type ''' </summary> Private _paramType As SqlDbType ''' <summary> ''' Parameter Direction ''' </summary> Private _paramDirection As ParameterDirection #End Region #Region "Properties" ''' <summary> ''' Gets or sets the name of the parameter ''' </summary> ''' <value>The name of the param.</value> Public Property ParamName() As String Get Return _paramName End Get Set(ByVal value As String) _paramName = value End Set End Property ''' <summary> ''' Gets or sets the parameter value ''' </summary> ''' <value>The param value.</value> Public Property ParamValue() As Object Get Return _paramValue End Get Set(ByVal value As Object) _paramValue = value End Set End Property ''' <summary> ''' Gets or sets the type of the parameter (SqlDbType) ''' </summary> ''' <value>The type of the param.</value> Public Property ParamType() As SqlDbType Get Return _paramType End Get Set(ByVal value As SqlDbType) _paramType = value End Set End Property ''' <summary> ''' Gets or sets the parameter direction of type Data.ParameterDirection ''' </summary> ''' <value>The param direction.</value> Public Property ParamDirection() As ParameterDirection Get Return _paramDirection End Get Set(ByVal value As ParameterDirection) _paramDirection = value End Set End Property #End Region End Class
Imports System.IO Imports System.Net Imports System.Text Public Class Ftp Sub New(ByVal server As String, ByVal user As String, ByVal pass As String) Me.ftpServer = server Me.ftpUser = user Me.ftpPass = pass End Sub Private ftpServer As String Private ftpUser As String Private ftpPass As String Public Function DirectoryExists(ByVal fldr As String) As Boolean Dim retVal As Boolean = True Try Dim request = DirectCast(WebRequest.Create(Me.ftpServer & fldr & "/"), FtpWebRequest) request.Credentials = New NetworkCredential(Me.ftpUser, Me.ftpPass) request.Method = WebRequestMethods.Ftp.ListDirectory Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) ' directory exists End Using Catch ex As WebException Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse) If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then retVal = False End If End Try Return retVal End Function Public Function CreateDirectory(ByVal fldr As String) As Boolean Dim retVal As Boolean = True Try Dim request As Net.FtpWebRequest = CType(FtpWebRequest.Create(Me.ftpServer & fldr), FtpWebRequest) request.Credentials = New NetworkCredential(Me.ftpUser, Me.ftpPass) request.Method = WebRequestMethods.Ftp.MakeDirectory Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) ' Folder created End Using Catch ex As WebException Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse) If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then retVal = False End If End Try Return retVal End Function Public Function CopyFile(ByVal srcFile As String, ByVal destFile As String) As Boolean Dim retVal As Boolean = True Try Dim fi As New FileInfo(srcFile) ' Get the object used to communicate with the server. Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Me.ftpServer & destFile), FtpWebRequest) request.Method = WebRequestMethods.Ftp.UploadFile ' This example assumes the FTP site uses anonymous logon. request.Credentials = New NetworkCredential(Me.ftpUser, Me.ftpPass) ' Copy the contents of the file to the request stream. Dim sourceStream As New StreamReader(srcFile) Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()) sourceStream.Close() request.ContentLength = fileContents.Length Dim requestStream As Stream = request.GetRequestStream() requestStream.Write(fileContents, 0, fileContents.Length) requestStream.Close() Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) response.Close() Catch ex As Exception retVal = False End Try Return retVal End Function Public Function FileExists(ByVal fileName As String) As Boolean Dim retVal As Boolean = True Try Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Me.ftpServer & fileName), FtpWebRequest) request.Credentials = New NetworkCredential(Me.ftpUser, Me.ftpPass) request.Method = WebRequestMethods.Ftp.GetFileSize Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) Catch ex As WebException Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse) If FtpStatusCode.ActionNotTakenFileUnavailable = response.StatusCode Then retVal = False End If End Try Return retVal End Function Public Function DeleteFile(ByVal fileName As String) As Boolean Dim retVal As Boolean = True Try Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Me.ftpServer & fileName), FtpWebRequest) request.Credentials = New NetworkCredential(Me.ftpUser, Me.ftpPass) request.Method = WebRequestMethods.Ftp.DeleteFile Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) Catch ex As WebException Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse) If FtpStatusCode.ActionNotTakenFileUnavailable = response.StatusCode Then retVal = False End If End Try Return retVal End Function Public Function RenameFile(ByVal srcFile As String, ByVal destFile As String) As Boolean Dim retVal As Boolean = True Try Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Me.ftpServer & srcFile), FtpWebRequest) request.Credentials = New NetworkCredential(Me.ftpUser, Me.ftpPass) request.Method = WebRequestMethods.Ftp.Rename request.RenameTo = destFile Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) Catch ex As WebException Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse) If FtpStatusCode.ActionNotTakenFileUnavailable = response.StatusCode Then retVal = False End If End Try Return retVal End Function End Class
Imports Route4MeSDKLibrary.Route4MeSDK Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes Namespace Route4MeSDKTest.Examples Partial Public NotInheritable Class Route4MeExamples ''' <summary> ''' The example refers to the process of creating ''' an optimization with round trip option. ''' </summary> Public Sub SingleDriverRoundTrip() ' Create the manager with the api key Dim route4Me = New Route4MeManager(ActualApiKey) ' Prepare the addresses Dim addresses As Address() = New Address() {New Address() With { .AddressString = "754 5th Ave New York, NY 10019", .[Alias] = "Bergdorf Goodman", .IsDepot = True, .Latitude = 40.7636197, .Longitude = -73.9744388, .Time = 0 }, New Address() With { .AddressString = "717 5th Ave New York, NY 10022", .[Alias] = "Giorgio Armani", .Latitude = 40.7669692, .Longitude = -73.9693864, .Time = 0 }, New Address() With { .AddressString = "888 Madison Ave New York, NY 10014", .[Alias] = "Ralph Lauren Women's and Home", .Latitude = 40.7715154, .Longitude = -73.9669241, .Time = 0 }, New Address() With { .AddressString = "1011 Madison Ave New York, NY 10075", .[Alias] = "Yigal Azrou'l", .Latitude = 40.7772129, .Longitude = -73.9669, .Time = 0 }, New Address() With { .AddressString = "440 Columbus Ave New York, NY 10024", .[Alias] = "Frank Stella Clothier", .Latitude = 40.7808364, .Longitude = -73.9732729, .Time = 0 }, New Address() With { .AddressString = "324 Columbus Ave #1 New York, NY 10023", .[Alias] = "Liana", .Latitude = 40.7803123, .Longitude = -73.9793079, .Time = 0 }, New Address() With { .AddressString = "110 W End Ave New York, NY 10023", .[Alias] = "Toga Bike Shop", .Latitude = 40.7753077, .Longitude = -73.9861529, .Time = 0 }, New Address() With { .AddressString = "555 W 57th St New York, NY 10019", .[Alias] = "BMW of Manhattan", .Latitude = 40.7718005, .Longitude = -73.9897716, .Time = 0 }, New Address() With { .AddressString = "57 W 57th St New York, NY 10019", .[Alias] = "Verizon Wireless", .Latitude = 40.7558695, .Longitude = -73.9862019, .Time = 0 }} ' Set parameters Dim parameters = New RouteParameters() With { .AlgorithmType = AlgorithmType.TSP, .RouteName = "Single Driver Round Trip", .RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)), .RouteTime = 60 * 60 * 7, .RouteMaxDuration = 86400, .VehicleCapacity = 1, .VehicleMaxDistanceMI = 10000, .Optimize = Optimize.Time.GetEnumDescription(), .DistanceUnit = DistanceUnit.KM.GetEnumDescription(), .DeviceType = DeviceType.Web.GetEnumDescription(), .TravelMode = TravelMode.Driving.GetEnumDescription() } Dim optimizationParameters = New OptimizationParameters() With { .Addresses = addresses, .Parameters = parameters } ' Run the query Dim errorString As String = Nothing Dim dataObject As DataObject = route4Me.RunOptimization( optimizationParameters, errorString) OptimizationsToRemove = New List(Of String)() From { If(dataObject?.OptimizationProblemId, Nothing) } PrintExampleOptimizationResult(dataObject, errorString) RemoveTestOptimizations() End Sub End Class End Namespace
' *********************************************************************** ' Author : Elektro ' Modified : 03-May-2015 ' *********************************************************************** ' <copyright file="ElektroCheckBox.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Option Statements " Option Explicit On Option Strict On Option Infer Off #End Region #Region " Imports " Imports System.Drawing.Drawing2D #End Region Namespace UserControls ''' <summary> ''' An extended <see cref="CheckBox"/> control. ''' </summary> Public NotInheritable Class ElektroCheckBox : Inherits CheckBox #Region " Properties " ''' <summary> ''' Gets or sets the color of the box. ''' </summary> ''' <value>The color of the box.</value> Public Property BoxColor As Color = CheckBox.DefaultBackColor ''' <summary> ''' Gets or sets the color of the tick. ''' </summary> ''' <value>The color of the tick.</value> Public Property TickColor As Color = CheckBox.DefaultForeColor ''' <summary> ''' Gets or sets the color of the border. ''' </summary> ''' <value>The color of the border.</value> Public Property BorderColor As Color = SystemColors.ControlLight #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="ElektroCheckBox"/> class. ''' </summary> Public Sub New() Me.SuspendLayout() Me.SetStyle(ControlStyles.DoubleBuffer, True) Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True) Me.SetStyle(ControlStyles.ResizeRedraw, True) Me.SetStyle(ControlStyles.UserPaint, True) Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True) Me.ResumeLayout(performLayout:=False) End Sub #End Region #Region " Events " ''' <summary> ''' Raises the <see cref="E:Control.Paint"/> event. ''' </summary> ''' <param name="e">A <see cref="T:Forms.PaintEventArgs"/> that contains the event data.</param> Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) MyBase.OnPaint(e) Me.DrawCheckBox(e.Graphics, rect:=Me.GetBoxRectangle, drawCheckHot:=False, checkState:=Me.CheckState) End Sub #End Region #Region " Private Methods" ''' <summary> ''' Draws the parts of the CheckBox. ''' </summary> ''' <param name="g">The drawing surface.</param> ''' <param name="rect">The drawing rectangle.</param> ''' <param name="drawCheckHot">If set to <c>true</c> draws a check hot icon.</param> ''' <param name="checkState">The checkbox state.</param> Private Sub DrawCheckBox(ByVal g As Graphics, ByVal rect As Rectangle, ByVal drawCheckHot As Boolean, ByVal checkState As CheckState) Me.DrawCheckBackground(g, rect) If drawCheckHot Then Me.DrawCheckHot(g, rect) End If Me.DrawTick(g, rect, checkState) End Sub ''' <summary> ''' Draws the parts of the CheckBox. ''' </summary> ''' <param name="g">The drawing surface.</param> ''' <param name="rect">The drawing rectangle.</param> Private Sub DrawCheckBackground(ByVal g As Graphics, ByVal rect As Rectangle) Using fillBrush As New SolidBrush(Me.BoxColor) ' New LinearGradientBrush(rect, SystemColors.ControlLightLight, SystemColors.ControlDark, LinearGradientMode.ForwardDiagonal) ' fillBrush.SetSigmaBellShape(0, 0.5F) Using borderPen As New Pen(Me.BorderColor, 1) g.FillRectangle(fillBrush, rect) g.DrawRectangle(borderPen, rect) End Using End Using End Sub Private Sub DrawCheckHot(ByVal g As Graphics, ByVal rect As Rectangle) Dim fillBrush As LinearGradientBrush Dim hotPen As Pen fillBrush = New LinearGradientBrush(rect, SystemColors.ControlLight, SystemColors.ControlDark, LinearGradientMode.ForwardDiagonal) Dim relativeIntensities As Single() = {0.0F, 0.7F, 1.0F} Dim relativePositions As Single() = {0.0F, 0.5F, 1.0F} Dim blend As New Blend blend.Factors = relativeIntensities blend.Positions = relativePositions fillBrush.Blend = blend hotPen = New Pen(fillBrush, 1) Dim rect1 As New Rectangle(rect.X + 1, rect.Y + 1, rect.Width - 2, rect.Height - 2) Dim rect2 As New Rectangle(rect.X + 2, rect.Y + 2, rect.Width - 4, rect.Height - 4) g.DrawRectangles(hotPen, New Rectangle() {rect1, rect2}) fillBrush.Dispose() hotPen.Dispose() End Sub ''' <summary> ''' Draws the checkbox tick. ''' </summary> ''' <param name="g">The drawing surface.</param> ''' <param name="rect">The box rectangle.</param> ''' <param name="checkState">The checkbox state.</param> Private Sub DrawTick(ByVal g As Graphics, ByVal rect As Rectangle, ByVal checkState As CheckState) Select Case checkState Case checkState.Checked Dim scaleFactor As Single = Convert.ToSingle(rect.Width / 12.0) Dim points As PointF() = New PointF() { New PointF(rect.X + scaleFactor * 3, rect.Y + scaleFactor * 5), New PointF(rect.X + scaleFactor * 5, rect.Y + scaleFactor * 7), New PointF(rect.X + scaleFactor * 9, rect.Y + scaleFactor * 3), New PointF(rect.X + scaleFactor * 9, rect.Y + scaleFactor * 4), New PointF(rect.X + scaleFactor * 5, rect.Y + scaleFactor * 8), New PointF(rect.X + scaleFactor * 3, rect.Y + scaleFactor * 6), New PointF(rect.X + scaleFactor * 3, rect.Y + scaleFactor * 7), New PointF(rect.X + scaleFactor * 5, rect.Y + scaleFactor * 9), New PointF(rect.X + scaleFactor * 9, rect.Y + scaleFactor * 5) } Using checkPen As New Pen(Me.TickColor, 1) g.DrawLines(checkPen, points) End Using Case checkState.Indeterminate Using checkBrush As New SolidBrush(Me.TickColor) g.FillRectangle(checkBrush, New Rectangle(rect.X + 3, rect.Y + 3, rect.Width - 5, rect.Height - 5)) End Using Case checkState.Unchecked ' Do Nothing. End Select End Sub ''' <summary> ''' Gets the box rectangle. ''' </summary> ''' <returns>The box rectangle.</returns> Private Function GetBoxRectangle() As Rectangle Dim x As Integer = 0 Dim y As Integer = 2 Dim width As Integer = 14 Select Case Me.CheckAlign Case ContentAlignment.BottomCenter x = Decimal.ToInt32(Decimal.Floor(New Decimal((Me.Width - width) / 2) - 1)) y = Me.Height - width - 2 Case ContentAlignment.BottomLeft y = Me.Height - width - 2 Case ContentAlignment.BottomRight x = Me.Width - width - 2 y = Me.Height - width - 2 Case ContentAlignment.MiddleCenter x = Decimal.ToInt32(Decimal.Floor(New Decimal((Me.Width - width) / 2) - 1)) y = Decimal.ToInt32(Decimal.Floor(New Decimal((Me.Height - width) / 2) - 1)) Case ContentAlignment.MiddleLeft y = Decimal.ToInt32(Decimal.Floor(New Decimal((Me.Height - width) / 2) - 1)) Case ContentAlignment.MiddleRight x = Me.Width - width - 2 y = Decimal.ToInt32(Decimal.Floor(New Decimal((Me.Height - width) / 2) - 1)) Case ContentAlignment.TopCenter x = Decimal.ToInt32(Decimal.Floor(New Decimal((Me.Width - width) / 2) - 1)) Case ContentAlignment.TopRight x = Me.Width - width - 2 Case ContentAlignment.TopLeft ' Do Nothing. End Select Return New Rectangle(x, y, width, width) End Function #End Region End Class End Namespace
Imports BVSoftware.Bvc5.Core Imports System.Collections.ObjectModel Partial Class BVAdmin_Controls_KitComponentViewer Inherits System.Web.UI.UserControl Public Event PartsChanged As EventHandler Public Property ComponentId() As String Get Return Me.ComponentIdField.Value End Get Set(ByVal value As String) Me.ComponentIdField.Value = value LoadParts() End Set End Property Public Sub LoadParts() Dim ps As Collection(Of Catalog.KitPart) = Catalog.KitPart.FindByComponentId(Me.ComponentId) If ps IsNot Nothing Then Me.GridView1.DataSource = ps Me.GridView1.DataBind() End If End Sub Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit Dim bvin As String = CType(GridView1.DataKeys(e.RowIndex).Value, String) Catalog.KitPart.MoveUp(bvin) LoadParts() RaiseEvent PartsChanged(Me, System.EventArgs.Empty) End Sub Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then Dim DescriptionLiteral As Literal = e.Row.FindControl("DescriptionLiteral") If DescriptionLiteral IsNot Nothing Then Dim descriptionText As String Dim k As Catalog.KitPart = CType(e.Row.DataItem, Catalog.KitPart) descriptionText = k.Description & " - " & k.Price.ToString("C") If k.Quantity > 1 Then descriptionText += " Qty: " & k.Quantity End If If k.IsTiedToProduct Then If (Not k.IsVisibleInKit) Then descriptionText = "<del>" & descriptionText & "</del>" End If If (k.Product.Status = Catalog.ProductStatus.Disabled) Then descriptionText = descriptionText & " *" End If Dim productUrl As String = Me.ResolveUrl("~/BVAdmin/Catalog/Products_Edit.aspx?id=" & k.ProductBvin) DescriptionLiteral.Text = "<a href=""" & productUrl & """ title=""Strikethrough = out of stock, * = disabled product"">" & descriptionText & "</a>" Else DescriptionLiteral.Text = descriptionText End If End If End If End Sub Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting Dim bvin As String = CType(GridView1.DataKeys(e.RowIndex).Value, String) Catalog.KitPart.Delete(bvin) LoadParts() RaiseEvent PartsChanged(Me, System.EventArgs.Empty) End Sub Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing Dim bvin As String = CType(GridView1.DataKeys(e.NewEditIndex).Value, String) Response.Redirect("~/BVAdmin/Catalog/KitPart_Edit.aspx?id=" & bvin) End Sub Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating Dim bvin As String = CType(GridView1.DataKeys(e.RowIndex).Value, String) Catalog.KitPart.MoveDown(bvin) LoadParts() RaiseEvent PartsChanged(Me, System.EventArgs.Empty) End Sub End Class
Imports System Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Imports System.ComponentModel.DataAnnotations.Schema Imports System.Data.Entity.Spatial <Table("Person")> Partial Public Class Person Public Property Id As Integer Public Property FirstName As String Public Property LastName As String <StringLength(1)> Public Property Sex As String Public Property BirthDate As Date? Public Property City As String Public Property Country As String End Class
 Namespace Constants Public Class ConfigurationConstant Public Const DotNumber As String = ".Number" Public Const DotTask_Number As String = ".Task_Number" Public Const DotTaskNumber As String = ".TaskNumber" Public Const StationTaskNumber As String = "Station_Task_Number.Station_Task_Number" Public Const StationTaskNumberNew As String = "StationConfig.Station_Task_Number" End Class Public Class DbTableNameConstant Public Const StationsConfiguration As String = "Stations_Configuration" Public Const TasksConfiguration As String = "Tasks_Configuration" End Class Public Class StationsConfigurationColumnConstant Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const MemberName As String = "Member_Name" Public Const MemberValue As String = "Member_Value" Public Const MemberType As String = "Member_type" Public Const BaseTag As String = "Base_Tag" End Class Public Class StationsColumnConstant Public Const Id As String = "ID" Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const StationType As String = "Station_Type" Public Const PlcType As String = "PLC_Type" Public Const MasterFileName As String = "MasterFile_Name" Public Const MasterFileRevision As String = "MasterFile_Revision" Public Const ModelAffiliation As String = "ModelAffiliation" Public Const Accept As String = "Accept" End Class Public Class TasksConfigurationColumnConstant Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const TaskName As String = "Task_Name" Public Const TaskInstance As String = "Task_Instance" Public Const MemberName As String = "Member_Name" Public Const MemberValue As String = "Member_Value" Public Const MemberType As String = "Member_type" Public Const BaseTag As String = "Base_Tag" End Class Public Class TasksColumnConstant Public Const Id As String = "ID" Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const TaskName As String = "Task_Name" Public Const MasterFileName As String = "MasterFile_Name" Public Const ModelAffiliation As String = "ModelAffiliation" Public Const TaskMemory As String = "Task_Memory" Public Const TaskMemoryPlus As String = "Task_MemoryPLUS" Public Const TaskNodes As String = "Task_Nodes" Public Const TaskConnection As String = "Task_Connection" Public Const MaxNoOfInstances As String = "MaxNoOfInstances" End Class Public Class MasterFileColumnConstant Public Const MasterFileName As String = "MasterFile_Name" Public Const MasterFileRevision As String = "MasterFile_Revision" Public Const MasterFileApplicationNotes As String = "MasterFile_Application_Notes" Public Const OverheadMemoryBase As String = "Overhead_Memory_Base" Public Const OverheadMemoryPlus As String = "Overhead_Memory_PLUS" End Class Public Class MasterFilesTaskColumnConstant Public Const MasterFileName As String = "MasterFile_Name" Public Const TaskName As String = "Task_Name" Public Const MemoryUsed As String = "Memory_Used" Public Const Version As String = "Version" Public Const MultiStation As String = "Multi-Station" Public Const MaxNoOfInstances As String = "MaxNoOfInstances" Public Const ModelAffiliation As String = "ModelAffiliation" Public Const L5XFileName As String = "L5XFileName" End Class Public Class ModelConfigurationColumnConstant Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const TaskName As String = "Task_Name" Public Const TaskInstance As String = "Task_Instance" Public Const MemberName As String = "Member_Name" Public Const MemberValue As String = "Member_Value" Public Const MemberType As String = "Member_type" Public Const ModelInstance As String = "Model_Instance" End Class Public Class PlcsConfigurationColumnConstant Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const PlcName As String = "PLC_Name" Public Const MemberName As String = "Member_Name" Public Const MemberValue As String = "Member_Value" Public Const Address1 As String = "PLC.IP Address[1]" Public Const Address2 As String = "PLC.IP Address[2]" Public Const Address3 As String = "PLC.IP Address[3]" Public Const Address4 As String = "PLC.IP Address[4]" Public Const Slot As String = "PLC.PLC Slot" End Class Public Class PlcInformationColumnConstant Public Const ProcessorType As String = "Processor_Type" Public Const ApplicationNotes As String = "Application_Notes" Public Const TotalBytesAvailable As String = "Total_Bytes_Available" Public Const MaxNodes As String = "Max_Nodes" Public Const MaxConnections As String = "Max_Connections" End Class Public Class AreasConfigurationColumnConstant Public Const AreaName As String = "Area_Name" Public Const ModelNumber As String = "Model_Number" Public Const ModelName As String = "Model_Name" End Class Public Class MemoryUsageColumnConstant Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const StationName As String = "Station_Name" Public Const PlcType As String = "PLCType" Public Const TotalMem As String = "Total_Mem" Public Const TotalMemRsvd As String = "Total_Mem_Rsvd" Public Const MemAvailable As String = "Mem_Available" Public Const MemUsed As String = "Mem_Used" Public Const PercentAvailable As String = "Percent_Available" Public Const PercentUsed As String = "Percent_Used" End Class Public Class SectionConfigurationColumnConstant Public Const AreaName As String = "Area_Name" Public Const SectionName As String = "Section_Name" Public Const MemberName As String = "Member_Name" Public Const MemberValue As String = "Member_Value" End Class Public Class AreaStructureConstant Public Const ModelID As String = "ModelID" End Class Public Class OrderChangeConstant Public Const Show As String = "Save is OK" Public Const Station As String = "STATION" Public Const StationConfig As String = "StationConfig" Public Const Space As String = "-------" End Class Public Class StructureConstant Public Const Space As String = "SPACE" Public Const Parent As String = "Parent" End Class Public Class Form2Constant Public Const OrderChange As String = "Order Change" Public Const AcceptStation As String = "Accept Station" Public Const Config As String = "Config" Public Const Dot As String = "." Public Const LogixService As String = ".\Services\LogixService.py" Public Const True1 As String = "True" Public Const False1 As String = "False" End Class Public Class TreeNodeTagConstant Public Const PLANT As String = "PLANT" Public Const AREA As String = "AREA" Public Const SECTION As String = "SECTION" Public Const STATION As String = "STATION" Public Const TASK As String = "TASK" Public Const TASKInstancePrefix As String = "TASK|" Public Const MASTERFILE As String = "MASTERFILE" Public Const MASTERFILEATTRIBUTE As String = "MASTERFILEATTRIBUTE" Public Const PLC As String = "PLC" Public Const PLCAttribute As String = "PLCAttribute" End Class Public Class TreeNodeImageIndexConstant Public Const Plant As Integer = 0 Public Const Area As Integer = 1 Public Const Section As Integer = 2 Public Const Station As Integer = 3 Public Const Task As Integer = 5 Public Const MasterFileSub As Integer = 10 Public Const MasterFile As Integer = 12 Public Const MasterFileAttribute As Integer = 16 Public Const Plc As Integer = 15 Public Const PlcAttribute As Integer = 16 Public Const InvalidNode As Integer = 17 Public Const ValidNode As Integer = 19 Public Const NotFoundNode As Integer = 18 Public Const NotFoundValidationFieldNode As Integer = 9 Public Const ManualAcceptNode As Integer = 20 End Class Public Class StationTypeConstant Public Const Auto As String = "Auto" Public Const Manual As String = "Manual" End Class Public Class PlcMemoryGridViewHeaderConstant Public Const No As String = "No." Public Const AreaName As String = "Area Name" Public Const SectionName As String = "Section Name" Public Const StationName As String = "Station Name" Public Const StationType As String = "Station Type" Public Const PlcType As String = "PLC Type" Public Const TotalPlcMem As String = "Total PLC Mem" Public Const TotalRsvdMem As String = "Total Rsvd Mem" Public Const MemAvailable As String = "Mem Available" Public Const MemUsed As String = "Mem Used" End Class Public Class PlcMemoryGdvColumnNameConstant Public Const No As String = "No" Public Const AreaName As String = "AreaName" Public Const SectionName As String = "SectionName" Public Const StationName As String = "StationName" Public Const StationType As String = "StationType" Public Const PlcType As String = "PLCType" Public Const TotalPlcMem As String = "TotalPLCMem" Public Const TotalRsvdMem As String = "TotalRsvdMem" Public Const MemAvailable As String = "MemAvailable" Public Const MemUsed As String = "MemUsed" End Class End Namespace
Imports AutoMapper Imports UGPP.CobrosCoactivo.Datos Public Class TareaObservacionBLL Private Property _tareaObservacionDAL As TareaObservacionDAL Private Property _AuditEntity As Entidades.LogAuditoria Public Sub New() _tareaObservacionDAL = New TareaObservacionDAL() End Sub Public Sub New(ByVal auditData As Entidades.LogAuditoria) _AuditEntity = auditData _tareaObservacionDAL = New TareaObservacionDAL(_AuditEntity) End Sub ''' <summary> ''' Convierte un objeto del tipo Datos.TAREA_OBSERVACION a Entidades.TareaObservacion ''' </summary> ''' <param name="prmObjTareaObervacionDatos">Objeto de tipo Datos.TAREA_OBSERVACION</param> ''' <returns>Objeto de tipo Entidades.TareaObservacion</returns> Public Function ConvertirAEntidadTareaObervacion(ByVal prmObjTareaObervacionDatos As Datos.TAREA_OBSERVACION) As Entidades.TareaObservacion Dim tareaObervacion As Entidades.TareaObservacion Dim config As New MapperConfiguration(Function(cfg) Return cfg.CreateMap(Of Entidades.TareaObservacion, Datos.TAREA_OBSERVACION)() End Function) Dim IMapper = config.CreateMapper() tareaObervacion = IMapper.Map(Of Datos.TAREA_OBSERVACION, Entidades.TareaObservacion)(prmObjTareaObervacionDatos) Return tareaObervacion End Function ''' <summary> ''' Metódo que agrega un nuevo registro en la tabla TAREA_ONSERVACION ''' </summary> ''' <param name="prmObjTareaObservacionEntidad">Objeto de tipo Entidades.TareaObservacion</param> ''' <returns>Objeto de tipo Datos.TAREA_OBSERVACION</returns> Public Function crearTareaObservacion(ByVal prmObjTareaObservacionEntidad As Entidades.TareaObservacion) As Entidades.TareaObservacion Return ConvertirAEntidadTareaObervacion(_tareaObservacionDAL.crearTareaObservacion(prmObjTareaObservacionEntidad)) End Function ''' <summary> ''' Obtiene una observacion de una tarea por su ID ''' </summary> ''' <param name="prmIntITareaObservacion">Identificador de la observación</param> ''' <returns>Objeto del tipo Entidades.TareaObservacion</returns> Public Function obtenerTareaObservacionPorId(ByVal prmIntITareaObservacion As Int32) As Entidades.TareaObservacion Return ConvertirAEntidadTareaObervacion(_tareaObservacionDAL.obtenerTareaObservacionPorId(prmIntITareaObservacion)) End Function End Class
Namespace Servicios Public Class Inscripcion Private ReadOnly categoriasTorneo As Servicios.CategoriasTorneo Public Sub New(CategoriasTorneo As Servicios.CategoriasTorneo) Me.categoriasTorneo = CategoriasTorneo End Sub Public Sub New() End Sub Public Function BuscarCategoria(ByVal Categoria As Dominios.CategoriasTorneo) As Dominios.CategoriasTorneo For Each elemento As DictionaryEntry In Me.categoriasTorneo.Categorias If CType(elemento.Value, Dominios.CategoriasTorneo).Categoria = Categoria.Categoria Then Dim catEncontrada = CType(elemento.Value, Dominios.CategoriasTorneo) Return New Dominios.CategoriasTorneo With {.Categoria = catEncontrada.Categoria, .CuposDisponibles = catEncontrada.CuposDisponibles, .PrecioInscripcion = catEncontrada.PrecioInscripcion} End If Next Return Nothing End Function Public Function ValidarCampoDisponible(ByVal Categoria As Dominios.CategoriasTorneo) As Boolean For Each elemento As DictionaryEntry In Me.categoriasTorneo.Categorias If CType(elemento.Value, Dominios.CategoriasTorneo).Categoria = Categoria.Categoria Then If CType(elemento.Value, Dominios.CategoriasTorneo).CuposDisponibles > 0 Then Return True End If End If Next Return False End Function End Class End Namespace
'----------------------------------------------------- ' MessageBoxHelloWorld.vb (c) 2002 by Charles Petzold '----------------------------------------------------- Module MessageBoxHelloWorld Sub Main() System.Windows.Forms.MessageBox.Show("Hello, world!") End Sub End Module
Public Partial Class UC_Bank_Insert Inherits System.Web.UI.UserControl Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Public msg As String = "" Public Validataion As Boolean = True ''' <summary> ''' เพิ่มข้อมูลธนาคาร ''' </summary> ''' <param name="dao"></param> ''' <remarks></remarks> Public Sub insert(ByRef dao As DAO_MAS.TB_MAS_BANK) If txtBank_Name.Text = "" Then msg = "กรุณากรอกข้อมูลธนาคาร" Validataion = False Exit Sub Else Validataion = True dao.fields.BANK_NAME = txtBank_Name.Text End If End Sub ''' <summary> ''' ดึงข้อมูลธนาคาร ''' </summary> ''' <param name="dao"></param> ''' <remarks></remarks> Public Sub getdata(ByRef dao As DAO_MAS.TB_MAS_BANK) txtBank_Name.Text = dao.fields.BANK_NAME End Sub End Class
''' <summary> ''' Database1.accdb has been setup to be copied to Bin\Debug folder ''' each time you run this demo so we start fresh each time. ''' ''' Run the oproject, press Demo button. ''' Close the app ''' ''' </summary> ''' <remarks></remarks> Public Class Form1 ''' <summary> ''' Access to database operations ''' </summary> ''' <remarks></remarks> Private DataOpts As New DataAccess.Operations ''' <summary> ''' Used for the data source for the DataGridView ''' </summary> ''' <remarks></remarks> WithEvents bsCustmers As New BindingSource ''' <summary> ''' Load data from back end database ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load bsCustmers.DataSource = DataOpts.LoadCustomers DataGridView1.DataSource = bsCustmers End Sub ''' <summary> ''' Add new rows to the cutomer table, we get the new primary key via the method ''' AddNewRow. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub cmdAddRows_Click(sender As Object, e As EventArgs) Handles cmdAddRows.Click Dim SeconaryTry As Boolean = False Dim Customers As New List(Of Customer) From { New Customer With {.CompanyName = "BDF Inc.", .ContactName = "Anne", .ContactTitle = "Owner"}, New Customer With {.CompanyName = "Bill's shoes", .ContactName = "Bill", .ContactTitle = "Owner"}, New Customer With {.CompanyName = "Salem Fishing Corp", .ContactName = "Debbie", .ContactTitle = "Sales"} } Dim NewIdentifier As Integer = 0 Dim dt As DataTable = CType(bsCustmers.DataSource, DataTable) For Each Customer In Customers ' ' See if the row already exists ' If bsCustmers.Find("CompanyName", Customer.CompanyName) = -1 Then If DataOpts.AddNewRow(Customer, NewIdentifier) Then dt.Rows.Add(New Object() {NewIdentifier, Customer.CompanyName, Customer.ContactName, Customer.ContactTitle}) End If Else SeconaryTry = True Exit For End If Next If SeconaryTry Then MessageBox.Show("This was designed to work once :-)") End If End Sub Private Sub cmdView_Click(sender As Object, e As EventArgs) Handles cmdView.Click DataOpts.ViewDatabase() End Sub ''' <summary> ''' This code was added 10/2016 to show using a modal dialog to add a record. ''' In this case unlike the original method on the same form I don't check for ''' if the company already exists. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim f As New frmNewCustomer f.cboContactTitle.DataSource = DataOpts.ContactTitles If f.ShowDialog = DialogResult.OK Then If Not String.IsNullOrWhiteSpace(f.txtCompanyName.Text) OrElse Not String.IsNullOrWhiteSpace(f.txtContactName.Text) Then Dim NewIdentifier As Integer = 0 If DataOpts.AddNewRow(f.txtCompanyName.Text, f.txtContactName.Text, f.cboContactTitle.Text, NewIdentifier) Then Dim dt As DataTable = CType(bsCustmers.DataSource, DataTable) dt.Rows.Add(New Object() {NewIdentifier, f.txtCompanyName.Text, f.txtContactName.Text, f.cboContactTitle.Text}) End If End If End If End Sub End Class
 Option Compare Binary Option Infer On Option Strict On Option Explicit On Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.ComponentModel.DataAnnotations Imports System.Linq Imports System.ServiceModel.DomainServices.Hosting Imports System.ServiceModel.DomainServices.Server Imports CableSoft.BLL.Utility 'TODO: 建立包含應用程式邏輯的方法。 Public Class CopyOrder 'Inherits DomainService Implements IDisposable Private _CopyOrder As CableSoft.SO.BLL.Order.CopyOrder.CopyOrder Private result As New RIAResult() Public Property isHTML As Boolean = False Private Sub InitClass(ByVal LoginInfo As LoginInfo) _CopyOrder = New CableSoft.SO.BLL.Order.CopyOrder.CopyOrder(LoginInfo.ConvertTo(LoginInfo)) End Sub Public Function CanEdit(ByVal LoginInfo As LoginInfo, ByVal OrderNo As String) As RIAResult Try InitClass(LoginInfo) Return _CopyOrder.CanEdit(OrderNo) 'Return RIAResult.Convert(_CopyOrder.CanEdit(OrderNo)) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() End Try End Function Public Function ChkAllSNOCitemCount(ByVal LoginInfo As LoginInfo, ByVal CustId As Integer, ByVal AllSNO As String) As RIAResult Try InitClass(LoginInfo) result.ResultBoolean = True result = _CopyOrder.ChkAllSNOCitemCount(CustId, AllSNO) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() End Try Return result End Function Public Function GetCloseWipData(ByVal LoginInfo As LoginInfo, ByVal OrderNo As String, ByVal CustId As Integer, _ ByVal IncludeOrder As Boolean, ByVal WorkType As Integer) As RIAResult Try InitClass(LoginInfo) result.ResultBoolean = True result = _CopyOrder.GetCloseWipData(OrderNo, CustId, IncludeOrder, WorkType) If result.ResultBoolean Then result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(result.ResultDataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) End If 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(dt.DataSet) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() End Try Return result End Function Public Function ChkReturnCode(ByVal LoginInfo As LoginInfo, ByVal OrderNo As String) As RIAResult Try InitClass(LoginInfo) result.ResultBoolean = True Dim dt As DataTable = _CopyOrder.ChkReturnCode(OrderNo) result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(dt.DataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(dt.DataSet) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() End Try Return result End Function Public Function GetCustId(ByVal LoginInfo As LoginInfo, ByVal OrderNo As String) As RIAResult Try InitClass(LoginInfo) Dim dt As DataTable = _CopyOrder.GetCustId(OrderNo) result.ResultBoolean = True result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(dt.DataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(dt.DataSet) 'Return RIAResult.Convert(_CopyOrder.Execute(OrderNo)) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() End Try Return result End Function Public Function ExecuteHtml(ByVal LoginInfo As LoginInfo, _ ByVal OrderNo As String, ByVal AllSNO As String, ByVal WorkType As Integer, _ ByVal ExecTab As String, ByVal ShouldRegPriv As Boolean, _ ByVal CustId As Integer, ByVal IsOrderTurnSend As Boolean, ByVal OtherTable As String) As RIAResult Dim dsExecTab As DataSet = Nothing Dim dtOther As DataTable = Nothing Dim dtExecTab As DataTable = Nothing Try InitClass(LoginInfo) If Not String.IsNullOrEmpty(ExecTab) Then dsExecTab = Silverlight.DataSetConnector.Connector.FromXml(ExecTab) dtExecTab = dsExecTab.Tables(0) End If If Not String.IsNullOrEmpty(OtherTable) Then dtOther = Silverlight.DataSetConnector.Connector.FromXml(OtherTable).Tables(0) End If result = _CopyOrder.Execute(OrderNo, AllSNO, WorkType, dtExecTab, ShouldRegPriv, CustId, IsOrderTurnSend, dtOther) If result.ResultBoolean Then result.ResultBoolean = True result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(result.ResultDataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) End If 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(dt.DataSet) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() If dsExecTab IsNot Nothing Then dsExecTab.Dispose() dsExecTab = Nothing End If If dtOther IsNot Nothing Then dtOther.Dispose() dtOther = Nothing End If End Try Return result End Function Public Function Execute(ByVal LoginInfo As LoginInfo, ByVal OrderNo As String) As RIAResult Try InitClass(LoginInfo) result = _CopyOrder.Execute(OrderNo) If result.ResultBoolean Then result.ResultBoolean = True result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(result.ResultDataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) End If 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(dt.DataSet) Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _CopyOrder.Dispose() End Try Return result End Function #Region "IDisposable Support" Private disposedValue As Boolean ' 偵測多餘的呼叫 ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: 處置 Managed 狀態 (Managed 物件)。 End If ' TODO: 釋放 Unmanaged 資源 (Unmanaged 物件) 並覆寫下面的 Finalize()。 ' TODO: 將大型欄位設定為 null。 End If Me.disposedValue = True End Sub ' TODO: 只有當上面的 Dispose(ByVal disposing As Boolean) 有可釋放 Unmanaged 資源的程式碼時,才覆寫 Finalize()。 'Protected Overrides Sub Finalize() ' ' 請勿變更此程式碼。在上面的 Dispose(ByVal disposing As Boolean) 中輸入清除程式碼。 ' Dispose(False) ' MyBase.Finalize() 'End Sub ' 由 Visual Basic 新增此程式碼以正確實作可處置的模式。 Public Sub Dispose() Implements IDisposable.Dispose ' 請勿變更此程式碼。在以上的 Dispose 置入清除程式碼 (ByVal 視為布林值處置)。 Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class
Module ModKeypressHandler Sub onlyNumeric(ByRef e As System.Windows.Forms.KeyPressEventArgs) If Asc(e.KeyChar) <> 8 Then ' if it's not a backspace If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then ' then if it isn't numeric e.Handled = True ' stop paying attention to it End If End If End Sub End Module
Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.InteropServices Namespace Day13VB Friend Class Parser Public Function Convert(ByVal matrix As Char()()) As Char(,) Dim w As Integer = matrix.Count() Dim h As Integer = matrix(0).Length Dim result = New Char(h - 1, w - 1) {} For i As Integer = 0 To w - 1 For j As Integer = 0 To h - 1 result(j, i) = matrix(i)(j) Next Next Return result End Function Public Sub Load(ByRef cells As Char(,), ByRef carts As List(Of Cart)) Dim file = System.IO.File.ReadAllLines("Input.txt").[Select](Function(line) line.ToCharArray()).ToArray() cells = Convert(file) carts = New List(Of Cart)() For y As Integer = 0 To cells.GetUpperBound(1) For x As Integer = 0 To cells.GetUpperBound(0) Select Case cells(x, y) Case "<"c carts.Add(New Cart() With { .X = x, .Y = y, .CurrentDirection = Direction.West, .NextTurn = Turn.Left }) cells(x, y) = "-"c Case ">"c carts.Add(New Cart() With { .X = x, .Y = y, .CurrentDirection = Direction.East, .NextTurn = Turn.Left }) cells(x, y) = "-"c Case "^"c carts.Add(New Cart() With { .X = x, .Y = y, .CurrentDirection = Direction.North, .NextTurn = Turn.Left }) cells(x, y) = "|"c Case "v"c carts.Add(New Cart() With { .X = x, .Y = y, .CurrentDirection = Direction.South, .NextTurn = Turn.Left }) cells(x, y) = "|"c Case Else End Select Next Next End Sub End Class End Namespace
 ''DTO Definition - SalesOrderItem (to SalesOrderItem)'Generated from Table:SalesOrderItem Imports RTIS.DataLayer Imports RTIS.DataLayer.clsDBConnBase Imports RTIS.CommonVB.clsGeneralA Imports RTIS.CommonVB Public Class dtoSalesOrderItem : Inherits dtoBase Private pSalesOrderItem As dmSalesOrderItem Public Sub New(ByRef rDBSource As clsDBConnBase) MyBase.New(rDBSource) End Sub Protected Overrides Sub SetTableDetails() pTableName = "SalesOrderItem" pKeyFieldName = "SalesOrderItemID" pUseSoftDelete = False pRowVersionColName = "rowversion" pConcurrencyType = eConcurrencyType.OverwriteChanges End Sub Overrides Property ObjectKeyFieldValue() As Integer Get ObjectKeyFieldValue = pSalesOrderItem.SalesOrderItemID End Get Set(ByVal value As Integer) pSalesOrderItem.SalesOrderItemID = value End Set End Property Overrides Property IsDirtyValue() As Boolean Get IsDirtyValue = pSalesOrderItem.IsDirty End Get Set(ByVal value As Boolean) pSalesOrderItem.IsDirty = value End Set End Property Overrides Property RowVersionValue() As ULong Get End Get Set(ByVal value As ULong) End Set End Property Overrides Sub ObjectToSQLInfo(ByRef rFieldList As String, ByRef rParamList As String, ByRef rParameterValues As System.Data.IDataParameterCollection, ByVal vSetList As Boolean) Dim mDummy As String = "" Dim mDummy2 As String = "" If vSetList Then DBSource.AddParamPropertyInfo(rParameterValues, mDummy, mDummy2, vSetList, "SalesOrderItemID", pSalesOrderItem.SalesOrderItemID) End If With pSalesOrderItem DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "SalesOrderID", .SalesOrderID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ItemNumber", StringToDBValue(.ItemNumber)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "Description", StringToDBValue(.Description)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "Quantity", .Quantity) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "UnitPrice", .UnitPrice) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ImageFile", StringToDBValue(.ImageFile)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "WoodFinish", .WoodFinish) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "WoodSpecieID", .WoodSpecieID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "QtyInvoiced", .QtyInvoiced) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "SalesItemAssemblyID", .SalesItemAssemblyID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "HouseTypeID", .SalesHouseID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ProductTypeID", .ProductTypeID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ProductID", .ProductID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "SalesItemType", .SalesItemType) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "SalesSubItemType", .SalesSubItemType) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ProductConstructionType", .ProductConstructionType) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "Comments", StringToDBValue(.Comments)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "UoM", .UoM) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "WoodCost", .WoodCost) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "StockItemCost", .StockItemCost) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "TransportationCost", .TransportationCost) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ManpowerCost", .ManpowerCost) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "SubContractCost", .SubContractCost) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "MaterialCost", .MaterialCost) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "VatRateCode", .VatRateCode) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "VatValue", .VatValue) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "LineValue", .LineValue) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "POStageID", .POStageID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "IsGeneral", .IsGeneral) End With End Sub Overrides Function ReaderToObject(ByRef rDataReader As IDataReader) As Boolean Dim mOK As Boolean Try If pSalesOrderItem Is Nothing Then SetObjectToNew() With pSalesOrderItem .SalesOrderItemID = DBReadInt32(rDataReader, "SalesOrderItemID") .SalesOrderID = DBReadInt32(rDataReader, "SalesOrderID") .ItemNumber = DBReadString(rDataReader, "ItemNumber") .Description = DBReadString(rDataReader, "Description") .Quantity = DBReadInt32(rDataReader, "Quantity") .UnitPrice = DBReadDecimal(rDataReader, "UnitPrice") .ImageFile = DBReadString(rDataReader, "ImageFile") .WoodFinish = DBReadInt32(rDataReader, "WoodFinish") .WoodSpecieID = DBReadInt32(rDataReader, "WoodSpecieID") .QtyInvoiced = DBReadInt32(rDataReader, "QtyInvoiced") .SalesItemAssemblyID = DBReadInt32(rDataReader, "SalesItemAssemblyID") .SalesHouseID = DBReadInt32(rDataReader, "HouseTypeID") .ProductTypeID = DBReadByte(rDataReader, "ProductTypeID") .ProductID = DBReadInt32(rDataReader, "ProductID") .SalesSubItemType = DBReadInt32(rDataReader, "SalesSubItemType") .SalesItemType = DBReadInt32(rDataReader, "SalesItemType") .ProductConstructionType = DBReadInt32(rDataReader, "ProductConstructionType") .Comments = DBReadString(rDataReader, "Comments") .UoM = DBReadInt32(rDataReader, "UoM") .WoodCost = DBReadDecimal(rDataReader, "WoodCost") .StockItemCost = DBReadDecimal(rDataReader, "StockItemCost") .TransportationCost = DBReadDecimal(rDataReader, "TransportationCost") .ManpowerCost = DBReadDecimal(rDataReader, "ManpowerCost") .SubContractCost = DBReadDecimal(rDataReader, "SubContractCost") .VatValue = DBReadDecimal(rDataReader, "VatValue") .VatRateCode = DBReadInt32(rDataReader, "VatRateCode") .LineValue = DBReadDecimal(rDataReader, "LineValue") .MaterialCost = DBReadDecimal(rDataReader, "MaterialCost") .POStageID = DBReadInt32(rDataReader, "POStageID") .IsGeneral = DBReadBoolean(rDataReader, "IsGeneral") pSalesOrderItem.IsDirty = False End With mOK = True Catch Ex As Exception mOK = False If clsErrorHandler.HandleError(Ex, clsErrorHandler.PolicyDataLayer) Then Throw ' or raise an error ? mOK = False Finally End Try Return mOK End Function Protected Overrides Function SetObjectToNew() As Object pSalesOrderItem = New dmSalesOrderItem ' Or .NewBlankSalesOrderItem Return pSalesOrderItem End Function Public Function LoadSalesOrderItem(ByRef rSalesOrderItem As dmSalesOrderItem, ByVal vSalesOrderItemID As Integer) As Boolean Dim mOK As Boolean mOK = LoadObject(vSalesOrderItemID) If mOK Then rSalesOrderItem = pSalesOrderItem Else rSalesOrderItem = Nothing End If pSalesOrderItem = Nothing Return mOK End Function Public Function SaveSalesOrderItem(ByRef rSalesOrderItem As dmSalesOrderItem) As Boolean Dim mOK As Boolean pSalesOrderItem = rSalesOrderItem mOK = SaveObject() pSalesOrderItem = Nothing Return mOK End Function Public Function LoadSalesOrderItemCollection(ByRef rSalesOrderItems As colSalesOrderItems, ByVal vParentID As Integer) As Boolean Dim mParams As New Hashtable Dim mOK As Boolean mParams.Add("@SalesOrderID", vParentID) mOK = MyBase.LoadCollection(rSalesOrderItems, mParams, "SalesOrderItemID") rSalesOrderItems.TrackDeleted = True If mOK Then rSalesOrderItems.IsDirty = False Return mOK End Function Public Function SaveSalesOrderItemCollection(ByRef rCollection As colSalesOrderItems, ByVal vParentID As Integer) As Boolean Dim mParams As New Hashtable Dim mAllOK As Boolean Dim mCount As Integer Dim mIDs As String = "" If rCollection.IsDirty Then mParams.Add("@SalesOrderID", vParentID) ''Alternative Approach - where maintain collection of deleted items If rCollection.SomeDeleted Then mAllOK = True For Each Me.pSalesOrderItem In rCollection.DeletedItems If pSalesOrderItem.SalesOrderItemID <> 0 Then If mAllOK Then mAllOK = MyBase.DeleteDBRecord(pSalesOrderItem.SalesOrderItemID) End If Next Else mAllOK = True End If For Each Me.pSalesOrderItem In rCollection If pSalesOrderItem.IsDirty Or pSalesOrderItem.SalesOrderID <> vParentID Or pSalesOrderItem.SalesOrderItemID = 0 Then 'Or pSalesOrderItem.SalesOrderItemID = 0 pSalesOrderItem.SalesOrderID = vParentID If mAllOK Then mAllOK = SaveObject() End If Next If mAllOK Then rCollection.IsDirty = False Else mAllOK = True End If Return mAllOK End Function End Class
Public Class dbNominasDetalles Public ID As Integer Public NuevoConcepto As Boolean Public Tipo As Byte Public IdNomina As Integer Public TipoPercepcionDeduccion As Integer Public Clave As String Public Concepto As String Public ImporteGravado As Double Public ImporteExento As Double Public valorMercado As Double Public precioAlOtorgarse As Double Dim Comm As New MySql.Data.MySqlClient.MySqlCommand Public Sub New(ByVal Conexion As MySql.Data.MySqlClient.MySqlConnection) ID = -1 Tipo = 0 IdNomina = 0 TipoPercepcionDeduccion = 0 '0 Percepcion 1 Deduccion Clave = "" Concepto = "" ImporteExento = 0 ImporteGravado = 0 NuevoConcepto = False Comm.Connection = Conexion End Sub Public Sub New(ByVal pID As Integer, ByVal Conexion As MySql.Data.MySqlClient.MySqlConnection) ID = pID Comm.Connection = Conexion LlenaDatos() End Sub Public Sub LlenaDatos() Dim DReader As MySql.Data.MySqlClient.MySqlDataReader Comm.CommandText = "select * from tblnominadetalles where iddetalle=" + ID.ToString DReader = Comm.ExecuteReader If DReader.Read() Then Tipo = DReader("tipo") IdNomina = DReader("idnomina") TipoPercepcionDeduccion = DReader("tipodetalle") Clave = DReader("clave") Concepto = DReader("concepto") ImporteGravado = DReader("importegravado") ImporteExento = DReader("importeexento") valorMercado = DReader("valormercado") precioAlOtorgarse = DReader("precioalotorgarse") End If DReader.Close() 'If Idinventario > 1 Then Inventario = New dbInventario(Idinventario, Comm.Connection) 'If IdVariante > 1 Then Producto = New dbProductosVariantes(IdVariante, Comm.Connection) 'Moneda = New dbMonedas(IdMoneda, Comm.Connection) End Sub Public Sub Guardar(ByVal pIdNomina As Integer, ByVal pTipo As Byte, ByVal pTipoDetalle As Integer, ByVal pClave As String, ByVal pConcepto As String, ByVal pImpGravado As Double, ByVal pImpExento As Double, ByVal valorMercado As Double, ByVal precioAlOtorgarse As Double) NuevoConcepto = True Comm.CommandText = "insert into tblnominadetalles(idnomina,tipo,tipodetalle,clave,concepto,importegravado,importeexento,valormercado,precioalotorgarse) values(" + pIdNomina.ToString + "," + pTipo.ToString + "," + pTipoDetalle.ToString + ",'" + Replace(pClave, "'", "''") + "','" + Replace(pConcepto, "'", "''") + "'," + pImpGravado.ToString + "," + pImpExento.ToString + "," + valorMercado.ToString + "," + precioAlOtorgarse.ToString + ");" Comm.CommandText += "select ifnull(last_insert_id(),0);" ID = Comm.ExecuteScalar End Sub Public Sub Modificar(ByVal pID As Integer, ByVal pTipo As Byte, ByVal pTipoDetalle As Integer, ByVal pClave As String, ByVal pConcepto As String, ByVal pImpGravado As Double, ByVal pImpExento As Double, ByVal valorMercado As Double, ByVal precioAlOtorgarse As Double) ID = pID Comm.CommandText = "update tblnominadetalles set tipo=" + pTipo.ToString + ",tipodetalle=" + pTipoDetalle.ToString + ",clave='" + Replace(pClave, "'", "''") + "',concepto='" + Replace(pConcepto, "'", "''") + "',importegravado=" + pImpGravado.ToString + ",importeexento=" + pImpExento.ToString + ", valorMercado=" + valorMercado.ToString + ", precioalotorgarse=" + precioAlOtorgarse.ToString + " where iddetalle=" + ID.ToString Comm.ExecuteNonQuery() End Sub Public Sub Eliminar(ByVal pID As Integer) Comm.CommandText = "delete from tblnominadetalles where iddetalle=" + pID.ToString Comm.ExecuteNonQuery() End Sub Public Function Consulta(ByVal pIdVenta As Integer) As DataView Dim DS As New DataSet Comm.CommandText = "select tvi.iddetalle,if(tvi.tipodetalle=0,'Percepción','Deducción') as tipod,tvi.tipo,tvi.clave,tvi.concepto,tvi.importegravado,tvi.importeexento from tblnominadetalles as tvi where tvi.idnomina=" + pIdVenta.ToString Dim DA As New MySql.Data.MySqlClient.MySqlDataAdapter(Comm) DA.Fill(DS, "tblnominadetalles") Return DS.Tables("tblnominadetalles").DefaultView End Function Public Function ConsultaReader(ByVal pIdVenta As Integer, ByVal pTipoDetalle As Byte) As MySql.Data.MySqlClient.MySqlDataReader If pTipoDetalle <> 3 Then Comm.CommandText = "select tvi.iddetalle,if(tvi.tipodetalle=0,'Percepción','Deducción') as tipod,tvi.clave,if(tvi.tipodetalle=0,(select descripcion from tblpercepciones where idpercepcion=tvi.tipo),(select descripcion from tbldeducciones where iddeduccion=tvi.tipo)) as tipode,tvi.concepto,tvi.importegravado,tvi.importeexento,tvi.tipo,tvi.valormercado,tvi.precioalotorgarse,if(tvi.tipodetalle=0,(select clave from tblpercepciones where idpercepcion=tvi.tipo),(select clave from tbldeducciones where iddeduccion=tvi.tipo)) as tipocl from tblnominadetalles as tvi where tvi.idnomina=" + pIdVenta.ToString + " and tvi.tipodetalle=" + pTipoDetalle.ToString Else Comm.CommandText = "select tvi.iddetalle,if(tvi.tipodetalle=0,'Percepción','Deducción') as tipod,tvi.clave,if(tvi.tipodetalle=0,(select descripcion from tblpercepciones where idpercepcion=tvi.tipo),(select descripcion from tbldeducciones where iddeduccion=tvi.tipo)) as tipode,if(tvi.tipodetalle=0,concat(tvi.concepto,spdadetallespercepciones(tvi.iddetalle)),tvi.concepto) as concepto,tvi.importegravado,tvi.importeexento,tvi.tipo,tvi.valormercado,tvi.precioalotorgarse,if(tvi.tipodetalle=0,(select clave from tblpercepciones where idpercepcion=tvi.tipo),(select clave from tbldeducciones where iddeduccion=tvi.tipo)) as tipocl from tblnominadetalles as tvi where tvi.idnomina=" + pIdVenta.ToString End If Return Comm.ExecuteReader End Function Public Function Consulta(ByVal pIdVenta As Integer, ByVal pTipoDetalle As Byte) As List(Of Integer) If pTipoDetalle <> 3 Then Comm.CommandText = "select tvi.iddetalle,if(tvi.tipodetalle=0,'Percepción','Deducción') as tipod,tvi.clave,if(tvi.tipodetalle=0,(select descripcion from tblpercepciones where clave=tvi.tipo),(select descripcion from tbldeducciones where clave=tvi.tipo)) as tipod,tvi.concepto,tvi.importegravado,tvi.importeexento,tvi.tipo,tvi.valormercado,tvi.precioalotorgarse from tblnominadetalles as tvi where tvi.idnomina=" + pIdVenta.ToString + " and tvi.tipodetalle=" + pTipoDetalle.ToString Else Comm.CommandText = "select tvi.iddetalle,if(tvi.tipodetalle=0,'Percepción','Deducción') as tipod,tvi.clave,if(tvi.tipodetalle=0,(select descripcion from tblpercepciones where clave=tvi.tipo),(select descripcion from tbldeducciones where clave=tvi.tipo)) as tipod,tvi.concepto,tvi.importegravado,tvi.importeexento,tvi.tipo,tvi.valormercado,tvi.precioalotorgarse from tblnominadetalles as tvi where tvi.idnomina=" + pIdVenta.ToString End If Dim lista As New List(Of Integer) Dim dr As MySql.Data.MySqlClient.MySqlDataReader = Comm.ExecuteReader While dr.Read() lista.Add(dr("iddetalle")) End While dr.Close() Return lista End Function End Class
 Public Class TOCBLL ''' <summary> ''' returns all of the rules and descriptions for a particular screen ''' </summary> ''' <param name="intTOCID"></param> ''' <returns>ScreenRuleBO</returns> ''' <remarks></remarks> Public Shared Function GetScreenRuleByTOCID(ByVal intTOCID As Integer) As ScreenRuleBO Dim oTOCRules As List(Of TOCRulesDO) = TOCRules.GetByTOCID(intTOCID).ToList Dim oTOC As TOCDO = TOC.GetByPK(intTOCID).FirstOrDefault Dim oRules As List(Of RuleBO) = Nothing Dim oScreenRule As New ScreenRuleBO oScreenRule.TOCID = intTOCID oScreenRule.NavigateUrl = oTOC.NavigateUrl oRules = New List(Of RuleBO) Dim oRule As RuleBO Dim oSS As RuleSubSectionDO Dim strOldSection As String = "" 'get all the rules for this screen, loop thru once to get section and then a second loop for the first time of a new section to get subsections For Each oTOCRule As TOCRulesDO In oTOCRules 'initiate rule oRule = New RuleBO 'only if new section, add rules If oTOCRule.Section <> strOldSection Then 'get section oRule.RuleSection = RuleSection.GetByPK(oTOCRule.Section).FirstOrDefault 'initiate list of subsections oRule.RuleSubSection = New List(Of RuleSubSectionDO) 'loop through again to get subsections For Each oTOCSubSectionRule As TOCRulesDO In TOCRules.GetBySectionTOCID(oTOCRule.Section, intTOCID).ToList oSS = New RuleSubSectionDO oSS = RuleSubSection.GetByPK(oTOCSubSectionRule.SubSection).FirstOrDefault oRule.RuleSubSection.Add(oSS) Next 'add to list oRules.Add(oRule) 'reset section name to check strOldSection = oTOCRule.Section End If Next oScreenRule.Rules = oRules Return oScreenRule End Function ''' <summary> ''' Get the HelpBO for a screen ''' </summary> ''' <param name="strNavigateUrl"></param> ''' <returns>HelpBO</returns> ''' <remarks></remarks> Public Shared Function GetHelp(ByVal strNavigateUrl As String) As HelpBO Dim oTOC As TOCDO = TOC.GetAll().Where(Function(TR) TR.NavigateUrl = strNavigateUrl).FirstOrDefault Dim oHelp As New HelpBO oHelp.TOCID = oTOC.TOCID oHelp.ParentTOCID = oTOC.ParentTOCID oHelp.NavigateUrl = oTOC.NavigateUrl oHelp.ScreenTitle = oTOC.Description oHelp.Instructions = oTOC.Instructions oHelp.Templates = AttachmentBLL.GetAttachments(oTOC.TOCID) oHelp.ScreenRules = GetScreenRuleByTOCID(oTOC.TOCID) Return oHelp End Function ''' <summary> ''' Get the HelpBO for all screen ''' </summary> ''' <returns>List(Of HelpBO)</returns> ''' <remarks></remarks> Public Shared Function GetHelpForAllScreens() As List(Of HelpBO) Dim oScreens As List(Of ScreenBO) = GetScreens() Dim oAllHelp As New List(Of HelpBO) Dim oHelp As HelpBO Dim oTOC As TOCDO For Each oScreen As ScreenBO In oScreens oTOC = TOC.GetAll().Where(Function(TR) TR.TOCID = oScreen.TOCID).FirstOrDefault oHelp = New HelpBO oHelp.TOCID = oTOC.TOCID oHelp.ParentTOCID = oTOC.ParentTOCID oHelp.ScreenTitle = oTOC.Description oHelp.NavigateUrl = oTOC.NavigateUrl oHelp.Instructions = oTOC.Instructions oHelp.Templates = AttachmentBLL.GetAttachments(oTOC.TOCID) oHelp.ScreenRules = GetScreenRuleByTOCID(oTOC.TOCID) oAllHelp.Add(oHelp) Next Return oAllHelp End Function ''' <summary> ''' Get the HelpBO for only the sections ''' </summary> ''' <returns>List(Of HelpBO)</returns> ''' <remarks></remarks> Public Shared Function GetHelpForSections() As List(Of HelpBO) Dim oScreens As List(Of ScreenBO) = GetSections() Dim oAllHelp As New List(Of HelpBO) Dim oHelp As HelpBO Dim oTOC As TOCDO For Each oScreen As ScreenBO In oScreens oTOC = TOC.GetAll().Where(Function(TR) TR.TOCID = oScreen.TOCID).FirstOrDefault oHelp = New HelpBO oHelp.TOCID = oTOC.TOCID oHelp.ParentTOCID = oTOC.ParentTOCID oHelp.ScreenTitle = oTOC.Description oHelp.NavigateUrl = oTOC.NavigateUrl oHelp.Instructions = oTOC.Instructions oHelp.Templates = AttachmentBLL.GetAttachments(oTOC.TOCID) oHelp.ScreenRules = GetScreenRuleByTOCID(oTOC.TOCID) oAllHelp.Add(oHelp) Next Return oAllHelp End Function ''' <summary> ''' Get the Home Page information for a user ''' </summary> ''' <param name="RegistrationID"></param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function GetHomePage(ByVal RegistrationID As Integer) As HomeBO Dim oHome As New HomeBO oHome.RegistrationID = RegistrationID 'only get permits for registrationID oHome.Permits = PermitBLL.GetPermits(RegistrationID).ToList oHome.SelectedPermitID = "" 'Don't have on here 'get announcement oHome.Announcement = GetAnnouncement() 'get Activity Logs for the registered user 'Dim oActivityLogs As List(Of ActivityLogDO) = ActivityLogBLL.GetByUser(RegistrationID) oHome.ActivityLogs = ActivityLogBLL.GetByUser(RegistrationID) oHome.UserTasks = Nothing Return oHome End Function ''' <summary> ''' Get all the activities for a user and permit information ''' </summary> ''' <param name="RegistrationID"></param> ''' <param name="PermitID"></param> ''' <returns></returns> ''' <remarks>if PermitID is blank, return everything</remarks> Public Shared Function GetAllActivities(ByVal RegistrationID As Integer, ByVal PermitID As String) As HomeBO Dim oHome As New HomeBO oHome.RegistrationID = RegistrationID 'only get permits for registrationID oHome.Permits = PermitBLL.GetPermits(RegistrationID).ToList oHome.PermitIDs = New List(Of String) oHome.SelectedPermitID = PermitID For Each oPermit As PermitDO In oHome.Permits If oHome.PermitIDs.Contains(oPermit.PermitID) = False Then oHome.PermitIDs.Add(oPermit.PermitID) End If Next 'get announcement oHome.Announcement = GetAnnouncement() 'get Activity Logs for the registered user 'Dim oActivityLogs As List(Of ActivityLogDO) = ActivityLogBLL.GetByUser(RegistrationID) oHome.ActivityLogs = ActivityLogBLL.GetByPermitID(RegistrationID, PermitID) oHome.UserTasks = Nothing Return oHome End Function ''' <summary> ''' Get the Announcement for main screen ''' </summary> ''' <returns>AnnouncementDO</returns> ''' <remarks></remarks> Public Shared Function GetAnnouncement() As AnnouncementDO Return Announcement.GetByPK(1).FirstOrDefault End Function ''' <summary> ''' Set the Announcement ''' </summary> ''' <param name="Description"></param> ''' <remarks></remarks> Public Shared Sub SetAnnouncement(ByVal Description As String) 'Get the announcement Dim oAnnouncement As AnnouncementDO = Announcement.GetByPK(1).FirstOrDefault If oAnnouncement IsNot Nothing Then 'Delete announcement Announcement.Delete(oAnnouncement) Else 'create new instance and set ID = 1 oAnnouncement = New AnnouncementDO oAnnouncement.AnnouncementID = 1 End If 'Update description oAnnouncement.Description = Description 'Creat new entry Announcement.Create(oAnnouncement) End Sub ''' <summary> ''' Returns all the screen names ''' </summary> ''' <returns>list of string</returns> ''' <remarks></remarks> Public Shared Function GetScreenNames() As List(Of String) Dim oScreenNames As New List(Of String) Dim oTOC As List(Of TOCDO) = TOC.GetAll().Where(Function(TR) TR.ParentTOCID <> 0).ToList For Each oTOCDO As TOCDO In oTOC oScreenNames.Add(oTOCDO.Description) Next Return oScreenNames End Function ''' <summary> ''' Returns the screen name for a tocid ''' </summary> ''' <param name="TOCID"></param> ''' <returns>Screen Name</returns> ''' <remarks></remarks> Public Shared Function GetScreenName(ByVal TOCID As Integer) As String Dim oScreenName As String = "" Dim oTOC As TOCDO = TOC.GetAll().Where(Function(TR) TR.TOCID = TOCID).FirstOrDefault If oTOC IsNot Nothing Then oScreenName = oTOC.Description End If Return oScreenName End Function ''' <summary> ''' Returns all the screenBO for Screen Name,URL, TOCID ''' </summary> ''' <returns>list of ScreenBO</returns> ''' <remarks></remarks> Public Shared Function GetScreens() As List(Of ScreenBO) Dim oScreens As New List(Of ScreenBO) Dim oScreen As ScreenBO Dim oTOC As List(Of TOCDO) = TOC.GetAll().Where(Function(TR) TR.ParentTOCID <> 0).OrderBy(Function(x) x.DisplayOrder).ToList For Each oTOCDO As TOCDO In oTOC oScreen = New ScreenBO oScreen.ScreenName = oTOCDO.Description oScreen.TOCID = oTOCDO.TOCID oScreen.URL = oTOCDO.NavigateUrl oScreens.Add(oScreen) Next Return oScreens End Function ''' <summary> ''' Returns all the screenBO for Screen Sections ''' </summary> ''' <returns>list of ScreenBO</returns> ''' <remarks></remarks> Public Shared Function GetSections() As List(Of ScreenBO) Dim oScreens As New List(Of ScreenBO) Dim oScreen As ScreenBO Dim oTOC As List(Of TOCDO) = TOC.GetAll().Where(Function(TR) TR.ParentTOCID = 0).ToList For Each oTOCDO As TOCDO In oTOC oScreen = New ScreenBO oScreen.ScreenName = oTOCDO.Description oScreen.TOCID = oTOCDO.TOCID oScreen.URL = oTOCDO.NavigateUrl oScreens.Add(oScreen) Next Return oScreens End Function ''' <summary> ''' Save the TOC instructions ''' </summary> ''' <param name="intTOCID"></param> ''' <param name="strInstructions"></param> ''' <returns>True or False</returns> ''' <remarks></remarks> Public Shared Function SaveInstruction(ByVal intTOCID As Integer, ByVal strInstructions As String) As Boolean 'if update fails, return 0 Dim oTOC As TOCDO = TOC.GetAll().Where(Function(TR) TR.TOCID = intTOCID).FirstOrDefault oTOC.Instructions = strInstructions If TOC.Update(oTOC) = 0 Then Return False End If Return True End Function ''' <summary> ''' Get the view connecting URL to Rule ''' </summary> ''' <returns>List of vRuleScreenDO</returns> ''' <remarks></remarks> Public Shared Function GetRuleScreen() As List(Of vRuleScreenDO) Dim oRuleScreens As List(Of vRuleScreenDO) = vRuleScreen.GetAll().OrderBy(Function(x) x.SectionNumber).ThenBy(Function(y) y.SubSection).ToList Return oRuleScreens End Function ''' <summary> ''' Save the TOC ''' </summary> ''' <param name="oTOC"></param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function Save(oTOC As TOCDO) As Boolean 'if update fails, return 0 If TOC.Update(oTOC) = 0 Then Return False End If Return True End Function End Class
' ' Copyright (c) Clevergy ' ' The SOFTWARE, as well as the related copyrights and intellectual property rights, are the exclusive property of Clevergy srl. ' Licensee acquires no title, right or interest in the SOFTWARE other than the license rights granted herein. ' ' conceived and developed by Marco Fagnano (D.R.T.C.) ' il software è ricorsivo, nel tempo rigenera se stesso. ' Imports System Imports System.Collections.Generic Imports SF.DAL Imports System.IO Namespace SF.BLL Public Class Rapportini_Firme #Region "constructor" Public Sub New() Me.New(0, String.Empty) End Sub Public Sub New(m_Id As Integer, m_imgFirma As String) Id = m_Id imgFirma = m_imgFirma End Sub #End Region #Region "methods" Public Shared Function Read(Id As Integer) As Rapportini_Firme If Id <= 0 Then Return Nothing End If Return DataAccessHelper.GetDataAccess.Rapportini_Firme_Read(Id) End Function Public Shared Function Add(Id As Integer, imgFirma As String) As Boolean If Id <= 0 Then Return False End If If String.IsNullOrEmpty(imgFirma) Then Return False End If Return DataAccessHelper.GetDataAccess.Rapportini_Firme_Add(Id, imgFirma) End Function #End Region #Region "public properties" Public Property Id As Integer Public Property imgFirma As String #End Region End Class End Namespace
Imports Microsoft.VisualBasic Imports System Imports System.Drawing.Drawing2D Imports Neurotec.Images Imports Neurotec.Images.Processing Friend Class Program Private Shared Function Usage() As Integer Console.WriteLine("usage:") Console.WriteLine(vbTab & "{0} [image] [width] [height] [output image] [interpolation mode]", TutorialUtils.GetAssemblyName()) Console.WriteLine(vbTab & "[image] - image to scale") Console.WriteLine(vbTab & "[width] - scaled image width") Console.WriteLine(vbTab & "[height] - scaled image height") Console.WriteLine(vbTab & "[output image] - scaled image") Console.WriteLine(vbTab & "[interpolation mode] - (optional) interpolation mode to use: 0 - nearest neighbour, 1 - bilinear") Console.WriteLine() Return 1 End Function Shared Function Main(ByVal args() As String) As Integer TutorialUtils.PrintTutorialHeader(args) If args.Length < 4 Then Return Usage() End If Try Dim dstWidth As UInteger = UInteger.Parse(args(1)) Dim dstHeight As UInteger = UInteger.Parse(args(2)) Dim mode As InterpolationMode = InterpolationMode.NearestNeighbor If args.Length >= 5 AndAlso args(4) = "1" Then mode = InterpolationMode.Bilinear End If ' open image Dim image As NImage = NImage.FromFile(args(0)) ' convert image to grayscale Dim grayscaleImage As NImage = NImage.FromImage(NPixelFormat.Grayscale8U, 0, image) ' scale image Dim result As NImage = Ngip.Scale(grayscaleImage, dstWidth, dstHeight, mode) result.Save(args(3)) Console.WriteLine("scaled image saved to ""{0}""", args(3)) Return 0 Catch ex As Exception Return TutorialUtils.PrintException(ex) End Try End Function End Class
Public Class clsETipoEmpleado Private mid As Integer Private mtipoEmpleado As String Public Property id As Integer Get Return mid End Get Set(value As Integer) mid = value End Set End Property Public Property tipoEmpleado As String Get Return mtipoEmpleado End Get Set(value As String) mtipoEmpleado = value End Set End Property End Class
'************************************************************************** ' adnCommerce Online Web Shop ' ' Developer : Cem Ikta ' ' Copyright(c) 2009-2010, adnatives new media agency ' www.adnatives.com '************************************************************************** Imports Microsoft.VisualBasic Imports System.Collections.Generic Imports Adnatives.AdnCommerce.DAL Namespace Adnatives.AdnCommerce.BLL.BasicsModule Public Class Country Inherits BaseBasicsModule '---------------------------- ' Private variables '---------------------------- Private _name As String = "" Private _isoCode2 As String = "" Private _isoCode3 As String = "" Private _taxZoneID As Integer = 0 Private _status As Boolean = True '---------------------------- ' Properties '---------------------------- Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Public Property IsoCode2() As String Get Return _isoCode2 End Get Set(ByVal value As String) _isoCode2 = value End Set End Property Public Property IsoCode3() As String Get Return _isoCode3 End Get Set(ByVal value As String) _isoCode3 = value End Set End Property Public Property TaxZoneID() As Integer Get Return _taxZoneID End Get Set(ByVal value As Integer) _taxZoneID = value End Set End Property Public Property Status() As Boolean Get Return _status End Get Set(ByVal value As Boolean) _status = value End Set End Property '---------------------------- ' Constructor '---------------------------- Public Sub New(ByVal id As Integer, ByVal name As String, ByVal isoCode2 As String, _ ByVal isoCode3 As String, ByVal taxZoneID As Integer, ByVal status As Boolean, _ ByVal createUser As String, ByVal createDate As DateTime, _ ByVal updateUser As String, ByVal updateDate As DateTime) Me.ID = id Me.Name = name Me.IsoCode2 = isoCode2 Me.IsoCode3 = isoCode3 Me.TaxZoneID = taxZoneID Me.Status = status Me.CreateUser = createUser Me.CreateDate = createDate Me.UpdateUser = updateUser Me.UpdateDate = updateDate End Sub '---------------------------- ' Methods '---------------------------- Public Function Delete() As Boolean Dim success As Boolean = Country.DeleteCountry(Me.ID) If success Then Me.ID = 0 Return success End Function Public Function Update() As Boolean Return Country.UpdateCountry(Me.ID, Me.Name, Me.IsoCode2, Me.IsoCode3, Me.TaxZoneID, Me.Status) End Function '---------------------------- ' Shared Methods '---------------------------- ' CountryList doner Public Shared Function GetCountryList() As List(Of Country) Dim countryList As List(Of Country) Dim key As String = "Store_Country" If BaseBasicsModule.Settings.EnableCaching AndAlso Not IsNothing(BizObject.Cache(key)) Then countryList = CType(BizObject.Cache(key), List(Of Country)) Else Dim recordset As List(Of CountryModel) = SiteProvider.BasicsModule.GetCountryList() countryList = GetCountryListFromCountryModelList(recordset) BaseBasicsModule.CacheData(key, countryList) End If Return countryList End Function ' Verilen ID ile Country doner Public Shared Function GetCountryByID(ByVal countryID As Integer) As Country Dim country As Country Dim key As String = "Store_Country_" & countryID.ToString() If BaseBasicsModule.Settings.EnableCaching AndAlso Not IsNothing(BizObject.Cache(key)) Then country = CType(BizObject.Cache(key), Country) Else country = GetCountryFromCountryModel(SiteProvider.BasicsModule.GetCountryByID(countryID)) BaseBasicsModule.CacheData(key, country) End If Return country End Function ' Country update islemi Public Shared Function UpdateCountry(ByVal id As Integer, ByVal name As String, _ ByVal isoCode2 As String, ByVal isoCode3 As String, ByVal taxZoneID As Integer, _ ByVal status As Boolean) As Boolean ' update isleminde createUser ve createDate update edilmicek ' CreateDate zaten dolu oldugu icin sorun yok. Dim record As New CountryModel(id, name, isoCode2, isoCode3, taxZoneID, status, "", Nothing, _ BizObject.CurrentUserName, DateTime.Now) Dim ret As Boolean = SiteProvider.BasicsModule.UpdateCountry(record) BizObject.PurgeCacheItems("store_country") Return ret End Function ' Country delete islemi Public Shared Function DeleteCountry(ByVal id As Integer) As Boolean ' eger country customer'lerde kullanilmissa silinmez. ' customer profile de tutuldugu icin foreign key verilemiyor. Dim allUsers As MembershipUserCollection = Membership.GetAllUsers() For Each user As MembershipUser In allUsers Dim profile As New ProfileCommon profile = ProfileCommon.Create(user.UserName) If profile.Billing.Country = id Then 'bu country kullaniliyor. silinmiyecek Throw New ApplicationException("DeleteException") ' aslinda gerek yok ama bulunca ciksin Exit For ElseIf profile.Shipping.Country = id Then 'bu country kullaniliyor. silinmiyecek Throw New ApplicationException("DeleteException") ' aslinda gerek yok ama bulunca ciksin Exit For End If Next ' eger exception cikmassa silsin. Dim ret As Boolean = SiteProvider.BasicsModule.DeleteCountry(id) Dim ev As New RecordDeletedEvent("country", id, Nothing) ev.Raise() BizObject.PurgeCacheItems("store_country") Return ret End Function ' Country insert islemi Public Shared Function InsertCountry(ByVal name As String, ByVal isoCode2 As String, _ ByVal isoCode3 As String, ByVal taxZoneID As Integer, ByVal status As Boolean) As Integer Dim record As New CountryModel(0, name, isoCode2, isoCode3, taxZoneID, status, _ BizObject.CurrentUserName, DateTime.Now, "", New DateTime(1900, 1, 1)) Dim ret As Integer = SiteProvider.BasicsModule.InsertCountry(record) BizObject.PurgeCacheItems("store_country") Return ret End Function ' Parametre olarak gelen CountryModel'den olusturulan Country objesi doner. Private Shared Function GetCountryFromCountryModel(ByVal record As CountryModel) As Country If IsNothing(record) Then Return Nothing Else Return New Country(record.ID, record.Name, record.IsoCode2, _ record.IsoCode3, record.TaxZoneID, record.Status, _ record.CreateUser, record.CreateDate, _ record.UpdateUser, record.UpdateDate) End If End Function ' Parametre olarak gelen CountryModel Listesinden olusturulan CountryList objesi doner. Private Shared Function GetCountryListFromCountryModelList(ByVal recordset As List(Of CountryModel)) As List(Of Country) Dim countryList As New List(Of Country) For Each record As CountryModel In recordset countryList.Add(GetCountryFromCountryModel(record)) Next Return countryList End Function End Class End Namespace
Imports LN.Gestores Imports LN.Estructuras Public Class frmBuscarCurso #Region "Eventos" ''' <summary> ''' Load de el formulario ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Diego Salas Arce</remarks> Private Sub frmBuscarCurso_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load lblValidaCriterioCodigo.Visible = False lblValidaCriterioNombre.Visible = False End Sub ''' <summary> ''' Validación del label hacia el textbox de busqueda de curso por codigo ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Diego Salas Arce</remarks> Private Sub txtBuscCursoCodigo_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtBuscCursoCodigo.KeyUp If Trim(txtBuscCursoCodigo.Text) = String.Empty Then lblValidaCriterioCodigo.Visible = True Else lblValidaCriterioCodigo.Visible = False End If End Sub ''' <summary> ''' Validación del label hacia el textbox de busqueda de curso por nombre ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Diego Salas Arce</remarks> Private Sub txtBuscCursoNombre_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtBuscCursoNombre.KeyUp If Trim(txtBuscCursoNombre.Text) = String.Empty Then lblValidaCriterioNombre.Visible = True Else lblValidaCriterioNombre.Visible = False End If End Sub ''' <summary> ''' Acción del botón de buscar curso por código ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Diego Salas Arce</remarks> Private Sub btnBuscarCursoCodigo_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscarCursoCodigo.Click vlcMensaje = "Debe ingresar el código del curso" If Trim(txtBuscCursoCodigo.Text) = String.Empty Then MessageBox.Show(vlcMensaje, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtBuscCursoCodigo.Focus() Else BusquedaXCodigoCurso() End If End Sub ''' <summary> ''' Acción del boton de buscar curso por nombre ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Diego Salas Arce</remarks> Private Sub btnBuscarCursoNombre_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscarCursoNombre.Click vlcMensaje = "Debe ingresar el nombre del curso" If Trim(txtBuscCursoNombre.Text) = String.Empty Then MessageBox.Show(vlcMensaje, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtBuscCursoCodigo.Focus() Else BusquedaXNombreCurso() End If End Sub ''' <summary> ''' Cierra la ventana de búsqueda de cursos ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Diego Salas Arce</remarks> Private Sub btnSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalir.Click Me.Close() End Sub #End Region #Region "Atributos" Dim vlcMensaje As String = "" #End Region #Region "Constantes" #End Region #Region "Procedimientos" Private Sub BusquedaXCodigoCurso() 'Obtengo el codigo del curso digitado por el usuario Dim codigoCurso As String = txtBuscCursoCodigo.Text() 'Obtengo la estructura de cursos haciendo un llamado al gestor Dim vlostrDatosCurso As StrCurso = GestorCurso.buscarXCodigo(codigoCurso) MessageBox.Show("Información del curso" & vbCrLf & "ID: " & vlostrDatosCurso.Codigo & vbCrLf & "Código: " & vlostrDatosCurso.Nombre & vbCrLf & "Nombre: " & vlostrDatosCurso.Estado) End Sub Private Sub BusquedaXNombreCurso() 'Obtengo el nombre del curso digitado por el usuario Dim nombreCurso As String = txtBuscCursoNombre.Text() 'Obtengo la estructura de cursos haciendo un llamado al gestor Dim vlostrDatosCurso As StrCurso = GestorCurso.buscarXNombre(nombreCurso) MessageBox.Show("Información del curso" & vbCrLf & "Código de curso: " & vlostrDatosCurso.Codigo & vbCrLf & "Curso: " & vlostrDatosCurso.Nombre & vbCrLf & "Estado: " & vlostrDatosCurso.Estado) End Sub #End Region #Region "Funciones" #End Region End Class
Public Class AdendaModelo Public Property id As Integer Public Property entityType As String Public Property idCreador As String Public Property texto As String Public Property idReferencia As String Public Property informacionComprador As String Public Property idCreadorAlt As String Public Property tipoDivisa As String Public Property tipoCambio As Double Public Property cantidadTotal As Double Public Property cantidadBase2 As Double Public Property porcentajeTax2 As Double Public Property cantidadTax2 As Double Public Property categoriaTax2 As String Public Property tipoTax As String Public Property cantidadFinal As Double Public Property idVenta As Integer Public Sub New() End Sub Public Sub New(ByVal id As Integer) Me.id = id End Sub Public Sub New(ByVal id As Integer, ByVal entityType As String, ByVal idCreador As String, ByVal texto As String, ByVal idReferencia As String, ByVal informacionComprador As String, ByVal idCreadorAlt As String, ByVal tipoDivisa As String, ByVal tipoCambio As Double, ByVal cantidadtotal As Double, ByVal cantidadBase2 As Double, ByVal porcentajeTax2 As Double, ByVal cantidadTax2 As Double, ByVal categoriaTax2 As String, ByVal tipoTax As String, ByVal cantidadFinal As Double, ByVal idVenta As Integer) Me.id = id Me.entityType = entityType Me.idCreador = idCreador Me.texto = texto Me.idReferencia = idReferencia Me.informacionComprador = informacionComprador Me.idCreadorAlt = idCreadorAlt Me.tipoDivisa = tipoDivisa Me.tipoCambio = tipoCambio Me.cantidadTotal = cantidadTotal Me.cantidadBase2 = cantidadBase2 Me.porcentajeTax2 = porcentajeTax2 Me.cantidadTax2 = cantidadTax2 Me.categoriaTax2 = categoriaTax2 Me.tipoTax = tipoTax Me.cantidadFinal = cantidadFinal Me.idVenta = idVenta End Sub Public Sub New(ByVal entityType As String, ByVal idCreador As String, ByVal texto As String, ByVal idReferencia As String, ByVal informacionComprador As String, ByVal idCreadorAlt As String, ByVal tipoDivisa As String, ByVal tipoCambio As Double, ByVal cantidadtotal As Double, ByVal cantidadBase2 As Double, ByVal porcentajeTax2 As Double, ByVal cantidadTax2 As Double, ByVal categoriaTax2 As String, ByVal tipoTax As String, ByVal cantidadFinal As Double, ByVal idVenta As Integer) Me.entityType = entityType Me.idCreador = idCreador Me.texto = texto Me.idReferencia = idReferencia Me.informacionComprador = informacionComprador Me.idCreadorAlt = idCreadorAlt Me.tipoDivisa = tipoDivisa Me.tipoCambio = tipoCambio Me.cantidadTotal = cantidadtotal Me.cantidadBase2 = cantidadBase2 Me.porcentajeTax2 = porcentajeTax2 Me.cantidadTax2 = cantidadTax2 Me.categoriaTax2 = categoriaTax2 Me.tipoTax = tipoTax Me.cantidadFinal = cantidadFinal Me.idVenta = idVenta End Sub Public Function crearXml() As String Dim detalles As New detalleAdendaModeloDAO(MySqlcon) Dim lista As List(Of detalleAdendaModelo) = detalles.listaDetalles(Me.id) Dim xml As String = "<cfdi:Addenda>" + vbCrLf xml += "<modelo:AddendaModelo xmlns:modelo=""http://www.gmodelo.com.mx/CFD/Addenda/Receptor"" xsi:schemaLocation=""http://www.gmodelo.com.mx/CFD/Addenda/Receptor https://femodelo.gmodelo.com/Addenda/ADDENDAMODELOCORTA.xsd"">" + vbCrLf xml += "<modelo:requestForPayment>" + vbCrLf xml += "<modelo:requestForPaymentIdentification>" + vbCrLf xml += "<modelo:entityType>" + Me.entityType + "</modelo:entityType>" + vbCrLf xml += "<modelo:uniqueCreatorIdentification>" + Me.idCreador + "</modelo:uniqueCreatorIdentification>" + vbCrLf xml += "</modelo:requestForPaymentIdentification>" + vbCrLf xml += "<modelo:specialInstruction>" + vbCrLf xml += "<modelo:text>" + Me.texto + "</modelo:text>" + vbCrLf xml += "</modelo:specialInstruction>" + vbCrLf xml += "<modelo:orderIdentification>" + vbCrLf xml += "<modelo:referenceIdentification>" + Me.idReferencia + "</modelo:referenceIdentification>" + vbCrLf xml += "</modelo:orderIdentification>" + vbCrLf xml += "<modelo:buyer>" + vbCrLf xml += "<modelo:contactInformation>" + vbCrLf xml += "<modelo:personOrDepartmentName>" + vbCrLf xml += "<modelo:text>" + Me.informacionComprador + "</modelo:text>" + vbCrLf xml += "</modelo:personOrDepartmentName>" + vbCrLf xml += "</modelo:contactInformation>" + vbCrLf xml += "</modelo:buyer>" + vbCrLf xml += "<modelo:InvoiceCreator>" + vbCrLf xml += "<modelo:alternatePartyIdentification>" + Me.idCreadorAlt + "</modelo:alternatePartyIdentification>" + vbCrLf xml += "</modelo:InvoiceCreator>" + vbCrLf xml += "<modelo:currency currencyISOCode=""" + Me.tipoDivisa + """>" + vbCrLf xml += "<modelo:rateOfChange>" + Me.tipoCambio.ToString() + "</modelo:rateOfChange>" + vbCrLf xml += "</modelo:currency>" + vbCrLf Dim Des As String For Each d As detalleAdendaModelo In lista xml += "<modelo:lineItem orderLineNumber=""" + d.posicionPedido.ToString() + """>" + vbCrLf xml += "<modelo:tradeItemIdentification>" + vbCrLf xml += "<modelo:gtin>" + d.codigoEAN + "</modelo:gtin>" + vbCrLf xml += "</modelo:tradeItemIdentification>" + vbCrLf xml += "<modelo:alternateTradeItemIdentification>" + d.numProveedor + "</modelo:alternateTradeItemIdentification>" + vbCrLf xml += "<modelo:tradeItemDescriptionInformation language=""" + d.idioma + """>" + vbCrLf If d.descripcion.Length > 35 Then Des = d.descripcion.Substring(0, 35) Else Des = d.descripcion End If Des = Trim(Replace(Des, vbCrLf, "")) While Des.IndexOf(" ") <> -1 Des = Replace(Des, " ", " ") End While Des = Replace(Replace(Replace(Replace(Replace(Replace(Des, vbCrLf, ""), "&", "&amp;"), ">", "&gt"), "<", "&lt;"), """", "&quot;"), "'", "&apos;") xml += "<modelo:longText>" + Des + "</modelo:longText>" xml += "</modelo:tradeItemDescriptionInformation>" + vbCrLf xml += "<modelo:invoicedQuantity unitOfMeasure=""" + d.unidadMedida + """>" + d.cantidadProductosFacturada.ToString() + "</modelo:invoicedQuantity>" + vbCrLf xml += "<modelo:grossPrice>" + vbCrLf xml += "<modelo:Amount>" + d.precioBruto.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:grossPrice>" + vbCrLf xml += "<modelo:netPrice>" + vbCrLf xml += "<modelo:Amount>" + d.precioNeto.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:netPrice>" + vbCrLf xml += "<modelo:AdditionalInformation>" + vbCrLf xml += "<modelo:referenceIdentification>" + d.numReferenciaAdicional + "</modelo:referenceIdentification>" + vbCrLf xml += "</modelo:AdditionalInformation>" + vbCrLf xml += "<modelo:tradeItemTaxInformation>" + vbCrLf xml += "<modelo:taxTypeDescription>" + d.tipoArancel + "</modelo:taxTypeDescription>" + vbCrLf xml += "<modelo:taxCategory>" + d.identificacionImpuesto + "</modelo:taxCategory>" + vbCrLf xml += "<modelo:tradeItemTaxAmount>" + vbCrLf xml += "<modelo:taxPercentage>" + d.porcentajeImpuesto.ToString() + "</modelo:taxPercentage>" + vbCrLf xml += "<modelo:taxAmount>" + d.montoImpuesto.ToString() + "</modelo:taxAmount>" + vbCrLf xml += "</modelo:tradeItemTaxAmount>" + vbCrLf xml += "</modelo:tradeItemTaxInformation>" + vbCrLf xml += "<modelo:totalLineAmount>" + vbCrLf xml += "<modelo:grossAmount>" + vbCrLf xml += "<modelo:Amount>" + d.precioBrutoArticulos.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:grossAmount>" + vbCrLf xml += "<modelo:netAmount>" + vbCrLf xml += "<modelo:Amount>" + d.precioNetoArticulos.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:netAmount>" + vbCrLf xml += "</modelo:totalLineAmount>" + vbCrLf xml += "</modelo:lineItem>" + vbCrLf Next xml += "<modelo:totalAmount>" + vbCrLf xml += "<modelo:Amount>" + Me.cantidadTotal.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:totalAmount>" + vbCrLf xml += "<modelo:baseAmount>" + vbCrLf xml += "<modelo:Amount>" + Me.cantidadBase2.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:baseAmount>" + vbCrLf xml += "<modelo:tax type=""" + Me.tipoTax + """>" + vbCrLf xml += "<modelo:taxPercentage>" + Me.porcentajeTax2.ToString() + "</modelo:taxPercentage>" + vbCrLf xml += "<modelo:taxAmount>" + Me.cantidadTax2.ToString() + "</modelo:taxAmount>" + vbCrLf xml += "<modelo:taxCategory>" + Me.categoriaTax2 + "</modelo:taxCategory>" + vbCrLf xml += "</modelo:tax>" + vbCrLf xml += "<modelo:payableAmount>" + vbCrLf xml += "<modelo:Amount>" + Me.cantidadFinal.ToString() + "</modelo:Amount>" + vbCrLf xml += "</modelo:payableAmount>" + vbCrLf xml += "</modelo:requestForPayment>" + vbCrLf xml += "</modelo:AddendaModelo>" + vbCrLf xml += "</cfdi:Addenda>" Return xml End Function End Class
Imports System.Collections.ObjectModel Module utilFiddlerCtrl Private Sub FiddlerApplication_AfterSessionComplete(oSession As Fiddler.Session) System.Diagnostics.Debug.WriteLine(String.Format("Session {0}({3}):HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl, oSession.oResponse.MIMEType)) Logger.Push(String.Format("{0}:HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl), {oSession, oSession.oRequest, oSession.oResponse}) End Sub Class Logger Friend Shared RecognizedList As New ListView Protected Friend Shared WithEvents log As New ObservableCollection(Of Object) Shared Sub Push(value As String, sessionDescription As Object) log.Add(sessionDescription) Debug.Print(value) End Sub Shared ReadOnly filterOfMIME As New List(Of String) From {"|[A-F0-9]{8}|", "video/mp4", "video/mp2t"} Shared ReadOnly filterOfMIME_streaming As New List(Of String) From {"|application/x-mpegURL|"} Shared Sub Parse(sender As Object, e As Specialized.NotifyCollectionChangedEventArgs) Handles log.CollectionChanged Dim mime As String = DirectCast(e.NewItems(0)(0), Fiddler.Session).oResponse.MIMEType Parallel.ForEach(filterOfMIME, Sub(f) If Evaluation(mime, f, strategy:=f.StartsWith("|") AndAlso f.EndsWith("|")) Then recognizedList.Invoke(Sub() RegisterMovie(e.NewItems(0), DirectCast(e.NewItems(0), Fiddler.Session).fullUrl, mime)) End If End Sub) Parallel.ForEach(filterOfMIME_streaming, Sub(f) If Evaluation(mime, f, strategy:=f.StartsWith("|") AndAlso f.EndsWith("|")) Then recognizedList.Invoke(Sub() RegisterMovie(e.NewItems(0), DirectCast(e.NewItems(0), Fiddler.Session).fullUrl, mime, "Streaming")) End If End Sub) End Sub Shared Sub RegisterMovie(oSession As Fiddler.Session, WhereIsThis As String, Optional MIMEtype As String = "(null)", Optional type As String = "Common") If type <> "Common" Then Dim item As ListViewItem = recognizedList.Items.Add(New ListViewItem({CStr(recognizedList.Items.Count), oSession.oRequest.headers.UriScheme, oSession.oRequest.headers.RequestPath, type, MIMEtype}) With {.ForeColor = Drawing.Color.Green, .Tag = oSession}) item.EnsureVisible() Else Dim item As ListViewItem = recognizedList.Items.Add(New ListViewItem({CStr(recognizedList.Items.Count), oSession.oRequest.headers.UriScheme, oSession.oRequest.headers.RequestPath, type, MIMEtype}) With {.Tag = oSession}) item.EnsureVisible() End If End Sub End Class Private Sub InitFiddler() AddHandler Fiddler.FiddlerApplication.ResponseHeadersAvailable, AddressOf FiddlerApplication_AfterSessionComplete Fiddler.CONFIG.IgnoreServerCertErrors = True Fiddler.CONFIG.bStreamAudioVideo = True Fiddler.FiddlerApplication.Startup(0, Fiddler.FiddlerCoreStartupFlags.CaptureLocalhostTraffic Or Fiddler.FiddlerCoreStartupFlags.DecryptSSL) Fiddler.URLMonInterop.SetProxyInProcess(String.Format("127.0.0.1:{0}", Fiddler.FiddlerApplication.oProxy.ListenPort), "<local>") End Sub Private Sub Shutdown() Fiddler.URLMonInterop.ResetProxyInProcessToDefault() Fiddler.FiddlerApplication.Shutdown() End Sub End Module
 Public Class ConvMatrix Public Property Factor() As Integer Get Return m_Factor End Get Set(ByVal value As Integer) m_Factor = Value End Set End Property Private m_Factor As Integer Public Property Offset() As Integer Get Return m_Offset End Get Set(ByVal value As Integer) m_Offset = Value End Set End Property Private m_Offset As Integer Private _matrix As Integer(,) = {{0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}} Public Property Matrix() As Integer(,) Get Return _matrix End Get Set(ByVal value As Integer(,)) _matrix = value Factor = 0 For i As Integer = 0 To Size - 1 For j As Integer = 0 To Size - 1 Factor += _matrix(i, j) Next Next If Factor = 0 Then Factor = 1 End If End Set End Property Private _size As Integer = 5 Public Property Size() As Integer Get Return _size End Get Set(ByVal value As Integer) If value <> 1 AndAlso value <> 3 AndAlso value <> 5 AndAlso value <> 7 Then _size = 5 Else _size = value End If End Set End Property Public Sub New() Offset = 0 Factor = 1 End Sub End Class
Imports System.Runtime.CompilerServices Imports System.Windows Imports System.Windows.Media.Animation Imports System.Windows.Media.Effects Module BlurElementExtension <Extension()> Sub BlurApply(ByVal element As UIElement, ByVal blurRadius As Double, ByVal duration As TimeSpan, ByVal beginTime As TimeSpan) Dim blur As BlurEffect = New BlurEffect() With { .Radius = 0 } Dim blurEnable As DoubleAnimation = New DoubleAnimation(0, blurRadius, duration) With { .BeginTime = beginTime } element.Effect = blur blur.BeginAnimation(BlurEffect.RadiusProperty, blurEnable) End Sub <Extension()> Sub BlurDisable(ByVal element As UIElement, ByVal duration As TimeSpan, ByVal beginTime As TimeSpan) Dim blur As BlurEffect = TryCast(element.Effect, BlurEffect) If blur Is Nothing OrElse blur.Radius = 0 Then Return End If Dim blurDisable As DoubleAnimation = New DoubleAnimation(blur.Radius, 0, duration) With { .BeginTime = beginTime } blur.BeginAnimation(BlurEffect.RadiusProperty, blurDisable) End Sub End Module
 Imports System.Text Imports System Imports System.IO Imports PCANBasicExample.Peak.Can.Basic Imports TPCANHandle = System.Byte Imports System.Collections.Stack Imports System.Threading.ThreadState Imports Excel = Microsoft.Office.Interop.Excel Imports Microsoft.Office Public Class Form1 Public Sub New() ' Initializes Form's component ' InitializeComponent() ' Initializes specific components ' InitializeBasicComponents() End Sub #Region "Structures" ''' <summary> ''' Message Status structure used to show CAN Messages ''' in a ListView ''' </summary> Private Class MessageStatus Private m_Msg As TPCANMsg Private m_TimeStamp As TPCANTimestamp Private m_oldTimeStamp As TPCANTimestamp Private m_iIndex As Integer Private m_Count As Integer Private m_bShowPeriod As Boolean Private m_bWasChanged As Boolean Public Sub New(ByVal canMsg As TPCANMsg, ByVal canTimestamp As TPCANTimestamp, ByVal listIndex As Integer) m_Msg = canMsg m_TimeStamp = canTimestamp m_iIndex = listIndex m_Count = 1 m_bShowPeriod = True m_bWasChanged = False End Sub Public Sub Update(ByVal canMsg As TPCANMsg, ByVal canTimestamp As TPCANTimestamp) m_Msg = canMsg m_oldTimeStamp = m_TimeStamp m_TimeStamp = canTimestamp m_bWasChanged = True m_Count += 1 End Sub Private Function GetMsgTypeString() As String Dim strTemp As String If (m_Msg.MSGTYPE And TPCANMessageType.PCAN_MESSAGE_EXTENDED) = TPCANMessageType.PCAN_MESSAGE_EXTENDED Then strTemp = "EXTENDED" Else strTemp = "STANDARD" End If If (m_Msg.MSGTYPE And TPCANMessageType.PCAN_MESSAGE_RTR) = TPCANMessageType.PCAN_MESSAGE_RTR Then strTemp += "/RTR" End If Return strTemp End Function Private Function GetIdString() As String If (m_Msg.MSGTYPE And TPCANMessageType.PCAN_MESSAGE_EXTENDED) = TPCANMessageType.PCAN_MESSAGE_EXTENDED Then Return String.Format("{0:X8}h", m_Msg.ID) Else Return String.Format("{0:X3}h", m_Msg.ID) End If End Function Private Function GetDataString() As String Dim strTemp As String strTemp = "" If (m_Msg.MSGTYPE And TPCANMessageType.PCAN_MESSAGE_RTR) = TPCANMessageType.PCAN_MESSAGE_RTR Then strTemp = "Remote Request" Else For i As Integer = 0 To m_Msg.LEN - 1 strTemp += String.Format("{0:X2} ", m_Msg.DATA(i)) Next End If Return strTemp End Function Private Function GetTimeString() As String Dim fTime As Double fTime = m_TimeStamp.millis + (m_TimeStamp.micros / 1000.0R) If m_bShowPeriod Then fTime -= (m_oldTimeStamp.millis + (m_oldTimeStamp.micros / 1000.0R)) End If Return fTime.ToString("F1") End Function Public ReadOnly Property CANMsg() As TPCANMsg Get Return m_Msg End Get End Property Public ReadOnly Property Timestamp() As TPCANTimestamp Get Return m_TimeStamp End Get End Property Public ReadOnly Property Position() As Integer Get Return m_iIndex End Get End Property Public ReadOnly Property TypeString() As String Get Return GetMsgTypeString() End Get End Property Public ReadOnly Property IdString() As String Get Return GetIdString() End Get End Property Public ReadOnly Property DataString() As String Get Return GetDataString() End Get End Property Public ReadOnly Property Count() As Integer Get Return m_Count End Get End Property Public Property ShowingPeriod() As Boolean Get Return m_bShowPeriod End Get Set(ByVal value As Boolean) If m_bShowPeriod Xor value Then m_bShowPeriod = value m_bWasChanged = True End If End Set End Property Public Property MarkedAsUpdated() As Boolean Get Return m_bWasChanged End Get Set(ByVal value As Boolean) m_bWasChanged = value End Set End Property Public ReadOnly Property TimeString() As String Get Return GetTimeString() End Get End Property End Class #End Region #Region "Delegates" ''' <summary> ''' Read-Delegate Handler ''' </summary> Private Delegate Sub ReadDelegateHandler() #End Region #Region "Members" ''' <summary> ''' Saves the handle of a PCAN hardware ''' </summary> Private m_PcanHandle As TPCANHandle ''' <summary> ''' Saves the baudrate register for a conenction ''' </summary> Private m_Baudrate As TPCANBaudrate ''' <summary> ''' Saves the type of a non-plug-and-play hardware ''' </summary> Private m_HwType As TPCANType ''' <summary> ''' Stores the status of received messages for its display ''' </summary> Private m_LastMsgsList As System.Collections.ArrayList ''' <summary> ''' Read Delegate for calling the function "ReadMessages" ''' </summary> Private m_ReadDelegate As ReadDelegateHandler ''' <summary> ''' Receive-Event ''' </summary> Private m_ReceiveEvent As System.Threading.AutoResetEvent ''' <summary> ''' Thread for message reading (using events) ''' </summary> Private m_ReadThread As System.Threading.Thread ''' <summary> ''' Handles of the current available PCAN-Hardware ''' </summary> Private m_HandlesArray As TPCANHandle() ''' <summary> ''' Array to handel multipule channels ''' </summary> Public chan_Array() As String Public Recipe As Boolean ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> #End Region #Region "Methods" #Region "UI Handler" Private Sub btnInit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInit.Click Dim stsResult As TPCANStatus ' Connects a selected PCAN-Basic channel ' stsResult = PCANBasic.Initialize(m_PcanHandle, m_Baudrate, m_HwType, Convert.ToUInt32(cbbIO.Text, 16), Convert.ToUInt16(cbbInterrupt.Text)) If stsResult <> TPCANStatus.PCAN_ERROR_OK Then MessageBox.Show(GetFormatedError(stsResult)) Else ' Prepares the PCAN-Basic's PCAN-Trace file ' ConfigureTraceFile() End If ' Sets the connection status of the main-form ' SetConnectionStatus(stsResult = TPCANStatus.PCAN_ERROR_OK) End Sub Private Sub cbbChannel_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbbChannel.SelectedIndexChanged Dim bNonPnP As Boolean Dim strTemp As String ' Get the handle fromt he text being shown strTemp = cbbChannel.Text strTemp = strTemp.Substring(strTemp.IndexOf("("c) + 1, 2) ' Determines if the handle belong to a No Plug&Play hardware ' m_PcanHandle = Convert.ToByte(strTemp, 16) bNonPnP = m_PcanHandle <= PCANBasic.PCAN_DNGBUS1 ' Activates/deactivates configuration controls according with the ' kind of hardware ' cbbHwType.Enabled = bNonPnP cbbIO.Enabled = bNonPnP cbbInterrupt.Enabled = bNonPnP End Sub Private Sub btnHwRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHwRefresh.Click Dim iBuffer As UInt32 Dim stsResult As TPCANStatus ' Clears the Channel combioBox and fill it againa with ' the PCAN-Basic handles for no-Plug&Play hardware and ' the detected Plug&Play hardware ' cbbChannel.Items.Clear() Try For i As Integer = 0 To m_HandlesArray.Length - 1 ' Includes all no-Plug&Play Handles If m_HandlesArray(i) <= PCANBasic.PCAN_DNGBUS1 Then cbbChannel.Items.Add(FormatChannelName(m_HandlesArray(i))) Else ' Checks for a Plug&Play Handle and, according with the return value, includes it ' into the list of available hardware channels. ' stsResult = PCANBasic.GetValue(m_HandlesArray(i), TPCANParameter.PCAN_CHANNEL_CONDITION, iBuffer, System.Runtime.InteropServices.Marshal.SizeOf(iBuffer)) If (stsResult = TPCANStatus.PCAN_ERROR_OK) AndAlso (iBuffer = PCANBasic.PCAN_CHANNEL_AVAILABLE) Then cbbChannel.Items.Add(FormatChannelName(m_HandlesArray(i))) End If End If Next cbbChannel.SelectedIndex = cbbChannel.Items.Count - 1 Catch ex As DllNotFoundException MessageBox.Show("Unable to find the library: PCANBasic.dll !", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error) Environment.Exit(-1) End Try End Sub Private Sub cbbBaudrates_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbbBaudrates.SelectedIndexChanged ' Saves the current selected baudrate register code ' Select Case cbbBaudrates.SelectedIndex Case 0 m_Baudrate = TPCANBaudrate.PCAN_BAUD_1M Exit Select Case 1 m_Baudrate = TPCANBaudrate.PCAN_BAUD_800K Exit Select Case 2 m_Baudrate = TPCANBaudrate.PCAN_BAUD_500K Exit Select Case 3 m_Baudrate = TPCANBaudrate.PCAN_BAUD_250K Exit Select Case 4 m_Baudrate = TPCANBaudrate.PCAN_BAUD_125K Exit Select Case 5 m_Baudrate = TPCANBaudrate.PCAN_BAUD_100K Exit Select Case 6 m_Baudrate = TPCANBaudrate.PCAN_BAUD_95K Exit Select Case 7 m_Baudrate = TPCANBaudrate.PCAN_BAUD_83K Exit Select Case 8 m_Baudrate = TPCANBaudrate.PCAN_BAUD_50K Exit Select Case 9 m_Baudrate = TPCANBaudrate.PCAN_BAUD_47K Exit Select Case 10 m_Baudrate = TPCANBaudrate.PCAN_BAUD_33K Exit Select Case 11 m_Baudrate = TPCANBaudrate.PCAN_BAUD_20K Exit Select Case 12 m_Baudrate = TPCANBaudrate.PCAN_BAUD_10K Exit Select Case 13 m_Baudrate = TPCANBaudrate.PCAN_BAUD_5K Exit Select End Select End Sub Private Sub cbbHwType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbbHwType.SelectedIndexChanged ' Saves the current type for a no-Plug&Play hardware ' Select Case cbbHwType.SelectedIndex Case 0 m_HwType = TPCANType.PCAN_TYPE_ISA Exit Select Case 1 m_HwType = TPCANType.PCAN_TYPE_ISA_SJA Exit Select Case 2 m_HwType = TPCANType.PCAN_TYPE_ISA_PHYTEC Exit Select Case 3 m_HwType = TPCANType.PCAN_TYPE_DNG Exit Select Case 4 m_HwType = TPCANType.PCAN_TYPE_DNG_EPP Exit Select Case 5 m_HwType = TPCANType.PCAN_TYPE_DNG_SJA Exit Select Case 6 m_HwType = TPCANType.PCAN_TYPE_DNG_SJA_EPP Exit Select End Select End Sub Private Sub btnRelease_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRelease.Click ' Releases a current connected PCAN-Basic channel ' PCANBasic.Uninitialize(m_PcanHandle) tmrRead.Enabled = False If m_ReadThread IsNot Nothing Then m_ReadThread.Abort() m_ReadThread.Join() m_ReadThread = Nothing End If ' Sets the connection status of the main-form ' SetConnectionStatus(False) End Sub Private Sub chbFilterExt_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbFilterExt.CheckedChanged Dim iMaxValue As Integer iMaxValue = IIf((chbFilterExt.Checked), &H1FFFFFFF, &H7FF) ' We check that the maximum value for a selected filter ' mode is used ' If nudIdTo.Value > iMaxValue Then nudIdTo.Value = iMaxValue End If nudIdTo.Maximum = iMaxValue End Sub Private Sub btnFilterApply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFilterApply.Click Dim iBuffer As UInt32 Dim stsResult As TPCANStatus ' Gets the current status of the message filter ' If Not GetFilterStatus(iBuffer) Then Return End If ' Configures the message filter for a custom range of messages ' If rdbFilterCustom.Checked Then ' Sets the custom filter ' stsResult = PCANBasic.FilterMessages(m_PcanHandle, Convert.ToUInt32(nudIdFrom.Value), Convert.ToUInt32(nudIdTo.Value), IIf(chbFilterExt.Checked, TPCANMode.PCAN_MODE_EXTENDED, TPCANMode.PCAN_MODE_STANDARD)) ' If success, an information message is written, if it is not, an error message is shown ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The filter was customized. IDs from {0:X} to {1:X} will be received", nudIdFrom.Text, nudIdTo.Text)) Else MessageBox.Show(GetFormatedError(stsResult)) End If Return End If ' The filter will be full opened or complete closed ' If rdbFilterClose.Checked Then iBuffer = PCANBasic.PCAN_FILTER_CLOSE Else iBuffer = PCANBasic.PCAN_FILTER_OPEN End If ' The filter is configured ' stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_MESSAGE_FILTER, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) ' If success, an information message is written, if it is not, an error message is shown ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The filter was successfully {0}", IIf(rdbFilterClose.Checked, "closed.", "opened."))) Else MessageBox.Show(GetFormatedError(stsResult)) End If End Sub Private Sub btnFilterQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFilterQuery.Click Dim iBuffer As UInt32 ' Queries the current status of the message filter ' If GetFilterStatus(iBuffer) Then Select Case iBuffer ' The filter is closed ' Case PCANBasic.PCAN_FILTER_CLOSE IncludeTextMessage("The Status of the filter is: closed.") Exit Select ' The filter is fully opened ' Case PCANBasic.PCAN_FILTER_OPEN IncludeTextMessage("The Status of the filter is: full opened.") Exit Select ' The filter is customized ' Case PCANBasic.PCAN_FILTER_CUSTOM IncludeTextMessage("The Status of the filter is: customized.") Exit Select Case Else ' The status of the filter is undefined. (Should never happen) ' IncludeTextMessage("The Status of the filter is: Invalid.") Exit Select End Select End If End Sub Private Sub cbbParameter_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbbParameter.SelectedIndexChanged ' Activates/deactivates controls according with the selected ' PCAN-Basic parameter ' rdbParamActive.Enabled = TryCast(sender, ComboBox).SelectedIndex <> 0 rdbParamInactive.Enabled = rdbParamActive.Enabled nudDeviceId.Enabled = Not rdbParamActive.Enabled End Sub Private Sub btnParameterSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParameterSet.Click Dim stsResult As TPCANStatus Dim iBuffer As UInt32 Dim bActivate As Boolean bActivate = rdbParamActive.Checked ' Sets a PCAN-Basic parameter value ' Select Case cbbParameter.SelectedIndex ' The Device-Number of an USB channel will be set ' Case 0 iBuffer = Convert.ToUInt32(nudDeviceId.Value) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_DEVICE_NUMBER, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("The desired Device-Number was successfully configured") End If Exit Select ' The 5 Volt Power feature of a PC-card or USB will be set ' Case 1 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_5VOLTS_POWER, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The USB/PC-Card 5 power was successfully {0}", IIf(bActivate, "activated", "deactivated"))) End If Exit Select ' The feature for automatic reset on BUS-OFF will be set ' Case 2 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_BUSOFF_AUTORESET, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The automatic-reset on BUS-OFF was successfully {0}", IIf(bActivate, "activated", "deactivated"))) End If Exit Select ' The CAN option "Listen Only" will be set ' Case 3 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_LISTEN_ONLY, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The CAN option ""Listen Only"" was successfully {0}", IIf(bActivate, "activated", "deactivated"))) End If Exit Select ' The feature for logging debug-information will be set ' Case 4 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_LOG_STATUS, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The feature for logging debug information was successfully {0}", IIf(bActivate, "activated", "deactivated"))) End If Exit Select ' The channel option "Receive Status" will be set ' Case 5 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_RECEIVE_STATUS, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The channel option ""Receive Status"" was set to {0}", IIf(bActivate, "ON", "OFF"))) End If Exit Select ' The feature for tracing will be set ' Case 7 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_STATUS, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The feature for tracing data was successfully {0}", IIf(bActivate, "activated", "deactivated"))) End If Exit Select ' The feature for identifying an USB Channel will be set ' Case 8 iBuffer = CUInt((IIf(bActivate, PCANBasic.PCAN_PARAMETER_ON, PCANBasic.PCAN_PARAMETER_OFF))) stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_CHANNEL_IDENTIFYING, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The procedure for channel identification was successfully {0}", IIf(bActivate, "activated", "deactivated"))) End If Exit Select Case Else ' The current parameter is invalid ' stsResult = TPCANStatus.PCAN_ERROR_UNKNOWN MessageBox.Show("Wrong parameter code.") Return End Select ' If the function fail, an error message is shown ' If stsResult <> TPCANStatus.PCAN_ERROR_OK Then MessageBox.Show(GetFormatedError(stsResult)) End If End Sub Private Sub btnParameterGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParameterGet.Click Dim stsResult As TPCANStatus Dim iBuffer As UInt32 ' Gets a PCAN-Basic parameter value ' Select Case cbbParameter.SelectedIndex ' The Device-Number of an USB channel will be retrieved ' Case 0 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_DEVICE_NUMBER, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The configured Device-Number is {0:X}", iBuffer)) End If Exit Select ' The activation status of the 5 Volt Power feature of a PC-card or USB will be retrieved ' Case 1 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_5VOLTS_POWER, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The 5-Volt Power of the USB/PC-Card is {0:X}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select ' The activation status of the feature for automatic reset on BUS-OFF will be retrieved ' Case 2 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_BUSOFF_AUTORESET, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The automatic-reset on BUS-OFF is {0:X}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select ' The activation status of the CAN option "Listen Only" will be retrieved ' Case 3 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_LISTEN_ONLY, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The CAN option ""Listen Only"" is {0:X}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select ' The activation status for the feature for logging debug-information will be retrieved Case 4 stsResult = PCANBasic.GetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_LOG_STATUS, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The feature for logging debug information is {0:X}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select ' The activation status of the channel option "Receive Status" will be retrieved ' Case 5 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_RECEIVE_STATUS, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The channel option ""Receive Status"" is {0}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select ' The Number of the CAN-Controller used by a PCAN-Channel ' Case 6 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_CONTROLLER_NUMBER, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The CAN Controller number is {0}", iBuffer)) End If Exit Select ' The activation status for the feature for tracing data will be retrieved ' Case 7 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_STATUS, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The feature for tracing data is {0}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select ' The activation status of the Channel Identifying procedure will be retrieved ' Case 8 stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_CHANNEL_IDENTIFYING, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(String.Format("The identification procedure of the selected channel is {0}", IIf((iBuffer = PCANBasic.PCAN_PARAMETER_ON), "ON", "OFF"))) End If Exit Select Case Else ' The current parameter is invalid ' stsResult = TPCANStatus.PCAN_ERROR_UNKNOWN MessageBox.Show("Wrong parameter code.") Return End Select ' If the function fail, an error message is shown ' If stsResult <> TPCANStatus.PCAN_ERROR_OK Then MessageBox.Show(GetFormatedError(stsResult)) End If End Sub Private Sub rdbTimer_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbTimer.CheckedChanged, rdbManual.CheckedChanged, rdbEvent.CheckedChanged ''Checks Form Initialization is complete ' If Not isFormInitCompleted Then ' Return ' End If If Not btnRelease.Enabled Then Return End If ' According with the kind of reading, a timer, a thread or a button will be enabled ' If rdbTimer.Checked Then ' Abort Read Thread if it exists ' If m_ReadThread IsNot Nothing Then m_ReadThread.Abort() m_ReadThread.Join() m_ReadThread = Nothing End If ' Enable Timer ' tmrRead.Enabled = btnRelease.Enabled End If If rdbEvent.Checked Then ' Disable Timer ' tmrRead.Enabled = False ' Create and start the tread to read CAN Message using SetRcvEvent() ' Dim threadDelegate As New System.Threading.ThreadStart(AddressOf Me.CANReadThreadFunc) m_ReadThread = New System.Threading.Thread(threadDelegate) m_ReadThread.IsBackground = True m_ReadThread.Start() End If If rdbManual.Checked Then ' Abort Read Thread if it exists ' If m_ReadThread IsNot Nothing Then m_ReadThread.Abort() m_ReadThread.Join() m_ReadThread = Nothing End If ' Disable Timer ' tmrRead.Enabled = False btnRead.Enabled = btnRelease.Enabled AndAlso rdbManual.Checked End If End Sub Private Sub chbShowPeriod_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbShowPeriod.CheckedChanged ' According with the check-value of this checkbox, ' the recieved time of a messages will be interpreted as ' period (time between the two last messages) or as time-stamp ' (the elapsed time since windows was started) ' SyncLock m_LastMsgsList.SyncRoot For Each msg As MessageStatus In m_LastMsgsList msg.ShowingPeriod = chbShowPeriod.Checked Next End SyncLock End Sub Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click Dim CANMsg As TPCANMsg = Nothing Dim CANTimeStamp As TPCANTimestamp Dim stsResult As TPCANStatus ' We execute the "Read" function of the PCANBasic ' stsResult = PCANBasic.Read(m_PcanHandle, CANMsg, CANTimeStamp) If stsResult = TPCANStatus.PCAN_ERROR_OK Then ' We show the received message ' ProcessMessage(CANMsg, CANTimeStamp) Else ' If an error occurred, an information message is included ' IncludeTextMessage(GetFormatedError(stsResult)) End If End Sub Private Sub btnMsgClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMsgClear.Click ' The information contained in the messages List-View ' is cleared ' SyncLock m_LastMsgsList.SyncRoot lstMessages.Items.Clear() m_LastMsgsList.Clear() End SyncLock End Sub Private Sub txtID_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtID.KeyPress, txtData7.KeyPress, txtData6.KeyPress, txtData5.KeyPress, txtData4.KeyPress, txtData3.KeyPress, txtData2.KeyPress, txtData1.KeyPress, txtData0.KeyPress Dim chCheck As Int16 ' We convert the Character to its Upper case equivalent ' chCheck = Microsoft.VisualBasic.Asc(e.KeyChar.ToString().ToUpper()) ' The Key is the Delete (Backspace) Key ' If chCheck = 8 Then Return End If ' The Key is a number between 0-9 ' If (chCheck > 47) AndAlso (chCheck < 58) Then Return End If ' The Key is a character between A-F ' If (chCheck > 64) AndAlso (chCheck < 71) Then Return End If ' Is neither a number nor a character between A(a) and F(f) ' e.Handled = True End Sub Private Sub txtID_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtID.Leave Dim iTextLength As Integer Dim uiMaxValue As UInteger ' Calculates the text length and Maximum ID value according ' with the Message Type ' iTextLength = IIf((chbExtended.Checked), 8, 3) uiMaxValue = IIf((chbExtended.Checked), CUInt(&H1FFFFFFF), CUInt(&H7FF)) ' The Textbox for the ID is represented with 3 characters for ' Standard and 8 characters for extended messages. ' Therefore if the Length of the text is smaller than TextLength, ' we add "0" ' While txtID.Text.Length <> iTextLength txtID.Text = ("0" & txtID.Text) End While ' We check that the ID is not bigger than current maximum value ' If Convert.ToUInt32(txtID.Text, 16) > uiMaxValue Then txtID.Text = String.Format("{0:X" & iTextLength.ToString() & "}", uiMaxValue) End If End Sub Private Sub chbExtended_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbExtended.CheckedChanged Dim uiTemp As UInteger txtID.MaxLength = IIf((chbExtended.Checked), 8, 3) ' the only way that the text length can be bigger als MaxLength ' is when the change is from Extended to Standard message Type. ' We have to handle this and set an ID not bigger than the Maximum ' ID value for a Standard Message (0x7FF) ' If txtID.Text.Length > txtID.MaxLength Then uiTemp = Convert.ToUInt32(txtID.Text, 16) txtID.Text = IIf((uiTemp < &H7FF), String.Format("{0:X3}", uiTemp), "7FF") End If txtID_Leave(Me, New EventArgs()) End Sub Private Sub chbRemote_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbRemote.CheckedChanged Dim txtbCurrentTextBox As TextBox txtbCurrentTextBox = txtData0 ' If the message is a RTR, no data is sent. The textbox for data ' will be turned invisible ' For i As Integer = 0 To 7 txtbCurrentTextBox.Visible = Not chbRemote.Checked If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End Sub Private Sub txtData0_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtData7.Leave, txtData6.Leave, txtData5.Leave, txtData4.Leave, txtData3.Leave, txtData2.Leave, txtData1.Leave, txtData0.Leave Dim txtbCurrentTextbox As TextBox ' all the Textbox Data fields are represented with 2 characters. ' Therefore if the Length of the text is smaller than 2, we add ' a "0" ' If sender.[GetType]().Name = "TextBox" Then txtbCurrentTextbox = DirectCast(sender, TextBox) While txtbCurrentTextbox.Text.Length <> 2 txtbCurrentTextbox.Text = ("0" & txtbCurrentTextbox.Text) End While End If End Sub Private Sub btnWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWrite.Click Dim CANMsg As TPCANMsg Dim txtbCurrentTextBox As TextBox Dim stsResult As TPCANStatus ' We create a TCLightMsg message structure ' CANMsg = New TPCANMsg() CANMsg.DATA = New Byte(7) {} ' We configurate the Message. The ID (max 0x1FF), ' Length of the Data, Message Type (Standard in ' this example) and die data ' CANMsg.ID = Convert.ToUInt32(txtID.Text, 16) CANMsg.LEN = Convert.ToByte(nudLength.Value) CANMsg.MSGTYPE = IIf((chbExtended.Checked), TPCANMessageType.PCAN_MESSAGE_EXTENDED, TPCANMessageType.PCAN_MESSAGE_STANDARD) ' If a remote frame will be sent, the data bytes are not important. ' If chbRemote.Checked Then CANMsg.MSGTYPE = CANMsg.MSGTYPE Or TPCANMessageType.PCAN_MESSAGE_RTR Else ' We get so much data as the Len of the message ' txtbCurrentTextBox = txtData0 For i As Integer = 0 To CANMsg.LEN - 1 CANMsg.DATA(i) = Convert.ToByte(txtbCurrentTextBox.Text, 16) If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End If ' The message is sent to the configured hardware ' stsResult = PCANBasic.Write(m_PcanHandle, CANMsg) ' The Hardware was successfully sent ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("Message was successfully SENT") Else ' An error occurred. We show the error. ' MessageBox.Show(GetFormatedError(stsResult)) End If ''Check for faults txtID.Text = "10051112" autoSend() End Sub Private Sub btnGetVersions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetVersions.Click Dim stsResult As TPCANStatus Dim strTemp As StringBuilder Dim strArrayVersion As String() strTemp = New StringBuilder(256) ' We get the vesion of the PCAN-Basic API ' stsResult = PCANBasic.GetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_API_VERSION, strTemp, 256) If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("API Version: " & strTemp.ToString()) ' We get the driver version of the channel being used ' stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_CHANNEL_VERSION, strTemp, 256) If stsResult = TPCANStatus.PCAN_ERROR_OK Then ' Because this information contains line control characters (several lines) ' we split this also in several entries in the Information List-Box ' strArrayVersion = strTemp.ToString().Split(New Char() {ControlChars.Lf}) IncludeTextMessage("Channel/Driver Version: ") For i As Integer = 0 To strArrayVersion.Length - 1 IncludeTextMessage(" * " & strArrayVersion(i)) Next End If End If ' If an error ccurred, a message is shown ' If stsResult <> TPCANStatus.PCAN_ERROR_OK Then MessageBox.Show(GetFormatedError(stsResult)) End If IncludeTextMessage("K & S Home Grown Controllor Version: 1") IncludeTextMessage("AstrodynTDI SW#: T100106228-LF") IncludeTextMessage("Based on PCANBasic Example, Peak Systems") IncludeTextMessage("Released By: Joe Lockhart 4/09/2015") End Sub Private Sub btnInfoClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInfoClear.Click ' The information contained in the Information List-Box ' is cleared lbxInfo.Items.Clear() End Sub Private Sub Form_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing ' Releases the used PCAN-Basic channel ' PCANBasic.Uninitialize(m_PcanHandle) End Sub Private Sub tmrRead_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrRead.Tick '' Checks if in the receive-queue are currently messages for read ReadMessages() End Sub Private Sub tmrDisplay_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDisplay.Tick DisplayMessages() End Sub Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load chbShowPeriod.Checked = True rdbParamActive.Checked = True rdbTimer.Checked = True rdbFilterOpen.Checked = True 'Setup page Auto btnInit_Click(sender, e) btnFilterApply_Click(sender, e) chbExtended.CheckState = CheckState.Checked End Sub Private Sub lstMessages_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstMessages.DoubleClick ' Clears the content of the Message List-View ' btnMsgClear_Click(Me, New EventArgs()) End Sub Private Sub lbxInfo_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbxInfo.DoubleClick ' Clears the content of the Information List-Box ' btnInfoClear_Click(Me, New EventArgs()) End Sub #End Region #Region "Help functions" ''' <summary> ''' Initialization of PCAN-Basic components ''' </summary> Private Sub InitializeBasicComponents() ' Creates the list for received messages ' m_LastMsgsList = New System.Collections.ArrayList() ' Creates the delegate used for message reading ' m_ReadDelegate = New ReadDelegateHandler(AddressOf ReadMessages) ' Creates the event used for signalize incomming messages ' m_ReceiveEvent = New System.Threading.AutoResetEvent(False) ' Creates an array with all possible PCAN-Channels ' m_HandlesArray = New TPCANHandle() {PCANBasic.PCAN_ISABUS1, PCANBasic.PCAN_ISABUS2, PCANBasic.PCAN_ISABUS3, PCANBasic.PCAN_ISABUS4, PCANBasic.PCAN_ISABUS5, PCANBasic.PCAN_ISABUS6, _ PCANBasic.PCAN_ISABUS7, PCANBasic.PCAN_ISABUS8, PCANBasic.PCAN_DNGBUS1, PCANBasic.PCAN_PCIBUS1, PCANBasic.PCAN_PCIBUS2, PCANBasic.PCAN_PCIBUS3, _ PCANBasic.PCAN_PCIBUS4, PCANBasic.PCAN_PCIBUS5, PCANBasic.PCAN_PCIBUS6, PCANBasic.PCAN_PCIBUS7, PCANBasic.PCAN_PCIBUS8, PCANBasic.PCAN_USBBUS1, _ PCANBasic.PCAN_USBBUS2, PCANBasic.PCAN_USBBUS3, PCANBasic.PCAN_USBBUS4, PCANBasic.PCAN_USBBUS5, PCANBasic.PCAN_USBBUS6, PCANBasic.PCAN_USBBUS7, _ PCANBasic.PCAN_USBBUS8, PCANBasic.PCAN_PCCBUS1, PCANBasic.PCAN_PCCBUS2} ' Fills and configures the Data of several comboBox components ' FillComboBoxData() ' Prepares the PCAN-Basic's debug-Log file ' ConfigureLogFile() End Sub ''' <summary> ''' Configures the Debug-Log file of PCAN-Basic ''' </summary> Private Sub ConfigureLogFile() Dim iBuffer As UInt32 ' Sets the mask to catch all events ' iBuffer = PCANBasic.LOG_FUNCTION_ALL ' Configures the log file. ' NOTE: The Log capability is to be used with the NONEBUS Handle. Other handle than this will ' cause the function fail. ' PCANBasic.SetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_LOG_CONFIGURE, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) End Sub ''' <summary> ''' Configures the Debug-Log file of PCAN-Basic ''' </summary> Private Sub ConfigureTraceFile() Dim iBuffer As UInt32 Dim stsResult As TPCANStatus ' Configure the maximum size of a trace file to 5 megabytes ' iBuffer = 5 stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_SIZE, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult <> TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(GetFormatedError(stsResult)) End If ' Configure the way how trace files are created: ' * Standard name is used ' * Existing file is ovewritten, ' * Only one file is created. ' * Recording stopts when the file size reaches 5 megabytes. ' iBuffer = PCANBasic.TRACE_FILE_SINGLE Or PCANBasic.TRACE_FILE_OVERWRITE stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_CONFIGURE, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult <> TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage(GetFormatedError(stsResult)) End If End Sub ''' <summary> ''' Help Function used to get an error as text ''' </summary> ''' <param name="error">Error code to be translated</param> ''' <returns>A text with the translated error</returns> Private Function GetFormatedError(ByVal [error] As TPCANStatus) As String Dim strTemp As StringBuilder ' Creates a buffer big enough for a error-text ' strTemp = New StringBuilder(256) ' Gets the text using the GetErrorText API function ' If the function success, the translated error is returned. If it fails, ' a text describing the current error is returned. ' If PCANBasic.GetErrorText([error], 0, strTemp) <> TPCANStatus.PCAN_ERROR_OK Then Return String.Format("An error occurred. Error-code's text ({0:X}) couldn't be retrieved", [error]) Else Return strTemp.ToString() End If End Function ''' <summary> ''' Includes a new line of text into the information Listview ''' </summary> ''' <param name="strMsg">Text to be included</param> Private Sub IncludeTextMessage(ByVal strMsg As String) lbxInfo.Items.Add(strMsg) lbxInfo.SelectedIndex = lbxInfo.Items.Count - 1 End Sub ''' <summary> ''' Gets the current status of the PCAN-Basic message filter ''' </summary> ''' <param name="status">Buffer to retrieve the filter status</param> ''' <returns>If calling the function was successfull or not</returns> Private Function GetFilterStatus(ByRef status As UInteger) As Boolean Dim stsResult As TPCANStatus ' Tries to get the sttaus of the filter for the current connected hardware ' stsResult = PCANBasic.GetValue(m_PcanHandle, TPCANParameter.PCAN_MESSAGE_FILTER, status, CType(System.Runtime.InteropServices.Marshal.SizeOf(status), UInteger)) ' If it fails, a error message is shown ' If stsResult <> TPCANStatus.PCAN_ERROR_OK Then MessageBox.Show(GetFormatedError(stsResult)) Return False End If Return True End Function ''' <summary> ''' Configures the data of all ComboBox components of the main-form ''' </summary> Private Sub FillComboBoxData() ' Channels will be check ' btnHwRefresh_Click(Me, New EventArgs()) ' Baudrates ' cbbBaudrates.SelectedIndex = 2 ' 500 K ' Hardware Type for no plugAndplay hardware ' cbbHwType.SelectedIndex = 0 ' Interrupt for no plugAndplay hardware ' cbbInterrupt.SelectedIndex = 0 ' IO Port for no plugAndplay hardware ' cbbIO.SelectedIndex = 0 ' Parameters for GetValue and SetValue function calls ' cbbParameter.SelectedIndex = 0 End Sub ''' <summary> ''' Activates/deaactivates the different controls of the main-form according ''' with the current connection status ''' </summary> ''' <param name="bConnected">Current status. True if connected, false otherwise</param> Private Sub SetConnectionStatus(ByVal bConnected As Boolean) ' Buttons ' btnInit.Enabled = Not bConnected btnRead.Enabled = bConnected AndAlso rdbManual.Checked btnWrite.Enabled = bConnected btnRelease.Enabled = bConnected btnFilterApply.Enabled = bConnected btnFilterQuery.Enabled = bConnected btnParameterSet.Enabled = bConnected btnParameterGet.Enabled = bConnected btnGetVersions.Enabled = bConnected btnHwRefresh.Enabled = Not bConnected btnStatus.Enabled = bConnected btnReset.Enabled = bConnected ' ComboBoxs ' cbbBaudrates.Enabled = Not bConnected cbbChannel.Enabled = Not bConnected cbbHwType.Enabled = Not bConnected cbbIO.Enabled = Not bConnected cbbInterrupt.Enabled = Not bConnected ' Hardware configuration and read mode ' If Not bConnected Then cbbChannel_SelectedIndexChanged(Me, New EventArgs()) Else rdbTimer_CheckedChanged(Me, New EventArgs()) End If ' Display messages in grid ' tmrDisplay.Enabled = bConnected End Sub ''' <summary> ''' Gets the formated text for a CPAN-Basic channel handle ''' </summary> ''' <param name="handle">PCAN-Basic Handle to format</param> ''' <returns>The formatted text for a channel</returns> Private Function FormatChannelName(ByVal handle As TPCANHandle) As String Dim devDevice As TPCANDevice Dim byChannel As Byte ' Gets the owner device and channel for a ' PCAN-Basic handle ' devDevice = DirectCast((handle >> 4), TPCANDevice) byChannel = CByte((handle And &HF)) ' Constructs the PCAN-Basic Channel name and return it ' Return String.Format("{0} {1} ({2:X2}h)", devDevice, byChannel, handle) End Function #End Region #Region "Message-proccessing functions" ''' <summary> ''' Display CAN messages in the Message-ListView ''' </summary> Private Sub DisplayMessages() Dim lviCurrentItem As ListViewItem SyncLock m_LastMsgsList.SyncRoot For Each msgStatus As MessageStatus In m_LastMsgsList ' Get the data to actualize ' If msgStatus.MarkedAsUpdated Then msgStatus.MarkedAsUpdated = False lviCurrentItem = lstMessages.Items(msgStatus.Position) lviCurrentItem.SubItems(2).Text = msgStatus.CANMsg.LEN.ToString() lviCurrentItem.SubItems(3).Text = msgStatus.DataString lviCurrentItem.SubItems(4).Text = msgStatus.Count.ToString() lviCurrentItem.SubItems(5).Text = msgStatus.TimeString 'Check for faults If msgStatus.CANMsg.DATA(0) = CByte(3) Then rdIHFLTCON.Checked = True rdBBHCON.Checked = True rdIHFLTCON.ForeColor = Color.DarkRed rdBBHCON.ForeColor = Color.DarkRed IncludeTextMessage("Bond Heater and Index Heater NOT CONNECTED!") ElseIf msgStatus.CANMsg.DATA(0) = CByte(1) Then rdIHFLTCON.Checked = False rdBBHCON.Checked = True rdIHFLTCON.ForeColor = Color.MediumSeaGreen rdBBHCON.ForeColor = Color.DarkRed IncludeTextMessage("Bond Head Heater in Fault Condition!") ElseIf msgStatus.CANMsg.DATA(0) = CByte(2) Then rdIHFLTCON.Checked = True rdBBHCON.Checked = False rdIHFLTCON.ForeColor = Color.DarkRed rdBBHCON.ForeColor = Color.MediumSeaGreen IncludeTextMessage("Index Heater in Fault Condition!") ElseIf msgStatus.CANMsg.DATA(0) = CByte(0) Then rdIHFLTCON.Checked = False rdBBHCON.Checked = False rdIHFLTCON.ForeColor = Color.MediumSeaGreen rdBBHCON.ForeColor = Color.MediumSeaGreen End If End If Next End SyncLock End Sub ''' <summary> ''' Inserts a new entry for a new message in the Message-ListView ''' </summary> ''' <param name="newMsg">The messasge to be inserted</param> ''' <param name="timeStamp">The Timesamp of the new message</param> Private Sub InsertMsgEntry(ByVal newMsg As TPCANMsg, ByVal timeStamp As TPCANTimestamp) Dim lviCurrentItem As ListViewItem Dim msgStsCurrentMsg As MessageStatus SyncLock m_LastMsgsList.SyncRoot ' We add this status in the last message list ' msgStsCurrentMsg = New MessageStatus(newMsg, timeStamp, lstMessages.Items.Count) m_LastMsgsList.Add(msgStsCurrentMsg) ' Add the new ListView Item with the Type of the message ' lviCurrentItem = lstMessages.Items.Add(msgStsCurrentMsg.TypeString) ' We set the ID of the message ' lviCurrentItem.SubItems.Add(msgStsCurrentMsg.IdString) ' We set the length of the Message ' lviCurrentItem.SubItems.Add(newMsg.LEN.ToString()) ' We set the data of the message. ' lviCurrentItem.SubItems.Add(msgStsCurrentMsg.DataString) ' we set the message count message (this is the First, so count is 1) ' lviCurrentItem.SubItems.Add(msgStsCurrentMsg.Count.ToString()) ' Add time stamp information if needed ' lviCurrentItem.SubItems.Add(msgStsCurrentMsg.TimeString) End SyncLock End Sub ''' <summary> ''' Processes a received message, in order to show it in the Message-ListView ''' </summary> ''' <param name="theMsg">The received PCAN-Basic message</param> ''' <param name="itsTimeStamp">The Timestamp of the received message</param> Private Sub ProcessMessage(ByVal theMsg As TPCANMsg, ByVal itsTimeStamp As TPCANTimestamp) ' We search if a message (Same ID and Type) is ' already received or if this is a new message ' SyncLock m_LastMsgsList.SyncRoot For Each msg As MessageStatus In m_LastMsgsList If (msg.CANMsg.ID = theMsg.ID) And (msg.CANMsg.MSGTYPE = theMsg.MSGTYPE) Then ' Messages of this kind are already received; we do an update ' msg.Update(theMsg, itsTimeStamp) Exit Sub End If Next ' Message not found. It will created ' InsertMsgEntry(theMsg, itsTimeStamp) End SyncLock End Sub ''' <summary> ''' Thread-Function used for reading PCAN-Basic messages ''' </summary> Private Sub CANReadThreadFunc() Dim iBuffer As UInt32 Dim stsResult As TPCANStatus iBuffer = Convert.ToUInt32(m_ReceiveEvent.SafeWaitHandle.DangerousGetHandle().ToInt32()) ' Sets the handle of the Receive-Event. ' stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_RECEIVE_EVENT, iBuffer, CType(System.Runtime.InteropServices.Marshal.SizeOf(iBuffer), UInteger)) If stsResult <> TPCANStatus.PCAN_ERROR_OK Then MessageBox.Show(GetFormatedError(stsResult), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error) Return End If ' While this mode is selected While rdbEvent.Checked ' Waiting for Receive-Event ' If m_ReceiveEvent.WaitOne(50) Then ' Process Receive-Event using .NET Invoke function ' in order to interact with Winforms UI (calling the ' function ReadMessages) ' Me.Invoke(m_ReadDelegate) End If End While End Sub ''' <summary> ''' Function for reading PCAN-Basic messages ''' </summary> Private Sub ReadMessages() Dim CANMsg As TPCANMsg = Nothing Dim CANTimeStamp As TPCANTimestamp Dim stsResult As TPCANStatus ' We read at least one time the queue looking for messages. ' If a message is found, we look again trying to find more. ' If the queue is empty or an error occurr, we get out from ' the dowhile statement. ' Do ' We execute the "Read" function of the PCANBasic ' stsResult = PCANBasic.Read(m_PcanHandle, CANMsg, CANTimeStamp) ' A message was received ' We process the message(s) ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then ProcessMessage(CANMsg, CANTimeStamp) End If Loop While btnRelease.Enabled AndAlso (Not Convert.ToBoolean(stsResult And TPCANStatus.PCAN_ERROR_QRCVEMPTY)) End Sub #End Region #End Region Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click Dim stsResult As TPCANStatus ' Resets the receive and transmit queues of a PCAN Channel. ' stsResult = PCANBasic.Reset(m_PcanHandle) ' If it fails, a error message is shown ' If (stsResult <> TPCANStatus.PCAN_ERROR_OK) Then MessageBox.Show(GetFormatedError(stsResult)) Else IncludeTextMessage("Receive and transmit queues successfully reset") End If End Sub Private Sub btnStatus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStatus.Click Dim stsResult As TPCANStatus Dim errorName As String ' Gets the current BUS status of a PCAN Channel. ' stsResult = PCANBasic.GetStatus(m_PcanHandle) ' Switch On Error Name ' Select Case stsResult Case TPCANStatus.PCAN_ERROR_INITIALIZE errorName = "PCAN_ERROR_INITIALIZE" Exit Select Case TPCANStatus.PCAN_ERROR_BUSLIGHT errorName = "PCAN_ERROR_BUSLIGHT" Exit Select Case TPCANStatus.PCAN_ERROR_BUSHEAVY errorName = "PCAN_ERROR_BUSHEAVY" Exit Select Case TPCANStatus.PCAN_ERROR_BUSOFF errorName = "PCAN_ERROR_BUSOFF" Exit Select Case TPCANStatus.PCAN_ERROR_OK errorName = "PCAN_ERROR_OK" Exit Select Case Else errorName = "See Documentation" Exit Select End Select ' Display Message ' IncludeTextMessage(String.Format("Status: {0} ({1:X}h)", errorName, stsResult)) End Sub Private Sub CmBBond_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CmBBond.SelectedIndexChanged If CmBBond.Text = "Duty Cycle Adjust" Then chbExtended.CheckState = CheckState.Checked txtID.Text = "10011112" End If If CmBBond.Text = "CAN Reset" Then chbExtended.CheckState = CheckState.Checked txtID.Text = "10021112" End If 'If CmBBond.Text = "ALL Digital I/O Pins ON (PWM)" Then txtID.Text = "10031112" 'If CmBBond.Text = "ALL Digital I/O Pins OFF (PWM)" Then txtID.Text = "10031112" 'If CmBBond.Text = "Duty Cycle Adjust" Then txtID.Text = "10011112" End Sub Private Sub CmbBHHCHN_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CmbBHHCHN.SelectedIndexChanged If CmbBHHCHN.Text = "Channel 1=Output 1A" Then txtData0.Text = Hex(16) If CmbBHHCHN.Text = "Channel 2=Output 1B" Then txtData0.Text = Hex(17) If CmbBHHCHN.Text = "Channel 3=Output 2A" Then txtData0.Text = Hex(18) If CmbBHHCHN.Text = "Channel 4=Output 2B" Then txtData0.Text = Hex(19) End Sub Private Sub txtBHHDC_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtBHHDC.TextChanged If txtBHHDC.Text = "" Then Exit Sub txtData1.Text = Hex(txtBHHDC.Text) 'End If End Sub Private Sub CmBIond_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CmBIond.SelectedIndexChanged If CmBIond.Text = "Duty Cycle Adjust" Then chbExtended.CheckState = CheckState.Checked txtID.Text = "10011112" End If If CmBIond.Text = "CAN Reset" Then chbExtended.CheckState = CheckState.Checked txtID.Text = "10021112" End If End Sub Private Sub CmbIHCHN_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CmbIHCHN.SelectedIndexChanged If CmbIHCHN.Text = "Channel 1" Then txtData0.Text = Hex(0) If CmbIHCHN.Text = "Channel 2" Then txtData0.Text = Hex(1) If CmbIHCHN.Text = "Channel 3" Then txtData0.Text = Hex(2) If CmbIHCHN.Text = "Channel 4" Then txtData0.Text = Hex(3) If CmbIHCHN.Text = "Channel 5" Then txtData0.Text = Hex(4) If CmbIHCHN.Text = "Channel 6" Then txtData0.Text = Hex(5) If CmbIHCHN.Text = "Channel 7" Then txtData0.Text = Hex(6) If CmbIHCHN.Text = "Channel 8" Then txtData0.Text = Hex(7) If CmbIHCHN.Text = "Channel 9" Then txtData0.Text = Hex(8) If CmbIHCHN.Text = "Channel 10" Then txtData0.Text = Hex(9) If CmbIHCHN.Text = "Channel 11" Then txtData0.Text = Hex(10) If CmbIHCHN.Text = "Channel 12" Then txtData0.Text = Hex(11) If CmbIHCHN.Text = "Channel 13" Then txtData0.Text = Hex(12) If CmbIHCHN.Text = "Channel 14" Then txtData0.Text = Hex(13) If CmbIHCHN.Text = "Channel 15" Then txtData0.Text = Hex(14) If CmbIHCHN.Text = "Channel 16" Then txtData0.Text = Hex(15) End Sub Private Sub txtIHDC_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtIHDC.TextChanged If txtIHDC.Text = "" Or txtIHDC.Text = "False" Then Exit Sub txtData1.Text = Hex(txtIHDC.Text) ' End If End Sub Private Sub cmdSendBHH_Click(sender As System.Object, e As System.EventArgs) Handles cmdSendBHH.Click Dim CANMsg As TPCANMsg Dim txtbCurrentTextBox As TextBox Dim stsResult As TPCANStatus ' We create a TCLightMsg message structure ' CANMsg = New TPCANMsg() CANMsg.DATA = New Byte(7) {} ' We configurate the Message. The ID (max 0x1FF), ' Length of the Data, Message Type (Standard in ' this example) and die data ' CANMsg.ID = Convert.ToUInt32(txtID.Text, 16) CANMsg.LEN = Convert.ToByte(nudLength.Value) CANMsg.MSGTYPE = IIf((chbExtended.Checked), TPCANMessageType.PCAN_MESSAGE_EXTENDED, TPCANMessageType.PCAN_MESSAGE_STANDARD) ' If a remote frame will be sent, the data bytes are not important. ' If chbRemote.Checked Then CANMsg.MSGTYPE = CANMsg.MSGTYPE Or TPCANMessageType.PCAN_MESSAGE_RTR Else ' We get so much data as the Len of the message ' txtbCurrentTextBox = txtData0 For i As Integer = 0 To CANMsg.LEN - 1 CANMsg.DATA(i) = Convert.ToByte(txtbCurrentTextBox.Text, 16) If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End If ' The message is sent to the configured hardware ' stsResult = PCANBasic.Write(m_PcanHandle, CANMsg) ' The Hardware was successfully sent ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("Message was successfully SENT " & "Duty Cycle: " & CStr(txtData1.Text) & "HEX " & CInt("&H" & txtData1.Text) & "INT") IncludeTextMessage("TO Bond Head Heater " & "Channel#: " & CInt("&H" & txtData0.Text)) Else ' An error occurred. We show the error. ' MessageBox.Show(GetFormatedError(stsResult)) End If ''Check for faults txtID.Text = "10051112" autoSend() DisplayMessages() 'txtData0.Text = "00" 'txtData1.Text = "00" txtBHHDC.Text = "" txtIHDC.Text = "" If CmBIond.Text = "Duty Cycle Adjust" Or CmBBond.Text = "Duty Cycle Adjust" Then txtID.Text = "10011112" End Sub Private Sub cmdSendIH_Click(sender As System.Object, e As System.EventArgs) Handles cmdSendIH.Click Dim CANMsg As TPCANMsg Dim txtbCurrentTextBox As TextBox Dim stsResult As TPCANStatus ' We create a TCLightMsg message structure ' CANMsg = New TPCANMsg() CANMsg.DATA = New Byte(7) {} ' We configurate the Message. The ID (max 0x1FF), ' Length of the Data, Message Type (Standard in ' this example) and die data ' CANMsg.ID = Convert.ToUInt32(txtID.Text, 16) CANMsg.LEN = Convert.ToByte(nudLength.Value) CANMsg.MSGTYPE = IIf((chbExtended.Checked), TPCANMessageType.PCAN_MESSAGE_EXTENDED, TPCANMessageType.PCAN_MESSAGE_STANDARD) ' If a remote frame will be sent, the data bytes are not important. ' If chbRemote.Checked Then CANMsg.MSGTYPE = CANMsg.MSGTYPE Or TPCANMessageType.PCAN_MESSAGE_RTR Else ' We get so much data as the Len of the message ' txtbCurrentTextBox = txtData0 For i As Integer = 0 To CANMsg.LEN - 1 CANMsg.DATA(i) = Convert.ToByte(txtbCurrentTextBox.Text, 16) If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End If ' The message is sent to the configured hardware ' stsResult = PCANBasic.Write(m_PcanHandle, CANMsg) ' The Hardware was successfully sent ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("Message was successfully SENT " & "Duty Cycle: " & CStr(txtData1.Text) & "HEX " & CInt("&H" & txtData1.Text) & "INT") IncludeTextMessage("TO Index Heater " & "Channel#: " & CInt("&H" & txtData0.Text)) Else ' An error occurred. We show the error. ' MessageBox.Show(GetFormatedError(stsResult)) End If ''Check for faults txtID.Text = "10051112" autoSend() 'txtData0.Text = "00" txtData1.Text = "00" txtBHHDC.Text = "" txtIHDC.Text = "" If CmBIond.Text = "Duty Cycle Adjust" Or CmBBond.Text = "Duty Cycle Adjust" Then txtID.Text = "10011112" End Sub Private Sub cmdPWMDIO_Click(sender As System.Object, e As System.EventArgs) Handles cmdPWMDIO.Click Dim CANMsg As TPCANMsg Dim txtbCurrentTextBox As TextBox Dim stsResult As TPCANStatus chbExtended.CheckState = CheckState.Checked txtID.Text = "10031112" txtData0.Text = Hex(0) txtData1.Text = Hex(0) If cmdPWMDIO.Text = "PWM DIGITAL I/O" Then cmdPWMDIO.Text = "PWM DIGITAL I/O ON" txtData0.Text = Hex(255) ElseIf cmdPWMDIO.Text = "PWM DIGITAL I/O ON" Then cmdPWMDIO.Text = "PWM DIGITAL I/O OFF" txtData0.Text = Hex(0) ElseIf cmdPWMDIO.Text = "PWM DIGITAL I/O OFF" Then cmdPWMDIO.Text = "PWM DIGITAL I/O ON" txtData0.Text = Hex(255) End If ' We create a TCLightMsg message structure ' CANMsg = New TPCANMsg() CANMsg.DATA = New Byte(7) {} ' We configurate the Message. The ID (max 0x1FF), ' Length of the Data, Message Type (Standard in ' this example) and die data ' CANMsg.ID = Convert.ToUInt32(txtID.Text, 16) CANMsg.LEN = Convert.ToByte(nudLength.Value) CANMsg.MSGTYPE = IIf((chbExtended.Checked), TPCANMessageType.PCAN_MESSAGE_EXTENDED, TPCANMessageType.PCAN_MESSAGE_STANDARD) ' If a remote frame will be sent, the data bytes are not important. ' If chbRemote.Checked Then CANMsg.MSGTYPE = CANMsg.MSGTYPE Or TPCANMessageType.PCAN_MESSAGE_RTR Else ' We get so much data as the Len of the message ' txtbCurrentTextBox = txtData0 For i As Integer = 0 To CANMsg.LEN - 1 CANMsg.DATA(i) = Convert.ToByte(txtbCurrentTextBox.Text, 16) If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End If ' The message is sent to the configured hardware ' stsResult = PCANBasic.Write(m_PcanHandle, CANMsg) ' The Hardware was successfully sent ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("Message was successfully SENT") Else ' An error occurred. We show the error. ' MessageBox.Show(GetFormatedError(stsResult)) End If ''Check for faults from unit fault pins txtID.Text = "10051112" autoSend() End Sub Private Sub cmdDIO_Click(sender As System.Object, e As System.EventArgs) Handles cmdDIO.Click Dim CANMsg As TPCANMsg Dim txtbCurrentTextBox As TextBox Dim stsResult As TPCANStatus chbExtended.CheckState = CheckState.Checked txtID.Text = "10041112" 'txtData0.Text = Hex(0) txtData1.Text = Hex(0) If cmdDIO.Text = "DIGITAL I/O" Then cmdDIO.Text = "DIGITAL I/O ON" txtData1.Text = Hex(255) ElseIf cmdDIO.Text = "DIGITAL I/O ON" Then cmdDIO.Text = "DIGITAL I/O OFF" txtData1.Text = Hex(0) ElseIf cmdDIO.Text = "DIGITAL I/O OFF" Then cmdDIO.Text = "DIGITAL I/O ON" txtData1.Text = Hex(255) End If ' We create a TCLightMsg message structure ' CANMsg = New TPCANMsg() CANMsg.DATA = New Byte(7) {} ' We configurate the Message. The ID (max 0x1FF), ' Length of the Data, Message Type (Standard in ' this example) and die data ' CANMsg.ID = Convert.ToUInt32(txtID.Text, 16) CANMsg.LEN = Convert.ToByte(nudLength.Value) CANMsg.MSGTYPE = IIf((chbExtended.Checked), TPCANMessageType.PCAN_MESSAGE_EXTENDED, TPCANMessageType.PCAN_MESSAGE_STANDARD) ' If a remote frame will be sent, the data bytes are not important. ' If chbRemote.Checked Then CANMsg.MSGTYPE = CANMsg.MSGTYPE Or TPCANMessageType.PCAN_MESSAGE_RTR Else ' We get so much data as the Len of the message ' txtbCurrentTextBox = txtData0 For i As Integer = 0 To CANMsg.LEN - 1 CANMsg.DATA(i) = Convert.ToByte(txtbCurrentTextBox.Text, 16) If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End If ' The message is sent to the configured hardware ' stsResult = PCANBasic.Write(m_PcanHandle, CANMsg) ' The Hardware was successfully sent ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("Message was successfully SENT") Else ' An error occurred. We show the error. ' MessageBox.Show(GetFormatedError(stsResult)) End If ''Check for faults txtID.Text = "10051112" autoSend() End Sub Public Sub autoSend() Dim CANMsg As TPCANMsg Dim txtbCurrentTextBox As TextBox Dim stsResult As TPCANStatus ' We create a TCLightMsg message structure ' CANMsg = New TPCANMsg() CANMsg.DATA = New Byte(7) {} ' We configurate the Message. The ID (max 0x1FF), ' Length of the Data, Message Type (Standard in ' this example) and die data ' CANMsg.ID = Convert.ToUInt32(txtID.Text, 16) CANMsg.LEN = Convert.ToByte(nudLength.Value) CANMsg.MSGTYPE = IIf((chbExtended.Checked), TPCANMessageType.PCAN_MESSAGE_EXTENDED, TPCANMessageType.PCAN_MESSAGE_STANDARD) ' If a remote frame will be sent, the data bytes are not important. ' If chbRemote.Checked Then CANMsg.MSGTYPE = CANMsg.MSGTYPE Or TPCANMessageType.PCAN_MESSAGE_RTR Else ' We get so much data as the Len of the message ' txtbCurrentTextBox = txtData0 For i As Integer = 0 To CANMsg.LEN - 1 CANMsg.DATA(i) = Convert.ToByte(txtbCurrentTextBox.Text, 16) If i < 7 Then txtbCurrentTextBox = DirectCast(Me.GetNextControl(txtbCurrentTextBox, True), TextBox) End If Next End If ' The message is sent to the configured hardware ' stsResult = PCANBasic.Write(m_PcanHandle, CANMsg) ' The Hardware was successfully sent ' If stsResult = TPCANStatus.PCAN_ERROR_OK Then IncludeTextMessage("Message was successfully SENT" & "Error ?: " & CStr(txtData0.Text)) If CInt("&H" & txtData0.Text) > 0 Then IncludeTextMessage("There is a Fault Condition: " & txtData0.Text) If CInt("&H" & txtData0.Text) = 1 Then IncludeTextMessage("INDEX HEATER ONLY") If CInt("&H" & txtData0.Text) = 2 Then IncludeTextMessage("BOND HEAD HEATER ONLY") If CInt("&H" & txtData0.Text) = 3 Then IncludeTextMessage("INDEX HEATER And BOND HEAD HEATER. Check connections") Else ' An error occurred. We show the error. ' MessageBox.Show(GetFormatedError(stsResult)) End If End Sub Private Sub CmbENABLE_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CmbENABLE.SelectedIndexChanged 'Dim IH As Integer, BBH1 As Integer, BBH2 As Integer, FH1 As Integer, FH2 As Integer cmdDIO.ResetText() cmdDIO.Text = "DIGITAL I/O" If CmbENABLE.Text = "Enable Index Heater" Then txtData0.Text = Hex(0) If CmbENABLE.Text = "Enable BBH 1" Then txtData0.Text = Hex(1) If CmbENABLE.Text = "Enable BBH 2" Then txtData0.Text = Hex(2) If CmbENABLE.Text = "Enable Heater Fault 1" Then txtData0.Text = Hex(3) If CmbENABLE.Text = "Enable Heater Fault 2" Then txtData0.Text = Hex(4) If CmbENABLE.Text = "Channel 6" Then txtData0.Text = Hex(5) If CmbENABLE.Text = "Channel 7" Then txtData0.Text = Hex(6) End Sub Private Sub txtID_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtID.TextChanged chbExtended.CheckState = CheckState.Checked End Sub Public Sub FileToArray(ByVal FileName As String, _ ByRef TheArray As Object) End Sub Private Sub btnSA_Click(sender As System.Object, e As System.EventArgs) Handles btnSA.Click Dim SArray() As String Dim f As Integer txtID.Text = "10011112" ReDim SArray(UBound(txtALLC.Lines)) For f = 0 To UBound(txtALLC.Lines) SArray(f) = txtALLC.Lines(f) 'txtData0.Text = Hex(SArray(f)) 'txtData1.Text = Hex(txtALLDuty.Text) 'Call autoSend() Debug.Print(SArray(f)) Next For Each inp As String In SArray txtData0.Text = Hex(inp) txtID.Text = "10011112" txtData1.Text = Hex(txtALLDuty.Text) Call autoSend() Next 'txtALLC.Text = "" txtData0.Text = "00" txtData1.Text = "00" End Sub Private Sub MenuStrip1_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) End Sub Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click End End Sub Private Sub runRecipe() Dim arrName() As String Dim arrValue() As String Dim DCValue() As String Dim tmr As Integer Static Dim howlong As New Stopwatch Using ioReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\tdi\KandS_Recipe.csv") ioReader.TextFieldType = FileIO.FieldType.Delimited ioReader.SetDelimiters(",") While Not ioReader.EndOfData And Recipe = True Dim arrCurrentRow As String() = ioReader.ReadFields() If arrName Is Nothing Then ReDim Preserve arrName(0) ReDim Preserve arrValue(0) ReDim Preserve DCValue(0) arrName(0) = arrCurrentRow(0) arrValue(0) = arrCurrentRow(1) DCValue(0) = arrCurrentRow(2) Else ReDim Preserve arrName(arrName.Length) ReDim Preserve arrValue(arrValue.Length) ReDim Preserve DCValue(DCValue.Length) tmr = CInt(arrName((arrName.Length - 1)) = arrCurrentRow(0)) tmr = CInt(arrCurrentRow(0)) arrValue((arrValue.Length - 1)) = arrCurrentRow(1) txtData0.Text = Hex(arrCurrentRow(1)) txtIHDC.Text = DCValue((DCValue.Length - 1)) = arrCurrentRow(2) txtData1.Text = Hex(arrCurrentRow(2)) 'Load Duty Cycle send variables txtID.Text = "10011112" 'send duty cycle cmd autoSend() howlong.Start() Console.WriteLine(howlong.ElapsedMilliseconds) Console.WriteLine(DateTime.Now.ToLongTimeString) Do While howlong.Elapsed.TotalMinutes < tmr And Recipe = True IncludeTextMessage("Recipe Running: " & howlong.Elapsed.ToString()) 'autoSend() Loop howlong.Stop() End If End While End Using End Sub Private Sub CustomizeToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CustomizeToolStripMenuItem.Click Static Dim howlong As New Stopwatch Dim Task1 As New System.Threading.Thread(AddressOf runRecipe) MsgBox("Other Controls may not function during Recipe run") Recipe = True 'Task1.Start(Sub() runRecipe() 'End Sub) Console.WriteLine("Recipe Completed Sucssesfully!") End Sub Private Sub OptionsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles OptionsToolStripMenuItem.Click Dim Task2 As New System.Threading.Thread(AddressOf runRecipe) Recipe = False 'Task2.Start(Sub() runRecipe() 'End Sub) Console.WriteLine("Recipe Stopped!") End Sub Private Sub NewToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) End Sub Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click MsgBox("K & S Home Grown Controllor Version: 1" & vbCrLf _ & "AstrodynTDI SW#: T100106228-LF" & vbCrLf _ & "Based on PCANBasic Example, Peak Systems" & vbCrLf _ & "Released By: Joe Lockhart 4/09/2015") End Sub 'Public Shared Function Run(action As Action) As Task Private Sub OpenToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles OpenToolStripMenuItem.Click ' Specify the directories you want to manipulate. Dim di As DirectoryInfo = New DirectoryInfo("c:\TDI\KandS_Recipe.csv") Try ' Determine whether the directory exists. If di.Exists Then ' Indicate that it already exists. Console.WriteLine("That path exists already.") FileOpen(1, "KandS_Recipe.csv", OpenMode.Output, OpenAccess.Default, OpenShare.Default, 1) Return End If ' Try to create the directory. di.Create() Console.WriteLine("The directory was created successfully.") FileOpen(1, "KandS_Recipe.csv", OpenMode.Output, OpenAccess.Default, OpenShare.Default, 1) ' Delete the directory. di.Delete() Console.WriteLine("The directory was deleted successfully.") Catch x As Exception Console.WriteLine("The process failed: {0}", x.ToString()) Exit Sub End Try 'User can now view and edit file. FileOpen(1, "KandS_Recipe.csv", OpenMode.Output, OpenAccess.Default, OpenShare.Default, 1) Dim Recipe As New ProcessStartInfo("c:\TDI\KandS_Recipe.csv") With Recipe .FileName = "c:\TDI\KandS_Recipe.csv" .UseShellExecute = True Recipe.WindowStyle = ProcessWindowStyle.Normal 'StartInfo = Recipe End With Process.Start("c:\TDI\KandS_Recipe.csv") End Sub Private Sub BenchVueToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles BenchVueToolStripMenuItem.Click If System.IO.File.Exists("C:\Program Files (x86)\Keysight\BenchVue\Applications\BenchVue\Keysight BenchVue.exe") = True Then Process.Start("C:\Program Files (x86)\Keysight\BenchVue\Applications\BenchVue\Keysight BenchVue.exe") Else MsgBox("Please Install Keysight BenchVue Software") End If End Sub End Class
Imports System.Windows Imports DTO Imports MySql.Data.MySqlClient Public Class SachDaXoaDAL Shared con As MySqlConnection = New MySqlConnection(ConnectionDTO.Connection) ''' <summary> ''' lấy dữ liệu các sách đã xóa ''' </summary> ''' <returns></returns> Public Shared Function LoadSachDaXoa() As List(Of SachDTO) Dim listSachDaXoa As New List(Of SachDTO) Try con.Open() Dim query = "select * from sachdaxoa join sach on sachdaxoa.MaSachDaXoa = sach.MaSach" Dim reader As MySqlDataReader = New MySqlCommand(query, con).ExecuteReader While reader.Read listSachDaXoa.Add(New SachDTO(reader.GetString("MaSach"), reader.GetString("TenSach"), reader.GetString("TheLoai"), reader.GetString("TacGia"), reader.GetString("SoLuongTon"), reader.GetString("DonGia"))) End While Catch ex As Exception MessageBox.Show(ex.Message) Finally con.Dispose() con.Close() End Try Return listSachDaXoa End Function Public Shared Function KhoiPhucSach(ByVal MaSach As String) As Boolean Try con.Open() Dim query = "delete from sachdaxoa where MaSachDaXoa = @MaSach" Dim cmd As MySqlCommand = New MySqlCommand(query, con) cmd.Parameters.AddWithValue("@MaSach", MaSach) Dim count = 0 count = cmd.ExecuteNonQuery() If count > 0 Then Return True End If Catch ex As Exception MessageBox.Show(ex.Message) Finally con.Dispose() con.Close() End Try Return False End Function ''' <summary> ''' kiểm tra mã sách có tồn tại trong bảng sách đã xóa không ''' </summary> ''' <param name="MaSach"></param> ''' <returns></returns> Public Shared Function TimMaSachDaXoa(ByVal MaSach As String) As Boolean Try con.Open() Dim query = "select * from sachdaxoa" Dim reader As MySqlDataReader = New MySqlCommand(query, con).ExecuteReader While reader.Read If reader.GetString("MaSachDaXoa") = MaSach Then Return True End If End While Catch ex As Exception MessageBox.Show(ex.Message) Finally con.Dispose() con.Close() End Try Return False End Function End Class
Imports Route4MeSDKLibrary.Route4MeSDK Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes Namespace Route4MeSDKTest.Examples Partial Public NotInheritable Class Route4MeExamples ''' <summary> ''' Get limited number of the optimizations. ''' </summary> Public Sub GetOptimizations() ' Create the manager with the api key Dim route4Me = New Route4MeManager(ActualApiKey) Dim queryParameters = New RouteParametersQuery() With { .Limit = 10, .Offset = 5 } Dim errorString As String = Nothing Dim dataObjects As DataObject() = route4Me.GetOptimizations(queryParameters, errorString) PrintExampleOptimizationResult(dataObjects, errorString) End Sub End Class End Namespace
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class colorroundmeter Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "Color Round Meters" End Function 'Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 6 End Function 'Main code for creating charts Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _ Implements DemoModule.createChart ' The value to display on the meter Dim value As Double = 72.3 ' The background and border colors of the meters Dim bgColor() As Integer = {&H88ccff, &Hffdddd, &Hffddaa, &Hffccff, &Hdddddd, &Hccffcc} Dim borderColor() As Integer = {&H000077, &H880000, &Hee6600, &H440088, &H000000, &H006000} ' Create an AngularMeter object of size 250 x 250 pixels with transparent background Dim m As AngularMeter = New AngularMeter(250, 250, Chart.Transparent) ' Demonstration two different meter scale angles If chartIndex Mod 2 = 0 Then ' Center at (125, 125), scale radius = 111 pixels, scale angle -140 to +140 degrees m.setMeter(125, 125, 111, -140, 140) Else ' Center at (125, 125), scale radius = 111 pixels, scale angle -180 to +90 degrees m.setMeter(125, 125, 111, -180, 90) End If ' Background gradient color with brighter color at the center Dim bgGradient() As Double = {0, m.adjustBrightness(bgColor(chartIndex), 3), 0.75, _ bgColor(chartIndex)} ' Add circle with radius 123 pixels as background using the background gradient m.addRing(0, 123, m.relativeRadialGradient(bgGradient)) ' Add a ring between radii 116 and 123 pixels as border m.addRing(116, 123, borderColor(chartIndex)) ' Meter scale is 0 - 100, with major/minor/micro ticks every 10/5/1 units m.setScale(0, 100, 10, 5, 1) ' Set the scale label style to 15pt Arial Italic. Set the major/minor/micro tick lengths to ' 12/9/6 pixels pointing inwards, and their widths to 2/1/1 pixels. m.setLabelStyle("Arial Italic", 15) m.setTickLength(-12, -9, -6) m.setLineWidth(0, 2, 1, 1) ' Demostrate different types of color scales and putting them at different positions Dim smoothColorScale() As Double = {0, &H3333ff, 25, &H0088ff, 50, &H00ff00, 75, &Hdddd00, _ 100, &Hff0000} Dim stepColorScale() As Double = {0, &H00cc00, 60, &Hffdd00, 80, &Hee0000, 100} Dim highLowColorScale() As Double = {0, &H00ff00, 70, Chart.Transparent, 100, &Hff0000} If chartIndex = 0 Then ' Add the smooth color scale at the default position m.addColorScale(smoothColorScale) ElseIf chartIndex = 1 Then ' Add the smooth color scale starting at radius 62 with zero width and ending at radius ' 40 with 22 pixels outer width m.addColorScale(smoothColorScale, 62, 0, 40, 22) ElseIf chartIndex = 2 Then ' Add green, yellow and red zones between radii 44 and 60 m.addZone(0, 60, 44, 60, &H00dd00) m.addZone(60, 80, 44, 60, &Hffff00) m.addZone(80, 100, 44, 60, &Hff0000) ElseIf chartIndex = 3 Then ' Add the high/low color scale at the default position m.addColorScale(highLowColorScale) ElseIf chartIndex = 4 Then ' Add the smooth color scale at radius 44 with 16 pixels outer width m.addColorScale(smoothColorScale, 44, 16) Else ' Add the step color scale at the default position m.addColorScale(stepColorScale) End If ' Add a text label centered at (125, 175) with 15pt Arial Italic font m.addText(125, 175, "CPU", "Arial Italic", 15, Chart.TextColor, Chart.Center) ' Add a readout to some of the charts as demonstration If chartIndex = 0 Or chartIndex = 2 Then ' Put the value label center aligned at (125, 232), using white (0xffffff) 14pt Arial ' font on a black (0x000000) background. Set box width to 50 pixels with 5 pixels ' rounded corners. Dim t As ChartDirector.TextBox = m.addText(125, 232, m.formatValue(value, _ "<*block,width=50,halign=center*>{value|1}"), "Arial", 14, &Hffffff, _ Chart.BottomCenter) t.setBackground(&H000000) t.setRoundedCorners(5) End If ' Add a red (0xff0000) pointer at the specified value m.addPointer2(value, &Hff0000) ' Output the chart viewer.Chart = m End Sub End Class
Imports System.Data.SqlClient Imports Newtonsoft.Json Imports UGPP.CobrosCoactivo.Entidades Imports UGPP.CobrosCoactivo.Logica Partial Public Class EditDIRECCIONES Inherits PaginaBase ''' <summary> ''' Se declaran las propiedades necesarias ''' </summary> Dim tareaAsignadaObject As TareaAsignada Dim fuenteDireccionBLL As FuenteDireccionBLL Dim tareaAsignadaBLL As TareaAsignadaBLL Dim almacenamientoTemporalBLL As AlmacenamientoTemporalBLL Protected Overrides Sub OnInit(e As EventArgs) fuenteDireccionBLL = New FuenteDireccionBLL() tareaAsignadaBLL = New TareaAsignadaBLL() almacenamientoTemporalBLL = New AlmacenamientoTemporalBLL() End Sub ''' <summary> ''' Carga los controles de la vista segun las propiedades del objeto ''' </summary> ''' <param name="prmdireccionUbicacion">Objeto de tipo direccion</param> Public Sub cargarObjetoDirreccion(prmdireccionUbicacion As DireccionUbicacion) If Session("mnivelacces") = 10 And prmdireccionUbicacion.idunico > 0 Then cmdSave.Visible = False cmdSave.Enabled = False End If If String.IsNullOrEmpty(prmdireccionUbicacion.direccionCompleta) = False Then txtDireccion.Text = prmdireccionUbicacion.direccionCompleta End If If String.IsNullOrEmpty(prmdireccionUbicacion.idDepartamento) = False Then cboDepartamento.SelectedValue = prmdireccionUbicacion.idDepartamento LoadcboCiudad(prmdireccionUbicacion.idDepartamento) End If If String.IsNullOrEmpty(prmdireccionUbicacion.idCiudad) = False Then cboCiudad.SelectedValue = prmdireccionUbicacion.idCiudad End If If String.IsNullOrEmpty(prmdireccionUbicacion.telefono) = False Then txtTelefono.Text = prmdireccionUbicacion.telefono End If If String.IsNullOrEmpty(prmdireccionUbicacion.email) = False Then txtEmail.Text = prmdireccionUbicacion.email End If If String.IsNullOrEmpty(prmdireccionUbicacion.celular) = False Then txtMovil.Text = prmdireccionUbicacion.celular End If If String.IsNullOrEmpty(prmdireccionUbicacion.paginaweb) = False Then txtpaginaweb.Text = prmdireccionUbicacion.paginaweb End If If String.IsNullOrEmpty(prmdireccionUbicacion.fuentesDirecciones) = False Then CboFuente.SelectedValue = prmdireccionUbicacion.fuentesDirecciones End If If String.IsNullOrEmpty(prmdireccionUbicacion.otrasFuentesDirecciones) = False Then TxtOtraFuente.Text = prmdireccionUbicacion.otrasFuentesDirecciones End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Evaluates to true when the page is loaded for the first time. If IsPostBack = False Then LoadcboDepartamento() LoadcboFuente() If Len(Request("ID_TASK")) > 0 Then 'Si ID_TASK tiene valor se carga valida el item tareaAsignadaObject = tareaAsignadaBLL.consultarTareaPorId(Long.Parse(Request("ID_TASK").ToString())) Dim tituloEjecutivoObj As TituloEjecutivoExt 'Si TareaAsignadaObject.ID_UNICO_TITULO esta vacio realiza el cargue del objeto parcial Dim almacenamientoTemportalItem = almacenamientoTemporalBLL.consultarAlmacenamientoPorId(tareaAsignadaObject.ID_TAREA_ASIGNADA) tituloEjecutivoObj = JsonConvert.DeserializeObject(Of TituloEjecutivoExt)(almacenamientoTemportalItem.JSON_OBJ) HdnIdTask.Value = Request("ID_TASK") If String.IsNullOrEmpty(Request("IdDireccion")) = False Then cargarObjetoDirreccion(tituloEjecutivoObj.LstDireccionUbicacion.Where(Function(x) (x.idunico).ToString() = Request("IdDireccion")).FirstOrDefault()) Else LoadcboCiudad(cboDepartamento.SelectedValue) End If If Session("mnivelacces") <> 11 Then 'Solo área origen puede editar la dirección pnlDirecciones.Enabled = False End If Else LoadcboCiudad(cboDepartamento.SelectedValue) End If If Session("mnivelacces") = 10 Then nombreModulo = "ESTUDIO_TITULOS" End If If Session("mnivelacces") = 11 Then nombreModulo = "AREA_ORIGEN" End If #Region "EstudioTitulos" 'TODO: VALIDAR COMPORTAMIENTO EN ESTUDIO DE TITULOS ''Create a new connection to the database 'Dim Connection As New SqlConnection(Funciones.CadenaConexion) ''Opens a connection to the database. 'Connection.Open() ''Si el expediente esta en estado devuelto o terminado =>Impedir adicionar o editar datos 'If NomEstadoProceso = "DEVUELTO" Or NomEstadoProceso = "TERMINADO" Then ' cmdSave.Visible = False ' CustomValidator1.Text = "Los expedientes en estado " & NomEstadoProceso & " no permiten editar datos" ' CustomValidator1.IsValid = False ' 'Deshabilitar controles ' txtDireccion.Enabled = False ' cboDepartamento.Enabled = False ' cboCiudad.Enabled = False ' txtTelefono.Enabled = False ' txtEmail.Enabled = False ' txtMovil.Enabled = False ' txtpaginaweb.Enabled = False 'End If #End Region End If End Sub Private Sub LoadcboFuente() CboFuente.DataSource = fuenteDireccionBLL.ConsultarFuentes() CboFuente.DataTextField = "DES_NOMBRE_FUENTE_DIRECCION" CboFuente.DataValueField = "ID_FUENTE_DIRECCION" CboFuente.DataBind() End Sub Protected Sub LoadcboDepartamento() 'Create a new connection to the database Dim Connection As New SqlConnection(Funciones.CadenaConexion) 'Opens a connection to the database. Connection.Open() Dim sql As String = "select codigo, nombre from [DEPARTAMENTOS] order by nombre" Dim Command As New SqlCommand(sql, Connection) cboDepartamento.DataTextField = "nombre" cboDepartamento.DataValueField = "codigo" cboDepartamento.DataSource = Command.ExecuteReader() cboDepartamento.DataBind() 'Close the Connection Object Connection.Close() End Sub Protected Sub LoadcboCiudad(ByVal prmStrCodigoDepartamento As String) 'Create a new connection to the database Dim Connection As New SqlConnection(Funciones.CadenaConexion) Connection.Open() Dim sql As String = "select codigo, nombre from [MUNICIPIOS] WHERE departamento = '" & prmStrCodigoDepartamento & "' order by nombre" Dim Command As New SqlCommand(sql, Connection) cboCiudad.DataTextField = "nombre" cboCiudad.DataValueField = "codigo" cboCiudad.DataSource = Command.ExecuteReader() cboCiudad.DataBind() 'Close the Connection Object Connection.Close() End Sub Private Overloads Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click Dim almacenamientoTemportalItem = almacenamientoTemporalBLL.consultarAlmacenamientoPorId(Request("ID_TASK")) Dim tituloEjecutivoObj As TituloEjecutivoExt = JsonConvert.DeserializeObject(Of TituloEjecutivoExt)(almacenamientoTemportalItem.JSON_OBJ) Dim direccionUbicacionItem As DireccionUbicacion = New DireccionUbicacion() If String.IsNullOrEmpty(txtDireccion.Text) = False Then direccionUbicacionItem.direccionCompleta = txtDireccion.Text End If If String.IsNullOrEmpty(cboDepartamento.SelectedValue) = False Then direccionUbicacionItem.idDepartamento = cboDepartamento.SelectedValue direccionUbicacionItem.NombreDepartamento = cboDepartamento.SelectedItem.Text End If If String.IsNullOrEmpty(cboCiudad.SelectedValue) = False Then direccionUbicacionItem.idCiudad = cboCiudad.SelectedValue direccionUbicacionItem.NombreMunicipio = cboCiudad.SelectedItem.Text End If If String.IsNullOrEmpty(txtTelefono.Text) = False Then direccionUbicacionItem.telefono = txtTelefono.Text End If If String.IsNullOrEmpty(txtEmail.Text) = False Then direccionUbicacionItem.email = txtEmail.Text End If If String.IsNullOrEmpty(txtMovil.Text) = False Then direccionUbicacionItem.celular = txtMovil.Text End If If String.IsNullOrEmpty(txtpaginaweb.Text) = False Then direccionUbicacionItem.paginaweb = txtpaginaweb.Text End If If String.IsNullOrEmpty(CboFuente.SelectedValue) = False Then direccionUbicacionItem.fuentesDirecciones = CboFuente.SelectedValue direccionUbicacionItem.nombreFuente = CboFuente.SelectedItem.Text End If If String.IsNullOrEmpty(TxtOtraFuente.Text) = False Then direccionUbicacionItem.otrasFuentesDirecciones = TxtOtraFuente.Text End If direccionUbicacionItem.numeroidentificacionDeudor = Request("IdDeudor").ToString() If String.IsNullOrEmpty(Request("IdDireccion")) = False Then direccionUbicacionItem.idunico = Int32.Parse(Request("IdDireccion").ToString()) tituloEjecutivoObj.LstDireccionUbicacion.Remove(tituloEjecutivoObj.LstDireccionUbicacion.Where(Function(x) (x.idunico).ToString() = Request("IdDireccion")).FirstOrDefault()) Else direccionUbicacionItem.idunico = -(tituloEjecutivoObj.LstDireccionUbicacion().Count() + 1) End If tituloEjecutivoObj.LstDireccionUbicacion.Add(direccionUbicacionItem) almacenamientoTemportalItem.JSON_OBJ = JsonConvert.SerializeObject(tituloEjecutivoObj) almacenamientoTemporalBLL = New AlmacenamientoTemporalBLL(llenarAuditoria("jsonobj=" + almacenamientoTemportalItem.JSON_OBJ)) almacenamientoTemporalBLL.actualizarAlmacenamiento(almacenamientoTemportalItem) 'Go to the Summary page Response.Redirect("DIRECCIONES.aspx?ID_TASK=" & Request("ID_TASK") & "&IdDeudor=" & Request("IdDeudor") & "&IdDireccion=" & Request("IdDireccion")) End Sub Protected Sub cmdCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCancel.Click Response.Redirect("DIRECCIONES.aspx?ID_TASK=" & Request("ID_TASK") & "&IdDeudor=" & Request("IdDeudor") & "&IdDireccion=" & Request("IdDireccion")) End Sub Private Shared Function GetCiudades() As DataTable Dim cmd, cnx As String cnx = Funciones.CadenaConexion cmd = "SELECT codigo, nombre, departamento FROM municipios" Dim Adaptador As New SqlDataAdapter(cmd, cnx) Dim dtMunicipios As New DataTable Adaptador.Fill(dtMunicipios) Return dtMunicipios End Function Private Function llenarAuditoria(ByVal valorAfectado As String) As LogAuditoria Dim log As New LogProcesos Dim auditData As New UGPP.CobrosCoactivo.Entidades.LogAuditoria auditData.LOG_APLICACION = log.AplicationName auditData.LOG_FECHA = Date.Now auditData.LOG_HOST = log.ClientHostName auditData.LOG_IP = log.ClientIpAddress auditData.LOG_MODULO = "Seguridad" auditData.LOG_USER_CC = String.Empty auditData.LOG_USER_ID = Session("ssloginusuario") auditData.LOG_DOC_AFEC = valorAfectado Return auditData End Function Protected Sub cboDepartamento_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboDepartamento.SelectedIndexChanged LoadcboCiudad(cboDepartamento.SelectedValue) End Sub End Class
'Exercise 3-2-41 page 83 'Programmer: Samantha Naini 'Date: 2/6/2012 'Program Purpose: Compute the number of pounds lost through entering 'the number of hours spent cycling, running, and swimming in a program 'entitled "Triathlon". Option Explicit On Option Strict On Public Class frmTriathlon Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click Dim cycling, running, swimming, weightloss As Double cycling = CDbl(txtBoxCycling.Text) * 200 running = CDbl(txtBoxRunning.Text) * 475 swimming = CDbl(txtBoxSwimming.Text) * 275 weightloss = (cycling + running + swimming) / 3500 weightloss = Math.Round(weightloss, 1) txtBoxWeightLoss.Text = weightloss & " pounds were lost." End Sub End Class
Public MustInherit Class Pessoa Private Nome As String Private Endereço As String Public Sub New() End Sub Public Sub New(ByVal Nome As String, ByVal Endereço As String) Me.Nome = Nome Me.Endereço = Endereço End Sub Public Function GetNome() As String Return Nome End Function Public Sub SetNome(ByVal Nome As String) Me.Nome = Nome End Sub Public Function GetEndereço() As String Return Endereço End Function Public Sub SetEndereço(ByVal Endereço As String) Me.Endereço = Endereço End Sub Public Overrides Function ToString() As String Return "Nome: " + Nome + "; Endereço: " + Endereço End Function End Class
Imports DevExpress.Xpo Imports DevExpress.Persistent.Base ''' <summary> ''' ''' </summary> ''' <remarks></remarks> <ImageName("BO_Skull"), Persistent("TPF.InventoryMaterialCostForYear"), DefaultClassOptions()> Public Class TPF_InventoryMaterialCostForYear Inherits XPObject Public Sub New(ByVal session As Session) MyBase.New(session) End Sub Public Overrides Sub AfterConstruction() MyBase.AfterConstruction() End Sub Private _material As Part_PartsBase Private _year As DateTime Private _cost As Decimal ''' <summary> ''' ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <Association("Part-InventoryCosts")> Public Property Material As Part_PartsBase Get Return _material End Get Set(ByVal Value As Part_PartsBase) SetPropertyValue("Material", _material, Value) End Set End Property ''' <summary> ''' ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property Year As DateTime Get Return _year End Get Set(ByVal Value As DateTime) SetPropertyValue("Year", _year, Value) End Set End Property ''' <summary> ''' ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property Cost As Decimal Get Return _cost End Get Set(ByVal Value As Decimal) SetPropertyValue("Cost", _cost, Value) End Set End Property End Class
Imports DevExpress.Xpo.DB Imports DevExpress.Xpo.DB.Helpers Imports System.Data Imports System.Data.SqlClient Imports Ladle.AppLogger Public Class CustomMSSqlConnectionProvider Inherits MSSqlConnectionProvider Public Shadows Const XpoProviderTypeString As String = "CustomMSSqlServer" Private Const CommandTimeout As Integer = 15 Public Sub New(conn As IDbConnection, acOpt As AutoCreateOption) MyBase.New(conn, acOpt) 'Logger.ToLog("++ CustomMSSqlServer ++") End Sub Public Overloads Shared Sub Register() Try DataStoreBase.RegisterDataStoreProvider(XpoProviderTypeString, New DataStoreCreationFromStringDelegate(AddressOf CreateProviderFromString)) Catch ex As Exception Logger.ToLog(ex.Message) End Try End Sub Public Overloads Shared Function CreateProviderFromConnection(connection As IDbConnection, autoCreateOption As AutoCreateOption) As IDataStore Return New CustomMSSqlConnectionProvider(connection, autoCreateOption) End Function Public Overloads Shared Function CreateProviderFromString(connectionString As String, autoCreateOption As AutoCreateOption, ByRef objectsToDisposeOnDisconnect As IDisposable()) As IDataStore Dim connection As IDbConnection = New SqlConnection(connectionString) objectsToDisposeOnDisconnect = New IDisposable() {connection} Return CreateProviderFromConnection(connection, autoCreateOption) End Function Public Overrides Function CreateCommand() As IDbCommand Dim ret As IDbCommand = MyBase.CreateCommand() ret.CommandTimeout = CommandTimeout 'Logger.ToLog("CreateCommand(): Command timeout is {0} seconds", CommandTimeout) Return ret End Function Protected Overrides Function CreateCommand(query As Query) As IDbCommand Dim ret As IDbCommand = MyBase.CreateCommand(query) ret.CommandTimeout = CommandTimeout 'Logger.ToLog("CreateCommand(q): Command timeout is {0} seconds", CommandTimeout) Return ret End Function End Class
Imports System.Data Imports System.IO Namespace DAO_WELFARE 'ระบบงบประมาณ ''' <summary> ''' คลาสหลักสำหรับเชื่อมต่อ LINQ_WELFARE ''' </summary> ''' <remarks></remarks> Public MustInherit Class MainContext ''' <summary> ''' ตัวแปรสำหรับเรียกใช้ CONTEXT ของ LINQ ''' </summary> ''' <remarks></remarks> Public DB As New LINQ_WELFAREDataContext ''' <summary> ''' OBJECT เก็บค่าจาก LINQ ''' </summary> ''' <remarks></remarks> Public datas Private _ID As Integer ''' <summary> ''' ID สำหรับเรียกใช้ PK ของตาราง ''' </summary> Public Property ID() As Integer Get Return _ID End Get Set(ByVal value As Integer) _ID = value End Set End Property End Class ''' <summary> ''' บันทึก แก้ไข ลบ ข้อมูลตาราง ALL_WELFARE_BILL ''' </summary> ''' <remarks></remarks> Public Class TB_ALL_WELFARE_BILL Inherits MainContext ''' <summary> ''' รายชื่อ Fields ของตาราง ALL_WELFARE_BILL ''' </summary> ''' <remarks></remarks> Public fields As New ALL_WELFARE_BILL ''' <summary> ''' แสดงข้อมูล ''' </summary> ''' <remarks></remarks> Public Sub Getdata() datas = From p In DB.ALL_WELFARE_BILLs Select p For Each Me.fields In datas Next End Sub ''' <summary> ''' แสดงข้อมูลแบบมีเงื่อนไข ''' </summary> ''' <param name="ID"></param> ''' <remarks></remarks> Public Sub Getdata_by_BUDGET_WELFARE_ID(ByVal ID As Integer) datas = From p In DB.ALL_WELFARE_BILLs Where p.ALL_WELFARE_ID = ID Select p For Each Me.fields In datas Next End Sub ''' <summary> ''' แสดงค่ารักษาพยาบาล ''' </summary> ''' <param name="ID"></param> ''' <remarks></remarks> Public Sub Getdata_Welfare_Cure(ByVal ID As Integer) datas = From p In DB.ALL_WELFARE_BILLs Where p.WELFARE_ID = 2 Select p For Each Me.fields In datas Next End Sub ''' <summary> ''' แสดงค่าเล่าเรียน ''' </summary> ''' <param name="ID"></param> ''' <remarks></remarks> Public Sub Getdata_Welfare_Study(ByVal ID As Integer) datas = From p In DB.ALL_WELFARE_BILLs Where p.WELFARE_ID = 3 Select p For Each Me.fields In datas Next End Sub Public Sub Get_Welfare_Cure_Home() datas = From p In DB.ALL_WELFARE_BILLs Where p.WELFARE_ID = 1 And p.WELFARE_ID = 4 Select p For Each Me.fields In datas Next End Sub Public Sub Get_Welfare_Cremetion() datas = From p In DB.ALL_WELFARE_BILLs Where p.WELFARE_ID = 3 Select p For Each Me.fields In datas Next End Sub Public Sub Getdata_Welfare_Cure_by_Cure_ID(ByVal ida As Integer) datas = From p In DB.ALL_WELFARE_BILLs Where p.CURE_STUDY_ID = ida Select p For Each Me.fields In datas Next End Sub Public Function chk_exist_cure(ByVal id As Integer) As Boolean Dim bool As Boolean = False Dim count_exist As Integer = 0 datas = From p In DB.ALL_WELFARE_BILLs Where p.CURE_STUDY_ID = id Select p For Each Me.fields In datas count_exist = count_exist + 1 Next If count_exist > 0 Then bool = True End If Return bool End Function ''' <summary> ''' เพิ่มข้อมูล ''' </summary> ''' <remarks></remarks> Public Sub insert() DB.ALL_WELFARE_BILLs.InsertOnSubmit(fields) DB.SubmitChanges() End Sub ''' <summary> ''' แก้ไข ''' </summary> ''' <remarks></remarks> Public Sub update() DB.SubmitChanges() End Sub ''' <summary> ''' ลบข้อมูล ''' </summary> ''' <remarks></remarks> Public Sub delete() DB.ALL_WELFARE_BILLs.DeleteOnSubmit(fields) DB.SubmitChanges() End Sub ''' <summary> ''' Export To CSV ''' </summary> ''' <remarks></remarks> Public Function export() Return DB.ALL_WELFARE_BILLs.CreateCSVFromGenericList() End Function End Class End Namespace
Imports System.Text ''' <summary> ''' Provides a base class for reading texts from different sources. ''' </summary> Public MustInherit Class TextReader Private intStringBufferDefaultLength As Integer ''' <summary> ''' Moves on to the next character. ''' </summary> Public MustOverride Sub MoveNext() ''' <summary> ''' Reads characters into the specified buffer starting at the specified index. Returns the amount of characters read. ''' </summary> ''' <param name="chars">The buffer to fill with characters.</param> ''' <param name="index">The index at which to start filling the buffer.</param> ''' <param name="count">The maximum amount of characters to read.</param> ''' <returns>Returns the amount of characters read into the buffer.</returns> Public MustOverride Overloads Function ReadChars(ByVal chars() As Char, ByVal index As Integer, ByVal count As Integer) As Integer ''' <summary> ''' Reads all characters in the stream starting from the current offset. ''' </summary> Public MustOverride Function ReadToEnd() As String ''' <summary> ''' Retrieves whether the end of content is reached. ''' </summary> Public MustOverride ReadOnly Property EndOfContent() As Boolean ''' <summary> ''' Returns the character currently selected. ''' </summary> Public MustOverride ReadOnly Property CurrentChar() As Char ''' <summary> ''' Reads a char-array containing the specified amount of characters. ''' </summary> ''' <param name="count"></param> ''' <returns></returns> ''' <remarks></remarks> Public Overridable Overloads Function ReadChars(ByVal count As Integer) As Char() Dim c(count - 1) As Char ReadChars(c, 0, count) Return c End Function ''' <summary> ''' Fills the specified array with characters and returns the amount of read characters. ''' </summary> ''' <param name="buffer">The buffer to fill with characters.</param> Public Overridable Overloads Function ReadChars(ByVal buffer() As Char) As Integer Return ReadChars(buffer, 0, buffer.Length) End Function ''' <summary> ''' Reads a string with the specified length. ''' </summary> ''' <param name="length">The amount of characters to read.</param> Public Overridable Function ReadString(ByVal length As Integer) As String Dim sb As New StringBuilder(length) Dim chr As Char While (sb.Length < length) If TryReadChar(chr) Then sb.Append(chr) Else Return sb.ToString End If End While Return sb.ToString() End Function ''' <summary> ''' Specifies whether the text reader currently is able to read. ''' </summary> Protected Overridable ReadOnly Property CanRead() As Boolean Get Return Not EndOfContent() End Get End Property ''' <summary> ''' Tries to read a character which, if successful, is stored in the result parameter and returns whether the operation was successful. ''' </summary> ''' <param name="result">Contains the read character if the operation was successful. Otherwise the parameter's value does not change.</param> Public Overridable Function TryReadChar(ByRef result As Char) As Boolean If EndOfContent() = False Then result = ReadChar() Return True Else Return False End If End Function ''' <summary> ''' Returns the default length of a string builder which is instantiated during general string reading operations. ''' </summary> Public ReadOnly Property StringBufferDefaultLength() As Integer Get Return intStringBufferDefaultLength End Get End Property ''' <summary> ''' Initializes a new instance of the IniLib.TextReader class. ''' </summary> ''' <param name="stringBufferDefaultLength">Specifies the default length of a string builder which is instantiated during general string reading operations.</param> Public Sub New(ByVal stringBufferDefaultLength As Integer) intStringBufferDefaultLength = stringBufferDefaultLength End Sub ''' <summary> ''' Initializes a new instance of the IniLib.TextReader class. ''' </summary> Public Sub New() intStringBufferDefaultLength = 8192 End Sub ''' <summary> ''' Reads a line. ''' </summary> Public Overridable Function ReadLine() As String ReadLine = ReadUntil(AddressOf IsLinefeedChar) Advance() End Function ''' <summary> ''' Skips all characters while they match the specified requirements. ''' </summary> ''' <param name="match">A delegate specifying the requirements.</param> Public Overridable Sub SkipWhile(ByVal match As Predicate(Of Char)) If match(CurrentChar) Then While Not EndOfContent() AndAlso match(CurrentChar) MoveNext() End While End If End Sub ''' <summary> ''' Skips line feeds. ''' </summary> ''' <remarks>As there are differences in treating line feed characters when it comes to different standards the IniLib supports these. The IniLib's rules of interpreting line feeds are as follows. ''' Cr, Lf, CrLf, LfCr are interpreted as one character (Cr = Carriage return, Lf = Line feed) while LfLf or CrCr are two characters.</remarks> Public Sub SkipLinefeed() If CurrentChar = Chr(10) Then MoveNext() If CurrentChar = Chr(13) Then MoveNext() End If ElseIf CurrentChar = Chr(13) Then MoveNext() If CurrentChar = Chr(10) Then MoveNext() End If Else Throw New ArgumentException("Current char was not a linefeed character.") End If End Sub ''' <summary> ''' Reads a string while the match parameter indicates that a character matches the requirements. ''' </summary> ''' <param name="match">A delegate specifying the requirements of the characters.</param> Public Overridable Function ReadWhile(ByVal match As Predicate(Of Char)) As String If match(CurrentChar) Then Dim sb As New StringBuilder(StringBufferDefaultLength) While Not EndOfContent() AndAlso match(CurrentChar) sb.Append(CurrentChar) MoveNext() End While Return sb.ToString Else Return CurrentChar.ToString End If End Function ''' <summary> ''' Reads a string until the match parameter indicates that a character does not match the requirements. ''' </summary> ''' <param name="match">A delegate specifying the requirements of the characters.</param> Public Overridable Function ReadUntil(ByVal match As Predicate(Of Char)) As String If Not match(CurrentChar) Then Dim sb As New StringBuilder(StringBufferDefaultLength) While Not (EndOfContent() OrElse match(CurrentChar)) sb.Append(CurrentChar) MoveNext() End While Return sb.ToString Else Return CurrentChar.ToString End If End Function ''' <summary> ''' Reads a string until the reached character matches the specified character. ''' </summary> ''' <param name="character">The character which represents the end of the string to retrieve.</param> Public Overridable Function ReadUntil(ByVal character As Char) As String If CurrentChar <> character Then Dim sb As New StringBuilder(StringBufferDefaultLength) While Not (EndOfContent() OrElse CurrentChar = character) sb.Append(CurrentChar) MoveNext() End While Return sb.ToString Else Return CurrentChar.ToString End If End Function ''' <summary> ''' Advances the buffer position by one and returns the character which is then at the buffer position. ''' </summary> Public Overridable Function ReadChar() As Char MoveNext() Return CurrentChar End Function ''' <summary> ''' Reads a word. ''' </summary> Public Overridable Function ReadWord() As String Return ReadWhile(Function(charValue As Char) Char.IsWhiteSpace(charValue) OrElse Char.IsPunctuation(charValue) OrElse Char.IsSeparator(charValue)) End Function ''' <summary> ''' Sets the position of the underlying stream to the actual position considering the buffer position. ''' </summary> Public Overridable Sub SkipSpaces() If CurrentChar = " "c OrElse CurrentChar = Chr(9) Then While (CurrentChar = Chr(9) OrElse CurrentChar = " "c) MoveNext() End While End If End Sub ''' <summary> ''' Advances the buffer position depending on the content. View remarks for further information. ''' </summary> ''' <returns>Returns whether advancing was successful.</returns> ''' <remarks>As there are differences in treating line feed characters when it comes to different standards the IniLib supports these. The IniLib's rules of interpreting line feeds are as follows. ''' Cr, Lf, CrLf, LfCr are interpreted as one character (Cr = Carriage return, Lf = Line feed) while LfLf or CrCr are two characters.</remarks> Public Overridable Function Advance() As Boolean If Not EndOfContent Then If IsLinefeedChar(CurrentChar) Then SkipLinefeed() Else MoveNext() End If Return Not EndOfContent Else Return False End If End Function ''' <summary> ''' Flushes this text reader. ''' </summary> Public Overridable Sub Flush() End Sub ''' <summary> ''' Indicates whether the specified character is a line feed character. ''' </summary> ''' <param name="charValue">The character to check.</param> Protected Overridable Function IsLinefeedChar(ByVal charValue As Char) As Boolean Return charValue = Chr(10) OrElse charValue = Chr(13) End Function End Class
' ------------------------------------------------------------------------ ' XBMControl - A compact remote controller for XBMC (.NET 3.5) ' Copyright (C) 2008 Bram van Oploo (bramvano@gmail.com) ' Mike Thiels (Mike.Thiels@gmail.com) ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program. If not, see <http://www.gnu.org/licenses/>. ' ------------------------------------------------------------------------ Imports System.Collections.Generic Imports System.Text Imports System.Windows.Forms Imports System.IO Imports System.Drawing Imports System.Net Imports XBMControl.Properties Namespace XBMC Public Class XBMC_Video Private parent As XBMC_Communicator = Nothing Public Sub New(p As XBMC_Communicator) parent = p End Sub Public Function Hash(input As String) As String Dim bytes As Byte() Dim m_crc As UInteger = &HffffffffUI Dim encoding As New System.Text.ASCIIEncoding() bytes = encoding.GetBytes(input.ToLower()) For Each myByte As Byte In bytes m_crc = m_crc Xor (CUInt(myByte) << 24) For i As Integer = 0 To 7 If (System.Convert.ToUInt32(m_crc) And &H80000000UI) = &H80000000UI Then m_crc = (m_crc << 1) Xor &H4c11db7 Else m_crc <<= 1 End If Next Next Return [String].Format("{0:x8}", m_crc) End Function Public Function getVideoThumb(videoID As String) As System.Drawing.Image Dim hashName As String Dim strPath As String() Dim downloadData As String() Dim ipString As String Dim fileExist As String() Dim thumbnail As Image = Nothing Dim client As New WebClient() Dim condition As String = If((videoID Is Nothing), "", " WHERE C09 LIKE '%%" & videoID & "%%'") strPath = parent.Request("QueryVideoDatabase", "SELECT strpath FROM movieview " & condition) hashName = Hash(strPath(0) & "VIDEO_TS.IFO") ipString = "P:\Thumbnails\Video\" & hashName(0) & "\" & hashName & ".tbn" fileExist = parent.Request("FileExists", ipString) If fileExist(0) = "True" Then Try downloadData = parent.Request("FileDownload", ipString) ' Convert Base64 String to byte[] Dim imageBytes As Byte() = Convert.FromBase64String(downloadData(0)) Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length) ' Convert byte[] to Image ms.Write(imageBytes, 0, imageBytes.Length) thumbnail = Image.FromStream(ms, True) Catch e As Exception thumbnail = My.Resources.video_32x32 End Try Else thumbnail = My.Resources.video_32x32 End If Return thumbnail End Function Public Function GetVideoPath(movieName As String) As String Dim tempString As String Dim tempStringList As String() Dim condition As String = If((movieName Is Nothing), "", " WHERE C00 LIKE '%%" & movieName & "%%'") tempStringList = parent.Request("QueryVideoDatabase", "SELECT strpath FROM movieview " & condition) tempString = tempStringList(0) tempString += "VIDEO_TS.IFO" Return tempString End Function Public Function GetVideoNames(searchString As String) As String() Dim condition As String = If((searchString Is Nothing), "", " WHERE C00 LIKE '%%" & searchString & "%%'") Return parent.Request("QueryVideoDatabase", "SELECT C00 FROM movie " & condition) End Function Public Function GetVideoNames() As String() Return Me.GetVideoNames(Nothing) End Function Public Function GetVideoYears(searchString As String) As String() Dim condition As String = If((searchString Is Nothing), "", " WHERE C00 LIKE '%%" & searchString & "%%'") Return parent.Request("QueryVideoDatabase", "SELECT C07 FROM movie " & condition) End Function Public Function GetVideoYears() As String() Return Me.GetVideoYears(Nothing) End Function Public Function GetVideoIMDB(searchString As String) As String() Dim condition As String = If((searchString Is Nothing), "", " WHERE C00 LIKE '%%" & searchString & "%%'") Return parent.Request("QueryVideoDatabase", "SELECT C09 FROM movie " & condition) End Function Public Function GetVideoIMDB() As String() Return Me.GetVideoIMDB(Nothing) End Function Public Function GetVideoIds(searchString As String) As String() Dim condition As String = If((searchString Is Nothing), "", " WHERE C00 LIKE '%%" & searchString & "%%'") Return parent.Request("QueryVideoDatabase", "SELECT idMovie FROM movie" & condition & " ORDER BY idMovie") End Function Public Function GetVideoIds() As String() Return Me.GetVideoIds(Nothing) End Function Public Function GetVideoLibraryInfo(videoID As String) As String() Dim condition As String = If((videoID Is Nothing), "", " WHERE C09 LIKE '%%" & videoID & "%%'") Return parent.Request("QueryVideoDatabase", "SELECT * FROM movie " & condition) End Function Public Sub sendAction(buttonAction As String) parent.Request("action", buttonAction) End Sub End Class End Namespace
Public Class Pelicula Private mIdPelicula As Integer Private mTitulo As String Private mTituloOriginal As String Private mAñoEstreno As Date Private mDuracion As Integer Private mSinopsis As String Private mCartelPelicula As String Private mRoles As Collection Private mPersonas As Collection Private mGeneros As Collection Private GestorPel As GestorPelicula Sub New(ByVal IdPelicula As Integer, ByVal Titulo As String, ByVal TituloOriginal As String, ByVal AñoEstreno As Date, ByVal Duracion As Integer, ByVal Sinopsis As String, ByVal CartelPelicula As String) Me.mIdPelicula = IdPelicula Me.mTitulo = Titulo Me.mTituloOriginal = TituloOriginal Me.mAñoEstreno = AñoEstreno Me.mDuracion = Duracion Me.mSinopsis = Sinopsis Me.mCartelPelicula = CartelPelicula GestorPel = New GestorPelicula() End Sub Sub New() GestorPel = New GestorPelicula() End Sub Property IdPelicula As Integer Get Return mIdPelicula End Get Set(ByVal mIdPelicula As Integer) Me.mIdPelicula = mIdPelicula End Set End Property Property Titulo As String Get Return mTitulo End Get Set(ByVal mTitulo As String) Me.mTitulo = mTitulo End Set End Property Property TituloOriginal As String Get Return mTituloOriginal End Get Set(ByVal mTituloOriginal As String) Me.mTituloOriginal = mTituloOriginal End Set End Property Property AñoEstreno As Date Get Return mAñoEstreno End Get Set(ByVal mAñoEstreno As Date) Me.mAñoEstreno = mAñoEstreno End Set End Property Property Duracion As Integer Get Return mDuracion End Get Set(ByVal mDuracion As Integer) Me.mDuracion = mDuracion End Set End Property Property Sinopsis As String Get Return mSinopsis End Get Set(ByVal mSinopsis As String) Me.mSinopsis = mSinopsis End Set End Property Property CartelPelicula As String Get Return mCartelPelicula End Get Set(ByVal mCartelPelicula As String) Me.mCartelPelicula = mCartelPelicula End Set End Property Property ListaGeneros As Collection Get Return mGeneros End Get Set(ByVal mgeneros As Collection) Me.mGeneros = mgeneros End Set End Property Property ListaPersonas As Collection Get Return mPersonas End Get Set(ByVal mPersonas As Collection) Me.mPersonas = mPersonas End Set End Property Property ListaRoles As Collection Get Return mRoles End Get Set(ByVal mRoles As Collection) Me.mRoles = mRoles End Set End Property Sub leerPelicula(ByVal IdPelicula As Integer) GestorPel.read(IdPelicula, Me) End Sub Sub leerTitulo(ByVal Titulo As String) GestorPel.readtitulo(Titulo, Me) End Sub Function leertodos() As Collection Dim todos As Collection Me.GestorPel.readAll() todos = GestorPel.listaPeliculas Return todos End Function Sub leerGeneros() GestorPel.leerGenero(Me) ListaGeneros = GestorPel.listaGeneros End Sub Sub leerPersonas() GestorPel.leerPersonas(Me) ListaPersonas = GestorPel.listaPersonas End Sub Sub leerRoles(ByVal per As Persona) GestorPel.leerRoles(Me, per) ListaRoles = GestorPel.listaRoles End Sub Sub insertarPelicula() Me.GestorPel.insert(Me) End Sub Sub modificarPelicula() Me.GestorPel.update(Me) End Sub Sub eliminarPelicula() Me.GestorPel.delete(Me) End Sub Sub eliminarTodo() Me.GestorPel.deleteAll() End Sub Sub eliminarGen() Me.GestorPel.deletegen(Me) End Sub Sub eliminarTodoGen() Me.GestorPel.deleteAllPelGen() End Sub Sub eliminarPar() Me.GestorPel.deletePar(Me) End Sub Sub eliminarTodoPar() Me.GestorPel.deleteAllPar() End Sub Sub insertarGenero(ByVal gen As Genero) Me.GestorPel.insertgen(Me, gen) End Sub Sub eliminarGenero(ByVal gen As Genero) Me.GestorPel.deletegen(Me, gen) End Sub Sub insertarPersonaRol(ByVal per As Persona, ByVal ro As Rol) Me.GestorPel.insertperrol(Me, per, ro) End Sub Sub eliminarPersonaRol(ByVal per As Persona, ByVal ro As Rol) Me.GestorPel.deleteperrol(Me, per, ro) End Sub End Class
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' '' FacturaItem.vb '' Implementation of the Class FacturaItem '' Generated by Enterprise Architect '' Created on: 29-ago-2018 09:50:44 p.m. '' Original author: Hernan '' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' Modification history: '' '' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Option Explicit On Public Class FacturaItem Public Property id As Integer Public Property descripcion As String Public Property monto As Double End Class ' FacturaItem
Partial Public Class clsLnTrans_pe_enc Public Shared Function MaxID() As Integer Try Dim lMax As Integer = 0 'Validacion y estandarizacion de los datos Using lConnection As New SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("CST")) 'Acceso a los datos. Using lCommand As New SqlClient.SqlCommand(String.Format("SELECT ISNULL(Max(IdPedidoEnc),0) FROM trans_pe_enc"), lConnection) lCommand.CommandType = CommandType.Text lCommand.CommandTimeout = 200 lConnection.Open() Dim lReturnValue As Object = lCommand.ExecuteScalar() lConnection.Close() If lReturnValue IsNot DBNull.Value AndAlso lReturnValue IsNot Nothing Then lMax = CInt(lReturnValue) + 1 End If End Using End Using Return lMax Catch ex As Exception Throw ex End Try End Function Public Shared Function GetSingle(ByVal pIdPedidoEnc As Integer) As clsBeTrans_pe_enc Try Using lCnn As New SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("CST")) 'Acceso a los datos. Using lDTA As New SqlClient.SqlDataAdapter("SELECT * FROM trans_pe_enc WHERE IdPedidoEnc=@IdPedidoEnc", lCnn) lDTA.SelectCommand.CommandType = CommandType.Text lDTA.SelectCommand.Parameters.AddWithValue("@IdPedidoEnc", pIdPedidoEnc) Dim lDT As New DataTable() lDTA.Fill(lDT) If lDT IsNot Nothing AndAlso lDT.Rows.Count > 0 Then Dim lRow As DataRow = lDT.Rows(0) Dim vPedidoEnc As New clsBeTrans_pe_enc() Dim dPropBodega As New clsLnPropietario_bodega Dim dCliente As New clsLnCliente vPedidoEnc.IdPedidoEnc = CType(lRow("IdPedidoEnc"), System.Int32) vPedidoEnc.IdBodega = IIf(IsDBNull(CType(lRow("IdBodega"), System.Int32)), 0, CType(lRow("IdBodega"), System.Int32)) vPedidoEnc.Cliente.IdCliente = IIf(IsDBNull(CType(lRow("IdCliente"), System.Int32)), 0, CType(lRow("IdCliente"), System.Int32)) dCliente.Obtener(vPedidoEnc.Cliente) vPedidoEnc.IdMuelle = IIf(IsDBNull(CType(lRow("IdMuelle"), System.Int32)), 0, CType(lRow("IdMuelle"), System.Int32)) vPedidoEnc.PropietarioBodega.IdPropietarioBodega = IIf(IsDBNull(CType(lRow("IdPropietarioBodega"), System.Int32)), 0, CType(lRow("IdPropietarioBodega"), System.Int32)) dPropBodega.Obtener(vPedidoEnc.PropietarioBodega) vPedidoEnc.RoadIdRuta = IIf(IsDBNull(CType(lRow("RoadIdRuta"), System.Int32)), 0, CType(lRow("RoadIdRuta"), System.Int32)) vPedidoEnc.RoadIdVendedor = IIf(IsDBNull(CType(lRow("RoadIdVendedor"), System.Int32)), 0, CType(lRow("RoadIdVendedor"), System.Int32)) vPedidoEnc.Fecha_Pedido = IIf(IsDBNull(lRow("Fecha_Pedido")), Now, lRow("Fecha_Pedido")) vPedidoEnc.Hora_ini = IIf(IsDBNull(lRow("Hora_ini")), Now, lRow("Hora_ini")) vPedidoEnc.Hora_fin = IIf(IsDBNull(lRow("Hora_fin")), Now, lRow("Hora_fin")) vPedidoEnc.Ubicacion = IIf(IsDBNull(lRow("Ubicacion")), "", lRow("Ubicacion")) vPedidoEnc.Estado = IIf(IsDBNull(lRow("estado")), "", lRow("estado")) vPedidoEnc.Estado = IIf(IsDBNull(lRow("estado")), "", lRow("estado")) vPedidoEnc.No_despacho = IIf(IsDBNull(lRow("No_despacho")), "", lRow("No_despacho")) vPedidoEnc.Activo = IIf(IsDBNull(lRow("activo")), True, lRow("activo")) vPedidoEnc.User_agr = IIf(IsDBNull(lRow("user_agr")), "", lRow("user_agr")) vPedidoEnc.Fec_agr = IIf(IsDBNull(lRow("fec_agr")), Now, lRow("fec_agr")) vPedidoEnc.User_mod = IIf(IsDBNull(lRow("user_mod")), "", lRow("user_mod")) vPedidoEnc.Fec_mod = IIf(IsDBNull(lRow("fec_mod")), "", lRow("fec_mod")) vPedidoEnc.No_documento = IIf(IsDBNull(lRow("no_documento")), "", lRow("no_documento")) vPedidoEnc.Local = IIf(IsDBNull(lRow("local")), False, lRow("local")) vPedidoEnc.Pallet_primero = IIf(IsDBNull(lRow("pallet_primero")), False, lRow("pallet_primero")) vPedidoEnc.Dias_cliente = IIf(IsDBNull(lRow("dias_cliente")), "0", lRow("dias_cliente")) vPedidoEnc.Anulado = IIf(IsDBNull(lRow("anulado")), False, lRow("anulado")) vPedidoEnc.RoadKilometraje = IIf(IsDBNull(lRow("RoadKilometraje")), "0", lRow("RoadKilometraje")) vPedidoEnc.RoadFechaEntr = IIf(IsDBNull(lRow("RoadFechaEntr")), Now, lRow("RoadFechaEntr")) vPedidoEnc.RoadDirEntrega = IIf(IsDBNull(lRow("RoadDirEntrega")), "", lRow("RoadDirEntrega")) vPedidoEnc.RoadTotal = IIf(IsDBNull(lRow("RoadTotal")), "0", lRow("RoadTotal")) vPedidoEnc.RoadDesMonto = IIf(IsDBNull(lRow("RoadDesMonto")), "0", lRow("RoadDesMonto")) vPedidoEnc.RoadImpMonto = IIf(IsDBNull(lRow("RoadImpMonto")), "0", lRow("RoadImpMonto")) vPedidoEnc.RoadPeso = IIf(IsDBNull(lRow("RoadPeso")), "0", lRow("RoadPeso")) vPedidoEnc.RoadBandera = IIf(IsDBNull(lRow("RoadBandera")), "", lRow("RoadBandera")) vPedidoEnc.RoadBandera = IIf(IsDBNull(lRow("RoadBandera")), "", lRow("RoadBandera")) vPedidoEnc.RoadStatCom = IIf(IsDBNull(lRow("RoadStatCom")), "", lRow("RoadStatCom")) vPedidoEnc.RoadCalcoBJ = IIf(IsDBNull(lRow("RoadCalcoBJ")), "", lRow("RoadCalcoBJ")) vPedidoEnc.RoadImpres = IIf(IsDBNull(lRow("RoadImpres")), "", lRow("RoadImpres")) vPedidoEnc.RoadADD1 = IIf(IsDBNull(lRow("RoadADD1")), "", lRow("RoadADD1")) vPedidoEnc.RoadADD2 = IIf(IsDBNull(lRow("RoadADD2")), "", lRow("RoadADD2")) vPedidoEnc.RoadADD3 = IIf(IsDBNull(lRow("RoadADD3")), "", lRow("RoadADD3")) vPedidoEnc.RoadStatProc = IIf(IsDBNull(lRow("RoadStatProc")), "", lRow("RoadStatProc")) vPedidoEnc.RoadRechazado = IIf(IsDBNull(lRow("RoadRechazado")), "", lRow("RoadRechazado")) vPedidoEnc.RoadRazon_Rechazado = IIf(IsDBNull(lRow("RoadRazon_Rechazado")), "", lRow("RoadRazon_Rechazado")) vPedidoEnc.RoadInformado = IIf(IsDBNull(lRow("RoadInformado")), False, lRow("RoadInformado")) vPedidoEnc.RoadSucursal = IIf(IsDBNull(lRow("RoadSucursal")), False, lRow("RoadSucursal")) vPedidoEnc.RoadIdDespacho = IIf(IsDBNull(lRow("RoadIdDespacho")), False, lRow("RoadIdDespacho")) vPedidoEnc.RoadIdFacturacion = IIf(IsDBNull(lRow("RoadIdFacturacion")), False, lRow("RoadIdFacturacion")) vPedidoEnc.Detalle = clsLnTrans_pe_det.GetByPedidoEnc(vPedidoEnc.IdPedidoEnc) Return vPedidoEnc End If End Using End Using Return Nothing Catch ex As Exception Throw ex End Try End Function Public Shared Function GetAll(ByVal pActivo As Boolean, ByVal pFiltro As String) As DataTable Dim lTable As New DataTable("Result") Try vSQL = " SELECT trans_pe_enc.IdPedidoEnc, trans_pe_enc.no_documento, trans_pe_enc.Fecha_Pedido, " & _ " cliente.codigo + ' - ' + cliente.nombre_comercial AS Cliente, trans_pe_enc.estado AS Estado, bodega.nombre AS Bodega, " & _ " bodega_muelles.nombre AS Muelle, propietarios.nombre_comercial AS Propietario, " & _ " road_p_vendedor.codigo + ' - ' + road_p_vendedor.nombre AS RoadVendedor, road_ruta.CODIGO + ' - ' + road_ruta.NOMBRE AS RoadRuta, " & _ " trans_pe_enc.anulado AS Anualdo, trans_pe_enc.activo " & _ " FROM trans_pe_enc " & _ " INNER JOIN bodega ON trans_pe_enc.IdBodega = bodega.IdBodega " & _ " INNER JOIN propietario_bodega ON trans_pe_enc.IdPropietarioBodega = propietario_bodega.IdPropietarioBodega " & _ " AND bodega.IdBodega = propietario_bodega.IdBodega " & _ " INNER JOIN cliente ON trans_pe_enc.IdCliente = cliente.IdCliente " & _ " INNER JOIN bodega_muelles ON trans_pe_enc.IdMuelle = bodega_muelles.IdMuelle " & _ " AND bodega.IdBodega = bodega_muelles.IdBodega " & _ " INNER JOIN road_p_vendedor ON bodega.codigo = road_p_vendedor.codigo " & _ " AND trans_pe_enc.RoadIdVendedor = road_p_vendedor.IdVendedor " & _ " INNER JOIN road_ruta ON trans_pe_enc.RoadIdRuta = road_ruta.IdRuta " & _ " INNER JOIN propietarios ON propietario_bodega.IdPropietario = propietarios.IdPropietario " & _ " AND cliente.IdPropietario = propietarios.IdPropietario " If pActivo = True Then vSQL += " AND trans_pe_enc.Activo=1" Else vSQL += " AND trans_pe_enc.Activo=0" End If If String.IsNullOrEmpty(pFiltro) = False Then vSQL += String.Format(" AND (trans_pe_enc.IdPedidoEnc LIKE '%{0}%'", pFiltro) vSQL += String.Format(" OR trans_pe_enc.no_documento LIKE '%{0}%'", pFiltro) vSQL += String.Format(" OR cliente.codigo + ' - ' + cliente.nombre_comerciall LIKE '%{0}%'", pFiltro) vSQL += String.Format(" OR propietarios.nombre_comercial LIKE '%{0}%')", pFiltro) End If Using lConnection As New SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("CST")) Using lDataAdapter As New SqlClient.SqlDataAdapter(vSQL, lConnection) lDataAdapter.SelectCommand.CommandType = CommandType.Text lDataAdapter.Fill(lTable) End Using End Using Return lTable Catch ex As Exception Throw ex End Try End Function End Class
'--------------------------------------------------------------------------- ' Author : Nguyen Khanh Tung ' Company : Thiên An ESS ' Created Date : Sunday, May 04, 2008 '--------------------------------------------------------------------------- Imports System Namespace Entity Public Class LoaiGiayTo #Region "Constructor" #End Region #Region "Var" Private mID_giay_to As Integer = 0 Private mMa_giay_to As String = "" Private mTen_giay_to As String = "" #End Region #Region "Property" Public Property ID_giay_to() As Integer Get Return mID_giay_to End Get Set(ByVal Value As Integer) mID_giay_to = Value End Set End Property Public Property Ma_giay_to() As String Get Return mMa_giay_to End Get Set(ByVal Value As String) mMa_giay_to = Value End Set End Property Public Property Ten_giay_to() As String Get Return mTen_giay_to End Get Set(ByVal Value As String) mTen_giay_to = Value End Set End Property #End Region End Class End Namespace
Imports Microsoft.VisualBasic Public Class LanguageClass Public Shared Function GetLanguageName(ByVal LanguageCode As String) As String Dim Lang As String = "" Select Case LanguageCode Case "en", "en-us" Lang = "English" Case "zh-hk" Lang = "繁體中文" Case "zh-cn" Lang = "简体中文" End Select Return Lang End Function End Class
''DTO Definition - ExcelMapping (to ExcelMapping)'Generated from Table:ExcelMapping Imports RTIS.DataLayer Imports RTIS.DataLayer.clsDBConnBase Imports RTIS.CommonVB.clsGeneralA Imports RTIS.CommonVB Public Class dtoExcelMapping : Inherits dtoBase Private pExcelMapping As dmExcelMapping Public Sub New(ByRef rDBSource As clsDBConnBase) MyBase.New(rDBSource) End Sub Protected Overrides Sub SetTableDetails() pTableName = "ExcelMapping" pKeyFieldName = "ExcelMappingID" pUseSoftDelete = False pRowVersionColName = "rowversion" pConcurrencyType = eConcurrencyType.OverwriteChanges End Sub Overrides Property ObjectKeyFieldValue() As Integer Get ObjectKeyFieldValue = pExcelMapping.ExcelMappingID End Get Set(ByVal value As Integer) pExcelMapping.ExcelMappingID = value End Set End Property Overrides Property IsDirtyValue() As Boolean Get IsDirtyValue = pExcelMapping.IsDirty End Get Set(ByVal value As Boolean) pExcelMapping.IsDirty = value End Set End Property Overrides Property RowVersionValue() As ULong Get End Get Set(ByVal value As ULong) End Set End Property Overrides Sub ObjectToSQLInfo(ByRef rFieldList As String, ByRef rParamList As String, ByRef rParameterValues As System.Data.IDataParameterCollection, ByVal vSetList As Boolean) Dim mDummy As String = "" Dim mDummy2 As String = "" If vSetList Then DBSource.AddParamPropertyInfo(rParameterValues, mDummy, mDummy2, vSetList, "ExcelMappingID", pExcelMapping.ExcelMappingID) End If With pExcelMapping DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ImportTypeID", .ImportTypeID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ColumnID", .ColumnID) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "CellValue", StringToDBValue(.CellValue)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "TranslationValue", .TranslationValue) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "AdditionalText", StringToDBValue(.AdditionalText)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "TranslationText", StringToDBValue(.TranslationText)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "ColumnHeading", StringToDBValue(.ColumnHeading)) DBSource.AddParamPropertyInfo(rParameterValues, rFieldList, rParamList, vSetList, "RefListID", .RefListID) End With End Sub Overrides Function ReaderToObject(ByRef rDataReader As IDataReader) As Boolean Dim mOK As Boolean Try If pExcelMapping Is Nothing Then SetObjectToNew() With pExcelMapping .ExcelMappingID = DBReadInt32(rDataReader, "ExcelMappingID") .ImportTypeID = DBReadInt32(rDataReader, "ImportTypeID") .ColumnID = DBReadInt32(rDataReader, "ColumnID") .CellValue = DBReadString(rDataReader, "CellValue") .TranslationValue = DBReadInt32(rDataReader, "TranslationValue") .AdditionalText = DBReadString(rDataReader, "AdditionalText") .TranslationText = DBReadString(rDataReader, "TranslationText") .ColumnHeading = DBReadString(rDataReader, "ColumnHeading") .RefListID = DBReadInt32(rDataReader, "RefListID") pExcelMapping.IsDirty = False End With mOK = True Catch Ex As Exception mOK = False If clsErrorHandler.HandleError(Ex, clsErrorHandler.PolicyDataLayer) Then Throw ' or raise an error ? mOK = False Finally End Try Return mOK End Function Protected Overrides Function SetObjectToNew() As Object pExcelMapping = New dmExcelMapping ' Or .NewBlankExcelMapping Return pExcelMapping End Function Public Function LoadExcelMapping(ByRef rExcelMapping As dmExcelMapping, ByVal vExcelMappingID As Integer) As Boolean Dim mOK As Boolean mOK = LoadObject(vExcelMappingID) If mOK Then rExcelMapping = pExcelMapping Else rExcelMapping = Nothing End If pExcelMapping = Nothing Return mOK End Function Public Function SaveExcelMapping(ByRef rExcelMapping As dmExcelMapping) As Boolean Dim mOK As Boolean pExcelMapping = rExcelMapping mOK = SaveObject() pExcelMapping = Nothing Return mOK End Function Public Function LoadExcelMappingCollection(ByRef rExcelMappings As colExcelMappings) As Boolean Dim mParams As New Hashtable Dim mOK As Boolean ''mParams.Add("@ImportTypeID", vImportTypeID) mOK = MyBase.LoadCollection(rExcelMappings, mParams, "ExcelMappingID") If mOK Then rExcelMappings.IsDirty = False Return mOK End Function Public Function LoadExcelMappingCollection(ByRef rExcelMappings As colExcelMappings, ByVal vImportTypeID As Integer) As Boolean Dim mParams As New Hashtable Dim mOK As Boolean mParams.Add("@ImportTypeID", vImportTypeID) mOK = MyBase.LoadCollection(rExcelMappings, mParams, "ExcelMappingID") If mOK Then rExcelMappings.IsDirty = False Return mOK End Function Public Function SaveExcelMappingCollection(ByRef rCollection As colExcelMappings) As Boolean Dim mParams As New Hashtable Dim mAllOK As Boolean Dim mCount As Integer Dim mIDs As String = "" If rCollection.IsDirty Then ''mParams.Add("@ImportTypeID", vImportTypeID) ''Approach where delete items not found in the collection ''If rCollection.SomeRemoved Then '' For Each Me.pExcelMapping In rCollection '' If pExcelMapping.ExcelMappingID <> 0 Then '' mCount = mCount + 1 '' If mCount > 1 Then mIDs = mIDs & ", " '' mIDs = mIDs & pExcelMapping.ExcelMappingID.ToString '' End If '' Next '' mAllOK = MyBase.CollectionDeleteMissingItems(mParams, mIDs) ''Else '' mAllOK = True ''End If ''Alternative Approach - where maintain collection of deleted items If rCollection.SomeDeleted Then mAllOK = True For Each Me.pExcelMapping In rCollection.DeletedItems If pExcelMapping.ExcelMappingID <> 0 Then If mAllOK Then mAllOK = MyBase.DeleteDBRecord(pExcelMapping.ExcelMappingID) End If Next Else mAllOK = True End If For Each Me.pExcelMapping In rCollection If pExcelMapping.IsDirty Or pExcelMapping.ExcelMappingID = 0 Then 'Or pExcelMapping.ExcelMappingID = 0 If mAllOK Then mAllOK = SaveObject() End If Next If mAllOK Then rCollection.IsDirty = False Else mAllOK = True End If Return mAllOK End Function Public Function SaveExcelMappingCollection(ByRef rCollection As colExcelMappings, ByVal vImportTypeID As Integer) As Boolean Dim mParams As New Hashtable Dim mAllOK As Boolean Dim mCount As Integer Dim mIDs As String = "" If rCollection.IsDirty Then mParams.Add("@ImportTypeID", vImportTypeID) ''Approach where delete items not found in the collection ''If rCollection.SomeRemoved Then '' For Each Me.pExcelMapping In rCollection '' If pExcelMapping.ExcelMappingID <> 0 Then '' mCount = mCount + 1 '' If mCount > 1 Then mIDs = mIDs & ", " '' mIDs = mIDs & pExcelMapping.ExcelMappingID.ToString '' End If '' Next '' mAllOK = MyBase.CollectionDeleteMissingItems(mParams, mIDs) ''Else '' mAllOK = True ''End If ''Alternative Approach - where maintain collection of deleted items If rCollection.SomeDeleted Then mAllOK = True For Each Me.pExcelMapping In rCollection.DeletedItems If pExcelMapping.ExcelMappingID <> 0 Then If mAllOK Then mAllOK = MyBase.DeleteDBRecord(pExcelMapping.ExcelMappingID) End If Next Else mAllOK = True End If For Each Me.pExcelMapping In rCollection If pExcelMapping.IsDirty Or pExcelMapping.ImportTypeID <> vImportTypeID Or pExcelMapping.ExcelMappingID = 0 Then 'Or pExcelMapping.ExcelMappingID = 0 pExcelMapping.ImportTypeID = vImportTypeID If mAllOK Then mAllOK = SaveObject() End If Next If mAllOK Then rCollection.IsDirty = False Else mAllOK = True End If Return mAllOK End Function End Class
Imports Microsoft.Xna.Framework.Graphics Public Class TextureObject ''' <summary> ''' Unique name of the texture object ''' </summary> Public Name As String ''' <summary> ''' Texture of the object ''' </summary> Public Texture As Texture2D ''' <summary> ''' If set to true the texture will be randomly rotated for each object it is used on ''' </summary> Public HasRandomTextureRotation As Boolean = False ''' <summary> ''' If set to true objects with this texture won't have collision ''' </summary> Public IsFoliage As Boolean = False Sub New(ByRef _name As String, ByRef _texture As Texture2D, _randtexrot As Boolean, _foliage As Boolean) Name = _name Texture = _texture HasRandomTextureRotation = _randtexrot IsFoliage = _foliage End Sub End Class
'=============================================================================== ' Microsoft patterns & practices ' CompositeUI Application Block '=============================================================================== ' Copyright © Microsoft Corporation. All rights reserved. ' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY ' OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT ' LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND ' FITNESS FOR A PARTICULAR PURPOSE. '=============================================================================== Imports Microsoft.VisualBasic Imports System ''' <summary> ''' Indicates that this assembly has a dependency on another named module. ''' The other named module will be loaded before this module. Can be used ''' multiple times to indicate multiple dependencies. ''' </summary> <AttributeUsage(AttributeTargets.Assembly, AllowMultiple:=True)> _ Public NotInheritable Class ModuleDependencyAttribute Inherits Attribute Private innerName As String ''' <summary> ''' Creates a new instance of the <see cref="ModuleDependencyAttribute"/> class ''' using the provided module name as a dependency. ''' </summary> ''' <param name="name">The name of the module which this module depends on.</param> Public Sub New(ByVal aName As String) Me.innerName = aName End Sub ''' <summary> ''' The name of the module which this module depends on. ''' </summary> Public Property Name() As String Get Return innerName End Get Set(ByVal value As String) innerName = value End Set End Property End Class
Imports System.IO Imports System.Reflection Public Class Helpers Public Shared Path As String = "save.bin" Public Shared Function CreateMenuListFromDir(dirName As String) As List(Of IMenuItem) Dim items As New List(Of IMenuItem) For Each item As String In Directory.GetFiles($"{Environment.CurrentDirectory}\..\..\{dirName}") Dim className As String = IO.Path.GetFileNameWithoutExtension(item) Dim t As Type = Type.GetType($"VirtualPets.{className}") If t.GetField("Ignore", BindingFlags.Static Or BindingFlags.NonPublic) IsNot Nothing Then Continue For If t.GetInterface("VirtualPets.IMenuItem") IsNot Nothing Then items.Add(Activator.CreateInstance(t)) Next Return items End Function End Class
Imports System Imports System.Data Imports System.Configuration Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Namespace EntitySpaces.Websites.GridLoader ''' <summary> ''' Summary description for Utilities ''' </summary> Public Class Utilities ' private ctor all functions are static Private Sub New() End Sub Public Shared Function ConstructUrl(ByVal controlKey As String, ByVal pageName As String) As String Return String.Format("~/Index.aspx?{0}={1}", controlKey, pageName) End Function Public Shared Function ConstructUrl(ByVal ParamArray args As String()) As String Dim theUrl As String = "~/Index.aspx?" For Each parameter As String In args theUrl = theUrl + parameter Next Return theUrl End Function End Class End Namespace
Option Strict On Option Explicit On Imports System.Xml Imports Microsoft.Web.Services3 Imports Microsoft.Web.Services3.Addressing Imports Microsoft.Web.Services3.Messaging Imports System.Text Imports httpUtil = System.Web.HttpUtility Imports System Imports System.Collections.Generic Imports Contensive.BaseClasses Namespace Contensive.Addons.tlpa ' ' Sample Vb addon ' Public Class housekeepClass Inherits AddonBaseClass ' ' Field memberMaxSyncStatus (Organizations and People) holds the state of the record ' memberMaxSyncStatus is tracked in Member Rules in the create key field ' Const recordNotUpdated = 1 ' Record Needs to be updated Const recordChangedAndNeedsToBeUpdated = 2 ' Record needs to be requested from membermax Const recordUpdated = 3 ' Record requested from membermax ' Public Const spHousekeepStartTime As String = "TLPA Housekeep Start Time" Public Const spSyncEnabled As String = "TLPA MemberMax Sync Enabled" Public Const spHousekeepLastExecution As String = "TLPA Housekeep Last Execution" ' 'Hi Jay, I think this is what you’re after. TLPA MbrxSoapLicenseNo = MBR3853850 Sincerely, Kerry ' Public Const MbrxSoapLicenseNo As String = "MBR3853850" ' Private _allowLogging As String = Nothing Private nowDate As Date 'Private logFile As String 'Private soapUtils As New soapUtilsClass Private errCount As Integer = 0 Private modeFull As Boolean = False Private requestAddr As String = "" ' ' Envelops ' Private Const memberMaxSoapServicesTxtEnv As String = "" _ & "<?xml version=""1.0"" encoding=""ISO-8859-1""?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" _ & "<SOAP-ENV:Body>" _ & "<tns:SoapServicesTxt xmlns:tns=""http://www.MemberMax.com/namespace/default"" >" _ & "<inText xsi:type=""xsd:string"">{{inText}}</inText>" _ & "</tns:SoapServicesTxt>" _ & "</SOAP-ENV:Body>" _ & "</SOAP-ENV:Envelope>" _ & "" ' Private Const memberMaxSoapServicesBlobEnv As String = "" _ & "<?xml version=""1.0"" encoding=""ISO-8859-1""?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" _ & "<SOAP-ENV:Body>" _ & "<tns:SoapServicesBlob xmlns:tns=""http://www.MemberMax.com/namespace/default"" >" _ & "<inText xsi:type=""xsd:string"">{{inText}}</inText>" _ & "</tns:SoapServicesBlob>" _ & "</SOAP-ENV:Body>" _ & "</SOAP-ENV:Envelope>" _ & "" ' ' Requests ' Private Const memberMaxSoapRequestCompanyList3 As String = "" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>" & MbrxSoapLicenseNo & "</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>CompanyList3</RequestedMethod>" _ & "<CompanyForOrgID>All</CompanyForOrgID>" _ & "<MemberShipStatus>All</MemberShipStatus>" _ & "</RequestedMethodParams>" _ & "</RequestedMethodWrapper>" _ & "" Private Const memberMaxSoapRequestAllCommittees As String = "" _ & "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>" & MbrxSoapLicenseNo & "</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>AllCommittees</RequestedMethod>" _ & "<CommitteesForOrgID>TLPA</CommitteesForOrgID>" _ & "<CommitteesForChapter>All</CommitteesForChapter>" _ & "</RequestedMethodParams>" _ & "</RequestedMethodWrapper>" _ & "" Private Const memberMaxSoapRequestCompanyDetail As String = "" _ & "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>" & MbrxSoapLicenseNo & "</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>CompanyDetail</RequestedMethod>" _ & "<Companyfilter>{{memberMaxCompanyID}}</Companyfilter>" _ & "<KeyWordFilter>All</KeyWordFilter>" _ & "<RelatedPersonfilter>All</RelatedPersonfilter>" _ & "<ChaptersFilter>All</ChaptersFilter>" _ & "<RelatedRecordsFilter>All</RelatedRecordsFilter>" _ & "<SecondGroupsFilter>ActiveOnly</SecondGroupsFilter>" _ & "</RequestedMethodParams>" _ & "</RequestedMethodWrapper>" _ & "" '"<SecondGroupsFilter>ActiveOnly</SecondGroupsFilter>" Private Const memberMaxSoapRequest As String = "" _ & "<inText xsi:type=""xsd:string"">" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>" & MbrxSoapLicenseNo & "</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>PersonDetailDump</RequestedMethod>" _ & "<Personfilter>{{memberMaxPersonID}}</Personfilter>" _ & "<KeyWordFilter>All</KeyWordFilter>" _ & "<CommitteeFilter>All</CommitteeFilter>" _ & "<ChaptersFilter>All</ChaptersFilter>" _ & "<RelatedRecordsFilter>All</RelatedRecordsFilter>" _ & "</RequestedMethodParams> " _ & "</RequestedMethodWrapper>" _ & "" ' Private Const memberMaxSoapRequestRemoteLogin As String = "" _ & "<?xml version=""1.0"" encoding=""UTF-8""?>" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>Designer</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>RemoteLogon</RequestedMethod>" _ & "<LogonFor>Person</LogonFor>" _ & "<WebLogon>McGow15263</WebLogon>" _ & "<WebPassword>15263</WebPassword>" _ & "<GenerateMbrMaxSession>On</GenerateMbrMaxSession>" _ & "<CommitteeFilter>ActiveOnly</CommitteeFilter>" _ & "<SecondaryDuesFilter>Off</SecondaryDuesFilter>" _ & "</RequestedMethodParams>" _ & "</RequestedMethodWrapper>" _ & "" ' Private Const memberMaxSoapRequestGetChangedCompanies As String = "" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>" & MbrxSoapLicenseNo & "</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>GetChangedCompanies</RequestedMethod>" _ & "<CompanyForOrgID>All</CompanyForOrgID>" _ & "<Orgfilter>TLPA</Orgfilter>" _ & "<changedSinceDate>{{lastSyncDate}}</changedSinceDate>" _ & "<changedSinceTime>{{lastSyncTime}}</changedSinceTime>" _ & "<MemberShipStatus>All</MemberShipStatus>" _ & "</RequestedMethodParams>" _ & "</RequestedMethodWrapper>" _ & "" Private Const memberMaxSoapRequestPersonDetailDump As String = "" _ & "<RequestedMethodWrapper>" _ & "<RequestedMethodParams>" _ & "<MbrxSoapLicenseNo>" & MbrxSoapLicenseNo & "</MbrxSoapLicenseNo>" _ & "<DataReturnFormat>XML</DataReturnFormat>" _ & "<ServerDebugLog>Off</ServerDebugLog>" _ & "<RequestedMethod>PersonDetailDump</RequestedMethod>" _ & "<Personfilter>{{memberMaxPersonID}}</Personfilter>" _ & "<KeyWordFilter>All</KeyWordFilter>" _ & "<CommitteeFilter>All</CommitteeFilter>" _ & "<ChaptersFilter>All</ChaptersFilter>" _ & "<RelatedRecordsFilter>All</RelatedRecordsFilter>" _ & "</RequestedMethodParams> " _ & "</RequestedMethodWrapper>" _ & "" 'Private Const memberMaxSoapRequest As String = "" _ ' & "" ' Private Const memberMaxSoapServicesBlobResponseNode As String = "ns1:SoapServicesBlobResponse" ' ' fields to add ' Organizations ' .memberMaxSyncStatus ' .memberMaxDateDeleted ' .memberMaxMemberNo ' .memberMaxMemberType ' ' ccMembers ' .memberMaxSyncStatus ' .memberMaxDateDeleted ' .memberMaxMemberNo ' ' ccGroups ' .memberMaxCommitteeId ' ' '==================================================================================================== ''' <summary> ''' housekeep Addon ''' </summary> ''' <param name="CP"></param> ''' <returns></returns> ''' <remarks></remarks> Public Overrides Function Execute(ByVal CP As Contensive.BaseClasses.CPBaseClass) As Object Execute = "" Try ' Dim rightNow As Date = Now() Dim cs As CPCSBaseClass = CP.CSNew() Dim housekeepStartTime As Integer = CP.Site.GetInteger(spHousekeepStartTime, "2") Dim syncEnabled As Boolean = CP.Utils.EncodeBoolean(CP.Site.GetProperty(spSyncEnabled, "0")) Dim housekeepLastExecution As Date = CP.Site.GetDate(spHousekeepLastExecution, Date.MinValue.ToString) ' If (housekeepLastExecution.Date < rightNow.Date) And (rightNow.Hour >= housekeepStartTime) Then Call CP.Site.SetProperty(spHousekeepLastExecution, rightNow.ToString) ' Call appendLog(CP, "housekeep start ") ' ' run the sync first ' If Not syncEnabled Then appendLog(CP, "MemberMax sync skipped because it is disabled in settings.") Else Call syncMemberMax(CP) End If ' ' verify longitude and latitude for all organzizations without it ' Call populateLonglat(CP) ' ' build subcategory select for membership directory ' Call buildOrganizationSubcategorySelect(CP) ' ' Build out the SEO pages ' Call buildSEOPages(CP) ' ' build city selectors for Find-A-Ride ' Call buildFleetCitySelectors(CP) ' ' build state selectors for Find-A-Ride ' Call buildFleetStateSelector(CP) ' ' build country selector ' Call buildFleetCountrySelector(CP) ' ' build home page carosel ' Call buildHomePageCarousel(CP) appendLog(CP, "housekeep, exit") End If Catch ex As Exception Try appendLog(CP, "ERROR, execute() - " & ex.ToString) CP.Site.ErrorReport(ex) appendLog(CP, "housekeep, error exit") Catch errObj As Exception End Try End Try ' Return Execute End Function ' '==================================================================================================== ''' <summary> ''' buildHomePageCarousel ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub buildHomePageCarousel(cp As CPBaseClass) Try ' appendLog(cp, "buildHomePageCarousel") ' Dim cs As CPCSBaseClass Dim sql As String Dim link As String Dim homePageCarosel As String Dim img As String ' homePageCarosel = "<!-- HomePageCarosel built in housekeep " & Now.Year.ToString & Now.Month.ToString.PadLeft(2, "0"c) & Now.Day.ToString.PadLeft(2, "0"c) & " -->" cs = cp.CSNew sql = "" sql = sql & "select o.name, o.link, o.memberMaxCompanyID" sql = sql & " from organizations o" sql = sql & " where" sql = sql & " (o.memberMaxMemberType<>'Not A Member')" 'sql = sql & " and(o.memberMaxCompanyID is not null)" sql = sql & " and(o.memberMaxHasLogo>0)" sql = sql & " order by o.name" ' If cs.OpenSQL(sql) Then Do link = cs.GetText("link") img = "https://members.tlpa.org/scripts/4disapi.dll/4DACTION/WebsGetImage/Company/" & cs.GetText("memberMaxCompanyID") 'cp.Utils.AppendLog("TLPA Images", img) If link <> "" Then homePageCarosel = homePageCarosel & vbCrLf & vbTab & vbTab & "<div><a href=""" & link & """ target=""_blank""><img src=""" & img & """ alt="""" /></a></div>" Else homePageCarosel = homePageCarosel & vbCrLf & vbTab & vbTab & "<div><img src=""" & img & """ alt="""" /></div>" End If Call cs.GoNext() Loop While cs.OK() homePageCarosel = vbCrLf & vbTab & "<div id=""js-members-carousel"" class=""members-carousel"">" & homePageCarosel & "</div>" End If Call cs.Close() ' ' update the html in the addon ' cp.File.SaveVirtual("homePageCarousel.html", homePageCarosel) ' appendLog(cp, "buildHomePageCarousel, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in buildHomePageCarousel") ' appendLog(cp, "buildHomePageCarousel, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' buildFleetCitySelectors ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub buildFleetCitySelectors(cp As CPBaseClass) Try Dim cs As CPCSBaseClass Dim cs2 As CPCSBaseClass Dim layout As String Dim laststate As String Dim state As String Dim city As String Dim sql As String Dim stateId As Integer ' appendLog(cp, "buildFleetCitySelectors") ' layout = "" cs = cp.CSNew() cs2 = cp.CSNew() sql = "select distinct state,city from organizations where (state is not null)and(country='USA')and(memberMaxMemberType='Fleet Operator') order by state,city" If cs.OpenSQL(sql) Then stateId = 0 laststate = cs.GetText("state ") If cs2.Open("states", "(abbreviation=" & cp.Db.EncodeSQLText(laststate) & ")") Then stateId = cs2.GetInteger("id") End If cs2.Close() layout = layout & vbCrLf & "<select class=""lptaCitySelector"" id=""st-" & stateId & """ name=""citySelect"">" Do city = cs.GetText("city") state = cs.GetText("state") If state <> laststate Then If cs2.Open("states", "(abbreviation=" & cp.Db.EncodeSQLText(state) & ")") Then stateId = cs2.GetInteger("id") End If cs2.Close() If stateId > 0 Then layout = layout & vbCrLf & "</select>" layout = layout & vbCrLf & "<select class=""lptaCitySelector"" id=""st-" & stateId & """ name="""">" End If End If layout = layout & vbCrLf & vbTab & "<option>" & city & "</option>" laststate = state stateId = 0 Call cs.GoNext() Loop While cs.OK() layout = layout & vbCrLf & "</select>" End If Call cs.Close() If layout <> "" Then If Not cs.Open("layouts", "name='TLPACitySelectLayout'") Then Call cs.Close() Call cs.Insert("layouts") Call cs.SetField("name", "TLPACitySelectLayout") End If If cs.OK() Then Call cs.SetField("layout", layout) End If Call cs.Close() End If ' appendLog(cp, "buildFleetCitySelectors, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in buildFleetCitySelectors") ' appendLog(cp, "buildFleetCitySelectors, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' buildFleetCountrySelector ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub buildFleetCountrySelector(cp As CPBaseClass) Try Dim cs As CPCSBaseClass Dim layout As String = "" Dim sql As String ' appendLog(cp, "buildFleetCountrySelector") ' layout = "" cs = cp.CSNew() sql = "select distinct country from organizations where (country is not null)and(memberMaxMemberType='Fleet Operator') order by country" If cs.OpenSQL(sql) Then Do layout &= vbCrLf & vbTab & "<option>" & cs.GetText("country") & "</option>" Call cs.GoNext() Loop While cs.OK() layout = "" _ & vbCrLf & vbTab & "<select id=""js-findRideCountry"" size=""1"" name=""country"">" _ & vbCrLf & vbTab & vbTab & "<option value="""">Select Country</option>" _ & layout _ & vbCrLf & vbTab & "</select>" End If Call cs.Close() If layout <> "" Then If Not cs.Open("layouts", "name='TLPACountrySelectLayout'") Then Call cs.Close() Call cs.Insert("layouts") Call cs.SetField("name", "TLPACountrySelectLayout") End If If cs.OK() Then Call cs.SetField("layout", layout) End If Call cs.Close() End If ' appendLog(cp, "buildFleetCountrySelector, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in buildFleetCountrySelector") ' appendLog(cp, "buildFleetCountrySelector, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' buildFleetStateSelector ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub buildFleetStateSelector(cp As CPBaseClass) Try Dim cs As CPCSBaseClass Dim layout As String = "" Dim sql As String Dim stateId As Integer ' appendLog(cp, "buildFleetStateSelector") ' layout = "" cs = cp.CSNew() sql = "select distinct s.name as state,s.id as stateId from organizations o left join ccstates s on s.abbreviation=o.state where (s.id is not null)and(o.country='USA')and(o.memberMaxMemberType='Fleet Operator') order by s.name" If cs.OpenSQL(sql) Then Do stateId = cs.GetInteger("stateId") If stateId > 0 Then layout &= vbCrLf & vbTab & "<option value=""" & stateId.ToString() & """>" & cs.GetText("state") & "</option>" End If Call cs.GoNext() Loop While cs.OK() layout = "" _ & vbCrLf & vbTab & "<select id=""js-findRideState"" size=""1"" name=""stateId"">" _ & vbCrLf & vbTab & vbTab & "<option value="""">Select State</option>" _ & layout _ & vbCrLf & vbTab & "</select>" End If Call cs.Close() If layout <> "" Then If Not cs.Open("layouts", "name='TLPAStateSelectLayout'") Then Call cs.Close() Call cs.Insert("layouts") Call cs.SetField("name", "TLPAStateSelectLayout") End If If cs.OK() Then Call cs.SetField("layout", layout) End If Call cs.Close() End If ' appendLog(cp, "buildFleetStateSelector, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in buildFleetStateSelector") ' appendLog(cp, "buildFleetStateSelector, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' buildSEOPages ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub buildSEOPages(cp As CPBaseClass) Try Dim cs As CPCSBaseClass Dim cs2 As CPCSBaseClass Dim pageBody As String Dim state As String Dim city As String Dim sql As String Dim stateId As Integer Dim pagename As String Dim cnt As Integer Dim cityListPageId As Integer Dim cityListPageBody As String Dim cityListPageName As String = "TLPA Member Cities" Dim pageLink As String Dim pageid As Integer Dim contentId As Integer Dim pageKeyWords As String Dim pageHeadline As String Dim stateAbbr As String = "" ' appendLog(cp, "buildSEOPages") ' cs = cp.CSNew() cs2 = cp.CSNew() ' cityListPageBody = "" cityListPageId = 0 If cs.Open("page content", "name=" & cp.Db.EncodeSQLText(cityListPageName)) Then cityListPageId = cs.GetInteger("id") End If Call cs.Close() If cityListPageId = 0 Then Call cs.Insert("page content") cityListPageId = cs.GetInteger("id") Call cs.SetField("name", cityListPageName) Call cs.Close() End If ' sql = "select distinct state,city from organizations where (memberMaxCompanyId is not null)and(memberMaxMemberType='Fleet Operator')and(city is not null)and(state is not null) order by state,city" If cs.OpenSQL(sql) Then stateId = 0 cnt = 0 Do city = cs.GetText("city") stateAbbr = cs.GetText("state") state = stateAbbr If cs2.Open("states", "(abbreviation=" & cp.Db.EncodeSQLText(stateAbbr) & ")") Then state = cs2.GetText("name") End If cs2.Close() ' pageHeadline = "Taxi, Limo, and Paratransit in " & city & ", " & state pageBody = "" pagename = "SEO City Page " & state & ", " & city pageLink = "/Taxi_Limo_and_Paratransit_in_" & city & "_" & state pageKeyWords = "Taxi, Limo, Paratransit, " & city & ", " & state ' appendLog(cp, "buildSEOPages, city [" & city & "], state [" & state & "]") ' ' list of all member companies in that city ' Dim orgList As String = "" If cs2.Open("organizations", "(memberMaxCompanyId is not null)and(memberMaxMemberType='Fleet Operator')and(city=" & cp.Db.EncodeSQLText(city) & ")and(state=" & cp.Db.EncodeSQLText(stateAbbr) & ")") Then Do ' appendLog(cp, "buildSEOPages, city [" & city & "], state [" & stateAbbr & "], member [" & cs2.GetText("name") & "]") ' Dim orgBody As String orgBody = "" orgBody = "<div class=""seoOrgListName"">" & cs2.GetText("name") & "</div>" Dim address As String = cs2.GetText("address1") If address <> "" Then orgBody &= "<div class=""seoOrgListAddress1"">" & address & "</div>" End If address = city & ", " & state & " " & cs2.GetText("zip") If address <> "" Then orgBody &= "<div class=""seoOrgListAddress2"">" & address & "</div>" End If If cs2.GetText("logo") <> "" Then orgBody &= "<div class=""seoOrgListLogo""><img src=""" & cp.Site.FilePath & cs2.GetText("logo") & """></div>" End If If cs2.GetText("phone") <> "" Then orgBody &= "<div class=""seoOrgListPhone"">Main Phone: " & cs2.GetText("phone") & "</div>" End If If cs2.GetText("phone2") <> "" Then orgBody &= "<div class=""seoOrgListTollFree"">Toll Free: " & cs2.GetText("phone2") & "</div>" End If If cs2.GetText("phoneSales") <> "" Then orgBody &= "<div class=""seoOrgListSales"">Reservations/Sales: " & cs2.GetText("phoneSales") & "</div>" End If If cs2.GetText("email") <> "" Then orgBody &= "<div class=""seoOrgListEmail"">E-mail: " & cs2.GetText("email") & "</div>" End If If cs2.GetText("copyFilename") <> "" Then orgBody &= "<div class=""seoOrgListDescription"">Member Service Description: " & cs2.GetText("copyFilename") & "</div>" End If If cs2.GetText("web") <> "" Then Dim web As String = cs2.GetText("web") If web.IndexOf("://") < 0 Then web = "http://" & web End If orgBody &= "<div class=""seoOrgListWeb""><a href=""" & web & """>" & web & "</a></div>" End If orgList &= vbCrLf & vbTab & vbTab & "<li class=""seoOrgListItem"">" _ & orgBody _ & vbCrLf & vbTab & vbTab & "</li>" cs2.GoNext() Loop While cs2.OK End If cs2.Close() If orgList <> "" Then pageBody &= vbCrLf & vbTab & "<ul class=""seoOrgList"">" & orgList & vbCrLf & vbTab & "</ul>" End If ' If pageBody <> "" Then pageid = 0 If Not cs2.Open("page content", "name=" & cp.Db.EncodeSQLText(pagename)) Then Call cs2.Close() Call cs2.Insert("page content") Call cs2.SetField("name", pagename) End If If cs2.OK() Then pageid = cs2.GetInteger("id") Call cs2.SetField("copyFilename", pageBody) Call cs2.SetField("headline", pageHeadline) Call cs2.SetField("menuheadline", pageHeadline) Call cs2.SetField("linkAlias", pageLink) Call cs2.SetField("parentid", cityListPageId.ToString()) contentId = cs2.GetInteger("contentcontrolid") End If Call cs2.Close() ' If pageid > 0 Then If Not cs2.Open("meta content", "(contentid=" & contentId & ")and(recordid=" & pageid & ")") Then Call cs2.Close() Call cs2.Insert("meta content") Call cs2.SetField("contentid", contentId.ToString()) Call cs2.SetField("recordid", pageid.ToString()) End If If cs2.OK() Then Call cs2.SetField("name", pageHeadline) Call cs2.SetField("metaDescription", pageHeadline) Call cs2.SetField("MetaKeywordList", pageKeyWords) End If Call cs2.Close() End If End If If Not cs2.Open("link aliases", "(pageid=" & pageid & ")") Then Call cs2.Close() Call cs2.Insert("link aliases") Call cs2.SetField("pageid", pageid.ToString()) End If If cs2.OK() Then Call cs2.SetField("name", pageLink) Call cs2.SetField("link", pageLink) End If Call cs2.Close() ' 'cityListPageBody &= "<li><a href=""" & pageLink & """>" & pagename & "</a></li>" Call cs.GoNext() cnt = cnt + 1 Loop While cs.OK() End If Call cs.Close() ' 'cityListPageBody = "<ul>" & cityListPageBody & "</ul>" cityListPageBody = "<p></p>" If cs.Open("page content", "id=" & cityListPageId) Then Call cs.SetField("copyFilename", cityListPageBody) Call cs.SetField("headline", cityListPageName) Call cs.SetField("MenuHeadline", cityListPageName) 'Call cs.SetField("AllowInMenus", "0") End If Call cs.Close() ' appendLog(cp, "buildSEOPages, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in buildOrganizationSubcategorySelect") ' appendLog(cp, "buildSEOPages, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' populateLonglat ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub populateLonglat(cp As CPBaseClass) Try Dim cs As CPCSBaseClass Dim address As String Dim result As String Dim defaultValue As String = "" Dim resultArr As String() Dim lat As String Dim lon As String Dim criteria As String ' appendLog(cp, "populateLonglat") ' cs = cp.CSNew() criteria = "" _ & "(Country='USA')" _ & "and((memberMaxMemberType='Fleet Operator')or(memberMaxMemberType='Public Sector')or(memberMaxMemberType='Associate')or(memberMaxMemberType='Association'))" _ & "and(includeInDirectory>0)" _ & "and(longitudeNo is null)and(latitudeNo is null)" _ & "" If cs.Open("organizations", criteria) Then Do address = cs.GetText("address1") address = address & " " & cs.GetText("address2") address = address & " " & cs.GetText("city") address = address & " " & cs.GetText("state") address = address & " " & cs.GetText("zip") ' ' call googleMap addon function ' Call cp.Doc.SetProperty("address", address) result = cp.Utils.ExecuteAddon("Get Latitude and Longitude") If (result <> "") And (result <> defaultValue) Then resultArr = Split(result, "^") lat = resultArr(0) lon = resultArr(1) ' If ((lon <> "0") And (lat <> "0")) Then Call cs.SetField("latitudeNo", lat) Call cs.SetField("longitudeNo", lon) End If End If cs.GoNext() Loop While cs.OK End If Call cs.Close() ' appendLog(cp, "populateLonglat, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in populateLonglat") ' appendLog(cp, "populateLonglat, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' Build the layout TLPAOrganizationDirectory2SubcategorySelectLayout ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub buildOrganizationSubcategorySelect(cp As CPBaseClass) Try Dim cs As CPCSBaseClass Dim layout As String Dim lastCategory As String Dim category As String Dim name As String ' appendLog(cp, "buildOrganizationSubcategorySelect") ' layout = "" cs = cp.CSNew() If cs.Open("directory subcategories", , "category,name") Then lastCategory = "" Do name = cp.Utils.EncodeHTML(cs.GetText("name")) category = cp.Utils.EncodeHTML(cs.GetText("category")) Select Case category.ToLower() Case "business services", "fleet comm systems &amp; equipment", "parts and accessories", "vehicle mfg and dealers" If category <> lastCategory Then layout = layout & vbCrLf & vbTab & "<option disabled=""disabled""> </option>" layout = layout & vbCrLf & vbTab & "<option value=""" & category & """>" & category.ToUpper() & "</option>" End If layout = layout & vbCrLf & vbTab & "<option value=""" & category & ":" & name & """>" & name & "</option>" lastCategory = category End Select Call cs.GoNext() Loop While cs.OK() layout = "" _ & vbCrLf & vbTab & "<option value="""" selected=""selected"">Select One</option>" _ & layout _ & "" End If Call cs.Close() If layout <> "" Then If Not cs.Open("layouts", "name='TLPAOrganizationDirectory2SubcategorySelectLayout'") Then Call cs.Close() Call cs.Insert("layouts") Call cs.SetField("name", "TLPAOrganizationDirectory2SubcategorySelectLayout") End If If cs.OK() Then Call cs.SetField("layout", layout) End If Call cs.Close() End If ' appendLog(cp, "buildOrganizationSubcategorySelect, exit") ' Catch ex As Exception cp.Site.ErrorReport(ex, "exception in buildOrganizationSubcategorySelect") ' appendLog(cp, "buildOrganizationSubcategorySelect, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' syncMemberMax main() ''' </summary> ''' <param name="CP"></param> ''' <remarks></remarks> Private Sub syncMemberMax(CP As CPBaseClass) Try Dim lastRunPartial As Date = CP.Utils.EncodeDate(CP.Site.GetProperty("TLPA Last Sync Time Partial")) Dim lastRunFull As Date = CP.Utils.EncodeDate(CP.Site.GetProperty("TLPA Last Sync Time Full")) Dim lastStartString As String = CP.Site.GetProperty("TLPA Sync Currently Running") Dim sql As String = "" ' appendLog(CP, "syncMemberMax") ' nowDate = Date.Now.Date 'logFile = "tcaSync-" & nowDate.Year.ToString & "-" & nowDate.Month.ToString & "-" & nowDate.Day.ToString & ".log" requestAddr = CP.Site.GetProperty("TLPA MemberMax SOAP Address", "http://209.166.141.85:8080/4DSOAP/") CP.Site.SetProperty("TLPA Sync Currently Running", Date.Now().ToString()) ' 'CP.Db.ExecuteSQL("UPDATE Organizations SET memberMaxSyncStatus=" & recordNotUpdated & " WHERE memberMaxMemberNo is Not null") 'CP.Db.ExecuteSQL("UPDATE ccMembers SET memberMaxSyncStatus=" & recordNotUpdated & " WHERE memberMaxMemberNo is Not null") ' ' 01/27/2017 Full Sync Mark any record with memberMaxCompanyId or memberMaxPersonId ' CP.Db.ExecuteSQL("UPDATE Organizations SET memberMaxSyncStatus=" & recordNotUpdated & " WHERE memberMaxMemberNo is Not null or memberMaxCompanyId is Not null") CP.Db.ExecuteSQL("UPDATE ccMembers SET memberMaxSyncStatus=" & recordNotUpdated & " WHERE memberMaxMemberNo is Not null or memberMaxPersonId is Not null" ) CP.Db.ExecuteSQL("UPDATE ccMemberRules SET createKey=" & recordNotUpdated) ' ' sync committees ' Call syncMemberMax_syncCommittees(CP) ' ' run either Partial or Full baced on last run of the Full ' modeFull = (lastRunFull.AddDays(7) < Date.Today) If modeFull Then ' ' full sync deletes records that were present in the MemberMax feed ' deletion only occures if there are no errors prior to the delete being called ' each routine within should increment the global errCount if an error occures ' appendLog(CP, "syncMemberMax, full sync") syncMemberMax_pullFullCompanyList(CP) Else ' ' partial sync does no record deletion ' appendLog(CP, "syncMemberMax, partial sync") syncMemberMax_pullPartialCompanyList(CP, lastRunPartial) End If ' syncMemberMax_updateOrgs(CP) syncMemberMax_updatePeople(CP) ' If errCount <> 0 Then ' ' error occired ' appendLog(CP, "syncMemberMax, ERROR occured, do not clean up old records") Else ' ' only update sync time and delete if no errors ' If Not modeFull Then CP.Site.SetProperty("TLPA Last Sync Time Partial", Date.Now.ToString()) Else ' ' mark stale records for deletion 7 days from now ' appendLog(CP, "syncMemberMax, no error, clean up old records") CP.Db.ExecuteSQL("UPDATE ccMembers SET memberMaxDateDeleted=" & CP.Db.EncodeSQLDate(Date.Now()) & " WHERE (memberMaxSyncStatus=" & recordNotUpdated & ") and ((memberMaxDateDeleted is Null) OR (memberMaxDateDeleted=''))") CP.Db.ExecuteSQL("UPDATE organizations SET memberMaxDateDeleted=" & CP.Db.EncodeSQLDate(Date.Now()) & " WHERE (memberMaxSyncStatus=" & recordNotUpdated & ") and ((memberMaxDateDeleted is Null) OR (memberMaxDateDeleted=''))") ' ' delete records marked for deletion 7 days prior ' CP.Content.Delete("People", "(memberMaxSyncStatus=" & recordNotUpdated & ") and (memberMaxDateDeleted<" & CP.Db.EncodeSQLDate(Date.Now.AddDays(-7)) & ")") CP.Content.Delete("Organizations", "(memberMaxSyncStatus=" & recordNotUpdated & ") and (memberMaxDateDeleted<" & CP.Db.EncodeSQLDate(Date.Now.AddDays(-7)) & ")") ' ' clean up sync managed grsoups (anything with a memberMaxCommitteeId in the group record) ' 'syncMemberMax_cleanGroups(CP) ' ' remove any people from the members gruop that may have been members at one point ' this is a safety net - added an else case to isMember check to remove from group ' and also move to People cdef ' 'syncMemberMax_removeUnwantedPeople(CP) ' If errCount = 0 Then CP.Site.SetProperty("TLPA Last Sync Time Full", Date.Now.ToString()) End If End If ' 'Call syncMemberMax_setPermissions(CP) End If ' ' update the imageFilename to MemberMax image URL ' sql = "update ccmembers" _ & " set imagefilename='https://members.tlpa.org/scripts/4disapi.dll/4DACTION/WebsGetImage/Person/'+cast( [membermaxpersonid] as varchar)" _ & " where" _ & " (membermaxpersonid is not null)" Call CP.Db.ExecuteSQL(sql) ' ' clear the start time ' CP.Site.SetProperty("TLPA Sync Currently Running", "") ' If errCount <> 0 Then appendLog(CP, "Sync Ended With Errors [" & errCount & "]") Else appendLog(CP, "Sync Ended Successfully") End If ' Catch ex As Exception CP.Site.ErrorReport(ex, "exception in runMemberMaxSync") ' appendLog(CP, "syncMemberMax, error exit") ' End Try End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <remarks></remarks> Private Sub syncMemberMax_pullFullCompanyList(ByVal CP As Contensive.BaseClasses.CPBaseClass) Try ' Dim objXML As New XmlDocument Dim reqEnv As String = "" Dim opNode As XmlNode Dim csOrg As BaseClasses.CPCSBaseClass = CP.CSNew Dim responseString As String = "" 'Dim errorNumber As Integer = 0 'Dim errorMessage As String = "" Dim primaryRecord As Boolean ' appendLog(CP, "syncMemberMax_pullFullCompanyList") ' ' wrap it in the command envelope ' reqEnv = memberMaxSoapServicesBlobEnv.Replace("{{inText}}", xmlEscape(memberMaxSoapRequestCompanyList3)) '' 'reqEnv = "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" 'reqEnv += "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<SOAP-ENV:Body>" 'reqEnv += "<tns:SoapServicesBlob xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<inText xsi:type=""xsd:string"">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;" 'reqEnv += "&lt;RequestedMethodWrapper&gt;" 'reqEnv += "&lt;RequestedMethodParams&gt;" 'reqEnv += "&lt;MbrxSoapLicenseNo&gt;MBR9056592&lt;/MbrxSoapLicenseNo&gt;" 'reqEnv += "&lt;DataReturnFormat&gt;XML&lt;/DataReturnFormat&gt;" 'reqEnv += "&lt;ServerDebugLog&gt;Off&lt;/ServerDebugLog&gt; " 'reqEnv += "&lt;RequestedMethod&gt;CompanyList3&lt;/RequestedMethod&gt;" 'reqEnv += "&lt;CompanyForOrgID&gt;All&lt;/CompanyForOrgID&gt; " 'reqEnv += "&lt;MemberShipStatus&gt;All&lt;/MemberShipStatus&gt;" 'reqEnv += "&lt;/RequestedMethodParams&gt;" 'reqEnv += "&lt;/RequestedMethodWrapper&gt;" 'reqEnv += "</inText>" 'reqEnv += "</tns:SoapServicesBlob>" 'reqEnv += "</SOAP-ENV:Body>" 'reqEnv += "</SOAP-ENV:Envelope>" ' 'appendLog(CP, reqEnv) ' responseString = getMemberMaxSoapResponse(CP, requestAddr, reqEnv, "ns1:SoapServicesBlobResponse") ' 'appendLog(CP, "responseString: " & responseString) ' Dim memberMaxCompanyID As Integer Dim orgName As String If (responseString <> "") Then ' ' temp save xml from MM ' 'appendLog(CP, "pullFullCompanyList - responseString: " & responseString) ' Call objXML.LoadXml(responseString) If Not objXML Is Nothing Then 'appendLog(CP, objXML.InnerXml) For Each opNode In objXML.GetElementsByTagName("COMPANY") ' memberMaxCompanyID = CP.Utils.EncodeInteger(getXmNodelField(CP, opNode, "CompanyID")) orgName = getXmNodelField(CP, opNode, "CompanyName") csOrg.Open("Organizations", "memberMaxCompanyID=" & CP.Db.EncodeSQLNumber(memberMaxCompanyID), "id", False) If Not csOrg.OK Then csOrg.Close() csOrg.Insert("Organizations") csOrg.SetField("memberMaxCompanyID", memberMaxCompanyID.ToString()) 'appendLog(CP, "mmcompId-1", memberMaxCompanyID.ToString) End If primaryRecord = True Do While csOrg.OK If primaryRecord Then csOrg.SetField("Name", orgName) csOrg.SetField("memberMaxSyncStatus", recordChangedAndNeedsToBeUpdated.ToString()) csOrg.SetField("active", "1") csOrg.SetField("memberMaxDateDeleted", "") Else csOrg.SetField("active", "0") csOrg.SetField("memberMaxDateDeleted", Now.Date.ToString()) 'appendLog(CP, "mmcompId-2", Now.Date.ToString()) End If Call csOrg.GoNext() Loop csOrg.Close() Next End If Else 'appendLogVerbose(CP, "Error: [" & errorNumber & "] " & errorMessage) End If ' appendLog(CP, "syncMemberMax_pullFullCompanyList, exit") ' Catch ex As Exception CP.Site.ErrorReport(ex, "exception in syncMemberMax_pullFullCompanyList") appendLog(CP, "ERROR, syncMemberMax_pullFullCompanyList() - " & ex.ToString) errCount += 1 End Try End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <remarks></remarks> Private Sub syncMemberMax_updateOrgs(ByVal CP As Contensive.BaseClasses.CPBaseClass) Try ' Dim cs As BaseClasses.CPCSBaseClass = CP.CSNew ' appendLog(CP, "syncMemberMax_updateCompanies, enter") ' cs.Open("Organizations", "memberMaxSyncStatus=" & recordChangedAndNeedsToBeUpdated) Do While cs.OK syncMemberMax_updateOrg(CP, cs) 'appendLog(CP, "mmcompId-3", Now.Date.ToString()) cs.GoNext() Loop cs.Close() ' appendLog(CP, "syncMemberMax_updateCompanies, exit") ' Catch ex As Exception CP.Site.ErrorReport(ex, "exception in syncMemberMax_updateOrgs") appendLog(CP, "ERROR, syncMemberMax_updateOrgs() - " & ex.ToString) errCount += 1 End Try End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <param name="csOrg"></param> ''' <remarks></remarks> Private Sub syncMemberMax_updateOrg(ByVal CP As Contensive.BaseClasses.CPBaseClass, ByVal csOrg As BaseClasses.CPCSBaseClass) Try ' Dim orgId As Integer Dim orgName As String Dim reqEnv As String = "" Dim csPeople As BaseClasses.CPCSBaseClass = CP.CSNew Dim groupID As Integer = 0 Dim objXML As New XmlDocument Dim comNode As XmlNode Dim prNode As XmlNode Dim responseString As String = "" 'Dim errorNumber As Integer = 0 'Dim errorMessage As String = "" Dim firstRecordFound As Boolean Dim contactMemberId As Integer Dim memberMaxPrimaryContactPersonID As Integer Dim memberMaxPrimaryContactPlusPersonID As Integer Dim memberMaxCompanyID As Integer = 0 Dim defaultPlacementId As Integer = 0 Dim memberMaxMemberType As String = "" ' orgId = csOrg.GetInteger("ID") orgName = csOrg.GetText("name") ' appendLog(CP, "syncMemberMax_updateOrg [#" & orgId & ", " & orgName & "]") ' csOrg.SetField("memberMaxSyncStatus", recordUpdated.ToString()) ' ''appendLog(CP, "syncMemberMax_updateOrg, 100") ' reqEnv = memberMaxSoapServicesBlobEnv.Replace("{{inText}}", xmlEscape(memberMaxSoapRequestCompanyDetail)) reqEnv = reqEnv.Replace("{{memberMaxCompanyID}}", csOrg.GetText("memberMaxCompanyID")) ' ''appendLog(CP, "syncMemberMax_updateOrg, 110") ' 'reqEnv = "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" 'reqEnv += "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<SOAP-ENV:Body>" 'reqEnv += "<tns:SoapServicesBlob xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<inText xsi:type=""xsd:string"">" 'reqEnv += "&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;" 'reqEnv += "&lt;RequestedMethodWrapper&gt;" 'reqEnv += "&lt;RequestedMethodParams&gt;" 'reqEnv += "&lt;MbrxSoapLicenseNo&gt;MBR9056592&lt;/MbrxSoapLicenseNo&gt;" 'reqEnv += "&lt;DataReturnFormat&gt;XML&lt;/DataReturnFormat&gt;" 'reqEnv += "&lt;ServerDebugLog&gt;Off&lt;/ServerDebugLog&gt; " 'reqEnv += "&lt;RequestedMethod&gt;CompanyDetail&lt;/RequestedMethod&gt;" 'reqEnv += "&lt;Companyfilter&gt;" & csOrg.GetText("memberMaxMemberNo") & "&lt;/Companyfilter&gt;" 'reqEnv += "&lt;KeyWordFilter&gt;All&lt;/KeyWordFilter&gt;" 'reqEnv += "&lt;RelatedPersonfilter&gt;All&lt;/RelatedPersonfilter&gt;" 'reqEnv += "&lt;ChaptersFilter&gt;All&lt;/ChaptersFilter&gt;" 'reqEnv += "&lt;RelatedRecordsFilter&gt;All&lt;/RelatedRecordsFilter&gt;" 'reqEnv += "&lt;/RequestedMethodParams&gt;" 'reqEnv += "&lt;/RequestedMethodWrapper&gt;" 'reqEnv += "</inText>" 'reqEnv += "</tns:SoapServicesBlob>" 'reqEnv += "</SOAP-ENV:Body>" 'reqEnv += "</SOAP-ENV:Envelope>" ' 'appendLog(CP, "syncMemberMax_updateOrg, request [" & reqEnv & "]") ' responseString = getMemberMaxSoapResponse(CP, requestAddr, reqEnv, "ns1:SoapServicesBlobResponse") 'CP.Utils.AppendLog("membermaxResponse.log", responseString) ' ''appendLog(CP, "syncMemberMax_updateOrg, 120") ' If (responseString <> "") Then ' ' temp save xml from MM ' csOrg.SetField("memberMaxData", responseString) 'appendLog(CP, "syncMemberMax_updateOrg, response [" & responseString & "]") ' ''appendLog(CP, "syncMemberMax_updateOrg, 130") ' Call objXML.LoadXml(responseString) If Not objXML Is Nothing Then comNode = objXML.GetElementsByTagName("COMPANY").Item(0) ' ''appendLog(CP, "syncMemberMax_updateOrg, 140") ' memberMaxPrimaryContactPersonID = 0 memberMaxPrimaryContactPlusPersonID = 0 If comNode.HasChildNodes Then memberMaxCompanyID = CP.Utils.EncodeInteger(getXmNodelField(CP, comNode, "CompanyID")) memberMaxPrimaryContactPersonID = CP.Utils.EncodeInteger(getXmNodelField(CP, comNode, "RepID")) memberMaxPrimaryContactPlusPersonID = CP.Utils.EncodeInteger(getXmNodelField(CP, comNode, "RepPlusID")) memberMaxMemberType = getXmNodelField(CP, comNode, "MemberType") ' csOrg.SetField("memberMaxCompanyID", memberMaxCompanyID.ToString()) csOrg.SetField("memberMaxMemberNo", getXmNodelField(CP, comNode, "MemberNo")) csOrg.SetField("Name", getXmNodelField(CP, comNode, "CompanyName")) csOrg.SetField("Address1", getXmNodelField(CP, comNode, "MainAddress1")) csOrg.SetField("Address2", getXmNodelField(CP, comNode, "MainAddress2")) csOrg.SetField("City", getXmNodelField(CP, comNode, "MainCity")) csOrg.SetField("State", getXmNodelField(CP, comNode, "MainState")) csOrg.SetField("Zip", getXmNodelField(CP, comNode, "MainZip")) csOrg.SetField("Country", getXmNodelField(CP, comNode, "MainCountry")) csOrg.SetField("Phone", getXmNodelField(CP, comNode, "MainPhone")) csOrg.SetField("Fax", getXmNodelField(CP, comNode, "MainFax")) csOrg.SetField("Web", getXmNodelField(CP, comNode, "WebPage")) 'csOrg.SetField("JoinDate", getXmlField(CP,comNode,"Joined")) 'csOrg.SetField("ExpDate", getXmlField(CP,comNode,"DuesExpireDate")) csOrg.SetField("memberMaxMemberType", memberMaxMemberType) csOrg.SetField("taxiCnt", getXmNodelField(CP, comNode, "CompCustm28")) csOrg.SetField("limoCnt", getXmNodelField(CP, comNode, "CompCustm29")) csOrg.SetField("paratransitCnt", getXmNodelField(CP, comNode, "CompCustm30")) csOrg.SetField("Phone2", getXmNodelField(CP, comNode, "TollFreePhone")) csOrg.SetField("PhoneSales", getXmNodelField(CP, comNode, "Attention")) csOrg.SetField("copyFileName", getXmNodelField(CP, comNode, "CompInfo")) ' Dim memberMaxBackwardsInDirectoryField As Boolean = Not CP.Utils.EncodeBoolean(getXmNodelField(CP, comNode, "InDirectory")) csOrg.SetField("includeInDirectory", memberMaxBackwardsInDirectoryField.ToString()) ' ' set inDirectory and check if there is a logo ' If (Not CP.Site.GetBoolean("TLPA Membermax - allow logo detection in sync", "0")) Then appendLog(CP, "syncMemberMax_updateOrg, logo detection skipped - see site property [TLPA Membermax - allow logo detection in sync]") Else Dim memberMaxHasLogo As String = "0" If memberMaxMemberType.ToLower() = "not a member" Then appendLog(CP, "syncMemberMax_updateOrg, memberMaxMemberType.ToLower() = not a member") 'csOrg.SetField("includeInDirectory", "0") Else 'csOrg.SetField("includeInDirectory", "1") ' ' 20171127 http failing, switched to https 'Dim logoLink As String = "http://members.tlpa.org/scripts/4disapi.dll/4DACTION/WebsGetImage/Company/" & memberMaxCompanyID.ToString() Dim logoLink As String = "https://members.tlpa.org/scripts/4disapi.dll/4DACTION/WebsGetImage/Company/" & memberMaxCompanyID.ToString() ' Dim logoLength As Integer = 0 Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(logoLink) webRequest.Timeout = 30000 appendLog(CP, "syncMemberMax_updateOrg, checking for image [" & logoLink & "]") Try Using webResponse As System.Net.WebResponse = webRequest.GetResponse() logoLength = CInt(webResponse.ContentLength) appendLog(CP, "syncMemberMax_updateOrg, logo webResponse.ContentLength [" & logoLength & "]") End Using Catch ex As Exception logoLength = 0 appendLog(CP, "syncMemberMax_updateOrg, ERROR fetching logo, ex=[" & ex.ToString & "]") End Try appendLog(CP, "syncMemberMax_updateOrg, logoLength=" & logoLength) If logoLength > 1050 Then memberMaxHasLogo = "1" Else End If End If csOrg.SetField("memberMaxHasLogo", memberMaxHasLogo) appendLog(CP, "syncMemberMax_updateOrg, memberMaxHasLogo=" & memberMaxHasLogo) End If End If ' ' ''appendLog(CP, "syncMemberMax_updateOrg, 150") ' Dim memberMaxPersonID As Integer For Each prNode In objXML.GetElementsByTagName("PersonID") memberMaxPersonID = CP.Utils.EncodeInteger(prNode.InnerText) If memberMaxPersonID > 0 Then csPeople.Open("People", "memberMaxPersonID=" & memberMaxPersonID.ToString(), "id", False) If Not csPeople.OK Then Call csPeople.Close() csPeople.Insert("People") csPeople.SetField("memberMaxPersonID", memberMaxPersonID.ToString) End If firstRecordFound = True Do While csPeople.OK contactMemberId = csPeople.GetInteger("id") If firstRecordFound Then If memberMaxPrimaryContactPersonID = memberMaxPersonID Then csOrg.SetField("contactMemberId", contactMemberId.ToString()) End If ' ' update the first record found with this memberMaxCompanyID ' csPeople.SetField("OrganizationID", orgId.ToString()) 'csPeople.SetField("phone3", getXmlField(CP,comNode,"MainPhone")) csPeople.SetField("company", csOrg.GetText("Name")) csPeople.SetField("memberMaxSyncStatus", recordChangedAndNeedsToBeUpdated.ToString()) csPeople.SetField("memberMaxDateDeleted", "") ' ' RepPlusID add to the group: "Mail List, Rep Plus" ' Call verifyGroup(CP, contactMemberId, mailListRepPlusId(CP), (memberMaxPrimaryContactPlusPersonID = memberMaxPersonID) And (Not String.IsNullOrEmpty(memberMaxMemberType) And (memberMaxMemberType <> "Not A Member"))) ' Else ' ' delete duplicates ' csPeople.SetField("memberMaxDateDeleted", Date.Now.ToString()) csPeople.SetField("active", "0") End If firstRecordFound = True Call csPeople.GoNext() Loop csPeople.Close() End If Next ' ' get organization subcategories out of keywords ' Dim keywordOuterNode As XmlElement Dim keywordNode As XmlElement Dim category As String Dim subCategory As String Dim subCategoryId As Integer Dim cs As CPCSBaseClass = CP.CSNew() For Each keywordOuterNode In objXML.GetElementsByTagName("COMP_KEYWORDS") For Each keywordNode In keywordOuterNode.GetElementsByTagName("COMP_KEYWORDS") category = getXmNodelField(CP, keywordNode, "KeyWordGroup") Select Case category.ToLower() Case "business services", "fleet comm systems & equipment", "parts and accessories", "vehicle mfg and dealers" subCategory = getXmNodelField(CP, keywordNode, "Keyword") If Not String.IsNullOrEmpty(category) And Not String.IsNullOrEmpty(subCategory) Then If subCategory.Length > 3 Then subCategory = subCategory.Substring(3) End If If Not cs.Open("directory subcategories", "(name=" & CP.Db.EncodeSQLText(subCategory) & ")and(category=" & CP.Db.EncodeSQLText(category) & ")") Then Call cs.Insert("directory subcategories") cs.SetField("name", subCategory) cs.SetField("category", category) End If subCategoryId = cs.GetInteger("id") cs.Close() ' If subCategoryId <> 0 Then If Not cs.Open("organization subcategories", "(OrganizationID=" & orgId & ")and(HeadingID=" & subCategoryId & ")") Then cs.Close() If defaultPlacementId = 0 Then If Not cs.Open("directory placements", "name='Normal'") Then cs.Close() Call cs.Insert("directory placements") cs.SetField("name", "Normal") End If defaultPlacementId = cs.GetInteger("id") cs.Close() End If cs.Insert("organization subcategories") cs.SetField("OrganizationID", orgId.ToString()) cs.SetField("HeadingID", subCategoryId.ToString()) cs.SetField("Approved", "1") cs.SetField("placementId", defaultPlacementId.ToString()) End If Call cs.Close() End If End If End Select Next Next ' ''appendLog(CP, "syncMemberMax_updateOrg, 160") ' ' ' ' Dim SecondaryDuesGroup As String = "" Dim SecondaryDuesStatus as Boolean = false For Each keywordOuterNode In objXML.GetElementsByTagName("SecondaryDues") For Each keywordNode In keywordOuterNode.GetElementsByTagName("SecondaryDues") ' SecondaryDuesGroup = getXmNodelField(CP, keywordNode, "SecondaryDuesGroup") SecondaryDuesStatus = cp.Utils.EncodeBoolean(getXmNodelField(CP, keywordNode, "SecondaryDuesStatus")) ' Select Case SecondaryDuesGroup Case "Taxicab Division" csOrg.SetField("isTaxicabDivision",SecondaryDuesStatus.ToString()) Case "Limousine & Sedan Division" csOrg.SetField("isLimousineSedanDivision",SecondaryDuesStatus.ToString()) Case "Paratransit & Contracting Division" csOrg.SetField("isParatransitContractingDivision",SecondaryDuesStatus.ToString()) End Select Next Next ' End If Else 'appendLogVerbose(CP, "Error: [" & errorNumber & "] " & errorMessage) End If ' 'appendLog(CP, "syncMemberMax_updateOrg, exit") ' Catch ex As Exception CP.Site.ErrorReport(ex, "exception in syncMemberMax_updateOrg") appendLog(CP, "ERROR, syncMemberMax_updateOrg() - " & ex.ToString) errCount += 1 End Try End Sub ' Private Function getXmNodelField(cp As CPBaseClass, node As XmlNode, fieldName As String) As String Dim returnValue As String = "" Try 'csOrg.SetField("includeInDirectory", comNode.Item("inDirectory").InnerText) If node Is Nothing Then cp.Site.ErrorReport("getXmlField ERROR, node argument is Nothing") Else Dim item As System.Xml.XmlElement item = node.Item(fieldName) If item Is Nothing Then cp.Site.ErrorReport("getXmlField ERROR, node does not contain field [" & fieldName & "]") Else returnValue = item.InnerText End If End If Catch ex As Exception cp.Site.ErrorReport(ex, "Exception in getXmlField, field [" & fieldName & "]") End Try Return returnValue End Function ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <remarks></remarks> Private Sub syncMemberMax_updatePeople(ByVal CP As Contensive.BaseClasses.CPBaseClass) Try ' Dim cs As BaseClasses.CPCSBaseClass = CP.CSNew ' appendLog(CP, "syncMemberMax_updateIndividuals, enter") ' ' open them in ID order so duplicate usernames can be detected, primary is always first. ' cs.Open("People", "memberMaxSyncStatus=" & recordChangedAndNeedsToBeUpdated, "id", False) Do While cs.OK syncMemberMax_updatePerson(CP, cs) cs.GoNext() Loop cs.Close() ' appendLog(CP, "syncMemberMax_updateIndividuals, exit") ' Catch ex As Exception CP.Site.ErrorReport(ex, "exception in syncMemberMax_updateIndividuals") appendLog(CP, "ERROR, syncMemberMax_updateIndividuals() - " & ex.ToString) errCount += 1 End Try End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <param name="csPeople"></param> ''' <remarks></remarks> Private Sub syncMemberMax_updatePerson(ByVal CP As Contensive.BaseClasses.CPBaseClass, ByVal csPeople As BaseClasses.CPCSBaseClass) Try ' 'Dim docNode As XmlNode Dim objPpl As New XmlDocument Dim pplNode As XmlNode Dim personId As Integer = csPeople.GetInteger("ID") Dim email As String = csPeople.GetText("Email") Dim reqEnv As String = "" Dim cs2 As BaseClasses.CPCSBaseClass = CP.CSNew Dim groupID As Integer = 0 'Dim isMember As Boolean = syncMemberMax_isOrgMember(CP, csPeople.GetInteger("OrganizationID")) Dim OrganizationModel As New OrganizationModel(cp,csPeople.GetInteger("OrganizationID")) Dim csUpd As BaseClasses.CPCSBaseClass = CP.CSNew Dim responseString As String = "" 'Dim errorNumber As Integer = 0 'Dim errorMessage As String = "" Dim role As String = "" Dim dateExpires As String = "" Dim dateAppointed As String = "" Dim receivesTlpaMailings As Boolean = False Dim optedOut As Boolean = True Dim taggedAsRep As Boolean = False Dim memberMaxCompanyId As Integer = 0 Dim sql As String Dim csTest As CPCSBaseClass ' Dim divisionMemberTaxicab As Boolean = False Dim divisionMemberLimousine As Boolean = False Dim divisionMemberParatransit As Boolean = False ' 'appendLog(CP, "syncMemberMax_setPeopleData") ' csPeople.SetField("memberMaxSyncStatus", recordUpdated.ToString()) ' reqEnv = memberMaxSoapServicesBlobEnv.Replace("{{inText}}", xmlEscape(memberMaxSoapRequestPersonDetailDump)) reqEnv = reqEnv.Replace("{{memberMaxPersonID}}", csPeople.GetText("memberMaxPersonID")) '' 'reqEnv = "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" 'reqEnv += "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<SOAP-ENV:Body>" 'reqEnv += "<tns:SoapServicesBlob xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<inText xsi:type=""xsd:string"">" 'reqEnv += "&lt;RequestedMethodWrapper&gt;" 'reqEnv += "&lt;RequestedMethodParams&gt;" 'reqEnv += "&lt;MbrxSoapLicenseNo&gt;MBR9056592&lt;/MbrxSoapLicenseNo&gt;" 'reqEnv += "&lt;DataReturnFormat&gt;XML&lt;/DataReturnFormat&gt;" 'reqEnv += "&lt;ServerDebugLog&gt;Off&lt;/ServerDebugLog&gt;" 'reqEnv += "&lt;RequestedMethod&gt;PersonDetailDump&lt;/RequestedMethod&gt;" 'reqEnv += "&lt;Personfilter&gt;" & csPeople.GetText("memberMaxMemberNo") & "&lt;/Personfilter&gt;" 'reqEnv += "&lt;KeyWordFilter&gt;All&lt;/KeyWordFilter&gt;" 'reqEnv += "&lt;CommitteeFilter&gt;All&lt;/CommitteeFilter&gt;" 'reqEnv += "&lt;ChaptersFilter&gt;All&lt;/ChaptersFilter&gt;" 'reqEnv += "&lt;RelatedRecordsFilter&gt;All&lt;/RelatedRecordsFilter&gt;" 'reqEnv += "&lt;/RequestedMethodParams&gt; " 'reqEnv += "&lt;/RequestedMethodWrapper&gt;" 'reqEnv += "</inText>" 'reqEnv += "</tns:SoapServicesBlob>" 'reqEnv += "</SOAP-ENV:Body>" 'reqEnv += "</SOAP-ENV:Envelope>" ' 'appendLog(CP, reqEnv) ' responseString = getMemberMaxSoapResponse(CP, requestAddr, reqEnv, "ns1:SoapServicesBlobResponse") If (responseString <> "") Then ' ' save raw data ' csPeople.SetField("memberMaxData", responseString) ' Call objPpl.LoadXml(responseString) If Not objPpl Is Nothing Then pplNode = objPpl.GetElementsByTagName("PERSON").Item(0) If pplNode.HasChildNodes Then ' ' MemberMax has a record, mark the local one active and populate it ' memberMaxCompanyId = CP.Utils.EncodeInteger(getXmNodelField(CP, pplNode, "CompanyID")) ' csPeople.SetField("active", "1") csPeople.SetField("memberMaxPersonID", getXmNodelField(CP, pplNode, "PersonID")) csPeople.SetField("memberMaxCompanyID", memberMaxCompanyId.ToString()) csPeople.SetField("memberMaxMemberNo", getXmNodelField(CP, pplNode, "MemberNo")) ' csPeople.SetField("Name", getXmNodelField(CP, pplNode, "FirstName") & " " & getXmNodelField(CP, pplNode, "LastName")) csPeople.SetField("LastName", getXmNodelField(CP, pplNode, "LastName")) csPeople.SetField("FirstName", getXmNodelField(CP, pplNode, "FirstName")) csPeople.SetField("Title", getXmNodelField(CP, pplNode, "Title")) csPeople.SetField("Address", getXmNodelField(CP, pplNode, "MailAddress1")) csPeople.SetField("Address2", getXmNodelField(CP, pplNode, "MailAddress2")) csPeople.SetField("City", getXmNodelField(CP, pplNode, "MailCity")) csPeople.SetField("State", getXmNodelField(CP, pplNode, "MailState")) csPeople.SetField("Zip", getXmNodelField(CP, pplNode, "MailZip")) csPeople.SetField("Country", getXmNodelField(CP, pplNode, "MailCountry")) csPeople.SetField("Email", getXmNodelField(CP, pplNode, "EMail1")) 'csPeople.SetField("Salutation", getXmNodelField(CP,pplNode,"Salutation")) csPeople.SetField("Fax", getXmNodelField(CP, pplNode, "Fax")) csPeople.SetField("Phone", getXmNodelField(CP, pplNode, "Phone")) 'cs.SetField("Phone2", getXmNodelField(CP,pplNode,"CellPhone")) '' '' detect duplicate username from some other thing and set it to "", even if inactive. '' 'csUpd.Open("People", "(username=" & CP.Db.EncodeSQLText(getXmNodelField(CP,pplNode,"WebLogon")) & ") and (ID<>" & CP.Db.EncodeSQLNumber(csPeople.GetInteger("ID")) & ")", "id", False) 'Do While csUpd.OK ' csUpd.SetField("Username", "") ' csUpd.GoNext() 'Loop 'csUpd.Close() '' 'csPeople.SetField("Username", getXmNodelField(CP,pplNode,"WebLogon")) 'csPeople.SetField("Password", getXmNodelField(CP,pplNode,"WebPassword")) 'If isMember Then ' csPeople.SetField("ContentControlID", CP.Content.GetRecordID("Content", "Members")) 'Else ' csPeople.SetField("ContentControlID", CP.Content.GetRecordID("Content", "People")) 'End If ' ' TLPA mailing lists ' sql = "select top 1 id from organizations where (membermaxcompanyid=" & memberMaxCompanyId & ")and(contactmemberid=" & personId & ")" cstest = CP.CSNew() taggedAsRep = csTest.openSql(sql) Call csTest.close() ' receivesTlpaMailings = (getXmNodelField(CP, pplNode, "JobFunction") = "Receives TLPA Mailings") optedOut = (getXmNodelField(CP, pplNode, "EmailFieldForListServ") <> "1") 'taggedAsRep = (getXmNodelField(CP, pplNode, "Rep") <> "false") End If End If ' '********CP.Content.Delete("Member Rules", "(MemberID=" & recordID & ") AND (ContentCategoryID=1)") ' ' ' log if user is a member ' 'appendLog(CP, "isMember: " & isMember & "; ccMmberID:" & csPeople.GetInteger("id") & "; organizationID:" & csPeople.GetInteger("organizationID"), "isMember") ' If OrganizationModel.isMember Then ' ' make sure they are not in the non-members group ' CP.Db.ExecuteSQL("DELETE FROM ccMemberRules WHERE (groupID=" & CP.Content.GetRecordID("Groups", "MemberMax TLPA Non-Members") & ") and (memberID=" & personId & ")") ' cs2.Open("Groups", "Name='MemberMax TLPA Members'") If Not cs2.OK Then cs2.Close() cs2.Insert("Groups") If cs2.OK Then cs2.SetField("Name", "MemberMax TLPA Members") cs2.SetField("Caption", "TCA Members") cs2.SetField("ContentCategoryID", "1") groupID = cs2.GetInteger("ID") End If Else groupID = cs2.GetInteger("ID") End If cs2.Close() ' cs2.Open("Member Rules", "(groupid=" & groupID & ") AND (memberID=" & personId & ")") If Not cs2.OK Then cs2.Close() cs2.Insert("Member Rules") End If If cs2.OK Then cs2.SetField("GroupID", groupID.ToString()) cs2.SetField("MemberID", personId.ToString()) End If cs2.Close() Else ' ' make sure they are not in the members group ' CP.Db.ExecuteSQL("DELETE FROM ccMemberRules WHERE (groupID=" & CP.Content.GetRecordID("Groups", "MemberMax TLPA Members") & ") and (memberID=" & personId & ")") ' ' Set 13 12 - add non members to a group named MemberMax TLPA Non-Members ' cs2.Open("Groups", "Name='MemberMax TLPA Non-Members'") If Not cs2.OK Then cs2.Close() cs2.Insert("Groups") If cs2.OK Then cs2.SetField("Name", "MemberMax TLPA Non-Members") cs2.SetField("Caption", "MemberMax TLPA Non-Members") cs2.SetField("ContentCategoryID", "1") groupID = cs2.GetInteger("ID") End If Else groupID = cs2.GetInteger("ID") End If cs2.Close() ' cs2.Open("Member Rules", "(groupid=" & groupID & ") AND (memberID=" & personId & ")") If Not cs2.OK Then cs2.Close() cs2.Insert("Member Rules") End If If cs2.OK Then cs2.SetField("GroupID", groupID.ToString()) cs2.SetField("MemberID", personId.ToString()) End If cs2.Close() End If ' ' Add this person to all his.her committees (with roles) ' pplNode = objPpl.GetElementsByTagName("PERSON_ROLES").Item(0) If Not pplNode Is Nothing Then For Each docNode As XmlNode In pplNode.ChildNodes If docNode.Item("Name").InnerText <> "" Then 'If docNode.Item("Name").InnerText = "Carrier Contacts" Then ' cs2.Open("Members", "ID=" & recordID, , , "PrimaryContact") ' If cs2.OK Then ' cs2.SetField("PrimaryContact", "1") ' End If ' cs2.Close() 'End If cs2.Open("Groups", "Name='" & Replace(Replace(docNode.Item("Name").InnerText, "'", "''"), "&amp;", "&") & "'") If Not cs2.OK Then cs2.Close() cs2.Insert("Groups") If cs2.OK Then cs2.SetField("Name", docNode.Item("Name").InnerXml) cs2.SetField("Caption", docNode.Item("Name").InnerXml) cs2.SetField("ContentCategoryID", "1") groupID = cs2.GetInteger("ID") End If Else groupID = cs2.GetInteger("ID") End If cs2.Close() ' role = docNode.Item("Role").InnerText cs2.Open("Member Rules", "(groupid=" & groupID & ") AND (memberID=" & personId & ") AND (role=" & CP.Db.EncodeSQLText(role) & ")") If Not cs2.OK Then cs2.Close() cs2.Insert("Member Rules") End If If cs2.OK Then cs2.SetField("GroupID", groupID.ToString()) cs2.SetField("MemberID", personId.ToString()) dateExpires = "" If docNode.Item("ToDate").InnerText <> "" Then If IsDate(docNode.Item("ToDate").InnerText.ToString) And (CDate(docNode.Item("ToDate").InnerText) > CDate("1/1/1900")) Then dateExpires = docNode.Item("ToDate").InnerText.ToString End If End If dateAppointed = "" If docNode.Item("FromDate").InnerText <> "" Then If IsDate(docNode.Item("FromDate").InnerText.ToString) And (CDate(docNode.Item("FromDate").InnerText) > CDate("1/1/1900")) Then dateAppointed = docNode.Item("FromDate").InnerText.ToString End If End If cs2.SetField("DateExpires", dateExpires) 'cs2.SetField("DateAppointed", dateAppointed) cs2.SetField("role", role) cs2.SetField("createKey", recordChangedAndNeedsToBeUpdated.ToString()) End If cs2.Close() End If Next ' 'pplNode = Nothing '' 'pplNode = objPpl.GetElementsByTagName("KEYWORD_TABLE").Item(0) 'If Not pplNode Is Nothing Then ' For Each docNode As XmlNode In pplNode.ChildNodes ' If docNode.Item("Keyword").InnerText = "Safety Contact" Then ' cs2.Open("Members", "ID=" & recordID, , , "SafetyContact") ' If cs2.OK Then ' cs2.SetField("SafetyContact", "1") ' End If ' cs2.Close() ' End If ' Next 'End If End If ' ' Mail Lists ' Call appendLog(CP, "Mailing lists: personId [" & personId & "], isMember [" & OrganizationModel.isMember & "],receivesTlpaMailings [" & receivesTlpaMailings & "],optedOut [" & optedOut & "],taggedAsRep [" & taggedAsRep & "]") ' Call verifyGroup(CP, personId, mailListRideHailNewsId(CP), OrganizationModel.isMember And receivesTlpaMailings And (Not optedOut)) Call verifyGroup(CP, personId, mailListTaxicabId(CP), OrganizationModel.isMember And receivesTlpaMailings And (Not optedOut) And OrganizationModel.isTaxicabDivision) Call verifyGroup(CP, personId, mailListLimousineId(CP), OrganizationModel.isMember And receivesTlpaMailings And (Not optedOut) And OrganizationModel.isLimousineSedanDivision) Call verifyGroup(CP, personId, mailListParatransitId(CP), OrganizationModel.isMember And receivesTlpaMailings And (Not optedOut) And OrganizationModel.isParatransitContractingDivision) Call verifyGroup(CP, personId, mailListLegislativeAlertId(CP), OrganizationModel.isMember And receivesTlpaMailings And (Not optedOut) And taggedAsRep) Call verifyGroup(CP, personId, mailListSpecialAlertId(CP), OrganizationModel.isMember And receivesTlpaMailings And (Not optedOut) And taggedAsRep) Else 'appendLogVerbose(CP, "Error: [" & errorNumber & "] " & errorMessage) End If ' 'appendLog(CP, "syncMemberMax_setPeopleData, exit") ' Catch ex As Exception CP.Site.ErrorReport(ex, "exception in syncMemberMax_updatePerson") appendLog(CP, "ERROR, syncMemberMax_setPeopleData() - " & ex.ToString) errCount += 1 End Try End Sub '' ''==================================================================================================== ' ''' <summary> ' ''' ' ''' </summary> ' ''' <param name="CP"></param> ' ''' <remarks></remarks> 'Private Sub syncMemberMax_setPermissions(ByVal CP As Contensive.BaseClasses.CPBaseClass) ' Try ' ' ' Dim cs As BaseClasses.CPCSBaseClass = CP.CSNew ' Dim recCount As Integer = 0 ' Dim recArr() As Integer ' Dim recArrCount As Integer = 0 ' Dim recArrPointer As Integer = 0 ' ' ' cs.Open("Groups", "memberMaxCommitteeId is Not Null", , , "ID") ' Do While cs.OK ' recCount += 1 ' cs.GoNext() ' Loop ' ' ' cs.GoFirst() ' ReDim recArr(recCount) ' recCount = 0 ' ' ' Do While cs.OK ' recArr(recCount) = cs.GetInteger("ID") ' recCount += 1 ' cs.GoNext() ' Loop ' cs.Close() ' ' ' cs.Open("Members", "memberMaxSyncStatus=" & recordNotUpdated, , , "ID") ' Do While cs.OK ' For recArrPointer = 0 To recArrCount ' '********CP.Content.Delete("Member Rules", "(groupID=" & CP.Db.EncodeSQLNumber(recArr(recArrPointer)) & ") and (memberID=" & cs.GetInteger("ID") & ")") ' Next ' recArrPointer = 0 ' cs.GoNext() ' Loop ' cs.Close() ' ' ' Catch ex As Exception ' Try ' appendFile( cp, "ERROR, setPermissions() - " & ex.ToString) ' errCount += 1 ' CP.Site.ErrorReport(ex) ' Catch errObj As Exception ' End Try ' End Try 'End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <param name="lastSync"></param> ''' <remarks></remarks> Private Sub syncMemberMax_pullPartialCompanyList(ByVal CP As Contensive.BaseClasses.CPBaseClass, ByVal lastSync As Date) Try ' Dim objXML As New XmlDocument Dim reqEnv As String = "" Dim opNode As XmlNode Dim cs As BaseClasses.CPCSBaseClass = CP.CSNew Dim responseString As String = "" 'Dim errorNumber As Integer 'Dim errorMessage As String ' appendLog(CP, "syncMemberMax_pullPartialCompanyList, enter") ' ' Invalid filter parameters passed to your RequestedMethod. The value of tag (changedSinceTime) was not a valid time. I was expecting HH:MM:SS ' If lastSync <= #8/7/1990# Then lastSync = Now.AddDays(-1) End If reqEnv = memberMaxSoapServicesBlobEnv.Replace("{{inText}}", xmlEscape(memberMaxSoapRequestGetChangedCompanies)) reqEnv = reqEnv.Replace("{{lastSyncDate}}", lastSync.Date.ToShortDateString()) reqEnv = reqEnv.Replace("{{lastSyncTime}}", lastSync.TimeOfDay.ToString()) '' 'reqEnv = "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" 'reqEnv += "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<SOAP-ENV:Body>" 'reqEnv += "<tns:SoapServicesBlob xmlns:tns=""http://www.MemberMax.com/namespace/default"">" 'reqEnv += "<inText xsi:type=""xsd:string"">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;" 'reqEnv += "&lt;RequestedMethodWrapper&gt;" 'reqEnv += "&lt;RequestedMethodParams&gt;" 'reqEnv += "&lt;MbrxSoapLicenseNo&gt;MBR9056592&lt;/MbrxSoapLicenseNo&gt;" 'reqEnv += "&lt;DataReturnFormat&gt;XML&lt;/DataReturnFormat&gt;" 'reqEnv += "&lt;ServerDebugLog&gt;Off&lt;/ServerDebugLog&gt;" 'reqEnv += "&lt;RequestedMethod&gt;GetChangedCompanies&lt;/RequestedMethod&gt;" 'reqEnv += "&lt;CompanyForOrgID&gt;All&lt;/CompanyForOrgID&gt;" 'reqEnv += "&lt;Orgfilter&gt;TCA&lt;/Orgfilter&gt;" 'reqEnv += "&lt;changedSinceDate&gt;" & lastSync.Date & "&lt;/changedSinceDate&gt;" 'reqEnv += "&lt;changedSinceTime&gt;" & lastSync.TimeOfDay.ToString & "&lt;/changedSinceTime&gt;" 'reqEnv += "&lt;MemberShipStatus&gt;All&lt;/MemberShipStatus&gt;" 'reqEnv += "&lt;/RequestedMethodParams&gt;" 'reqEnv += "&lt;/RequestedMethodWrapper&gt;" 'reqEnv += "</inText>" 'reqEnv += "</tns:SoapServicesBlob>" 'reqEnv += "</SOAP-ENV:Body>" 'reqEnv += "</SOAP-ENV:Envelope>" ' 'appendLog(CP, reqEnv) ' 'errorMessage = "" ' responseString = getMemberMaxSoapResponse(CP, requestAddr, reqEnv, "ns1:SoapServicesBlobResponse") If (responseString <> "") Then ' ' temp save xml from MM ' 'appendLog(CP, "pullPartialCompanyList: " & responseString) ' Call objXML.LoadXml(responseString) If Not objXML Is Nothing Then 'appendLog(CP, objXML.InnerXml) For Each opNode In objXML.GetElementsByTagName("ChangedCompany") Dim LegacyContactKey As Integer LegacyContactKey = CP.Utils.EncodeInteger(opNode.Item("LegacyContactKey").InnerText) ' cs.Open("Organizations", "memberMaxCompanyID=" & CP.Db.EncodeSQLNumber(LegacyContactKey)) If Not cs.OK Then cs.Close() cs.Insert("Organizations") cs.SetField("memberMaxCompanyID", LegacyContactKey.ToString()) End If If cs.OK Then cs.SetField("memberMaxSyncStatus", recordChangedAndNeedsToBeUpdated.ToString()) End If cs.Close() Next End If Else 'appendLogVerbose(CP, "Error: [" & errorNumber & "] " & errorMessage) End If ' appendLog(CP, "syncMemberMax_pullPartialCompanyList, exit") ' Catch ex As Exception appendLog(CP, "syncMemberMax_pullPartialCompanyList, error exit ex - " & ex.ToString()) errCount += 1 CP.Site.ErrorReport(ex) End Try End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <param name="organizationID"></param> ''' <returns></returns> ''' <remarks></remarks> Private Function syncMemberMax_isOrgMember(ByVal CP As Contensive.BaseClasses.CPBaseClass, ByVal organizationID As Integer) As Boolean Try Dim cs As BaseClasses.CPCSBaseClass = CP.CSNew ' ' look up if org is in an active (non deleting) organization ' 'isOrgMember = cs.Open("Organizations", "(ID=" & organizationID & ") and (memberMaxMemberType is not null) and (memberMaxMemberType<>'Not A Member')", , , "memberMaxMemberType") syncMemberMax_isOrgMember = cs.OpenSQL("select id from organizations where (ID=" & organizationID & ") and (memberMaxMemberType is not null) and (memberMaxMemberType<>'Not A Member')") Call cs.Close() ' Catch ex As Exception Try appendLog(CP, "ERROR, isOrgMember() - " & ex.ToString) errCount += 1 CP.Site.ErrorReport(ex) Catch errObj As Exception End Try End Try End Function ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="cp"></param> ''' <remarks></remarks> Private Sub syncMemberMax_syncCommittees(ByVal cp As Contensive.BaseClasses.CPBaseClass) Try 'Dim soapServicesTxtEnv As String = "" Dim csGroup As Contensive.BaseClasses.CPCSBaseClass Dim objXML As New XmlDocument Dim comNode As XmlNode Dim insrtFgl As Boolean = False 'Dim errorNumber As Integer = 0 'Dim errorMessage As String = "" Dim responseString As String = "" Dim memberMaxSoapRequestRemoteLogin As String = "" Dim requestEnv As String Dim memberMaxCommitteeId As Integer Dim memberMaxCommitteeName As String ' appendLog(cp, "syncMemberMax_syncCommittees") ' ' wrap it in the command envelope ' requestEnv = memberMaxSoapServicesBlobEnv.Replace("{{inText}}", xmlEscape(memberMaxSoapRequestAllCommittees)) '' '' Beth is out until 3/2 '' 'Dim mmax As New MemberMax.MbrMaxWebServicePortTypeClient 'mmax.Open() 'mmax.SoapServicesTxt(inText) 'mmax.Close() ' ' Josh's original TCA call ' 'reqEnv = "<?xml version=""1.0"" encoding=""ISO-8859-1""?>" _ ' & "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:tns=""http://www.MemberMax.com/namespace/default"">" _ ' & "<SOAP-ENV:Body>" _ ' & "<tns:SoapServicesBlob xmlns:tns=""http://www.MemberMax.com/namespace/default"">" _ ' & "<inText xsi:type=""xsd:string"">" _ ' & "&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;" _ ' & "&lt;RequestedMethodWrapper&gt;" _ ' & "&lt;RequestedMethodParams&gt;" _ ' & "&lt;MbrxSoapLicenseNo&gt;MBR9056592&lt;/MbrxSoapLicenseNo&gt;" _ ' & "&lt;DataReturnFormat&gt;XML&lt;/DataReturnFormat&gt;" _ ' & "&lt;ServerDebugLog&gt;Off&lt;/ServerDebugLog&gt;" _ ' & "&lt;RequestedMethod&gt;AllCommittees&lt;/RequestedMethod&gt;" _ ' & "&lt;CommitteesForOrgID&gt;TCA&lt;/CommitteesForOrgID&gt;" _ ' & "&lt;CommitteesForChapter&gt;All&lt;/CommitteesForChapter&gt;" _ ' & "&lt;/RequestedMethodParams&gt;" _ ' & "&lt;/RequestedMethodWrapper&gt;" _ ' & "</inText>" _ ' & "</tns:SoapServicesBlob>" _ ' & "</SOAP-ENV:Body>" _ ' & "</SOAP-ENV:Envelope>" ' responseString = getMemberMaxSoapResponse(cp, requestAddr, requestEnv, "ns1:SoapServicesBlobResponse") ' 'syncMemberMax_logSyncEvent(cp, "responseString: " & responseString, "committee") 'syncMemberMax_logSyncEvent(cp, "reqEnv: " & soapServicesTxtEnv, "committee") ' If (responseString <> "") Then ' ' temp save xml from MM ' 'appendLog(cp, "syncCommittees: " & responseString) ' Call objXML.LoadXml(responseString) If Not objXML Is Nothing Then For Each comNode In objXML.GetElementsByTagName("COMMITTEES") insrtFgl = False memberMaxCommitteeId = cp.Utils.EncodeInteger(comNode.Item("CommitteeID").InnerText) If memberMaxCommitteeId = 0 Then Call appendLog(cp, "syncMemberMax_syncCommittees, committee downloaded with a non-valid membermaxcommitteeid [" & memberMaxCommitteeId.ToString() & "]") Else memberMaxCommitteeName = comNode.Item("Name").InnerText csGroup = cp.CSNew csGroup.Open("Groups", "memberMaxCommitteeId=" & cp.Db.EncodeSQLNumber(memberMaxCommitteeId)) If Not csGroup.OK Then Call csGroup.Close() csGroup.Open("Groups", "Name=" & cp.Db.EncodeSQLText(memberMaxCommitteeName)) If Not csGroup.OK Then Call csGroup.Close() Call csGroup.Insert("Groups") Call csGroup.SetField("Name", memberMaxCommitteeName) End If End If If csGroup.OK() Then Call csGroup.SetField("memberMaxCommitteeId", memberMaxCommitteeId.ToString()) Call csGroup.SetField("Caption", memberMaxCommitteeName) Call csGroup.SetField("CopyFileName", comNode.Item("Charter").InnerText) End If Call csGroup.Close() End If Next End If End If ' appendLog(cp, "syncMemberMax_syncCommittees, exit ") ' Catch ex As Exception Try appendLog(cp, "ERROR, syncCommittees() - " & ex.ToString) errCount += 1 cp.Site.ErrorReport(ex, "catch in syncCommittees") Catch errObj As Exception End Try ' appendLog(cp, "syncMemberMax_syncCommittees, error exit") ' End Try End Sub '==================================================================================================== ''' <summary> ''' encode a text string to be included as an xml entity ''' </summary> ''' <param name="txtSrc"></param> ''' <returns></returns> ''' <remarks></remarks> Private Function xmlEscape(txtSrc As String) As String Return txtSrc.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\", "&quot;").Replace("'", "&apos;") End Function ' '==================================================================================================== ''' <summary> ''' request an envelope from a serviceURI. REturn empty on error. ''' </summary> ''' <param name="serviceURI"></param> ''' <param name="requestEnvelope"></param> ''' <param name="responseNode"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function getMemberMaxSoapResponse(cp As CPBaseClass, ByVal serviceURI As String, ByVal requestEnvelope As String, ByVal responseNode As String) As String Dim soapResponse As String = "" ' Try Dim sysURI As New System.Uri(serviceURI) Dim eop As New Microsoft.Web.Services3.Addressing.EndpointReference(sysURI) Dim se As New Microsoft.Web.Services3.SoapEnvelope() Dim memberMaxSoapClient As New memberMaxSoapClientClass(eop) Dim fileContent As String = "" ' Dim decodedBytes As Byte() Dim decodedText As String = "" ' Dim returnEnvelope As New Microsoft.Web.Services3.SoapEnvelope() ' fileContent += requestEnvelope & vbCrLf & vbCrLf se.InnerXml = requestEnvelope fileContent += se.OuterXml & vbCrLf & vbCrLf ' 'System.IO.File.AppendAllText("c:\temp\seleralizedXML3.txt", fileContent) ' returnEnvelope = memberMaxSoapClient.RequestResponseMethod(se) If returnEnvelope Is Nothing Then ' ' membermax empty reply throws error, client catches it and returns nothing ' soapResponse = "" Else ' If responseNode = "" Then responseNode = "//Result" End If ' For Each XmlNode As XmlNode In returnEnvelope.Body.ChildNodes If XmlNode.Name = responseNode Then decodedBytes = Convert.FromBase64String(returnEnvelope.Body.InnerText) decodedText = Encoding.UTF8.GetString(decodedBytes) ' soapResponse = decodedText End If Next End If Catch ex As Exception cp.Site.ErrorReport(ex, "exception in getMemberMaxSoapResponse") End Try ' Return soapResponse ' End Function '' ''==================================================================================================== ' ''' <summary> ' ''' ' ''' </summary> ' ''' <param name="cp"></param> ' ''' <remarks></remarks> 'Private Sub syncMemberMax_cleanGroups(ByVal cp As Contensive.BaseClasses.CPBaseClass) ' Try ' Dim cs As BaseClasses.CPCSBaseClass = cp.CSNew() ' Dim csSQL As BaseClasses.CPCSBaseClass = cp.CSNew() ' ' ' ' go through all groups with memberMaxCommitteeId (groups maintained by the sync) ' ' clear out everyone who was not updated ' ' unlike people and organziations, this should happen immediately ' ' ' cs.Open("Groups", "memberMaxCommitteeId is not null", , , "ID") ' Do While cs.OK() ' '********cp.Db.ExecuteSQL("DELETE FROM ccMemberRules WHERE (groupID=" & cs.GetInteger("ID") & ") and (createKey=" & recordStale & ")") ' cs.GoNext() ' Loop ' cs.Close() ' Catch ex As Exception ' Try ' appendFile( cp, "ERROR, cleanTCAGroups() - " & ex.ToString) ' errCount += 1 ' cp.Site.ErrorReport(ex, "catch in cleanTCAGroups") ' Catch eerrObj As Exception ' End Try ' End Try 'End Sub ' ''==================================================================================================== ' ''' <summary> ' ''' ' ''' </summary> ' ''' <param name="cp"></param> ' ''' <remarks></remarks> 'Private Sub syncMemberMax_removeUnwantedPeople(ByVal cp As Contensive.BaseClasses.CPBaseClass) ' Try ' Dim cs As BaseClasses.CPCSBaseClass = cp.CSNew() ' Dim csM As BaseClasses.CPCSBaseClass = cp.CSNew() ' ' ' If cs.Open("Organizations", "memberMaxMemberType='Not A Member'", , , "id") Then ' Do While cs.OK() ' If csM.Open("People", "organizationID=" & cs.GetInteger("id"), , , "id") Then ' Do While csM.OK() ' '********cp.Group.RemoveUser("MemberMax TLPA Members", csM.GetInteger("ID")) ' csM.GoNext() ' Loop ' End If ' csM.Close() ' ' ' cs.GoNext() ' Loop ' End If ' cs.Close() ' ' ' Catch ex As Exception ' Try ' appendFile( cp, "ERROR, removeUnwantedPeople() - " & ex.ToString) ' errCount += 1 ' cp.Site.ErrorReport(ex, "catch in removeUnwantedPeople") ' Catch errObj As Exception ' End Try ' End Try 'End Sub ' '==================================================================================================== ''' <summary> ''' ''' </summary> ''' <param name="CP"></param> ''' <param name="eventMsg"></param> ''' <param name="appPart"></param> ''' <remarks></remarks> Public Sub appendLog(ByVal CP As Contensive.BaseClasses.CPBaseClass, ByVal eventMsg As String, Optional appPart As String = "") Try Dim rightNow As Date = Now() If _allowLogging Is Nothing Then _allowLogging = CP.Site.GetProperty("TLPA Allow Housekeep Log", "0") If _allowLogging Is Nothing Then _allowLogging = "0" End If End If If CP.Utils.EncodeBoolean(_allowLogging) Then CP.Utils.AppendLog("tlpaHousekeep" & rightNow.Year & rightNow.Month.ToString().PadLeft(2, "0"c) & rightNow.Day.ToString().PadLeft(2, "0"c) & ".log", eventMsg) End If Catch ex As Exception CP.Site.ErrorReport(ex, "error in Contensive.Addons.performanceCloud.commonClass.logPCEvent") End Try End Sub ' Private Function getGroupId(cp As CPBaseClass, groupGuid As String, groupName As String) As Integer Dim returnId As Integer = 0 Try Dim cs As CPCSBaseClass = cp.CSNew() cs.Open("Groups", "ccguid='" & groupGuid & "'") If Not cs.OK Then cs.Close() cs.Insert("Groups") If cs.OK Then cs.SetField("Name", groupName) cs.SetField("Caption", groupName) cs.SetField("ccguid", groupGuid) returnId = cs.GetInteger("ID") End If Else returnId = cs.GetInteger("ID") End If cs.Close() Catch ex As Exception cp.Site.ErrorReport(ex, "error in getGroupId") End Try Return returnId End Function ' Private ReadOnly Property mailListSpecialAlertId(cp As CPBaseClass) As Integer Get If _mailListSpecialAlert = 0 Then _mailListSpecialAlert = getGroupId(cp, "{CCAC64B0-A0E0-4F2F-A958-D87743AD2BE2}", "Mail List, Special Alert") End If Return _mailListSpecialAlert End Get End Property : Private _mailListSpecialAlert As Integer = 0 ' Private ReadOnly Property mailListLegislativeAlertId(cp As CPBaseClass) As Integer Get If _mailListLegislativeAlertId = 0 Then _mailListLegislativeAlertId = getGroupId(cp, "{7F62015C-B86C-4321-BD9B-9B603668DDFD}", "Mail List, Legislative alert") End If Return _mailListLegislativeAlertId End Get End Property : Private _mailListLegislativeAlertId As Integer = 0 ' Private ReadOnly Property mailListParatransitId(cp As CPBaseClass) As Integer Get If _mailListParatransitId = 0 Then _mailListParatransitId = getGroupId(cp, "{B8B8DCBB-A747-4DD5-A3D7-6EDE2D0FD36F}", "Mail List, Paratransit") End If Return _mailListParatransitId End Get End Property : Private _mailListParatransitId As Integer = 0 ' Private ReadOnly Property mailListLimousineId(cp As CPBaseClass) As Integer Get If _mailListLimousineId = 0 Then _mailListLimousineId = getGroupId(cp, "{A3AC4DA8-47F4-484A-8187-0B431350222C}", "Mail List, Limousine") End If Return _mailListLimousineId End Get End Property : Private _mailListLimousineId As Integer = 0 ' Private ReadOnly Property mailListTaxicabId(cp As CPBaseClass) As Integer Get If _mailListTaxicabId = 0 Then _mailListTaxicabId = getGroupId(cp, "{ABEFC41D-86FE-484B-AC2C-751AE121EFB6}", "Mail List, Taxicab") End If Return _mailListTaxicabId End Get End Property : Private _mailListTaxicabId As Integer = 0 ' Private ReadOnly Property mailListRideHailNewsId(cp As CPBaseClass) As Integer Get If _mailListRideHailNewsId = 0 Then _mailListRideHailNewsId = getGroupId(cp, "{CF7820D1-06B2-49C5-A9E6-E4129F832665}", "Mail List, Ride Hail News") End If Return _mailListRideHailNewsId End Get End Property : Private _mailListRideHailNewsId As Integer = 0 ' Private ReadOnly Property mailListRepPlusId(cp As CPBaseClass) As Integer Get If _mailListRepPlusId = 0 Then _mailListRepPlusId = getGroupId(cp, "{0145EA2B-59C1-43D8-926D-DC527D3D6C4E}", "Mail List, Rep Plus") End If Return _mailListRepPlusId End Get End Property : Private _mailListRepPlusId As Integer = 0 ' Private Sub verifyGroup(cp As Contensive.BaseClasses.CPBaseClass, userId As Integer, groupId As Integer, isGroupMember As Boolean) Try Dim cs2 As CPCSBaseClass = cp.CSNew() ' cs2.Open("Member Rules", "(groupid=" & groupId & ") AND (memberID=" & userId & ")") If cs2.OK Then If Not isGroupMember Then ' is in group but should not be cs2.Delete() End If Else If isGroupMember Then ' is not in group but should be cs2.Close() cs2.Insert("Member Rules") If cs2.OK Then cs2.SetField("GroupID", groupId.ToString()) cs2.SetField("MemberID", userId.ToString()) End If End If End If cs2.Close() Catch ex As Exception End Try End Sub End Class End Namespace
Public MustInherit Class Behavior Inherits FrameworkElement Private _Element As DependencyObject Public ReadOnly Property Element As DependencyObject Get Return _Element End Get End Property Protected Sub New() End Sub Friend Sub Attach(element As DependencyObject) If _Element IsNot Nothing Then Throw New BehaviorException(Me, String.Format("The behavior '{0}' is already attached to the element {1}.", Me, _Element)) End If _Element = element Me.OnAttached() End Sub Protected Overridable Sub OnAttached() End Sub End Class
Imports BVSoftware.Bvc5.Core.PersonalizationServices Imports BVSoftware.Bvc5.Core Imports System.Web.Security Partial Class BVModules_Checkouts_One_Page_Checkout_Plus_Login Inherits BaseStorePage Public Overrides ReadOnly Property RequiresSSL() As Boolean Get Return True End Get End Property Private Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.MasterPageFile = PersonalizationServices.GetSafeMasterPage("Checkout.master") Me.Title = "Login to Checkout" End Sub Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load AddHandler ucLoginControl.LoginCompleted, AddressOf LoginCompleted If Not Page.IsPostBack Then Me.btnContinue.ImageUrl = PersonalizationServices.GetThemedButton("ContinueToCheckout") If SessionManager.IsUserAuthenticated Then RedirectOnComplete(SessionManager.GetCurrentUserId) End If End If End Sub Private Sub RedirectOnComplete(ByVal userId As String) Response.Redirect(PersonalizationServices.GetCheckoutUrl(userId)) End Sub Public Sub LoginCompleted(ByVal sender As Object, ByVal args As Controls.LoginCompleteEventArgs) RedirectOnComplete(args.UserId) End Sub Protected Sub ibtnContinue_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnContinue.Click Response.Redirect(PersonalizationServices.GetCheckoutUrl(SessionManager.GetCurrentUserId) & "?s=new") End Sub End Class
#Region "Microsoft.VisualBasic::2255a5773c85b274cf5238bf66ecd7f3, mzkit\src\mzmath\ms2_simulator\FragmentSamples.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: 94 ' Code Lines: 69 ' Comment Lines: 14 ' Blank Lines: 11 ' File Size: 3.30 KB ' Module FragmentSamples ' ' Function: GetFragmentsMz, productTree, RtSamples ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1 Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra Imports Microsoft.VisualBasic.ComponentModel.Algorithm.BinaryTree Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.MachineLearning.ComponentModel.StoreProcedure Imports Microsoft.VisualBasic.Math.Quantile Public Module FragmentSamples ''' <summary> ''' Get all unique product m/z values ''' </summary> ''' <param name="ms2"></param> ''' <param name="tolerance"></param> ''' <returns></returns> <Extension> Public Function GetFragmentsMz(ms2 As IEnumerable(Of LibraryMatrix), Optional tolerance As Tolerance = Nothing) As Double() Dim productMz As NaiveBinaryTree(Of Double, Double) = (tolerance Or ppm20).productTree For Each ion As LibraryMatrix In ms2 For Each mz As ms2 In ion Call productMz.insert(mz.mz, mz.mz, append:=False) Next Next Return productMz _ .GetAllNodes _ .Select(Function(mz) mz.Key) _ .ToArray End Function <MethodImpl(MethodImplOptions.AggressiveInlining)> <Extension> Private Function productTree(tolerance As Tolerance) As NaiveBinaryTree(Of Double, Double) Return New NaiveBinaryTree(Of Double, Double)( Function(x, y) If tolerance.Equals(x, y) Then Return 0 ElseIf x > y Then Return 1 Else Return -1 End If End Function) End Function ''' <summary> ''' Create samples data for ML training or rt evaluation ''' </summary> ''' <param name="ms2"></param> ''' <param name="fragments#"></param> ''' <param name="tolerance"></param> ''' <returns></returns> <Extension> Public Iterator Function RtSamples(ms2 As IEnumerable(Of PeakMs2), fragments#(), Optional tolerance As Tolerance = Nothing) As IEnumerable(Of Sample) Dim rt# ' parent/mz, product/mz intensity Dim mzSample As New List(Of Double) Dim equals As GenericLambda(Of Double).IEquals = tolerance Or ppm20 Dim into As ms2() fragments = fragments _ .OrderBy(Function(x) x) _ .ToArray For Each matrix As PeakMs2 In ms2 rt = matrix.rt mzSample *= 0 For Each indexMz As Double In fragments into = matrix.mzInto _ .Where(Function(m) equals(m.mz, indexMz)) _ .ToArray If into.Length = 0 Then mzSample += 0 Else mzSample += into _ .Select(Function(m) m.intensity) _ .Quartile _ .ModelSamples _ .normal _ .Average End If Next Yield New Sample(matrix.mz + mzSample) With { .ID = matrix.ToString, .target = {rt} } Next End Function End Module
Imports System.Runtime.Serialization Namespace DataContracts <DataContract()> Public Class FingerPrintClass Private m_MYFINGERPRINT As New ARTBOPTCALC_FINGERPRINTS Private m_FingerPrints As New List(Of ARTBOPTCALC_FINGERPRINTS) Private m_FPStatus As FPStatusEnum Private m_FPMessage As String = String.Empty Private m_License As New ARTBOPTCALC_LICENSES Private m_PRODUCT_ID As String Private m_PRODUCT As New ARTBOPTCALC_PRODUCTS Private m_OFPswd As String <DataMember()> Public Property OFPswd As String Get Return m_OFPswd End Get Set(value As String) m_OFPswd = value End Set End Property <DataMember()> Public Property FPMessage As String Get Return m_FPMessage End Get Set(value As String) m_FPMessage = value End Set End Property <DataMember()> Public Property PRODUCT As ARTBOPTCALC_PRODUCTS Get Return m_PRODUCT End Get Set(value As ARTBOPTCALC_PRODUCTS) m_PRODUCT = value End Set End Property <DataMember()> Public Property PRODUCT_ID As String Get Return m_PRODUCT_ID End Get Set(value As String) m_PRODUCT_ID = value End Set End Property <DataMember()> Public Property MYFINGERPRINT As ARTBOPTCALC_FINGERPRINTS Get Return m_MYFINGERPRINT End Get Set(value As ARTBOPTCALC_FINGERPRINTS) m_MYFINGERPRINT = value End Set End Property <DataMember()> Public Property FingerPrints As List(Of ARTBOPTCALC_FINGERPRINTS) Get Return m_FingerPrints End Get Set(value As List(Of ARTBOPTCALC_FINGERPRINTS)) m_FingerPrints = value End Set End Property <DataMember> Public Property License As ARTBOPTCALC_LICENSES Get Return m_License End Get Set(value As ARTBOPTCALC_LICENSES) m_License = value End Set End Property <DataMember> Public Property FPStatus As FPStatusEnum Get Return m_FPStatus End Get Set(value As FPStatusEnum) m_FPStatus = value End Set End Property End Class <DataContract> _ Public Class FFASuiteCredentials Private m_FINGERPRINT As String = String.Empty Private m_PRODUCT_ID As String = String.Empty Private m_ANSWER As FPStatusEnum Private m_TimeStamp As DateTime = Now Private m_SubscribedRoutes As New List(Of Integer) <DataMember> _ Public Property SubscribedRoutes As List(Of Integer) Get Return m_SubscribedRoutes End Get Set(value As List(Of Integer)) m_SubscribedRoutes = value End Set End Property <DataMember> _ Public Property FINGERPRINT As String Get Return m_FINGERPRINT End Get Set(value As String) m_FINGERPRINT = value End Set End Property <DataMember> _ Public Property PRODUCT_ID As String Get Return m_PRODUCT_ID End Get Set(value As String) m_PRODUCT_ID = value End Set End Property <DataMember> _ Public Property ANSWER As FPStatusEnum Get Return m_ANSWER End Get Set(value As FPStatusEnum) m_ANSWER = value End Set End Property <DataMember> _ Public Property TimeStamp As DateTime Get Return m_TimeStamp End Get Set(value As DateTime) m_TimeStamp = value End Set End Property End Class <DataContract> _ Public Class ChatMessage <DataMember> _ Public Property Username As String <DataMember> _ Public Property Text As String <DataMember> _ Public Property Timestamp As DateTime End Class <DataContract> _ Public Class FFAMessage Private m_UserName As String Private m_MsgType As MessageEnum Private m_Payload As String Private m_TimeStamp As DateTime <DataMember> _ Public Property Username As String Get Return m_UserName End Get Set(value As String) m_UserName = value End Set End Property <DataMember> _ Public Property MsgType As MessageEnum Get Return m_MsgType End Get Set(value As MessageEnum) m_MsgType = value End Set End Property <DataMember> _ Public Property Payload As String Get Return m_Payload End Get Set(value As String) m_Payload = value End Set End Property <DataMember> _ Public Property TimeStamp As DateTime Get Return m_TimeStamp End Get Set(value As DateTime) m_TimeStamp = value End Set End Property End Class <DataContract(Name:="MessageEnum")> _ Public Enum MessageEnum <EnumMember> MarketViewUpdate <EnumMember> TradeAnnouncement <EnumMember> SpotRatesUpdate <EnumMember> SwapRatesUpdate <EnumMember> CloseClient <EnumMember> AmmendReportedTrade End Enum <DataContract()> Public Class VolDataClass Private m_VolRecordType As VolRecordTypeEnum Private m_ROUTE_ID As Integer Private m_ROUTE_ID2 As Integer Private m_FIXING_DATE As Date Private m_PERIOD As String Private m_FFA_PRICE As Double Private m_SPOT_PRICE As Double Private m_IVOL As Double Private m_HVOL As Double Private m_INTEREST_RATE As Double Private m_YY1 As Integer Private m_YY2 As Integer Private m_MM1 As Integer Private m_MM2 As Integer Private m_YY21 As Integer Private m_YY22 As Integer Private m_MM21 As Integer Private m_MM22 As Integer Private m_TRADE_TYPE As OrderTypesEnum Private m_PNC As Boolean Private m_ONLYHISTORICAL As Boolean Private m_TRADE_ID As Integer Private m_DESK_TRADER_ID As Integer <DataMember()> Public Property DESK_TRADER_ID As Integer Get Return m_DESK_TRADER_ID End Get Set(value As Integer) m_DESK_TRADER_ID = value End Set End Property <DataMember()> Public Property TRADE_ID As Integer Get Return m_TRADE_ID End Get Set(value As Integer) m_TRADE_ID = value End Set End Property <DataMember()> Public Property VolRecordType As VolRecordTypeEnum Get Return m_VolRecordType End Get Set(value As VolRecordTypeEnum) m_VolRecordType = value End Set End Property <DataMember()> Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember()> Public Property ROUTE_ID2 As Integer Get Return m_ROUTE_ID2 End Get Set(value As Integer) m_ROUTE_ID2 = value End Set End Property <DataMember()> Public Property FIXING_DATE As Date Get Return m_FIXING_DATE End Get Set(value As Date) m_FIXING_DATE = value End Set End Property <DataMember()> Public Property PERIOD As String Get Return m_PERIOD End Get Set(value As String) m_PERIOD = value End Set End Property <DataMember()> Public Property FFA_PRICE As Double Get Return m_FFA_PRICE End Get Set(value As Double) m_FFA_PRICE = value End Set End Property <DataMember()> Public Property SPOT_PRICE As Double Get Return m_SPOT_PRICE End Get Set(value As Double) m_SPOT_PRICE = value End Set End Property <DataMember()> Public Property IVOL As Double Get Return m_IVOL End Get Set(value As Double) m_IVOL = value End Set End Property <DataMember()> Public Property HVOL As Double Get Return m_HVOL End Get Set(value As Double) m_HVOL = value End Set End Property <DataMember()> Public Property INTEREST_RATE As Double Get Return m_INTEREST_RATE End Get Set(value As Double) m_INTEREST_RATE = value End Set End Property <DataMember()> Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property <DataMember()> Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property <DataMember()> Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property <DataMember()> Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property <DataMember()> Public Property YY21 As Integer Get Return m_YY21 End Get Set(value As Integer) m_YY21 = value End Set End Property <DataMember()> Public Property YY22 As Integer Get Return m_YY22 End Get Set(value As Integer) m_YY22 = value End Set End Property <DataMember()> Public Property MM21 As Integer Get Return m_MM21 End Get Set(value As Integer) m_MM21 = value End Set End Property <DataMember()> Public Property MM22 As Integer Get Return m_MM22 End Get Set(value As Integer) m_MM22 = value End Set End Property <DataMember()> Public Property ONLYHISTORICAL As Boolean Get Return m_ONLYHISTORICAL End Get Set(value As Boolean) m_ONLYHISTORICAL = value End Set End Property <DataMember()> Public Property PNC As Boolean Get Return m_PNC End Get Set(value As Boolean) m_PNC = value End Set End Property <DataMember()> Public Property TRADE_TYPE As OrderTypesEnum Get Return m_TRADE_TYPE End Get Set(value As OrderTypesEnum) m_TRADE_TYPE = value End Set End Property Public Function clone() As VolDataClass Dim ne As New VolDataClass ne.TRADE_TYPE = m_TRADE_TYPE ne.DESK_TRADER_ID = DESK_TRADER_ID ne.TRADE_ID = m_TRADE_ID ne.FFA_PRICE = m_FFA_PRICE ne.FIXING_DATE = m_FIXING_DATE ne.HVOL = m_HVOL ne.INTEREST_RATE = m_INTEREST_RATE ne.IVOL = m_IVOL ne.MM1 = m_MM1 ne.MM2 = m_MM2 ne.MM21 = m_MM21 ne.MM22 = m_MM22 ne.ONLYHISTORICAL = m_ONLYHISTORICAL ne.PERIOD = m_PERIOD ne.ROUTE_ID = m_ROUTE_ID ne.ROUTE_ID2 = m_ROUTE_ID2 ne.SPOT_PRICE = m_SPOT_PRICE ne.YY1 = m_YY1 ne.YY2 = m_YY2 ne.YY21 = m_YY21 ne.YY22 = m_YY22 ne.PNC = m_PNC Return ne End Function End Class <DataContract()> Public Class SwapPeriodClass Private m_YY1 As Integer Private m_YY2 As Integer Private m_MM1 As Integer Private m_MM2 As Integer Private m_PERIOD As String Public Sub New() End Sub <DataMember()> Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property <DataMember()> Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property <DataMember()> Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property <DataMember()> Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property <DataMember()> Public Property PERIOD As String Get Return m_PERIOD End Get Set(value As String) m_PERIOD = value End Set End Property End Class <DataContract()> Public Class SwapDataClass Private m_ROUTE_ID As Integer Private m_VESSEL_CLASS_ID As Integer Private m_TRADE_CLASS_SHORT As Char Private m_CCY_ID As Integer Private m_SPOT_AVG As Double Private m_SPOT_PRICE As Double Private m_AVERAGE_INCLUDES_TODAY As Boolean Private m_PRICING_TICK As Double Private m_FORMAT_STRING As String Private m_DECIMAL_PLACES As Integer Private m_ROUTE_SHORT As String Private m_SPOT_FIXING_DATE As Date <DataMember()> Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember()> Public Property VESSEL_CLASS_ID As Integer Get Return m_VESSEL_CLASS_ID End Get Set(value As Integer) m_VESSEL_CLASS_ID = value End Set End Property <DataMember()> Public Property TRADE_CLASS_SHORT As Char Get Return m_TRADE_CLASS_SHORT End Get Set(value As Char) m_TRADE_CLASS_SHORT = value End Set End Property <DataMember()> Public Property DECIMAL_PLACES As Integer Get Return m_DECIMAL_PLACES End Get Set(value As Integer) m_DECIMAL_PLACES = value End Set End Property <DataMember()> Public Property FORMAT_STRING As String Get Return m_FORMAT_STRING End Get Set(value As String) m_FORMAT_STRING = value End Set End Property <DataMember()> Public Property CCY_ID As Integer Get Return m_CCY_ID End Get Set(value As Integer) m_CCY_ID = value End Set End Property <DataMember()> Public Property FIXING_AVG As Double Get Return m_SPOT_AVG End Get Set(value As Double) m_SPOT_AVG = value End Set End Property <DataMember()> Public Property SPOT_PRICE As Double Get Return m_SPOT_PRICE End Get Set(value As Double) m_SPOT_PRICE = value End Set End Property <DataMember()> Public Property SPOT_FIXING_DATE As Date Get Return m_SPOT_FIXING_DATE End Get Set(value As Date) m_SPOT_FIXING_DATE = value End Set End Property <DataMember()> Public Property AVERAGE_INCLUDES_TODAY As Boolean Get Return m_AVERAGE_INCLUDES_TODAY End Get Set(value As Boolean) m_AVERAGE_INCLUDES_TODAY = value End Set End Property <DataMember()> Public Property PRICING_TICK As Double Get Return m_PRICING_TICK End Get Set(value As Double) m_PRICING_TICK = value End Set End Property <DataMember()> Public Property ROUTE_SHORT As String Get Return m_ROUTE_SHORT End Get Set(value As String) m_ROUTE_SHORT = value End Set End Property End Class <DataContract()> Public Class InterestRatesClass Private m_CCY_ID As Integer Private m_FIXING_DATE As Date Private m_PERIOD As Integer Private m_RATE As Double <DataMember()> Public Property CCY_ID As Integer Get Return m_CCY_ID End Get Set(value As Integer) m_CCY_ID = value End Set End Property <DataMember()> Public Property FIXING_DATE As Date Get Return m_FIXING_DATE End Get Set(value As Date) m_FIXING_DATE = value End Set End Property <DataMember()> Public Property PERIOD As Integer Get Return m_PERIOD End Get Set(value As Integer) m_PERIOD = value End Set End Property <DataMember()> Public Property RATE As Double Get Return m_RATE End Get Set(value As Double) m_RATE = value End Set End Property End Class <DataContract()> Public Class CCYInterestRatesClass Private m_Count As Integer Private m_CCY_INTEREST_RATES As New List(Of InterestRatesClass) <DataMember()> Public Property Count As Integer Get m_Count = m_CCY_INTEREST_RATES.Count Return m_Count End Get Set(value As Integer) m_Count = value End Set End Property <DataMember()> Public Property CCY_INTEREST_RATES As List(Of InterestRatesClass) Get Return m_CCY_INTEREST_RATES End Get Set(value As List(Of InterestRatesClass)) m_CCY_INTEREST_RATES = value End Set End Property End Class <DataContract()> Public Class ArtBTimePeriod Private m_ROUTE_ID As Integer Private m_SERVER_DATE As Date Private m_StartMonth As Integer = -1 Private m_EndMonth As Integer = -1 Private m_Descr As String = "" Private m_Selected As Boolean = False Private m_StartDate As Date Private m_EndDate As Date Private m_MM1 As Integer Private m_YY1 As Integer Private m_MM2 As Integer Private m_YY2 As Integer Private m_DPM As Double Private m_TotDays As Integer <DataMember()> Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember()> Public Property SERVER_DATE As Date Get Return m_SERVER_DATE End Get Set(value As Date) m_SERVER_DATE = value End Set End Property <DataMember()> Public Property StartMonth As Integer Get Return m_StartMonth End Get Set(value As Integer) m_StartMonth = value End Set End Property <DataMember()> Public Property EndMonth As Integer Get Return m_EndMonth End Get Set(value As Integer) m_EndMonth = value End Set End Property <DataMember()> Public Property Descr As String Get Return m_Descr End Get Set(value As String) m_Descr = value End Set End Property <DataMember()> Public Property Selected As Boolean Get Return m_Selected End Get Set(value As Boolean) m_Selected = value End Set End Property <DataMember()> Public Property StartDate As Date Get Return m_StartDate End Get Set(value As Date) m_StartDate = value End Set End Property <DataMember()> Public Property EndDate As Date Get Return m_EndDate End Get Set(value As Date) m_EndDate = value End Set End Property <DataMember()> Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property <DataMember()> Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property <DataMember()> Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property <DataMember()> Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property <DataMember()> Public Property DPM As Double Get Return m_DPM End Get Set(value As Double) m_DPM = value End Set End Property <DataMember()> Public Property TotDays As Integer Get Return m_TotDays End Get Set(value As Integer) m_TotDays = value End Set End Property Public Sub FillDPM() Dim i As Integer, m As Integer, y As Integer TotDays = 0 For i = StartMonth To EndMonth y = CInt(Int(i / 12)) m = (i - y * 12) + 1 y = y + 2000 TotDays = TotDays + DateTime.DaysInMonth(y, m) Next DPM = TotDays / (EndMonth - StartMonth + 1) End Sub Public Sub FillMY(ByVal a_mm1 As Integer, ByVal a_yy1 As Integer, _ ByVal a_mm2 As Integer, ByVal a_yy2 As Integer) MM1 = a_mm1 YY1 = a_yy1 Mod 2000 MM2 = a_mm2 YY2 = a_yy2 Mod 2000 StartMonth = YY1 * 12 + MM1 - 1 EndMonth = YY2 * 12 + MM2 - 1 End Sub Public Sub FillDates() Dim s As String If (StartMonth = -1) Then YY1 = 0 MM1 = 1 Else YY1 = CInt(Int(StartMonth / 12)) MM1 = (StartMonth - YY1 * 12) + 1 End If Try s = "20" & Format(YY1, "00") & "-" & Format(MM1, "00") & "-01" StartDate = Date.Parse(s) Catch e As Exception End Try If EndMonth = -1 Then YY2 = 0 MM2 = 1 Else YY2 = CInt(Int(EndMonth / 12)) MM2 = (EndMonth - YY2 * 12) + 1 End If Try s = "20" & Format(YY2, "00") & "-" & Format(MM2, "00") & "-" & Format(DateTime.DaysInMonth(YY2, MM2), "00") EndDate = Date.Parse(s) Catch e As Exception End Try End Sub Public Function AddOverlapping(ByRef t As ArtBTimePeriod) As Boolean AddOverlapping = False If t Is Nothing Then Exit Function If t.EndMonth < StartMonth - 1 Then Exit Function If EndMonth < StartMonth - 1 Then Exit Function If t.StartMonth < StartMonth Then StartMonth = t.StartMonth If t.EndMonth > EndMonth Then EndMonth = t.EndMonth AddOverlapping = True End Function Public Sub CreateDescr() FillDates() Descr = "" Dim i As Integer, y As Integer If StartMonth = EndMonth Then i = (StartMonth Mod 12) + 1 Descr = MonthShort(MM1) & "-" & Format(YY1, "00") Exit Sub End If If EndMonth Mod 3 <> 2 Then If EndMonth - StartMonth >= 4 Then Descr = MonthShort(MM1) & "-" & Format(YY1, "00") i = EndMonth - StartMonth Descr = Descr & "+" & Format(i, "0") & " Months" Exit Sub Else For i = StartMonth To EndMonth If Len(Descr) > 0 Then Descr = Descr & "+" Descr = Descr & MonthShort(i Mod 12 + 1) & "-" & Format(Int(i / 12), "00") Next i Exit Sub End If End If Dim YEM As Integer = EndMonth Dim SY As Integer = YY1 + 1 Dim EY As Integer = YY2 If MM2 = 12 Then If MM1 = 1 Then YEM = -1 SY = YY1 Else YEM = SY * 12 - 1 End If For i = SY To EY If Len(Descr) > 0 Then Descr = Descr & "+" Descr = Descr & "Cal-" & Format(i, "00") Next End If If StartMonth > YEM Then Exit Sub Dim mDescr As String = "" Dim qDescr As String = "" Dim minQ As Integer = CInt(Int(StartMonth / 3)) If minQ * 3 < StartMonth Then minQ = minQ + 1 For i = StartMonth To minQ * 3 - 1 If Len(mDescr) > 0 Then mDescr = mDescr & "+" mDescr = mDescr & MonthShort(i Mod 12 + 1) & "-" & Format(Int(i / 12), "00") Next End If Dim maxQ As Integer = CInt(Int(YEM / 3)) For i = minQ To maxQ If Len(qDescr) > 0 Then qDescr = qDescr & "+" y = CInt(Int(i / 4)) If i Mod 4 = 0 And i + 3 <= maxQ Then qDescr = qDescr & "Cal-" & Format(y, "00") i += 3 Else qDescr = qDescr & "Q" & Format((i Mod 4) + 1, "0") & "-" & Format(y, "00") End If Next If Len(qDescr) > 0 Then If Len(Descr) > 0 Then Descr = "+" & Descr Descr = qDescr + Descr End If If Len(mDescr) > 0 Then If Len(Descr) > 0 Then Descr = "+" & Descr Descr = mDescr + Descr End If End Sub Public Sub ParseDescr() Dim i As Integer Dim qr As Integer Dim y As Integer If Len(Descr) >= 3 Then For i = 1 To 12 If Left(Descr, 3) = MonthShort(i) Then y = CInt(Right(Descr, 2)) StartMonth = y * 12 + i - 1 EndMonth = y * 12 + i - 1 Exit Sub End If Next If Left(Descr, 3) = "Cal" Then y = CInt(Right(Descr, 2)) StartMonth = y * 12 EndMonth = y * 12 + 11 End If End If Dim s As String = Descr Dim q As String StartMonth = 1000 EndMonth = -1000 While Len(s) > 1 Dim j As Integer = s.IndexOf("+") If j > 1 Then q = s.Substring(0, j) s = s.Substring(j) Else q = s s = "" End If If Left(q, 1) <> "Q" Then StartMonth = -1 EndMonth = -1 Exit Sub End If qr = CInt(Mid(q, 3, 1)) If qr < 1 Or qr > 4 Then StartMonth = -1 EndMonth = -1 Exit Sub End If y = CInt(Right(q, 2)) Dim sm As Integer = y * 12 + (qr - 1) * 3 Dim em As Integer = y * 12 + (qr - 1) * 3 + 2 If StartMonth > sm Then StartMonth = sm If EndMonth < em Then EndMonth = em End While End Sub Public Function MonthShort(ByVal i As Integer) As String MonthShort = "" Select Case i Case 1 MonthShort = "Jan" Case 2 MonthShort = "Feb" Case 3 MonthShort = "Mar" Case 4 MonthShort = "Apr" Case 5 MonthShort = "May" Case 6 MonthShort = "Jun" Case 7 MonthShort = "Jul" Case 8 MonthShort = "Aug" Case 9 MonthShort = "Sep" Case 10 MonthShort = "Oct" Case 11 MonthShort = "Nov" Case 12 MonthShort = "Dec" End Select End Function Public Sub Add(ByVal s As String) Dim tp As New ArtBTimePeriod tp.Descr = s tp.ParseDescr() If EndMonth = -1 Then EndMonth = tp.EndMonth StartMonth = tp.StartMonth Exit Sub End If If StartMonth > tp.StartMonth Then StartMonth = tp.StartMonth If EndMonth > tp.EndMonth Then EndMonth = tp.EndMonth End Sub Public Function AddConsecutive(ByRef tp As ArtBTimePeriod) As Boolean AddConsecutive = True If EndMonth = -1 Then EndMonth = tp.EndMonth StartMonth = tp.StartMonth FillDates() Exit Function End If StartMonth = Math.Min(StartMonth, tp.StartMonth) EndMonth = Math.Max(EndMonth, tp.EndMonth) FillDates() Exit Function If StartMonth = tp.EndMonth + 1 Then StartMonth = tp.StartMonth Exit Function End If If EndMonth = tp.StartMonth - 1 Then EndMonth = tp.EndMonth Exit Function End If AddConsecutive = False End Function Public Function TotalDays() As Integer FillDates() TotalDays = CInt(1 + DateDiff(DateInterval.Day, StartDate, EndDate)) TotDays = TotalDays End Function Public Function TotalMonths() As Integer FillDates() TotalMonths = CInt(1 + DateDiff(DateInterval.Month, StartDate, EndDate)) End Function Public Function MinDaysInMonth() As Integer Dim i As Integer, y As Integer, m As Integer, d As Integer If StartMonth = -1 Or EndMonth = -1 Then MinDaysInMonth = 0 Exit Function End If MinDaysInMonth = 31 For i = StartMonth To EndMonth y = CInt(Int(i / 12)) m = (i - y * 12) + 1 d = Date.DaysInMonth(y, m) If d < MinDaysInMonth Then MinDaysInMonth = d Next End Function Public Function GetID() As Integer GetID = 0 GetID = (YY1 Mod 2000) * 1000000 GetID = GetID + MM1 * 10000 GetID = GetID + (YY2 Mod 2000) * 100 GetID = GetID + MM2 End Function Public Function SortRanking() As Double SortRanking = (YY2 Mod 2000) * 1000000 SortRanking = SortRanking + MM2 * 10000 SortRanking = SortRanking - (YY1 Mod 2000) * 100 SortRanking = SortRanking - MM1 End Function Public Sub FillFromID(ByVal ID As Integer) YY1 = CInt(Int(ID / 1000000)) MM1 = CInt(Int((ID Mod 1000000) / 10000)) YY2 = CInt(Int((ID Mod 10000) / 100)) MM2 = Int(ID Mod 100) StartMonth = YY1 * 12 + MM1 - 1 EndMonth = YY2 * 12 + MM2 - 1 End Sub Public Function AddToList(ByVal PeriodList As List(Of ArtBTimePeriod)) As Boolean AddToList = False For Each p As ArtBTimePeriod In PeriodList If p.StartMonth = StartMonth And p.EndMonth = EndMonth Then Exit Function Next PeriodList.Add(Me) AddToList = True End Function Public Sub GetFromRPStr(ByVal RPStr As String) Dim ID As Integer ID = CInt(RPStr.Substring(5, 8)) FillFromID(ID) End Sub Public Function Contains(ByRef tp As ArtBTimePeriod) As Boolean If tp.StartMonth >= StartMonth And tp.EndMonth <= EndMonth Then Return True Return False End Function Public Function OverlapMonths(ByRef tp As ArtBTimePeriod) As Integer Dim MaxSM As Integer = Math.Max(tp.StartMonth, StartMonth) Dim MinEM As Integer = Math.Min(tp.EndMonth, EndMonth) If MinEM < MaxSM Then Return 0 Return MinEM - StartMonth + 1 End Function End Class <DataContract> Public Class MVClass Private m_SERVER_DATE As Date = Today Private m_MarketViewPeriods As New List(Of ArtBTimePeriod) <DataMember()> Public Property SERVER_DATE As Date Get Return m_SERVER_DATE End Get Set(value As Date) m_SERVER_DATE = value End Set End Property <DataMember()> Public Property MarketViewPeriods As List(Of ArtBTimePeriod) Get Return m_MarketViewPeriods End Get Set(value As List(Of ArtBTimePeriod)) m_MarketViewPeriods = value End Set End Property End Class <DataContract()> Public Class ForwardsClass Private m_ROUTE_ID As Integer Private m_FIXING_DATE As Date Private m_FIXING As Double Private m_NORMFIX As Double Private m_YY1 As Integer Private m_YY2 As Integer Private m_MM1 As Integer Private m_MM2 As Integer Private m_KEY As String Private m_PERIOD As Integer Private m_REPORTDESC As String Private m_CMSROUTE_ID As String <DataMember()> Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember()> Public Property FIXING_DATE As Date Get Return m_FIXING_DATE End Get Set(value As Date) m_FIXING_DATE = value End Set End Property <DataMember()> Public Property FIXING As Double Get Return m_FIXING End Get Set(value As Double) m_FIXING = value End Set End Property <DataMember()> Public Property NORMFIX As Double Get Return m_NORMFIX End Get Set(value As Double) m_NORMFIX = value End Set End Property <DataMember()> Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property <DataMember()> Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property <DataMember()> Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property <DataMember()> Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property <DataMember()> Public Property KEY As String Get Return m_KEY End Get Set(value As String) m_KEY = value End Set End Property <DataMember()> Public Property PERIOD As Integer Get Return m_PERIOD End Get Set(value As Integer) m_PERIOD = value End Set End Property <DataMember()> Public Property REPORTDESC As String Get Return m_REPORTDESC End Get Set(value As String) m_REPORTDESC = value End Set End Property <DataMember()> Public Property CMSROUTE_ID As String Get Return m_CMSROUTE_ID End Get Set(value As String) m_CMSROUTE_ID = value End Set End Property End Class <DataContract()> Public Class SwapFixingsClass Private m_ROUTE_ID As Integer Private m_FIXING_DATE As Date Private m_FIXING As Double Private m_YY1 As Integer Private m_MM1 As Integer Private m_YY2 As Integer Private m_MM2 As Integer Public Sub New() End Sub Public Sub New(ByVal f_ROUTE_ID As Integer, ByVal f_FIXING_DATE As Date, ByVal f_FIXING As Double, ByVal f_YY1 As Integer, ByVal f_MM1 As Integer, ByVal f_YY2 As Integer, ByVal f_MM2 As Integer) m_ROUTE_ID = f_ROUTE_ID m_FIXING_DATE = f_FIXING_DATE m_FIXING = f_FIXING m_YY1 = f_YY1 m_MM1 = f_MM1 m_YY2 = f_YY2 m_MM2 = f_MM2 End Sub <DataMember()> Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember()> Public Property FIXING_DATE As Date Get Return m_FIXING_DATE End Get Set(value As Date) m_FIXING_DATE = value End Set End Property <DataMember()> Public Property FIXING As Double Get Return m_FIXING End Get Set(value As Double) m_FIXING = value End Set End Property <DataMember()> Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property <DataMember()> Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property <DataMember()> Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property <DataMember()> Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property End Class <DataContract()> Public Class SpotFixingsClass Private m_ROUTE_ID As Integer Private m_FIXING_DATE As Date Private m_FIXING As Double Private m_AVG_FIXING As Double Public Sub New() End Sub Public Sub New(ByVal f_ROUTE_ID As Integer, ByVal f_FIXING_DATE As Date, ByVal f_FIXING As Double, Optional ByVal f_AVG_FIXING As Double = 0.0#) m_ROUTE_ID = f_ROUTE_ID m_FIXING_DATE = f_FIXING_DATE m_FIXING = f_FIXING m_AVG_FIXING = f_AVG_FIXING End Sub <DataMember()> Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember()> Public Property FIXING_DATE As Date Get Return m_FIXING_DATE End Get Set(value As Date) m_FIXING_DATE = value End Set End Property <DataMember()> Public Property FIXING As Double Get Return m_FIXING End Get Set(value As Double) m_FIXING = value End Set End Property <DataMember()> Public Property AVG_FIXING As Double Get Return m_AVG_FIXING End Get Set(value As Double) m_AVG_FIXING = value End Set End Property End Class Public Class LiveRecorsdClass Private m_TRADE_ID As Integer Private m_ORDER_DATETIME As Date Private m_PRICE As Double Private m_PNC As Boolean Public Sub New() End Sub Public Sub New(ByVal _TRADE_ID As Integer, ByVal _ORDER_DATETIME As Date, ByVal _PRICE As Double, ByVal _PNC As Boolean) m_TRADE_ID = _TRADE_ID m_ORDER_DATETIME = _ORDER_DATETIME m_PRICE = _PRICE m_PNC = _PNC End Sub Public Property PNC As Boolean Get Return m_PNC End Get Set(value As Boolean) m_PNC = value End Set End Property Public Property TRADE_ID As Integer Get Return m_TRADE_ID End Get Set(value As Integer) m_TRADE_ID = value End Set End Property Public Property ORDER_DATETIME As Date Get Return m_ORDER_DATETIME End Get Set(value As Date) m_ORDER_DATETIME = value End Set End Property Public Property PRICE As Double Get Return m_PRICE End Get Set(value As Double) m_PRICE = value End Set End Property End Class #Region "WP8" <DataContract> _ Public Class WP8FFAData Private m_ROUTE_ID As Integer <DataMember> _ Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property Private m_PERIOD As String = String.Empty <DataMember> _ Public Property PERIOD As String Get Return m_PERIOD End Get Set(value As String) m_PERIOD = value End Set End Property Private m_YY1 As Integer <DataMember> _ Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property Private m_YY2 As Integer <DataMember> _ Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property Private m_MM1 As Integer <DataMember> _ Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property Private m_MM2 As Integer <DataMember> _ Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property Private m_FIXING As Decimal <DataMember> _ Public Property FIXING As Decimal Get Return m_FIXING End Get Set(value As Decimal) m_FIXING = value End Set End Property Private m_FIXING_DATE As DateTime <DataMember> _ Public Property FIXING_DATE As DateTime Get Return m_FIXING_DATE End Get Set(value As DateTime) m_FIXING_DATE = value End Set End Property Private m_LAST_TRADED As Decimal <DataMember> _ Public Property LAST_TRADED As Decimal Get Return m_LAST_TRADED End Get Set(value As Decimal) m_LAST_TRADED = value End Set End Property Private m_TRADE_ID As Integer <DataMember> _ Public Property TRADE_ID As Integer Get Return m_TRADE_ID End Get Set(value As Integer) m_TRADE_ID = value End Set End Property Private m_ORDER_DATETIME As DateTime <DataMember> _ Public Property ORDER_DATETIME As DateTime Get Return m_ORDER_DATETIME End Get Set(value As DateTime) m_ORDER_DATETIME = value End Set End Property Private m_HVOL As Decimal <DataMember> _ Public Property HVOL As Decimal Get Return m_HVOL End Get Set(value As Decimal) m_HVOL = value End Set End Property Private m_SpotAvg As Decimal <DataMember> _ Public Property SpotAvg As Decimal Get Return m_SpotAvg End Get Set(value As Decimal) m_SpotAvg = value End Set End Property Private m_PRICE_STATUS As PriceStatusEnum <DataMember> _ Public Property PRICE_STATUS As PriceStatusEnum Get Return m_PRICE_STATUS End Get Set(value As PriceStatusEnum) m_PRICE_STATUS = value End Set End Property Private m_RECORD_TYPE As RecordTypeEnum <DataMember> _ Public Property RECORD_TYPE As RecordTypeEnum Get Return m_RECORD_TYPE End Get Set(value As RecordTypeEnum) m_RECORD_TYPE = value End Set End Property Private m_BID As Decimal <DataMember> _ Public Property BID As Decimal Get Return m_BID End Get Set(value As Decimal) m_BID = value End Set End Property Private m_ASK As Decimal <DataMember> _ Public Property ASK As Decimal Get Return m_ASK End Get Set(value As Decimal) m_ASK = value End Set End Property Private m_BidSize As Integer <DataMember> _ Public Property BidSize As Integer Get Return m_BidSize End Get Set(value As Integer) m_BidSize = value End Set End Property Private m_AskSize As Integer <DataMember> _ Public Property AskSize As Integer Get Return m_AskSize End Get Set(value As Integer) m_AskSize = value End Set End Property Private m_LastSize As Integer <DataMember> _ Public Property LastSize As Integer Get Return m_LastSize End Get Set(value As Integer) m_LastSize = value End Set End Property Public ReadOnly Property NoMonths As Integer Get Return DateDiff(DateInterval.Month, DateSerial(m_YY1, m_MM1, 1), DateSerial(m_YY2, m_MM2, 1)) + 1 End Get End Property Public ReadOnly Property PctDiff As Double Get Return (m_LAST_TRADED - m_FIXING) / m_FIXING End Get End Property End Class <DataContract> _ Public Class GeneralFFDataClass Private m_ROUTES As New List(Of ROUTES) Private m_VESSEL_CLASSES As New List(Of VESSEL_CLASS) Private m_TRADE_CLASS As New TRADE_CLASSES <DataMember> _ Public Property TRADE_CLASS As TRADE_CLASSES Get Return m_TRADE_CLASS End Get Set(value As TRADE_CLASSES) m_TRADE_CLASS = value End Set End Property <DataMember> _ Public Property VESSEL_CLASSES As List(Of VESSEL_CLASS) Get Return m_VESSEL_CLASSES End Get Set(value As List(Of VESSEL_CLASS)) m_VESSEL_CLASSES = value End Set End Property <DataMember> _ Public Property ROUTES As List(Of ROUTES) Get Return m_ROUTES End Get Set(value As List(Of ROUTES)) m_ROUTES = value End Set End Property End Class <DataContract> _ Public Class SwapCurveClass Private m_ROUTE_ID As Integer Private m_PERIOD As String Private m_YY1 As Integer Private m_YY2 As Integer Private m_MM1 As Integer Private m_MM2 As Integer Private m_FIXING_DATE As Date Private m_FIXING As Double Private m_ORDER_DATETIME As Date Private m_PRICE_TRADED As Double Private m_PRICE_STATUS As PriceStatusEnum Private m_NoMonths As Integer Private m_HVOL As Double Private m_SpotAvg As Double Private m_RECORD_TYPE As RecordTypeEnum Private m_BID As Double Private m_ASK As Double Public Sub New() End Sub Public Sub New(ByVal _RECORD_TYPE As RecordTypeEnum, ByVal _ROUTE_ID As Integer, ByVal _YY1 As Integer, ByVal _MM1 As Integer, ByVal _YY2 As Integer, ByVal _MM2 As Integer, ByVal _FIXING_DATE As Date, ByVal _FIXING As Double, Optional ByVal _ORDER_DATETIME As Date = #1/1/1900#, Optional ByVal _PRICE_TRADED As Double = 0, Optional ByVal _PRICE_STATUS As PriceStatusEnum = PriceStatusEnum.Historic) m_RECORD_TYPE = _RECORD_TYPE m_ROUTE_ID = _ROUTE_ID m_YY1 = _YY1 m_YY2 = _YY2 m_MM1 = _MM1 m_MM2 = _MM2 m_FIXING_DATE = _FIXING_DATE m_FIXING = _FIXING m_ORDER_DATETIME = _ORDER_DATETIME m_PRICE_TRADED = _PRICE_TRADED m_PRICE_STATUS = _PRICE_STATUS End Sub Public ReadOnly Property NoMonths As Integer Get Return DateDiff(DateInterval.Month, DateSerial(m_YY1, m_MM1, 1), DateSerial(m_YY2, m_MM2, 1)) + 1 End Get End Property Public ReadOnly Property PctDiff As Double Get Return (m_PRICE_TRADED - m_FIXING) / m_FIXING End Get End Property <DataMember> _ Public Property PERIOD As String Get Return m_PERIOD End Get Set(value As String) m_PERIOD = value End Set End Property <DataMember> _ Public Property RECORD_TYPE As RecordTypeEnum Get Return m_RECORD_TYPE End Get Set(value As RecordTypeEnum) m_RECORD_TYPE = value End Set End Property <DataMember> _ Public Property PRICE_STATUS As PriceStatusEnum Get Return m_PRICE_STATUS End Get Set(value As PriceStatusEnum) m_PRICE_STATUS = value End Set End Property <DataMember> _ Public Property ORDER_DATETIME As Date Get Return m_ORDER_DATETIME End Get Set(value As Date) m_ORDER_DATETIME = value End Set End Property <DataMember> _ Public Property FIXING_DATE As Date Get Return m_FIXING_DATE End Get Set(value As Date) m_FIXING_DATE = value End Set End Property <DataMember> _ Public Property ROUTE_ID As Integer Get Return m_ROUTE_ID End Get Set(value As Integer) m_ROUTE_ID = value End Set End Property <DataMember> _ Public Property HVOL As Double Get Return m_HVOL End Get Set(value As Double) m_HVOL = value End Set End Property <DataMember> _ Public Property SpotAvg As Double Get Return m_SpotAvg End Get Set(value As Double) m_SpotAvg = value End Set End Property <DataMember> _ Public Property PRICE_TRADED As Double Get Return m_PRICE_TRADED End Get Set(value As Double) m_PRICE_TRADED = value End Set End Property <DataMember> _ Public Property FIXING As Double Get Return m_FIXING End Get Set(value As Double) m_FIXING = value End Set End Property <DataMember> _ Public Property YY1 As Integer Get Return m_YY1 End Get Set(value As Integer) m_YY1 = value End Set End Property <DataMember> _ Public Property YY2 As Integer Get Return m_YY2 End Get Set(value As Integer) m_YY2 = value End Set End Property <DataMember> _ Public Property MM1 As Integer Get Return m_MM1 End Get Set(value As Integer) m_MM1 = value End Set End Property <DataMember> _ Public Property MM2 As Integer Get Return m_MM2 End Get Set(value As Integer) m_MM2 = value End Set End Property <DataMember> _ Public Property BID As Double Get Return m_BID End Get Set(value As Double) m_BID = value End Set End Property <DataMember> _ Public Property ASK As Double Get Return m_ASK End Get Set(value As Double) m_ASK = value End Set End Property End Class <DataContract> _ Public Class NSwapPeriodsClass Private m_NSwapPeriod As NSwapPeriodsEnum Private m_FM As Double() Private m_M1 As Double Private m_M2 As Double Private m_M3 As Double Private m_M4 As Double Private m_M5 As Double Private m_M6 As Double Private m_M7 As Double Private m_M8 As Double Private m_M9 As Double Private m_M10 As Double Private m_M11 As Double Private m_M12 As Double Public Sub New() End Sub Public Sub New(ByVal _NSwapPeriod As NSwapPeriodsEnum) m_NSwapPeriod = _NSwapPeriod Select Case NSwapPeriod Case NSwapPeriodsEnum.Cal ReDim m_FM(11) Case NSwapPeriodsEnum.Q234 ReDim m_FM(9) Case NSwapPeriodsEnum.Q34 ReDim m_FM(5) Case NSwapPeriodsEnum.Q4 ReDim m_FM(2) End Select End Sub <DataMember> _ Public Property NSwapPeriod As NSwapPeriodsEnum Get Return m_NSwapPeriod End Get Set(value As NSwapPeriodsEnum) m_NSwapPeriod = value End Set End Property <DataMember> _ Public Property FM As Double() Get Return m_FM End Get Set(value As Double()) m_FM = value End Set End Property <DataMember> _ Public Property M1 As Double Get Return m_M1 End Get Set(value As Double) m_M1 = value End Set End Property <DataMember> _ Public Property M2 As Double Get Return m_M2 End Get Set(value As Double) m_M2 = value End Set End Property <DataMember> _ Public Property M3 As Double Get Return m_M3 End Get Set(value As Double) m_M3 = value End Set End Property <DataMember> _ Public Property M4 As Double Get Return m_M4 End Get Set(value As Double) m_M4 = value End Set End Property <DataMember> _ Public Property M5 As Double Get Return m_M5 End Get Set(value As Double) m_M5 = value End Set End Property <DataMember> _ Public Property M6 As Double Get Return m_M6 End Get Set(value As Double) m_M6 = value End Set End Property <DataMember> _ Public Property M7 As Double Get Return m_M7 End Get Set(value As Double) m_M7 = value End Set End Property <DataMember> _ Public Property M8 As Double Get Return m_M8 End Get Set(value As Double) m_M8 = value End Set End Property <DataMember> _ Public Property M9 As Double Get Return m_M9 End Get Set(value As Double) m_M9 = value End Set End Property <DataMember> _ Public Property M10 As Double Get Return m_M10 End Get Set(value As Double) m_M10 = value End Set End Property <DataMember> _ Public Property M11 As Double Get Return m_M11 End Get Set(value As Double) m_M11 = value End Set End Property <DataMember> _ Public Property M12 As Double Get Return m_M12 End Get Set(value As Double) m_M12 = value End Set End Property End Class <DataContract(Name:="PriceStatusEnum")> _ Public Enum PriceStatusEnum <EnumMember> Trade = 0 <EnumMember> Level = 1 <EnumMember> Historic = 2 End Enum <DataContract(Name:="RecordTypeEnum")> _ Public Enum RecordTypeEnum <EnumMember> Swap = 0 <EnumMember> RatioSpread = 1 <EnumMember> CalendarSpread = 2 <EnumMember> PriceSpread = 3 <EnumMember> MarketSpread = 4 <EnumMember> Spot = 99 <EnumMember> Vol = 100 End Enum <DataContract(Name:="NSwapPeriodsEnum")> _ Public Enum NSwapPeriodsEnum <EnumMember> Cal = 1 <EnumMember> Q234 = 4 <EnumMember> Q34 = 7 <EnumMember> Q4 = 10 End Enum #End Region #Region "Enumerations" <DataContract(Name:="OptCalcServiceEnum")> _ Public Enum OptCalcServiceEnum <EnumMember> SpotsUploaded <EnumMember> ForwardsUploaded <EnumMember> RefreshAll <EnumMember> Success <EnumMember> ServiceError End Enum <DataContract(Name:="VolRecordTypeEnum")> _ Public Enum VolRecordTypeEnum <EnumMember> spot <EnumMember> nspot <EnumMember> swap <EnumMember> live <EnumMember> level <EnumMember> all <EnumMember> mvperiods <EnumMember> decimals End Enum <DataContract(Name:="FPStatusEnum")> _ Public Enum FPStatusEnum <EnumMember> InvalidLicenseKey <EnumMember> ValidLicenseKey <EnumMember> ExistingClientAllOK <EnumMember> NewClient <EnumMember> NewClientFPTrialCreated <EnumMember> ExistingFPTrialLicenseExpired <EnumMember> ExistingFPLiveLicenseExpired <EnumMember> ExistingFPTrialRenewed <EnumMember> ExistingFPLiveRenewed <EnumMember> ExistingFPLiveMaxLicensesError <EnumMember> UserDataAmmendSuccess <EnumMember> UserDataAmmendError <EnumMember> LiveLicenseNewFingerPrintAdded <EnumMember> DemoLicenseNewFingerPrintAdded <EnumMember> LiveLicenseExistingFingerPrintAdded <EnumMember> DemoLicenseExistingFingerPrintAdded <EnumMember> LiveLicenseHasExpiredNoFingerPrintAdded <EnumMember> DemoLicenseHasExpiredNoFingerPrintAdded <EnumMember> DemoFingerPrintHasExpired <EnumMember> UserWantsToRegisterPC <EnumMember> DBError <EnumMember> OFError <EnumMember> NoInternetConnection <EnumMember> InternetConnectionOK <EnumMember> ServiceOK <EnumMember> ServiceError End Enum <DataContract(Name:="OrderTypes")> _ Public Enum OrderTypesEnum <EnumMember> FFA = 0 <EnumMember> RatioSpread <EnumMember> CalendarSpread <EnumMember> PriceSpread <EnumMember> MarketSpread End Enum <DataContract(Name:="RouteAvgTypeEnum")> _ Public Enum RouteAvgTypeEnum <EnumMember> WholeMonth = 0 <EnumMember> LastSevenDays = 7 <EnumMember> LastTenDays = 10 End Enum <DataContract()> Public Class CompositeType <DataMember()> Public Property BoolValue() As Boolean <DataMember()> Public Property StringValue() As String End Class #End Region End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. Option Strict On Option Explicit On Imports System.Collections.ObjectModel Imports System.Reflection Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Namespace Microsoft.VisualBasic.ApplicationServices ''' <summary> ''' A class that contains the information about an Application. This information can be ''' specified using the assembly attributes (contained in AssemblyInfo.vb file in case of ''' a VB project in Visual Studio .NET). ''' </summary> ''' <remarks>This class is based on the FileVersionInfo class of the framework, but ''' reduced to a number of relevant properties.</remarks> Public Class AssemblyInfo ''' <summary> ''' Creates an AssemblyInfo from an assembly ''' </summary> ''' <param name="CurrentAssembly">The assembly for which we want to obtain the information.</param> Public Sub New(currentAssembly As Assembly) If currentAssembly Is Nothing Then Throw GetArgumentNullException("CurrentAssembly") End If _assembly = currentAssembly End Sub ''' <summary> ''' Gets the description associated with the assembly. ''' </summary> ''' <value>A String containing the AssemblyDescriptionAttribute associated with the assembly.</value> ''' <exception cref="InvalidOperationException">if the AssemblyDescriptionAttribute is not defined.</exception> Public ReadOnly Property Description() As String Get If _description Is Nothing Then Dim Attribute As AssemblyDescriptionAttribute = CType(GetAttribute(GetType(AssemblyDescriptionAttribute)), AssemblyDescriptionAttribute) If Attribute Is Nothing Then _description = "" Else _description = Attribute.Description End If End If Return _description End Get End Property ''' <summary> ''' Gets the company name associated with the assembly. ''' </summary> ''' <value>A String containing the AssemblyCompanyAttribute associated with the assembly.</value> ''' <exception cref="InvalidOperationException">if the AssemblyCompanyAttribute is not defined.</exception> Public ReadOnly Property CompanyName() As String Get If _companyName Is Nothing Then Dim Attribute As AssemblyCompanyAttribute = CType(GetAttribute(GetType(AssemblyCompanyAttribute)), AssemblyCompanyAttribute) If Attribute Is Nothing Then _companyName = "" Else _companyName = Attribute.Company End If End If Return _companyName End Get End Property ''' <summary> ''' Gets the title associated with the assembly. ''' </summary> ''' <value>A String containing the AssemblyTitleAttribute associated with the assembly.</value> ''' <exception cref="InvalidOperationException">if the AssemblyTitleAttribute is not defined.</exception> Public ReadOnly Property Title() As String Get If _title Is Nothing Then Dim Attribute As AssemblyTitleAttribute = CType(GetAttribute(GetType(AssemblyTitleAttribute)), AssemblyTitleAttribute) If Attribute Is Nothing Then _title = "" Else _title = Attribute.Title End If End If Return _title End Get End Property ''' <summary> ''' Gets the copyright notices associated with the assembly. ''' </summary> ''' <value>A String containing the AssemblyCopyrightAttribute associated with the assembly.</value> ''' <exception cref="InvalidOperationException">if the AssemblyCopyrightAttribute is not defined.</exception> Public ReadOnly Property Copyright() As String Get If _copyright Is Nothing Then Dim Attribute As AssemblyCopyrightAttribute = CType(GetAttribute(GetType(AssemblyCopyrightAttribute)), AssemblyCopyrightAttribute) If Attribute Is Nothing Then _copyright = "" Else _copyright = Attribute.Copyright End If End If Return _copyright End Get End Property ''' <summary> ''' Gets the trademark notices associated with the assembly. ''' </summary> ''' <value>A String containing the AssemblyTrademarkAttribute associated with the assembly.</value> ''' <exception cref="InvalidOperationException">if the AssemblyTrademarkAttribute is not defined.</exception> Public ReadOnly Property Trademark() As String Get If _trademark Is Nothing Then Dim Attribute As AssemblyTrademarkAttribute = CType(GetAttribute(GetType(AssemblyTrademarkAttribute)), AssemblyTrademarkAttribute) If Attribute Is Nothing Then _trademark = "" Else _trademark = Attribute.Trademark End If End If Return _trademark End Get End Property ''' <summary> ''' Gets the product name associated with the assembly. ''' </summary> ''' <value>A String containing the AssemblyProductAttribute associated with the assembly.</value> ''' <exception cref="InvalidOperationException">if the AssemblyProductAttribute is not defined.</exception> Public ReadOnly Property ProductName() As String Get If _productName Is Nothing Then Dim Attribute As AssemblyProductAttribute = CType(GetAttribute(GetType(AssemblyProductAttribute)), AssemblyProductAttribute) If Attribute Is Nothing Then _productName = "" Else _productName = Attribute.Product End If End If Return _productName End Get End Property ''' <summary> ''' Gets the version number of the assembly. ''' </summary> ''' <value>A System.Version class containing the version number of the assembly</value> ''' <remarks>Cannot use AssemblyVersionAttribute since it always return Nothing.</remarks> Public ReadOnly Property Version() As Version Get Return _assembly.GetName().Version End Get End Property ''' <summary> ''' Gets the name of the file containing the manifest (usually the .exe file). ''' </summary> ''' <value>A String containing the file name.</value> Public ReadOnly Property AssemblyName() As String Get Return _assembly.GetName.Name End Get End Property ''' <summary> ''' Gets the directory where the assembly lives. ''' </summary> Public ReadOnly Property DirectoryPath() As String Get Return IO.Path.GetDirectoryName(_assembly.Location) End Get End Property ''' <summary> ''' Returns the names of all assemblies loaded by the current application. ''' </summary> ''' <value>A ReadOnlyCollection(Of Assembly) containing all the loaded assemblies.</value> ''' <exception cref="AppDomainUnloadedException">attempt on an unloaded application domain.</exception> Public ReadOnly Property LoadedAssemblies() As ReadOnlyCollection(Of Assembly) Get Dim Result As New Collection(Of Assembly) For Each Assembly As Assembly In AppDomain.CurrentDomain.GetAssemblies() Result.Add(Assembly) Next Return New ReadOnlyCollection(Of Assembly)(Result) End Get End Property ''' <summary> ''' Returns the current stack trace information. ''' </summary> ''' <value>A string containing stack trace information. Value can be String.Empty.</value> ''' <exception cref="ArgumentOutOfRangeException">The requested stack trace information is out of range.</exception> Public ReadOnly Property StackTrace() As String Get Return Environment.StackTrace End Get End Property ''' <summary> ''' Gets the amount of physical memory mapped to the process context. ''' </summary> ''' <value> ''' A 64-bit signed integer containing the size of physical memory mapped to the process context, in bytes. ''' </value> Public ReadOnly Property WorkingSet() As Long Get Return Environment.WorkingSet End Get End Property ''' <summary> ''' Gets an attribute from the assembly and throw exception if the attribute does not exist. ''' </summary> ''' <param name="AttributeType">The type of the required attribute.</param> ''' <returns>The attribute with the given type gotten from the assembly, or Nothing.</returns> Private Function GetAttribute(AttributeType As Type) As Object Debug.Assert(_assembly IsNot Nothing, "Null m_Assembly") Dim Attributes() As Object = _assembly.GetCustomAttributes(AttributeType, inherit:=True) If Attributes.Length = 0 Then Return Nothing Else Return Attributes(0) End If End Function ' Private fields. Private ReadOnly _assembly As Assembly ' The assembly with the information. ' Since these properties will not change during runtime, they're cached. ' "" is not Nothing so use Nothing to mark an un-accessed property. Private _description As String ' Cache the assembly's description. Private _title As String ' Cache the assembly's title. Private _productName As String ' Cache the assembly's product name. Private _companyName As String ' Cache the assembly's company name. Private _trademark As String ' Cache the assembly's trademark. Private _copyright As String ' Cache the assembly's copyright. End Class End Namespace
Imports BVSoftware.BVC5.Core Imports System.Linq Imports System.Collections.ObjectModel Partial Class BVAdmin_Orders_EditOrder Inherits BaseAdminPage Private _InputsAndModifiersLoaded As Boolean = False Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Dim val As Decimal = 0D PaymentAuthorizedField.Text = val.ToString("c") PaymentChargedField.Text = val.ToString("c") PaymentRefundedField.Text = val.ToString("c") PaymentDueField.Text = val.ToString("c") End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.UserPicker1.MessageBox = MessageBox1 InitializeAddresses() If Request.QueryString("id") IsNot Nothing Then Me.BvinField.Value = Request.QueryString("id") Else ' Show Error End If Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If o IsNot Nothing Then ShippingAddressBook.UserID = o.UserID BillingAddressBook.UserID = o.UserID End If If Not Page.IsPostBack Then LoadOrder() LoadShippingMethodsForOrder(o) LoadSalesPeople(o) End If If EditLineBvin.Value <> String.Empty Then EditLineVariantsDisplay.Initialize(False) EditLineKitComponentsDisplay.Initialize(EditLineBvin.Value) End If If Me.AddProductSkuHiddenField.Value <> String.Empty Then VariantsDisplay1.Initialize(False) Dim p As Catalog.Product = Catalog.InternalProduct.FindByBvin(Me.AddProductSkuHiddenField.Value) AddNewKitComponentsDisplay.Initialize(p) End If If Page.IsPostBack Then If Not _InputsAndModifiersLoaded Then ViewUtilities.GetInputsAndModifiersForAdminLineItemDescription(Me.Page, ItemsGridView) End If End If ViewUtilities.DisplayKitInLineItem(Me.Page, ItemsGridView) End Sub Protected Sub ItemsGridView_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles ItemsGridView.DataBound ViewUtilities.GetInputsAndModifiersForAdminLineItemDescription(Me.Page, ItemsGridView) ViewUtilities.DisplayKitInLineItem(Me.Page, ItemsGridView) _InputsAndModifiersLoaded = True End Sub Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.PageTitle = "Edit Order" Me.CurrentTab = AdminTabType.Orders ValidateCurrentUserHasPermission(Membership.SystemPermissions.OrdersEdit) End Sub #Region " Loading Methods " Private Sub InitializeAddresses() Me.ShippingAddressEditor.RequireCompany = WebAppSettings.ShipAddressRequireCompany Me.ShippingAddressEditor.RequireFax = WebAppSettings.ShipAddressRequireFax Me.ShippingAddressEditor.RequireFirstName = WebAppSettings.ShipAddressRequireFirstName Me.ShippingAddressEditor.RequireLastName = WebAppSettings.ShipAddressRequireLastName Me.ShippingAddressEditor.RequirePhone = WebAppSettings.ShipAddressRequirePhone Me.ShippingAddressEditor.RequireWebSiteURL = WebAppSettings.ShipAddressRequireWebSiteURL Me.ShippingAddressEditor.ShowCompanyName = WebAppSettings.ShipAddressShowCompany Me.ShippingAddressEditor.ShowFaxNumber = WebAppSettings.ShipAddressShowFax Me.ShippingAddressEditor.ShowMiddleInitial = WebAppSettings.ShipAddressShowMiddleInitial Me.ShippingAddressEditor.ShowPhoneNumber = WebAppSettings.ShipAddressShowPhone Me.ShippingAddressEditor.ShowWebSiteURL = WebAppSettings.ShipAddressShowWebSiteURL Me.ShippingAddressEditor.ShowNickName = False Me.ShippingAddressEditor.ShowCounty = True Me.BillingAddressEditor.RequireCompany = WebAppSettings.BillAddressRequireCompany Me.BillingAddressEditor.RequireFax = WebAppSettings.BillAddressRequireFax Me.BillingAddressEditor.RequireFirstName = WebAppSettings.BillAddressRequireFirstName Me.BillingAddressEditor.RequireLastName = WebAppSettings.BillAddressRequireLastName Me.BillingAddressEditor.RequirePhone = WebAppSettings.BillAddressRequirePhone Me.BillingAddressEditor.RequireWebSiteURL = WebAppSettings.BillAddressRequireWebSiteURL Me.BillingAddressEditor.ShowCompanyName = WebAppSettings.BillAddressShowCompany Me.BillingAddressEditor.ShowFaxNumber = WebAppSettings.BillAddressShowFax Me.BillingAddressEditor.ShowMiddleInitial = WebAppSettings.BillAddressShowMiddleInitial Me.BillingAddressEditor.ShowPhoneNumber = WebAppSettings.BillAddressShowPhone Me.BillingAddressEditor.ShowWebSiteURL = WebAppSettings.BillAddressShowWebSiteUrl Me.BillingAddressEditor.ShowNickName = False Me.BillingAddressEditor.ShowCounty = True End Sub Private Sub LoadOrder() Dim bvin As String = Me.BvinField.Value.ToString Dim o As Orders.Order = Orders.Order.FindByBvin(bvin) 'o.RecalculateProductPrices() 'needed to apply modifier options to newly added line item of placed order 'Orders.Order.Update(o) If o IsNot Nothing Then If o.Bvin <> String.Empty Then TaxExemptField.Checked = o.CustomPropertyExists("Develisys", "TaxExempt") CalculateTax(o) Orders.Order.Update(o) PopulateFromOrder(o) End If End If LoadShippingMethodsForOrder(o) End Sub Private Sub PopulateFromOrder(ByVal o As Orders.Order) ' Header Me.OrderNumberField.Text = o.OrderNumber ' Status Me.StatusField.Text = o.FullOrderStatusDescription Me.lblCurrentStatus.Text = o.StatusName ' Billing Me.BillingAddressEditor.LoadFromAddress(o.BillingAddress) 'Email Me.UserEmailField.Text = o.UserEmail If o.UserID <> String.Empty Then If o.User IsNot Nothing Then If String.IsNullOrEmpty(o.UserEmail) Then Me.UserEmailField.Text = o.User.Email End If Me.UserPicker1.UserName = o.User.UserName Me.UserIdField.Value = o.UserID ShippingAddressBook.UserID = o.UserID BillingAddressBook.UserID = o.UserID ShippingAddressBook.BindAddresses() BillingAddressBook.BindAddresses() End If End If ' Shipping Me.ShippingAddressEditor.LoadFromAddress(o.ShippingAddress) ' Payment Dim paySummary As Orders.OrderPaymentSummary = o.PaymentSummary Me.lblPaymentSummary.Text = paySummary.PaymentsSummary Me.PaymentAuthorizedField.Text = String.Format("{0:C}", paySummary.AmountAuthorized) Me.PaymentChargedField.Text = String.Format("{0:C}", paySummary.AmountCharged) Me.PaymentDueField.Text = String.Format("{0:C}", paySummary.AmountDue) Me.PaymentRefundedField.Text = String.Format("{0:C}", paySummary.AmountRefunded) 'Items Me.ItemsGridView.DataSource = o.Items Me.ItemsGridView.DataBind() ' Instructions Me.InstructionsField.Text = o.Instructions ' Totals Me.SubTotalField.Text = String.Format("{0:c}", o.SubTotal) Me.OrderDiscountsField.Text = String.Format("{0:c}", o.OrderDiscounts) Me.ShippingTotalTextBox.Text = String.Format("{0:c}", o.ShippingTotal) 'Me.lblShippingDescription.Text = o.ShippingMethodDisplayName Me.ShippingDiscountsField.Text = String.Format("{0:c}", o.ShippingDiscounts) Me.TaxTotalField.Text = String.Format("{0:c}", o.TaxTotal) Me.HandlingTotalField.Text = String.Format("{0:c}", o.HandlingTotal) Me.GrandTotalField.Text = String.Format("{0:c}", o.GrandTotal) ' Adjustments Field If o.CustomPropertyExists("bvsoftware", "postorderadjustment") Then Dim adjustment As Decimal = 0D Dim a As String = o.CustomPropertyGet("bvsoftware", "postorderadjustment") Dim amount As Decimal = 0D Decimal.TryParse(a, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, amount) Me.OrderDiscountAdjustments.Text = String.Format("{0:c}", amount) Else Me.OrderDiscountAdjustments.Text = String.Format("{0:c}", 0D) End If ' Coupons Me.lstCoupons.DataSource = o.Coupons Me.lstCoupons.DataBind() End Sub Protected Sub ItemsGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles ItemsGridView.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then Dim lineItem As Orders.LineItem = CType(e.Row.DataItem, Orders.LineItem) If lineItem IsNot Nothing Then Dim SKUField As Label = e.Row.FindControl("SKUField") If SKUField IsNot Nothing Then SKUField.Text = lineItem.ProductSku End If Dim description As Label = e.Row.FindControl("DescriptionField") If description IsNot Nothing Then description.Text = lineItem.ProductName If (lineItem.ProductShortDescription.Trim().Length > 0) Then description.Text += "<br />" & lineItem.ProductShortDescription End If End If 'Only show the button if this product has variations or kit selections Dim btnEdit As ImageButton = e.Row.FindControl("btnEdit") Dim product As Catalog.Product = Catalog.InternalProduct.FindByBvin(lineItem.ProductId) 'we need to load the full object to check for variants If product IsNot Nothing AndAlso Not String.IsNullOrEmpty(product.ParentId) Then product = Catalog.InternalProduct.FindByBvin(product.ParentId) End If Dim kitHasOptions As Boolean = False If product IsNot Nothing AndAlso product.IsKit Then Dim kc As Collection(Of Catalog.KitComponent) = Catalog.KitComponent.FindByGroupId(product.Groups(0).Bvin) For Each component As Catalog.KitComponent In kc If component.ComponentType <> Catalog.KitComponentType.IncludedHidden AndAlso component.ComponentType <> Catalog.KitComponentType.IncludedShown Then kitHasOptions = True Exit For End If Next End If If (product IsNot Nothing AndAlso product.ChoicesAndInputs.Count > 0) OrElse kitHasOptions Then btnEdit.Visible = True Else btnEdit.Visible = False End If End If End If End Sub #End Region #Region " Menu Buttons " Protected Sub btnPreviousStatus_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnPreviousStatus.Click Dim o As Orders.Order = Orders.Order.FindByBvin(Request.QueryString("id")) If o IsNot Nothing Then o.MoveToPreviousStatus() SaveOrder(False, False) LoadOrder() End If End Sub Protected Sub btnNextStatus_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNextStatus.Click Dim o As Orders.Order = Orders.Order.FindByBvin(Request.QueryString("id")) If o IsNot Nothing Then o.MoveToNextStatus() SaveOrder(False, False) LoadOrder() End If End Sub #End Region Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnDelete.Click Dim success As Boolean = False Dim o As Orders.Order = Orders.Order.FindByBvin(Request.QueryString("id")) Select Case o.ShippingStatus Case Orders.OrderShippingStatus.FullyShipped success = Orders.Order.Delete(o.Bvin) Case Orders.OrderShippingStatus.NonShipping success = Orders.Order.Delete(o.Bvin) Case Orders.OrderShippingStatus.PartiallyShipped Me.MessageBox1.ShowWarning("Partially shipped orders can't be deleted. Either unship or ship all items before deleting.") Case Orders.OrderShippingStatus.Unknown success = Orders.Order.DeleteWithInventoryReturn(o.Bvin) Case Orders.OrderShippingStatus.Unshipped success = Orders.Order.DeleteWithInventoryReturn(o.Bvin) End Select If success Then Response.Redirect("~/BVAdmin/Orders/Default.aspx") End If End Sub Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCancel.Click Response.Redirect("ViewOrder.aspx?id=" & Me.BvinField.Value) End Sub #Region " Saving " Protected Sub btnSaveChanges_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSaveChanges.Click Me.MessageBox1.ClearMessage() Dim saveResult As BVOperationResult = SaveOrder(False, True) If saveResult.Success Then RunOrderEditedWorkflow(saveResult) End If LoadOrder() End Sub Private Sub RunOrderEditedWorkflow(ByVal saveResult As BVOperationResult) Dim c As New BusinessRules.OrderTaskContext() c.UserId = SessionManager.GetCurrentUserId() c.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If Not BusinessRules.Workflow.RunByBvin(c, WebAppSettings.WorkflowIdOrderEdited) Then For Each msg As BusinessRules.WorkflowMessage In c.Errors EventLog.LogEvent("Order Edited Workflow", msg.Description, Metrics.EventLogSeverity.Error) Next If Not String.IsNullOrEmpty(saveResult.Message) Then Me.MessageBox1.ShowError(saveResult.Message & " Error Occurred. Please see event log.") Else Me.MessageBox1.ShowError("Error Occurred. Please see event log.") End If Else If Not String.IsNullOrEmpty(saveResult.Message) Then Me.MessageBox1.ShowError(saveResult.Message) Else Me.MessageBox1.ShowOk("Changes Saved") End If End If End Sub Private Function SaveOrder(ByVal forceOfferCalculations As Boolean, ByVal requireValidOptions As Boolean) As BVOperationResult Dim result As New BVOperationResult(False, "") Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If o Is Nothing Then result.Success = False result.Message = "Unable to reload order." MessageBox1.ShowError(result.Message) Return result End If Dim validateResult As BVOperationResult = ValidateOptions(o) If Not validateResult.Success Then Me.MessageBox1.ShowError(validateResult.Message) End If If validateResult.Success OrElse Not requireValidOptions Then TagOrderWithUser(o) o.UserEmail = Me.UserEmailField.Text o.Instructions = Me.InstructionsField.Text.Trim() o.SalesPersonId = Me.ddlSalesPerson.SelectedValue o.BillingAddress = Me.BillingAddressEditor.GetAsAddress o.SetShippingAddress(Me.ShippingAddressEditor.GetAsAddress) Dim modifyResult As BVOperationResult = ModifyQuantities(o) If Not modifyResult.Success Then result.Message = modifyResult.Message End If ' Apply Adjustments Dim adjustmentAmount As Decimal = 0D Decimal.TryParse(Me.OrderDiscountAdjustments.Text, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, adjustmentAmount) o.CustomPropertySet("bvsoftware", "postorderadjustment", adjustmentAmount) ' Shipping Changes If Me.ShippingRatesList.Items.Count > 0 Then Dim r As Shipping.ShippingRate = FindSelectedRate(Me.ShippingRatesList.SelectedValue, o) o.ApplyShippingRate(r) Dim shippingAmount As Decimal = 0D If Decimal.TryParse(Me.ShippingTotalTextBox.Text, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, shippingAmount) Then o.ShippingTotal = shippingAmount End If End If If forceOfferCalculations Then o.RecalculatePlacedOrder() Else CalculateTax(o) End If result.Success = Orders.Order.Update(o) Else result = validateResult End If ' If we're returning validateResult, there's no need to show this again If Not result.Success AndAlso Not result Is validateResult Then MessageBox1.ShowError(result.Message) End If Return result End Function Private Function ModifyQuantities(ByVal o As Orders.Order) As BVOperationResult Dim result As New BVOperationResult(True, "") For i As Integer = 0 To Me.ItemsGridView.Rows.Count - 1 If ItemsGridView.Rows(i).RowType = DataControlRowType.DataRow Then Dim qty As TextBox = ItemsGridView.Rows(i).FindControl("QtyField") If qty IsNot Nothing Then Dim bvin As String = CType(ItemsGridView.DataKeys(ItemsGridView.Rows(i).RowIndex).Value, String) Dim val As String = o.UpdateItemQuantity(bvin, qty.Text.Trim).Message If val <> String.Empty Then result.Success = False result.Message = val End If End If Dim price As TextBox = ItemsGridView.Rows(i).FindControl("PriceField") If price IsNot Nothing Then If Decimal.TryParse(price.Text, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, Nothing) Then Dim bvin As String = CType(ItemsGridView.DataKeys(ItemsGridView.Rows(i).RowIndex).Value, String) Dim val As String = o.SetItemAdminPrice(bvin, Decimal.Parse(price.Text, System.Globalization.NumberStyles.Currency)).Message If val <> String.Empty Then MessageBox1.ShowError(val) End If End If End If End If Next Return result End Function #End Region #Region " User " Protected Sub UserPicker1_UserSelected(ByVal args As BVSoftware.Bvc5.Core.Controls.UserSelectedEventArgs) Handles UserPicker1.UserSelected Me.UserEmailField.Text = args.UserAccount.Email ShippingAddressBook.UserID = args.UserAccount.Bvin BillingAddressBook.UserID = args.UserAccount.Bvin ShippingAddressBook.BindAddresses() BillingAddressBook.BindAddresses() RecalculateProductPrices_Click(Nothing, Nothing) ' needed to recalculate product prices End Sub Private Sub TagOrderWithUser(ByVal o As Orders.Order) If Me.UserPicker1.UserName.Trim = String.Empty Then o.UserID = String.Empty Else Dim u As Membership.UserAccount = Membership.UserAccount.FindByUserName(UserPicker1.UserName) If u IsNot Nothing Then If u.Bvin <> String.Empty Then Me.UserIdField.Value = u.Bvin o.UserID = u.Bvin Me.BillingAddressEditor.GetAsAddress.CopyTo(u.BillingAddress) Me.ShippingAddressEditor.GetAsAddress.CopyTo(u.ShippingAddress) Membership.UserAccount.Update(u) End If End If End If End Sub Protected Sub AddressSelected(ByVal addressType As String, ByVal address As Contacts.Address) Handles ShippingAddressBook.AddressSelected, BillingAddressBook.AddressSelected If String.Compare(addressType, "Billing", True) = 0 Then BillingAddressEditor.LoadFromAddress(address) ElseIf String.Compare(addressType, "Shipping", True) = 0 Then ShippingAddressEditor.LoadFromAddress(address) End If SaveOrder(False, False) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) LoadShippingMethodsForOrder(o) End Sub #End Region #Region " Coupons " Protected Sub btnDeleteCoupon_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnDeleteCoupon.Click SaveOrder(False, False) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If o IsNot Nothing Then For Each li As ListItem In Me.lstCoupons.Items If li.Selected = True Then o.RemoveCouponCode(li.Text, True) End If Next End If LoadOrder() End Sub Protected Sub btnAddCoupon_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAddCoupon.Click SaveOrder(False, False) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If o IsNot Nothing Then Dim result As BVOperationResult = o.AddCouponCode(Me.CouponField.Text.Trim.ToUpper, True, True) If result.Success = False Then Me.MessageBox1.ShowWarning(result.Message) End If End If LoadOrder() End Sub #End Region #Region " Shipping Changes " Private Sub LoadShippingMethodsForOrder(ByVal o As Orders.Order) ' Shipping Methods Me.ShippingRatesList.Items.Clear() If o.HasShippingItems = False Then Me.ShippingRatesList.Items.Add(New ListItem("No Shipping Required", "NOSHIPPING")) Else Dim Rates As Utilities.SortableCollection(Of Shipping.ShippingRate) Rates = o.FindAvailableShippingRates() SessionManager.LastEditorShippingRates = Rates Me.ShippingRatesList.AppendDataBoundItems = True Me.ShippingRatesList.Items.Add(New ListItem("-Select a shipping method-", String.Empty)) Me.ShippingRatesList.DataTextField = "RateAndNameForDisplayNoDiscounts" Me.ShippingRatesList.DataValueField = "UniqueKey" Me.ShippingRatesList.DataSource = Rates Me.ShippingRatesList.DataBind() End If ' Set Current Shipping Dim currentKey As String = o.ShippingMethodUniqueKey If Me.ShippingRatesList.Items.FindByValue(currentKey) IsNot Nothing Then Me.ShippingRatesList.ClearSelection() Me.ShippingRatesList.Items.FindByValue(currentKey).Selected = True End If End Sub Private Function FindSelectedRate(ByVal uniqueKey As String, ByVal o As Orders.Order) As Shipping.ShippingRate Dim result As Shipping.ShippingRate = Nothing If o.HasShippingItems = False Then result = New Shipping.ShippingRate result.DisplayName = "No Shipping Required" result.ProviderId = "NOSHIPPING" result.ProviderServiceCode = "NOSHIPPING" result.Rate = 0D result.ShippingMethodId = "NOSHIPPING" result.UniqueKey = "NOSHIPPING" Else Dim rates As Utilities.SortableCollection(Of Shipping.ShippingRate) = SessionManager.LastEditorShippingRates If (rates Is Nothing) OrElse (rates.Count < 1) Then rates = o.FindAvailableShippingRates() End If For Each r As Shipping.ShippingRate In rates If r.UniqueKey = uniqueKey Then result = r Exit For End If Next End If Return result End Function #End Region #Region " Add Product Form " Protected Sub btnBrowseProducts_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBrowseProducts.Click Me.MessageBox1.ClearMessage() Me.pnlProductPicker.Visible = Not Me.pnlProductPicker.Visible If Me.NewSkuField.Text.Trim.Length > 0 Then If Me.pnlProductPicker.Visible = True Then Me.ProductPicker1.Keyword = Me.NewSkuField.Text Me.ProductPicker1.LoadSearch() End If End If End Sub Protected Sub btnProductPickerCancel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnProductPickerCancel.Click Me.MessageBox1.ClearMessage() Me.pnlProductPicker.Visible = False End Sub Protected Sub btnProductPickerOkay_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnProductPickerOkay.Click Me.MessageBox1.ClearMessage() If Me.ProductPicker1.SelectedProducts.Count > 0 Then Dim p As Catalog.Product = Catalog.InternalProduct.FindByBvin(Me.ProductPicker1.SelectedProducts(0)) If p IsNot Nothing Then Me.NewSkuField.Text = p.Sku End If AddProductBySku() Me.pnlProductPicker.Visible = False Else Me.MessageBox1.ShowWarning("Please select a product first.") End If End Sub Private Sub AddProductBySku() Me.MessageBox1.ClearMessage() Me.pnlProductChoices.Visible = False If Me.NewSkuField.Text.Trim.Length < 1 Then Me.MessageBox1.ShowWarning("Please enter a sku first.") Else Dim p As Catalog.Product = Catalog.InternalProduct.FindBySku(Me.NewSkuField.Text.Trim) If p IsNot Nothing Then ' Accept Child Skus and switch to parent automatically If p.ParentId.Trim().Length > 0 Then p = Catalog.InternalProduct.FindByBvin(p.ParentId) End If If (p.Sku = String.Empty) OrElse (p.Saved = False) Then Me.MessageBox1.ShowWarning("That product could not be located. Please check SKU.") Else If p.ChoicesAndInputs.Count > 0 Then Me.pnlProductChoices.Visible = True Me.AddProductSkuHiddenField.Value = p.Bvin Me.VariantsDisplay1.BaseProduct = p Me.AddLineVariantsDisplayContainer.Visible = True Me.AddNewKitComponentsDisplay.Initialize(p) 'We are re-initializing the kit display so that it will disappear as this product is not a kit Else 'If ValidateInventory(p, Me.NewProductQuantity.Text.Trim) Then Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If p.IsKit Then 'Determine if there are any options for this kit Dim kc As Collection(Of Catalog.KitComponent) = Catalog.KitComponent.FindByGroupId(p.Groups(0).Bvin) Dim hasOptions As Boolean = False For Each component As Catalog.KitComponent In kc If component.ComponentType <> Catalog.KitComponentType.IncludedHidden AndAlso component.ComponentType <> Catalog.KitComponentType.IncludedShown Then hasOptions = True Exit For End If Next If hasOptions Then 'Kit has options, so allow user to select options before adding it Me.pnlProductChoices.Visible = True Me.AddProductSkuHiddenField.Value = p.Bvin Me.AddNewKitComponentsDisplay.Initialize(p) 'Hide variants display container (we don't have any modifiers/options/choices) Me.AddLineVariantsDisplayContainer.Visible = False Else 'Kit does not have options; add to cart immediately Dim li As New Orders.LineItem() li.ProductId = p.Bvin li.Quantity = Me.NewProductQuantity.Text.Trim li.KitSelections = Services.KitService.GetKitDefaultSelections(p) li.BasePrice = p.GetCurrentPrice(o.UserID, 0, li) Try If o.AddItem(li) = True Then Me.BvinField.Value = o.Bvin LoadOrder() Me.MessageBox1.ShowOk("Product Added!") NewSkuField.Text = String.Empty Else Me.MessageBox1.ShowError("Kit was not added correctly. Unknown Error") End If Catch ex As Exception Me.MessageBox1.ShowError("Kit was not added correctly. Error: " + ex.ToString()) End Try End If Else If o.AddItem(p.Bvin, CDec(Me.NewProductQuantity.Text.Trim)) = True Then Me.BvinField.Value = o.Bvin LoadOrder() Me.MessageBox1.ShowOk("Product Added!") NewSkuField.Text = String.Empty Else Me.MessageBox1.ShowError("Product was not added correctly. Unknown Error") End If End If 'End If End If End If Else ' The Product is nothing - probably because a non-existent SKU Me.MessageBox1.ShowWarning("That product could not be located. Please check SKU.") End If End If LoadOrder() End Sub Protected Sub btnAddProductBySku_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAddProductBySku.Click AddProductBySku() End Sub Protected Sub btnCloseVariants_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCloseVariants.Click Me.MessageBox1.ClearMessage() Me.AddProductSkuHiddenField.Value = String.Empty Me.pnlProductChoices.Visible = False End Sub Protected Sub btnAddVariant_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAddVariant.Click Me.MessageBox1.ClearMessage() Dim product As Catalog.Product = Catalog.InternalProduct.FindByBvin(Me.AddProductSkuHiddenField.Value) If product IsNot Nothing Then If product.IsKit Then If Not Me.AddNewKitComponentsDisplay.IsValid Then Me.MessageBox1.ShowWarning("Please make all kit selections first.") Else Dim li As New Orders.LineItem() li.ProductId = product.Bvin li.Quantity = CDec(Me.NewProductQuantity.Text.Trim) AddNewKitComponentsDisplay.WriteToLineItem(li) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If o.AddItem(li) Then Me.AddProductSkuHiddenField.Value = String.Empty Me.BvinField.Value = o.Bvin LoadOrder() Me.MessageBox1.ShowOk("Product added!") Else Me.MessageBox1.ShowError("Product was not added.") End If Me.pnlProductChoices.Visible = False End If Else Dim p As Catalog.Product = Me.VariantsDisplay1.GetSelectedProduct(Nothing) If Not VariantsDisplay1.IsValidCombination Then Me.MessageBox1.ShowError("This is not a valid combination") Else If Me.VariantsDisplay1.IsValid Then If p IsNot Nothing Then Dim li As New Orders.LineItem() li.ProductId = p.Bvin li.Quantity = CDec(Me.NewProductQuantity.Text.Trim) VariantsDisplay1.WriteValuesToLineItem(li) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) If (p IsNot Nothing) AndAlso (o.AddItem(li)) Then Me.AddProductSkuHiddenField.Value = String.Empty Me.BvinField.Value = o.Bvin LoadOrder() Me.MessageBox1.ShowOk("Product Added!") Else Me.MessageBox1.ShowError("Product was not added correctly. Unknown Error") End If Me.pnlProductChoices.Visible = False End If End If End If End If End If End Sub ' NOTE: required Product Inputs cannot be validated because the 'required' setting isn't a property of the ProductInput object Protected Function ValidateOptions(ByVal o As Orders.Order) As BVOperationResult Dim result As New BVOperationResult(False, "") Dim errorSkus As New Collection(Of String) Dim errorBvins As New Collection(Of String) If o Is Nothing Then result.Success = False result.Message = "Order could not be found." Return result End If For Each li As Orders.LineItem In o.Items Dim p As Catalog.Product = Catalog.InternalProduct.FindByBvin(li.ProductId) Dim parentP As Catalog.Product = p If Not String.IsNullOrEmpty(p.ParentId) Then parentP = Catalog.InternalProduct.FindByBvin(p.ParentId) End If ' make sure that choices have been made If p.Bvin = parentP.Bvin AndAlso parentP.ChoiceCombinations.Count > 0 Then errorSkus.Add(li.ProductSku) errorBvins.Add(li.Bvin) Else ' make sure that required modifiers have been chosen For Each cib As Catalog.ProductChoiceInputBase In parentP.ChoicesAndInputs If TypeOf (cib) Is Catalog.ProductModifier Then Dim modifier As Catalog.ProductModifier = CType(cib, Catalog.ProductModifier) If modifier.Required Then Dim lim As Orders.LineItemModifier = li.Modifiers.FirstOrDefault(Function(m) m.ModifierBvin = modifier.Bvin) If lim Is Nothing OrElse String.IsNullOrEmpty(lim.Bvin) OrElse modifier.ModifierOptions.Any(Function(m) m.IsNull AndAlso m.Bvin = lim.ModifierValue) Then errorSkus.Add(li.ProductSku) errorBvins.Add(li.Bvin) Exit For End If End If End If Next End If Next If errorSkus.Count > 0 Then Dim errorMessage As String = String.Format("Your order contains the following SKU's that require you to select options: {0}", String.Join(", ", errorSkus.ToArray())) result.Success = False result.Message = errorMessage Else result.Success = True End If Return result End Function #End Region #Region " Product Editing " Protected Sub ItemGridView_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles ItemsGridView.RowDeleting Me.MessageBox1.ClearMessage() Dim bvin As String = CType(ItemsGridView.DataKeys(e.RowIndex).Value, String) SaveOrder(False, False) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) o.RemoveItem(bvin) LoadOrder() End Sub #End Region #Region " Line Editing " Protected Sub btnCancelLineEdit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCancelLineEdit.Click Me.MessageBox1.ClearMessage() Me.EditLineBvin.Value = String.Empty Me.pnlEditLineItem.Visible = False Me.pnlAdd.Visible = True End Sub Protected Sub btnSaveLineEdit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSaveLineEdit.Click Me.MessageBox1.ClearMessage() Dim li As Orders.LineItem = Orders.LineItem.FindByBvin(Me.EditLineBvin.Value) If li IsNot Nothing Then If li.Bvin <> String.Empty Then Dim valid As Boolean = False If li.KitSelections IsNot Nothing Then If Not Me.EditLineKitComponentsDisplay.IsValid Then Me.MessageBox1.ShowWarning("Please make all kit selections first.") Else Me.EditLineKitComponentsDisplay.WriteToLineItem(li) valid = True End If Else Dim prod As Catalog.Product = Me.EditLineVariantsDisplay.GetSelectedProduct(Nothing) If Not Me.EditLineVariantsDisplay.IsValidCombination Then Me.MessageBox1.ShowError("This is not a valid combination") Else If Me.EditLineVariantsDisplay.IsValid Then If prod IsNot Nothing Then li.ProductId = prod.Bvin End If Me.EditLineVariantsDisplay.WriteValuesToLineItem(li) Dim o As Orders.Order = Orders.Order.FindByBvin(Request.QueryString("id")) li.SetBasePrice(o.UserID) ' force to recalculate with modifiers valid = True End If End If End If If valid Then If Orders.LineItem.Update(li) Then Me.MessageBox1.ShowOk("Line Item Updated") LoadOrder() Me.EditLineBvin.Value = String.Empty Me.pnlEditLineItem.Visible = False Me.pnlAdd.Visible = True End If End If End If End If End Sub Protected Sub ItemsGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles ItemsGridView.RowUpdating Me.MessageBox1.ClearMessage() Dim bvin As String = String.Empty bvin = ItemsGridView.DataKeys(e.RowIndex).Value.ToString If bvin <> String.Empty Then Dim li As Orders.LineItem = Orders.LineItem.FindByBvin(bvin) If li IsNot Nothing Then Me.pnlAdd.Visible = False Me.pnlEditLineItem.Visible = True Me.EditLineBvin.Value = li.Bvin PopulateLineEditor(li.Bvin) 'Me.EditLineKitComponentsDisplay.LoadFromLineItem(li) If li.KitSelections IsNot Nothing Then 'AndAlso Not li.KitSelections.IsEmpty Then Me.EditLineVariantsDisplayContainer.Visible = False Me.EditLineKitComponentsDisplay.LoadFromLineItem(li) Else Me.EditLineVariantsDisplay.LoadFromLineItem(li) Me.EditLineVariantsDisplayContainer.Visible = True End If End If Else Me.MessageBox1.ShowWarning("Unable to get line item ID for editing") End If End Sub Public Sub PopulateLineEditor() PopulateLineEditor(Me.EditLineBvin.Value) End Sub Public Sub PopulateLineEditor(ByVal lineBvin As String) If lineBvin <> String.Empty Then Dim li As Orders.LineItem = Orders.LineItem.FindByBvin(lineBvin) If li IsNot Nothing Then If li.Bvin <> String.Empty Then Me.EditLineVariantsDisplay.BaseProduct = Catalog.InternalProduct.FindByBvin(li.ProductId) End If End If End If End Sub #End Region Protected Sub ShippingTotalBVCustomValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles ShippingTotalBVCustomValidator.ServerValidate If Decimal.TryParse(args.Value, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, Nothing) Then args.IsValid = True Else args.IsValid = False End If End Sub Protected Sub RecalculateOffersLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RecalculateOffersLinkButton.Click Dim saveResult As BVOperationResult = SaveOrder(True, False) If saveResult.Success Then RunOrderEditedWorkflow(saveResult) End If LoadOrder() End Sub Protected Sub RecalculateProductPrices_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RecalculateProductPrices.Click Dim saveResult As BVOperationResult = SaveOrder(True, False) If saveResult.Success Then Dim o As Orders.Order = Orders.Order.FindByBvin(Request.QueryString("id")) o.RecalculateProductPrices() Orders.Order.Update(o) End If LoadOrder() End Sub Protected Sub TaxExemptField_CheckChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TaxExemptField.CheckedChanged, OrderDiscountAdjustments.TextChanged SaveOrder(False, False) LoadOrder() End Sub Protected Sub ShippingTotalTextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ShippingTotalTextBox.TextChanged SaveOrder(True, False) ' shipping discount offers must be recalculated LoadOrder() End Sub Protected Sub ShippingRatesList_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ShippingRatesList.SelectedIndexChanged If Not String.IsNullOrEmpty(Me.ShippingRatesList.SelectedValue) Then Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) Dim rate As Shipping.ShippingRate = FindSelectedRate(Me.ShippingRatesList.SelectedValue, o) Me.ShippingTotalTextBox.Text = rate.Rate.ToString("C") SaveOrder(True, False) LoadOrder() End If End Sub Protected Sub AddressEditor_AddressChanged() Handles ShippingAddressEditor.AddressChanged SaveOrder(False, False) Dim o As Orders.Order = Orders.Order.FindByBvin(Me.BvinField.Value) LoadShippingMethodsForOrder(o) End Sub Private Sub CalculateTax(ByVal o As Orders.Order) o.CalculateTax() If TaxExemptField.Checked Then o.TaxTotal = 0 o.CalculateGrandTotalOnly(False, False) o.CustomPropertySet("Develisys", "TaxExempt", "1") Orders.Order.Update(o) Else o.CustomPropertyRemove("Develisys", "TaxExempt") Orders.Order.Update(o) End If End Sub Private Sub LoadSalesPeople(ByVal o As Orders.Order) Me.ddlSalesPerson.DataSource = Membership.UserAccount.FindAllSalesPeople() Me.ddlSalesPerson.AppendDataBoundItems = True Me.ddlSalesPerson.Items.Add(New ListItem("- None -", "")) Me.ddlSalesPerson.DataValueField = "bvin" Me.ddlSalesPerson.DataTextField = "UserName" Me.ddlSalesPerson.DataBind() Me.ddlSalesPerson.SelectedValue = o.SalesPersonId ' disable editing of sales person if user isn't an admin Dim adminUserBvin As String = SessionManager.GetCurrentUserId() If Not (adminUserBvin = "30" OrElse Membership.Role.FindByUserId(SessionManager.GetCurrentUserId()).Any(Function(r) r.Bvin = WebAppSettings.AdministratorsRoleId)) Then Me.ddlSalesPerson.Enabled = False End If End Sub End Class
Public Class Form1 'This is the x and y of the players "centre" point where all calculations are based off of Dim x As Integer = 50 Dim y As Integer = 50 'used to determine tick rate Const fps As Decimal = 60 'Variables for detecting key presses Dim wpress As Boolean Dim apress As Boolean Dim spress As Boolean Dim dpress As Boolean 'misc maths variables Dim r As Integer = 0 'Roataion from ghost image Dim rv As Integer = 5 'Rotation multiplier Dim v As Decimal = 0 'Velocity Dim maxv As Decimal = 7 'Max velocity Dim length As Integer = 20 'Length of player 'Drawing stuff Dim formGraphics As System.Drawing.Graphics 'Graphics layer? Dim playerpen As New System.Drawing.Pen(System.Drawing.Color.Blue, 1) 'Blue pen Dim debugpen As New System.Drawing.Pen(System.Drawing.Color.Red, 1) 'Red pen Dim debugpen2 As New System.Drawing.Pen(System.Drawing.Color.Green, 1) 'Green pen Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'Load graphics formGraphics = Me.CreateGraphics() 'Makes the tickspeed relevant to set fps GameTick.Interval = 1 / (fps / 1000) End Sub Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown 'Getting key presses and storing htem in the respective variables Select Case e.KeyCode Case Keys.W : wpress = True Case Keys.A : apress = True Case Keys.S : spress = True Case Keys.D : dpress = True End Select End Sub Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp 'Getting key presses and storing htem in the respective variables Select Case e.KeyCode Case Keys.W : wpress = False Case Keys.A : apress = False Case Keys.S : spress = False Case Keys.D : dpress = False End Select End Sub Private Sub GameTick_Tick(sender As Object, e As EventArgs) Handles GameTick.Tick 'Radians stuff Dim ToRadians As Double = System.Math.PI / 180 Dim ToDegrees As Double = 180 / System.Math.PI Dim rr As Double 'Rotation direction Dim rdir As Integer 'Checking w and s If wpress = True And spress = True Then 'Nothing ElseIf wpress = True Then v = v + 0.1 ElseIf spress = True Then v = v - 0.1 End If 'Keeping v in acceptable values If v > maxv Then v = maxv If v < 0 Then v = 0 'Checking a and d If dpress = True And apress = True Then rdir = 0 ElseIf dpress = True Then rdir = -1 ElseIf apress = True Then rdir = 1 Else rdir = 0 End If 'Updating rotation value r = r + rdir * rv 'Keeping r in acceptable values If r > 360 Then r = r - 360 If r < 0 Then r = r + 360 'Making radians r rr = r * ToRadians 'Different points used for drawing Dim forward As Point Dim back As Point Dim centre As Point Dim p1 As Point 'These two are used for the left and right point to make the shape Dim p2 As Point formGraphics.Clear(Color.White) 'Updating centrepint using v and r x = x + v * Math.Cos(90 * ToRadians - rr) y = y + v * Math.Sin(90 * ToRadians - rr) 'Updating labels Label5.Text = wpress Label6.Text = apress Label7.Text = spress Label8.Text = dpress Label4.Text = r Label1.Text = x Label2.Text = y 'Setting the centre centre.X = x centre.Y = y 'Setting thetopand bottom points of the shape forward.X = x + (0.5 * length * Math.Sin(rr)) forward.Y = y + (0.5 * length * Math.Cos(rr)) back.X = x - (0.5 * length * Math.Sin(rr)) back.Y = y - (0.5 * length * Math.Cos(rr)) 'Setting the two edge points p1.X = x + length * Math.Sin(rr + 160 * ToRadians) p1.Y = y + length * Math.Cos(rr + 160 * ToRadians) p2.X = x + length * Math.Sin(rr + 200 * ToRadians) p2.Y = y + length * Math.Cos(rr + 200 * ToRadians) 'Drawing the shape formGraphics.DrawLine(playerpen, forward, p1) formGraphics.DrawLine(playerpen, p1, back) formGraphics.DrawLine(playerpen, forward, p2) formGraphics.DrawLine(playerpen, p2, back) 'Debug line so i can see the shape if i muck up formGraphics.DrawLine(debugpen, forward, back) End Sub End Class
Public Class WhatAmIBook Inherits Book Sub New(photo As Bitmap, bookTitle As String) MyBase.New(photo, bookTitle) pages.Add(New WhatAmIPage(My.Resources.What_Am_I_Apple_Non_Coloured, My.Resources.What_Am_I_Apple_Coloured, "APPLE", 1, 4)) pages.Add(New WhatAmIPage(My.Resources.What_Am_I_Book_Non_Coloured, My.Resources.What_Am_I_Book_Coloured, "BOOK", 1, 4)) pages.Add(New WhatAmIPage(My.Resources.What_Am_I_Cat_Non_Coloured, My.Resources.What_Am_I_Cat_Coloured, "CAT", 1, 4)) pages.Add(New WhatAmIPage(My.Resources.What_Am_I_Dog_Non_Coloured, My.Resources.What_Am_I_Dog_Coloured, "DOG", 1, 4)) pages.Add(New WhatAmIPage(My.Resources.What_Am_I_Flower_Non_Coloured, My.Resources.What_Am_I_Flower_Coloured, "FLOWER", 1, 4)) difficultPages.Add(New WhatAmIPage(My.Resources.What_Am_I_House_Non_Coloured, My.Resources.What_Am_I_House_Coloured, "HOUSE", 2, 5)) difficultPages.Add(New WhatAmIPage(My.Resources.What_Am_I_Mouse_Non_Coloured, My.Resources.What_Am_I_Mouse_Coloured, "MOUSE", 2, 6)) difficultPages.Add(New WhatAmIPage(My.Resources.What_Am_I_Telephone_Non_Coloured, My.Resources.What_Am_I_Telephone_Coloured, "TELEPHONE", 3, 7)) difficultPages.Add(New WhatAmIPage(My.Resources.What_Am_I_Violin_Non_Coloured, My.Resources.What_Am_I_Violin_Coloured, "VIOLIN", 3, 8)) difficultPages.Add(New WhatAmIPage(My.Resources.What_Am_I_Watermelon_Non_Coloured, My.Resources.What_Am_I_Watermelon_Coloured, "WATERMELON", 4, 10)) ' Initialize the pages here End Sub End Class
Imports Microsoft.AspNetCore.Builder Imports Microsoft.AspNetCore.Hosting Imports Microsoft.Extensions.Configuration Imports Microsoft.Extensions.DependencyInjection Imports Microsoft.Extensions.Logging Public Class Startup Public Sub New(env As IHostingEnvironment) Dim builder = (New ConfigurationBuilder()).SetBasePath(env.ContentRootPath). AddJsonFile("appsettings.json", optional:=False, reloadOnChange:=True). AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:=True).AddEnvironmentVariables() Configuration = builder.Build() End Sub Public ReadOnly Property Configuration() As IConfigurationRoot ' This method gets called by the runtime. Use this method to add services to the container. Public Sub ConfigureServices(services As IServiceCollection) ' Add framework services. services.AddMvc() End Sub ' This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public Sub Configure(app As IApplicationBuilder, env As IHostingEnvironment, loggerFactory As ILoggerFactory) app.UseMvc(Sub(routes) routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}")) End Sub End Class
Imports System.Data Imports System.Net.Mail ''' <summary> ''' Approval page of HR Related Requests ''' </summary> Partial Class Master_Default Inherits System.Web.UI.Page Private GlobalFunctions As New GlobalFunctions #Region "HR Request" #Region "Properties" Public Property GlobalFunctionsProperty() As GlobalFunctions Get Return GlobalFunctions End Get Set(ByVal value As GlobalFunctions) End Set End Property ''' <summary> ''' Gets or sets the sort order HRQ. ''' </summary> ''' <value> ''' The sort order HRQ. ''' </value> Private Property SortOrderHRQ() As String Get If Me.ViewState("SortOrderHRQ").ToString = "desc" Then Me.ViewState("SortOrderHRQ") = "asc" Else Me.ViewState("SortOrderHRQ") = "desc" End If Return Me.ViewState("SortOrderHRQ").ToString End Get Set(ByVal value As String) Me.ViewState("SortOrderHRQ") = value End Set End Property ''' <summary> ''' Gets or sets the sort expression HRQ. ''' </summary> ''' <value> ''' The sort expression HRQ. ''' </value> Private Property SortExpressionHRQ() As String Get Return Me.ViewState("SortExpressionHRQ").ToString End Get Set(ByVal value As String) Me.ViewState("SortExpressionHRQ") = value End Set End Property #End Region #Region "Events" ''' <summary> ''' Confirms that an <see cref="T:System.Web.UI.HtmlControls.HtmlForm" /> control is rendered for the specified ASP.NET server control at run time. ''' </summary> ''' <param name="control">The ASP.NET server control that is required in the <see cref="T:System.Web.UI.HtmlControls.HtmlForm" /> control.</param> Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control) End Sub ''' <summary> ''' Handles the Click event of the btn_done control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub btn_done_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_done.Click Dim intID As Integer Dim lb_success As Boolean = True Dim ErrorApp As Boolean Dim blnChecked As Boolean Dim HRRequestDAL As New HRRequestDAL Dim GlobalFunctions As New GlobalFunctions Dim strStatus As String Dim strEmail As String Dim strReqType As String Dim strFName As String Dim strEmpNo As String = "" strStatus = cboStatus2.SelectedValue For Each gvr As GridViewRow In grdvwHrReq.Rows Dim cb As CheckBox = CType(gvr.FindControl("chkSelect"), CheckBox) If cb.Checked = True And cb.Visible = True Then blnChecked = True intID = Val(CType(gvr.FindControl("hdnIDItem"), HiddenField).Value) strEmail = CType(gvr.FindControl("hdnEmail"), HiddenField).Value strReqType = CType(gvr.FindControl("lblDReqType"), Label).Text strFName = CType(gvr.FindControl("hdnFName"), HiddenField).Value strEmpNo = CType(gvr.FindControl("lblEmpNo"), Label).Text HRRequestDAL.UpdateHRRequestStatus(intID, strStatus, _ txt_remark.Text, lb_success, strReqType, strEmail, _ strFName, cboStatus2.SelectedItem.Text) 'SendEmailToEmployeeForApproval(strEmpNo, intID, cboStatus2.SelectedItem.Text, txt_remark.Text) End If Next If SortExpressionHRQ.ToString.Trim.Length > 0 Then DisplayRequest(True, SortExpressionHRQ.ToString, Me.ViewState("SortOrderHRQ").ToString) Else DisplayRequest() End If If blnChecked = False Then GlobalFunctions.AddBulletedItems(bulError, Webconfig.RECORDS_SELECTED_PROMPT, ErrorApp) pError.Visible = True pSuccess.Visible = False End If If lb_success = False Then pError.Visible = True lblErrSummary.Text = "Error!" ElseIf ErrorApp = False And lb_success = True Then pError.Visible = False pSuccess.Visible = True GlobalFunctions.AddBulletedItems(bulSuccessUpdate, Webconfig.CHANGES_SAVED_APP_PROMPT) txt_remark.Text = "" cboStatus2.SelectedIndex = 0 End If End Sub ''' <summary> ''' Handles the Load event of the Page control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then clearSortingProperties() PopulateCombo() ddlStatus.SelectedValue = "HRS00003" DisplayRequest() End If End Sub ''' <summary> ''' Handles the PreRender event of the Page control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender btn_done.Attributes.Add("onClick", "return confirm('Are you sure you want to save the changes you made?');") End Sub ''' <summary> ''' Handles the SelectedIndexChanged event of the ddlPages control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub ddlPages_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Dim gvrPager As GridViewRow Dim ddlPages As DropDownList gvrPager = grdvwHrReq.BottomPagerRow ddlPages = CType(gvrPager.Cells(0).FindControl("ddlPages"), DropDownList) grdvwHrReq.PageIndex = ddlPages.SelectedIndex If SortExpressionHRQ.ToString.Trim.Length > 0 Then DisplayRequest(True, SortExpressionHRQ.ToString, Me.ViewState("SortOrderHRQ").ToString) Else DisplayRequest() End If End Sub ''' <summary> ''' Paginates the specified sender. ''' </summary> ''' <param name="sender">The sender.</param> ''' <param name="e">The <see cref="CommandEventArgs"/> instance containing the event data.</param> Protected Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs) Dim intCurIndex As Integer 'get the current page selected With grdvwHrReq intCurIndex = .PageIndex Try Select Case e.CommandArgument.ToString().ToLower() Case "first" .PageIndex = 0 Exit Select Case "prev" .PageIndex = intCurIndex - 1 Exit Select Case "next" .PageIndex = intCurIndex + 1 Exit Select Case "last" .PageIndex = .PageCount Exit Select End Select Catch ex As Exception End Try If SortExpressionHRQ.ToString.Trim.Length > 0 Then DisplayRequest(True, SortExpressionHRQ.ToString, Me.ViewState("SortOrderHRQ").ToString) Else DisplayRequest() End If End With End Sub ''' <summary> ''' Handles the RowDataBound event of the grdvwHrReq control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param> Protected Sub grdvwHrReq_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdvwHrReq.RowDataBound Dim hdnStatus As HiddenField Dim chkSelect As CheckBox With grdvwHrReq e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#FFDF7D'") e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;") Select Case e.Row.RowState Case DataControlRowState.Normal, DataControlRowState.Alternate hdnStatus = e.Row.Cells(0).FindControl("hdnStatus") chkSelect = e.Row.Cells(0).FindControl("chkSelect") If IsNothing(hdnStatus) = False And IsNothing(chkSelect) = False Then If hdnStatus.Value.Trim = "HRS00002" Then chkSelect.Visible = False Else chkSelect.Visible = True End If End If End Select End With End Sub ''' <summary> ''' Handles the RowCreated event of the grdvwHrReq control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param> Protected Sub grdvwHrReq_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdvwHrReq.RowCreated Dim GlobalFunctions As New GlobalFunctions Dim strSourceControl As String = "" If IsNothing(Request.Form("__EVENTTARGET")) = False Then strSourceControl = Request.Form("__EVENTTARGET").ToString End If If strSourceControl = "ctl00$ContentPlaceHolder1$grdvwHrReq" Then ' Use the RowType property to determine whether the ' row being created is the header row. If e.Row.RowType = DataControlRowType.Header Then ' Call the GetSortColumnIndex helper method to determine ' the index of the column being sorted. Dim sortColumnIndex As Integer sortColumnIndex = GlobalFunctions.GetSortColumnIndex(grdvwHrReq, SortExpressionHRQ) If sortColumnIndex <> -1 Then ' Call the AddSortImage helper method to add ' a sort direction image to the appropriate ' column header. GlobalFunctions.AddSortImage(sortColumnIndex, e.Row, Me.ViewState("SortOrderHRQ").ToString) End If End If End If End Sub ''' <summary> ''' Handles the Sorting event of the grdvwHrReq control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.Web.UI.WebControls.GridViewSortEventArgs"/> instance containing the event data.</param> Protected Sub grdvwHrReq_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdvwHrReq.Sorting SortExpressionHRQ = e.SortExpression.ToString DisplayRequest(True, e.SortExpression.ToString, SortOrderHRQ) End Sub ''' <summary> ''' Handles the DataBound event of the grdvwHrReq control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub grdvwHrReq_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdvwHrReq.DataBound Dim ddlPages As DropDownList Dim lblPageCount As Label Dim i As Integer Dim intPageNumber As Integer Dim lstItem As ListItem Dim gvrPager As GridViewRow Dim chkSelectAll As CheckBox Try With grdvwHrReq Dim grdRow As GridViewRow grdRow = .HeaderRow chkSelectAll = CType(grdRow.FindControl("chkSelectAll"), CheckBox) If IsNothing(chkSelectAll) = False Then If Val(hdnRecCount.Value) = 0 Then chkSelectAll.Visible = False Else chkSelectAll.Visible = True End If End If gvrPager = .BottomPagerRow ddlPages = CType(gvrPager.Cells(0).FindControl("ddlPages"), DropDownList) lblPageCount = .BottomPagerRow.FindControl("lblPageCount") If IsNothing(ddlPages) = False Then 'populate pager For i = 0 To .PageCount - 1 intPageNumber = i + 1 lstItem = New ListItem(intPageNumber.ToString()) If (i = .PageIndex) Then lstItem.Selected = True End If ddlPages.Items.Add(lstItem) Next End If ' populate page count If IsNothing(lblPageCount) = False Then lblPageCount.Text = " of " & .PageCount.ToString() End If End With Catch ex As Exception End Try End Sub ''' <summary> ''' Handles the Click event of the btn_clear control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub btn_clear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_clear.Click txtFrom.Text = "" txtRemark.Text = "" txtTo.Text = "" ddlReqType.SelectedIndex = -1 ddlStatus.SelectedIndex = -1 txtPurpose.Text = "" txtEmpName.Text = "" txt_empno.Text = "" End Sub ''' <summary> ''' Handles the Click event of the btn_search control. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> Protected Sub btn_search_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_search.Click DisplayRequest() End Sub #End Region #Region "Methods / Functions" ''' <summary> ''' Sends the email to employee for approval. ''' </summary> ''' <param name="strEmpNo">The string emp no.</param> ''' <param name="intID">The int identifier.</param> ''' <param name="strStatus">The string status.</param> ''' <param name="strRemark">The string remark.</param> Private Sub SendEmailToEmployeeForApproval(ByVal strEmpNo As String, ByVal intID As Integer, _ ByVal strStatus As String, ByVal strRemark As String) Dim LogsDAL As New LogsDAL Dim HRRequestDAL As New HRRequestDAL Try HRRequestDAL.EmailHRRequestToEmployee(intID, strStatus, strRemark) Catch ex As Exception LogsDAL.InsertLog("Error Log", "Module:HRRequestAdmin; Function:SendEmailToEmployeeForApproval; Description:" & _ ex.Message.ToString) End Try End Sub ''' <summary> ''' Sets the date fields. ''' </summary> Protected Sub SetDateFields() txtFrom.Text = FormatDateTime(DateTime.Now.AddDays(-60), DateFormat.ShortDate) End Sub ''' <summary> ''' Clears the sorting properties. ''' </summary> Private Sub clearSortingProperties() Me.ViewState("SortOrderHRQ") = "" Me.ViewState("SortExpressionHRQ") = "" SortExpressionHRQ = "" End Sub ''' <summary> ''' Populates the combo. ''' </summary> Private Sub PopulateCombo() Dim GlobalFunctions As New GlobalFunctions Dim LogsDAL As New LogsDAL Dim dt As New DataTable Dim HRRequestDAL As New HRRequestDAL Try GlobalFunctions.BindComboList(ddlReqType, _ HRRequestDAL.GetEmployeeRequestTypeList().Tables(0), _ , "-Select Request Type-") dt = HRRequestDAL.GetEmployeeRequestStatusList() With ddlStatus GlobalFunctions.BindComboList(ddlStatus, dt, , "-Select Status-", , , "-1") End With With cboStatus2 GlobalFunctions.BindComboList(cboStatus2, dt) .Items.Remove(cboStatus2.Items.FindByValue("HRS00003")) End With Catch ex As Exception LogsDAL.InsertLog("Error Log", "Module:HRRequestAdmin; Function:PopulateCombo; Description:" & _ ex.Message.ToString) End Try End Sub ''' <summary> ''' Displays the request. ''' </summary> ''' <param name="blnSort">if set to <c>true</c> [BLN sort].</param> ''' <param name="strSortExp">The string sort exp.</param> ''' <param name="strSortOrder">The string sort order.</param> Private Sub DisplayRequest(Optional ByVal blnSort As Boolean = False, Optional ByVal strSortExp As String = "", _ Optional ByVal strSortOrder As String = "") Dim dt As DataTable Dim dv As DataView Dim HRRequestDAL As New HRRequestDAL Dim GlobalFunctions As New GlobalFunctions Dim strReqType As String Dim ErrorApp As Boolean Dim LogsDAL As New LogsDAL Try strReqType = GlobalFunctions.verifyDropdownlistGen(ddlReqType) If Not IsDate(txtFrom.Text.Trim) And txtFrom.Text.Trim.Length > 0 Then GlobalFunctions.AddBulletedItems(bulError, Webconfig.INVALID_FROM_DATE_PROMPT, ErrorApp) ElseIf Not IsDate(txtTo.Text.Trim) And txtTo.Text.Trim.Length > 0 Then GlobalFunctions.AddBulletedItems(bulError, Webconfig.INVALID_TO_DATE_PROMPT, ErrorApp) ElseIf txtTo.Text.Trim.Length > 0 And txtFrom.Text.Trim.Length > 0 And IsDate(txtTo.Text.Trim) _ And IsDate(txtFrom.Text.Trim) Then If (CDate(txtFrom.Text.Trim) > CDate(txtTo.Text.Trim)) Then GlobalFunctions.AddBulletedItems(bulError, Webconfig.DATE_TO_PRIOR_PROMPT, ErrorApp) End If End If If ErrorApp = False Then dt = HRRequestDAL.GetHRRequest(txtRemark.Text, txtFrom.Text, _ txtTo.Text, strReqType, txtPurpose.Text, ddlStatus.SelectedValue, _ txt_empno.Text, _ txtEmpName.Text, True).Tables(0).Copy hdnRecCount.Value = dt.Rows.Count If dt.Rows.Count > 0 Then If blnSort = True Then dv = dt.DefaultView dv.Sort = strSortExp & " " & strSortOrder grdvwHrReq.DataSource = dv grdvwHrReq.DataBind() Else grdvwHrReq.DataSource = dt grdvwHrReq.DataBind() End If btn_done.Visible = True Else GlobalFunctions.ShowNoResult(dt, grdvwHrReq, 4, False) btn_done.Visible = False End If End If If ErrorApp Then pError.Visible = True pSuccess.Visible = False Else pError.Visible = False End If Catch ex As Exception LogsDAL.InsertLog("Error Log", "Module:HRRequestAdmin; Function:DisplayRequest; Description:" & _ ex.Message.ToString) End Try End Sub #End Region #End Region End Class
Imports System.Runtime.InteropServices Public Class formPaciente_Captura Public IDPAC As Integer Dim DATOS As IDataObject Dim IMAGEN As Image Dim IMG As Image Public Const WM_CAP As Short = &H400S Public Const WM_CAP_DLG_VIDEOFORMAT As Integer = WM_CAP + 41 Public Const WM_CAP_DRIVER_CONNECT As Integer = WM_CAP + 10 Public Const WM_CAP_DRIVER_DISCONNECT As Integer = WM_CAP + 11 Public Const WM_CAP_EDIT_COPY As Integer = WM_CAP + 30 Public Const WM_CAP_SEQUENCE As Integer = WM_CAP + 62 Public Const WM_CAP_FILE_SAVEAS As Integer = WM_CAP + 23 Public Const WM_CAP_SET_PREVIEW As Integer = WM_CAP + 50 Public Const WM_CAP_SET_PREVIEWRATE As Integer = WM_CAP + 52 Public Const WM_CAP_SET_SCALE As Integer = WM_CAP + 53 Public Const WS_CHILD As Integer = &H40000000 Public Const WS_VISIBLE As Integer = &H10000000 Public Const SWP_NOMOVE As Short = &H2S Public Const SWP_NOSIZE As Short = 1 Public Const SWP_NOZORDER As Short = &H4S Public Const HWND_BOTTOM As Short = 1 Public Const WM_CAP_STOP As Integer = WM_CAP + 68 Public iDevice As Integer = 0 ' Current device ID Public hHwnd As Integer ' Handle to preview window Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, _ <MarshalAs(UnmanagedType.AsAny)> ByVal lParam As Object) As Integer Public Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal hwnd As Integer, _ ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, _ ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer Public Declare Function DestroyWindow Lib "user32" (ByVal hndw As Integer) As Boolean Public Declare Function capCreateCaptureWindowA Lib "avicap32.dll" _ (ByVal lpszWindowName As String, ByVal dwStyle As Integer, _ ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, _ ByVal nHeight As Short, ByVal hWndParent As Integer, _ ByVal nID As Integer) As Integer Public Declare Function capGetDriverDescriptionA Lib "avicap32.dll" (ByVal wDriver As Short, _ ByVal lpszName As String, ByVal cbName As Integer, ByVal lpszVer As String, _ ByVal cbVer As Integer) As Boolean Private Sub formPaciente_Captura_Load(sender As Object, e As EventArgs) Handles MyBase.Load OpenPreviewWindow() End Sub 'Open View Public Sub OpenPreviewWindow() ' Open Preview window in picturebox ' hHwnd = capCreateCaptureWindowA(iDevice, WS_VISIBLE Or WS_CHILD, 0, 0, 640, _ 480, Display.Handle.ToInt32, 0) ' Connect to device ' SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) If SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) Then ' 'Set the preview scale SendMessage(hHwnd, WM_CAP_SET_SCALE, True, 0) 'Set the preview rate in milliseconds ' SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0) 'Start previewing the image from the camera ' SendMessage(hHwnd, WM_CAP_SET_PREVIEW, True, 0) ' Resize window to fit in picturebox ' SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, Display.Width, Display.Height, _ SWP_NOMOVE Or SWP_NOZORDER) Else ' Error connecting to device close window ' DestroyWindow(hHwnd) End If End Sub Private Sub GPicture_Click(sender As Object, e As EventArgs) Handles GPicture.Click ' Copy image to clipboard ' SendMessage(hHwnd, WM_CAP_EDIT_COPY, 0, 0) ' Get image from clipboard and convert it to a bitmap ' DATOS = Clipboard.GetDataObject() IMAGEN = CType(DATOS.GetData(GetType(System.Drawing.Bitmap)), Image) Display.Visible = False GPicture.Visible = False Visor.Visible = True Save.Visible = True PDelete.Visible = True Visor.Image = IMAGEN End Sub Private Sub PDelete_Click(sender As Object, e As EventArgs) Handles PDelete.Click Display.Visible = True GPicture.Visible = True Visor.Visible = False Save.Visible = False PDelete.Visible = False End Sub Private Sub Save_Click(sender As Object, e As EventArgs) Handles Save.Click Try Dim context As New CMLinqDataContext() Dim pac As PACIENTE = (From p In context.PACIENTEs Where p.CPACIENTE = Me.IDPAC Select p).First() Dim _imagen As Bitmap = New Bitmap(IMAGEN) Dim _bytes() As Byte = ConvertToByteArray(_imagen) pac.FOTO() = _bytes pac.FOTOGRAFIA = (DateTime.Now).ToString() IMG = IMAGEN context.SubmitChanges() Catch ex As Exception MessageBox.Show("Error al cargar imagen " & ex.Message) End Try Me.DialogResult = Windows.Forms.DialogResult.OK Me.Close() End Sub Public Shared Function ConvertToByteArray(ByVal value As Bitmap) As Byte() Dim bitmapBytes As Byte() Using stream As New System.IO.MemoryStream value.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp) bitmapBytes = stream.ToArray End Using Return bitmapBytes End Function Public ReadOnly Property Selected() As Image ' la parte Get es la que devuelve el valor de la propiedad Get Return IMG End Get End Property Public Function TestConnection() As Boolean hHwnd = capCreateCaptureWindowA(iDevice, WS_VISIBLE Or WS_CHILD, 0, 0, 640, _ 480, Display.Handle.ToInt32, 0) ' Connect to device ' SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) If SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) Then DestroyWindow(hHwnd) Return True Else DestroyWindow(hHwnd) Return False End If End Function End Class
Imports System.Runtime.InteropServices Imports System.Runtime.InteropServices.ComTypes Public Enum WTS_ALPHATYPE WTSAT_UNKNOWN = 0 WTSAT_RGB = 1 WTSAT_ARGB = 2 End Enum Public Enum SIGDN As UInteger NORMALDISPLAY = 0 PARENTRELATIVEPARSING = &H80018001UI PARENTRELATIVEFORADDRESSBAR = &H8001C001UI DESKTOPABSOLUTEPARSING = &H80028000UI PARENTRELATIVEEDITING = &H80031001UI DESKTOPABSOLUTEEDITING = &H8004C000UI FILESYSPATH = &H80058000UI URL = &H80068000UI End Enum Public Enum typedef As Short VT_EMPTY = 0 VT_NULL = 1 VT_I2 = 2 VT_I4 = 3 VT_BOOL = 11 VT_VARIANT = 12 VT_I1 = 16 VT_UI1 = 17 VT_UI2 = 18 VT_UI4 = 19 VT_I8 = 20 VT_UI8 = 21 VT_LPWSTR = 31 VT_BLOB = 65 VT_CLSID = 72 VT_VECTOR = &H1000 End Enum <StructLayout(LayoutKind.Sequential)> Public Structure PROPERTYKEY Public fmtid As Guid Public pid As UIntPtr Public Sub New(fmt As Guid, p As UIntPtr) fmtid = fmt pid = p End Sub Public Overrides Function ToString() As String Dim sFMT As String = fmtid.ToString("B").ToUpper Dim sPID As String = pid.ToString Select Case sFMT Case "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}" sFMT = "Document" Select Case pid.ToUInt32 Case 2 : sPID = "Title" Case 6 : sPID = "Comment" End Select Case "{56A3372E-CE9C-11D2-9F0E-006097C686F6}" sFMT = "Music" Select Case pid.ToUInt32 Case 2 : sPID = "Artist" Case 4 : sPID = "Album" Case 5 : sPID = "Year" Case 7 : sPID = "Track" Case &HB : sPID = "Genre" End Select Case "{64440490-4C8B-11D1-8B70-080036B11A03}" sFMT = "Audio" Select Case pid.ToUInt32 Case 2 : sPID = "Format" Case 3 : sPID = "Duration" Case 4 : sPID = "Bitrate" Case 5 : sPID = "Samplerate" Case 7 : sPID = "Channels" End Select Case "{64440491-4C8B-11D1-8B70-080036B11A03}" sFMT = "Video" Select Case pid.ToUInt32 Case 2 : sPID = "Title" Case 3 : sPID = "Width" Case 4 : sPID = "Height" Case 5 : sPID = "Duration" Case 6 : sPID = "FrameRate" Case 8 : sPID = "Bitrate" Case &HA : sPID = "Format" End Select Case "{AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED}" sFMT = "DRM" Select Case pid.ToUInt32 Case 2 : sPID = "IsProtected" End Select End Select Return sFMT & " " & sPID End Function End Structure <StructLayout(LayoutKind.Sequential)> Public Structure PropVariant2 Public variantType As typedef Public Reserved1, Reserved2, Reserved3 As Short Public pointerValue As IntPtr End Structure <StructLayout(LayoutKind.Explicit, Size:=16)> Public Structure PropVariant <FieldOffset(0)> <MarshalAs(UnmanagedType.U4)> Public type As VarEnum <FieldOffset(8)> Friend union As PropVariantUnion End Structure <StructLayout(LayoutKind.Explicit)> _ Public Structure PropVariantUnion <FieldOffset(0)> _ Public ptr As IntPtr <FieldOffset(0)> _ Public i1Value As SByte <FieldOffset(0)> _ Public i2Value As Int16 <FieldOffset(0)> _ Public i4Value As Int32 <FieldOffset(0)> _ Public i8Value As Int64 <FieldOffset(0)> _ Public ui1Value As Byte <FieldOffset(0)> _ Public ui2Value As UInt16 <FieldOffset(0)> _ Public ui4Value As UInt32 <FieldOffset(0)> _ Public ui8Value As UInt64 <FieldOffset(0)> _ Public boolValue As VARIANT_BOOL <FieldOffset(0)> _ Public lpwstrValue As IntPtr <FieldOffset(0)> _ Public filetimeValue As System.Runtime.InteropServices.ComTypes.FILETIME End Structure Public Enum VARIANT_BOOL As Int16 VARIANT_TRUE = -1S VARIANT_FALSE = 0S End Enum <ComVisible(True), Guid("E357FCCD-A995-4576-B01F-234630154E96"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IThumbnailProvider Sub GetThumbnail(ByVal cx As UInteger, ByRef hBitmap As IntPtr, ByRef bitmapType As WTS_ALPHATYPE) End Interface <ComVisible(True), Guid("B7D14566-0509-4CCE-A71F-0A554233BD9B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IInitializeWithFile Sub Initialize(<MarshalAs(UnmanagedType.LPWStr)> ByVal pszFilePath As String, ByVal grfMode As UInt32) End Interface <ComVisible(True), Guid("7F73BE3F-FB79-493C-A6C7-7EE14E245841"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IInitializeWithItem Sub Initialize(ByVal psi As IShellItem, ByVal grfMode As Integer) End Interface <ComVisible(True), Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IShellItem Sub BindToHandler(ByVal pbc As IntPtr, <MarshalAs(UnmanagedType.LPStruct)> ByVal bhid As Guid, <MarshalAs(UnmanagedType.LPStruct)> ByVal riid As Guid, ByRef ppv As IntPtr) Sub GetParent(ByRef ppsi As IShellItem) Sub GetDisplayName(ByVal sigdnName As SIGDN, ByRef ppszName As IntPtr) Sub GetAttributes(ByVal sfgaoMask As UInt32, ByRef psfgaoAttribs As UInt32) Sub Compare(ByVal psi As IShellItem, ByVal hint As UInt32, ByRef piOrder As Integer) End Interface <ComImport(), Guid("c8e2d566-186e-4d49-bf41-6909ead56acc"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IPropertyStoreCapabilities <PreserveSig()> Function IsPropertyWritable(<[In]()> ByRef key As PROPERTYKEY) As Integer End Interface <ComImport(), Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Public Interface IPropertyStore <PreserveSig()> Function GetCount(<Out()> ByRef cProps As UInteger) As Integer <PreserveSig()> Function GetAt(<[In]()> iProp As UInteger, <Out()> ByRef pkey As PROPERTYKEY) As Integer <PreserveSig()> Function GetValue(<[In]()> key As PROPERTYKEY, <Out()> ByRef pv As PropVariant) As Integer <PreserveSig()> Function SetValue(<[In]()> key As PROPERTYKEY, <[In]()> ByRef pv As Object) As Integer <PreserveSig()> Function Commit() As Integer End Interface
Public Class CrearFecha Friend Sub llenarCombo(ByVal cbo As ComboBox, ByVal source As Object, ByVal display As String, ByVal value As String) cbo.DataSource = source cbo.DisplayMember = display cbo.ValueMember = value End Sub Private Sub CrearFecha_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'TODO: esta línea de código carga datos en la tabla 'Torneos._Torneos' Puede moverla o quitarla según sea necesario. Me.TorneosTableAdapter.getTorneos(Me.Torneos._Torneos) cbo_torneos.SelectedValue = -1 End Sub Private Sub btn_cargar_Click(sender As Object, e As EventArgs) Handles btn_cargar.Click If (cbo_equipo1.Text IsNot cbo_equipo1.Text) Then dgv_partidos.Rows.Add(New String() {cbo_equipo1.Text, cbo_equipo2.Text, txt_cancha.Text.ToString, cbo_equipo1.SelectedValue.ToString, cbo_equipo2.SelectedValue.ToString}) Else MessageBox.Show("Los equipos son iguales", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub Private Sub clear_components() cbo_torneos.SelectedValue = -1 cbo_equipo1.SelectedValue = -1 cbo_equipo2.SelectedValue = -1 txt_nroFecha.Text = "" txt_diaFecha.Clear() dgv_partidos.Rows.Clear() End Sub Private Sub btn_aceptar_Click(sender As Object, e As EventArgs) Handles btn_aceptar.Click Dim partidos = New List(Of Partidos) Dim flag As Boolean = False For Each row In dgv_partidos.Rows Dim p As Partidos = New Partidos(row.Cells("col_equipo1_id").Value, row.Cells("col_equipo2_id").Value, row.Cells("col_cancha").Value) partidos.Add(p) Next If IsDate(txt_diaFecha.Text) Then Dim diaFecha As DateTime = Date.Parse(Me.txt_diaFecha.Text) Dim fechaDesde As DateTime = Date.Parse(Me.txt_fechaDesde.Text) Dim fechaHasta As DateTime = Date.Parse(Me.txt_fechaHasta.Text) If (Date.Compare(diaFecha, fechaHasta) < 0 And Date.Compare(fechaDesde, diaFecha) < 0) Then Dim xdiaFecha As String = diaFecha.ToString("yyyy-MM-dd") BDHelper.guardarFechaTorneoYPartidos(txt_nroFecha.Text, cbo_torneos.SelectedValue, xdiaFecha, partidos) MessageBox.Show("Transaccion completada. Se insertaron los partidos de la correspondiente Fecha", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) clear_components() Else MessageBox.Show("Fecha Fuera de Periodo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else MessageBox.Show("no paso el formato de fecha", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub Private Sub txt_nroFecha_TextChanged(sender As Object, e As EventArgs) Handles txt_nroFecha.TextChanged End Sub Private Sub cbo_torneos_DisplayMemberChanged(sender As Object, e As EventArgs) Handles cbo_torneos.DisplayMemberChanged End Sub Private Sub cbo_torneos_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cbo_torneos.SelectionChangeCommitted Dim filters As New List(Of Object) filters.Add(cbo_torneos.SelectedValue) llenarCombo(cbo_equipo1, BDHelper.getDBHelper.ConsultarSQLConParametros("SELECT * from EquiposxTorneos ET JOIN Equipos E ON ET.id_equipo = E.id_equipo WHERE id_torneo =@param1 ", filters.ToArray), "nombre_equipo", "id_equipo") llenarCombo(cbo_equipo2, BDHelper.getDBHelper.ConsultarSQLConParametros("SELECT * from EquiposxTorneos ET JOIN Equipos E ON ET.id_equipo = E.id_equipo WHERE id_torneo =@param1 ", filters.ToArray), "nombre_equipo", "id_equipo") Dim sql As String = "select T.fechaDesde, T.fechaHasta from Torneos T where T.id_torneo = @param1" Dim fechaDesde = BDHelper.getDBHelper.ConsultarSQLConParametros(sql, filters.ToArray).Rows(0).Item("fechaDesde").ToString Dim xfechaD = Date.Parse(fechaDesde) txt_fechaDesde.Text = xfechaD.ToString("dd/MM/yyyy") Dim fechaHasta = BDHelper.getDBHelper.ConsultarSQLConParametros(sql, filters.ToArray).Rows(0).Item("fechaHasta").ToString Dim xfechaH = Date.Parse(fechaHasta) txt_fechaHasta.Text = xfechaH.ToString("dd/MM/yyyy") End Sub End Class
Public Class MenuItem Private m_parent As Menu Private m_target As String = Nothing Public Sub New(parent As Menu) MyBase.New() InitializeComponent() m_parent = parent Lbl_DropDown.Visible = False End Sub Public Overrides Property Text As String Get Return Lbl_Text.Text End Get Set(value As String) Lbl_Text.Text = value End Set End Property Public Property Target As String Get Return m_target End Get Set(value As String) m_target = value End Set End Property Public Property Image As Image Get Return Pct_Icon.Image End Get Set(value As Image) Pct_Icon.Image = value End Set End Property Private Sub Lbl_Text_Click(sender As Object, e As EventArgs) Handles Lbl_Text.Click If m_target IsNot Nothing Then m_parent.GoToTarget(Me, m_target) End If End Sub Private Sub Lbl_Text_MouseEnter(sender As Object, e As EventArgs) Handles Lbl_Text.MouseEnter Lbl_Text.ForeColor = Color.Gold End Sub Private Sub Lbl_Text_MouseLeave(sender As Object, e As EventArgs) Handles Lbl_Text.MouseLeave Lbl_Text.ForeColor = Color.White End Sub End Class
#Region "Microsoft.VisualBasic::014171f8d99980ad7e5d3d4fbdf7433c, mzkit\src\metadb\Massbank\MetaLib\Match\ComparesIdXrefInteger.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: 61 ' Code Lines: 49 ' Comment Lines: 3 ' Blank Lines: 9 ' File Size: 1.77 KB ' Class ComparesIdXrefInteger ' ' Constructor: (+1 Overloads) Sub New ' ' Function: ParseInteger ' ' Sub: DoCompares ' ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic.Language Namespace MetaLib Friend Class ComparesIdXrefInteger Dim intId As i32 = 0 Dim yes, no As Action Sub New(yes As Action, no As Action) Me.no = no Me.yes = yes End Sub Public Sub DoCompares(a$, b$) a = Strings.Trim(a) b = Strings.Trim(b) ' 2019-03-25 ' 都没有该数据库的编号,即改数据库之中还没有登录该物质 ' 则不应该认为是不一样的 If a = b AndAlso a = "NA" Then yes() Return ElseIf (a.StringEmpty OrElse b.StringEmpty) AndAlso (a = "NA" OrElse b = "NA") Then yes() Return End If If a = b AndAlso Not a.StringEmpty Then yes() Return ElseIf a.StringEmpty OrElse b.StringEmpty Then no() Return End If If ((intId = ParseInteger(a)) = ParseInteger(b)) Then If intId.Equals(0) Then no() Else yes() End If Else no() End If End Sub <MethodImpl(MethodImplOptions.AggressiveInlining)> Private Function ParseInteger(xref As String) As Integer With xref.Match("\d+") If .StringEmpty Then Return 0 Else Return Integer.Parse(.ByRef) End If End With End Function End Class End Namespace
Public Interface IFocusSetter Event SetFocus(ByVal sender As Object, ByVal e As SetFocusEventArgs) End Interface
Imports Microsoft.VisualBasic Imports System Imports System.Drawing Imports System.Windows.Forms Imports Neurotec.Biometrics.Standards Partial Public Class RecordTypeForm Inherits Form #Region "Private fields" Private _version As NVersion = CType(0, NVersion) Private _useSelectMode As Boolean = True #End Region #Region "Public constructor" Public Sub New() InitializeComponent() OnUseSelectModeChanged() End Sub #End Region #Region "Private methods" Private Sub UpdateRecords() lvRecordType.BeginUpdate() lvRecordType.Items.Clear() For Each recordType As ANRecordType In ANRecordType.Types Dim recordVersion As NVersion = recordType.Version If (Not _useSelectMode) OrElse (recordType.Number <> 1 AndAlso recordVersion >= _version) Then Dim recordTypeItem As New ListViewItem(recordType.Number.ToString()) recordTypeItem.Tag = recordType recordTypeItem.SubItems.Add(recordType.Name) If (Not _useSelectMode) Then recordTypeItem.SubItems.Add(recordType.DataType.ToString()) recordTypeItem.SubItems.Add(recordVersion.ToString()) End If lvRecordType.Items.Add(recordTypeItem) End If Next recordType lvRecordType.EndUpdate() End Sub Private Sub OnVersionChanged() UpdateRecords() End Sub Private Sub OnUseSelectModeChanged() UpdateRecords() If _useSelectMode Then Dim index As Integer index = lvRecordType.Columns.IndexOf(recordTypeDataTypeColumnHeader) If index <> -1 Then lvRecordType.Columns.RemoveAt(index) End If index = lvRecordType.Columns.IndexOf(recordTypeVersionColumnHeader) If index <> -1 Then lvRecordType.Columns.RemoveAt(index) End If Else Dim index As Integer index = lvRecordType.Columns.IndexOf(recordTypeDataTypeColumnHeader) If index = -1 Then lvRecordType.Columns.Add(recordTypeDataTypeColumnHeader) End If index = lvRecordType.Columns.IndexOf(recordTypeVersionColumnHeader) If index = -1 Then lvRecordType.Columns.Add(recordTypeVersionColumnHeader) End If End If ClientSize = New Size(CInt(IIf(_useSelectMode, 380, 530)), ClientSize.Height) btnShowFields.Visible = Not _useSelectMode btnOk.Visible = _useSelectMode btnCancel.Text = CStr(IIf(_useSelectMode, "Cancel", "Close")) OnSelectedRecordTypeChanged() End Sub Private Sub OnSelectedRecordTypeChanged() Dim selectedRecordType As ANRecordType = RecordType btnShowFields.Enabled = (Not _useSelectMode) AndAlso selectedRecordType IsNot Nothing btnOk.Enabled = _useSelectMode AndAlso selectedRecordType IsNot Nothing End Sub Private Sub ShowFields() Dim form As New FieldNumberForm() form.Text = "Fields" form.UseSelectMode = False form.RecordType = RecordType form.ShowDialog() End Sub #End Region #Region "Public properties" Public Property Version() As NVersion Get Return _version End Get Set(ByVal value As NVersion) If _version <> value Then _version = value OnVersionChanged() End If End Set End Property Public Property UseSelectMode() As Boolean Get Return _useSelectMode End Get Set(ByVal value As Boolean) If _useSelectMode <> value Then _useSelectMode = value OnUseSelectModeChanged() End If End Set End Property Public Property RecordType() As ANRecordType Get If lvRecordType.SelectedItems.Count = 0 Then Return Nothing Else Return CType(lvRecordType.SelectedItems(0).Tag, ANRecordType) End If End Get Set(ByVal value As ANRecordType) If value Is Nothing Then lvRecordType.SelectedItems.Clear() Else lvRecordType.Items(ANRecordType.Types.IndexOf(value)).Selected = True End If End Set End Property #End Region #Region "private form events" Private Sub LvRecordTypeSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lvRecordType.SelectedIndexChanged OnSelectedRecordTypeChanged() End Sub Private Sub LvRecordTypeDoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles lvRecordType.DoubleClick If RecordType IsNot Nothing Then If _useSelectMode Then DialogResult = Windows.Forms.DialogResult.OK Else ShowFields() End If End If End Sub Private Sub BtnShowFieldsClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnShowFields.Click ShowFields() End Sub #End Region End Class
Public Class userControlFlags Property FlagsReference As List(Of flagElement) Get Return __flagReference End Get Set(value As List(Of flagElement)) __flagReference = value userControlFlagsLoad(Me, Nothing) End Set End Property 'Property labelReference As String() Private controlsNeedToReferesh As List(Of Control) = New List(Of Control) Private __flagReference As List(Of flagElement) Public Overrides Sub Refresh() ' refresh all sub controls For Each uc As Control In controlsNeedToReferesh uc.Refresh() Next MyBase.Refresh() End Sub Private Sub userControlFlagsLoad(sender As Object, e As EventArgs) Handles MyBase.Load If (FlagsReference Is Nothing) Then Exit Sub End If '--------------- ' Hsien , reset all status '--------------- controlsNeedToReferesh.Clear() TableLayoutPanelFlagControl.Controls.Clear() Dim element As userControlFlagElement For Each flag As flagElement In FlagsReference element = New userControlFlagElement element.FlagElementReference = flag controlsNeedToReferesh.Add(element) ' addin tables TableLayoutPanelFlagControl.Controls.Add(element) Next End Sub End Class
Imports DevExpress.Xpo Imports DevExpress.ExpressApp.DC Imports DevExpress.Persistent.Base <Persistent("Equipment2.ChecklistHeader"), DefaultClassOptions(), ImageName("BO_List"), XafDefaultProperty("Name")> Public Class Equipment2_ChecklistHeader Inherits XPObject Public Sub New(ByVal session As Session) MyBase.New(session) End Sub Public Overrides Sub AfterConstruction() MyBase.AfterConstruction() End Sub Private _isInactive As Boolean Private _description As String Private _name As String Public Property Name As String Get Return _name End Get Set(ByVal Value As String) SetPropertyValue("Name", _name, Value) End Set End Property Public Property Description As String Get Return _description End Get Set(ByVal Value As String) SetPropertyValue("Description", _description, Value) End Set End Property Public Property IsInactive As Boolean Get Return _isInactive End Get Set(ByVal Value As Boolean) SetPropertyValue("IsInactive", _isInactive, Value) End Set End Property <Association("ChecklistHeader2-ChecklistDetails")> Public ReadOnly Property Details As XPCollection(Of Equipment2_ChecklistDetail) Get Return GetCollection(Of Equipment2_ChecklistDetail)("Details") End Get End Property <Association("Equipment2-Checklists")> Public ReadOnly Property UsedBy As XPCollection(Of Equipment2_Equipment) Get Return GetCollection(Of Equipment2_Equipment)("UsedBy") End Get End Property End Class
Imports System.Windows.Forms Imports System.Collections.Generic Imports System.Linq Public Class PaycheckEstimator #Region "CONSTANTS" #End Region #Region "PAGE EVENTS" ' Page Load Private Sub MainForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load ' Update the pay period setting if the new pay period has started. If Date.Compare(My.Settings.PayPeriodStartDate.AddDays(My.Settings.PayPeriodLength), Date.Today) < 0 Then My.Settings.PayPeriodStartDate = My.Settings.PayPeriodStartDate.AddDays(My.Settings.PayPeriodLength) My.Settings.Save() End If UpdateEstimatedPayStubLabels(UpdatePayStub(GetListOfDayItemControls())) Dim listOfLists As List(Of List) = GetListOfLists() lbxLists_ListBox.DataSource = listOfLists lbxLists_ListBox.DisplayMember = "Name" lbxLists_ListBox.ValueMember = "ID" lbxLists_ListBox.SetSelected(0, True) End Sub ' Day Item Load Private Sub DayItem_Load(sender As Object, e As System.EventArgs) Handles Monday_DayItem.Load, Tuesday_DayItem.Load, Wednesday_DayItem.Load, Thursday_DayItem.Load, _ Friday_DayItem.Load, Saturday_DayItem.Load, Sunday_DayItem.Load ' The day item that is raising the on load event. Dim dayItem As DayItem_UserControl = sender Dim isDayOff As Boolean = GetIsDayOffSettingValue(dayItem.DayOfWeek) Dim hours As Decimal = GetTimeSettingValue(dayItem.DayOfWeek, "Hours") Dim minutes As Decimal = GetTimeSettingValue(dayItem.DayOfWeek, "Minutes") Dim lunchBreak As Decimal = GetTimeSettingValue(dayItem.DayOfWeek, "LunchBreak") SetDayItemProperties(dayItem, isDayOff, hours, minutes, lunchBreak) End Sub ' Calculate Pay Stub Button Click Private Sub btnCalculatePayStub_Button_Click(sender As System.Object, e As System.EventArgs) Handles btnCalculatePayStub_Button.Click UpdateEstimatedPayStubLabels(UpdatePayStub(GetListOfDayItemControls())) End Sub ' Reset All Button Click Private Sub btnResetAll_Button_Click(sender As System.Object, e As System.EventArgs) Handles btnResetAll_Button.Click My.Settings.Reset() Dim listOfDayItems As List(Of DayItem_UserControl) = GetListOfDayItemControls() For i = 0 To listOfDayItems.Count - 1 DayItem_Load(listOfDayItems(i), e) Next End Sub ' Pay Period Start Date Date Time Picker Value Changed Private Sub dtpPayPeriodStartDate_DateTimePicker_ValueChanged(sender As Object, e As System.EventArgs) Handles dtpPayPeriodStartDate_DateTimePicker.ValueChanged My.Settings.PayPeriodStartDate = dtpPayPeriodStartDate_DateTimePicker.Value My.Settings.Save() dtpPayPeriodEndDate_DateTimePicker.Value = My.Settings.PayPeriodStartDate.AddDays(My.Settings.PayPeriodLength - 1) lblPayPeriodEndDate_Label.Text = My.Settings.PayPeriodStartDate.AddDays(My.Settings.PayPeriodLength - 1).ToShortDateString() End Sub ' Additional Withholding Name Text Box Got Focus Private Sub txtAdditionalWithholdingName_TextBox_GotFocus(sender As Object, e As System.EventArgs) Handles txtAdditionalWithholdingName1_TextBox.GotFocus, txtAdditionalWithholdingName2_TextBox.GotFocus Dim txtAdditionalWithholding As Windows.Forms.TextBox = sender txtAdditionalWithholding.Text = String.Empty End Sub ' Additional Withholding Name Text Box Lost Focus Private Sub txtAdditionalWithholdingName_TextBox_LostFocus(sender As Object, e As System.EventArgs) Handles txtAdditionalWithholdingName1_TextBox.LostFocus, txtAdditionalWithholdingName2_TextBox.LostFocus Dim txtAdditionalWithholding As Windows.Forms.TextBox = sender Dim strNewText As String = txtAdditionalWithholding.Text If String.IsNullOrEmpty(strNewText) Then strNewText = My.Settings.Item("AdditionalWithholdingName" + txtAdditionalWithholding.Tag.ToString()) ElseIf Not My.Settings.Item("AdditionalWithholdingName" + txtAdditionalWithholding.Tag.ToString()).Equals(strNewText) Then My.Settings.Item("AdditionalWithholdingName" + txtAdditionalWithholding.Tag.ToString()) = strNewText My.Settings.Save() End If txtAdditionalWithholding.Text = strNewText End Sub ' Additional Withholding Value Numeric Up Down Lost Focus Private Sub nudAdditionalWithholdingValue_NumericUpDown_LostFocus(sender As Object, e As System.EventArgs) Handles nudAdditionalWithholdingValue1_NumericUpDown.LostFocus, nudAdditionalWithholdingValue2_NumericUpDown.LostFocus Dim nudAdditionalWithholding As Windows.Forms.NumericUpDown = sender Dim amount As Decimal = nudAdditionalWithholding.Value If Not IsNumeric(amount) Then amount = My.Settings.Item("AdditionalWithholdingValue" + nudAdditionalWithholding.Tag.ToString()) ElseIf Not My.Settings.Item("AdditionalWithholdingValue" + nudAdditionalWithholding.Tag.ToString()).Equals(amount) Then My.Settings.Item("AdditionalWithholdingValue" + nudAdditionalWithholding.Tag.ToString()) = amount My.Settings.Save() End If nudAdditionalWithholding.Value = amount End Sub #End Region #Region "PRIVATE METHODS" ' Get Total Minutes Worked Private Function GetTotalMinutesWorked(ByVal aryHours As Decimal(), ByVal aryMinutes As Decimal(), ByVal aryLunch As Decimal()) As Decimal Dim totalMinutes As Decimal = 0.0 totalMinutes += ConvertHoursToMinutes(GetSumOfArrayElements(aryHours)) totalMinutes += GetSumOfArrayElements(aryMinutes) totalMinutes -= GetSumOfArrayElements(aryLunch) Return totalMinutes End Function ' Get Additional Withholdings Array Private Function GetAdditionalWithholdingsArray() As AdditionalWithholding() Dim listAdditionalWithholdingsTextBoxes As List(Of TextBox) = GetListOfAdditionalWithholdingsTextBoxes() Dim listAdditionalWithholdingsNumericUpDowns As List(Of NumericUpDown) = GetListOfAdditionalWithholdingsNumericUpDowns() Dim additionalWithholdings(listAdditionalWithholdingsTextBoxes.Count - 1) As AdditionalWithholding For i = 0 To listAdditionalWithholdingsTextBoxes.Count - 1 additionalWithholdings(i) = New AdditionalWithholding(listAdditionalWithholdingsTextBoxes(i).Text, listAdditionalWithholdingsNumericUpDowns(i).Value) Next Return additionalWithholdings End Function ' Update Pay Stub Private Function UpdatePayStub(ByVal listDayItemControls As List(Of DayItem_UserControl)) As PayStub Dim totalMinutesWorked As Decimal = GetTotalMinutesWorked(GetArrayOfHoursWorked(listDayItemControls), _ GetArrayOfMinutesWorked(listDayItemControls), _ GetArrayOfLunchBreakMinutesWorked(listDayItemControls)) Dim additionalWithholdings() As AdditionalWithholding = GetAdditionalWithholdingsArray() Return New PayStub(My.Settings.PayPeriodStartDate, My.Settings.PayPeriodLength, My.Settings.PayRate, totalMinutesWorked, additionalWithholdings) End Function ' Update Estimated Pay Stub Labels Private Sub UpdateEstimatedPayStubLabels(ByVal estimatedPayStub As PayStub) ' Pay period date time pickers. DirectCast(dtpPayPeriodStartDate_DateTimePicker, DateTimePicker).Value = estimatedPayStub.PayPeriodStartDate DirectCast(dtpPayPeriodEndDate_DateTimePicker, DateTimePicker).Value = estimatedPayStub.PayPeriodEndDate ' Pay period and pay day labels. DirectCast(lblPayPeriodStartDate_Label, Label).Text = estimatedPayStub.PayPeriodStartDate.ToShortDateString() DirectCast(lblPayPeriodEndDate_Label, Label).Text = estimatedPayStub.PayPeriodEndDate.ToShortDateString() DirectCast(lblPaydayDayOfWeekValue_Label, Label).Text = estimatedPayStub.PayDate.DayOfWeek.ToString() DirectCast(lblPayDateValue_Label, Label).Text = estimatedPayStub.PayDate.ToShortDateString() ' Regular earnings labels. DirectCast(lblRegularHoursValue_Label, Label).Text = estimatedPayStub.RegularHours.ToString() + ":" + GetMinutesString(estimatedPayStub.RegularMinutes.ToString()) DirectCast(lblRegularRateValue_Label, Label).Text = GetDollarString(estimatedPayStub.PayRate.ToString()) DirectCast(lblTotalRegularEarningsValue_Label, Label).Text = GetDollarString(estimatedPayStub.RegularPay.ToString()) ' Overtime earnings labels. DirectCast(lblOverTimeHoursValue_Label, Label).Text = estimatedPayStub.OvertimeHours.ToString() + ":" + GetMinutesString(estimatedPayStub.OvertimeMinutes.ToString()) DirectCast(lblOverTimeRateValue_Label, Label).Text = GetDollarString(estimatedPayStub.OvertimePayRate.ToString()) DirectCast(lblTotalOvertimeEarningsValue_Label, Label).Text = GetDollarString(estimatedPayStub.OvertimePay.ToString()) ' Total earnings label. DirectCast(lblTotalEarningsValue_Label, Label).Text = "$" + (estimatedPayStub.RegularPay + estimatedPayStub.OvertimePay).ToString() ' Tax labels. DirectCast(lblTaxFederalValue_Label, Label).Text = "- " + estimatedPayStub.FederalWithholding.ToString() DirectCast(lblTaxStateValue_Label, Label).Text = "- " + estimatedPayStub.StateWithholding.ToString() DirectCast(lblTaxSocialSecurityValue_Label, Label).Text = "- " + estimatedPayStub.SocialSecurityWithholding.ToString() DirectCast(lblTaxMedicareValue_Label, Label).Text = "- " + estimatedPayStub.MedicareWithholding.ToString() ' Total taxes label. DirectCast(lblTotalTaxesValue_Label, Label).Text = "- $" + GetDollarString(estimatedPayStub.TotalTaxWithholdings.ToString()) ' Additional Withholdings. Dim listOfAdditionalWithholdingsTextBoxes As List(Of TextBox) = GetListOfAdditionalWithholdingsTextBoxes() Dim listOfAdditionalWithholdingsNumericUpDowns As List(Of NumericUpDown) = GetListOfAdditionalWithholdingsNumericUpDowns() For i = 0 To estimatedPayStub.AdditionalWithholdings.Length - 1 DirectCast(listOfAdditionalWithholdingsTextBoxes(i), TextBox).Text = estimatedPayStub.AdditionalWithholdings(i).Name DirectCast(listOfAdditionalWithholdingsNumericUpDowns(i), NumericUpDown).Value = estimatedPayStub.AdditionalWithholdings(i).Amount Next ' Total additional withholdings label. DirectCast(lblTotalAdditionalWithholdingsValue_Label, Label).Text = "- $" + GetDollarString(estimatedPayStub.TotalAdditionalWithholdings.ToString()) ' Net pay label. DirectCast(lblNetPayValue_Label, Label).Text = "$" + GetDollarString(estimatedPayStub.NetIncome.ToString()) End Sub ' Get Array Of Hours Worked Private Function GetArrayOfHoursWorked(ByVal listDayItems As List(Of DayItem_UserControl)) As Decimal() Dim aryHours(listDayItems.Count - 1) As Decimal For i = 0 To listDayItems.Count - 1 aryHours(i) = listDayItems(i).HoursWorked Next Return aryHours End Function ' Get Array Of Minutes Worked Private Function GetArrayOfMinutesWorked(ByVal listDayItems As List(Of DayItem_UserControl)) As Decimal() Dim aryMinutes(listDayItems.Count - 1) As Decimal For i = 0 To listDayItems.Count - 1 aryMinutes(i) = listDayItems(i).MinutesWorked Next Return aryMinutes End Function ' Get Array Of Lunch Break Minutes Worked Private Function GetArrayOfLunchBreakMinutesWorked(ByVal listDayItems As List(Of DayItem_UserControl)) As Decimal() Dim aryLunchMinutes(listDayItems.Count - 1) As Decimal For i = 0 To listDayItems.Count - 1 aryLunchMinutes(i) = listDayItems(i).LunchBreakMinutes Next Return aryLunchMinutes End Function ' Get Is Day Off Setting Value Private Function GetIsDayOffSettingValue(ByVal strDayOfWeek As String) As Boolean Return My.Settings.Item(strDayOfWeek + "IsDayOff") End Function ' Get Time Setting Value Private Function GetTimeSettingValue(ByVal strDayOfWeek As String, ByVal strSettingName As String) As Decimal Return My.Settings.Item(strDayOfWeek + strSettingName) End Function ' Get Minutes String Private Function GetMinutesString(ByVal stringToConvert) As String Dim newString As String = String.Empty If stringToConvert.Length.Equals(1) Then stringToConvert += "0" End If Return stringToConvert + newString End Function ' Get Dollar String Private Function GetDollarString(ByVal stringToConvert As String) As String Dim substr As String = String.Empty If stringToConvert.IndexOf(".") >= 0 Then substr = stringToConvert.Substring(stringToConvert.IndexOf(".")) End If Dim s As String = String.Empty Select Case substr.Length Case 0 s = ".00" Case 2 s = "0" End Select Return stringToConvert + s End Function ' Set Day Item Properties Private Sub SetDayItemProperties(ByVal dayItem As DayItem_UserControl, ByVal isDayOff As Boolean, ByVal hours As Decimal, _ ByVal minutes As Decimal, ByVal lunchBrreak As Decimal) With dayItem .HoursWorked = hours .MinutesWorked = minutes .LunchBreakMinutes = lunchBrreak .IsDayOff = isDayOff End With End Sub ' Get List Of Day Item Controls Private Function GetListOfDayItemControls() As List(Of DayItem_UserControl) Dim listOfDayItems As New List(Of DayItem_UserControl) For Each cntrl As System.Windows.Forms.Control In Me.SplitContainer3.Panel2.Controls If cntrl.Name.EndsWith("_DayItem") Then listOfDayItems.Add(cntrl) End If Next Return listOfDayItems End Function ' Get List Of Additional Withholdings Text Boxes Private Function GetListOfAdditionalWithholdingsTextBoxes() As List(Of TextBox) Dim listOfTextBoxes As New List(Of TextBox) For i = 0 To Me.pnlAdditionalWithholdings_Panel.Controls.Count - 1 If Me.pnlAdditionalWithholdings_Panel.Controls(i).Name.EndsWith("_TextBox") Then listOfTextBoxes.Add(Me.pnlAdditionalWithholdings_Panel.Controls(i)) End If Next Return listOfTextBoxes End Function ' Get List Of Additional Withholdings Numeric Up Downs Private Function GetListOfAdditionalWithholdingsNumericUpDowns() As List(Of NumericUpDown) Dim listOfNumericUpDowns As New List(Of NumericUpDown) For i = 0 To Me.pnlAdditionalWithholdings_Panel.Controls.Count - 1 If Me.pnlAdditionalWithholdings_Panel.Controls(i).Name.EndsWith("_NumericUpDown") Then listOfNumericUpDowns.Add(Me.pnlAdditionalWithholdings_Panel.Controls(i)) End If Next Return listOfNumericUpDowns End Function ' Get Sum Of Array Elements Public Shared Function GetSumOfArrayElements(ByVal aryToAdd As Decimal()) As Decimal Dim sumOfArray As Decimal = 0 For i = 0 To aryToAdd.Length - 1 sumOfArray += aryToAdd(i) Next Return sumOfArray End Function ' Convert Hours To Minutes Public Shared Function ConvertHoursToMinutes(ByVal hours As Decimal) As Decimal Return Convert.ToDecimal(hours * 60) End Function #End Region ' Add List Button Click Private Sub btnAddList_Button_Click(sender As System.Object, e As System.EventArgs) Handles btnAddList_Button.Click If ValidateNewListTextBox() Then lblNewListNameErrorMessage_Label.Visible = False Dim newList As List = CreateList() InsertList(newList) lbxLists_ListBox.Update() Else lblNewListNameErrorMessage_Label.Text = GetNewListNameErrorMessage() lblNewListNameErrorMessage_Label.Visible = True End If txtNewListName_TextBox.Text = String.Empty End Sub ' Add List Item Button Click Private Sub btnAddListItem_Button_Click(sender As System.Object, e As System.EventArgs) Handles btnAddListItem_Button.Click If ValidateNewListItemTextBox() Then lblNewListItemNameErrorMessage_Label.Visible = False Dim lstItem As New ListItem With { .ListID = lbxLists_ListBox.SelectedValue, .Name = txtNewListItemName_TextBox.Text, .Amount = 0, .Quantity = 1, .IsComplete = False } Dim db As New PaycheckEstimator_DataClassesDataContext db.ListItems.InsertOnSubmit(lstItem) db.SubmitChanges() Dim lstItemControl As New ListItem_UserControl(lbxLists_ListBox.SelectedValue, lstItem.Name, lstItem.Amount, lstItem.Quantity, lstItem.IsComplete) flpListItems_FlowLayoutPanel.Controls.Add(lstItemControl) Else lblNewListItemNameErrorMessage_Label.Text = GetNewListItemNameErrorMessage() lblNewListItemNameErrorMessage_Label.Visible = True End If txtNewListItemName_TextBox.Text = String.Empty End Sub ' Validate New List Text Box Private Function ValidateNewListTextBox() As Boolean If String.IsNullOrEmpty(txtNewListName_TextBox.Text) Then Return False End If For i = 0 To lbxLists_ListBox.Items.Count - 1 If lbxLists_ListBox.Items(i).ToString.Equals(txtNewListName_TextBox.Text) Then Return False End If Next Return True End Function ' Get New List Name Error Message Private Function GetNewListNameErrorMessage() As String If String.IsNullOrEmpty(txtNewListName_TextBox.Text) Then Return "Please input a name for the new list." End If Return "That list already exists." End Function ' Validate New List Item Text Box Private Function ValidateNewListItemTextBox() As Boolean If String.IsNullOrEmpty(txtNewListItemName_TextBox.Text) Then Return False End If For i = 0 To flpListItems_FlowLayoutPanel.Controls.Count - 1 Dim listItem As ListItem_UserControl = flpListItems_FlowLayoutPanel.Controls(i) If listItem.ItemName.Equals(txtNewListItemName_TextBox.Text) Then Return False End If Next If IsNothing(lbxLists_ListBox.SelectedIndex) Then Return False End If Return True End Function ' Get New List Item Name Error Message Private Function GetNewListItemNameErrorMessage() As String If String.IsNullOrEmpty(txtNewListItemName_TextBox.Text) Then Return "Please provide a name for the new list item." End If If IsNothing(lbxLists_ListBox.SelectedIndex) Then Return "Please select a list before adding a new item." End If Return "That item already exists in this list." End Function Private Sub tabsMain_TabControl_TabIndexChanged(sender As Object, e As System.EventArgs) Handles tabsMain_TabControl.TabIndexChanged If tabsMain_TabControl.TabIndex.Equals(0) Then Me.AcceptButton = btnCalculatePayStub_Button End If End Sub Private Sub txtNewListName_TextBox_GotFocus(sender As Object, e As System.EventArgs) Handles txtNewListName_TextBox.GotFocus Me.AcceptButton = btnAddList_Button End Sub Private Sub txtNewListName_TextBox_LostFocus(sender As Object, e As System.EventArgs) Handles txtNewListName_TextBox.LostFocus Me.AcceptButton = Nothing End Sub Private Sub txtNewListItemName_TextBox_GotFocus(sender As Object, e As System.EventArgs) Handles txtNewListItemName_TextBox.GotFocus Me.AcceptButton = btnAddListItem_Button End Sub Private Sub txtNewListItemName_TextBox_LostFocus(sender As Object, e As System.EventArgs) Handles txtNewListItemName_TextBox.LostFocus Me.AcceptButton = Nothing End Sub Private Sub lbxLists_ListBox_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles lbxLists_ListBox.SelectedIndexChanged flpListItems_FlowLayoutPanel.Controls.Clear() Dim db As New PaycheckEstimator_DataClassesDataContext If Not TypeOf (lbxLists_ListBox.SelectedValue) Is Paycheck_Esitmator.List Then Dim listOfListItems As List(Of ListItem) = GetListOfListItems(lbxLists_ListBox.SelectedValue) Dim listOfListItemControls As New List(Of ListItem_UserControl) For i = 0 To listOfListItems.Count - 1 listOfListItemControls.Add(New ListItem_UserControl(lbxLists_ListBox.SelectedValue, listOfListItems(i).Name, listOfListItems(i).Amount, listOfListItems(i).Quantity, listOfListItems(i).IsComplete)) Next flpListItems_FlowLayoutPanel.Controls.AddRange(listOfListItemControls.ToArray) End If End Sub Private Function GetListOfLists() As List(Of List) Dim db As New PaycheckEstimator_DataClassesDataContext Return New List(Of List)(From l In db.Lists _ Select l).ToList() End Function Private Function GetListOfListItems(ByVal idList As Guid) As List(Of ListItem) Dim db As New PaycheckEstimator_DataClassesDataContext Return New List(Of ListItem)(From li In db.ListItems _ Where li.ListID.Equals(idList) _ Select li).ToList() End Function Private Function CreateList() As List Return New List With { .ID = Guid.NewGuid(), .Name = txtNewListName_TextBox.Text, .PaystubID = Guid.Empty } End Function Private Sub InsertList(ByVal lst As List) Dim db As New PaycheckEstimator_DataClassesDataContext db.Lists.InsertOnSubmit(lst) Try db.SubmitChanges() Catch ex As Exception Console.WriteLine(ex) Close() End Try End Sub End Class
Imports DevExpress.ExpressApp.Model Imports GenerateUserFriendlyId.Module.Utils Imports System.ComponentModel Namespace GenerateUserFriendlyId.Model Public Interface IModelSequence Inherits IModelNode, ISequence <Browsable(False)> Property Sequence As Sequence '<Category("Design")> '<Description("Required. Specifies the current User friendly identifier.")> '<ModelPersistentName("ID")> 'Property Id As String '<ModelValueCalculator("((IModelUFIds)this.Parent).DefaultKeyTemplate")> 'Property KeyTemplate As String '<ModelValueCalculator("((IModelUFIds)this.Parent).DefaultStartValue")> 'Property StartValue As Integer '<ModelValueCalculator("((IModelUFIds)this.Parent).DefaultStep")> 'Property [Step] As Integer '<ModelValueCalculator("((IModelUFIds)this.Parent).DefaultTemplate")> 'Property Template As String '<ModelValueCalculator("((IModelUFIds)this.Parent).DefaultThroughNumeration")> 'Property ThroughNumeration As Boolean '<ModelValueCalculator("((IModelUFIds)this.Parent).DefaultUseDeletedNumbers")> 'Property UseDeletedNumbers As Boolean End Interface End Namespace
 Imports System.Text Imports System.Data Imports System.Data.SqlClient Imports System.Transactions Imports System.Configuration.ConfigurationSettings Imports System.Collections.Generic Public Class TCheckMsBC Public DA AS NEW TCheckMsDA ''' <summary> ''' ''' 检查结果Infoを検索する ''' </summary> '''<param name="chkNo_key">检查No</param> ''' <returns>检查结果Info</returns> ''' <remarks></remarks> ''' <history> ''' <para>2019/01/07 作成者:李さん 新規作成 </para> ''' </history> Public Function SelTCheckMs(Byval chkNo_key AS String) As Data.DataTable 'SQLコメント Return DA.SelTCheckMs( _ chkNo_key) End Function ''' <summary> ''' ''' 检查结果Infoを更新する ''' </summary> '''<param name="chkNo_key">检查No</param> '''<param name="chkNo">检查No</param> '''<param name="chkMethodId">检查项目ID</param> '''<param name="chkFlg">检查flg</param> '''<param name="in1">入力値1</param> '''<param name="in2">入力値2</param> '''<param name="chkResult">检查结果</param> '''<param name="mark">备考</param> '''<param name="kj0">基准</param> '''<param name="kj1">工差1</param> '''<param name="kj2">工差2</param> '''<param name="kjExplain">基准説明</param> '''<param name="insUser">登録者</param> '''<param name="insDate">登録日</param> ''' <returns>检查结果Info</returns> ''' <remarks></remarks> ''' <history> ''' <para>2019/01/07 作成者:李さん 新規作成 </para> ''' </history> Public Function UpdTCheckMs(Byval chkNo_key AS String, _ Byval chkNo AS String, _ Byval chkMethodId AS String, _ Byval chkFlg AS String, _ Byval in1 AS String, _ Byval in2 AS String, _ Byval chkResult AS String, _ Byval mark AS String, _ Byval kj0 AS String, _ Byval kj1 AS String, _ Byval kj2 AS String, _ Byval kjExplain AS String, _ Byval insUser AS String, _ Byval insDate AS String) As Boolean 'SQLコメント '--**テーブル:检查结果 : t_check_ms Return DA.UpdTCheckMs( _ chkNo_key, _ chkNo, _ chkMethodId, _ chkFlg, _ in1, _ in2, _ chkResult, _ mark, _ kj0, _ kj1, _ kj2, _ kjExplain, _ insUser, _ insDate) End Function ''' <summary> ''' ''' 检查结果Infoを登録する ''' </summary> '''<param name="chkNo">检查No</param> '''<param name="chkMethodId">检查项目ID</param> '''<param name="chkFlg">检查flg</param> '''<param name="in1">入力値1</param> '''<param name="in2">入力値2</param> '''<param name="chkResult">检查结果</param> '''<param name="mark">备考</param> '''<param name="kj0">基准</param> '''<param name="kj1">工差1</param> '''<param name="kj2">工差2</param> '''<param name="kjExplain">基准説明</param> '''<param name="insUser">登録者</param> '''<param name="insDate">登録日</param> ''' <returns>检查结果Info</returns> ''' <remarks></remarks> ''' <history> ''' <para>2019/01/07 作成者:李さん 新規作成 </para> ''' </history> Public Function InsTCheckMs(Byval chkNo AS String, _ Byval chkMethodId AS String, _ Byval chkFlg AS String, _ Byval in1 AS String, _ Byval in2 AS String, _ Byval chkResult AS String, _ Byval mark AS String, _ Byval kj0 AS String, _ Byval kj1 AS String, _ Byval kj2 AS String, _ Byval kjExplain AS String, _ Byval insUser AS String, _ Byval insDate AS String) As Boolean 'SQLコメント '--**テーブル:检查结果 : t_check_ms Return DA.InsTCheckMs( _ chkNo, _ chkMethodId, _ chkFlg, _ in1, _ in2, _ chkResult, _ mark, _ kj0, _ kj1, _ kj2, _ kjExplain, _ insUser, _ insDate) End Function ''' <summary> ''' ''' 检查结果Infoを削除する ''' </summary> '''<param name="chkNo_key">检查No</param> ''' <returns>检查结果Info</returns> ''' <remarks></remarks> ''' <history> ''' <para>2019/01/07 作成者:李さん 新規作成 </para> ''' </history> Public Function DelTCheckMs(ByVal chkNo_key As String) As Boolean 'SQLコメント '--**テーブル:检查结果 : t_check_ms Return DA.DelTCheckMs( _ chkNo_key) End Function Public Function SelTCheckMs(ByVal chkNo_key As String, ByVal line_id As String) As Data.DataTable Return DA.SelTCheckMs(chkNo_key, line_id) End Function Public Function UpdTCheckMs(ByVal chkNo_key As String, _ ByVal in1 As String, _ ByVal chkResult As String, _ ByVal mark As String, _ ByVal kj0 As String, _ ByVal kj1 As String, _ ByVal kj2 As String, _ ByVal insUser As String, _ ByVal line_id As String, ByVal chk_method_id As String) As Boolean Return DA.UpdTCheckMs(chkNo_key, _ in1, _ chkResult, _ mark, _ kj0, _ kj1, _ kj2, _ insUser, _ line_id, chk_method_id) End Function Public Function UpdTCheckResultMS(ByVal chkNo_key As String, _ ByVal line_id As String, ByVal insUser As String) As Boolean DA.UpdTCheckResultMS(chkNo_key, line_id, insUser) Return True End Function Public Function UpdTCheckResultMSWanliao(ByVal chkNo_key As String, _ ByVal line_id As String) As Boolean DA.UpdTCheckResultMSWanliao(chkNo_key, line_id) Return True End Function End Class
Class MainWindow Sub RunCode(sender As Object, e As RoutedEventArgs) ''''''''''''''''''''' Output("For Loop") For count As Integer = 0 To 3 Output("For Count: " + count.ToString()) Next Output(vbCrLf) ''''''''''''''''''''' Output("While Loop") Dim whileCount As Integer = 1 While whileCount <= 3 Output("While Count: " + whileCount.ToString()) whileCount += 1 End While Output(vbCrLf) ''''''''''''''''''''' Output("Do Loop") Dim doCount As Integer = 1 Do Output("Do While Count: " + doCount.ToString()) doCount += 1 Loop Until doCount > 3 Output(vbCrLf) ''''''''''''''''''''' Output("Infinite do") doCount = 1 Do Output("Do While Count: " + doCount.ToString()) doCount += 1 If doCount > 3 Then Exit Do End If Loop Output(vbCrLf) ''''''''''''''''''''' Output("For Each Loop") Dim numbers As Integer() = {1, 3, 5} For Each i In numbers Output("For Each Count: " + i.ToString()) Next Output(vbCrLf) End Sub Sub Output(Value As String) txtOutput.Text += Value + vbCrLf End Sub Sub ClearOutput(sender As Object, e As RoutedEventArgs) txtOutput.Text = "" End Sub End Class
Imports System.ComponentModel.DataAnnotations Public Class clsAccountActivityInfo Inherits clsAccountActivity Property Id As Integer Property EntryIndex As Integer ReadOnly Property ActivityTypeText As String Get Return Me.ActivityType.ToString End Get End Property End Class Public Class clsAccountActivity Inherits EskimoBaseClass Implements IValidatableObject Enum AccountActivityTypeEnum ''' <summary> ''' Used to set the initial balanace for a customer. Useful if bringing data across from another system. ''' </summary> OpeningBalance = 0 ''' <summary> ''' Driven by the CustomerAccountValuePaid field when using the endpoint POST api/Orders/Insert ''' </summary> Sale = 1 ''' <summary> ''' Any payments into the customer's account ''' </summary> Payment = 2 ''' <summary> ''' Any manual adjustments to increment the balance to what it should be. ''' </summary> AdjustmentCredit = 3 ''' <summary> ''' Any manual adjustments to decrement the balance to what it should be. ''' </summary> AdjustmentDebit = 4 End Enum <EnumDataType(GetType(AccountActivityTypeEnum))> <Required> Property ActivityType As AccountActivityTypeEnum <Required> Property ActivityDate As DateTime Property BalanceBefore As Decimal <Required> Property Amount As Decimal Property BalanceAfter As Decimal <Required> <StringLength(10, ErrorMessage:=clsCustomer.CustomerLengthMsg, MinimumLength:=10)> <RegularExpression(clsCustomer.CustomerIDFormat)> <ValidCustomer> Property CustomerID As String Property Till As Integer? Property Receipt As Integer? Property InvoiceId As Integer? Property WebOrderId As Integer? Property OrderExternalId As String Public Function Validate(validationContext As ValidationContext) As IEnumerable(Of ValidationResult) Implements IValidatableObject.Validate Dim lst As New List(Of ValidationResult) 'Select Case Me.ActivityType ' Case AccountActivityTypeEnum.OpeningBalance ' Case Else ' If Me.Amount < 0 Then ' lst.Add(New ValidationResult("The Amount must be a positive number")) ' End If 'End Select Return lst End Function End Class