Response.Write in a Shared function - vb.net

Is it possible to open a new window from a shared function? There is a compile time error on the line that starts: Response.Write:
<System.Web.Services.WebMethod()> _
Public Shared Function UpdateTimeBasedDisposal(ByVal usn As String, ByVal strCon As String, ByVal decision As String, ByVal review As String) As String
Dim boolDecision As Boolean = CType(decision, Boolean)
Dim objNominal As New clsPrimaryNominal(strCon)
Dim strUpdateTimeBasedDisposal As String = ""
Dim objReview As New clsReviews(ConfigurationManager.ConnectionStrings("GeniedbConnection").ConnectionString), tyReview As New typeReview, intTotal As Integer, intDisposalTotal As Integer, intType As Integer
If boolDecision Then
If objNominal.MakeTimeBased(CInt(usn)) < 1 Then
strUpdateTimeBasedDisposal = "THERE WAS A PROBLEM MAKING THE NOMINAL RECORD FOR " & usn & " TIME BASED DISPOSAL." & vbCrLf
Else
strUpdateTimeBasedDisposal = "The Primary Nominal was successfully put into time based disposal"
End If
Else
If objNominal.MakeNotTimeBased(CInt(usn)) < 1 Then
strUpdateTimeBasedDisposal = "THERE WAS A PROBLEM MAKING THE NOMINAL RECORD FOR " & usn & " NOT TIME BASED DISPOSAL." & vbCrLf
Else
strUpdateTimeBasedDisposal = "The Primary Nominal was successfully taken out of time based disposal"
' next thing to do is create all the disposal records
'CreateDisposals()
intType = objReview.ReviewType(CLng(review), intTotal, intDisposalTotal)
Response.Write("<script>window.open('frmNRAC.aspx?USN=" & CStr(Session("PNUSN")) & "&Review=" & CStr(Session("Review")) & "&Total=" & intTotal & "&Disposals=" & intDisposalTotal & "','_blank')</script>")
End If
End If
Return strUpdateTimeBasedDisposal
End Function

This is server-side code. Server-side code can never directly open a new window. All it can do is create an http response that causes some javascript to open a new window. WebMethods also can't call the javascript on their own directly. You need code at the call site for the webmethod to invoke your javascript based on the result of the method.
Additionally: beware Shared methods in ASP.Net in the first place. They share data at the application domain level, and in ASP.Net, all the users of your site are in the same application domain.

Related

Application freeze when I use an external library

My application contains a main file allowing to generate an executable using Codedom. This executable is make from my file Source.vb.
I would like to use an external library in the latter. In particular, this is Rebex: this will allow me to download a file from a server sFTP.
Here are my Codedom settings:
Public Shared Function compile_Stub(ByVal input As String, ByVal output As String, ByVal resources As String, ByVal showError As Boolean, Optional ByVal icon_Path As String = Nothing) As Boolean
Dim provider_Args As New Dictionary(Of String, String)()
provider_Args.Add("CompilerVersion", "v3.5")
Dim provider As New Microsoft.VisualBasic.VBCodeProvider(provider_Args)
Dim c_Param As New Compiler.CompilerParameters
Dim c_Args As String = " /target:winexe /platform:x86 /optimize "
If Not icon_Path = Nothing Then
c_Args = c_Args & "/win32icon:" & icon_Path
End If
c_Param.GenerateExecutable = True
c_Param.OutputAssembly = output
c_Param.EmbeddedResources.Add(resources)
c_Param.CompilerOptions = c_Args
c_Param.IncludeDebugInformation = False
c_Param.ReferencedAssemblies.AddRange({"C:\Users\marsh\Desktop\project\Galaxy\packages\Rebex.Common.5.0.7119\lib\net35\Rebex.Common.dll", "C:\Users\marsh\Desktop\project\Galaxy\packages\Rebex.Networking.5.0.7119\lib\net35\Rebex.Networking.dll", "C:\Users\marsh\Desktop\project\Galaxy\packages\Rebex.Sftp.5.0.7119\lib\net35\Rebex.Sftp.dll", "mscorlib.dll", "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Management.dll", "System.Dll", "System.Drawing.Dll", "System.Windows.Forms.Dll", "System.Data.Dll", "System.Xml.Dll"})
c_Param.GenerateInMemory = True
Dim c_Result As Compiler.CompilerResults = provider.CompileAssemblyFromSource(c_Param, input)
If c_Result.Errors.Count = 0 Then
Return True
Else
If showError Then
For Each _Error As Compiler.CompilerError In c_Result.Errors
MessageBox.Show("ERREUR de compilation" & vbNewLine &
"FileName: " & _Error.FileName & vbNewLine &
"Ligne: " & _Error.Line & vbNewLine & "ErrorText: " &
_Error.ErrorText & vbNewLine &
"Column: " &
_Error.Column & vbNewLine &
"Type d'erreur (True = avertissement, False = Erreur ): " &
_Error.IsWarning & vbNewLine & "ErrorNumber: " &
_Error.ErrorNumber)
Next
Return False
End If
Return False
End If
End Function
Despite having correctly implemented the libraries in question in my Codedom settings, nothing happens when I try to use them: no error, my application stops at the execution. The Rebex libraries are provided by the NuGet installation: Rebex.Common.dll, Rebex.Networking.dll, Rebex.Sftp.dll. The parameters that I have written in my code to import these libraries are however in agreement with this documentation.
My executable freeze when I implement this part of the code in my Stub Source.vb:
Dim sftp As New Rebex.Net.Sftp()
sftp.Connect(hostname)
' log in
sftp.Login(username, password)
I really do not understand where this problem comes from. The fact that no error appears blocks me more: I do not know which way to go to solve the error. Could you help me?

Dynamically creating multiple background workers and passing them arguments

I've written an app that basically does constant pings to a list of hosts and logs the results.
I have a function...
Public Function doping(ByRef host As String)
Dim Result As Net.NetworkInformation.PingReply
Dim SendPing As New Net.NetworkInformation.Ping
Dim ResponseTime As Long
Dim timestamp As String = System.DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss")
Try
Result = SendPing.Send(host, 300)
ResponseTime = Result.RoundtripTime
If Result.Status = Net.NetworkInformation.IPStatus.Success Then
DynaLogging(timestamp & " - Reply from " & host & ": bytes=32 time=" & ResponseTime.ToString & " TTL=??", host & ".log")
TextBox2.Text = timestamp & " - Reply from " & host & " : time =" & ResponseTime.ToString & br & TextBox2.Text
Else
DynaLogging(timestamp & " - No reply received from " & host, host & ".log")
TextBox2.Text = timestamp & " - No reply received from " & host & br & TextBox2.Text
End If
Catch ex As Exception
End Try
End Function
And I've got a timer, which currently fires off the following in a background worker...
On Error Resume Next
For Each hostyhost As String In ListBox1.Items
doping(hostyhost)
Next
This works a treat until one of the hosts in the list is not responding, then the backgroundworker waits because it can only process one ping at a time and so if one host is delayed, the remaining hosts have to wait before they are checked and the whole process slows down.
I could do with somehow dynamically creating multiple background workers at runtime but I do not know how to create a background worker dynamically which can be passed an argument.
I looked at this post about creating bgw's at runtime, but have no idea how to deploy this for what I need.
Can anyone point me in the right direction?
Why not a Parallel ForEach?
Dim Items As List(Of String) = New List(Of String)
For Each item As String In ListBox1.Items
Items.Add(item.ToString())
Next
Parallel.ForEach(Items, Sub(hostyhost)
doping(hostyhost)
End Sub)
It's included in the .NET Framework 4.0 under the System.Threading namespace and will take care of almost everything, without writing a million lines of code.

VB.net get bitlocker Password ID from Active Directory

I have a VB.net program that I am trying to add a bitlocker lookup tool that will search active directory for the machine name, and display the "Password ID" as well as the "Recovery Password"
So far my script/code works flawlessly for the lookup and displaying the Recovery Password, but I cannot get it to display the Password ID.
I've tried:
Item.Properties("msFVE-RecoveryGuid")(0)
Which returns the error "System.InvalidCastException: Conversion from type 'Byte()' to type 'String' is not valid."
Item.Properties("msFVE-RecoveryGuid")(0).ToString
Which returns "System.Byte[]"
Item.Properties("msFVE-RecoveryGuid").ToString
Which returns "System.DirectoryServices.ResultPropertyValueCollection"
So far in my searching I've only seen C# examples, and I haven't been able to translate.
The same for Recovery Password works however:
(Item.Properties("msFVE-RecoveryPassword")(0))
Here is the larger snippet of what I have for context:
Dim RootDSE As New DirectoryEntry("LDAP://RootDSE")
Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
Dim ADsearch As New DirectorySearcher("LDAP://" & DomainDN)
ADsearch.Filter = ("(&(objectClass=computer)(name=" & MachineName & "))")
Dim ADresult As SearchResult = ADsearch.FindOne
Dim ADpath As String = ADresult.Path
Dim BTsearch As New DirectorySearcher()
BTsearch.SearchRoot = New DirectoryEntry(ADpath)
BTsearch.Filter = "(&(objectClass=msFVE-RecoveryInformation))"
Dim BitLockers As SearchResultCollection = BTsearch.FindAll()
Dim Item As SearchResult
Dim longTempstring As String = ""
For Each Item In BitLockers
If Item.Properties.Contains("msFVE-RecoveryGuid") Then
Dim tempstring As String = Item.Properties("msFVE-RecoveryGuid")(0).ToString
longTempstring = longTempstring & tempstring & vbNewLine
'ListBox2.Items.Add(Item.Properties("msFVE-RecoveryGuid")(0))
End If
If Item.Properties.Contains("msFVE-RecoveryPassword") Then
ListBox1.Items.Add(Item.Properties("msFVE-RecoveryPassword")(0))
End If
Next
MsgBox(longTempstring)
So I figured out that I needed to convert the bytes to hex in order to get them to match what is viewed in the Microsoft Management Console. Once I began doing that the only problem I ran into is that I discovered the indexing of the byte arrays are not in the same order as they are in Active Directory. -- so instead of looping I had to list out each index of the Byte array and sort them to their proper positions so that they match how they show up in AD.
My end function is:
Function bitread(ByVal GUID As Byte())
Dim tempVar As String
tempVar = GUID(3).ToString("X02") & GUID(2).ToString("X02") _
& GUID(1).ToString("X02") & GUID(0).ToString("X02") & "-" _
& GUID(5).ToString("X02") & GUID(4).ToString("X02") & "-" _
& GUID(7).ToString("X02") & GUID(6).ToString("X02") & "-" _
& GUID(8).ToString("X02") & GUID(9).ToString("X02") & "-" _
& GUID(10).ToString("X02") & GUID(11).ToString("X02") _
& GUID(12).ToString("X02") & GUID(13).ToString("X02") _
& GUID(14).ToString("X02") & GUID(15).ToString("X02")
Return tempVar
End Function
Called with:
bitread(Item.Properties("msFVE-RecoveryGUID")(0))

Web Service doesn't write logs when called from Tablet

There's a web service set up that our application is calling.
When calling this function through a browser (Tested using Mozilla Firefox), this function writes to the log file correctly (with the values that we provide to it). However, when calling this function through a tablet (tested on the same network and on a different network), nothing is written to the logs.
It's simple, looks like this:
<WebMethod()> _
Public Function CreateClient( _
ByVal strUserID As String, _
ByVal strVehicleID As String, _
ByVal strUnit As String, _
ByVal strHouse As String, _
ByVal strStreet As String, _
ByVal strCity As String, _
ByVal strContactName As String, _
ByVal strPhone As String, _
ByVal strComments As String)
Dim strReturn As String = "14"
Dim strLog As String = ""
strLog = "CreateClient strUserID = " & strUserID & ", strVehicleID = " & strVehicleID & ", strUnit = " & strUnit & ", strHouse = " & strHouse & ", strStreet = " & strStreet & ", strCity = " & strCity
strLog &= ", strContactName=" & strContactName & ", strPhone=" & strPhone & ", strComments=" & strComments
Class1.WriteLogEntry(strLog, Class1.LOG_TYPE_DEBUG)
Return strReturn
End Function
We know we're reaching and calling the correct web service & function because when we change the return value, the tablet shows the correct value after each deployment. Eg: when the return value is set to "1", the tablet gets back a "1", and after changing it to a "14", the tablet also gets back a "14".
Does anyone know why the logs are not being written, and/or how to fix this?
Note: If you need to see the android code for how we're calling it, I'll post it, but again, I don't think it's necessary since we already know that we're calling it properly and getting the correct return value.
Not sure what the problem was, but after changing 2 things, the logs started working again:
Moved all the code from Class1 to a Module (Module)
Changed the target file it was saving to.
Could it be possible that there was something else locking onto the file, thus preventing this log from being written? Or perhaps Classes and Modules don't have the same file writing permissions?

Is it safe to call SmtpClient.Dispose() in .NET?

I have a scenario where I need to send 100 emails in one shot (using a loop), but also I am not allowed to send 1 email per SMTP session.
Right now all 100 emails are sharing same SMTP session.
I was thinking that calling SmtpClient.Dispose() will take care of what I need. Please correct me if I am wrong.
So, basically 3 questions:
Will SmtpClient.Dispose() take care of what I need?
If Yes, is it safe to Dispose() SmtpClient without affecting other services on the
server?
If No, What would be the right approach to achieve what I
want?
Sample Code:
Private Shared Sub SendMail(ByVal MailServer As SmtpClient, ByVal body As String, ByVal Subject As String, ByVal FromEmail As String, _
ByVal ToEmailList As String, Optional ByVal AttFile As Attachment = Nothing)
Dim message As New MailMessage
Try
message.From = New MailAddress(FromEmail)
message.Subject = Subject
message.IsBodyHtml = False
message.Body = body
message.Priority = MailPriority.High
If Not AttFile Is Nothing Then
message.Attachments.Add(AttFile)
Else
message.Attachments.Add(AttFile)
End If
MailServer.Send(message)
Catch ex As Exception
Throw New ApplicationException("SERVICE1.SendMail ERROR -- Error sending email [ERROR]:[" & ex.Message.ToString & "] " & vbCrLf & "To:" & ToEmailList & vbCrLf & "From:" & FromEmail & vbCrLf & "Subject: " & Subject & vbCrLf & "Body: " & body)
End Try
message.Dispose()
End Sub
And this is how the method is being executed:
For Each Item In ItemListCollection
m_MailServer = New SmtpClient(MailServerName)
MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
SendMail(WeeklyMailServer, msgBody, msgSubject, MsgFromEmail, "xyz#abc.com", rptAttachment)
Next
You could wrap it in a using statement and ensure that it is disposed when execution leaves the block. And you can call Send multiple times in a loop using the same SmtpClient.
Using client = New SmtpClient()
For i As Integer = 0 To 99
Dim message = New MailMessage()
'initialization of whatever is needed
' message creation
client.Send(message)
Next
End Using
Inside execution loop, you can enclose the code in a Using block. This will use a separate smtpclient for each email and will dispose / close it properly.
For Each Item In ItemListCollection
using m_MailServer as New SmtpClient(MailServerName)
MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
SendMail(WeeklyMailServer, msgBody, msgSubject, MsgFromEmail, "xyz#abc.com", rptAttachment)
end using
Next