I am trying to run Office365 cmdlets in a vb.net webservice project.The code is:
Public Function ExcutePowershellCommands() As ObjectModel.Collection(Of PSObject)
Try
Dim userList As ObjectModel.Collection(Of PSObject) = Nothing
Dim initialSession As InitialSessionState = InitialSessionState.CreateDefault()
initialSession.ImportPSModule(New String() {"MSOnline"})
Dim O365Password_secureString As New System.Security.SecureString()
Dim O365Password As String = "password"
For Each x As Char In O365Password
O365Password_secureString.AppendChar(x)
Next
Dim credential As New PSCredential("username", O365Password_secureString)
Dim connectCommand As New Command("Connect-MsolService")
connectCommand.Parameters.Add((New CommandParameter("Credential", credential)))
Dim getCommand As New Command("Get-MsolUser")
Using psRunSpace As Runspace = RunspaceFactory.CreateRunspace(initialSession)
psRunSpace.Open()
For Each com As Command In New Command() {connectCommand, getCommand}
Dim pipe As Pipeline = psRunSpace.CreatePipeline()
pipe.Commands.Add(com)
Dim results As ObjectModel.Collection(Of PSObject) = pipe.Invoke()
Dim [error] As ObjectModel.Collection(Of Object) = pipe.[Error].ReadToEnd()
If [error].Count > 0 AndAlso com.Equals(connectCommand) Then
Throw New ApplicationException("Problem in login! " + [error](0).ToString())
Return Nothing
End If
If [error].Count > 0 AndAlso com.Equals(getCommand) Then
Throw New ApplicationException("Problem in getting data! " + [error](0).ToString())
Return Nothing
Else
userList = results
End If
Next
psRunSpace.Close()
End Using
Return userList
Catch generatedExceptionName As Exception
Throw
End Try
End Function
When Connect-MsolService is run, I get this error message:
There was no endpoint listening at https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
I can run this function successfully within a windows App. I think some thing might be wrong in IIS. any idea?
Related
I am using asp.net / vb.net. I want to send an email. My code does not send an email as it is. I am wondering what I am doing wrong here.
I created a file called email.text that holds the email template. The rest of the code to send the email is below. I removed personal information from my code.
I setup the SMTP connection as such:
Private SMTPClientConnection As SmtpClient
Sub New()
SMTPClientConnection = New SmtpClient
SMTPClientConnection.Host = "HOSTHERE"
SMTPClientConnection.Port = PORTHERE
SMTPClientConnection.DeliveryMethod = SmtpDeliveryMethod.Network
End Sub
Then I created a function to send the email:
Private Shared Function SendEmail(ByVal emailUser As String, ByVal bodyMessage As List(Of String), ByVal priority As MailPriority) As Boolean
Dim functionReturnValue As Boolean = False
Try
If Not String.IsNullOrWhiteSpace(emailUser) Then
If Regex.IsMatch(emailUser, "^([a-zA-Z0-9]+([\.+_-][a-zA-Z0-9]+)*)#(([a-zA-Z0-9]+((\.|[-]{1,2})[a-zA-Z0-9]+)*)\.[a-zA-Z]{2,6})$") Then
Using SMTPClientConnection
Dim smtpMessage As MailMessage = New MailMessage()
Dim _with1 = smtpMessage
_with1.[To].Add(New MailAddress(emailUser))
_with1.From = New MailAddress("Test Email" & " <email#email.com>")
_with1.ReplyToList.Add(New MailAddress("email#email.com"))
_with1.Subject = "Test Email"
_with1.Priority = priority
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(bodyMessage(0), Nothing, "text/html")
Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString(bodyMessage(1), Nothing, "text/plain")
_with1.AlternateViews.Add(plainView)
_with1.AlternateViews.Add(htmlView)
SMTPClientConnection.Send(smtpMessage)
Return True
End Using
Else
Throw New SmtpException("Invalid email.")
End If
End If
Catch ex As Exception
End Try
Return functionReturnValue
End Function
I use the function on my code here:
Dim plainBody As String = File.ReadAllText(HttpContext.Current.Server.MapPath("email.txt"))
plainBody = plainBody.Replace("%Name%", emailName)
Dim emailBody As List(Of String) = New List(Of String)(New String() {plainBody})
SendEmail("email#email.com", emailBody, MailPriority.Normal)
The compiler error message is clear. The variable SmtpClientConnection is an instance variable (it exists as a different entity in any class instance where is declared) but you are trying to use inside a Shared method (a method that exists without a class instance). Inside this kind of methods you cannot use instance variables because you don't have an instance from which the method could pick the variable value and use it.
The solution could be to remove the Shared keyword from the method and then, whenever you want to call the method you need to create an instance of the class where the instance variable SmtpClientConnection is initialized and ready to be used in the following call to the SendMail method.
However, you could still use the Shared method but should remove the instance variable and create it inside the SmtpClient method:
Private Shared Function SendEmail(ByVal emailUser As String, ByVal bodyMessage As List(Of String), ByVal priority As MailPriority) As Boolean
Dim functionReturnValue As Boolean = False
Try
If Not String.IsNullOrWhiteSpace(emailUser) Then
If Regex.IsMatch(emailUser, "^([a-zA-Z0-9]+([\.+_-][a-zA-Z0-9]+)*)#(([a-zA-Z0-9]+((\.|[-]{1,2})[a-zA-Z0-9]+)*)\.[a-zA-Z]{2,6})$") Then
Dim SMTPClientConnection As SmtpClient = New SmtpClient
SMTPClientConnection.Host = "HOSTHERE"
SMTPClientConnection.Port = PORTHERE
SMTPClientConnection.DeliveryMethod = SmtpDeliveryMethod.Network
Using SMTPClientConnection
Dim smtpMessage As MailMessage = New MailMessage()
......
SMTPClientConnection.Send(smtpMessage)
Return True
End Using
Else
Throw New SmtpException("Invalid email.")
End If
End If
Catch ex As Exception
' No point in catching an exception and doing nothing here.
' You can log the exception somewhere and then throw it again
LogException(ex)
Throw
' or just remove the try/catch block.
End Try
Return functionReturnValue
End Function
In this way the variable is created only when needed and destroyed as well when the using statement ends. Take also note of the comments relative to the Try/Catch block.
In my ASP.NET(VB) project, I am facing error to get XML response from remote server using TcpClient. The error is Thread was being aborted. The code in which I am facing error is given as follows.
Private Function GetCMSAPIXMLResp(ByVal strReqXml As String, ByVal strAPIIpAddr As String, ByVal strAPIPort As String) As String
Dim strRespXml As String = String.Empty
Try
objClientSocket = New TcpClient()
objClientSocket.Connect(strAPIIpAddr, strAPIPort)
If objClientSocket.Connected = True Then
objNetStrm = objClientSocket.GetStream()
Dim btOutStrm() As Byte = System.Text.Encoding.ASCII.GetBytes(strReqXml)
objNetStrm.Write(btOutStrm, 0, btOutStrm.Length)
objNetStrm.Flush()
If objNetStrm.CanRead Then
Dim lngBuffSize As Long = CLng(objClientSocket.ReceiveBufferSize)
Dim btInStream(lngBuffSize) As Byte
strbldRespXml = New StringBuilder()
Dim iNoBytesRead As Integer = 0
Do
iNoBytesRead = objNetStrm.Read(btInStream, 0, btInStream.Length)
strbldRespXml.AppendFormat("{0}", System.Text.Encoding.ASCII.GetString(btInStream, 0, iNoBytesRead))
Loop While objNetStrm.DataAvailable
strRespXml = Convert.ToString(strbldRespXml)
strRespXml = strRespXml.Replace(vbCrLf, vbNullString)
Else
lblError.Text = "Unable to read"
End If
Else
lblError.Text = "Unable to connect with remote server"
End If
Catch ex As Exception
Throw
Finally
objClientSocket = Nothing
objNetStrm = Nothing
strbldRespXml = Nothing
End Try
Return strRespXml
End Function
Actually, I just want to know at what point the error is getting and Why.
NOTE : Port opening has been done and when I do ping and telnet to remote server, getting positive response.
I have a very simple code that invokes a stored procedure. The stored proc is used for sending out reminders to user's on expiring account.
When a user enters correct email address, the user gets a reminder email with the message, "Reminder sent successfully"
This is exactly what we want.
However, if the user enters an invalid email address, the user still sees same message, "Reminder sent successfully"
This is not good.
Can you please help with what I am doing wrong?
Please see entire (actual) code below:
Protected Sub BtnSubmit_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnSubmit.Click
Dim oConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("sConnectionString").ConnectionString)
Dim oCommand As SqlCommand = New SqlCommand()
Try
oConnection.Open()
oCommand.Connection = oConnection
oCommand.CommandText = "AcountExpiration"
oCommand.CommandType = CommandType.StoredProcedure
oCommand.Parameters.Add(New SqlParameter("#Email", Data.SqlDbType.VarChar, 50)).Value = Email.Text
Dim adpt As New SqlDataAdapter(oCommand)
Dim ds As New DataSet()
adpt.Fill(ds)
oCommand.ExecuteReader()
lblMsg.Text="Reminder successfully sent"
Catch ex As SqlException
Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('" + ex.Message + "')</SCRIPT>")
Finally
oConnection.Close()
End Try
End Sub
c# solution is welcome as well.
Dim scmd As SqlCommand = New SqlCommand("AcountExpiration", Conn)
scmd.CommandType = CommandType.StoredProcedure
scmd.Parameters.AddWithValue("#Email", Email.Text)
'Dim r As SqlDataReader = scmd.ExecuteReader()
Dim validEmail As Boolean = False
Dim reader As SqlDataReader = scmd.ExecuteReader()
While reader.Read()
'if we are here then something got returned.
'so probably a valid email.
validEmail = True
End While
If validEmail = True Then
lblMsg.Text = "Success"
Else
lblMsg.Text = "email does not exit on our system"
End If
You have a couple of different options as I see it.
Have the sproc throw an error if the email address isn't valid.
Have validation on the dataset to check and make sure you are getting back the expected values. Only display the success message if there was actually a success.
I would not use a SqlDataAdapter or Dataset for this. just use the SqlDataReader
bool validEmail = false;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//if we are here then something got returned.
//so probably a valid email.
validEmail = true;
}
Or use ExecuteScalar
bool validEmail = Convert.ToBoolean(command.ExecuteScalar());
then
if(validEmail)
{
}
else
{
}
UPDATE
Will add an update for this as some people don't realise that certain code wont magically work. I have already included links for ExecuteScalar and ExecuteReader to show how to use these methods.
If you wanted to use ExecuteScalar you would have to change your stored procedure to return a value that could then be parsed as a Boolean.
The above methods is simply for checking if an email exists in the DB. No this does not valdate an email address, as I would expect that to occur before this code would be reached.
I have the below mentioned code in a seperate class file for establishing connection and carry out DB transactions. I have an issue where multiple connections being opened which sometime exceed the connection pool. When I stepped through the code I found that there are codes which call ConnectDB() in a loop without calling DisconnectDB(). But I expected that the condition OraConn.State = ConnectionState.Closed should handle the situation. Somehow the condition is always satisfied hence openning another set of connection. Can you suggest where am I going wrong and also what best practice can be adopted here?
Public Class Connection
Dim Str_conn As String = "Data Source=...; User=...; password=...; Min Pool Size=10; Max Pool Size=500;"
Public OraConn As OracleConnection
Dim cmd As OracleCommand
Dim dr As OracleDataReader
Dim data_adapt As OracleDataAdapter
Dim dt As DataTable
Dim ds As DataSet
Public Sub ConnectDB()
OraConn = New OracleConnection(Str_conn)
If OraConn.State = ConnectionState.Closed Then
OraConn.Open()
End If
End Sub
Public Sub DisconnectDB()
If OraConn.State = ConnectionState.Open Then
OraConn.Close()
End If
End Sub
Public Function get_dataset(ByVal query As String, ByRef ds As DataSet) As DataSet
data_adapt = New OracleDataAdapter(query, OraConn)
data_adapt.Fill(ds)
Return ds
End Function
Public Function get_datareader(ByVal query As String) As OracleDataReader
cmd = New OracleCommand(query, OraConn)
dr = cmd.ExecuteReader()
Return dr
End Function
Public Sub UpdateDB(ByVal query As String)
cmd = New OracleCommand(query, OraConn)
cmd.ExecuteNonQuery()
cmd.Dispose()
End Sub
The class is refered in other classes or directly in the aspx.vb pages like this.
Public Function InsertData(ByVal var1 As String, ByVal var2 As String) As Integer
conn.ConnectDB()
Dim qryInsert As String
qryInsert = " INSERT INTO TABLE VALUES ('" & var1 & "', "
qryInsert = qryInsert & var2 & "')"
Try
conn.UpdateDB(qryInsert)
Catch ex As OracleException
If ex.Code = 1 Then
updData(var1, var2)
ElseIf ex.Code = 2091 Then
msgprompt("Duplicate Unique Key!", "Warning")
End If
Finally
conn.DisconnectDB()
End Try
Return count
End Function
The connection is again opened in function updData(). While I understand that it has to be closed correctly but keeping tab on every developer is not possible. Hence I want to control it directly from the connection class by using the same connection but the condition If OraConn.State = ConnectionState.Closed is not helping.
UPDATE
I have put the code in UpdateDB under a Using block and removed call to ConnectDB and DisconnectDB from function like InsertData(...). It seems that the issue has been resolved. But I would like to know in case of exception will the connection remain open? and also OraConn is a public variable defined outside Using block so will it be disposed of by the GC?
Public Sub UpdateDB(ByVal query As String)
Using OraConn = New OracleConnection(Str_conn)
cmd = New OracleCommand(query, OraConn)
Try
OraConn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw
Finally
cmd.Dispose()
End Try
End Using
End Sub
You must close all the connections as soon as you are done with it, no matter what.
Suggestion:
The best practice for closing the connection is to do it in finally block. So that even if there is any error, catch it (log it if required) in catch block, and then connection will get close in finally block.
UPDATE
You can put one private static counter in your Connection class. When ever ConnectDB() is called you increment this counter and decrement it in every DisconnectDB(). Now in ConnectDB() you check the value of counter, if it exceeds a minimum threshold you throw error, by doing this way; you can come to know idle connection present in your code and refactor it. On production keep this threshold value high or ignore it in code.
I'm using ASP.NET 3.5 and WF 3.5.
The code I have is constantly giving me a FileNotFoundException. Even though I have created two workflow instances. It keeps trying to grab the first Workflow (and tells me the assembly is not there) and not the second workflow. This is my code:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("LocalWFConnection").ConnectionString
Dim trackingQuery As SqlTrackingQuery = New SqlTrackingQuery(connectionString)
Dim options As SqlTrackingQueryOptions = New SqlTrackingQueryOptions()
Dim workflws As IList(Of SqlTrackingWorkflowInstance)
Try
workflws = trackingQuery.GetWorkflows(options)
Catch ex As SqlException
workflowError = String.Format("A SQL exception occurred. Details:<br />{0}", ex.Message)
Return workflowData
Catch ex As IO.FileNotFoundException
workflowError = String.Format("File loading exception occurred. Details:<br />{0}", ex.Message)
Return workflowData
End Try
Dim trackingQuery As SqlTrackingQuery = New SqlTrackingQuery(connectionString)
Dim options As SqlTrackingQueryOptions = New SqlTrackingQueryOptions()
options.WorkflowType = GetType(Workflow1) ' where Workflow1 is the name of your Workflow