Context issue in IHttpHandler - vb.net

Sorry, this can be a basic question for advanced VB.NET programmers but I am a beginner in VB.NET so I need your advice.
I have a web application and the login is required for some specific pages. To check if the user is logged in, the old programmer used this technique:
Dim sv As New WL.SessionVariables(Me.Context)
If Not (sv.IsLoggedIn) Then
Response.Redirect(WL.SiteMap.GetLoginURL())
End If
Well, I have to use this Logged In checking in a handler done by me and I tried this:
Public Class CustomHandler
Implements System.Web.IHttpHandler, IReadOnlySessionState
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim sv As New WL.SessionVariables(context)
If Not (sv.IsLoggedIn) Then
context.Response.Write("No access unless you're the CEO!!!" & sv.IsLoggedIn)
ElseIf sv.IsLoggedIn Then
DownloadFile(context)
Else
End If
End Sub
//other code
End Class
Well, the "is logged in" checking is always false (even after I login) and I think it's an issue with the context. So all the other pages works fine with logging checking but this handler have this specific issue.
Can you guys give a helping hand?
UPDATE:
The logged in is done trough this method:
Public Sub SetCreditialCookie(ByVal accountID As Integer)
Me.AccountID = accountID
m_context.Session.Item("loggedInAccount") = accountID
m_context.Response.Cookies.Add(New System.Web.HttpCookie("account_id", CStr(m_context.Session.Item("account_id"))))
m_context.Response.Cookies("account_id").Expires = DateTime.Now.AddDays(5)
End Sub
and to check it it's logged in, this method is called:
Public Function IsLoggedIn() As Boolean
If Not m_context.Session.Item("loggedInAccount") Is Nothing And Me.AccountID = m_context.Session.Item("loggedInAccount") Then
Return True
Else
Return False
End If
End Function
UPDATE 2:
- debugging the code shown that there were multiple kind of logins and I was checking the wrong one with the session.

Due to the use of IReadOnlySessionState, is it possible that the SessionVariables class attempts in some way to modify the Session, which in turn causes an error (possibly handled and not visible to you).
If this is the case it could mean that the IsLoggedIn property is not correctly initialised, or does not function as expected?
Do you have access to the code for the class. If so, try debugging it to see what is happening.

Related

Duplicated Control Name Causing 'Not A Member' Compile Errors

I have created a custom control called MultiTextbox. When I place my control onto a form and try to run my project, I get the following errors:
'MultiTextBox' is not a member of 'MultiTextbox.MultiTextbox'.
Type 'MultiTextbox.MultiTextbox' is not defined.
In my Form1.Designer code, I can see the following issues:
Me.MultiTextbox1 = New MultiTextbox.MultiTextbox()
Me.MultiTextbox1.ObjectAlignment = MultiTextbox.MultiTextbox.ObjectPlacement.Left
Me.MultiTextbox1.Style = MultiTextbox.MultiTextbox.TextboxStyle.Normal
Friend WithEvents MultiTextbox1 As MultiTextbox.MultiTextbox
I don't understand why it is duplicating the Control name for a selected few items.
The properties it is referring to are custom properties based from Enums.
For example:
Public Enum ObjectPlacement
Left
Right
End Enum
Private m_ObjectAlignment As ObjectPlacement = ObjectPlacement.Left
'ObjectAlignment
<Browsable(True), Category("Appearance"), _
Description("The text to display as an input group header.")> _
Public Property ObjectAlignment As ObjectPlacement
Get
Return m_ObjectAlignment
End Get
Set(value As ObjectPlacement)
If m_ObjectAlignment = value Then Return
m_ObjectAlignment = value
Me.Invalidate()
End Set
End Property
UPDATE
If I place my custom control on a form and run, everything will work fine without error, but as soon as I modify my control in any way (e.g. Size, Style, etc.) it gives me errors, and I can't even run the application as the compiler just sits in an infinite loop saying 'Building...'. I have to force quit VS.
Okay, after some useful posts on this thread and some googling, I found that by removing the Root Namespace from my project it removed all of my compiler errors that I was getting regarding a duplicated namespace (MultiTextbox.MultiTextbox):
Me.MultiTextbox1 = New MultiTextbox.MultiTextbox()
Me.MultiTextbox1.ObjectAlignment = MultiTextbox.MultiTextbox.ObjectPlacement.Left
Me.MultiTextbox1.Style = MultiTextbox.MultiTextbox.TextboxStyle.Normal
Friend WithEvents MultiTextbox1 As MultiTextbox.MultiTextbox
Secondly, the lockups that I was experiencing when trying to build my project was due to me setting a button's visible state within my paint event causing an infinite refresh loop of my control.

NullReferenceException on dll

Here is my code I get the error on:
Imports ADFactory
Public Class Salary
Inherits Salary_Datalayer
Protected _AD As New ADFactory.ADFactory
Protected Sub Page_Load(...)Handles Me.Load
_user = "username"
sDealer = _AD.GetUserCompany(_user)
It states that Protected _AD As New ADFactory.ADFactory is the line throwing the exception. I've looked online and read and changed it several times, declared 'New', am I missing something simple?
PatFromCanada was correct, my ADFactory was the problem. I didn't properly initialize a connection string within the reference, thus always throwing a nullexception, which apparently, I run into quite often in my questions. Thanks PatFromCanada!

Switching between forms (VB.NET)

I always get an exception when I try to switch between different forms in my program. Maybe you will help me to solve this issue. Here is the exception message:
Control.Invoke must be used to interact with controls created on a separate thread
I have attached the forms to very nice variables and this problem occurs when I try to use command like MyForm.Show().
It does not happen when the forms are not attached to variables, but then I have collosal problems with refreshing the textboxes and stuff.
Hope to hear you soon!
edit;
I have 4 different forms. When I load the main module and main form, in the Sub (...) Handles MyBase.Load I execute the following code:
In module:
Public StartupForm As frmStartup
Public RegularForm As frmRegularUse
Public LoginForm As frmLogin
Public PasswordForm As frmPassword
Public SettingsForm As frmSettings
In main form:
RegularForm = Me
StartupForm = frmStartup
LoginForm = frmLogin
PasswordForm = frmPassword
SettingsForm = frmSettings
This is the aproach I worked out to get the full control over refreshing the forms. It is a program for Motorola Scanner with Windows CE. Now, for example, when I enter the correct password in LoginForm, I want to switch to the RegularForm. When I try to use RegularForm.Show() or RegularForm.ShowDialog or RegularForm.BringToFront(), I get an exception. When I try to call the form with the frmRegularUse.Show() I can call the form, but it is being created in a different thread, I believe, so I loose control over it (when I try to put something from the keyboard, there is no response).
I doubt the forms are getting created in a different thread, but if they are then STOP, go back, and fix that. All of your forms should be created and accessed from the main GUI thread. Secondly, I don't think you "newed" the forms. You need something like this:
StartupForm = New frmStartup
RegularForm = New frmRegularUse
LoginForm = New frmLogin
PasswordForm = New frmPassword
SettingsForm = New frmSettings
Actually, what I did is:
Still I have the same code in the main module, which is:
Public StartupForm As frmStartup
Public RegularForm As frmRegularUse
Public LoginForm As frmLogin
Public PasswordForm As frmPassword
Public SettingsForm As frmSettings
I managed it to work in the simpliest possible way. For example - I run the Login form, and execute the following code (long story short):
LoginForm = Me
frmRegularUse.ShowDialog()
I jump to the frmRegularUse form, where, once again, I execute:
RegularForm = Me
frmPasswordForm.ShowDialog()
And so on...
I made some tests and it works quite okay. Tomorrow I will try to make it a little bit more sophisticated. ;-)

Silverlight RIA Application that only accepts registered users

I have implemented the RIA WCF side to authenticate with Forms Authentication and everything works from the client as expected.
This application should only allow registered users to use it (users are created by admin - no registeration page).
My question is then, what (or where) should be the efficient way to make the authentication; it has to show up at application start up (unless remember me was on and cookie is still active) and if the user logs out, it should automatically get out the interface and return to login form again.
Update (code trimmed for brevity):
Public Class MainViewModel
....
Public Property Content As Object 'DP property
Private Sub ValidateUser()
If Not IsUserValid Login()
End Sub
Private Sub Login()
'I want, that when the login returns a success it should continue
'navigating to the original content i.e.
Dim _content = Me.Content
Me.Content = Navigate(Of LoginPage)
If IsUserValid Then Me.Content = _content
End Sub
End Class
I saw you other question so I assume you're using mvvm. I accomplish this by creating a RootPage with a grid control and a navigation frame. I set the RootVisual to the RootPage. I bind the navigation frames source to a variable in the RootPageVM, then in the consructor of RootPageVM you can set the frame source to either MainPage or LoginPage based on user auth. RootPageVM can also receive messages to control further navigation like logging out.
Using MVVM-Light.
So, in the RootPageView (set as the RootVisual), something like:
public RootPageViewModel()
{
Messenger.Default.Register<NotificationMessage>
(this, "NavigationRequest", Navigate);
if (IsInDesignMode)
{
}
else
{
FrameSource =
WebContext.Current.User.IsAuthenticated ?
"Home" :
"Login";
}
}
And a method for navigation:
private void Navigate(NotificationMessage obj)
{
FrameSource = obj.Notification;
}
In the LoginViewModel:
if (loginOperation.LoginSuccess)
{
Messenger.Default.Send
(new NotificationMessage(this, "Home"), "NavigationRequest");
}

How can I write to my own app.config using a strongly typed object?

The following code has two flaws, I can't figure out if they are bugs or by design. From what I have seen it should be possible to write back to the app.config file using the Configuration.Save and according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx the code should work.
The bugs are shown in the source below and appear when you try to set the property or save the config back out.
Imports System.Configuration
Public Class ConfigTest
Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
Get
Return CStr(Me("JunkProperty"))
End Get
Set(ByVal value As String)
' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
Me("JunkProperty") = value
End Set
End Property
Public Sub Save()
Dim ConfigManager As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' The add / remove is according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
ConfigManager.Sections.Remove("ConfigTest")
' *** Bug 2, exception InvalidOperationException thrown with message "Cannot add a ConfigurationSection that already belongs to the Configuration."
ConfigManager.Sections.Add("ConfigTest", Me)
ConfigManager.Save(ConfigurationSaveMode.Full, True)
End Sub
Public Shared Sub Main()
Dim AppConfig As ConfigTest = TryCast(ConfigurationManager.GetSection("ConfigTest"), ConfigTest)
AppConfig.JunkProperty = "Some test data"
AppConfig.Save()
End Sub
' App.Config should be:
' <?xml version="1.0" encoding="utf-8" ?>
'<configuration>
' <configSections>
' <section name="ConfigTest" type="ConsoleApp.ConfigTest, ConsoleApp" />
' </configSections>
' <ConfigTest JunkProperty="" />
'</configuration>
End Class
I'd like to do it this way so that on the first run of the app I check for the properties and then tell the user to run as admin if they need to be set, where the UI would help them with the settings. I've already 'run as admin' to no effect.
Your code doesn't really make any sense. I took your example code and turned it into a simple example that works. Please note this is not best practise code, merely an example to aid you on your journey of learning the configuration API.
Public Class ConfigTest
Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
Get
Return CStr(Me("JunkProperty"))
End Get
Set(ByVal value As String)
' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
Me("JunkProperty") = value
End Set
End Property
Public Overrides Function IsReadOnly() As Boolean
Return False
End Function
Public Shared Sub Main()
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim AppConfig As ConfigTest = config.GetSection("ConfigTest")
AppConfig.JunkProperty = "Some test data"
config.Save()
End Sub
End Class
This code will open the config file, modify the attribute JunkProperty and persist it back it the executable's configuration file. Hopefully this will get you started- it looks like you need to read about the configuration API a bit more.
I've used the API to create configuration sections for large scale enterprise apps, with several 1000 of lines of custom hierarchical config (my config was readonly though). The configuration API is very powerful once you've learnt it. One way I found out more about its capabilities was to use Reflector to see how the .NET framework uses the API internally.
Maybe you don't know Portuguese or c# but this is you want http://www.linhadecodigo.com.br/Artigo.aspx?id=1613
using BuildProvider from asp.net
After loading a configuration it is readonly by default, principally because you have not overriden the IsReadOnly property. Try to override it.
¿Is there something that prevents you from using a setting?
Looks like it is not possible by design. App.config is normally protected as it resides along with the app in the Program Files directory so must be amended at installation time by the installer.
Pity really, I'd like the app to have settings that an admin can set.
Sorry if I didn't understand your case, but yes, you can change App.config at runtime.
Actually, you will need to change YourApp.exe.config, because once your app is compiled, App.config contents are copied into YourApp.exe.config and your application never looks back at App.config.
So here's what I do (C# code - sorry, I still haven't learnt VB.Net)
public void UpdateAppSettings(string key, string value)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement item in xmlDoc.DocumentElement)
{
foreach (XmlNode node in item.ChildNodes)
{
if (node.Name == key)
{
node.Attributes[0].Value = value;
break;
}
}
}
using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
{
xmlDoc.Save(sw);
}