How can I make my licence works only one year? When I activated my program I add registry with current date. On each run I check if the registry exist. If registry exists I can use my application otherwise it prompt me to activate it .
I want to make that my licence works only one year.
I tried with
Public Sub Licence_Check()
Dim licenca As Date
Dim days As Integer
licenca = CDate(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\tFull", "tFull", Nothing))
days = CInt(365 - (DateDiff(DateInterval.Day, licenca, Now)))
If days <= 0 Then
My.Computer.Registry.CurrentUser.DeleteValue("tFull")
pbInfo.Value = pbInfo.Maximum
gpbInfo.Text = "One year Licence OVER"
RbContinue.Enabled = False
End If
End Sub
I have already warned you about the weakness of this approach, but this is how you could write the above License_Check
Public Sub Licence_Check()
Dim licenca As Date
Using tempKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppNameHere", true)
licenca = CDate(tempKey.GetValue("InstallDate", Nothing))
Dim limit = licenca.AddYears(1)
if limit < DateTime.Today
tempKey.DeleteValue("InstallDate")
Console.WriteLine ("One year Licence OVER")
End If
End Using
End Sub
Notice that you should store your application info in a subkey of the SOFTWARE subkey and not directly under the root HKEY_CURRENT_USER. Then you need to open the appropriate subkey asking for the write permissions and finally read the value desidered.
To check the dates just add 1 year to the value read and do the check against Today.
To delete you should use the DeleteValue method of the opened subkey.
Also I suppose that this is not a check that should be applied on a user by user base. Instead it is a check that could be applied to the whole application. In this case you should use the predefined My.Computer.Registry.LocalMachine registry key.
Related
I am currently trying to write a VBA code that will look at a project plan and delete all of the tasks that have zero work effort, but are not a milestone, from my plan. We have added a custom field called Key Milestone to capture whether a task is a milestone or not. The reason we are not using the existing Milestone field is that not all of the tasks with zero work effort and zero duration are necessarily milestones.
I was previously unfamiliar with the GetField function in VBA and I have been working through a couple of tries at incorporating this to 'read' the custom field as a part of this code. Here is what I have so far:
Sub DeleteMsProjectTask()
Dim proj As Project
Dim t As Task
Set proj = ActiveProject
For Each t In proj.Tasks
If t.OutlineLevel > 1 And t.Work = 0 Then
If GetField(FieldNametoFieldConstant("Key Milestone") = Yes Then
Else
t.Delete
End If
End If
Next t
End Sub
This is not working as it doesn't read the milestone field correctly. Thanks in advance for the help!
GetField is a method of the Task object, so you need to preface it with your task object variable, e.g. t.GetField. Also, you missed a closing parentheses. And since GetField returns a string, you need to compare to a string--in other words, the word Yes needed to be in quotes. Since the criteria for deletion was actually a "No" value, I simplified your code accordingly.
Sub DeleteMsProjectTask()
Dim proj As Project
Dim t As Task
Set proj = ActiveProject
For Each t In proj.Tasks
If t.OutlineLevel > 1 And t.Work = 0 Then
If t.GetField(FieldNameToFieldConstant("Key Milestone")) = "No" Then
t.Delete
End If
End If
Next t
End Sub
I have number of split forms in an Access 2016 database which are regularly used by various employees for data entry. It is important that users are able to see old records but are not able to edit them.
However, I want to allow users to edit records that have been made that day in case they notice an error in a record they have just entered.
My current approach is to set the AllowEdits property on the form to yes, then to override it for entries made on the same day with the following code
Private Sub Form_Load()
If (Me![rec_date] < Now()) Then
Me.AllowEdits = False
Else: Me.AllowEdits = True
End If
End Sub
I think there is a problem with the If criteria though, as all this currently does is prevent editing of all records.
For background [rec_date] refers to the date on which the record was entered.
Couple of things:
Use the "Current" event instead if you're working with record changes. Form Load only works when the form itself opens. If you change records it will do nothing for you.
Might as well move that Else statement down to the next line and indent correctly for readability.
Your conditional statement doesn't quite match what you told me. You're trying to match a specific day but you use a date time (now()) instead of date. You also use less than instead of equals. I would suggest using equals and the date function (note: doesn't use () and returns only the date portion of now() ).
Hopefully that helps! Here's my suggested code:
Private Sub Form_Current()
' Only allow editing of records created today.
If (Me![rec_date] = Date) Then
Me.AllowEdits = True
Else
Me.AllowEdits = False
End If
End Sub
An even shorter form as suggested by Mat's Mug
Private Sub Form_Current()
Me.AllowEdits = Me![rec_date] = Date ' Only allow editing of records created today.
End Sub
While I have my app running, I question the methodology, and wondering if there’s a “better way”…
Overall design is to allow editing 200-300 records from a gridview (phase1) using VB.Net. The database itself is on SQL Server. There are a number of columns a user will enter into an “application”, and there are several columns that will be edited/maintained by “office users”, if you will. There are several dates involved in this ongoing maintenance, and that’s where the first of my questions revolves.
I have found “solutions” on the internet that got the code working, but am questioning them…
Problem #1 I ran into – dates are NULL in the database, and in trying to read them in using a SqlDataReader led to errors (cannot assign NULL to a Date object). Ok, that led into using a ternary operator to use “IsDBNull”, and either assign the value read from the DB, or to assign DateTime.MinValue. Problem “solved”…
Problem #2 – using the above method now shows dates that are the minimum VB date value – showing actual dates in the fields the user is to edit – definitely not “user friendly”, nor what I want. The only solution to this issue was:
Convert dates from Date or DateTime objects into String objects. This would then allow me to be able to assign an empty string to the gridview in the case where the date was originally NULL in the DB, which had to be transformed into DateTime.MinValue (which could be tested), and then another ternary operator to assign either “ToString” conversion, or an empty string to the gridview field.
Ok – editing is now accomplished. I added some “ScriptManager.RegisterStartupScript” commands to allow testing the validity of the dates the user enters – all is well.
Problem #3 (or 4) – I now need to update the database with the data the user entered – PRESERVING THE EMPTY DATE STRINGS – and update the database (using parameters…) with NULLs back in those date columns. However, again – the date is a string, and is empty, so I had to assign to a “MinValue”, first, then another ternary operator to test each date against “MinValue”, and either assign the date, or a DBNull.Value…
Yes, I guess I could have come up with a number of different update strings (including dates in some, excluding in others), depending on whether or not a string/date was empty or not... But that will only lead to future bugs, so, I guess I’ll be keeping a series of ternary operators.
So, the code for beginning the edit process looks something like:
While sdr.Read
Dim _date1 As Date = If(IsDBNull(sdr("date1")), DateTime.MinValue, sdr("date1"))
.
.
.
‘ Now add them to a List of my Class:
appsList.Add(New AppClass(… _
If(_date1 = DateTime.MinValue, " ", _date1.ToString("MM/dd/yyyy")), _
… )
Now to get the data back from the gridview to update the database:
Dim _date1 As Date
' see if we can convert the various dates...
Try
' see if empty…
If ((CType((row.Cells(19).Controls(0)), TextBox)).Text).Length < 2 Then
_date1 = DateTime.MinValue
Else
_date1 = DateTime.Parse((CType((row.Cells(19).Controls(0)), TextBox)).Text)
End If
Catch ex As Exception
ErrFlag = True
ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "alert(‘Date1 Date is not valid - enter as MM/DD/YYYY');", True)
End Try
.
.
.
Dim sql As String = "UPDATE [foo_bar].[dbo].[bar_foo] set date1=#Date1, …….)
cmd.Parameters.AddWithValue("#Date1", If(_date1 = DateTime.MinValue, DBNull.Value, _date1))
Honestly, all this conversion back and forth seems like it’s going to lead to bugs or errors at some point.
So – is this the “best” method for handling this? There isn’t a cleaner way?
If your using winforms then you can handle the Format and parse of the databindings. I haven't tried it on a Gridviewtextbox but worst case you can use a custom cell template and a textbox with format and parse handlers. The code would be something like this:
mybinding = New Binding("text", DataSet1, "table1.datefield")
Me.DataGridTextBoxColumn1.TextBox.DataBindings.Add(mybinding)
AddHandler mybinding.Parse, AddressOf StringToDateTime
AddHandler mybinding.Format, AddressOf formatdate
Private Sub StringToDateTime(ByVal sender As Object, ByVal cevent As ConvertEventArgs)
If cevent.Value.GetType().Equals(GetType(String)) And _
cevent.DesiredType Is GetType(DateTime) Then
If cevent.Value <> "" Then
' Make sure matches format in format funtion
cevent.Value = DateTime.Parse(String.Format(cevent.Value, "MMM d, yy"))
Else
cevent.Value = DBNull.Value
End If
'cevent.Value = DateTime.Parse(String.Format(cevent.Value, "MMM d yyyy")
End If
End Sub
Public Sub formatdate(ByVal sender As Object, ByVal e As ConvertEventArgs)
If e.Value.GetType().Equals(GetType(DateTime)) And e.DesiredType Is GetType(String) Then
' Hard-coded or user-specified
' Make sure matches format in parse funtion
e.Value = Format(e.Value, "d")
End If
End Sub
Sub change_the_time(ByVal NewDateTime As DateTime)
'
Dim NewDateTime2 As DateTime
'
NewDateTime2 = #5/1/2016 5:52:15 PM# ' try setting the time to this
'
'set the system date and time to this date and time - throw an exception if it can't
Try
TimeOfDay = NewDateTime2
Catch ex As Exception
MessageBox.Show("Could not set time. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
End Try
End Sub
Hi.
New to the site so hopefully I follow the rules :-)
My questions is how do I successfully change the system time? The above code I found on this site (as well as much info on other parts of my project - thank you!) and there are no errors, but it always throws an exception. I run as admin and I've tried changing the UAC and I still can't change the time. I read that I need to have the SE_SYSTEMTIME_NAME privilege set, but I have this set so that all users (ie me) have the right, still nothing. The MS reference here does not provide much insight. I suspect it's an issue with privileges, but i can't seem to see how to set what i need. What do I need to do to allow my application to change the system time to a value?
More info...there is another question along the same lines, but it's c# not Vb and I've tried something similar to that code, which is below. Still
Private Sub change_the_time2(ByRef NewDateTime As DateTime)
Dim d As DateTime
d = #6/10/2011# ' try setting the date to this before using NewDateTime
Dim worked As Boolean
'
Try
worked = setlocaltime(d)
MsgBox(" 1. Did it work " & worked)
Catch ex As Exception
MsgBox(" 2. Did it work " & worked)
End Try
End Sub
<DllImport("kernel32.dll", setLastError:=True)> _
Private Shared Function setlocaltime(ByRef time As System.DateTime) As Boolean
End Function
This is essentially a duplicate of this question as has been mentioned in the comments. But to clarify for VB.NET as oposed to C#, per one of the answers in that question:
On Windows Vista, 7, 8 OS this will require a UAC Prompt in order to
obtain the necessary administrative rights to successfully execute the
SetSystemTime function.
The reason is that calling process needs the
SE_SYSTEMTIME_NAME privilege. The SetSystemTime function is expecting
a SYSTEMTIME struct in coordinated universal time (UTC). It will not
work as desired otherwise.
Depending on where/ how you are getting
your DateTime values, it might be best to play it safe and use
ToUniversalTime() before setting the corresponding values in the
SYSTEMTIME struct.
Code example (modified for VB.NET):
Dim tempDateTime As DateTime = GetDateTimeFromSomeService()
Dim dateTime As DateTime = tempDateTime.ToUniversalTime()
Dim st As SYSTEMTIME
'All of these must be short
st.wYear = dateTime.Year.ToInt16()
st.wMonth = dateTime.Month.ToInt16()
st.wDay = dateTime.Day.ToInt16()
st.wHour = dateTime.Hour.ToInt16()
st.wMinute = dateTime.Minute.ToInt16()
st.wSecond = dateTime.Second.ToInt16()
// invoke the SetSystemTime method now
SetSystemTime(ByRef st)
Yes, you need Administrator privileges.
Using VB.net, create a new class called staff, with three properties:
Name , LastName, ID - should be suitable for use as a primary key in a database.
Provide a class constructor to populate Name and LastName. ID should be auto-generated within the constructor and should not be passed in.
I know how to create a class, properties and constructor, I just need to know how to auto-generate ID field within the constructor. Is it possible to do this?
what I usually do is either make the id field in database as identity field and primary key so it automatically inserts the next available id or In my application I read the last ID from database and add one to it. But I need to know how to auto-generate ID field within the constructor.
Guid
If you do not have any constrain about ID type you can use a GUID:
Dim id As Guid = Guid.NewGuid()
You may even keep it as string:
Dim id As String = Guid.NewGuid().ToString("N")
That should be granted to be unique across different machines (to satisfy your requirement that it has to be suitable for use as a primary key in a database). See also this post.
Timestamp
That was worse case, if you do not have such strict requirement (uniqueness across a network) you may use a timestamp. Of course, in this case, you have to consider more issues:
Legal time: time goes back and forward twice per year.
Zones: what if user enter data in London and then he moves to New York?
Concurrency: you have to assume no one else adds records to your database (you may have collisions if they use a different technique). Also you can't apply this if execution is concurrent (multiple instance of your program running together).
Timer granularity: system date has a coarse granularity: if you construct many objects in a short period of time then you may have duplicate IDs. Workaround in this post.
Counter
If all these conditions are satisfied:
Multiple instances of your application won't run in parallel.
You're working on a single computer (not a network).
Database is empty every time your application starts.
You may use a Shared counter incremented each time a new object is constructed. If system timer granularity isn't an issue (see paragraph about timestamp)you may use system up time as ID. With limitations about granularity it should work even with multiple instances of the same application running concurrently.
If you use a Shared field you have to deal with synchronization issues. As suggested in this comment you may use a SyncLock. As alternative you may use an Interlocked.Increment operation.
Hash code
If all condistions for a counter are satisfied and this one also:
Your application is 32 bit.
Your object is not a ValueType and it doesn't override GetHashCode() method.
You can use hash-code (obtained with GetHashCode()) because (from MSDN):
In other words, two objects for which the ReferenceEquals method returns true have identical hash codes.
Because Object.ReferenceEquals() returns true only if you compare same instance then each instance will have a unique hash code (because in a 32 bit application hash code is object reference itself). Be aware this is an implementation detail and it may change.
Random number
I know this may shock someone but a good random number generator for a 64 bit value has a very low probability of collisions. I repeat very very low probability (see this article for more math details). Just do not use System.Random for this!
According to which seed you use you may be able to generate random numbers in a network scenario too (do not forget - citation needed - that earlier drafts for one local network protocol proposed a 32 bit random number as address, it has been changed because of bad feedback from users but it doesn't mean it can't work).
You want a number that won't repeat ever! So why not just use this?
Dim dateAndTime As Date
dateAndTime = Now
TextBoxPID.Text = Format(dateAndTime, "yyyyMMddHHmmss").ToString
Unless your data entries are going to take place in milliseconds, this solution works great. If you are running into a millisecond issue then just add a counter to the end of the string.
counter +=1
TextBoxPID.Text = Format(dateAndTime, "yyyyMMddHHmmss").ToString & counter.ToString
If you are working on a network and have several people doing data entry then add their employee id to the string. There are easy solution to every issue, but in most, if not all cases, this will work without issue.
Generate Random Unique User ID depending on SNTP server.
My requirements are a bit different; yet I needed to generate a random and unique User ID, that is 10 numbers, spending fair time couldn't find a suitable solution.
so I ended up with the following function; its unique and random result.
As per one application instant on one test machine it is incremental unique result; because the user will generate the ten digits one time on a non pre-selective timestamp. In addition to playing with the random alpha prefix; I hope this function can provide a solution:
Imports System.Globalization
Imports System.Net
Public Class GetNetTime
Public Shared Function GetUTC()
' connect to google servers
' you could use some SNTP time servers but can't be sure port will be open
' or you could just ping your own webserver
Dim myNetRequest As WebRequest = HttpWebRequest.Create("http://www.example.com")
' read response header from connection
Dim response = myNetRequest.GetResponse()
' read date/time header
' assume its UTC format
Dim GlobalUTC As String = response.Headers("date").ToString
' convert string to datetime object
Dim parsedDateTime As DateTime = DateTime.Parse(GlobalUTC)
' get UNIX time stamp
Dim unixTime = (parsedDateTime - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
Return unixTime
End Function
End Class
To test the output, you could add:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim utc As String = GetNetTime.GetUTC
' add random alpha prefix to UNIX time stamp
Dim sPrefix As String = ""
Dim rdm As New Random()
For i As Integer = 1 To 3 ' if you need more than 3 alpah random charachters adjust i length
sPrefix &= ChrW(rdm.Next(65, 90))
Next
MsgBox(sPrefix & utc) ' OR MsgBox("ID" & sPrefix & utc)
' code here to use result
End Sub
I find this solution more useful than querying the SQL table and read last record id and do increment.
Notes:
Please don't mind long answer; as I tried to comment the code and
explain the scenario in details.
I think this is good for generating
UserID for application running on multiple workstations.
Please don't put the function in for ... loop or exhaust run it.
Output examples:
GYK1501270543
VWT1501270606
WRH1501270634
SKI1501270648
QXL1501270716
This is also based on #wpcoder answers above but a basic form and this one works for me
Public Function UIDGen(ByRef f As String) As String
Dim currentTime As DateTime = DateTime.UtcNow
Dim StringTime As String = currentTime.ToString
Dim parsedDateTime As DateTime = DateTime.Parse(StringTime)
Dim unixTime = (parsedDateTime - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
Dim utcString As String = unixTime.ToString
Dim sPrefix As String = ""
Dim rdm As New Random()
For i As Integer = 1 To 3 ' 3 Letters enough ?
sPrefix &= ChrW(rdm.Next(65, 90))
Next
f = (sPrefix & utcString)
Return f
End Function