I'm trying to get started with Fedex'es Address validation service and I'm running into a road block with FedEx's own demo application.
This is the code in there app:
Sub Main()
''# Build a AddressValidationRequest object
Dim request As AddressValidationRequest = New AddressValidationRequest()
Console.WriteLine("--- Setting Credentials ---")
request.WebAuthenticationDetail = New WebAuthenticationDetail()
request.WebAuthenticationDetail.UserCredential = New WebAuthenticationCredential()
request.WebAuthenticationDetail.UserCredential.Key = "###" ''# Replace "XXX" with the Key
request.WebAuthenticationDetail.UserCredential.Password = "###" ''# Replace "XXX" with the Password
Console.WriteLine("--- Setting Account Information ---")
request.ClientDetail = New ClientDetail()
request.ClientDetail.AccountNumber = "###" ''# Replace "XXX" with clients account number
request.ClientDetail.MeterNumber = "###" ''# Replace "XXX" with clients meter number
request.TransactionDetail = New TransactionDetail()
request.TransactionDetail.CustomerTransactionId = "Address Validation v2 Request using VB.NET Sample Code" ''# This is just an echo back
request.Version = New VersionId()
request.RequestTimestamp = DateTime.Now
Console.WriteLine("--- Setting Validation Options ---")
request.Options = New AddressValidationOptions()
request.Options.CheckResidentialStatus = True
request.Options.MaximumNumberOfMatches = 5
request.Options.StreetAccuracy = AddressValidationAccuracyType.LOOSE
request.Options.DirectionalAccuracy = AddressValidationAccuracyType.LOOSE
request.Options.CompanyNameAccuracy = AddressValidationAccuracyType.LOOSE
request.Options.ConvertToUpperCase = True
request.Options.RecognizeAlternateCityNames = True
request.Options.ReturnParsedElements = True
Console.WriteLine("--- Address 1 ---")
request.AddressesToValidate = New AddressToValidate(1) {New AddressToValidate(), New AddressToValidate()}
request.AddressesToValidate(0).AddressId = "WTC"
request.AddressesToValidate(0).Address = New Address()
request.AddressesToValidate(0).Address.StreetLines = New String(0) {"10 FedEx Parkway"}
request.AddressesToValidate(0).Address.PostalCode = "38017"
request.AddressesToValidate(0).CompanyName = "FedEx Services"
Console.WriteLine("--- Address 2 ---")
request.AddressesToValidate(1).AddressId = "Kinkos"
request.AddressesToValidate(1).Address = New Address()
request.AddressesToValidate(1).Address.StreetLines = New String(0) {"50 N Front St"}
request.AddressesToValidate(1).Address.PostalCode = "38103"
request.AddressesToValidate(1).CompanyName = "FedEx Kinkos"
Dim addressValidationService As AddressValidationService.AddressValidationService = New AddressValidationService.AddressValidationService
''#
Try
''# This is the call to the web service passing in a AddressValidationRequest and returning a AddressValidationReply
Console.WriteLine("--- Sending Request..... ---")
Dim reply As New AddressValidationReply()
reply = addressValidationService.addressValidation(request)
Console.WriteLine("--- Processing request.... ---")
''#This is where I get the error
If (Not reply.HighestSeverity = NotificationSeverityType.ERROR) And (Not reply.HighestSeverity = NotificationSeverityType.FAILURE) Then
If (Not reply.AddressResults Is Nothing) Then
For Each result As AddressValidationResult In reply.AddressResults
Console.WriteLine("Address Id - " + result.AddressId)
Console.WriteLine("--- Proposed Details ---")
If (Not result.ProposedAddressDetails Is Nothing) Then
For Each detail As ProposedAddressDetail In result.ProposedAddressDetails
Console.WriteLine("Score - " + detail.Score)
Console.WriteLine("Address - " + detail.Address.StreetLines(0))
Console.WriteLine(" " + detail.Address.StateOrProvinceCode + " " + detail.Address.PostalCode + " " + detail.Address.CountryCode)
Console.WriteLine("Changes -")
For Each change As AddressValidationChangeType In detail.Changes
Console.WriteLine(change.ToString())
Next
Console.WriteLine("")
Next
End If
Console.WriteLine("")
Next
End If
Else
For Each notification As Notification In reply.Notifications
Console.WriteLine(notification.Message)
Next
End If
Catch e As SoapException
Console.WriteLine(e.Detail.InnerText)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Console.WriteLine("Press any key to quit !")
Console.ReadKey()
End Sub
It seems to send the request object to the web service, but the"reply" object is returned with "Nothing". I could understand if I wrote the code, but good god... they can't even get their own code to work? Has anyone else seen/fixed this problem?
The app shows some tell-tale signs of having been first written in C# and then converted to VB.Net later. Specifically:
Dim request As AddressValidationRequest = New AddressValidationRequest()
Could be shortened to simply:
Dim request As New AddressValidationRequest()
.
If (Not reply.HighestSeverity = NotificationSeverityType.ERROR) And (Not reply.HighestSeverity = NotificationSeverityType.FAILURE) Then
could be written several ways, but at very least I would expect a pure-VB programmer to know of either AndAlso instead of And or <> instead of Not ... = .... Finally:
Dim reply As New AddressValidationReply()
reply = addressValidationService.addressValidation(request)
creates a new object and promptly discards it.
Related
I am trying to create a bot that reads the direct messages using websocket, to avoid the ratelimit.
The problem is I don`t know much about websocket.
I googled a bit and I found some code and I used it but it don't receive anything but empty text.
This is my code
Dim ws = New System.Net.WebSockets.ClientWebSocket
ServicePointManager.ServerCertificateValidationCallback = Function(s, c, h, d) True
With ws.Options
.SetRequestHeader("Origin", "https://www.instagram.com")
.SetRequestHeader("Cookie", "don`t care about this")
End With
Try
Await ws.ConnectAsync(New Uri("wss://edge-chat.instagram.com/chat"), Nothing)
Console.WriteLine("state: " & ws.State.ToString)
If (ws.State = WebSockets.WebSocketState.Open) Then
Console.WriteLine("state: " & ws.State.ToString)
Dim bytes(4096) As Byte
Dim answ = New ArraySegment(Of Byte)(bytes)
Await ws.ReceiveAsync(answ, Nothing)
Console.WriteLine("answer:" + Text.Encoding.UTF8.GetString(answ.Array))
Else
Console.WriteLine("Not opened?!")
End If
Catch e As Exception
Console.WriteLine("Error." & e.Message)
End Try
Console.ReadLine()
End Function
I see the request in the httpdebugger but I don't know why I don't get any data.
Is the problem in my code or have I misunderstood websocket.
I am trying to create 100 printer ports using a csv file that has IPAddress. I am spinning through this file using VB 2008 and then calling a function to create the port. The first port gets created fine but when program gets second address and passes it to function gets an unspecified error.
call to the function
MakePort("IP_" & ln, ln)
Private Function MakePort(ByVal lPrinterName As String, ByVal _ lHostAddress As String)
Dim res As Boolean = False
Dim objWMIService As WbemScripting.SWbemServices = GetObject("winmgmts:")
Dim objNewPort = objWMIService.Get("WIN32_TCPIPPrinterPort").SpawnInstance_
Try
objNewPort.Name = lPrinterName
objNewPort.Protocol = 1
objNewPort.HostAddress = lHostAddress
objNewPort.PortNumber = "6101"
objNewPort.SNMPEnabled = False
objNewPort.Put_()
res = True
Catch ex As Exception
res = False
MsgBox(ex.Message)
End Try
objNewPort.Name = ""
objNewPort.Protocol = ""
objNewPort.HostAddress = ""
objNewPort.PortNumber = ""
objNewPort = Nothing
objWMIService = Nothing
Return res
End Function
On the Line objNewPort.Name = lPrinterName in second pass is where the Unspecified Error occurs.
Looking to save someone time by not having them manually type in the ports
This actually worked for me. Powershell script.
$PrinterList=get-content C:\scripts\printers.csv
FOREACH ($ip in $PrinterList) {
Print $I $port=[wmiclass]"Win32_TcpIpPrinterPort"
$port.psbase.scope.options.EnablePrivileges=$true
$newPort=$port.CreateInstance()
$newport.name="$ip"
$newport.Protocol=1
$newport.HostAddress=$ip
$newport.PortNumber="6101"
$newport.SnmpEnabled=$false
$newport.Put()
}
I'm writing some software to import a CSV file into Active Directory (to create user accounts). At some point I know it was working perfectly importing multiple accounts. I'm not sure what I've changed as it's been a while since I last worked on it. But it now imports 2 accounts successfully and then crashes on the line below during the third loop iteration (however the third account is still created):
newUser.Save()
When it crashes I get the error "vshost32.exe has stopped working". I then enabled native code debugging and now get this error: "0xC0000374: A heap has been corrupted" and InvalidCastException (see immediate window at end of post for full error). For testing I've been deleting and recreating the same accounts. If I don't delete the first three accounts, the principal exists exception is handled and then the program crashes on the 4th iteration, and then the 5th and so on. But it never crashes on the first two. (The data I'm importing is identical except for numbers - E.g. sAMAccountNames: Test1, Test2, Test3 etc)
My Code
Private Sub bwImport_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwImport.DoWork
Dim _worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim beginImport As New StartImport(AddressOf progressForm.StartImport)
Me.Invoke(beginImport, New Object() {dtUsers.Rows.Count})
Dim log As New UpdateLog(AddressOf progressForm.UpdateLog)
'### TO DO: Check that all mandatory columns/attributes are in the DataTable
'### TO DO: Check for duplicate sAMAccountNames, userPrincipalNames and Cononical Names
#If Not Debug Then
Try
#End If
Dim rowNum As Integer = 0 'Keep track of how many accounts have been created
For Each row As DataRow In dtUsers.Rows
Dim newUser As UserPrincipalEx = New UserPrincipalEx(adCtx)
newUser.SamAccountName = row("sAMAccountName")
newUser.SetPassword(row("Password"))
'General Tab (of Template Exporter)
If row.Table.Columns.Contains("initials") Then
newUser.Initials = row("initials")
End If
If row.Table.Columns.Contains("givenName") Then
newUser.GivenName = row("givenName")
End If
If row.Table.Columns.Contains("sn") Then
newUser.Surname = row("sn")
End If
If row.Table.Columns.Contains("displayName") Then
newUser.DisplayName = row("displayName")
End If
If row.Table.Columns.Contains("description") Then
newUser.Description = row("description")
End If
If row.Table.Columns.Contains("physicalDeliveryOfficeName") Then
newUser.Office = row("physicalDeliveryOfficeName")
End If
If row.Table.Columns.Contains("telephoneNumber") Then
newUser.TelephoneNumber = row("telephoneNumber")
End If
If row.Table.Columns.Contains("wWWHomePage") Then
newUser.WebPage = row("wWWHomePage")
End If
'Address Tab (of Template Exporter)
If row.Table.Columns.Contains("streetAddress") Then
newUser.Street = row("streetAddress")
End If
If row.Table.Columns.Contains("postOfficeBox") Then
newUser.POBox = row("postOfficeBox")
End If
If row.Table.Columns.Contains("l") Then 'City
newUser.City = row("l")
End If
If row.Table.Columns.Contains("st") Then 'State/Province
newUser.State = row("st")
End If
If row.Table.Columns.Contains("postalCode") Then
newUser.PostCode = row("postalCode")
End If
'### TO DO: Add country fields
'Account Tab (of Template Exporter)
If row.Table.Columns.Contains("userPrincipalName") Then
newUser.UserPrincipalName = row("userPrincipalName")
End If
If row.Table.Columns.Contains("ResetPassword") Then
If row("ResetPassword").ToString.ToLower = "yes" Then
newUser.ExpirePasswordNow() 'Force the user to change their password at next logon
End If
End If
If row.Table.Columns.Contains("PreventPasswordChange") Then
If row("PreventPasswordChange").ToString.ToLower = "yes" Then
newUser.UserCannotChangePassword = True
End If
End If
If row.Table.Columns.Contains("PasswordNeverExpires") Then
If row("PasswordNeverExpires").ToString.ToLower = "yes" Then
newUser.PasswordNeverExpires = True
End If
End If
If row.Table.Columns.Contains("AccountDisabled") Then
If row("AccountDisabled").ToString.ToLower = "yes" Then
newUser.Enabled = False
Else
newUser.Enabled = True
End If
Else 'Enable the account by default if not specified
newUser.Enabled = True
End If
If row.Table.Columns.Contains("accountExpires") Then
Dim expireyDate As Date
Date.TryParse(row("accountExpires"), expireyDate) 'Try to convert the data from row("accountExpires") into a date
newUser.AccountExpirationDate = expireyDate
End If
'Profile Tab (of Template Exporter)
If row.Table.Columns.Contains("profilePath") Then
newUser.ProfilePath = row("profilePath")
End If
If row.Table.Columns.Contains("scriptPath") Then
newUser.ScriptPath = row("scriptPath")
End If
If row.Table.Columns.Contains("homeDrive") Then
newUser.HomeDrive = row("homeDrive")
End If
If row.Table.Columns.Contains("homeDirectory") Then
newUser.HomeDirectory = row("homeDirectory")
End If
'Telephones Tab (of Template Exporter)
If row.Table.Columns.Contains("homePhone") Then
newUser.HomePhone = row("homePhone")
End If
If row.Table.Columns.Contains("pager") Then
newUser.Pager = row("pager")
End If
If row.Table.Columns.Contains("mobile") Then
newUser.Mobile = row("mobile")
End If
If row.Table.Columns.Contains("facsimileTelephoneNumber") Then
newUser.Fax = row("facsimileTelephoneNumber")
End If
If row.Table.Columns.Contains("ipPhone") Then
newUser.IPPhone = row("ipPhone")
End If
'Organization Tab
If row.Table.Columns.Contains("title") Then
newUser.Title = row("title")
End If
If row.Table.Columns.Contains("department") Then
newUser.Department = row("department")
End If
If row.Table.Columns.Contains("company") Then
newUser.Company = row("company")
End If
rowNum += 1
_worker.ReportProgress(rowNum) 'Update progress dialog
Try
newUser.Save() 'Save the user to Active Directory
Me.Invoke(log, New Object() {"Successfully created " + row("sAMAccountName") + " (" + row("displayName") + ")", frmProgress.LogType.Success})
Catch ex As PrincipalExistsException
Me.Invoke(log, New Object() {"Error creating " + row("sAMAccountName") + " (" + row("displayName") + "). " + ex.Message, frmProgress.LogType.Failure})
Continue For
End Try
'Member Of Tab
If row.Table.Columns.Contains("MemberOf") Then
Dim groups() As String = row("MemberOf").ToString.Split(";")
'Add the user to any specified groups
Dim groupPrincipal As GroupPrincipal
Try 'Try adding group(s)
For Each group As String In groups
groupPrincipal = groupPrincipal.FindByIdentity(adCtx, group) 'Search for the group name, sid, sAMAccountName or display name
If groupPrincipal IsNot Nothing Then
groupPrincipal.Members.Add(newUser) 'Add the user to the group
groupPrincipal.Save()
Else
Me.Invoke(log, New Object() {"Unable to add " + row("sAMAccountName") + " to group: " + group + ". Group not found.", frmProgress.LogType.Failure})
End If
Next
Catch ex As PrincipalExistsException
'### TO DO: Try to get group name in exception
Me.Invoke(log, New Object() {"Error adding " + row("sAMAccountName") + " (" + row("displayName") + ") to " + "group(s). " + ex.Message, frmProgress.LogType.Failure})
End Try
End If
newUser.Dispose() 'Dispose of the newUser object
Next
#If Not Debug Then
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
#End If
End Sub
Immediate Window (When Native Debugging is enabled)
Critical error detected c0000374
First-chance exception at 0x76fbf996 in AD User Importer.exe: 0xC0000374: A heap has been corrupted.
A first chance exception of type 'System.InvalidCastException' occured in System.DirectoryServices.AccountManagement.dll
I think your issue lies in this block:
Try
newUser.Save() 'Save the user to Active Directory
Me.Invoke(log, New Object() {"Successfully created " + row("sAMAccountName") + " (" + row("displayName") + ")", frmProgress.LogType.Success})
Catch ex As PrincipalExistsException
Me.Invoke(log, New Object() {"Error creating " + row("sAMAccountName") + " (" + row("displayName") + "). " + ex.Message, frmProgress.LogType.Failure})
Continue For
End Try
This code handles exceptions but does not dispose newUser before continuing with the next loop iteration.
I recently began to receive similar heap exceptions and after a close examination I realized that I was not disposing my UserPrincipal object. Once I correctly disposed of the object the issue seems to have stopped.
You should wrap your newUser object in a Using block:
For Each row As DataRow In dtUsers.Rows
Using newUser As UserPrincipalEx = New UserPrincipalEx(adCtx)
newUser.SamAccountName = row("sAMAccountName")
newUser.SetPassword(row("Password"))
' ... the remainder of the code
' ... now wrapped in a Using block
End Using
Next
The newUser object will be automatically disposed no matter how the Using block is exited. Because the Using block disposes for you, you can remove the explicit call to newUser.Dispose().
If the Using block is not available in your version of VB.Net then you should wrap the loop in a Try...Finally block and explicitly dispose the newUser in the Finally block.
I update my question here .. Am using a combo box with no of phone numbers .I want to get the phone no one by one in a variable. Now am using the below code to get the combobox values. But still now am getting the following error message System.Data.DataRowView. Please help me to fix this error. am new for vb.net.
My partial code is here ..
For i = 0 To ComboBox1.Items.Count
Dim s As String
s = Convert.ToString(ComboBox1.Items(i))
Next i
you are using an index which is zero based.
change this:
For i = 0 To ComboBox1.Items.Count
to this:
For i = 0 To ComboBox1.Items.Count - 1
This also works!
Dim stgTest = "Some Text"
Dim blnItemMatched As Boolean = False
'-- Loop through combobox list to see if the text matches
Dim i As Integer = 0
For i = 0 To Me.Items.Count - 1
If Me.GetItemText(Me.Items(i)) = stgTest Then
blnItemMatched = True
Exit For
End If
Next i
If blnItemMatched = False Then
Dim stgPrompt As String = "You entered '" & stgTypedValue & "', which is not in the list."
MessageBox.Show(stgPrompt, "Incorrect Entry", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.Text = ""
Me.Focus()
End If
Your problem probably happens here:
s = Convert.ToString(ComboBox1.Items(i))
This doesn't return the value. It returns a string representation of the object at the given index, which in your case apparently is of type System.Data.DataRowView.
You would have to cast ComboBox1.Items(i) to the approbriate type and access its Value. Or, since its a DataRowView, you can access the values throgh the appropriate column names:
Dim row = CType(ComboBox1.Items(i), System.Data.DataRowView)
s = row.Item("column_name")
Nevertheless, first of all you should definitely close and dispose the connection, no matter whether the transaction fails or succeeds. This can be done in a finally block (option 1) or with a using statement (option 2).
Option 1
// ...
con1 = New MySqlConnection(str)
con1.Open()
Try
// ...
Catch ex As Exception
Lblmsg.Text = " Error in data insertion process....." + ex.Message
Finally
con1.Close()
con1.Dispose()
End Try
Option 2
// ...
Using con1 as New MySqlConnection(str)
con1.Open()
Try
// ...
Catch ex As Exception
Lblmsg.Text = " Error in data insertion process....." + ex.Message
Finally
con1.Close()
End Try
End using
Even after long time back you will achieve this with simply by following
For Each item As Object In combx.Items
readercollection.Add(item.ToString)
Next
Please try this
For j As Integer = 0 To CboCompany.Items.Count - 1
Dim obj As DataRowView = CboCompany.Items(j)
Dim xx = obj.Row(0)
If xx = "COMP01" Then
CboCompany.SelectedIndex = j
Exit For
End If
Next
I could not find this answer online in its entirety but pieced it together. In the snippet below cbox is a ComboBox control that has the DisplayMember and ValueMember properties initialized.
Dim itemIE As IEnumerator = cbox.Items.GetEnumerator
itemIE.Reset()
Dim thisItem As DataRowView
While itemIE.MoveNext()
thisItem = CType(itemIE.Current(), DataRowView)
Dim valueMember As Object = thisItem.Row.ItemArray(0)
Dim displayMember As Object = thisItem.Row.ItemArray(1)
' Insert code to process this element of the collection.
End While
I am working for application register form and I would like to know when the user opens the register form I need to check if the current date is true or not and when the user tries to change the system date he should pop up message.So I would like to refresh the form for every second and find whether he has changed the date or not.
How do I do that?
Here is my code:
btnRegister.Enabled = False
Dim oReg As Microsoft.Win32.RegistryKey
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey(kstrRegSubKeyName)
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\" & kstrRegSubKeyName)
Dim strOldDay As String = oReg.GetValue("UserSettings", "").ToString
Dim strOldMonth As String = oReg.GetValue("operatingsystem", "").ToString
Dim strOldYear As String = oReg.GetValue("GUID", "").ToString
Dim strRegName As String = oReg.GetValue("USERID", "").ToString
Dim strRegCode As String = oReg.GetValue("LOCALPATH", "").ToString
Dim strCompID As String = oReg.GetValue("CompID", "").ToString
Dim strTrialDone As String = oReg.GetValue("Enable", "").ToString
oReg.Close()
'If the keys should automatically be created, then create them.
If strOldDay = "" Then
CreateRegKeys(txtPassPhrase.Text)
End If
'If the keys are encrypted, decrypt them.
'If EncryptKeys = True Then
strOldDay = Decrypt(txtPassPhrase.Text, strOldDay)
strOldMonth = Decrypt(txtPassPhrase.Text, strOldMonth)
strOldYear = Decrypt(txtPassPhrase.Text, strOldYear)
'End If
'Define global variables.
mintUsedTrialDays = DiffDate(strOldDay, strOldMonth, strOldYear)
'Fill the progress bar
lblApplicationStatus.Text = DisplayApplicationStatus(DiffDate(strOldDay, strOldMonth, strOldYear), mintTrialPeriod)
'Disable the continue button if the trial is over
If DiffDate(strOldDay, strOldMonth, strOldYear) > mintTrialPeriod Then
'unregbutton.Enabled = False
mblnInTrial = False
btnRemind.Enabled = False
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey(kstrRegSubKeyName)
oReg.SetValue("Enable", "1")
oReg.Close()
End If
If strOldMonth = "" Then
Else
Dim dtmOldDate As Date = New Date(Convert.ToInt32(strOldYear), Convert.ToInt32(strOldMonth), Convert.ToInt32(strOldDay))
If Date.Compare(DateTime.Now, dtmOldDate) < 0 Then
'lblApplicationStatus.Text = DisplayApplicationStatus(mintTrialPeriod, mintTrialPeriod)
lblApplicationStatus.Text = "The system clock has been manually changed, and the application has been locked out to prevent unauthorized access!"
End If
End If
'If the trial is done then disable the button
If strTrialDone = "1" Then
mblnInTrial = False
btnRemind.Enabled = False
lblApplicationStatus.Text = "The system clock has been manually changed, and the application has been locked out to prevent unauthorized access!"
End If
'See if the user is already registered, if so re-process the info and check if the computer is all okay.,
If strRegName = "" Then
Else
Dim strRN As String = Decrypt(txtPassPhrase.Text, strRegName)
Dim strRC As String = Decrypt(txtPassPhrase.Text, strRegCode)
Dim UserName As String = strRegName
UserName = UserName.Remove(16, (UserName.Length - 16))
If UserName = Decrypt(txtPassPhrase.Text, strRegCode) Then
If Encrypt(txtPassPhrase.Text, cHardware.GetMotherBoardID.Trim.ToString) = strCompID Then
mblnInTrial = False
mblnFullVersion = True
strRC = strRC.Insert(4, "-")
strRC = strRC.Insert(8, "-")
strRC = strRC.Insert(12, "-") 'Add dashes to make it look cool
lblApplicationStatus.Text = "Licensed version to " + strRN + " with the key " + strRC
txtVKClientName.Enabled = False
txtKeyToValidate.Enabled = False
txtVKClientName.Text = strRN
txtKeyToValidate.Text = strRC
btnRemind.Text = "Registered"
frmMain.Text = "Aquamark v1.2(Registered)"
btnRegister.Hide()
Me.Close()
frmMain.Show()
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey(kstrRegSubKeyName)
oReg.SetValue("Enable", "")
oReg.Close()
End If
End If
End If
NO, you don't have to "refresh the form for every second and find whether he has changed the date or not. How do I do that", the solution is a lot easier
The windows will send a message to all applications when the data is changed. Listen to that message instead and whenever the data changed do what you want to do so:
//C# sorry I don't know VB but the code is simple and you should convert it without any problem
private DateTime _lastSystemClockChanged = DateTime.MinValue;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x1E://the time is changed.
//to avoid receiving duplicate notification about time changed
if (_lastSystemClockChanged.AddSeconds(1) < DateTime.Now ||
_lastSystemClockChanged > DateTime.Now)
{
_lastSystemClockChanged = DateTime.Now;
//do what ever you want to do when time changed. note you should
//not call a methods that will block here because of you will block
//this message from arriving to other applications then
}
break;
}
base.WndProc(ref m);
}
You could subscribe to the SystemEvents.TimeChanged event, which is fired when the user changes the time on the system clock. Don't forget to detach the event handler when the form closes as this is a static event.
You could store a date in a field and compare the new date to it when the system time is changed, or just disable the app when the event occurs.