I want to create class that is intended to serve as configuration management and serving helper. It would store some basic connection settings in XML file, read it to it's own properties and serve to any other module, form, object etc.
I've created a class like following:
Option Compare Database
Option Explicit
Private mstrSqlServerName As String
'...
Public Property Get SqlServerName() As String
SqlServerName = mstrSqlServerName
End Property
'...
Private Sub Class_Initialize()
readConfigFile
End Sub
Private Function loadConfigFile() As MSXML2.DOMDocument60
On Error GoTo FunctionError
Dim XMLFileName As String
Dim objRoot As IXMLDOMElement
Dim strMsg As String
Dim oXMLFile As MSXML2.DOMDocument60
'Open the xml file
Set oXMLFile = New MSXML2.DOMDocument60
XMLFileName = (Application.CurrentProject.Path & "\config.xml")
With oXMLFile
.validateOnParse = True
.SetProperty "SelectionLanguage", "XPath"
.async = False
.Load (XMLFileName)
End With
Set loadConfigFile = oXMLFile
End Function
Public Sub readConfigFile()
Dim oXMLFile As MSXML2.DOMDocument60
Set oXMLFile = loadConfigFile
mstrSqlServerName = oXMLFile.selectSingleNode("//config/database/SqlServerName").Text
End Sub
I've tested my class in intermediate window and everything works flawlessly. Then
I've created hidden form to instantiate the class like follows:
'frmYouShouldNotSeeMe
Option Compare Database
Option Explicit
Public configuration As clsConfiguration
Private Sub Form_Load()
Set configuration = New clsConfiguration
MsgBox Prompt:=configuration.SqlServerName
End Sub
Now, from other module/form/report etc. i wanted to call configuration item with:
MsgBox configuration.SqlServerName
But when I'm trying to compile my project it says "compile error, variable not defined". In short: I cannot find a way to use instantiated (named) object properties from other objects of database. They just don't know anything about it's existence. In the intermediate window everything works, I can instantiate object and call GET functions. What did I do wrong? Probably it's just what OOP design brings and I just don't understand that. What is the best way to achieve this goal?
You can add two public functions to your class.
Like this:
Public Function SqlServerName() As String
SqlServerName = oXMLFile.SelectSingleNode("//config/database/SqlServerName").Text
End Function
Public Function GetConfig(strNode As String, strValue As String) As String
Dim strXPATH As String
strXMPATH = "//config/" & strNode & "/" & strValue
GetConfig = oXMLFile.SelectSingleNode(strXMPATH).Text
End Function
Now in code you can use:
Msgbox configuration.SqlServerName
Or to get any config you can use the helper functon with 2 params
Msgbox configuration("database","SqlServerName")
So, the public members of the class HAVE to be written by you. It does not by "magic" or out of the blue expose information from that class. You can use public functions, and they will appear as inteli-sense when you create such public functions. (they become properties of the class). So, your syntax does not work because you don't have a public function (or a property get) that exposes what you want. You can use a property let/get, but a public function also works very well as the above shows.
So, either make a public function for each "thing" (node) you want to expose, or use the helper function above, and you can pass the key + node value with the function that accepts 2 parameters. Both the above will become part of the class, show inteli-sense during coding - you are free to add more public members to the class as per above.
#Edit
the sample code shows this:
Set configuration = New clsConfiguration
MsgBox Prompt:=configuration.SqlServerName
it needs to be this:
dim configuration as New clsConfiuration
MsgBox Prompt:=configuration.SqlServerName
You could on application startup setup a GLOBAL var called configueration, and thus not have to declare the configeration variable in the forms code.
You thus need a global var - set it up in your startup code before any form is launched.
So in a standard code module, you need this:
Public configuration as new clsConfiguration
But, your screen shot of the code is MISSING the create of the configuartion variable.
And your provided code has this:
Set configuration = New clsConfiguration
MsgBox Prompt:=configuration.SqlServerName
So where and when did you define configuration as global scoped variable?
You either have to use LOCAL scope to the form (in fact your on-load event)
dim configuration as New clsConfiuration
MsgBox Prompt:=configuration.SqlServerName
Or, you can as noted, declare "configuration" as a public global varible in a starndard code module (not forms module, and of course not a class module).
if you use the "new" keyword, then you can use this:
Public configuration as New clsConfiuration
The above can be placed in any standard code module - it will be global in scope.
With above, then in the forms load event, this will work:
MsgBox Prompt:=configuration.SqlServerName
As configuration is declared in frmYouShouldNotSeeMe you can refer to the form to access the variable, as long as the form is open.
Debug.Print Forms("frmYouShouldNotSeeMe").configuration.SqlServerName
Related
I tried this in an Access newgroup, and got over a hundred views, but not a single response, so I hope it fares better here.
I'm trying to get a grip on custom events in VBA. I've scoured endless sources on the net, studied my manuals, experimented with everything I can think of, and success is still somewhat tenuous.
Exactly what I hope to accomplish is not all that complicated, and seems like it should be ideal for custom event routines. I have main forms with comboboxes and listboxes fed from tables or queries. The user can open various dialog boxes and do things to modify the tables. When that activity is done, I would like to requery the box(es) affected by any such activity. The way I have done it in the past was to set a global 'SourceHasChanged' Boolean variable and check its status upon returning from the dialog. It works, but is a bit unwieldy, so I decided to try replacing this with custom events.
Hours of studying and endless dead-end tries and repeats have finally produced the following bits of code. They do nothing spectacular. There is a table called T. The dialog form adds records on each click of the Add button. The main form has another button that deletes all but the first record in the table. Each set of code is supposed to fire an event indicating that the listbox is to be requeried. The code in the main form does okay, but the code in the dialog refuses to activate the StalaSeZmena event. Obviously (I think, anyway), that's because the dialog from creates a new instance of the class module. But I have to have a WithEvents variable in the dialog form. If I don't, I would have to make a reference to the WithEvents variable in the main form. Requiring forms to know that much about each other is exactly back-asswards from what I thought the custom event route was going to accomplish. It would be easier and less confusing to just stay with a global status variable.
Class Module [Zmena]
Public WithEvents Udalost As HlaseniZmeny
Private Sub Udalost_StalaSeZmena()
Form_Mane.lstS.Requery
Debug.Print "Requery via class module"
End Sub
Class Module [HlaseniZmeny]
Public Event StalaSeZmena()
Public Sub OhlasitZmenu()
RaiseEvent StalaSeZmena
End Sub
Regular Module
Public chg As Zmena
Form Code [Mane]
Private WithEvents chgMane As HlaseniZmeny
Private Sub cmdCallDialog_Click()
DoCmd.OpenForm "Dia", acNormal, , , , acDialog
End Sub
Private Sub cmdShrinkT_Click()
CurrentDb.Execute "Delete * From T Where Pole1 <> 'A'"
chgMane.OhlasitZmenu
End Sub
Private Sub Form_Open(Cancel As Integer)
Me.Label1.Caption = Me.SpinButton1.Value
Set chg = New Zmena
Set chgMane = New HlaseniZmeny
Set chg.Udalost = chgMane
End Sub
Private Sub chgMane_StalaSeZmena()
lstS.Requery
Debug.Print "Requery from event on main"
End Sub
Form Code [Dia]
Private WithEvents chgDia As HlaseniZmeny
Private Sub cmdAdd_Click()
CurrentDb.Execute "Insert Into T (Pole1) Values(chr(asc('" & DMax("Pole1", "T", "Pole1") & "')+1))"
Set chgDia = New HlaseniZmeny
Set chg.Udalost = chgDia
chgDia.OhlasitZmenu
Set chgDia = Nothing
End Sub
It's functional, but feels awkward, clunky and not at all intuitive, like scratching my left ear with my right foot. The class module has a reference to the main form, which violates the principle of encapsulation, but I found no way to make the dialog form activate the event routine in the main form. I have to have a global variable to link the two WithEvents variables to, or nothing works, but this also violates encapsulation.
Is this really how these constructs are supposed to operate, or have I accidentally stumbled onto a Mad-Max version that happens to work, but isn't the proper way to build such procedures?
I am trying to create an appointment/meeting notice template that prevents forwarding, defaults to no response required and is sent from a delegated/shared calendar. I have the script to change the response required and can disable the forwarding option in the actions, but I can't figure out the delegate. I've found the getname script:
Sub ResolveName()
Dim myNamespace As Outlook.NameSpace
Dim myRecipient As Outlook.Recipient
Dim CalendarFolder As Outlook.Folder
Set myNamespace = Application.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Larry M Garrett")
myRecipient.Resolve
If myRecipient.Resolved Then
Call ShowCalendar(myNamespace, myRecipient)
End If
End Sub
Sub ShowCalendar(myNamespace, myRecipient)
Dim CalendarFolder As Outlook.Folder
Set CalendarFolder = _
myNamespace.GetSharedDefaultFolder _
(myRecipient, olFolderCalendar)
CalendarFolder.Display
End Sub
This works in visual basic, but it only opens the shared calendar. It doesn't set the appointment to come from the shared calendar. I get a code error if i put it into the "view code" section and try to run the form. I feel like i'm missing the step where i tell it to send from the delegated calendar but i can't find it. Thanks.
It looks like you need to use the shared calendar folder to create an appointment item. Use the sharedCalendarFolder.Items.Add method to create an appointment.
I am having a field in the database "IsActive" which is "Null" by default. Now I want to update the field once and set it to true. Now once the field is set to true I need to prohibit further modifications to it. Any help please!
For each property RIA Services creates in an entity, RIA Services also creates several partial method stubs that are called when the property value is changing for you to override, e.g. For your IsActive property, RIA Services generates:
Private Partial Sub OnIsActiveChanging(ByVal value As Boolean)
End Sub
Private Partial Sub OnIsActiveChanged()
End Sub
You'll find these stubs in the file that RIA Services creates when you compile (in the Generated_Code folder in your Silverlight project folder; it won't be included in the project itself).
There is no way to "cancel" the change, but you can put a little logic in to set the value back yourself, e.g. in a partial class for your entity:
Private _setBackToTrue As Boolean
Private Sub OnIsActiveChanging(ByVal value As Boolean)
If Not value AndAlso Me.IsActive Then
_setBackToTrue = True
End If
End Sub
Private Sub OnIsActiveChanged()
If _setBackToTrue Then
Me.IsActive = True
_setBackToTrue = False
End If
End Sub
I am working and excel addin and I am under the need to open a new window of the same workbook to enter data in a different worksheet. For the new window, I will need to know when the window is being closed so I can do some validations on the data entered. Is there a way to know when a Workbook window is being closed?
Thanks.
Take a look at this document:
http://support.microsoft.com/kb/213566
Create a Module and a Class Module. Code is below.
Class Module code:
Public WithEvents appevent As Application
Dim windowsCount As Integer
Private Sub appevent_WindowActivate(ByVal Wb As Workbook, ByVal Wn As Window)
If windowsCount <> Application.Windows.Count Then
MsgBox "You closed a window"
End If
End Sub
Private Sub appevent_WindowDeactivate(ByVal Wb As Workbook, ByVal Wn As Window)
windowsCount = Application.Windows.Count
End Sub
Module Code:
Dim myobject As New Class1
Sub Test()
Set myobject.appevent = Application
End Sub
And this handler for the workbook:
Private Sub Workbook_Open()
Test
End Sub
You can handle the BeforeClose event. An example using VBA is available here.
I have a custom application with a simple app.config specifying SQL Server name and Database, I want to prompt the user on application install for application configuration items and then update the app.config file.
I admit I'm totally new to setup projects and am looking for some guidance.
Thank You
Mark Koops
I had problems with the code Gulzar linked to on a 64 bit machine. I found the link below to be a simple solution to getting values from the config ui into the app.config.
http://raquila.com/software/configure-app-config-application-settings-during-msi-install/
check this out - Installer with a custom action for changing settings
App.Config CAN be changed...however it exists in a location akin to HKEY___LOCAL_MACHINE i.e. the average user has read-only access.
So you will need to change it as an administrator - best time would be during installation, where you're (supposed to be) installing with enhanced permissions.
So create an Installer class, use a Custom Action in the setup project to pass in the user's choices (e.g. "/svr=[SERVER] /db=[DB] /uilevel=[UILEVEL]") and, in the AfterInstall event, change the App.Config file using something like:
Public Shared Property AppConfigSetting(ByVal SettingName As String) As Object
Get
Return My.Settings.PropertyValues(SettingName)
End Get
Set(ByVal value As Object)
Dim AppConfigFilename As String = String.Concat(System.Reflection.Assembly.GetExecutingAssembly.Location, ".config")
If (My.Computer.FileSystem.FileExists(AppConfigFilename)) Then
Dim AppSettingXPath As String = String.Concat("/configuration/applicationSettings/", My.Application.Info.AssemblyName, ".My.MySettings/setting[#name='", SettingName, "']/value")
Dim AppConfigXML As New System.Xml.XmlDataDocument
With AppConfigXML
.Load(AppConfigFilename)
Dim DataNode As System.Xml.XmlNode = .SelectSingleNode(AppSettingXPath)
If (DataNode Is Nothing) Then
Throw New Xml.XmlException(String.Format("Application setting not found ({0})!", AppSettingXPath))
Else
DataNode.InnerText = value.ToString
End If
.Save(AppConfigFilename)
End With
Else
Throw New IO.FileNotFoundException("App.Config file not found!", AppConfigFilename)
End If
End Set
End Property
Create custom dialogs for use in your Visual Studio Setup projects:
http://www.codeproject.com/Articles/18834/Create-custom-dialogs-for-use-in-your-Visual-Studi