?
Solved

Help needed with Sharepoint Webpart

Posted on 2005-03-22
15
Medium Priority
?
1,214 Views
Last Modified: 2012-05-11
Hi,

I'm trying to create a sharepoint webpart that allows users of sharepoint to search the configured active directory for users details. Ie. email address and telephone number. I have created the code within a normal asp.net website and got it working so i know that the active directory search application code is working however I am now struggling to port the application into a webpart.

Using the code below I have managed to get the search box and button to display on the sharepoint page and for some reason the required field validator text is always present so  that is one of the issues, how to make it only visible when a user tries to submit the form without entering a search name. The other problem so far is that I am struggling to add the click event to the button so it fires off the active directory search code. When a user clicks the button the page refreshes but nothing happens.

Any help would be appreciated. I have pasted the webpart code I am using below I would be grateful if someone would look over it and point out the mistakes I am making.

Many thanks,

Robert Hedley

Imports System
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml.Serialization
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Utilities
Imports Microsoft.SharePoint.WebPartPages

'Description for WebPart1.
<DefaultProperty("Text"), ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>"), XmlRoot(Namespace:="SharepointADStaffSearch")> _
Public Class WebPart1
    Inherits Microsoft.SharePoint.WebPartPages.WebPart

    Private SearchBox As TextBox
    Private WithEvents SearchButton As Button
    Private SearchResults As DataGrid
    Public dsResults1 As DataSet
    Private lblNoResults As Label
    Private Validator As RequiredFieldValidator

    Protected Overrides Sub CreateChildControls()
        '
        SearchBox = New TextBox
        SearchBox.ID = "SearchBox1"
        SearchBox.Width = New Unit(287)
        SearchBox.ForeColor = System.Drawing.Color.DarkBlue
        '
        SearchButton = New Button
        SearchButton.ID = "SearchButton1"
        SearchButton.Text = "Submit"
        SearchButton.Width = New Unit(58)
        SearchButton.ForeColor = System.Drawing.Color.DarkBlue
        SearchButton.CausesValidation = True
        '
        SearchResults = New DataGrid
        SearchResults.ID = "SearchResults1"
        SearchResults.Width = New Unit(300)
        SearchResults.ForeColor = System.Drawing.Color.DarkBlue
        SearchResults.HeaderStyle.BackColor = System.Drawing.Color.LightBlue
        SearchResults.HeaderStyle.ForeColor = System.Drawing.Color.White
        SearchResults.Visible = False
        '
        lblNoResults = New Label
        lblNoResults.ID = "lblNoResults1"
        lblNoResults.Text = "No matches were found."
        lblNoResults.Visible = False
        lblNoResults.ForeColor = System.Drawing.Color.DarkBlue
        '
        Validator = New RequiredFieldValidator
        Validator.ID = "Validator1"
        Validator.ControlToValidate = SearchBox.ID
        Validator.ErrorMessage = "Required"
        Validator.Display = ValidatorDisplay.Static
        '
    End Sub

    'Render this Web Part to the output parameter specified.
    Protected Overrides Sub RenderWebPart(ByVal output As System.Web.UI.HtmlTextWriter)
        '
        EnsureChildControls()
        '
        output.RenderBeginTag("BR")
        output.RenderEndTag()
        Me.SearchBox.RenderControl(output)
        Me.SearchButton.RenderControl(output)
        output.RenderBeginTag("BR")
        output.RenderEndTag()
        Me.Validator.RenderControl(output)
        output.RenderBeginTag("BR")
        output.RenderEndTag()
        Me.lblNoResults.RenderControl(output)
        Me.SearchResults.RenderControl(output)
        '
        RenderChildren(output)
        '
    End Sub

    Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchButton.Click
        'Perform search
        dsResults1 = New DataSet
        dsResults1.Merge(StaffSearchAD.SearchSurname(SearchBox.Text))
        If dsResults1.Tables(0).Rows.Count.Equals(0) Then
            'Show no results
            lblNoResults.Visible = True
            SearchResults.Visible = False
        Else
            'Show grid of results
            SearchResults.Visible = True
            SearchResults.DataSource = "dsResults1"
            SearchResults.DataMember = "Results"
            SearchResults.DataBind()
            lblNoResults.Visible = False
        End If
    End Sub

End Class
0
Comment
Question by:rhedley
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
15 Comments
 
LVL 6

Accepted Solution

by:
zupi5 earned 2000 total points
ID: 13604865
add all of your controls to the controls collection in createChildControls() like so:


Controls.Add(lblNoResults)
Controls.Add(SearchBox)
Controls.Add(SearchButton)
Controls.Add(SearchResults)
Controls.Add(dsResults1)
Controls.Add(lblNoResults)
Controls.Add(Validator)



0
 

Author Comment

by:rhedley
ID: 13606264
Thanks, I have just tried what you suggested but now the form is drawn twice and when I submit a search name a sharepoint error page is produced saying that an unexpected error has occurred.

Regards,

Robert
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13609238

comment out RenderChildren(output)  - this function renders the second form
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 

Author Comment

by:rhedley
ID: 13611445
Hi Zupi5, thanks for your suggestion it has cured the control formatting, duplication and required field validator problems, they are now all ok however when I click enter a name and click the search button the unexpected error message is still shown. I think I must not have assigned the click action to the control called searchbutton properly. Does anyone know how this is done properly?

Many thanks,

Robert Hedley
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13611725
put the  code of your button_click event into a try catch block so we can rule out that part of code
does it say anything else or just  unexpected error?
0
 

Author Comment

by:rhedley
ID: 13612837
Hi Zupi, I put a try catch block in telling it to display the error as a text label but it still gives the unexpected error message. Nothing else is given. I have pasted the whole of my code below so you can see the whole picture.

Imports System
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml.Serialization
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Utilities
Imports Microsoft.SharePoint.WebPartPages
Imports System.Xml
Imports System.DirectoryServices
Imports System.Web
Imports System.Security.Principal


'Description for WebPart1.
<DefaultProperty("Text"), ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>"), XmlRoot(Namespace:="SharepointADStaffSearch")> _
Public Class WebPart1
    Inherits Microsoft.SharePoint.WebPartPages.WebPart

    Private SearchBox As TextBox
    Protected WithEvents SearchButton As Button
    Private SearchResults As DataGrid
    Private lblNoResults As Label
    Private Validator As RequiredFieldValidator
    Private ValidatorSummary As ValidationSummary

    Protected Overrides Sub CreateChildControls()
        '
        SearchBox = New TextBox
        SearchBox.ID = "SearchBox1"
        SearchBox.Width = New Unit(287)
        SearchBox.ForeColor = System.Drawing.Color.DarkBlue
        '
        SearchButton = New Button
        SearchButton.ID = "SearchButton1"
        SearchButton.Text = "Submit"
        SearchButton.Width = New Unit(58)
        SearchButton.ForeColor = System.Drawing.Color.DarkBlue
        SearchButton.CausesValidation = True
        '
        SearchResults = New DataGrid
        SearchResults.ID = "SearchResults1"
        SearchResults.Width = New Unit(300)
        SearchResults.ForeColor = System.Drawing.Color.DarkBlue
        SearchResults.HeaderStyle.BackColor = System.Drawing.Color.LightBlue
        SearchResults.HeaderStyle.ForeColor = System.Drawing.Color.White
        SearchResults.Visible = False
        '
        lblNoResults = New Label
        lblNoResults.ID = "lblNoResults1"
        lblNoResults.Text = "No matches were found."
        lblNoResults.Visible = False
        lblNoResults.ForeColor = System.Drawing.Color.DarkBlue
        '
        Validator = New RequiredFieldValidator
        Validator.ID = "Validator1"
        Validator.ControlToValidate = SearchBox.ID
        Validator.ErrorMessage = "A surname is required before attempting a staff search"
        Validator.Display = ValidatorDisplay.None
        '
        ValidatorSummary = New ValidationSummary
        ValidatorSummary.ID = "ValidatorSummary1"
        ValidatorSummary.HeaderText = "The following errors have occured:"
        ValidatorSummary.ShowMessageBox = True
        ValidatorSummary.DisplayMode = ValidationSummaryDisplayMode.List
        ValidatorSummary.ShowSummary = False
        '
        Controls.Add(SearchBox)
        Controls.Add(SearchButton)
        Controls.Add(Validator)
        Controls.Add(SearchResults)
        Controls.Add(lblNoResults)
        Controls.Add(ValidatorSummary)
        '
    End Sub

    'Render this Web Part to the output parameter specified.
    Protected Overrides Sub RenderWebPart(ByVal output As System.Web.UI.HtmlTextWriter)
        '
        EnsureChildControls()
        '
        output.RenderBeginTag("BR")
        output.RenderEndTag()
        Me.SearchBox.RenderControl(output)
        output.Write("&nbsp;")
        Me.SearchButton.RenderControl(output)
        output.Write("&nbsp;")
        Me.Validator.RenderControl(output)
        Me.ValidatorSummary.RenderControl(output)
        output.RenderBeginTag("BR")
        output.RenderEndTag()
        output.RenderBeginTag("HR")
        output.RenderEndTag()
        output.RenderBeginTag("BR")
        output.RenderEndTag()
        Me.lblNoResults.RenderControl(output)
        Me.SearchResults.RenderControl(output)
        '
    End Sub

    Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchButton.Click
        'Perform search
        '
        Try
            Dim strLDAPPath = "LDAP://dc=mydomain,dc=net"
            Dim strLDAPUsername = "MyDomain\LDAPUsername"
            Dim strLDAPPassword = "xxxxxxx"
            '
            Dim strResults As String
            Dim user As System.DirectoryServices.DirectoryEntry
            Dim resultsName As String
            Dim resultsEmail As String
            Dim resultsTelephone As String
            '
            Dim entry As New DirectoryServices.DirectoryEntry(strLDAPPath, strLDAPUsername, strLDAPPassword)
            Dim mySearcher As New System.DirectoryServices.DirectorySearcher(entry)
            Dim result As System.DirectoryServices.SearchResult
            mySearcher.Filter = ("(anr= " & SearchBox.Text & ")")
            '
            Dim dsSearchResults As DataSet = New DataSet
            '
            Dim dtSearchResults As DataTable
            dtSearchResults = New DataTable("Results")
            '
            Dim Name As DataColumn = New DataColumn("Name")
            Name.DataType = System.Type.GetType("System.String")
            dtSearchResults.Columns.Add(Name)
            '
            Dim Email As DataColumn = New DataColumn("Email Address")
            Email.DataType = System.Type.GetType("System.String")
            dtSearchResults.Columns.Add(Email)
            '
            Dim Telephone As DataColumn = New DataColumn("Telephone")
            Telephone.DataType = System.Type.GetType("System.String")
            dtSearchResults.Columns.Add(Telephone)
            '
            For Each result In mySearcher.FindAll()
                '
                user = New System.DirectoryServices.DirectoryEntry(result.GetDirectoryEntry.Path)
                '
                resultsName = user.Properties.Item("givenName").Value & " " & user.Properties.Item("sn").Value
                resultsEmail = user.Properties.Item("mail").Value
                resultsTelephone = user.Properties.Item("telephonenumber").Value
                '
                Dim rc As DataRowCollection
                Dim newRow As DataRow
                rc = dtSearchResults.Rows
                newRow = dtSearchResults.NewRow()
                '
                newRow(0) = resultsName
                newRow(1) = resultsEmail
                newRow(2) = resultsTelephone
                rc.Add(newRow)
                '
            Next
            '
            dsSearchResults.Tables.Add(dtSearchResults)
            '
            If dsSearchResults.Tables(0).Rows.Count.Equals(0) Then
                'Show no results
                lblNoResults.Visible = True
                SearchResults.Visible = False
            Else
                'Show grid of results
                SearchResults.Visible = True
                SearchResults.DataSource = "dsSearchResults"
                SearchResults.DataMember = "Results"
                SearchResults.DataBind()
                lblNoResults.Visible = False
            End If
        Catch ex As Exception
            lblNoResults.Text = ex.Message
            lblNoResults.Visible = True
        End Try

    End Sub

End Class
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13613775
did you recompile your webpart after adding the try catch block, I have compiled the code you've posted into a webpart and it works (lblNoResults shows error of Logon failure: unknown user name or bad password, this is normal as i have not changed you code), if I however comment-out try catch block I get this error on submiting
----
An unexpected error has occurred.

Web Parts Maintenance Page: If you have permission, you can use this page to temporarily disable Web Parts or remove personal settings. For more information, contact your site administrator.
---
are you getting this error, if so, you will have to rebuild your solution ...
0
 

Author Comment

by:rhedley
ID: 13615224
Everytime I saved changes I recompiled the project and the individual cab file and then redeployed on our sharepoint portal server for testing. I get exactly the same error message you get:

----
An unexpected error has occurred.

Web Parts Maintenance Page: If you have permission, you can use this page to temporarily disable Web Parts or remove personal settings. For more information, contact your site administrator.
---

With or without the Try Catch block.

Many thanks
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13619342
lets try this if you can, don't distribute the file in a cab form just copy your webpart's .dll file to your sharepoint server into wwwroot/bin folder (wwwroot is the root folder of the portal, default is c:\inetpub\wwwroot) and remove your webpart from GAC if its present there by any chance. Its possible that the file is not overwritten on your SPS server.
0
 

Author Comment

by:rhedley
ID: 13619653
Ok done that but what am I supposed to do with the .dll afterwards? Do I need to register it somewhere in Sharepoint and how do I get it to display on the portal page?

Thanks.
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13621380
just copy it into \bin folder in the root folder of your SPS web site,
you will have to declare the webpart as a safe control in web.config file located in the root folder
<SafeControl Assembly="WebPart1" Namespace="WebPart1" TypeName="*" Safe="True" />

you can add a webpart to a page via edit page link/addwebparts /import; where you upload thw .dwp file of your webpart
0
 

Author Comment

by:rhedley
ID: 13628857
OK tried that and I still get the same unexpected error message. To rule out my sharepoint server I installed the same webpart onto a clients sharepoint server and I get the same results.

Robert
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13635704
sorry, but I ran out of ideas
0
 

Author Comment

by:rhedley
ID: 13638810
Hi Zupi,

I've made progress! I started to comment out blocks of the code contained within the button_click function and it started to work. So in the end I discovered that the code for the webpart, buttons and validators worked but the system.directoryservices classes are not trusted enough within sharepoint to work that is why I get the unexpected error message. I have found some articles relating to the problem I now face so am working through.

I wouldn't have got this far without your help, many thanks.

Robert
0
 
LVL 6

Expert Comment

by:zupi5
ID: 13639696
glad to help, totally forgot about that, i'm using full trust on my development SPS machine
 
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Progress

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question