Upload files in vb.net - asp.net

I have a code in vb.net (as shown below) in which it ask to upload a file after the selection of yes button. On checking No button, it doesn't ask us to upload a file as shown below in the images.
************************************************VB Code******************************************************
Protected Sub rblOrgChart_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rblOrgChart.SelectedIndexChanged
ruOrgChart.Visible = False
hlOrgChart.Visible = False
' btnOrgChart.Visible = rblOrgChart.SelectedValue And bolHasWritePermission
hlOrgChart.Visible = rblOrgChart.SelectedValue
If CBool(rblOrgChart.SelectedValue) Then
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
Else
' If Me.lblOrgChartMissing2.Visible Then Me.lblOrgChartMissing2.Visible = False
End If
End Sub
The code inside the method btnOrgChart_Click is:
Protected Sub btnOrgChart_Click(sender As Object, e As System.EventArgs) Handles btnOrgChart.Click
Try
'If ruOrgChart.InvalidFiles.Count > 0 Then
' lblOrgChartNotPDF.Visible = True
'Else
' lblOrgChartNotPDF.Visible = False
'End If
'------------------------------------------------------------------
' Q07. HAS WRITTEN ORG. CHART [IAPData..tblReadinessProfile_Question ID=9 ]
'------------------------------------------------------------------
If (rblOrgChart.SelectedValue = 1 And ruOrgChart.UploadedFiles.Count > 0) Then
hlOrgChart.Visible = True
'' ''======' BEGIN NEW CODE --- to upload file to virtual directory
Dim sufile As Telerik.Web.UI.UploadedFile = Nothing
For Each sufile In Me.ruOrgChart.UploadedFiles
' for now upload files on webserver
'If AppSettings.Item("Environment") <> "Prod" Then
remoteName = Request.PhysicalApplicationPath
'Else
'remoteName = AppSettings.Item("UploadRootPath").ToString.Trim()
'End If
Dim strPhysicalFilePath As String = remoteName & AppSettings.Item("FileUploadRootPath").ToString & "\" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "\" & dtOrg.Rows(0).Item("OrgCode").ToString & "\"
CreateFileUploaderLink(remoteName)
If Not Directory.Exists(strPhysicalFilePath) Then
Directory.CreateDirectory(strPhysicalFilePath)
End If
hlOrgChart.NavigateUrl = AppSettings.Item("FileUploadRootPath").ToString & "/" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "/" & dtOrg.Rows(0).Item("OrgCode").ToString & "/" & ruOrgChart.UploadedFiles(0).GetName()
dalClientProfile.SaveFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART, ruOrgChart.UploadedFiles(0).GetName(), strPhysicalFilePath, True)
hlOrgChart.Text = ruOrgChart.UploadedFiles(0).GetName()
Dim NewFileName As String
NewFileName = sufile.GetName()
'If File.Exists(strPhysicalFilePath & NewFileName) Then
' Dim script As String = "alert('" + Me.GetLocalResourceObject("err.fileuploaded.text") + "');"
' ScriptManager.RegisterStartupScript(ruOrgChart, ruOrgChart.GetType(), "clientscript", script, True)
' Exit Sub
'End If
sufile.SaveAs(strPhysicalFilePath & NewFileName, True)
' Cancel the connection
RemoveFileUploaderLink(remoteName)
Next
End If
Catch ex As Exception
Dim oErr As New ErrorLog(ex, "Error in btnOrgChart_Click")
Response.Redirect("~/Error/ErrorPage.aspx?type=Err&ui=" & Request.QueryString("ui"), True)
Exit Sub
End Try
End Sub
**********************************************Images*******************************************************
As shown above in the images, on selection of yes it ask us to upload a file.
By default, it always remains No as the value of HasOrgChart is always 0.
rblOrgChart.SelectedValue = IIf(CBool(dtOrg.Rows(0).Item("HasOrgChart")), 1, 0)
******************************************************HTML*************************************************
The .aspx code belonging to the above images and to the above vb codes are:
<div class="grid-c2">
<div>
<asp:UpdatePanel runat="server" ID="Updatepanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>
<ContentTemplate>
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
<div>
<br />
<telerik:RadAsyncUpload ID="ruOrgChart" runat="server" AutoPostBack="true"
HideFileInput="True"
AllowedFileExtensions=".pdf"
OnClientValidationFailed="validationFailed"
onclientfileuploaded="ruOrgChart_Fileuploaded"
MaxFileInputsCount="1"
InitialFileInputsCount="1"
MaxFileSize="5000000"
/>
<div class="fileLink">
<asp:HyperLink runat="server" ID="hlOrgChart" Target="_blank" Visible="false"
Text=""></asp:HyperLink>
</div>
</div>
<br />
<div style="display:none">
<asp:linkButton ID="btnOrgChart" CssClass="btnUpload" runat="server" Text="" />
</div>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
I am wondering what changes do I need to make in the vb.net and .aspx codes so that instead of Yes and No radio button, there is only select button which ask us directly to upload a file with no yes/no options.

You already have a select button on your form. Why not bypass the Yes/No and just use that?
You should have a Sub btnOrgChart_Click code somewhere. Your variable names don't match with your intended actions, but I think that under the Click code, you might want this somewhere:
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
EDIT: I believe, to remove the radio button section, remove:
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
and
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>

Related

Select multiple value in DropDownList

I have a dropdownlist (SingleSelection) which retrieve the data from sql database, I want to change it to MultiSelection (select multi value), following is my code.
ASP.NET
<asp:DropDownList ID="DrpGroup" runat="server" Width="250px" AutoPostBack="True">
</asp:DropDownList>
VB
Protected Sub DrpGroup_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DrpGroup.SelectedIndexChanged
If (DrpGroup.SelectedValue.ToString.Trim.ToUpper <> "PLEASE SELECT...") Then
Dim cnt_value As Integer = TDES.FindKey("Select Count(*) from dbo.VU_CUSTOMERBYGROUP WHERE upper(ltrim(rtrim(GROUP_NAME)))='" & DrpGroup.SelectedValue.ToString.Trim.ToUpper & "'")
lblNumberCount.Visible = True
lblNumberCount.Text = DrpGroup.SelectedValue.ToString.Trim.ToUpper & " has " & CStr(cnt_value) & " member(s). <br /> The cost for this SMS broadcast will be xxx" & CStr(cnt_value * 0.5)
End If
If (DrpGroup.SelectedValue.ToString.Trim.ToUpper = "PLEASE SELECT...") Then
lblNumberCount.Visible = False
End If
End Sub
Your efforts would be appreciated.
Use ListBox instead of DropDownList
<asp:ListBox runat="server" ID="multiSelect" SelectionMode="multiple" >
<asp:ListItem Text="option1" Value="option1"></asp:ListItem>
<asp:ListItem Text="option2" Value="option2"></asp:ListItem>
<asp:ListItem Text="option3" Value="option3"></asp:ListItem>
</asp:ListBox>

How to assign value to the DropBox text propery?

I'm writing a program where user has 3 drop boxes to input date, month and a year. after user selects the values I concatenate them and check for valid By default when a page loads I need to assign a current day, month and year to each drop box accordingly. Then I check validity of the date and pass value to the database.
My problem is that when I assign the values to the text of DropBoxes upon the loading of the page they are becoming permanent. even if the index is changed the values which are passed to the database are the ones which assigned to them when the page is loaded.
I can't actually understand what am I doing wrong:
these are the code samples which I've used:
I populate them with a current date values using folowing code(on the page Load event):
Dim CurYear As Integer = DatePart("yyyy", Now)
Dim CurDate As Integer = DatePart("d", Now)
Dim CurMonth As String = Format(Today.Date, "MMMM")
Dim CurDate2 As Integer = DatePart("d", Now)
Dim CurMonth2 As String = Format(Now, "MM")
Dates.Text = CurDate
Monthe.Text = CurMonth
years.Text = CurYear
Month2.Text = CurMonth2
Dates2.Text = CurDate2
Than I had to synchronize the selected index of 2 the dropboxes which contain numerical value of the month and 2 digit format of the day, to to form the proper string for checking of the date
Protected Sub Months_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Months.SelectedIndexChanged
Month2.SelectedIndex = Months.SelectedIndex
TextBox3.Text = years.Text & "-" & Monthes.Text & "-" & Dates.Text
End Sub
Protected Sub Dates_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Dates.SelectedIndexChanged
Dates2.SelectedIndex = Dates.SelectedIndex
TextBox3.Text = years.Text & "-" & Monthes.Text & "-" & Dates.Text
End Sub
And this is front end ASP code:
<asp:DropDownList ID="Dates" runat="server" autopostback="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>1</asp:ListItem>
...
<asp:ListItem>26</asp:ListItem>
<asp:ListItem>27</asp:ListItem>
<asp:ListItem>28</asp:ListItem>
<asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>31</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Months" runat="server" autopostback="true" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>January</asp:ListItem>
...
<asp:ListItem>November</asp:ListItem>
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="years" runat="server" autopostback="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Dates2" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
<asp:ListItem>02</asp:ListItem>
....
<asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>31</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Month2" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
....
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
Again, if I don't assign the default values to the boxes upon loading of the page it works perfectly. if i do, those values are fixed no mater what you choose
The comparevalidator:
<asp:UpdatePanel ID="UpdatePanel19" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox3" ValidationGroup="CompareValidatorDateTest" runat="server"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Dates" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="Monthes" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="years" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:CompareValidator ID="CompareValidator3" Display="dynamic" ControlToValidate="TextBox3"
Type="Date" Operator="LessThanEqual" Text="Please enter a valid date" runat="server"
ValidationGroup="CompareValidatorDateTest"
I suppose you didnt use IsPostBack property while binding the dropdown with values on page load.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
// Bind your dropdown here here
End If

Update paneel blocks execution of some error messages

I ave an asp page with 1 update panels with 2 panels which are controlled by 2 buttons if you click in first button first panel appears and second becomes hidden and if you click second button the same thing happens for the second panel. It's working ok and no problem about that.
The problem begins in the second panel where I have another update panel which is in charge of printing error messages. The messages which just check the length of input are working ok, but those messages which involve querying the database to check the validity of id are not being printed .
I thought the querying are the problem and I've tried them in a separated page without update panels and they are working ok. The problem lays somewhere with Update panels. And I really can't understand where. I would be most grateful if you can help me.
This is front end code(i omit some insignificant details):
<asp:Button ID="Button1" runat="server" Text="[Input your Id?]" />
<asp:Button ID="Button2" runat="server" Text="[Aditional info]" />
.....
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
< asp:Panel ID="Panel1" runat="server">
some code here
</asp:Panel>
<asp:Panel ID="Panel2" runat="server">
<b>*ID Number: </b>
<asp:TextBox ID="IdNo" runat="server" ></asp:TextBox><font size='2'>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" class="errorMess" ErrorMessage="Letters are not Allowed!!" ControlToValidate="IdNumb" ValidationExpression="\d+"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:Label ID="errorEm" class="errorMess" runat="server" Text="Please fill in the required fields"></asp:Label>
<asp:Label ID="errorLenght" class="errorMess" runat="server" Text="Id is too long!!!"></asp:Label>
<asp:Label ID="errorUser" class="errorMess" runat="server" Text="Id is not valid!!!"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button5" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button5" runat="server" Text="Generate" /></td></tr>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
and this is backend VB code:
Protected Sub Button5_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button5.Click
If IdNo.Text = "" Then
Panel1.Visible = False
Panel2.Visible = True
errorEm.Visible = True
ElseIf IdNo.Text.Length > 9 Then
Panel1.Visible = False
Panel2.Visible = True
errorLenght.Visible = True
Else
Try 'everything that comes here does not work'
myconn.Open()
Dim stquery As String = "SELECT * from account WHERE user_id= #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNo.Text))
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
Panel1.Visible = False
Panel2.Visible = True
errorUser.Visible = True
myconn.Close()
Return
Else
Panel1.Visible = False
Panel2.Visible = True
myreader.Read()
Dim ErrorMessage As String = "alert('User has been found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
End If
End Sub
When you want to execute script from inside of Update panel - don't use
Page.ClientScript.RegisterStartupScript
Use
ClientScriptManager.RegisterStartupScript
instead.
Ref: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

passing checkboxlist selected items as a concatenated string

I am trying to pass the selected items from a checkboxlist in asp.net (vs 2005/.net 2.0) as a concatenated string.
Currently my .aspx is
<asp:CheckBoxList id="checkbox1" AutoPostBack="False" AppendDataBoundItems="true" CellPadding="5" CellSpacing="5" RepeatColumns="1" RepeatDirection="Vertical" RepeatLayout="Flow" TextAlign="Right" runat="server">
<asp:ListItem Value="1">Carrots</asp:ListItem>
<asp:ListItem Value="2">Lettuce</asp:ListItem>
<asp:ListItem Value="3">Olives</asp:ListItem>
<asp:ListItem Value="4">Onions</asp:ListItem>
<asp:ListItem Value="5">Tomato</asp:ListItem>
<asp:ListItem Value="6">Pickles</asp:ListItem>
</asp:CheckBoxList>
And the .aspx.vb is (inside the Protected Sub for submit)
For Each li As ListItem In checkbox1.Items
If li.Selected = True Then
checkbox1.Text = checkbox1.Text + "," + li.Text
End If
Next
Which is written to the db via
checkbox1.Text = dv(0)("Salad").ToString()
When I select and save, I am currently getting an error
Server Error in '/' Application.
'checkbox1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Any thoughts on how to concatenate the selected checkbox items
For example, if some selects Carrots, Lettuce, and Tomato;
checkbox1 = 1,2,5
I don't think you are assigning to a variable like you describe you are returning.
string list = "";
For Each li As ListItem In chkQ4.Items
If li.Selected = True Then
list = list + "," + li.Text
End If
Next
is how you should write the line above.
In C# using linq, I would write
var list = checkbox1.Items
.Cast<ListItem>()
.Where(item => item.Selected == true)
.Select(item => item.Value);
var result = string.Join(",",list);
which I believe is the following in VB
Dim list = checkbox1.Items.Cast(Of ListItem)().Where(Function(item) item.Selected = True).[Select](Function(item) item.Value)
Dim result = String.Join(",", list.ToArray())
This is a little example
Markup:
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="1">Carrots</asp:ListItem>
<asp:ListItem Value="2">Apples</asp:ListItem>
<asp:ListItem Value="3">Lettuce</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Concatenate" /><br />
<asp:Button ID="Button2" runat="server" Text="Save" />
Codebehind:
Private Sub SaveItems(ByVal strItems As String)
Dim cn As New SqlConnection("user id=sa;password=abcd;database=BD_Test;server=SERVNAME")
Dim cmd As New SqlCommand("Insert into CheckItems values (#ItemId)", cn)
Dim cmdPar As New SqlParameter("#ItemId", SqlDbType.Char, 1)
If strItems.Split(",").Length > 0 Then
cmd.Parameters.Add(cmdPar)
Using cn
cn.Open()
Using cmd
''Split the existing selected values, store it in an array
''and iterate to get each element of it to save it in the DB
For Each strItem As String In strItems.Split(",")
cmd.Parameters("#ItemId").Value = strItem
cmd.ExecuteNonQuery()
Next
End Using
Me.Literal1.Text = "Items saved"
End Using
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Literal1.Text = ""
For Each l As ListItem In Me.CheckBoxList1.Items
''Concatenate keeping the order of the items in your CheckboxList
If l.Selected Then
Me.Literal1.Text = Me.Literal1.Text & l.Value & ","
End If
Next
''Remove the final "," in case its at the end of the string
''to avoid db issues and selected items issues
If Right(Me.Literal1.Text, 1) = "," Then
Me.Literal1.Text = Left(Me.Literal1.Text, Me.Literal1.Text.Length - 1)
End If
''You can also save the items directly after concatenating
''Me.SaveItems(Me.Literal1.Text)
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.SaveItems(Me.Literal1.Text)
End Sub
The expected result is to have the selected values of the items on the page literal:
1,3
Hope this helps.

'AuthorizationRule' is a type and cannot be used as an expression

<%# Page Language="vb" MasterPageFile="~/4guys.master" %>
<%# Import Namespace="System.Web.Configuration" %>
<script runat="server">
Private Const VirtualImageRoot As String = "~/"
Private selectedFolderName As String
Private Sub Page_Init()
UserRoles.DataSource = Roles.GetAllRoles()
UserRoles.DataBind()
UserList.DataSource = Membership.GetAllUsers()
UserList.DataBind()
If IsPostBack Then
selectedFolderName = ""
Else
selectedFolderName = Request.QueryString("selectedFolderName")
End If
End Sub
Private Sub Page_Load()
'Interaction.MsgBox("Welcome");
If User.IsInRole("Administrator") Then
Else
Response.Redirect("~/homepage_aspx/homepage.aspx")
End If
If Not IsPostBack Then
PopulateTree()
End If
End Sub
Private Sub Page_PreRender()
If FolderTree.SelectedNode IsNot Nothing Then
DisplayAccessRules(FolderTree.SelectedValue)
SecurityInfoSection.Visible = True
End If
End Sub
Private Sub PopulateTree()
' Populate the tree based on the subfolders of the specified VirtualImageRoot
Dim rootFolder As New DirectoryInfo(Server.MapPath(VirtualImageRoot))
Dim root As TreeNode = AddNodeAndDescendents(rootFolder, Nothing)
FolderTree.Nodes.Add(root)
Try
FolderTree.SelectedNode.ImageUrl = "/Simple/i/target.gif"
Catch
End Try
End Sub
Private Function AddNodeAndDescendents(folder As DirectoryInfo, parentNode As TreeNode) As TreeNode
' Add the TreeNode, displaying the folder's name and storing the full path to the folder as the value...
Dim virtualFolderPath As String
If parentNode Is Nothing Then
virtualFolderPath = VirtualImageRoot
Else
virtualFolderPath = parentNode.Value + folder.Name + "/"
End If
Dim node As New TreeNode(folder.Name, virtualFolderPath)
node.Selected = (folder.Name = selectedFolderName)
' Recurse through this folder's subfolders
Dim subFolders As DirectoryInfo() = folder.GetDirectories()
For Each subFolder As DirectoryInfo In subFolders
If subFolder.Name <> "_controls" AndAlso subFolder.Name <> "App_Data" Then
Dim child As TreeNode = AddNodeAndDescendents(subFolder, node)
node.ChildNodes.Add(child)
End If
Next
Return node
' Return the new TreeNode
End Function
Protected Sub FolderTree_SelectedNodeChanged(sender As Object, e As EventArgs)
ActionDeny.Checked = True
ActionAllow.Checked = False
ApplyRole.Checked = True
ApplyUser.Checked = False
ApplyAllUsers.Checked = False
ApplyAnonUser.Checked = False
UserRoles.SelectedIndex = 0
UserList.SelectedIndex = 0
RuleCreationError.Visible = False
ResetFolderImageUrls(FolderTree.Nodes(0))
' Restore previously selected folder's ImageUrl.
FolderTree.SelectedNode.ImageUrl = "/Simple/i/target.gif"
' Set the newly selected folder's ImageUrl.
End Sub
Private Sub ResetFolderImageUrls(parentNode As TreeNode)
parentNode.ImageUrl = "/Simple/i/folder.gif"
' Recurse through this node's child nodes.
Dim nodes As TreeNodeCollection = parentNode.ChildNodes
For Each childNode As TreeNode In nodes
ResetFolderImageUrls(childNode)
Next
End Sub
Private Sub DisplayAccessRules(virtualFolderPath As String)
If Not virtualFolderPath.StartsWith(VirtualImageRoot) OrElse virtualFolderPath.IndexOf("..") >= 0 Then
Throw New ApplicationException("An attempt to access a folder outside of the website directory has been detected and blocked.")
End If
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim authorizationRules As AuthorizationRuleCollection = systemWeb.Authorization.Rules
RulesGrid.DataSource = authorizationRules
RulesGrid.DataBind()
TitleOne.InnerText = "Rules applied to " + virtualFolderPath
TitleTwo.InnerText = "Create new rule for " + virtualFolderPath
End Sub
Private Sub RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rule As AuthorizationRule = DirectCast(e.Row.DataItem, AuthorizationRule)
If Not rule.ElementInformation.IsPresent Then
e.Row.Cells(3).Text = "Inherited from higher level"
e.Row.Cells(4).Text = "Inherited from higher level"
e.Row.CssClass = "odd"
End If
End If
End Sub
Private Function GetAction(rule As AuthorizationRule) As String
Return rule.Action.ToString()
End Function
Private Function GetRole(rule As AuthorizationRule) As String
Return rule.Roles.ToString()
End Function
Private Function GetUser(rule As AuthorizationRule) As String
Return rule.Users.ToString()
End Function
Private Sub DeleteRule(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
Dim item As GridViewRow = DirectCast(button.Parent.Parent, GridViewRow)
Dim virtualFolderPath As String = FolderTree.SelectedValue
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim section As AuthorizationSection = DirectCast(systemWeb.Sections("authorization"), AuthorizationSection)
section.Rules.RemoveAt(item.RowIndex)
config.Save()
End Sub
Private Sub MoveUp(sender As Object, e As EventArgs)
MoveRule(sender, e, "up")
End Sub
Private Sub MoveDown(sender As Object, e As EventArgs)
MoveRule(sender, e, "down")
End Sub
Private Sub MoveRule(sender As Object, e As EventArgs, upOrDown As String)
upOrDown = upOrDown.ToLower()
If upOrDown = "up" OrElse upOrDown = "down" Then
Dim button As Button = DirectCast(sender, Button)
Dim item As GridViewRow = DirectCast(button.Parent.Parent, GridViewRow)
Dim selectedIndex As Integer = item.RowIndex
If (selectedIndex > 0 AndAlso upOrDown = "up") OrElse (upOrDown = "down") Then
Dim virtualFolderPath As String = FolderTree.SelectedValue
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim section As AuthorizationSection = DirectCast(systemWeb.Sections("authorization"), AuthorizationSection)
' Pull the local rules out of the authorization section, deleting them from same:
Dim rulesArray As ArrayList = PullLocalRulesOutOfAuthorizationSection(section)
If upOrDown = "up" Then
LoadRulesInNewOrder(section, rulesArray, selectedIndex, upOrDown)
ElseIf upOrDown = "down" Then
If selectedIndex < rulesArray.Count - 1 Then
LoadRulesInNewOrder(section, rulesArray, selectedIndex, upOrDown)
Else
' DOWN button in last row was pressed. Load the rules array back in without resorting.
For x As Integer = 0 To rulesArray.Count - 1
section.Rules.Add(DirectCast(rulesArray(x), AuthorizationRule))
Next
End If
End If
config.Save()
End If
End If
End Sub
Private Sub LoadRulesInNewOrder(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
AddFirstGroupOfRules(section, rulesArray, selectedIndex, upOrDown)
AddTheTwoSwappedRules(section, rulesArray, selectedIndex, upOrDown)
AddFinalGroupOfRules(section, rulesArray, selectedIndex, upOrDown)
End Sub
Private Sub AddFirstGroupOfRules(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
Dim adj As Integer
If upOrDown = "up" Then
adj = 1
Else
adj = 0
End If
For x As Integer = 0 To selectedIndex - adj - 1
section.Rules.Add(DirectCast(rulesArray(x), AuthorizationRule))
Next
End Sub
Private Sub AddTheTwoSwappedRules(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
If upOrDown = "up" Then
section.Rules.Add(DirectCast(rulesArray(selectedIndex), AuthorizationRule))
section.Rules.Add(DirectCast(rulesArray(selectedIndex - 1), AuthorizationRule))
ElseIf upOrDown = "down" Then
section.Rules.Add(DirectCast(rulesArray(selectedIndex + 1), AuthorizationRule))
section.Rules.Add(DirectCast(rulesArray(selectedIndex), AuthorizationRule))
End If
End Sub
Private Sub AddFinalGroupOfRules(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
Dim adj As Integer
If upOrDown = "up" Then
adj = 1
Else
adj = 2
End If
For x As Integer = selectedIndex + adj To rulesArray.Count - 1
section.Rules.Add(DirectCast(rulesArray(x), AuthorizationRule))
Next
End Sub
Private Function PullLocalRulesOutOfAuthorizationSection(section As AuthorizationSection) As ArrayList
' First load the local rules into an ArrayList.
Dim rulesArray As New ArrayList()
For Each rule As AuthorizationRule In section.Rules
If rule.ElementInformation.IsPresent Then
rulesArray.Add(rule)
End If
Next
' Next delete the rules from the section.
For Each rule As AuthorizationRule In rulesArray
section.Rules.Remove(rule)
Next
Return rulesArray
End Function
Private Sub CreateRule(sender As Object, e As EventArgs)
Dim newRule As AuthorizationRule
If ActionAllow.Checked Then
newRule = New AuthorizationRule(AuthorizationRuleAction.Allow)
Else
newRule = New AuthorizationRule(AuthorizationRuleAction.Deny)
End If
If ApplyRole.Checked AndAlso UserRoles.SelectedIndex > 0 Then
newRule.Roles.Add(UserRoles.Text)
AddRule(newRule)
ElseIf ApplyUser.Checked AndAlso UserList.SelectedIndex > 0 Then
newRule.Users.Add(UserList.Text)
AddRule(newRule)
ElseIf ApplyAllUsers.Checked Then
newRule.Users.Add("*")
AddRule(newRule)
ElseIf ApplyAnonUser.Checked Then
newRule.Users.Add("?")
AddRule(newRule)
End If
End Sub
Private Sub AddRule(newRule As AuthorizationRule)
Dim virtualFolderPath As String = FolderTree.SelectedValue
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim section As AuthorizationSection = DirectCast(systemWeb.Sections("authorization"), AuthorizationSection)
section.Rules.Add(newRule)
Try
config.Save()
RuleCreationError.Visible = False
Catch ex As Exception
RuleCreationError.Visible = True
RuleCreationError.Text = "<div class=""alert""><br />An error occurred and the rule was not added. I saw this happen during testing when I attempted to create a rule that the ASP.NET infrastructure realized was redundant. Specifically, I had the rule <i>DENY ALL USERS</i> in one folder, then attempted to add the same rule in a subfolder, which caused ASP.NET to throw an exception.<br /><br />Here's the error message that was thrown just now:<br /><br /><i>" + ex.Message + "</i></div>"
End Try
End Sub
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="c" Runat="Server">
<!-- #include file="_nav.aspx -->
<table class="webparts">
<tr>
<th>Website Access Rules</th>
</tr>
<tr>
<td class="details" valign="top">
<p>
Use this page to manage access rules for your Web site. Rules are applied to folders, thus providing robust folder-level security enforced by the ASP.NET infrastructure. Rules are persisted as XML in each folder's Web.config file. <i>Page-level security and inner-page security are not handled using this tool — they are handled using specialized code that is available to the Web Developers.</i>
</p>
<table>
<tr>
<td valign="top" style="padding-right: 30px;">
<div class="treeview">
<asp:TreeView runat="server" ID="FolderTree"
OnSelectedNodeChanged="FolderTree_SelectedNodeChanged">
<RootNodeStyle ImageUrl="/Simple/i/folder.gif" />
<ParentNodeStyle ImageUrl="/Simple/i/folder.gif" />
<LeafNodeStyle ImageUrl="/Simple/i/folder.gif" />
<SelectedNodeStyle Font-Underline="true" ForeColor="#A21818" />
</asp:TreeView>
</div>
</td>
<td valign="top" style="padding-left: 30px; border-left: 1px solid #999;">
<asp:Panel runat="server" ID="SecurityInfoSection" Visible="false">
<h2 runat="server" id="TitleOne" class="alert"></h2>
<p>
Rules are applied in order. The first rule that matches applies, and the permission in each rule overrides the permissions in all following rules. Use the Move Up and Move Down buttons to change the order of the selected rule. Rules that appear dimmed are inherited from the parent and cannot be changed at this level.
</p>
<asp:GridView runat="server" ID="RulesGrid" AutoGenerateColumns="false"
CssClass="list" GridLines="none"
OnRowDataBound="RowDataBound"
>
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<!--response.write(GetAction((AuthorizationRule)Container.DataItem))-->
**<%#GetAction((AuthorizationRule), Container.DataItem)%>**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roles">
<ItemTemplate>
<!-- response.write(GetRole((AuthorizationRule)Container.DataItem))-->
**<%# GetRole((AuthorizationRule),Container.DataItem) %>**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User">
<ItemTemplate>
<!-- response.write(GetUser((AuthorizationRule)Container.DataItem))-->
**<%#GetUser((AuthorizationRule), Container.DataItem)%>**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Rule">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Delete Rule" CommandArgument="<%# (AuthorizationRule)Container.DataItem %>" OnClick="DeleteRule" OnClientClick="return confirm('Click OK to delete this rule.')" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Move Rule">
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text=" Up " CommandArgument="<%# (AuthorizationRule)Container.DataItem %>" OnClick="MoveUp" />
<asp:Button ID="Button3" runat="server" Text="Down" CommandArgument="<%# (AuthorizationRule)Container.DataItem %>" OnClick="MoveDown" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<hr />
<h2 runat="server" id="TitleTwo" class="alert"></h2>
<b>Action:</b>
<asp:RadioButton runat="server" ID="ActionDeny" GroupName="action"
Text="Deny" Checked="true" />
<asp:RadioButton runat="server" ID="ActionAllow" GroupName="action"
Text="Allow" />
<br /><br />
<b>Rule applies to:</b>
<br />
<asp:RadioButton runat="server" ID="ApplyRole" GroupName="applyto"
Text="This Role:" Checked="true" />
<asp:DropDownList ID="UserRoles" runat="server" AppendDataBoundItems="true">
<asp:ListItem>Select Role</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RadioButton runat="server" ID="ApplyUser" GroupName="applyto"
Text="This User:" />
<asp:DropDownList ID="UserList" runat="server" AppendDataBoundItems="true">
<asp:ListItem>Select User</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RadioButton runat="server" ID="ApplyAllUsers" GroupName="applyto"
Text="All Users (*)" />
<br />
<asp:RadioButton runat="server" ID="ApplyAnonUser" GroupName="applyto"
Text="Anonymous Users (?)" />
<br /><br />
<asp:Button ID="Button4" runat="server" Text="Create Rule" OnClick="CreateRule"
OnClientClick="return confirm('Click OK to create this rule.');" />
<asp:Literal runat="server" ID="RuleCreationError"></asp:Literal>
</asp:Panel>
</td>
</tr>
</table>
</td>
</tr>
</table>
</asp:Content>
'AuthorizationRule' is a type and cannot be used as an expression.
errors are bold.
In some places of your markup you have an unnecessary , (line no. 352, 358 and 364)
stuff like
<%#GetAction((AuthorizationRule), Container.DataItem)%>
I think, should be
<%#GetAction(DirectCast(Container.DataItem, AuthorizationRule))%>
similarly
<%#GetRole(CType(Container.DataItem, AuthorizationRule))%>
and
<%#GetUser(DirectCast(Container.DataItem, AuthorizationRule))%>
Also use this replacing what you have
<asp:Button ID="Button1" runat="server" Text="Delete Rule" CommandArgument='<%# DirectCast(Container.DataItem, AuthorizationRule) %>' OnClick="DeleteRule" OnClientClick="return confirm('Click OK to delete this rule.')" />
and
<asp:Button ID="Button2" runat="server" Text=" Up " CommandArgument='<%# DirectCast(Container.DataItem, AuthorizationRule) %>' OnClick="MoveUp" />
<asp:Button ID="Button3" runat="server" Text="Down" CommandArgument='<%# DirectCast(Container.DataItem, AuthorizationRule) %>' OnClick="MoveDown" />

Resources