Breaking Inheritence for all Items in sharepoint list - vb.net

I'm trying to build a for-loop in Visual Basic that will go over each item in a sharepoint database list and stop it from inheriting permissions from its parent. I'm getting a Null Exception because my query object is null. I've searched and all the code snippets i found didnt define a value for the query and wrote the code exactly like i did, why is this a problem.
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client
Module Module1
Sub Main()
Dim siteUrl As String = "https://cws1.conti.de/content/00009504"
Dim clientContext As New ClientContext(siteUrl)
Dim oList As List = clientContext.Web.Lists.GetByTitle("TestBI")
Dim query As CamlQuery
query.ViewXml = "<Where><Eq><FieldRef Name='Account' /><Value Type='Text'></Value></Eq></Where>"
Dim oListItems As ListItemCollection = oList.GetItems(query)
For numItems As Integer = 0 To 2
oListItems(numItems).BreakRoleInheritance(True, False)
Next
clientContext.ExecuteQuery()
End Sub
End Module
I've never programmed VB before and i'm not familiar with automating anything on Sharepoint so I would really appreciate any help.

you need to assign an instance of an object to the query variable before you can use it. Right now, you only declare a variable.
Change the line:
Dim query AS CamlQuery
to
Dim query AS new CamlQuery
Also, CamlQuery expects a full <View> tag. So change your CAML to <View><Query><Where><Eq><FieldRef Name='Account' /><Value Type='Text'></Value></Eq></Where></Query></View> and you should be good to go.
If you wish to retrieve all items from the list, use the CamlQuery.CreateAllItemsQuery() method.
Dim query AS CamlQuery = CamlQuery.CreateAllItemsQuery()

Related

VB store list of records in a text file and read back

I have a VB program in VS2017. It reads many excel files and store relevant data in
Dim total_sessions As New List(Of Session_CSV_file)
The list is big (~10k), and includes about 20 fields each.
Is there a way in VB to store it in a file in one command and read it later on easily., without reading and writing each field?
Often I need to debug the later part. I prefer doing it without rerunning the whole first part.
Or is there a way in Visual Studio, to stop the run at a certain point, and store this point in a dump file, like simulators often do? (so they can run the simulation from this point later on)
Perhaps if you load your csv data into a DataTable instead:
Dim dt as New DataTable
dt.Columns.Add("Name")
dt.Columns.Add("Age", GetType(Int32))
For Each filepath in tenKFilePaths
For Each line in File.ReadAllLines(file)
Dim bits = line.Split(","c)
dt.Rows.Add(bits(0), Convert.ToInt32(bit(1))
Next line
Next filepath
Then you can save the whole lot to xml:
dt.WriteXml("c:\temp\my.xml")
Have a coffee, reboot etc the read them again and carry on where you left off:
Dim dt2 as New DataTable
dt2.ReadXml("c:\temp\my.xml")
Raw datatables are a bit difficult to work with because you end up accessing their rows and column data by string indexing and having to cast it a lot - fairly lame. There is a better way to use them, as visual studio can create custom classes that inherit from the base datatables and offer lots of functionality that does away with all the awkwardness of dealing with datatables as a very generic thing. Just like the forms designer creates a UI form that inherits from Form, the dataset designer creates custom datatables that inherit from the base
If you add a new DataSet type object to your project, double click it it opens something like a database designer. Right click that surface and choose Add DataTable, Add your Columns with their respective datatypes etc - this is the equivalent of your Session_Csv_File class, with its properties and fields. Double click on it and you can add code etc - if your session_csv_file has custom methods you can transfer their code to the custom data row
Imagine I created a new datatable in a DataSet and called it SessionCsvFiles. Imagine I added a Name and Age column, and I added a custom method called BlahBlah
I'd then be able to say in code things like:
Dim dt as New MyCustomDataSet.SessionCsvFilesDataTable
'it's like making a new SessionCsvFile
Dim r = dt.NewSessionCsvFilesRow()
'It's like setting your properties
r.Name = csvBits(0)
r.Age = Convert.ToInt32(csvBits(1))
'It's like adding your file to the List
dt.Add(r)
You now have virtually the same thing as you had before - a collection of objects that represents things about your csv files. The difference is with this route it has an already-built-in way of saving all the properties and the collection to xml and reading it back again
Add the Serializable attribute to the Class. I added a parameterized constructor for ease in building my list but you must provide a constructor without parameters for this to work. Thus, the empty Sub New.
<Serializable()>
Public Class Session_CSV_file
Public Property ID As Integer
Public Property Name As String
Public Property Type As String
Public Sub New()
End Sub
Public Sub New(SessID As Integer, SessName As String, SessType As String)
ID = SessID
Name = SessName
Type = SessType
End Sub
End Class
The add Imports System.Xml.Serialization to the top of the file.
Private Sub SaveList()
Dim serializer = New XmlSerializer(GetType(List(Of Session_CSV_file)))
Using writer As New StreamWriter("C:\Users\xxx\Documents\XMLtest.xml")
serializer.Serialize(writer, lst)
End Using
End Sub
I filled my list as follows but you can fill you list any way you choose.
Private lst As New List(Of Session_CSV_file)
Private Sub FillList()
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Top 10 * From Coffees;", cn)
cn.Open()
Dim reader = cmd.ExecuteReader
While reader.Read
Dim sess As New Session_CSV_file(reader.GetInt32(0), reader.GetString(1), reader.GetString(3))
lst.Add(sess)
End While
End Using
End Sub
To recreate the list... (OOps! forgot this)
Private RehydratedList As New List(Of Session_CSV_file)
Private Sub CreateListFromXML()
Dim serial As New XmlSerializer(GetType(List(Of Session_CSV_file)))
Using fs As New FileStream("C:\Users\maryo\Documents\XMLtest.xml", FileMode.Open)
RehydratedList = DirectCast(serial.Deserialize(fs), List(Of Session_CSV_file))
End Using
For Each item In RehydratedList
Debug.Print(item.ToString)
Next
End Sub

Running VB.Net code in my program, without creating instances, or parameters. Is it possible?

I am currently trying to make a program where you can type a VB.NET script into a richtextbox (strCode) and then execute it. Like as if I executed it in Visual Studio.
My current code look like this:
Dim objCompilerParameters As New CompilerParameters
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.GenerateInMemory = True
Dim objCompileResults As CompilerResults
Dim Provider As CodeDomProvider = CodeDomProvider.CreateProvider("VisualBasic")
objCompileResults = Provider.CompileAssemblyFromSource(objCompilerParameters, strCode)
' Get a reference to the assembly.
'
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
' Create an instance of the DynamicCode class referenced in the source code.
'
Dim objTheClass As Object = objAssembly.CreateInstance("Dynam.DynamicCode")
'----------------------------------------------------------------------------------------------------
' Create a parameter to be passed into the ExecuteCode function in class DynamicCode.
Dim objFunctionParameters(0) As Object
objFunctionParameters(0) = "Parameter 1"
'----------------------------------------------------------------------------------------------------
'Creating Result
Dim objResult As Object = objTheClass.GetType.InvokeMember("ExecuteCode", _
BindingFlags.InvokeMethod, Nothing, objTheClass, objFunctionParameters)
'---------------------
This runs fine .. as long as the namespace in my script is "Dynam", and the public class is "TestClass". Also the Public Function has to be named "ExecuteCode". Just like in the script.
Is there a way to create this, without having to hardcode the function and class names? So I can just call the classes, and functions whatever the user wants to call them.
Thanks in advance. I hope it made a little sense. If not, please let me know.

LDAP Vb.net simple query

I'm trying to create a vb.net code for a simple query through LDAP but having an issue and can't find where it is.
Dim ldapServerName As String = "xxx.test.intranet.xxx.ca"
Dim oRoot As DirectoryEntry = New DirectoryEntry("LDAP://" & ldapServerName & "/c=ca, DC=xxx,DC=corp,DC=xxx,DC=ca")
oRoot.Username = "ou=Tool,ou=applications,o=xxx,c=ca"
oRoot.Password = "something#2015"
Dim LDAPSearcher As New DirectorySearcher()
LDAPSearcher.Filter = "(&(employeenumber=6012589))"
Dim SearchResult As SearchResult = LDAPSearcher.FindOne()
Dim UserEntry As DirectoryEntry = SearchResult.GetDirectoryEntry()
EDTEST.Text = UserEntry.Properties("employeenumber").Value.ToString
it is giving me an error saying that the object is not valid. The searcher variable is in fact empty so it has to do with my query somehow.
This is my first time with LDAP¨and I have tried some of the solution i could find on the net but nothing is working so far.
Error: Object not set to an instance of an object.
Unless you're adding another attribute to search by, you don't need the AND operator in your filter syntax - a search for simply (employeenumber=6012589) should work just fine.
If do you have another attribute you'd like to search by, the filter syntax would be similiar to what you have now, only with the additional attribute :
(&(employeenumber=6012589)(objectClass=user))
EDIT:
I put together an example using the lower level System.DirectoryServices and System.DirectoryServices.Protocols namespaces. This helps break up the actual login and search functions, and will also provide better context when errors occur. For the example, I've replaced all of my variables with the ones you're using in your question. I tested this against our own Active Directory instance over unsecured port 389 using my creds and a base domain similar to the one you're using.
Imports System.DirectoryServices.Protocols
Imports System.Net
Module Module1
Sub Main()
' setup your creds, domain, and ldap prop array
Dim username As String = "ou=Tool,ou=applications,o=xxx,c=ca"
Dim pwd As String = "something#2015"
Dim domain As String = "DC=xxx,DC=corp,DC=xxx,DC=ca"
Dim propArray() As String = {"employeenumber"}
' setup your ldap connection, and domain component
Dim ldapCon As LdapConnection = New LdapConnection("xxx.test.intranet.xxx.ca:389")
Dim networkCreds As NetworkCredential = New NetworkCredential(username, pwd, domain)
' configure the connection and bind
ldapCon.AuthType = AuthType.Negotiate
ldapCon.Bind(networkCreds)
' if the above succceeded, you should now be able to issue search requests directly against the directory
Dim searchRequest = New SearchRequest(domain, "(employeenumber=6012589)", SearchScope.Subtree, propArray)
' issue the search request, and check the results
Dim searchResult As SearchResponse = ldapCon.SendRequest(searchRequest)
Dim searchResultEntry As SearchResultEntry
If (searchResult.Entries.Count > 0) Then ' we know we've located at least one match from the search
' if you're only expecting to get one entry back, get the first item off the entries list
searchResultEntry = searchResult.Entries.Item(0)
' continue to do whatever processing you wish against the returned SearchResultEntry
End If
End Sub
End Module

Opening pdf from Crystal Reports Viewer

Thank you for viewing my question. I am building a project in Visual Studio 2010 using vb and .net. I have a Crystal Reports report that I'm trying to have auto export and open in PDF with a button click. Right now I am using Crystal Reports Viewer in my project which opens the report fine; However, I would like to have it only open in a pdf format. Is there a way to do this?
Note: I'm not here hunting for code. I'm wanting to learn, so if you could just guide me in the right direction, that will be great (if you don't want to provide code)!
Thank you for the help.
Josh
I'm using code from http://www.codeproject.com/Articles/14549/Crystal-Reports-To-PDF-converter-Without-Crystal-R
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class clsCrystalToPDFConverter
Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo
Dim oRDoc As New ReportDocument
Dim expo As New ExportOptions
Dim sRecSelFormula As String
Dim oDfDopt As New DiskFileDestinationOptions
Dim strCrystalReportFilePath As String
Dim strPdfFileDestinationPath As String
Public Function SetCrystalReportFilePath(ByVal CrystalReportFileNameFullPath As String)
strCrystalReportFilePath = CrystalReportFileNameFullPath
End Function
Public Function SetPdfDestinationFilePath(ByVal pdfFileNameFullPath As String)
strPdfFileDestinationPath = pdfFileNameFullPath
End Function
Public Function SetRecordSelectionFormula(ByVal recSelFormula As String)
sRecSelFormula = recSelFormula
End Function
Public Function Transfer()
oRDoc.Load(strCrystalReportFilePath) 'loads the crystalreports in to the memory
oRDoc.RecordSelectionFormula = sRecSelFormula 'used if u want pass the query to u r crystal form
oDfDopt.DiskFileName = strPdfFileDestinationPath 'path of file where u want to locate ur PDF
expo = oRDoc.ExportOptions
expo.ExportDestinationType = ExportDestinationType.DiskFile
expo.ExportFormatType = ExportFormatType.PortableDocFormat
expo.DestinationOptions = oDfDopt
oRDoc.SetDatabaseLogon("PaySquare", "paysquare") 'login for your DataBase
oRDoc.Export()
End Function
End Class
You'll need to set the variables to the specifics of your project obviously. These are more than likely the classes and methods you'll be wanting to use however. This should allow you to take your crystal reports viewer file and turn it into something opened by PDF
This works for me.
Dim orpt As CrystalDecisions.CrystalReports.Engine.ReportDocument
orpt = DirectCast(crvInvoice.ReportSource, CrystalDecisions.CrystalReports.Engine.ReportDocument)
orpt.ExportToDisk(ExportFormatType.PortableDocFormat, "PdfFileName.pdf")

How to get all forms in a VB.net (VS08) project in an array?

Alright, so I need a method that traverses all the forms inside a VB.net project under Visual Studio 2008, and create an array of type form with references to all the forms inside it, so that the array looks like this (pseudocode)
FormsArray() = [Form1, Form2, Form3, Form4]
However, I don't have a clue as to how to begin.
You have to adjust the function to put the result of msgbox in a array
Public Sub getallforms(ByVal sender As Object)
Dim Forms As New List(Of Form)()
Dim formType As Type = Type.GetType("System.Windows.Forms.Form")
For Each t As Type In sender.GetType().Assembly.GetTypes()
If UCase(t.BaseType.ToString) = "SYSTEM.WINDOWS.FORMS.FORM" Then
MsgBox(t.Name)
End If
Next
End Sub
You must call the function from any form in the application like this (getallforms(me))
Here is how you would do this using Reflection, assuming that the class where you placed this code was in the same assembly that you wanted to iterate over. If not, then you'll need to change the Me.GetType().Assembly in the For Each loop into something else to account for loading the assembly in a different manner.
Dim Forms As New List(Of Form)()
Dim formType As Type = Type.GetType("System.Windows.Forms.Form")
For Each t As Type In Me.GetType().Assembly.GetTypes()
If t.IsSubclassOf(formType) = True Then
Forms.Add(CType(Activator.CreateInstance(t), Form))
End If
Next
Hey this is what I did to get the list of forms in my vb project, how ever this in not in code but you could write system.io code fragment to do just that.
open cmd prompt
go to project folder
run a dir /s/b *.designer.vb >> list.txt
use notepad or sublimetext and edit it to get the list ordered as you like it.
:) hope this helped!
I could not get this version to work:
Dim Forms As New List(Of Form)()
Dim formType As Type = Type.GetType("System.Windows.Forms.Form")
For Each t As Type In Me.GetType().Assembly.GetTypes()
If t.IsSubclassOf(formType) = True Then
Forms.Add(CType(Activator.CreateInstance(t), Form))
End If
Next
In VB2010 formType is always Nothing
So I dumped the formType line and simply modified your 'IF' statement to check the BaseType instead. Here is the New Version
Dim Forms As New List(Of Form)()
For Each t As Type In Me.GetType().Assembly.GetTypes()
If t.BaseType.Name = "Form" Then
Forms.Add(CType(Activator.CreateInstance(t), Form))
End If
Next
You need to either write a VS macro or an Addin.
In it, from a DTE or DTE2 instance, you can write:
Public Sub GetForms(ByVal host As DTE2)
Dim project As Project = host.ActiveDocument.ProjectItem.ContainingProject
For Each ce As CodeElement In project.CodeModel.CodeElements
If ce.Kind = vsCMElement.vsCMElementClass Then
Dim cl As CodeClass = CType(ce, CodeClass)
If cl.IsDerivedFrom("System.Windows.Forms) Then
'do something
End If
End If
Next
End Sub
2 options
I would load the actual project file into a XML reader. Then iterate all the nodes looking for all Form SubTypes and store the linked files in an array. If the name of file matches the name of the form class, you can create your FormsArray from that list. Otherwise you have to load each file and look for the public class definition of the file to get the list.
Using Reflection, examine the project using Assembly.GetTypes. Find all the System.Windows.Forms.Form Types and store them in a list. Then write out the Type.Name.