' Copyright (c) 2003, Plumtree Software

' All rights reserved.

' Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

' 1.  Neither the name of Plumtree Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission; 

' 2.  Licensee acknowledges that no license or other permission is granted herein with respect to any third party software and that Licensee may not use the code in any way that would infringe any third party right.

' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NONINFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. REGARDLESS OF THE BASIS OF RECOVERY CLAIMED, WHETHER UNDER ANY CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE AND STRICT LIABILITY), BREACH OF STATUTORY DUTY, PRINCIPLES OF CONTRIBUTION OR 
' ANY OTHER THEORY OF LIABILITY, IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
' THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE; AND IN NO EVENT WILL THE COPYRIGHT OWNER'S OR CONTRIBUTORS' EXCEED $10,000.

Imports System
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Imports Plumtree.Remote.Portlet
Imports Plumtree.Remote.PRC
Imports Plumtree.Remote.PRC.Collaboration
Imports Plumtree.Remote.PRC.Collaboration.Project
Imports Plumtree.Remote.PRC.Collaboration.Security

Public Class SecurityExampleVB
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents DropDownButton As System.Web.UI.WebControls.Button
    Protected WithEvents SecurityOptionsDropDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents AddMemberPanel As System.Web.UI.WebControls.Panel
    Protected WithEvents AddMemberDropDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents AddMemberIDInput As System.Web.UI.WebControls.TextBox
    Protected WithEvents AddMemberButton As System.Web.UI.WebControls.Button
    Protected WithEvents RemoveMemberPanel As System.Web.UI.WebControls.Panel
    Protected WithEvents RemoveMemberIDInput As System.Web.UI.WebControls.TextBox
    Protected WithEvents RemoveMemberDropDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents RemoveMemberButton As System.Web.UI.WebControls.Button
    Protected WithEvents RetrieveMembersPanel As System.Web.UI.WebControls.Panel
    Protected WithEvents RetrieveMembersDropDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents RetrieveMembersButton As System.Web.UI.WebControls.Button
    Protected WithEvents SetSecurityPanel As System.Web.UI.WebControls.Panel
    Protected WithEvents SetSecurityButton As System.Web.UI.WebControls.Button
    Protected WithEvents SetSecurityRoleTypeDropDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents FunctionalAreaDropDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents AccessLevelDropDownList As System.Web.UI.WebControls.DropDownList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region


    Dim sampleProject As IProject = Nothing

    Dim projectManager As IProjectManager
    Dim remoteSession As IRemoteSession
    Dim collabFactory As ICollaborationFactory
    Shared isLoaded As Boolean

    Dim SecurityOptions() As String = {"Add member", _
                                                "Remove member", _
                                                "Retrieve members", _
                                                "Set security for a functional area"}

    Dim RoleTypeOptions() As String = {"Member", "Guest"}
    Dim RetrieveRoleTypeOptions() As String = {"Member", "Guest", "Leader"}

    Dim FunctionalAreaOptions() As String = {"Discussion", _
                                                "Document", _
                                                "Document Folder", _
                                                "Project", _
                                                "Task List"}

    Dim AccessLevelOptions() As String = {"Admin", _
                                                "Edit", _
                                                "Write", _
                                                "Read", _
                                                "None"}



    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim portletContext As IPortletContext = PortletContextFactory.CreatePortletContext(Request, Response)
        remoteSession = portletContext.GetRemotePortalSession()		
        collabFactory = remoteSession.GetCollaborationFactory()
        projectManager = collabFactory.GetProjectManager()

        sampleProject = DirectCast(Session.Item("edk_sample_project"), IProject)
        If (sampleProject Is Nothing) Then
            Response.Redirect("../project/ProjectCreatorVB.aspx?source=../security/SecurityExampleVB.aspx")
        End If

        If (Not isLoaded Or SecurityOptionsDropDownList Is Nothing Or SecurityOptionsDropDownList.SelectedIndex = -1) Then
            SecurityOptionsDropDownList.DataSource = SecurityOptions
            SecurityOptionsDropDownList.DataBind()  'binds the data
            isLoaded = True
        End If
        GetPostBackEventReference(Me)
    End Sub

    Private Sub DropDownButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownButton.Click
        'Add Member
        If (SecurityOptionsDropDownList.SelectedIndex = 0) Then
            AddMemberPanel.Visible = True
            AddMemberPanel.Enabled = True
            AddMemberDropDownList.DataSource = RoleTypeOptions
            AddMemberDropDownList.DataBind()

            'Remove Member
        ElseIf (SecurityOptionsDropDownList.SelectedIndex = 1) Then
            RemoveMemberPanel.Visible = True
            RemoveMemberPanel.Enabled = True
            RemoveMemberDropDownList.DataSource = RoleTypeOptions
            RemoveMemberDropDownList.DataBind()

            'Retrieve Members
        ElseIf (SecurityOptionsDropDownList.SelectedIndex = 2) Then
            RetrieveMembersPanel.Visible = True
            RetrieveMembersPanel.Enabled = True
            RetrieveMembersDropDownList.DataSource = RetrieveRoleTypeOptions
            RetrieveMembersDropDownList.DataBind()

            'Set security for a functional area
        ElseIf (SecurityOptionsDropDownList.SelectedIndex = 3) Then
            SetSecurityPanel.Visible = True
            SetSecurityPanel.Enabled = True
            SetSecurityRoleTypeDropDownList.DataSource = RoleTypeOptions
            SetSecurityRoleTypeDropDownList.DataBind()
            FunctionalAreaDropDownList.DataSource = FunctionalAreaOptions
            FunctionalAreaDropDownList.DataBind()
            AccessLevelDropDownList.DataSource = AccessLevelOptions
            AccessLevelDropDownList.DataBind()
        End If

        GetPostBackEventReference(Me)
    End Sub

    Private Sub AddMemberButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddMemberButton.Click
        Dim roleType As RoleTypes = RoleTypes.Member
        Dim addMemberID As Integer = -1

        If (AddMemberDropDownList.SelectedIndex = 0) Then
            roleType = RoleTypes.Member
        ElseIf (AddMemberDropDownList.SelectedIndex = 1) Then
            roleType = RoleTypes.Guest
        End If

        Try
            addMemberID = Integer.Parse(AddMemberIDInput.Text)
        Catch ex As FormatException
            'for invalid input ID, print out error message and abort
            Response.Write("Cannot parse add member ID: [" & AddMemberIDInput.Text & "]")
            AddMemberPanel.Visible = False
            Return
        End Try

        'for valid Member ID
        Dim role As IRole = Nothing
        If (sampleProject Is Nothing) Then
            Response.Redirect("../project/ProjectCreatorVB.aspx?source=../security/SecurityExampleVB.aspx")
        End If

        If Not (sampleProject Is Nothing) Then
            role = sampleProject.GetRole(roleType)
            role.AddMember(addMemberID, MemberTypes.User)

            Try
                role.Store()
            Catch ex As Exception
                'failed to add non-negative ID, print out error message and abort
                Response.Write("Failed to add member with id=" & addMemberID & " to role. <br/> Cause of error is: ")
                Response.Write(ex.Message)
                AddMemberPanel.Visible = False
                Return
            End Try

            Dim memberIDs As Integer() = role.GetMemberIDs(MemberQueryTypes.AllUsers)
            Dim html As StringBuilder = New StringBuilder
            html.Append("Updated role ")
            html.Append(role.Name)
            html.Append(" - added user with ID=")
            html.Append(addMemberID)
            html.Append(".")
            html.Append("<br/>")
            html.Append("Now the role has ")
            html.Append(memberIDs.Length)
            html.Append(" members.")
            html.Append("<br/> <br/>")

            For i As Integer = 0 To memberIDs.Length - 1
                html.Append("<br/>")
                html.Append("memberIDs[")
                html.Append(i)
                html.Append("] is ")
                html.Append(memberIDs(i))
            Next i
            Response.Write(html.ToString())
        End If
        AddMemberPanel.Visible = False
    End Sub



    Private Sub RetrieveMembersButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RetrieveMembersButton.Click
        Dim roleType As RoleTypes = RoleTypes.Member

        If (RetrieveMembersDropDownList.SelectedIndex = 0) Then
            roleType = RoleTypes.Member
        ElseIf (RetrieveMembersDropDownList.SelectedIndex = 1) Then
            roleType = RoleTypes.Guest
        ElseIf (RetrieveMembersDropDownList.SelectedIndex = 2) Then
            roleType = RoleTypes.Leader
        End If

        'for valid Member ID
        Dim role As IRole = Nothing
        If (sampleProject Is Nothing) Then
            Response.Redirect("../project/ProjectCreatorVB.aspx?source=../security/SecurityExampleVB.aspx")
        End If

        If Not (sampleProject Is Nothing) Then
            role = sampleProject.GetRole(roleType)
            Dim memberIDs As Integer() = role.GetMemberIDs(MemberQueryTypes.AllUsers)

            Dim html As StringBuilder = New StringBuilder
            html.Append(role.Name)
            html.Append(" has ")
            html.Append(memberIDs.Length)
            html.Append(" members.")
            html.Append("<br/> <br/>")

            For i As Integer = 0 To memberIDs.Length - 1
                html.Append("<br/>")
                html.Append("memberIDs[")
                html.Append(i)
                html.Append("] is ")
                html.Append(memberIDs(i))
            Next i
            Response.Write(html.ToString())
        End If

        RetrieveMembersPanel.Visible = False
    End Sub


    Private Sub SetSecurityButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetSecurityButton.Click
        'get role type information
        Dim roleType As RoleTypes = RoleTypes.Member
        If (SetSecurityRoleTypeDropDownList.SelectedIndex = 0) Then
            roleType = RoleTypes.Member
        ElseIf (SetSecurityRoleTypeDropDownList.SelectedIndex = 1) Then
            roleType = RoleTypes.Guest
        End If

        'get functional area information
        Dim functionalArea As FunctionalAreas = FunctionalAreas.Discussion
        If (FunctionalAreaDropDownList.SelectedIndex = 0) Then
            functionalArea = FunctionalAreas.Discussion
        ElseIf (FunctionalAreaDropDownList.SelectedIndex = 1) Then
            functionalArea = FunctionalAreas.Document
        ElseIf (FunctionalAreaDropDownList.SelectedIndex = 2) Then
            functionalArea = FunctionalAreas.DocumentFolder
        ElseIf (FunctionalAreaDropDownList.SelectedIndex = 3) Then
            functionalArea = FunctionalAreas.Project
        ElseIf (FunctionalAreaDropDownList.SelectedIndex = 4) Then
            functionalArea = FunctionalAreas.TaskList
        End If

        'get functional area information
        Dim accessLevel As AccessLevels = AccessLevels.Admin
        If (AccessLevelDropDownList.SelectedIndex = 0) Then
            accessLevel = AccessLevels.Admin
        ElseIf (AccessLevelDropDownList.SelectedIndex = 1) Then
            accessLevel = AccessLevels.Edit
        ElseIf (AccessLevelDropDownList.SelectedIndex = 2) Then
            accessLevel = AccessLevels.Write
        ElseIf (AccessLevelDropDownList.SelectedIndex = 3) Then
            accessLevel = AccessLevels.Read
        ElseIf (AccessLevelDropDownList.SelectedIndex = 4) Then
            accessLevel = AccessLevels.None
        End If

        Dim role As IRole = Nothing
        If (sampleProject Is Nothing) Then
            Response.Redirect("../project/ProjectCreatorVB.aspx?source=../security/SecurityExampleVB.aspx")
        End If

        If Not (sampleProject Is Nothing) Then
            role = sampleProject.GetRole(roleType)
            role.SetAccessLevel(functionalArea, accessLevel)

            Try
                role.Store()
            Catch ex As Exception
                'failed to remove non-negative ID, print out error message and abort
                Response.Write("Failed to set security for function area=" & functionalArea.ToString & ", with access level=" & accessLevel.ToString & ". <br/> Cause of error is: ")
                Response.Write(ex.Message)
                SetSecurityPanel.Visible = False
                Return
            End Try

            Dim html As StringBuilder = New StringBuilder
            html.Append("Updated role ")
            html.Append(role.Name)
            html.Append(" with access level set to ")
            html.Append(role.GetAccessLevel(functionalArea).ToString)
            html.Append(" for ")
            html.Append(functionalArea.ToString)
            html.Append(". ")
            html.Append("<br/> <br/>")
            Response.Write(html.ToString())
        End If
        SetSecurityPanel.Visible = False
    End Sub


    Private Sub RemoveMemberButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveMemberButton.Click
        Dim roleType As RoleTypes = RoleTypes.Member
        Dim removeMemberID As Integer = -1

        If (RemoveMemberDropDownList.SelectedIndex = 0) Then
            roleType = RoleTypes.Member
        ElseIf (RemoveMemberDropDownList.SelectedIndex = 1) Then
            roleType = RoleTypes.Guest
        End If

        Try
            removeMemberID = Integer.Parse(RemoveMemberIDInput.Text)
        Catch ex As FormatException
            'for invalid input ID, print out error message and abort
            Response.Write("Cannot parse remove member ID: [" & RemoveMemberIDInput.Text & "]")
            RemoveMemberPanel.Visible = False
            Return
        End Try

        'for valid Member ID
        Dim role As IRole = Nothing
        If (sampleProject Is Nothing) Then
            Response.Redirect("../project/ProjectCreatorVB.aspx?source=../security/SecurityExampleVB.aspx")
        End If

        If Not (sampleProject Is Nothing) Then
            role = sampleProject.GetRole(roleType)
            role.RemoveMember(removeMemberID, MemberTypes.User)

            Try
                role.Store()
            Catch ex As Exception
                'failed to remove non-negative ID, print out error message and abort
                Response.Write("Failed to remove member with id=" & removeMemberID & ". <br/> Cause of error is: ")
                Response.Write(ex.Message)
                RemoveMemberPanel.Visible = False
                Return
            End Try

            Dim memberIDs As Integer() = role.GetMemberIDs(MemberQueryTypes.AllUsers)
            Dim html As StringBuilder = New StringBuilder
            html.Append("Updated role ")
            html.Append(role.Name)
            html.Append(" - removed user with ID : ")
            html.Append(removeMemberID)
            html.Append(".")
            html.Append("<br/>")
            html.Append("Now the role has ")
            html.Append(memberIDs.Length)
            html.Append(" members.")
            html.Append("<br/> <br/>")

            For i As Integer = 0 To memberIDs.Length - 1
                html.Append("<br/>")
                html.Append("memberIDs[")
                html.Append(i)
                html.Append("] is ")
                html.Append(memberIDs(i))
            Next i
            Response.Write(html.ToString())
        End If

        RemoveMemberPanel.Visible = False
    End Sub
End Class
