Add a Parameter Value in SSRS - vb.net

I have a report already setup on the ReportServer. And its subscription as well. What I'm trying to do is add the ParameterValue "CC" and some email addresses then send the email out. It doesn't seem to work.
My code:
Dim emailReader As SqlDataReader = selCount.ExecuteReader
Dim emailsTest As List(Of String) = New List(Of String)
emailsTest.Add("test1#pen.com")
emailsTest.Add("test2#pen.com")
emailsTest.Add("test3#pen.com")
emailsTest.Add("test4#pen.com")
If emailReader.HasRows() Then 'checks to see if there any quotes in query
For Each subscrp As rs.Subscription In subscr
Dim allValues = subscrp.DeliverySettings.ParameterValues
Dim allValuesList As List(Of ReportTriggerTemplate1.rs.ParameterValueOrFieldReference) = allValues.ToList()
Dim CCParameter As ReportTriggerTemplate1.rs.ParameterValue = New ReportTriggerTemplate1.rs.ParameterValue()
CCParameter.Name = "CC"
CCParameter.Value = String.Empty
allValuesList.Add(CCParameter)
Dim toValue = CType(allValuesList.Item(7), ReportTriggerTemplate1.rs.ParameterValue)
For Each testEmail As String In emailsTest
Dim ownerEmail As String = testEmail
If toValue.Value.Contains(ownerEmail) Then
'skip
ElseIf toValue.Value = String.Empty Then
toValue.Value += ownerEmail
Else
toValue.Value += "; " & ownerEmail
End If
Next
subscrp.DeliverySettings.ParameterValues = allValuesList.ToArray()
Dim hello As String = "hi"
tr.FireEvent(EventType, subscrp.SubscriptionID) 'forces subscription to be sent
Next
What I'm adding to toValue.Value doesn't seem to be adding to the report's CC subscription field at all. So what am I missing?

http://msdn.microsoft.com/en-us/library/ms154020%28v=SQL.100%29.aspx
http://msdn.microsoft.com/en-us/library/reportservice2005.reportingservice2005.getsubscriptionproperties.aspx
http://msdn.microsoft.com/en-us/library/reportservice2005.reportingservice2005.setsubscriptionproperties%28v=SQL.105%29.aspx
Try
tr = New rs.ReportingService2005
Dim extSettings As ExtensionSettings = Nothing
Dim desc As String = Nothing
Dim active As ActiveState = Nothing
Dim status As String = Nothing
Dim matchData As String = Nothing
Dim values As ParameterValue() = Nothing
Dim extensionParams As ParameterValueOrFieldReference() = Nothing
Dim mainLogin As System.Net.NetworkCredential = New System.Net.NetworkCredential("ADUser", "Password", "NetworkName")
If mainLogin Is Nothing Then
tr.Credentials = System.Net.CredentialCache.DefaultCredentials
Else
tr.Credentials = mainLogin
End If
'skip to relevant code
For Each subscrp As rs.Subscription In subscr
Dim allValues = subscrp.DeliverySettings.ParameterValues
Dim allValuesList As List(Of ReportTriggerTemplate1.rs.ParameterValueOrFieldReference) = allValues.ToList()
If CType(allValuesList.Item(0), ReportTriggerTemplate1.rs.ParameterValue).Value = "test#pen.com" Then
Dim subsID = subscrp.SubscriptionID
'important code just below
tr.GetSubscriptionProperties(subsID, extSettings, desc, active, status, EventType, matchData, extensionParams)
''''add change to CC here
Dim extSettingsList As List(Of ReportTriggerTemplate1.rs.ParameterValueOrFieldReference) = extSettings.ParameterValues.ToList()
If CType(extSettingsList.Item(1), ReportTriggerTemplate1.rs.ParameterValue).Name = "CC" Then
If CType(extSettingsList.Item(1), ReportTriggerTemplate1.rs.ParameterValue).Value = String.Empty Then
CType(extSettingsList.Item(1), ReportTriggerTemplate1.rs.ParameterValue).Value = emailsTest.Item(0) & ";" & emailsTest.Item(1)
Else
CType(extSettingsList.Item(1), ReportTriggerTemplate1.rs.ParameterValue).Value += ";" & emailsTest.Item(0) & ";" & emailsTest.Item(1)
End If
Else
Dim CCParameter As ReportTriggerTemplate1.rs.ParameterValue = New ReportTriggerTemplate1.rs.ParameterValue()
CCParameter.Name = "CC"
CCParameter.Value = emailsTest.Item(0) & ";" & emailsTest.Item(1)
extSettingsList.Insert(1, CCParameter)
extSettings.ParameterValues = extSettingsList.ToArray
End If
'important code just below
tr.SetSubscriptionProperties(subsID, extSettings, desc, EventType, matchData, extensionParams)
tr.FireEvent(EventType, subscrp.SubscriptionID) 'forces subscription to be sent
Else
End If
Next

Related

VB.Net signedXml "Invalid character in a Base-64 string"

I'm getting an error everytime I try to upload a XML file to an specific server.
It returns "Invalid character in a Base-64 string". Here the code I'm using to sign:
Public Sub Assinar03(ByVal strArqXMLAssinar As String, ByVal strUri As String, ByVal x509Certificado As X509Certificate2, ByVal strArqXMLAssinado As String)
Dim SR As StreamReader = Nothing
SR = File.OpenText(strArqXMLAssinar)
Dim vXMLString As String = SR.ReadToEnd()
SR.Close()
Dim _xnome As String = String.Empty
Dim _serial As String = String.Empty
If x509Certificado IsNot Nothing Then
_xnome = x509Certificado.Subject.ToString()
_serial = x509Certificado.SerialNumber
End If
Dim _X509Cert As New X509Certificate2()
Dim store As New X509Store("MY", StoreLocation.CurrentUser)
store.Open(OpenFlags.[ReadOnly] Or OpenFlags.OpenExistingOnly)
Dim collection As X509Certificate2Collection = DirectCast(store.Certificates, X509Certificate2Collection)
Dim collection1 As X509Certificate2Collection = DirectCast(collection.Find(X509FindType.FindBySerialNumber, _serial, False), X509Certificate2Collection)
If collection1.Count > 0 Then
_X509Cert = Nothing
For i As Integer = 0 To collection1.Count - 1
If DateTime.Now < collection1(i).NotAfter OrElse Not _X509Cert Is Nothing AndAlso _X509Cert.NotAfter < collection1(i).NotAfter Then
_X509Cert = collection1(i)
End If
Next
If _X509Cert Is Nothing Then _X509Cert = collection1(0)
Dim doc As New XmlDocument()
doc.PreserveWhitespace = False
doc.LoadXml(vXMLString)
Dim qtdeRefUri As Integer = doc.GetElementsByTagName(strUri).Count
Dim reference As New Reference()
Dim keyInfo As New KeyInfo()
Dim signedXml As New SignedXml(doc)
signedXml.SigningKey = _X509Cert.PrivateKey
Dim _Uri As XmlAttributeCollection = doc.GetElementsByTagName(strUri).Item(0).Attributes
For Each _atributo As XmlAttribute In _Uri
If _atributo.Name.ToLower.Trim = "Id".ToLower.Trim Then
reference.Uri = "#" + _atributo.InnerText
End If
Next
If reference.Uri Is Nothing Then reference.Uri = ""
reference.DigestMethod = SignedXml.XmlDsigSHA1Url
'--------------------------------------------------
Dim env As New XmlDsigEnvelopedSignatureTransform()
env.Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
reference.AddTransform(env)
'--------------------------
Dim c14 As New XmlDsigC14NTransform(False)
c14.Algorithm = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
reference.AddTransform(c14)
'--------------------------
signedXml.AddReference(reference)
keyInfo.AddClause(New KeyInfoX509Data(_X509Cert))
'--------------------------
signedXml.KeyInfo = keyInfo
signedXml.ComputeSignature()
'--
Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True))
XMLDoc = New XmlDocument()
XMLDoc.PreserveWhitespace = False
XMLDoc = doc
Me.vXMLStringAssinado = XMLDoc.OuterXml
'-----------
Dim SW_2 As StreamWriter = File.CreateText(strArqXMLAssinado)
SW_2.Write(Me.vXMLStringAssinado)
SW_2.Close()
'-----------
End If
SR.Close()
End Sub
Is there something else I should add to the code?
The manual tells me to follow the instructions from https://www.w3.org/TR/xmldsig-core/
Turns out it was a line break when saving the document. I set the .PreserveWhitespace property to true before saving the .xml file and not it seems to be working.

Can't get attributes from AD using vb.net

I use below code to get first name, last name, email, and department from AD using VB.Net 1.1
Public Shared Function GetAttribute(ByVal username As String, ByVal pwd As String) As UserInfo
Dim objUserInfo As New UserInfo
Dim ObjFirstName As String = ""
Dim ObjLastName As String = String.Empty
Dim ObjEmail As String = ""
Dim objDepartment As String = ""
Dim Success As Boolean = False
Dim LDAPAddress As String = ConfigurationSettings.AppSettings.Get("LDAPAddress")
Dim Entry As New System.DirectoryServices.DirectoryEntry(LDAPAddress, username, pwd)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Dim Filter As String = "(samAccountName=" & username & ")"
Dim findUser As DirectorySearcher = New DirectorySearcher(Entry, Filter)
Dim results As SearchResultCollection = findUser.FindAll
Try
Dim Resultsx As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Resultsx Is Nothing)
findUser.PropertiesToLoad.Add("name")
Dim name As String = DirectCast(Resultsx.Properties(name)(0), String)
Dim de As System.DirectoryServices.DirectoryEntry = Resultsx.GetDirectoryEntry()
Dim gg = de.Properties.PropertyNames()
For Each Onn As String In gg
Dim str As String = String.Format("{0}", Onn)
Next
Try
ObjFirstName = de.Properties("GivenName").Value.ToString()
ObjEmail = de.Properties("mail").Value.ToString()
ObjLastName = de.Properties("sn").Value.ToString()
objDepartment = de.Properties("department").Value.ToString()
Catch ex As Exception
ObjFirstName = de.Properties("DisplayName").Value.ToString()
End Try
But I can't get those attributes. in
Dim str As String = String.Format("{0}", Onn)
there are only 15 attributes, and there are no firstname, lastname, email, and department. What am I doing wrong?
Your code, though old-fashioned, looks fine on first sight. If you insist to continue with your code, I'll have a look later.
In the meantime, this code should fit your situation:
Dim user As DirectoryEntry = New DirectoryEntry("UserDN")
Dim src As DirectorySearcher = New DirectorySearcher(user, "(&(objectClass=user)(objectCategory=Person))")
src.PropertiesToLoad.Add("sn")
src.PropertiesToLoad.Add("givenName")
src.PropertiesToLoad.Add("mail")
src.PropertiesToLoad.Add("department")
Dim res As SearchResult = src.FindOne
Console.WriteLine(res.Properties("sn")(0))
Console.WriteLine(res.Properties("givenName")(0))
Console.WriteLine(res.Properties("mail")(0))
Console.WriteLine(res.Properties("department")(0))
Console.ReadLine()

dynamic table and button creation in asp.net

I have created a dynamic table using for loop condition.In which it has a button while i click a specific button it should open a file.But in my coding it is opening a file button in the last row.
If Not IsPostBack Then
txtlogsdate.Text = FormatDate(Now)
End If
Try
trViewlogs.Visible = True
lbllogs.Visible = False
lbllogname.Visible = True
RT1.Visible = False
pb.Visible = False
Dim d1 As DateTime = txtlogsdate.Text
Dim dd As String = d1.ToString("dd")
Dim mm As String = d1.ToString("MM")
Dim yy As String = d1.ToString("yy")
Dim d2 As String = yy & "" & mm & "" & dd
Dim di As DirectoryInfo = New DirectoryInfo(Server.MapPath("~\logs"))
Dim files As FileInfo() = di.GetFiles("*.log")
Dim tab As New Table()
tab.CellPadding = 0
tab.CellSpacing = 0
tab.BorderStyle = BorderStyle.Double
tab.Attributes.Add("style", "margin-left: 0.5px; width: 800px;")
Dim row As New TableRow()
Dim headerCell1 As New TableHeaderCell()
headerCell1.Text = "Logs"
headerCell1.Attributes.Add("style", "margin-left: 0.5px; height: 20px;")
headerCell1.BackColor = System.Drawing.Color.CornflowerBlue
headerCell1.ForeColor = System.Drawing.Color.White
row.Controls.Add(headerCell1)
tab.Controls.Add(row)
Dim headerCell2 = New TableHeaderCell()
headerCell2.Attributes.Add("style", "margin-left: 0.5px; height: 20px;")
headerCell2.BackColor = System.Drawing.Color.CornflowerBlue
headerCell2.ForeColor = System.Drawing.Color.White
headerCell2.Text = "Download"
row.Controls.Add(headerCell2)
tab.Controls.Add(row)
For i As Integer = 0 To files.Length - 1
Dim a As String = files(i).ToString.Replace("Event-", "")
Dim c As String = a.Substring(0, 6)
Dim sw As String
If d2 = c Then
sw = My.Computer.FileSystem.ReadAllText(_
GetWebSitePhysicalRoot & "\logs\" & files(i).ToString)
lbllogname.Text = files(i).ToString
lbllogname.Visible = False
row = New TableRow()
If i Mod 2 = 0 Then
row.BackColor = System.Drawing.Color.White
Else
row.BackColor = System.Drawing.Color.AliceBlue
End If
Dim cell As New TableCell()
cell.Text = lbllogname.Text
'cell.Width = New Unit("1000px")
cell.HorizontalAlign = HorizontalAlign.Center
row.Controls.Add(cell)
Dim cell2 As New TableCell()
Dim bt As New Button
bt.BorderStyle = BorderStyle.Solid
bt.Text = files(i).ToString
AddHandler bt.Click, AddressOf bt_Click
cell2.HorizontalAlign = HorizontalAlign.Center
cell2.Controls.Add(bt)
row.Controls.Add(cell2)
tab.Controls.Add(row)
Panel1.Controls.Add(tab)
End If
Next i
If lbllogname.Text = "" Then
lbllogname.Text = "No Logs to Display !"
End If
Session("pageurl") = ""
Session("pagecount") = ""
ib.SetInfo("Reports > View Logs", Infobar.InfoTypes.Caption)
Dim mi As Integer = GetQueryStringToInt("menuindex", 1)
If Not IsPostBack Then
leftmenu1.AddItem("View Logs", _
GetWebSiteUrlRoot & "/staff_rpt.aspx?rpt=logs&page=1&menuindex=" & mi)
End If
Catch ex As Exception
WriteLog(LogWriter.EventType.eError, ex.StackTrace.ToString)
End Try
Protected Sub bt_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs
Dim a As String
a = lbllogname.Text
Response.ContentType = "text/plain"
Response.AppendHeader("Content-Disposition", "attachment; filename=" & a)
Response.TransmitFile(Server.MapPath("~/logs/" & a))
Response.End()
End Sub
To use the dynamic table structure you have built in your code, then you need to uniquely name each button in each row; otherwise the button click handler (bt_Click) cannot figure out the correct row to open the file in, because they are all called the same and will use the last one.
Since you want a table structure, then I suggest you use the GridView server control, as it will provide similar output, but provide the ability to use templating to name the controls of each row the same, but allow for you to differentiate individual rows when a click event happens.

Excluding Deleted Records from returned Set using VFPOLEDB provider for FOXPRO database

VS 2010, VB.NET, WINFORMS. In my app i have a need to import foxpro database tables and exclude the deleted records. The problem is that FOXPRO tables keep deleted items inside the same table. I have tried using DELETED=NO in the connection string but vb throws
"Format of the initialization string does not conform to the OLE DB specification."
My function is as follows:
Dim _DBConn1 As String = "provider=vfpoledb.1; Data Source = " & file1 & ";DELETED=NO"
Dim _DBConn2 As String = "provider=vfpoledb.1; Data Source = " & file2 & ";DELETED=NO"
Dim _DBConn3 As String = "provider=vfpoledb.1; Data Source = " & file3 & ";DELETED=NO"
Dim _DBConn4 As String = "provider=vfpoledb.1; Data Source = " & file4 & ";DELETED=NO"
Using _connection As New OleDbConnection(_DBConn1)
Dim _savedId As String = String.Empty
_connection.Open()
Using _command As New OleDbCommand("SELECT * FROM " & _fileName1 & "", _connection)
Using _reader2 As OleDbDataReader = _command.ExecuteReader
While _reader2.Read
counter += 1
End While
y = 100 / counter
Dim x As String = String.Empty
End Using
Using _reader As OleDbDataReader = _command.ExecuteReader
While _reader.Read
Dim _letter As Integer = Nothing
Dim _name As String = String.Empty
Dim _content As String = String.Empty
Dim _copies As Integer = Nothing
Dim _type As Integer = Nothing
Dim _fee As Decimal = Nothing
_letter = _reader.Item(0)
_name = _reader.Item(1)
_content = _reader.Item(2)
_copies = _reader.Item(3)
_type = _reader.Item(4)
_fee = _reader.Item(5)
_UpdateLetters(_letter, _name, _content, _copies, _type, _fee)
_progress += y
Dim d As Integer = Convert.ToInt16((Convert.ToString(y).Split(".")(0)))
ProgressBar1.Increment(d)
End While
End Using
End Using
_connection.Close()
End Using
Using _connection As New OleDbConnection(_DBConn2)
Dim _savedId As String = String.Empty
_connection.Open()
Using _command As New OleDbCommand("SELECT * FROM " & _fileName2 & "", _connection)
Using _reader2 As OleDbDataReader = _command.ExecuteReader
While _reader2.Read
counter += 1
End While
y = 100 / counter
Dim x As String = String.Empty
End Using
Using _reader As OleDbDataReader = _command.ExecuteReader
While _reader.Read
Dim _unit As String = String.Empty
Dim _Size As String = String.Empty
Dim _contractDate As String = String.Empty
Dim _deposit As Decimal = Nothing
Dim _Tfirst As String = String.Empty
Dim _Tlast As String = String.Empty
Dim _optional As String = String.Empty
Dim _address1 As String = String.Empty
Dim _address2 As String = String.Empty
Dim _city As String = String.Empty
Dim _st As String = String.Empty
Dim _zip As String = String.Empty
Dim _hphone As String = String.Empty
Dim _drLicense As String = String.Empty
Dim _employer As String = String.Empty
Dim _wphone As String = String.Empty
Dim _bname As String = String.Empty
Dim _baddress1 As String = String.Empty
Dim _baddress2 As String = String.Empty
Dim _bCity As String = String.Empty
Dim _bState As String = String.Empty
Dim _bZip As String = String.Empty
Dim _bPhone As String = String.Empty
Dim _contact_Name As String = String.Empty
Dim _contact_Address1 As String = String.Empty
Dim _contact_Address2 As String = String.Empty
Dim _contact_City As String = String.Empty
Dim _contact_State As String = String.Empty
Dim _contact_zip As String = String.Empty
Dim _contact_phone As String = String.Empty
Dim _balance As Decimal = Nothing
Dim _lastPaymentDate As String = String.Empty
Dim _lastPayAmount As Decimal = Nothing
Dim _memo As String = String.Empty
Dim _lateFee As Decimal = Nothing
Dim _email As String = String.Empty
_unit = _reader.Item(0)
_Size = _reader.Item(1)
_contractDate = _reader.Item(2)
_deposit = _reader.Item(3)
_Tfirst = _reader.Item(4)
_Tlast = _reader.Item(5)
_optional = _reader.Item(6)
_address1 = _reader.Item(7)
_address2 = _reader.Item(8)
_city = _reader.Item(9)
_st = _reader.Item(10)
_zip = _reader.Item(11)
_hphone = _reader.Item(12)
_drLicense = _reader.Item(13)
_employer = _reader.Item(15)
_wphone = _reader.Item(16)
_bname = _reader.Item(17)
_baddress1 = _reader.Item(18)
_baddress2 = _reader.Item(19)
_bCity = _reader.Item(20)
_bState = _reader.Item(21)
_bZip = _reader.Item(22)
_bPhone = _reader.Item(23)
_contact_Name = _reader.Item(24)
_contact_Address1 = _reader.Item(25)
_contact_Address2 = _reader.Item(26)
_contact_City = _reader.Item(27)
_contact_State = _reader.Item(28)
_contact_zip = _reader.Item(29)
_contact_phone = _reader.Item(30)
_balance = _reader.Item(32)
_lastPaymentDate = _reader.Item(33)
_lastPayAmount = _reader.Item(34)
_memo = _reader.Item(46)
_lateFee = _reader.Item(49)
_email = _reader.Item(50)
_UpdateTenent(_unit, _Size, _contractDate, _deposit, _Tfirst, _Tlast, _optional, _address1, _address2, _city, _st, _zip, _hphone, _drLicense, _employer, _wphone, _bname, _baddress1, _baddress2, _bCity, _bState, _bZip, _bPhone, _contact_Name, _contact_Address1, _contact_Address2, _contact_City, _contact_State, _contact_zip, _contact_phone, _balance, _lastPaymentDate, _lastPayAmount, _memo, _lateFee, _email)
_progress += y
Dim d As Integer = Convert.ToInt16((Convert.ToString(y).Split(".")(0)))
ProgressBar2.Increment(d)
End While
End Using
End Using
_connection.Close()
End Using
Any ideas how my Connection string is wrong? Google results pointed me in the direction of DELETED=NO but its throwing that exception error now that I have added it..
The VfpOleDb provider excludes deleted records by default. So your connection string doesn't need to include the deleted setting. If you wanted to include delete records... you would include "deleted=false" in the connection string.

Sharepoont 2010 webpart vb.net Listbox SelectIndexChanged and errors

So let start I am new to coding widgets and in general. I had originally coded this in vb for asp pages and it work fine. Now converting over to a SharePoint 2010 webpart (not visual webpart).
The project is List box 1 has the user groups that they manage, List box 2 has the users in said group, List box 3 has all user not in List box 2
I am sure there lots of this that should be fix. Like not putting in admin login to get the data.
But the problem I have is: if select a group it will display the appropriate data but select a second group or select a user to add; same error.
Error:
"Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request."
Also still trying to figure out how to do the button to add a user.
Need some serious help please. I know part of the post back just having a hard time finding resources.
Below is the code:
Imports System
Imports System.ComponentModel
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.WebControls
Imports ActiveDs
Imports System.DirectoryServices
Imports System.Data
Imports ADODB
Imports System.Runtime.InteropServices
<ToolboxItemAttribute(False)> _
Public Class Groups
Inherits System.Web.UI.WebControls.WebParts.WebPart
Private LBgrp As ListBox
Private LBgrpmem As ListBox
Private LBaddgrp As ListBox
Private btnadd As Button
Protected Overrides Sub CreateChildControls()
Me.LBgrpmem = New ListBox
Me.LBgrpmem.AutoPostBack = True
Me.LBgrpmem.DataValueField = "sAMAccountName"
Me.LBgrpmem.DataTextField = "displayName"
Me.LBgrpmem.DataBind()
Me.LBgrpmem.Rows = 8
Me.LBgrpmem.Width = 170
Me.LBgrpmem.Height = 350
Me.LBgrpmem.Items.Insert(0, New ListItem("-- Current Members --"))
Me.Controls.Add(LBgrpmem)
Me.LBaddgrp = New ListBox
Me.LBaddgrp.AutoPostBack = True
Me.LBaddgrp.DataTextField = "displayName"
Me.LBaddgrp.DataValueField = "sAMAccountName"
Me.LBaddgrp.DataBind()
Me.LBaddgrp.Items.Insert(0, New ListItem("-- Add Users --"))
Me.LBaddgrp.Width = 170
Me.LBaddgrp.Height = 350
AddHandler LBaddgrp.SelectedIndexChanged, New EventHandler(AddressOf DLAdd_SelectedIndexChanged)
Me.Controls.Add(LBaddgrp)
Me.btnadd = New Button()
' AddHandler Me.btnadd.Click, New EventHandler(AddressOf Click_btnadd)
Me.btnadd.Text = "Add User"
Me.Controls.Add(btnadd)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Dim oCon As New ADODB.Connection
Dim oRecordSet As New ADODB.Recordset
Dim oCmd As New ADODB.Command
Dim sFullUser As String = Environment.UserName
Dim sProperties = "name,ADsPath,description,member,memberof,managedObjects"
Dim sGroup = "*"
Dim aMember
Dim iCount
oCon.ToString()
oCmd.ToString()
sFullUser.ToString()
sProperties.ToString()
sDomainADsPath.ToString()
oCon.Provider = "ADsDSOObject"
oCon.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd.ActiveConnection = oCon
oCmd.CommandText = "<" & sDomainADsPath & ">;(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & sFullUser & "));" & sProperties & ";subtree"
oRecordSet = oCmd.Execute
Dim de As DirectoryServices.DirectoryEntry = New DirectoryServices.DirectoryEntry(sDomainADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim i As Integer = 0
Dim sl As SortedList = New SortedList(New CaseInsensitiveComparer)
de.ToString()
While Not oRecordSet.EOF
aMember = oRecordSet.Fields("managedObjects").Value
If Not IsDBNull(aMember) Then
For iCount = 0 To UBound(aMember)
Dim groupDN As String = ("distinguishedName=" & aMember(iCount))
Dim src As DirectoryServices.DirectorySearcher = New DirectoryServices.DirectorySearcher("(&(objectCategory=Group)(" & groupDN & "))")
src.SearchRoot = de
src.SearchScope = DirectoryServices.SearchScope.Subtree
For Each res As DirectoryServices.SearchResult In src.FindAll
sl.Add(res.Properties("name")(0).ToString, i)
i += 1
Next
Next
End If
oRecordSet.MoveNext()
End While
Me.LBgrp = New ListBox
Me.LBgrp.AutoPostBack = True
Me.LBgrp.DataSource = sl
Me.LBgrp.DataTextField = "key"
Me.LBgrp.DataValueField = "value"
Me.LBgrp.DataBind()
Me.LBgrp.Items.Insert(0, New ListItem("-- Groups --"))
Me.Controls.Add(LBgrp)
Me.LBgrp.SelectedIndex = 0
AddHandler LBgrp.SelectedIndexChanged, New EventHandler(AddressOf LBgrp_SelectedIndexChanged)
LBgrp.SelectedItem.ToString()
End Sub
Protected Sub LBgrp_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles LBgrp.SelectedIndexChanged
Dim strQuery As String = "" & LBgrp.SelectedItem.Text.ToString() & "'"
'LBgrpmem.Items.Clear()
Dim oRootDSE2 = GetObject("LDAP://RootDSE")
Dim sDomainADsPath2 = "LDAP://" & oRootDSE2.Get("defaultNamingContext")
Dim oCon2 As New ADODB.Connection
Dim oRecordSet2 As New ADODB.Recordset
Dim sFullUser2 As String = Environment.UserName
Dim oCmd2 As New ADODB.Command
Dim sProperties2 = "name,ADsPath,description,member,memberof,managedObjects"
Dim grpADsPath2
Dim grpdsplynm2
oRootDSE2 = Nothing
oCon2.Provider = "ADsDSOObject"
oCon2.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd2.ActiveConnection = oCon2
oCmd2.CommandText = "<" & sDomainADsPath2 & ">;(&(objectCategory=group)(objectClass=group)(CN=" & LBgrp.SelectedItem.Text & "));" & sProperties2 & ";subtree"
oRecordSet2 = oCmd2.Execute
While oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
grpADsPath2.ToString()
grpdsplynm2 = grpADsPath2.remove(0, 7)
grpdsplynm2.ToString()
oRecordSet2.MoveNext()
End While
While Not oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
grpADsPath2.ToString()
grpdsplynm2 = grpADsPath2.remove(0, 7)
grpdsplynm2.ToString()
oRecordSet2.MoveNext()
End While
Dim groupDN2 As String = "" & grpdsplynm2 & ""
Dim filter As String = [String].Format("(&(objectClass=user)(objectCategory=person)(memberOf={0}))", groupDN2)
Me.LBgrpmem.AutoPostBack = True
Me.LBgrpmem.DataSource = FindUsers(filter, New String() {"sAMAccountName", "displayName"}, sDomainADsPath2, True)
Me.LBgrpmem.DataValueField = "sAMAccountName"
Me.LBgrpmem.DataTextField = "displayName"
Me.LBgrpmem.DataBind()
Me.LBgrpmem.Items.Insert(0, New ListItem("-- Current Members --"))
Me.Controls.Add(LBgrpmem)
Dim usrDN As String = "" & grpdsplynm2 & ""
usrDN.ToString()
Dim usrfilter As String = [String].Format("(&(objectClass=user)(objectCategory=person)(!memberOf={0}))", groupDN2)
Me.LBaddgrp.AutoPostBack = True
Me.LBaddgrp.DataSource = FindUsers(usrfilter, New String() {"sAMAccountName", "displayName"}, sDomainADsPath2, True)
Me.LBaddgrp.DataTextField = "displayName"
Me.LBaddgrp.DataValueField = "sAMAccountName"
Me.LBaddgrp.DataBind()
Me.LBaddgrp.Items.Insert(0, New ListItem("-- Add Users --"))
'AddHandler LBaddgrp.SelectedIndexChanged, New EventHandler(AddressOf DLAdd_SelectedIndexChanged)
Me.Controls.Add(LBaddgrp)
End Sub
Public Function FindUsers(ByVal sFilter As String, ByVal columns() As String, ByVal path As String, ByVal useCached As Boolean) As Data.DataSet
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
'try to retrieve from cache first
Dim context As HttpContext = HttpContext.Current
Dim userDS As Data.DataSet = CType(context.Cache(sFilter), Data.DataSet)
If userDS Is Nothing Or Not useCached Then
'setup the searching entries
Dim deParent As New DirectoryServices.DirectoryEntry(sDomainADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim ds As New DirectoryServices.DirectorySearcher(deParent, sFilter, columns, DirectoryServices.SearchScope.Subtree)
ds.PageSize = 1000
ds.Sort.PropertyName = "displayName" 'sort option
Using (deParent)
userDS = New Data.DataSet("userDS")
Dim dt As Data.DataTable = userDS.Tables.Add("users")
Dim dr As Data.DataRow
'add each parameter as a column
Dim prop As String
For Each prop In columns
dt.Columns.Add(prop, GetType(String))
Next prop
Dim src As DirectoryServices.SearchResultCollection = ds.FindAll
Try
Dim sr As DirectoryServices.SearchResult
For Each sr In src
dr = dt.NewRow()
For Each prop In columns
If sr.Properties.Contains(prop) Then
dr(prop) = sr.Properties(prop)(0)
End If
Next prop
dt.Rows.Add(dr)
Next sr
Finally
src.Dispose()
End Try
End Using
'cache it for later, with sliding window
context.Cache.Insert(sFilter, userDS, Nothing, DateTime.MaxValue, TimeSpan.FromSeconds(10))
End If
Return userDS
End Function 'FindUsers
Protected Sub DLAdd_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles Click_btnadd
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Dim oCon As New ADODB.Connection
Dim oRecordSet As New ADODB.Recordset
Dim oRcrdSet As New ADODB.Recordset
Dim oCmd As New ADODB.Command
Dim oCmd1 As New ADODB.Command
Dim sGroup = "*"
Dim sProperties = "name,ADsPath,description,member,memberof,proxyAddresses"
Dim grpADsPath
Dim grpdsplynm
Dim addusrADsPath
Dim addusrname
oRootDSE = Nothing
oCon.Provider = "ADsDSOObject"
oCon.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd.ActiveConnection = oCon
oCmd1.ActiveConnection = oCon
oCmd.CommandText = "<" & sDomainADsPath & ">;(&(objectClass=group)(cn=" & LBgrp.SelectedItem.Text & "));" & sProperties & ";subtree"
oRecordSet = oCmd.Execute
'Group Query
While Not oRecordSet.EOF
grpADsPath = oRecordSet.Fields("ADsPath").Value
grpdsplynm = oRecordSet.Fields("name").Value
oRecordSet.MoveNext()
End While
oCmd1.CommandText = "<" & sDomainADsPath & ">;(&(objectCategory=person)(objectClass=user)(cn=" & LBaddgrp.SelectedItem.Text & "));" & sProperties & ";subtree"
oRcrdSet = oCmd1.Execute
'User query
While Not oRcrdSet.EOF
addusrADsPath = oRcrdSet.Fields("ADsPath").Value
addusrname = oRcrdSet.Fields("name").Value
oRcrdSet.MoveNext()
End While
' Bind directly to the group
'
Dim oRootDSE2 = GetObject("LDAP://RootDSE")
Dim sDomainADsPath2 = "LDAP://" & oRootDSE2.Get("defaultNamingContext")
Dim oCon2 As New ADODB.Connection
Dim oRecordSet2 As New ADODB.Recordset
Dim sFullUser2 As String = Environment.UserName
'Dim sFullUser2 = Request.ServerVariables("LOGON_USER")
'Dim sUser2 = Split(sFullUser2, "\", -1)
Dim oCmd2 As New ADODB.Command
Dim sProperties2 = "name,ADsPath,description,member,memberof,managedObjects"
Dim grpADsPath2
oRootDSE2 = Nothing
oCon2.Provider = "ADsDSOObject"
oCon2.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd2.ActiveConnection = oCon2
oCmd2.CommandText = "<" & sDomainADsPath2 & ">;(&(objectCategory=group)(objectClass=group)(CN=" & LBgrp.SelectedItem.Text & "));" & sProperties2 & ";subtree"
oRecordSet2 = oCmd2.Execute
While Not oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
oRecordSet2.MoveNext()
End While
Dim group As New DirectoryServices.DirectoryEntry("" & grpADsPath2 & "", "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim user As New DirectoryServices.DirectoryEntry(addusrADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim isMember As Boolean = Convert.ToBoolean(group.Invoke("IsMember", New Object() {user.Path}))
If isMember Then
'
' TO CREATE ERROR MESSAGE
Else
' Add the user to the group by invoking the Add method
'
group.Invoke("Add", New Object() {user.Path})
End If
If Not IsNothing(user) Then
user.Dispose()
End If
If Not IsNothing(group) Then
group.Dispose()
End If
Console.ReadLine()
If (Err.Number <> 0) Then
' TO CREATE ERROR MESSAGE
Else
' TO CREATE SUCCESS MESSAGE
End If
End Sub
Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)
LBgrp.RenderControl(writer)
LBgrpmem.RenderControl(writer)
LBaddgrp.RenderControl(writer)
btnadd.RenderControl(writer)
End Sub
End Class
if memory serves me correctly, Page_Load event is firing on a postback too, where you are trying to create another instance of your drop down. So the system is trying to recreate the state of ListBox from ViewState but it is not the same ListBox, because you have just recreated it. So it barks.
To avoid it, in the page_load only create "parent" drop down if it's not postback. i.e.
Begin Page_Load()
If !Page.IsPostBack() Then
'load code here
End If
End Page_Load
Also there's no need to write
Me.LBgrpmem = New ListBox
as it is already created. Changing the datasource is usually enuff.