How to set AccountExpires in VB.NET via a AD DirectoryEntry - vb.net

I needed to set the accountExpires property in the AD DirectoryEntry couldn't find a simple answer.
Found some information;
http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.aspx
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/182bfb6a-8b23-4c96-9379-101a4d91241a
http://www.rlmueller.net/AccountExpires.htm
Saw some articles re ADS****.dll but didn't think I needed to use this method
Dim valueToSet As Date = Now.AddDays(10)
Dim ADSPath As String = "LDAP://cn=..."
Dim de As DirectoryEntry = New DirectoryEntry(ADSPath)
Dim d As TimeSpan = valueToSet.ToUniversalTime - Date.Parse("01/01/1601")
Dim ValueToSetAsString As String = d.Ticks.ToString
' it appears that the ticks value is too large for the value of the directory entry
' converting to a string (18 chars or so) works!
de.Properties("accountexpires").Value = ValueToSetAsString
Thanks to Brian it looks like the large amount of code wrote above can be simplified;
de.Properties("accountexpires").Value = valueToSet.ToFileTime.ToString
A function to return the AccountExpires and other largeInteger issues in VB.NET
Function ConvertADValueToDateTime(ByVal li As Object) As DateTime
' http://bytes.com/topic/visual-basic-net/answers/512901-lastlogontimestamp
Try
Dim lngHigh = li.HighPart
Dim lngLow = li.LowPart
Dim lastLogon = (lngHigh * 2 ^ 32) - lngLow
Dim returnDateTime As DateTime = DateTime.FromFileTime(lastLogon)
Return returnDateTime
Catch ex As Exception
Return Nothing
End Try
End Function
Example use :
Dim d As DateTime = ConvertADValueToDateTime(de.Properties("accountexpires").value)
If d = "01/01/1601" Then
' no expiry date
Return Nothing
Else
Return d
End If
An alternative method
Convert LDAP AccountExpires to DateTime in C#

Something like this will set your account to expire in 30 days:
Dim de As New DirectoryEntry("LDAP://cn=foo,cn=users,dc=contoso,dc=com")
de.Properties["accountExpires"].Value = DateTime.UtcNow.AddDays(30).ToFileTime()
de.CommitChanges()

This uses a DateTimePicker on a form but it should be trivial to use any other date format..
Imports System.DirectoryServices
Imports System.DirectoryServices.ActiveDirectory
Imports System.IO
'Get the user
Dim EntryString As String
EntryString = "LDAP://...."
Dim dirEntry As DirectoryEntry
dirEntry = New DirectoryEntry(EntryString)
Dim dirSearcher As New DirectorySearcher(dirEntry)
dirSearcher.Filter = "(&(objectCategory=Person)(objectClass=user)(SAMAccountName=" & Trim(Form1.AccountNameTB.Text) & "))"
dirSearcher.SearchScope = SearchScope.Subtree
Dim searchResults As SearchResult = dirSearcher.FindOne()
'Set the date
Dim d1 As Date = Form1.AccountExpiresDTP.Value
Dim d2 As New DateTime(d1.Year, d1.Month, d1.Day)
d2 = d2.AddDays(1) 'Add one day so that it matches what is in AD
Dim ft As Long = d2.ToFileTime()
dirEntryResults.Properties("accountExpires").Value = ft.ToString 'You do need to turn it into a string
dirEntryResults.CommitChanges()
dirEntryResults.Close()

Related

im trying to find the gap between 2 numbers

I'm having trouble finding the gap between 2 numbers for a parking charge. I tried this:
'time for entry
Dim entered As String = txtHourEnter.Text + ":" + txtMinEnter.Text
Dim time As DateTime
Dim display As String = "Invalid entry"
If DateTime.TryParse(entered, time) Then
display = time.ToString("h:mm tt")
End If
lblTimeIn.Text = display
'time for exited
Dim exited As String = txtHourExit.Text + ":" + txtMinExit.Text
Dim out As DateTime
Dim display2 As String = "invalid entry"
If DateTime.TryParse(exited, out) Then
display2 = out.ToString("h:mm tt")
End If
lblTimeOut.Text = display2
'parking time
Dim parkingtime As String = (display - display2)
lblParkingTime.Text = parkingtime
But I get this error:
The OP forgot to include the error message. How embarrassing for them :(
The code was trying to subtract the strings, instead of the timestamps. You need to get actual datetime values and subtract those.
Dim hourEnter As Integer = Int32.Parse(txtHourEnter.Text)
Dim minuteEnter As Integer = Int32.Parse(txtMinEnter.Text)
Dim hourExit As Integer = Int32.Parse(txtHourExit.Text)
Dim minuteExit As Integer = Int32.Parse(txtMinExit.Text)
Dim timeEnter As DateTime = DateTime.Today.AddHours(hourEnter).AddMinutes(minuteEnter)
Dim timeExit As DateTime = DateTime.Today.AddHours(hourExit).AddMinutes(minuteExit)
Dim parkingTime As TimeSpan = timeExit - timeEnter
lblTimeIn.Text = timeEnter.ToString("h:mm tt")
lblTimeOut.Text = timeExit.ToString("h:mm tt")
lblParkingTime.Text = parkingTime.ToString("h:mm")

How can I calculate the next birthday programmatically

I have a data table with a date-of-birth column.
I would want to split the date apart and change the year part with today.year which is current year.
Below is my code:
Dim birthda As New SqlDataAdapter(birthcmd)
Dim birthdt As New DataTable
birthda.Fill(birthdt)
For Each rw As DataRow In birthdt.Rows
Dim dob As String = rw.Item(3)
Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)
Dim bday As Date = (Date.Today.Year & mdat.Month & mdat.Day)
Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)
Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)
but I get this error:
Conversion from string "2019715" to type 'Date' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from string "2019715" to type 'Date' is not valid.
Source Error:
Line 149:
Line 150: Dim bday As Date = (Date.Today.Year & mdat.Month & mdat.Day)
VB.net is very peculiar when it comes to String to Date conversion.
I would recommend converting the Date from the individual components like this :
Dim bday as Date = New Date(Date.Today.Year, mdat.Month, mdat.Day)
Or as stated in the comments try using VB.Net DateTime
Dim bday as New DateTime(Date.Today.Year, mdat.Month, mdat.Day, 0, 0, 0)
thank you i think I have figured it out this is what i did. I calculated for the age with respect to current year and added the result to the year part of the date of birth.
here is the code
For Each rw As DataRow In birthdt.Rows
Dim dob As DateTime = rw.Item(2)
Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)
Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)
Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)
Dim ndob As Date = (DateAdd(DateInterval.Year, yers, mdat))
Dim yers2 As Integer = DateDiff(DateInterval.Year, ndob.Date, Today.Date)
Dim moths2 As Integer = DateDiff(DateInterval.Month, ndob.Date, Today.Date)
Dim dys2 As Integer = DateDiff(DateInterval.Day, ndob.Date, Today.Date)
I am basing this on what you wrote in a comment:
want to check those who have upcoming birthdays for a particular week.
It is fiddly to deal with leap years and dates which might be in the next year, but I think I've got all the cases covered here.
I made a table "Pets" in SQL Server with columns "Name" and "DOB", and put some data in.
I made a new Windows Forms project and added a multi-line textbox to Form1, and used this code:
Imports System.Data.SqlClient
Imports System.Text
Public Class Form1
Sub ShowUpcomingBirthdays()
Dim csb As New SqlConnectionStringBuilder With {.DataSource = ".\SQLEXPRESS", .InitialCatalog = "Testing", .IntegratedSecurity = True}
Dim birthdt As New DataTable()
Dim sql = "SELECT [Name], [DOB] FROM [Pets]"
Using conn As New SqlConnection(csb.ConnectionString)
Using sqlCmd As New SqlCommand(sql, conn)
Dim da As New SqlDataAdapter With {.SelectCommand = sqlCmd}
da.Fill(birthdt)
End Using
End Using
Dim matchEarliest = DateTime.Today
Dim matchLatest = matchEarliest.AddDays(8)
Dim sb As New StringBuilder ' somewhere to save the matching data
For Each r As DataRow In birthdt.Rows
Dim dob = Convert.ToDateTime(r.Item("DOB"))
' Allow for leap years by transferring the birthday to 1st March - some countries would use 28th February.
If DateTime.IsLeapYear(dob.Year) AndAlso Not DateTime.IsLeapYear(matchEarliest.Year) AndAlso dob.Month = 2 AndAlso dob.Day = 29 Then
dob = dob.AddDays(1)
End If
Dim nextBirthday = New DateTime(matchEarliest.Year, dob.Month, dob.Day)
If dob.Month <= matchEarliest.Month AndAlso dob.Day < matchEarliest.Day Then
' birthday has already happened this calendar year, make it next year
nextBirthday = nextBirthday.AddYears(1)
End If
If nextBirthday >= matchEarliest AndAlso nextBirthday < matchLatest Then
' the record is in the required range
sb.AppendLine(CStr(r.Item("Name")) & " " & dob.ToString("ddd dd MMMM"))
End If
Next
TextBox1.Text = sb.ToString()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ShowUpcomingBirthdays()
End Sub
End Class
It includes birthdays which happen "today" (you might not want to miss that), but you could
Dim matchEarliest = DateTime.Today.AddDays(1)
Dim matchLatest = matchEarliest.AddDays(7)
if you didn't want to include today.
I made a little class called Employee (it is at the bottom of the code). This answer is a bit similar to #AndrewMorton. I broke up the Sub into several functions that can be altered to suit without breaking the rest.
Private Sub DisplayUpcomingBirthdays()
Dim lstBirthdays As New List(Of Employee)
Dim dt = RetrieveBirthdays()
For Each rw As DataRow In dt.Rows
Dim CurrentYearBirthday As Date = GetCurrentYearBD(CDate(rw.Item("Birthdate")))
If IsBDThisWeek(CurrentYearBirthday) Then
lstBirthdays.Add(New Employee(CurrentYearBirthday, rw.Item("Name").ToString))
End If
Next
Dim SortedList = SortByBirthdays(lstBirthdays)
ListBox1.DataSource = SortedList
End Sub
Private Function RetrieveBirthdays() As DataTable
Dim query = "Select Name, Birthdate From Employes;"
Dim birthdt As New DataTable
Using cn As New SqlConnection("YourConnectionString")
Using cmd As New SqlCommand(query, cn)
cn.Open()
birthdt.Load(cmd.ExecuteReader)
End Using
End Using
Return birthdt
End Function
Private Function GetCurrentYearBD(BirthDate As Date) As Date
Dim Day As Integer = BirthDate.Day
Dim Month As Integer = BirthDate.Month
Dim Year As Integer = Now.Year
'Bithday is celebrated on the 28th when it is not a leap year
If Month = 2 AndAlso Day = 29 AndAlso Not DateTime.IsLeapYear(Year) Then
Day = 28
End If
Return New DateTime(Year, Month, Day)
End Function
Private Function IsBDThisWeek(BD As Date) As Boolean
Dim Tomorow = Now.AddDays(1)
Dim WeekFromNow = Now.AddDays(7)
If BD >= Tomorow AndAlso BD <= WeekFromNow Then
Return True
End If
Return False
End Function
Private Function SortByBirthdays(Employees As List(Of Employee)) As List(Of Employee)
Dim lst = (From emp In Employees
Order By emp.Birthdate
Select emp).ToList
Return lst
End Function
Public Class Employee
Public Property Birthdate As Date
Public Property Name As String
Public Sub New(BD As Date, eName As String)
Birthdate = BD
Name = eName
End Sub
Public Overrides Function ToString() As String
Return $"{Name}, {Birthdate.ToString("MMMM dd")}"
End Function
End Class

VB.Net - Adwords API Get Domain Keywords, CPC And Search Volume

Function 1:
Public Function DomainKeywords(ByVal url As String) As String
Dim output As String = ""
Dim user As AdWordsUser = New AdWordsUser
Using targetingIdeaService As TargetingIdeaService = CType(user.GetService(AdWordsService.v201710.TargetingIdeaService), TargetingIdeaService)
Dim selector As New TargetingIdeaSelector()
selector.requestType = RequestType.IDEAS
selector.ideaType = IdeaType.KEYWORD
selector.requestedAttributeTypes = New AttributeType() {AttributeType.KEYWORD_TEXT, AttributeType.SEARCH_VOLUME, AttributeType.AVERAGE_CPC, AttributeType.CATEGORY_PRODUCTS_AND_SERVICES}
Dim searchParameters As New List(Of SearchParameter)
Dim relatedToUrlSearchParameter As New RelatedToUrlSearchParameter
relatedToUrlSearchParameter.urls = New String() {url}
relatedToUrlSearchParameter.includeSubUrls = False
searchParameters.Add(relatedToUrlSearchParameter)
Dim languageParameter As New LanguageSearchParameter()
Dim hebrew As New Language()
hebrew.id = 1027
languageParameter.languages = New Language() {hebrew}
searchParameters.Add(languageParameter)
Dim locationParameter As New LocationSearchParameter()
Dim israel As New Location
israel.id = 2376
locationParameter.locations = New Location() {israel}
searchParameters.Add(locationParameter)
selector.searchParameters = searchParameters.ToArray()
selector.paging = New Paging
Dim page As New TargetingIdeaPage()
Dim offset As Integer = 0
Dim pageSize As Integer = 180
Try
Dim i As Integer = 0
Do
selector.paging.startIndex = offset
selector.paging.numberResults = pageSize
page = targetingIdeaService.get(selector)
Dim keywordCheck As List(Of String) = New List(Of String)
If Not page.entries Is Nothing AndAlso page.entries.Length > 0 Then
For Each targetingIdea As TargetingIdea In page.entries
For Each entry As Type_AttributeMapEntry In targetingIdea.data
Dim ideas As Dictionary(Of AttributeType, AdWords.v201710.Attribute) = MapEntryExtensions.ToDict(Of AttributeType, AdWords.v201710.Attribute)(targetingIdea.data)
Dim keyword As String = DirectCast(ideas(AttributeType.KEYWORD_TEXT), StringAttribute).value
Dim averageMonthlySearches As Long = DirectCast(ideas(AttributeType.SEARCH_VOLUME), LongAttribute).value
'''''''''''''''''''This Returns a Wrong Number
Dim cpc As Money = DirectCast(ideas(AttributeType.AVERAGE_CPC), MoneyAttribute).value
Dim microedit As String = Math.Round(cpc.microAmount / 1000000, 2).ToString + "$"
''''''''''''''''''
Dim isExist As Boolean = False
For Each keycheck In keywordCheck
If keyword = keycheck Then
isExist = True
End If
Next
If isExist = False Then
keywordCheck.Add(keyword)
If output = String.Empty Then
output = keyword + "###" + microedit + "###" + averageMonthlySearches.ToString
Else
output = output + Environment.NewLine + keyword + "###" + microedit + "###" + averageMonthlySearches.ToString
End If
End If
Next
i = i + 1
Next
End If
offset = offset + pageSize
Loop While (offset < page.totalNumEntries)
Catch e As Exception
If output = String.Empty Then
output = "ERROR"
If e.Message.Contains("Rate exceeded") Then
MsgBox("rate exceeded")
Else
MsgBox(e.Message.ToString)
End If
End If
End Try
End Using
Return output
End Function
This function gets a url as input and returns keywords that relevant to that url as output in the following format:
KeywordName1###CPC###SearchVolume
KeywordName2###CPC###SearchVolume
for some reason no matter what website I type in it returns 180 results,
Im aware that pageSize is set to 180,
In-fact if you lower pageSize to 179, you only get 179 results, the problem is that i cant get more then 180 results whatsoever..
Optional help: also why the CPC value returned in the first function is different from the CPC value returned from that function:
Function 2:
Public Function KeywordCPC(keyName As String, Optional Tries As Integer = 0) As String
Dim output As String = ""
Dim user As AdWordsUser = New AdWordsUser
Using trafficEstimatorService As TrafficEstimatorService = CType(user.GetService(AdWordsService.v201710.TrafficEstimatorService), TrafficEstimatorService)
Dim keyword3 As New Keyword
keyword3.text = keyName
keyword3.matchType = KeywordMatchType.EXACT
Dim keywords As Keyword() = New Keyword() {keyword3}
Dim keywordEstimateRequests As New List(Of KeywordEstimateRequest)
For Each keyword As Keyword In keywords
Dim keywordEstimateRequest As New KeywordEstimateRequest
keywordEstimateRequest.keyword = keyword
keywordEstimateRequests.Add(keywordEstimateRequest)
Next
Dim adGroupEstimateRequest As New AdGroupEstimateRequest
adGroupEstimateRequest.keywordEstimateRequests = keywordEstimateRequests.ToArray
adGroupEstimateRequest.maxCpc = New Money
adGroupEstimateRequest.maxCpc.microAmount = 1000000
Dim campaignEstimateRequest As New CampaignEstimateRequest
campaignEstimateRequest.adGroupEstimateRequests = New AdGroupEstimateRequest() {adGroupEstimateRequest}
Dim countryCriterion As New Location
countryCriterion.id = 2376
Dim languageCriterion As New Language
languageCriterion.id = 1027
campaignEstimateRequest.criteria = New Criterion() {countryCriterion, languageCriterion}
Try
Dim selector As New TrafficEstimatorSelector
selector.campaignEstimateRequests = New CampaignEstimateRequest() {campaignEstimateRequest}
selector.platformEstimateRequested = False
Dim result As TrafficEstimatorResult = trafficEstimatorService.get(selector)
If ((Not result Is Nothing) AndAlso (Not result.campaignEstimates Is Nothing) AndAlso (result.campaignEstimates.Length > 0)) Then
Dim campaignEstimate As CampaignEstimate = result.campaignEstimates(0)
If ((Not campaignEstimate.adGroupEstimates Is Nothing) AndAlso (campaignEstimate.adGroupEstimates.Length > 0)) Then
Dim adGroupEstimate As AdGroupEstimate = campaignEstimate.adGroupEstimates(0)
If (Not adGroupEstimate.keywordEstimates Is Nothing) Then
For i As Integer = 0 To adGroupEstimate.keywordEstimates.Length - 1
Dim keyword As Keyword = keywordEstimateRequests.Item(i).keyword
Dim keywordEstimate As KeywordEstimate = adGroupEstimate.keywordEstimates(i)
If keywordEstimateRequests.Item(i).isNegative Then
Continue For
End If
Dim meanAverageCpc As Long = 0L
Dim meanAveragePosition As Double = 0
Dim meanClicks As Single = 0
Dim meanTotalCost As Single = 0
If (Not (keywordEstimate.min Is Nothing) AndAlso Not (keywordEstimate.max Is Nothing)) Then
If (Not (keywordEstimate.min.averageCpc Is Nothing) AndAlso Not (keywordEstimate.max.averageCpc Is Nothing)) Then
meanAverageCpc = CLng((keywordEstimate.min.averageCpc.microAmount + keywordEstimate.max.averageCpc.microAmount) / 2)
End If
End If
output = Math.Round(meanAverageCpc / 1000000, 2).ToString + "$"
Next i
End If
End If
Else
output = "ZERO"
End If
Catch e As Exception
If output = String.Empty Then
output = "ERROR"
If e.Message.Contains("Rate exceeded") Then
output = KeywordCPC(keyName, Tries + 1)
End If
End If
End Try
End Using
Return output
End Function
how can I get EXCAT CPC in the first function?
because now only the second function return good CPC and the
first function return the wrong CPC(checked in israeli adwords frontend)
If you want to know how to use the functions (for beginners):
VB.Net - Trying To Increase the efficiency of adwords API requests

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()

automatically download a report

This is the code that i have made but now working to save the report to the directory:
As you see i follow pretty much a lot of microsoft tutorials of how use this class of reporting service, but still dont get how get it working
'objetos de reporting
Dim rs As New reportingservice.ReportingService2010
Dim rsExec As New ReportExecution.ReportExecutionService
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
'datos generales
Dim historyID As String = Nothing
Dim deviceInfo As String = Nothing
Dim format As String = "PDF"
Dim results As Byte()
Dim encoding As String = String.Empty
Dim mimeType As String = String.Empty
Dim extension As String = String.Empty
Dim warnings As ReportExecution.Warning() = Nothing
Dim streamIDs As String() = Nothing
Dim filename As String = "C:/Users/gdedieu/Desktop/reporte.pdf" ' Change to where you want to save
Dim _reportName As String = "per_anexo_1"
Dim _historyID As String = Nothing
Dim _forRendering As Boolean = False
Dim _values As ReportExecution.ParameterValue() = Nothing
Dim _credentials As reportingservice.DataSourceCredentials() = Nothing
Dim ei As ReportExecution.ExecutionInfo = rsExec.LoadReport(_reportName, historyID)
'definimos el parĂ¡metro
_values(0).Name = "an1_id"
_values(0).Value = 1
rsExec.SetExecutionParameters(_values, "en-us")
results = rsExec.Render(format, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
Dim stream As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
stream.Write(results, 0, results.Length)
stream.Close()
Try setting up a subscription via the Report Manager and specifying the Report Delivery Options value for 'Delivered By:' as 'Report Server File Share'.
This lets you specify a path for a report file to be written to - you will need to ensure that the Reporting Services server has write access to the destination.