Unable to access WMI on remote machine using vb.net - wmi

I've had a scout around and can't seem to find the answer anywhere, so need to ask.
I'm trying to query the WMI on a remote machine, but I need to do so as the admin account and I'm having problems doing so.
The code I am using is:
Public Sub OperatingSystem(ByVal computeritem As String)
'set Username and Password which system will access the network with.
Dim options As ConnectionOptions
options = New ConnectionOptions()
options.Authority = "ntdlmdomain:" & ipaddress
options.Username = "Username"
options.Password = "Password"
scope = New ManagementScope("\\" & ipaddress & "\root\cimv2", options)
scope.Connect()
Dim query As ObjectQuery
query = New ObjectQuery("SELECT * FROM Win32_OperatingSystem")
Dim searcher As ManagementObjectSearcher
searcher = New ManagementObjectSearcher(scope, query)
the query continues to go and pull all kinds of information through to a spradsheet.. well it would if it worked!
The line of code that is falling over is:
scope = New ManagementScope("\\" & ipaddress & "\root\cimv2", options)
scope.Connect()
It's giving me an error message that just says 'Invalid parameter'. When I go to view detail, there's nothing in inner exception and the only thing that I can see of any value is ErrorCode:ManagementStatus.InvalidParameter
I apologize if this is something really simple.. I am still fairly new to this but if someone could give me some guidance that would really be appreciated.
Many Thanks.

It looks like the reference to ipaddress is not initialized. Since computeritem is passed as a parameter to the sub, your code might work better with:
scope = New ManagementScope("\\" & computeritem & "\root\cimv2", options)

Related

How to pass text value to MFMailcomposeView Controller

Hi guys faily newbie here tons to learn in IOS
I am using messageUI and I want to pass a text value to MFmailComposeviewController
this is why I have try so far
var userdata = String(txtUserEmail.Text)
let mail = MFMailComposeViewController()
mail.setToRecipients([" \(userdata)"])
for somereason when I enter a email address it does not show in the composer of course there are other parts to the code that I have not included on here. As the main problem is i am unable to pass this value to the setToRecipients([])
any support would be most welcome here
Is txtUserEmail a UITextField?
If so declare your userdata like this:
let userdata = txtUserEmail.text
mail.setToRecipients(userdata!)
A UITextField.text (not "Text") already returns a string.

GetHostedProfilePage not honouring hostedProfileBillingAddressOptions setting

I've been trying to update our API call to the CIM interface for Authorize.net to hide the Billing Address fields on the hosted profile page.
The documentation states that when call the token creation function, passing in a setting "hostedProfileBillingAddressOptions" with a value of "showNone" will hide the billing address part of the form, however when I pass in this setting I am still getting the billing address showing.
I've verified that I'm passing the setting correctly (added the same way as the "hostedProfileIFrameCommunicatorUrl" and "hostedProfilePageBorderVisible" settings) and if I pass an invalid value for the "hostedProfileBillingAddressOptions" option, the Token creation function will return an error
Is there something else that this option is dependent on, such as an account setting or another settings parameter?
For reference, I'm testing this in the Sandbox system and I'm using the dotNet SDK, my test code for calling the API function is as follows
Public Shared Function CreateHostFormToken(apiId As String, apiKey As String, branchId As Int64, nUser As Contact, iframeComURL As String) As String
Dim nCustProfile = GetCustomerProfile(apiId, apiKey, branchId, nUser)
Dim nHost = New AuthorizeNet.Api.Contracts.V1.getHostedProfilePageRequest()
nHost.customerProfileId = nCustProfile
' Set Auth
Dim nAuth = New Api.Contracts.V1.merchantAuthenticationType()
nAuth.ItemElementName = Api.Contracts.V1.ItemChoiceType.transactionKey
nAuth.name = apiId
nAuth.Item = apiKey
nHost.merchantAuthentication = nAuth
' Set Params
Dim settingList As New List(Of Api.Contracts.V1.settingType)
Dim nParam As New Api.Contracts.V1.settingType With {.settingName = "hostedProfileIFrameCommunicatorUrl",
.settingValue = iframeComURL}
settingList.Add(nParam)
nParam = New Api.Contracts.V1.settingType With {.settingName = "hostedProfilePageBorderVisible",
.settingValue = "false"}
settingList.Add(nParam)
nParam = New Api.Contracts.V1.settingType With {.settingName = "hostedProfileBillingAddressOptions",
.settingValue = "showNone"}
settingList.Add(nParam)
nHost.hostedProfileSettings = settingList.ToArray
Dim nX = New AuthorizeNet.Api.Controllers.getHostedProfilePageController(nHost)
Dim nRes = nX.ExecuteWithApiResponse(GetEnvironment())
Return nRes.token
End Function
I've looked through the SDK code as well, and I don't see anything there that would be preventing the setting from being passed through.
Has anyone come across this issue, or successfully set the card entry form to hide the billing address?
There turned out to be two parts to the solution to this problem:
In order to use the "hostedProfileBillingAddressOptions" option, you need to use a newer version of the capture page than I was using. I was using "https://secure2.authorize.net/profile/", while the new version is "https://secure2.authorize.net/customer/". Added bonus, the new URL provides a much nicer and modern looking form.
However, once this was working, I then had the problem that on entering the card, a validation message told me that "address and Zip code are required", despite not being visible. I did also make sure that I had the option "hostedProfileBillingAddressRequired" set to false (which is it's default value anyway)
The response from Authorize.net support is that in order to capture card without an address, the option "hostedProfileValidationMode" must be set to "testMode".
This is not mentioned in the documentation (at least as far as I could see), so may not be something that other people are aware of since it is a little counter-intuitive to use 'testMode' on a live environment.
It's not ideal since validating the card for a customer account will send a transaction email to the merchant, but it seems there is not another way around this just now.
In summary, to allow the customer to add a credit card to their profile without having to provide an address, you need to specify the following options:
Form URL for capture - https://secure2.authorize.net/customer/
getHostedProfilePageRequest -
hostedProfileIFrameCommunicatorUrl: *your URL*
hostedProfilePageBorderVisible: false //assuming you are using an iFrame
hostedProfileValidationMode: testMode
hostedProfileBillingAddressOptions: showNone

How to get Expiration Date of access token in Facebook SDK for Unity

I am using parse sdk for backend management for my game. For user signup/login parse api ask for parameter tokenExpiration. I have no idea how to get it from facebook unity sdk.
https://www.parse.com/docs/unity_guide#fbusers-signup
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(accessToken, userId, tokenExpiration);
Got this problem solved by myself using debug_token. Here is the right code on how to do it.
FB.API("/debug_token?input_token="+FB.AccessToken+"&access_token="+FB.AccessToken,Facebook.HttpMethod.GET, AccessTokenCallback);
function AccessTokenCallback(response:String){
Debug.Log(response);
var access = JSON.Parse(response);
Debug.Log("Token Expiration is: "+access["data"]["expires_at"].Value);
}
If you will print the response it will give you a JSON with all information about the access token and you can take whatever info you need about an access token.
Open FacebookAccessTokenEditor.cs and replace original line 81:
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}]";
by these two:
string getExpiresAt = ",{\"method\":\"GET\", \"relative_url\":\"debug_token?input_token="+accessToken+"\"}";
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}"+getExpiresAt+"]";
Then open FacebookEditor.cs and in method MockLoginCallback, just before line 220:
isLoggedIn = true;
insert the following lines:
var tokenData = (Dictionary<string, object>)MiniJSON.Json.Deserialize(responses[2]);
var expiresAt = (long)((Dictionary<string, object>)tokenData["data"])["expires_at"];
accessTokenExpiresAt = FromTimestamp((int)expiresAt);
also, add the missing function FromTimestamp which you can copy from AndroidFacebook.cs or IOSFacebook.cs or jus copy from here:
private DateTime FromTimestamp(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
Finally, you can call the parse method like you do on IOS or Android or Web:
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(FB.UserId, FB.AccessToken, FB.AccessTokenExpiresAt);
Note: As I have worked on the code, I am not sure of the original line numbers, but I think they are correct. Also, this does not reflect the best coding practices, but since it is used only in a debug context, they're good enough for me.

Resolving incidents (closing cases) in CRM4 through webservices?

I'm trying to resolve/close Dynamics CRM4 cases/incidents through webservices.
A single SetStateIncidentRequest is not enough and returns a Server was unable to process request error message. I think it has something to do with active workflows that trigger on case's attribute changes. I don't know if there's anything else preventing the request to work.
Since it is possible to close those cases through the GUI, I guess there's a "correct" set of steps to follow in order to achieve it through CrmService; unfortunately, I've been googleing it for a while without finding what I want. Could anybody help me, please?
To resolve a case in CRM (in VB.NET), I do the following:
Try
Dim activity As New incidentresolution
Dim closeRequest As New CloseIncidentRequest
Dim closeResponse As New CloseIncidentResponse
Dim strErrors As String = String.Empty()
activity.incidentid = New Lookup
activity.incidentid.type = EntityName.incident.ToString
activity.incidentid.Value = //[GUID OF INCIDENT]
activity.ownerid = New Owner
activity.ownerid.type = EntityName.systemuser.ToString
activity.ownerid.Value = //[GUID OF USER PERFORMING ACTION]
activity.statecode = New IncidentResolutionStateInfo
activity.statecode.Value = 1 //Resolved
activity.statuscode = New Status
activity.statuscode.Value = 5 //Problem Solved
closeRequest.IncidentResolution = activity
closeRequest.Status = 5 //Problem Solved
// IF REQUIRED:
activity.timespent = New CrmNumber
activity.timespent.Value = //[INTEGER REPRESENTING No. OF MIN SPENT ON CASE]
closeResponse = objCrm.Execute(closeRequest)
Catch ex As System.Web.Services.Protocols.SoapException
Dim root As XmlElement = ex.Detail
strErrors = strErrors & vbCrLf & vbCrLf & root.ChildNodes(0).ChildNodes(3).InnerText
Return False
End Try
Here's a tip - catch the SoapException and examine the Detail.OuterXML property and you will get a more detailed error message. It's possible you're not building your request correctly.
Indeed, I didn't know that there exists a CloseIncidentRequest class to use with the CrmService.Execute() method. Most probably the SetStateIncidentRequeset won't work because it's expected that incident resolutions are created that way. Pity that names for classes and actions aren't used consistently (case/incident, resolution/closing)...

Classic Asp Web Service Problem

I'm trying to create a code to allow an existing classic asp program to use an asp.net web service. Updating from the classic asp is not an option, as I'm working in a big company and things are the way they are.
I've been browsing through a chunk of tutorials supposedly helping in this, but I haven't managed to get them to work yet. As a beginner I might've made some real obvious mistakes but I just don't know what.
First, the web service is located on an external server. The method "Greeting" needs a String parameter by which it determines which String is sent back. Inputting "g" to it procudes this xml:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://server1/Logger_WebService/">Greetings and welcome!</string>
I assume the xpath for getting the contents is either "string/*" or "*"?
Next, my web service itself looks like this:
<WebMethod()> _
Public Function Greeting(ByVal stringel As String) As String
If stringel.ToLower = "g" Then
Return "Greetings and welcome!"
Else
Return "Bye then!"
End If
End Function
The web service works fine from a regular asp.net solution.
Now here's the problem, the classic asp code looks like this (4 different ways I've tried to get this to work, SOAP toolkit is installed on the web service server, all examples taken and modified from tutorials):
'******* USING GET METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting?g"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET",wsurl,false
xmlhttp.send
Dim rValue
'rValue=xmlhttp.responseXML.selectSingleNode("string") 'use XPATH as input argument
' or you can get response XML
rValue=xmlhttp.responseXML
Set xmlhttp=nothing
'------------------------------------------------------
'******* USING POST METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST",wsurl,false
xmlhttp.send "stringeli=g"
Dim rValue
rValue=xmlhttp.responseXML.selectSingleNode("string")
' or you can get response XML
' rValue=xmlhttp.responseXML
Set xmlhttp=nothing
'------------------------------------------------------
Response.Write consumeWebService()
Function consumeWebService()
Dim webServiceUrl, httpReq, node, myXmlDoc
webServiceUrl = "http://server1/Logger_WebService/service.asmx/Greeting?stringel=g"
Set httpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "GET", webServiceUrl, False
httpReq.Send
Set myXmlDoc =Server.CreateObject("MSXML.DOMDocument")
myXmlDoc.load(httpReq.responseBody)
Set httpReq = Nothing
Set node = myXmlDoc.documentElement.selectSingleNode("string/*")
consumeWebService = " " & node.text
End Function
'------------------------------------------------------
Response.Write(Helou())
Public Function Helou()
SET objSoapClient = Server.CreateObject("MSSOAP.SoapClient")
objSoapClient.ClientProperty("ServerHTTPRequest") = True
' needs to be updated with the url of your Web Service WSDL and is
' followed by the Web Service name
Call objSoapClient.mssoapinit("http://server1/Logger_WebService/service.asmx?WSDL", "Service")
' use the SOAP object to call the Web Method Required
Helou = objSoapClient.Greeting("g")
End Function
I seriously have no idea why nothing works, I've tried them every which way with loads of different settings etc. One possible issue is that the web service is located on a server which in ASP.Net required me to input this "[ServiceVariableName].Credentials = System.Net.CredentialCache.DefaultCredentials". I do this from within company network, and there are some security and authorization issues.
I only need to be able to send information anyhow, not receive, as the actual method I will be using is going to insert information into a database. But for now, just getting the Hello World thingie to work seems to provide enough challenge. :)
Thx for all the help. I'll try to check back on holiday hours to check and reply to the comments, I've undoubtedly left out needed information.
Please, talk as you would to an idiot, I'm new to this so chances are I can understand better that way. :)
You might consider writing a bit of .NET wrapper code to consume the web service. Then expose the .NET code as a COM object that the ASP can call directly. As you've seen, there is no tooling to help you in classic ASP, so consider using as much .NET as possible, for the tooling. Then, use COM to interoperate between the two.
A colleague finally got it working after putting a whole day into it. It was decided that it's easier by far to send information than it is to receive it. Since the eventual purpose of the web service is to write data to the DB and not get any message back, we attempted the thing by simply writing a file in the web service.
The following changes were needed:
First, in order to get it to work through the company networks, anonymous access had to be enabled in IIS.
The web service needed the following change in the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
And the web service code-behind was changed like so:
<WebMethod()> _
Public Function Greeting(ByVal stringel As String) As String
Dim kirj As StreamWriter
'kirj = File.CreateText("\\server1\MyDir\Logger_WebService\test.txt")
'if run locally, the line above would need to be used, otherwise the one below
kirj = File.CreateText("C:\Inetpub\serverroot\MyDir\Logger_WebService\test.txt")
kirj.WriteLine(stringel)
kirj.Close()
kirj.Dispose()
Return stringel
End Function
As we got the above to work, it was a simple matter of applying the same to the big web method that would parse and check the info and insert it into the database.
The classic asp code itself that needs to be added to the old page, which was the biggest problem, turned out to be relatively simple in the end.
function works()
message = "http://server1/mydir/logger_webservice/service.asmx/Greeting?" & _
"stringel=" & "it works"
Set objRequest = Server.createobject("MSXML2.XMLHTTP")
With objRequest
.open "GET", message, False
.setRequestHeader "Content-Type", "text/xml"
.send
End With
works = objRequest.responseText
end function
works()
Took about a week's worth of work to get this solved. :/ The hardest part was simply not ever knowing what was wrong at any one time.
You might be missing the SOAPAction header. Here's a working example:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class GreetingService : WebService
{
[WebMethod]
public string Greet(string name)
{
return string.Format("Hello {0}", name);
}
}
And the calling VBS script:
Dim SoapRequest
Set SoapRequest = CreateObject("MSXML2.XMLHTTP")
Dim myXML
Set myXML = CreateObject("MSXML.DOMDocument")
myXML.Async=False
SoapRequest.Open "POST", "http://localhost:4625/GreetingService.asmx", False
SoapRequest.setRequestHeader "Content-Type","text/xml;charset=utf-8"
SoapRequest.setRequestHeader "SOAPAction", """http://tempuri.org/Greet"""
Dim DataToSend
DataToSend= _
"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" & _
"<soapenv:Header/>" & _
"<soapenv:Body>" & _
"<tem:Greet>" & _
"<tem:name>John</tem:name>" & _
"</tem:Greet>" & _
"</soapenv:Body>" & _
"</soapenv:Envelope>"
SoapRequest.Send DataToSend
If myXML.load(SoapRequest.responseXML) Then
Dim Node
Set Node = myXML.documentElement.selectSingleNode("//GreetResult")
msgbox Node.Text
Set Node = Nothing
End If
Set SoapRequest = Nothing
Set myXML = Nothing
Might want to double-check the version of the MSXML components. Are you using Windows Authentication? I've noticed some odd XML parsing problems with IIS 7, Classic ASP, and MSXML.
It would also help to get a useful error. Check the ** myXML.parseError.errorCode** and if its not 0 write out the error.
Reference Code:
If (myXML.parseError.errorCode <> 0) then
Response.Write "XML error: " & myXML.parseError.reason
Else
'no error, do whatever here
End If
'You get the idea...