Enable UWF via WMI - wmi

I am writing a program that needs to enable UWF. Unfortunately, I have no experience with the WMI interface and the UWF documentation has no C# or .NET examples.
When I enable UWF, I get an exception: 'Invalid method Parameters(s)'. But, according to the documentation - https://learn.microsoft.com/en-us/windows-hardware/customize/enterprise/uwf-filter - Enable does not have input parameters. Passing through null doesn't work neither:
var scope = new ManagementScope(#"root\standardcimv2\embedded");
var uwfClass = new ManagementClass(scope.Path.Path, "UWF_Filter", null);
var inputParameters = uwfClass.GetMethodParameters("Enable");
var result = uwfClass.InvokeMethod("Enable", inputParameters, null);

Ok, after a lot of headache, I finally know why it didn't work. The ManagementClass only represents a class, not the object (instance). To make it work, I need to invoke the method on the instance:
var instances = uwfClass.GetInstances();
foreach (ManagementObject instance in instances)
{
var result = instance.InvokeMethod("Enable", null);
break; //There should only be one instance, but to be sure, exit after first instance
}
It might be logical, but not very obvious if you are not used to WMI.

Related

How do I get the Code Review Id in a custom section of the code review page?

I am writing a visual studio extension that has a section on the code review page. I would like access to the information about the rest of the code review page, specifically what code review is current on the page being displayed. I should be able to access the workitemId but so far I have not figured out how.
Edit
Using Cole's suggestion I have accessed the PageContent but I do not know what type I should cast the content to. Nor do I know when it will be available. I would like access both when I initialize my section, and later. Here is my code when I try to initialize the section:
public override object SectionContent
{
get
{
if (base.SectionContent == null)
{
var teamExplorerPage = this.GetService<ITeamExplorerPage>();
var pageContent = teamExplorerPage.PageContent;
this.model.CodeReviewId = pageContent;
base.SectionContent = new CodePlusTeamExplorerSectionView(this.ServiceProvider, this.model);
}
return base.SectionContent;
}
}
When I debug the code I see that a DataContext is available on the PageContent, but I do not know what type to cast the pageContent (orITeamExplorerPage) to, to gain access to it. Also the DataContext has a CodeReviewId property which seems like the value I need but it is null at this point of the Lifecycle. If I want to retrieve some additional data based on the CodeReviewId when/where is it available?
I am still trying to figure out how to get it earlier in the lifecycle of the page but from an event like a button click in the page I can retrieve the value using reflection. This seems like a bit of a hack, perhaps someone else has a better way, but here it is.
private void Button_Click(object sender, RoutedEventArgs e)
{
var teamExplorer = this.GetService<ITeamExplorer>();
var currentPage = teamExplorer.CurrentPage;
var currentContent = currentPage.PageContent;
Type type = currentContent.GetType();
PropertyInfo pi = type.GetProperty("DataContext");
var dataContext = pi.GetValue(currentContent);
Type contextTypetype = dataContext.GetType();
PropertyInfo contextTypePi = contextTypetype.GetProperty("CodeReviewId");
var codeReviewId = contextTypePi.GetValue(dataContext);
var context = new Dictionary<string, object>();
context.Add("WorkItemId", codeReviewId);
teamExplorer.NavigateToPage(new Guid(TeamExplorerPageIds.ViewCodeReview), context);
}

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.

Unable to access WMI on remote machine using vb.net

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)

Locking script when accessing spreadsheet doesnot work

My problem is how to ensure that no data will be lost while concurrent access.
I have script published as web-app. I want to add new row to DATA_SHEET. The function that handles submit button looks like this:
function onButtonSubmit(e) {
var app = UiApp.getActiveApplication();
var lock = LockService.getPublicLock();
while (! lock.tryLock(1000))
;
var ssheet = SpreadsheetApp.openById(SHEET_ID);
var sheet = ssheet.getSheetByName(DATA_SHEET);
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var rangeToInsert = sheet.getRange(lastRow+1, 1, 1, lastCol);
var statText = rangeToInsert.getA1Notation();
rangeToInsert.setValues(<some data from webapp form>);
app.getElementById('statusLabel').setText(statText);
lock.releaseLock();
return app;
}
But it seems that this does not work. When I open two forms and click submit button within one second, it shows same range in statsLabel and writes data into same range. So I lose data from one form.
What is wrong with this code? It seems like tryLock() does not block script.
Is there any other way how to prevent concurrent write access to sheet?
It might be worth taking a look at appendRow(), rather than using getLastRow()/setValues() etc.
Allows for atomic appending of a row to a spreadsheet; can be used
safely even when multiple instances of the script are running at the
same time. Previously, one would have to call getLastRow(), then write
to that row. But if two invocations of the script were running at the
same time, they might both read the same value for getLastRow(), and
then overwrite each other's values.
while (! lock.tryLock(1000))
;
seems a bit hinky. Try this instead:
if (lock.tryLock(30000)) {
// I got the lock! Wo000t!!!11 Do whatever I was going to do!
} else {
// I couldn’t get the lock, now for plan B :(
GmailApp.sendEmail(“admin#example.com”, “epic fail”,
“lock acquisition fail!”);
}
http://googleappsdeveloper.blogspot.com/2011/10/concurrency-and-google-apps-script.html
You must insert this code when using getLastRow()/setValues() with lock.
SpreadsheetApp.flush();
// before
lock.releaseLock();

Using Apache HttpComponents for http requests with NTLM authentication

Quick background.
CFHTTP doesn't support Windows NTLM/Authenticate authentication, only basic authentication. I need to make http requests that will have to authenticate against NTLM, so I've ended up rolling my own version of CFHTTP.
I found Terry Ryan's article that uses the apache httpclient version 3.1 to perform digest authentication and have built upon that using version 4.1.2 instead which includes NTLM functionality.
I have a function that will perform a get request and then other functions to handle returning a structure that looks like the cfhttp result set. The changes I made are based on the authentication tutorial example.
public any function httpRequest(url,username,password,domain) {
var httpClient = createObject("java","org.apache.http.impl.client.DefaultHttpClient");
var authScope = createObject("java","org.apache.http.auth.AuthScope");
var httpCredentials = createObject("java","org.apache.http.auth.NTCredentials");
var httpGet = createObject("java","org.apache.http.client.methods.HttpGet");
var jURL = createObject("java", "java.net.URL").init(arguments.url);
var host = jURL.getHost();
var path = jURL.getPath();
var httpHostTarget = createObject("java","org.apache.http.HttpHost").init(host,80,"http");
var localContext = createObject("java","org.apache.http.protocol.BasicHttpContext");
var httpContent = {};
var response = '';
if (len(arguments.username) and len(arguments.password) gt 0){
httpCredentials.init(arguments.Username, arguments.password, cgi.remote_host,arguments.domain);
httpClient.getCredentialsProvider().setCredentials(authScope.ANY, httpCredentials);
}
if (!Len(path)) path = "/";
httpGet.init(path);
response = httpClient.execute(httpHostTarget, httpget, localContext);
httpContent = convertHttpClientResponseToCFHTTPFormat(response);
httpClient.getConnectionManager().shutdown();
return httpContent;
}
This was working fine until I altered the function to perform the authentication.
Unfortunately I'm now getting :
The execute method was not found.
Either there are no methods with the specified method name and argument types or the execute method is overloaded with argument types that ColdFusion cannot decipher reliably. ColdFusion found 2 methods that match the provided arguments. If this is a Java object and you verified that the method exists, use the javacast function to reduce ambiguity.
As far as I can tell there is only one matching execute() function in HttpClient for the object classes passed to it, so I'm a little confused. JavaCast doesn't allow you to cast to complex objects or super types, so that didn't work.
Can anyone suggest how I can get this to work? How can I reduce the ambiguity?
Looking at the error, it's getting confused between two execute methods that have the same number of parameters. Although I don't know why it is...
Anyway, I found a way around the error. It involves pulling the method you're after out of the class and invoking it directly. If ColdFusion was happier with casting Java objects life might be easier.
//response = httpClient.execute(httpHostTarget, httpget, localContext);
classes = [httpHostTarget.getClass(), CreateObject('java', 'org.apache.http.HttpRequest').getClass(), CreateObject('java', 'org.apache.http.protocol.HttpContext').getClass()];
method = httpClient.getClass().getMethod('execute', classes);
params = [httpHostTarget, httpget, localContext];
response = method.invoke(httpClient, params);
There may be another way of doing this (casting instead) but it's all I've got ;)
As a guess, could you be loading the wrong version of the .jars ? You don't seem to be using JavaLoader like Ryan did...