How to make a global variable in Visual Basic - vb.net

I have a Mysql login system in Visual Basic , and I want to store the username in a global variable after a succesful login but when the app will close I want that variable to be deleted.. can you show me some example? I'm a beginner at visual basic.

If you're developing on Windows, then use the Windows Registry to persist the value.
See http://msdn.microsoft.com/en-us/library/aa289494(v=vs.71).aspx for more details, and examples.
Take care if caching a password though; you'll need to encrypt that.

Just create a class (in your project) that will not be instantiated right...and then have a variable in that class with access modifier
Public Shared.
Like for me I made a class called Globals and in it was a variable called currentUser .
So to access the variable from any class I just had Globals.currentUser =txtUser.TextAnd declare it like Public Shared currentUser as String

Try this, in your form file outside of the main class, or in a separate module file:
Public Module Globals
Public UserName As String = ""
End Module
Now you can access it in any code throughout your project. It will dispose when the app is closed. If you wanted to make doubly sure, even though it would be redundant, add this to the main form that closes the whole app:
Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
UserName = ""
End Sub

Related

Can't Programmatically Minimize Window

I'm trying to create a custom TitleBar for my game, i got everything else to work like i wanted but i can't get it to minimize without using the windows buttons from the windows frame.
I have a Game class with these in the constructor :
'Having this here or in the constructor doesn't make any difference
Public AsWindow As Windows.Forms.Form = CType(Windows.Forms.Form.FromHandle(Me.Window.Handle), Windows.Forms.Form)
Public Sub New()
Window.AllowUserResizing = False
Window.IsBorderless = True
end sub
Public Sub Minimize()
AsWindow.WindowState = System.Windows.Forms.FormWindowState.Minimized
End Sub
Calling Minimize cause a "System.NullReferenceException" on AsWindow, regardless of if i define AsWindow on runtime or during the initiation.
Note that i have added "System.Windows.Forms" as a reference.
Things i've tried:
This is where i got the initial code for the AsWindow field.
And here i tried to send a Message to minimize the window.
The problem you're facing is that the MonoGame API (which is exactly like XNA) doesn't expose a direct way of controlling the window. This kinda makes sense, because MonoGame supports platforms that don't have a concept of a "window" so to speak.
However, it's usually possible to get access to the underlying platform specific code and workaround these issues. It's important to keep in mind however that this approach will be platform specific and might break if MonoGame changes under the hood.
Last I checked, under the hood MonoGame uses SDL on the Windows desktop platform. This may not be true anymore, but I do have some code in an old project that gives the general idea. My code is in C# but it should point you in the right direction.
The first step is to import the method you want from the SDL.dll. This not managed code do you can't reference it like you normally would in .NET project.
[DllImport("SDL2.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void SDL_MaximizeWindow(IntPtr window);
Once you have access to the method you can call it by passing in the window handle.
SDL_MaximizeWindow(Window.Handle);
Obviously, this is code to maximize the window (that's the only code I had handy) but I'm sure you can figure out how to do the minimize version yourself.

How does VB.NET execute a non-shared method without an instance? [duplicate]

I'm just curious to know that there is the (Name) property, which represents the name of the Form class. This property is used within the namespace to uniquely identify the class that the Form is an instance of and, in the case of Visual Basic, is used to access the default instance of the form.
Now where this Default Instance come from, why can't C# have a equivalent method to this.
Also for example to show a form in C# we do something like this:
// Only method
Form1 frm = new Form1();
frm.Show();
But in VB.Net we have both ways to do it:
' First common method
Form1.Show()
' Second method
Dim frm As New Form1()
frm.Show()
My question comes from this first method. What is this Form1, is it an instance of Form1 or the Form1 class itself? Now as I mentioned above the Form name is the Default instance in VB.Net. But we also know that Form1 is a class defined in Designer so how can the names be same for both the Instance and class name?
If Form1 is a class then there is no (Static\Shared) method named Show().
So where does this method come from?
What difference they have in the generated IL?
And finally why can't C# have an equivalent of this?
This was added back to the language in the version of VB.NET that came with VS2005. By popular demand, VB6 programmers had a hard time with seeing the difference between a type and a reference to an object of that type. Form1 vs frm in your snippet. There's history for that, VB didn't get classes until VB4 while forms go all the way back to VB1. This is otherwise quite crippling to the programmer's mind, understanding that difference is very important to get a shot at writing effective object oriented code. A big part of the reason that C# doesn't have this.
You can get this back in C# as well, albeit that it won't be quite so clean because C# doesn't allow adding properties and methods to the global namespace like VB.NET does. You can add a bit of glue to your form code, like this:
public partial class Form2 : Form {
[ThreadStatic] private static Form2 instance;
public Form2() {
InitializeComponent();
instance = this;
}
public static Form2 Instance {
get {
if (instance == null) {
instance = new Form2();
instance.FormClosed += delegate { instance = null; };
}
return instance;
}
}
}
You can now use Form2.Instance in your code, just like you could use Form2 in VB.NET. The code in the if statement of the property getter should be moved into its own private method to make it efficient, I left it this way for clarity.
Incidentally, the [ThreadStatic] attribute in that snippet is what has made many VB.NET programmers give up threading in utter despair. A problem when the abstraction is leaky. You are really better off not doing this at all.
VB is adding a load of code into your project behind your back, basically.
The easiest way to see what's going on is to build a minimal project and look at it with Reflector. I've just created a new WinForms app with VB and added this class:
Public Class OtherClass
Public Sub Foo()
Form1.Show()
End Sub
End Class
The compiled code for Foo looks like this when decompiled as C#:
public void Foo()
{
MyProject.Forms.Form1.Show();
}
MyProject.Forms is a property in the generated MyProject class, of type MyForms. When you start diving into this you see quite large amounts of generated code in there.
C# could do all of this, of course - but it doesn't typically have a history of doing quite as much behind your back. It builds extra methods and types for things like anonymous types, iterator blocks, lambda expressions etc - but not in quite the same way that VB does here. All the code that C# builds corresponds to source code that you've written - just cleverly transformed.
There are arguments for both approaches, of course. Personally I prefer the C# approach, but that's probably no surprise. I don't see why there should be a way of accessing an instance of a form as if it was a singleton but only for forms... I like the language to work the same way whether I'm using GUI classes or anything else, basically.

Use global variables inside dlls in vb6

I have a dll where i would like to access the global variables of the Project.
How can this be done in VB6?
You can not access anything in a different project unless you explicitly pass it between the projects via COM.
While it is syntactically correct to use a global variable it is a very poor idea. Add either a module or a class file and encapsulate your variable inside a property. If you want to access your properties from within your project a bas file is fine. If you are describing making an ActiveX dll and accessing properties with another, separate project you should make a class module. You will need to set the class Instancing property to something other than private.
'myproject.bas code
Option Explicit
private mblnIsDirty as boolean
Public Property Let IsDirty(ByVal vIsDirty)
mblnIsDirty = vIsDirty
End Property
Public Property Get IsDirt() As Boolean
IsDirty = mblnIsDirty
End Property

MDIParent designer screen is not loading

When i try to view MDIParent screen in designer mode I’m getting below exception...
`Could not find endpoint element with name 'NetTcpBinding_IMyService' and contract 'ClientProxy.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.'
Little background to understand my question more clearly...
I've a WCF server which I’m trying to consume in my Winform application. So i've created a separate class library in which i added service reference and created a proxy. I've copied the client endpoint info from app.config in class library to UI app.config file.
When i run the application everything is working fine but when i try to open MDIParent screen in designer mode its throwing above exception.
Note: I think i'm getting error because i'm trying to create a proxy object on NEW method (form constractor) if i comment that line - i'm able to view designer screen.
Please help :)
Venky
If you instantiate the service in the form's constructor, this could be the source of your problem.
If this is the case, wrap the service initialization in a test for DesignMode:
If Not Me.DesignMode Then
' Initialize service
End If
Update
It turns out that DesignMode is not supported in the constructor.
There are a couple of workarounds to choose from:
1) Use the following instead of the designmode test:
If System.ComponentModel.LicenseManager.UsageMode <> System.ComponentModel.LicenseUsageMode.Designtime Then`
2) Move your initialization code from the constructor into the Form's _load event and then use the DesignMode test.
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Me.DesignMode Then
' Initialize service
End If
End Sub

Can't access my class from code-behind. Class is App_Code folder

I have a very simple class that is located within my App_Code folder in my VS2008 web application project. I am trying to instantiate an instance of this class from my code-behind file. Intellisense does not seem to be seeing my class and I am not sure why. I am using VB.NET which I am admittedly not that familiar with as compared to C#. Perhaps I am missing something. I would bet it has something to do with something I am missing in VB.NET.
Here is my simple class (for testing):
Public Class mySimpleClass
'Private member variables whose data is obtained from user input
Private mUserID as String
'Class Properties
Public Property UserID() as Integer
Get
Return mUserID
End Get
Set(ByVal Value as Integer)
mUserID = Value
End Set
End Property
'Class Methods
Public Function DisplayUserID() as String
Return this.UserID
End Function
End Class
Here is how I try an instantiate it from the codebehind ...
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim obj As New mySimpleClass()
End Sub
End Class
What I ended up doing was deleting my App_Code folder and creating a new "AppCode" folder. I also selected properties for the class file and set the Build Action property to "Compile". Once I did that and recompiled the project my class showed up.
you should change Return this.UserID to Return Me.UserID (VB.Net ;-))
rebuild the solution and see if it works
I'm not as familiar with the app_code folder and Websites in general, i'm always using WebApplications. I would suggest to convert it to a WebApplication too, here are further informations why: ASP.NET Web Site or ASP.NET Web Application?
Actually, I think if you add namespace to your project, it should work as well. I seem to remember having that problem every so often in C# asp.net as well. I could be way wrong though
Agree with Gustyn (sort of).
Add a "using namespace;" line to the web form code behind
Dave
Going to each file holding the "public" class(es) in the "App_Code" folder and setting Build Action from Content to Compile will do the trick.
It works for Web Application type projects.
All the stuff on whether to use a module(VB) or namespace or static(C#) won't help until you set your class files to compile (no matter what folder they are in).