error message in calender - asp.net

i am experiencing thi error when i click on the application in the remote machine.
Server Error in '/please-god' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
Line 7: Dim oBF As New BinaryFormatter()
Line 8: Dim oFS As FileStream
Line 9: Dim strPath As String = Path.GetTempPath & "schedule.Bin"
Line 10:
Line 11: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Source File: D:\Hosting\4423045\html\please-god\appointmentscheduler.aspx.vb Line: 9
Can someone help me? the full codes for the application is this :
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Partial Class appointmentscheduler
Inherits System.Web.UI.Page
Dim arrCalendar(12, 31) As String
Dim oBF As New BinaryFormatter()
Dim oFS As FileStream
Dim strPath As String = Path.GetTempPath & "schedule.Bin"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Cache("arrCalendar") Is Nothing) Then
If (File.Exists(strPath)) Then
oFS = New FileStream(strPath, FileMode.Open)
arrCalendar = DirectCast(oBF.Deserialize(oFS), Array)
oFS.Close()
Cache("arrCalendar") = arrCalendar
End If
Else
arrCalendar = Cache("arrCalendar")
End If
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day) = Me.myNotes.Text
oFS = New FileStream(strPath, FileMode.Create)
oBF.Serialize(oFS, arrCalendar)
oFS.Close()
Cache("arrCalendar") = arrCalendar
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day) = ""
oFS = New FileStream(strPath, FileMode.Create)
oBF.Serialize(oFS, arrCalendar)
oFS.Close()
Cache("arrCalendar") = arrCalendar
Me.myNotes.Text = ""
End Sub
Protected Sub myCalendar_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles myCalendar.DayRender
If arrCalendar(e.Day.Date.Month, e.Day.Date.Day) <> "" Then
e.Cell.BackColor = Drawing.Color.Red
End If
End Sub
Protected Sub myCalendar_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myCalendar.SelectionChanged
Me.myNotes.Text = ""
If arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day) <> "" Then
Me.myNotes.Text = arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day)
End If
End Sub
End Class
What do i have to do to eliminate this error message?

It looks like you're attempting to open a file that is outside of the web application's root directory. Either move the file into a place where the service account used by IIS has permission to read the file or change the read/write permissions on the file you're attempting to read.

Did you type the error message by hand? Path.GetTempPath is a method and should cause a compile error if you don't use the syntax Path.GetTempPath(). Makes it hard to dig too deeply into the error messages you've posted if they may not be correct.

Related

Asp.net Vb.net , access control concurrency

Hello guys I am trying to make restriction on my WebApp that runs on VB.net with framework Asp.net. In another words, how can I Control the permitted number of sessions.
The WebApp works perfectly and now I want to add "How many users can access the WebApp" if Number of users "Sessions" exceeded the new coming users will be redirected to a site.
I have been working on this for few weeks... tried Cookies and Seasons and neither is working
Scenario: Maximum users can access the WebApp is 1
when I launch the second Browser and start new session the UserNumber will be incremented by 1 hence will be redirected to "ServerBusy" page...
However, If the second Browser opened new tab and accessed the WebApp that will bypass the Condition at Session_Start and will access the WebApp .
Thank you.
here is the Code
Imports System.Web
Public Class Global_asax
Inherits System.Web.HttpApplication
Public Shared maxUsersAllowance As Integer = 1 'Total number of users can enter the server
Public Shared UserNumber As Integer = 0 ' the current number of users
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
UserNumber = UserNumber + 1
Dim myCookie As New HttpCookie("UserNumber")
Dim myCookie2 As New HttpCookie("Access")
myCookie.Value = UserNumber
myCookie2.Value = True
Response.Cookies.Add(myCookie)
Response.Cookies.Add(myCookie2)
If (Request.Cookies("UserNumber") IsNot Nothing) Then
If (Request.Cookies("UserNumber").Value > 1) Then
If (Request.Cookies("Access").Value) Then
Response.Redirect("~/ServerBusy.aspx")
End If
End If
End If
End Sub
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_Init(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_Dispose(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_Unload(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class
After Reading Article https://stackoverflow.com/a/6218525/1260204 and Updating the code, the Issue still exist which is that the User Can get into the WebApp if he open new Tab on the browser and connected
Imports System.Web
Public Class Global_asax
Inherits System.Web.HttpApplication
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
Application("ActiveSessions") = 0
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Try
Application.Lock()
Dim activeSessions As Integer = CInt(Application("ActiveSessions")) + 1
Dim allowedSessions As Integer = 1
' retrieve the threshold here instead
Application("ActiveSessions") = activeSessions
If activeSessions > allowedSessions Then
System.Web.HttpContext.Current.Response.Redirect("~/ServerBusy.aspx", False)
End If
Finally
Application.UnLock()
End Try
End Sub
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim LiveSessionsCount As Integer = CInt(Application("LiveSessionsCount"))
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock()
Application("ActiveSessions") = CInt(Application("ActiveSessions")) - 1
Application.UnLock()
End Sub
End Class
Update, I have solved the Issue with the Tabs. by adding
Session.Abandon()
In my redirected page. However that is half solution as far as i can get to... the other half is , if the user closes his browser by the X , I do need to wait 20 minutes until the session ends ... is there a away to terminate the session once the user exit/kill the page?

asp.net (with vb.net) control array at run time giving error : Object reference not set to an instance of an object

asp.net (with vb.net) control array at run time giving error :
Object reference not set to an instance of an object.
I am getting this error.
My Code is :
Partial Class _Default
Inherits System.Web.UI.Page
Dim chk(10) As CheckBox
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Else
MsgBox("loading")
chk(0) = New CheckBox
With chk(0)
.ID = "chk(0)"
.Text = .ID
End With
Me.form1.Controls.Add(chk(0))
End If
TextBox1.Text = chk(0).Text
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If chk(0).Checked = True Then
MsgBox("Yes")
Else
MsgBox("No")
End If
Response.Redirect("Page1.aspx")
End Sub
End Class
Use this instead:
Dim chk As CheckBox
chk = New CheckBox
Solved !
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Else
MsgBox("loading")
chk(0) = New CheckBox
With chk(0)
.ID = "chk(0)"
.Text = .ID
End With
Me.form1.Controls.Add(chk(0))
End If
TextBox1.Text = chk(0).Text
End Sub

Jabber-net Send message (VB.NET)

I have created test project to send message via google talk using Jabber library. As I already have test project that can send message successfully using agsXMPP, I want to imitate this project to use jabber library instead. However, there is no message sent even though the code run pass sending message command without any error. It seems that the password has not even been checked as it didn't enter OnAuthError event.
My test project is ASP.NET Web application project using VB.NET language. There are 4 textboxes to fill in: sender account (txt_Sender), sender's password (txt_Password), message to be sent (txt_Message) and receiver account (txt_Receiver) and also 1 button for sending the message (btn_Send). I test by using my email account (xxx1#gmail.com) and send message to my friend (xxx2#gmail.com). Here are my VB code
Imports jabber
Imports jabber.client
Imports Microsoft.Win32
Imports System.Threading
Imports jabber.protocol.client
Imports jabber.connection
Public Class TestSendMsg
Inherits System.Web.UI.Page
Public done As ManualResetEvent
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
done = New ManualResetEvent(False)
End Sub
Private Sub btn_Send_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_Send.Click
Dim jcSender As JabberClient = New JabberClient()
Dim jidSender As New jabber.JID(txt_Sender.Text.Trim)
With jcSender
.User = jidSender.User
.Password = txt_Password.Text.Trim
.Server = jidSender.Server
.AutoReconnect = True
.AutoRoster = True
End With
With jcSender
Try
AddHandler .OnAuthenticate, New bedrock.ObjectHandler(AddressOf j_OnAuthenticate)
'AddHandler .OnAuthenticate, AddressOf j_OnAuthenticate
AddHandler .OnPresence, AddressOf j_OnPresence
AddHandler .OnBeforePresenceOut, AddressOf j_OnBeforePresenceOut
AddHandler .OnAuthError, AddressOf j_OnAuthError
AddHandler .OnAfterPresenceOut, AddressOf j_OnAfterPresenceOut
.Connect()
.Login()
.IsAuthenticated = True
.Message(txt_Reciever.Text.Trim, txt_Message.Text.Trim)
Catch ex As Exception
MsgBox(ex.Message)
End Try
.Close()
.Dispose()
End With
End Sub
Private Sub j_OnAfterPresenceOut(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Registered: " & iq.BaseURI)
'done.Set()
End Sub
Private Sub j_OnAuthError(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Registered: " & iq.BaseURI)
'done.Set()
End Sub
Private Sub j_OnBeforePresenceOut(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Registered: " & iq.BaseURI)
'done.Set()
End Sub
Private Sub j_OnPresence(ByVal sender As Object, ByVal pres As Presence)
'Dim j As JabberClient = CType(sender, JabberClient)
'j.Message(TARGET, "Presence: " & pres.BaseURI)
'done.Set()
End Sub
Private Sub j_OnAuthenticate(ByVal sender As Object)
' Sender is always the JabberClient.
Dim j As JabberClient = CType(sender, JabberClient)
j.Message(txt_Reciever.Text.Trim, "Test OnAuthenticate")
' Finished sending. Shut down.
done.Set()
End Sub
End Class
You need to wait for OnAuthenticate before sending your message.

Can not upload photos: NullReferenceException [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Hello everyone I've been struggling with this error message for days:
Here is the error message:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 7:
Line 8: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Line 9: UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
Line 10: cannotUploadImageMessage.Visible = False
Line 11: End Sub
Source File: C:\Users\Collins\Documents\Visual Studio 2005\WebSites\living to please god world\PhotoAdmin\Default.aspx.vb Line: 9
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
PhotoAdmin_Default.Page_Load(Object sender, EventArgs e) in C:\Users\Collins\Documents\Visual Studio 2005\WebSites\living to please god world\PhotoAdmin\Default.aspx.vb:9
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
This is my complete code to upload photos. Can someone help me please?
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class PhotoAdmin_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
cannotUploadImageMessage.Visible = False
End Sub
Protected Sub dvPictureInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvPictureInsert.ItemInserted
'If the record was successfully inserted, save the picture
If e.AffectedRows > 0 Then
'Determine the maximum pictureID for this user
Dim results As DataView = CType(maxPictureIDDataSource.Select(DataSourceSelectArguments.Empty), DataView)
Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
'Reference the FileUpload control
Dim imageUpload As FileUpload = CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If imageUpload.HasFile Then
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
End If
End If
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was inserted. Sometimes an error might occur that
' does not raise an exception, but prevents the insert
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record inserted successfully."
Else
MessageLabel.Text = "An error occurred during the insert operation."
' Use the KeepInInsertMode property to remain in insert mode
' when an error occurs during the insert operation.
e.KeepInInsertMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInInsertMode = True
End If
End Sub
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Dim acceptedExtensions = New String() {".jpg", ".png", ".gif"}
If Not acceptedExtensions.Contains(imageUpload.FileName, StringComparer.OrdinalIgnoreCase) Then
cancelInsert = True 'Invalid image file!
End If
Else
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream)
If image.Width > 1300 Or image.Height > 950 Then
cancelInsert = True
End If
End If
If cancelInsert Then
e.Cancel = True
cannotUploadImageMessage.Visible = True
End If
'Set the UserId value to the currently logged on user's ID
e.Values("UserId") = Membership.GetUser().ProviderUserKey
'Set the UploadedOn value to the current date/time
e.Values("UploadedOn") = DateTime.Now
End Sub
Protected Sub gvPictures_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvPictures.RowDeleted
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Dim fileName As String = baseDirectory & e.Keys("PictureID") & ".jpg"
File.Delete(fileName)
End Sub
Protected Sub gvPictures_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvPictures.RowUpdating
e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
End Sub
End Class
Are you sure Membership.GetUser() is actually returning a user?
You are authenticated and not an anonymous user, correct? You should add a null check or a check to make sure they are authenticated first. I believe you can use User.Identity.IsAuthenticated
Just while editing for formatting I see line 9 has to do with membership and a control. Gut instinct is saying you're not logged in or that control doesn't exist.
Place a breakpoint at your line 9, run the site in debug, and see if the Membership.GetUser() or UserIdValue are null.

using session state dont work properly

i am still new to using session state, i want to convert page name into and integer according to a database table
a function then compares "X" and "Y" to check if a user have the right to view this page
i know this is not the best way of managing website security, but it is like "training on how to use the session"
what have i done wrong
Partial Class advancedsearch
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Label1.Text = Session("username").ToString
Label3.Text = Session("role").ToString
Label4.Text = System.IO.Path.GetFileName(Request.Url.ToString())
Catch ex As Exception
Response.Redirect("login.aspx")
End Try
If Label1.Text = "" Then
Response.Redirect("login.aspx")
End If
Dim x As Integer = Int32.Parse(Label3.Text)
Dim y As Integer = Int32.Parse(DropDownList1.SelectedItem.ToString)
If x < y Then Response.Redirect("login.aspx")
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Redirect("default.aspx")
End Sub
End Class
try putting the comparison part in pre render complete
Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
Dim x As Integer = Int32.Parse(Label3.Text)
Dim y As Integer = Int32.Parse(DropDownList1.SelectedItem.ToString)
If x < y Then Response.Redirect("login.aspx")
End Sub

Resources