Detect Is userAccount Enable or disable in win xp or 7 + C# - c#-3.0

How can i programmically Detect Is userAccount Enable or disable in local OS like win xp or 7 (not Active directory). in C#
also how detect userAccount pass is Expire or not? in C#
thanks.

public static bool IsUserEnable(string username, ContextType type)
{
PrincipalContext context = new PrincipalContext(type);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
return user.Enabled.Value;
}
call this method like:
IsUserEnable("guest", ContextType.Machine);

Related

Need Guidance for better approch on raspberry pi

i want to toggle relays on/off remotely using raspberry pi model b running windows iot core, that raspberry pi have to connect with azure iot hub , and initially i can toggle relay on/off by accessing ui with browser over internet ,
Better approach(c#, node.js on windows iot core), link to related article will be appreciated.
For using Azure IoT Hub, you can utilize direct method.
Device side:
For Windows IoT Core, you can start with UWP app.
The following is a simple sample of implementing the direct method on the device:
using Microsoft.Azure.Devices.Client;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
namespace App1
{
public sealed partial class MainPage : Page
{
private string connectionStr = "HostName=[YOUR HUB NAME].azure-devices.net;DeviceId=[YOUR DEVICE ID];SharedAccessKey=[SHARED ACCESS KEY]";
private DeviceClient deviceClient;
public MainPage()
{
this.InitializeComponent();
AddDirectMethod();
}
private async void AddDirectMethod()
{
deviceClient = DeviceClient.CreateFromConnectionString(connectionStr, TransportType.Mqtt);
await deviceClient.SetMethodHandlerAsync("TurnOn", new MethodCallback(TurnOnRelay), null);
await deviceClient.SetMethodHandlerAsync("TurnOff", new MethodCallback(TurnOffRelay), null);
}
private Task<MethodResponse> TurnOffRelay(MethodRequest methodRequest, object userContext)
{
Debug.WriteLine("Direct method name:" + methodRequest.Name);
// Put Relay toggle code here.
// ...
string result = "{\"Relay Status\":\"The Relay is OFF.\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
}
private Task<MethodResponse> TurnOnRelay(MethodRequest methodRequest, object userContext)
{
Debug.WriteLine("Direct method name:" + methodRequest.Name);
// Put Relay toggle code here.
// ...
string result = "{\"Relay Status\":\"The Relay is ON.\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
}
}
}
You need install NuGet package microsoft.azure.devices.client to your UWP app. Here is a detailed tutorial of a .NET console app you can reference.
Cloud side:
You can call direct method from Azure Portal like this:

SharePoint O365 Get All Users With Certain Role

Is there a way to get all users who have "Full Control" permission at a site collection and subsite level and change their role to something else? PowerShell would be ideal but CSOM would be fine too if that's the only way to do it. I know I can get groups by role but I need a way to get explicitly added users.
I tried this older StackOverflow question: Get all the users based on a specific permission using CSOM in SharePoint 2013 but I keep getting a 403 forbidden error on the first ctx.ExecuteQuery(); for all sites even though I am a collection administrator. I also wonder if anyone had a PowerShell way to do it.
According the error message, I suspect that the credential is missing in your code.
Please try the code below and let me know whether it works on your side.
static void Main(string[] args)
{
var webUrl = "[your_site_url]";
var userEmailAddress = "[your_email_address]";
using (var context = new ClientContext(webUrl))
{
Console.WriteLine("input your password and click enter");
context.Credentials = new SharePointOnlineCredentials(userEmailAddress, GetPasswordFromConsoleInput());
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Console.WriteLine("Your site title is: " + context.Web.Title);
//Retrieve site users
var users = context.LoadQuery(context.Web.SiteUsers);
context.ExecuteQuery();
foreach(var user in users)
{
Console.WriteLine(user.Email);
}
}
}
private static SecureString GetPasswordFromConsoleInput()
{
ConsoleKeyInfo info;
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
You need the SharePoint Online Management shell to stand up a connection to O365 via Powershell.
Introduction to the SharePoint Online management shell

Implement Custom Authentication In Windows Azure Mobile Services

Windows Azure Mobile Services currently doesn't have an option for custom authentication and looking at the feature request
http://feedback.azure.com/forums/216254-mobile-services/suggestions/3313778-custom-user-auth
It isn't coming anytime soon.
With a .NET backend and a .NET application how do you implement custom authentication, so that you don't have to use Facebook, Google or any of their other current providers?
There are plenty of partially completed tutorials on how this this is done with a JS backend and iOS and Android but where are the .NET examples?
I finally worked through the solution, with some help of the articles listed below, some intellisense and some trial and error.
How WAMS Works
First I wanted to describe what WAMS is in a very simple form as this part confused me for a while until it finally clicked. WAMS is just a collection of pre-existing technologies packaged up for rapid deployment. What you need to know for this scenario is:
As you can see WAMS is really just a container for a WebAPI and other things, which I won't go into detail here. When you create a new Mobile Service in Azure you get to download a project that contains the WebAPI. The example they use is the TodoItem, so you will see code for this scenario through the project.
Below is where you download this example from (I was just doing a Windows Phone 8 app)
I could go on further about this but this tutorial will get you started:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-store-dotnet-get-started/
Setup WAMS Project
You will need your MasterKey and ApplicationKey. You can get them from the Azure Portal, clicking on your Mobile Services App and pressing Manage Keys at the bottom
The project you just downloaded, in the Controllers folder I just created a new controller called AccountController.cs and inside I put
public HttpResponseMessage GetLogin(String username, String password)
{
String masterKey = "[enter your master key here]";
bool isValidated = true;
if (isValidated)
return new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{ 'UserId' : 'F907F58C-09FE-4F25-A26B-3248CD30F835', 'token' : '" + GetSecurityToken(new TimeSpan(1,0, 0), String.Empty, "F907F58C-09FE-4F25-A26B-3248CD30F835", masterKey) + "' }") };
else
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Username and password are incorrect");
}
private static string GetSecurityToken(TimeSpan periodBeforeExpires, string aud, string userId, string masterKey)
{
var now = DateTime.UtcNow;
var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var payload = new
{
exp = (int)now.Add(periodBeforeExpires).Subtract(utc0).TotalSeconds,
iss = "urn:microsoft:windows-azure:zumo",
ver = 2,
aud = "urn:microsoft:windows-azure:zumo",
uid = userId
};
var keyBytes = Encoding.UTF8.GetBytes(masterKey + "JWTSig");
var segments = new List<string>();
//kid changed to a string
var header = new { alg = "HS256", typ = "JWT", kid = "0" };
byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
segments.Add(Base64UrlEncode(headerBytes));
segments.Add(Base64UrlEncode(payloadBytes));
var stringToSign = string.Join(".", segments.ToArray());
var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
SHA256Managed hash = new SHA256Managed();
byte[] signingBytes = hash.ComputeHash(keyBytes);
var sha = new HMACSHA256(signingBytes);
byte[] signature = sha.ComputeHash(bytesToSign);
segments.Add(Base64UrlEncode(signature));
return string.Join(".", segments.ToArray());
}
// from JWT spec
private static string Base64UrlEncode(byte[] input)
{
var output = Convert.ToBase64String(input);
output = output.Split('=')[0]; // Remove any trailing '='s
output = output.Replace('+', '-'); // 62nd char of encoding
output = output.Replace('/', '_'); // 63rd char of encoding
return output;
}
You can replace what is in GetLogin, with your own validation code. Once validated, it will return a security token (JWT) that is needed.
If you are testing on you localhost, remember to go into your web.config file and fill in the following keys
<add key="MS_MasterKey" value="Overridden by portal settings" />
<add key="MS_ApplicationKey" value="Overridden by portal settings" />
You need to enter in your Master and Application Keys here. They will be overridden when you upload them but they need to be entered if you are running everything locally.
At the top of the TodoItemController add the AuthorizeLevel attribute as shown below
[AuthorizeLevel(AuthorizationLevel.User)]
public class TodoItemController : TableController<TodoItem>
You will need to modify most of the functions in your TodoItemController but here is an example of the Get All function.
public IQueryable<TodoItem> GetAllTodoItems()
{
var currentUser = User as ServiceUser;
Guid id = new Guid(currentUser.Id);
return Query().Where(todo => todo.UserId == id);
}
Just a side note I am using UserId as Guid (uniqueidentifier) and you need to add this to the todo model definition. You can make the UserId as any type you want, e.g. Int32
Windows Phone/Store App
Please note that this is just an example and you should clean the code up in your main application once you have it working.
On your Client App
Install NuGet Package: Windows Azure Mobile Services
Go into App.xaml.cs and add this to the top
public static MobileServiceClient MobileService = new MobileServiceClient(
"http://localhost:50527/",
"[enter application key here]"
);
In the MainPage.xaml.cs I created
public class Token
{
public Guid UserId { get; set; }
public String token { get; set; }
}
In the main class add an Authenticate function
private bool Authenticate(String username, String password)
{
HttpClient client = new HttpClient();
// Enter your own localhost settings here
client.BaseAddress = new Uri("http://localhost:50527/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(String.Format("api/Account/Login?username={0}&password={1}", username, password)).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var token = Newtonsoft.Json.JsonConvert.DeserializeObject<Token>(response.Content.ReadAsStringAsync().Result);
App.MobileService.CurrentUser = new MobileServiceUser(token.UserId.ToString());
App.MobileService.CurrentUser.MobileServiceAuthenticationToken = token.token;
return true;
}
else
{
//Something has gone wrong, handle it here
return false;
}
}
Then in the Main_Loaded function
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Authenticate("test", "test");
RefreshTodoItems();
}
If you have break points in the WebAPI, you will see it come in, get the token, then come back to the ToDoItemController and the currentUser will be filled with the UserId and token.
You will need to create your own login page as with this method you can't use the automatically created one with the other identity providers. However I much prefer creating my own login screen anyway.
Any other questions let me know in the comments and I will help if I can.
Security Note
Remember to use SSL.
References
[] http://www.thejoyofcode.com/Exploring_custom_identity_in_Mobile_Services_Day_12_.aspx
[] http://www.contentmaster.com/azure/creating-a-jwt-token-to-access-windows-azure-mobile-services/
[] http://chrisrisner.com/Custom-Authentication-with-Azure-Mobile-Services-and-LensRocket
This is exactly how you do it. This man needs 10 stars and a 5 crates of beer!
One thing, I used the mobile Service LoginResult for login like:
var token = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
Hope to get this into Android now!

How can I get a VirtualMachine reference using VMware Java vSphere SDK?

I am familiar with using the VMware VIM API in C# using the VMware.Vim.dll provided in the PowerCLI. Now I want to be able to program with this API using Java, but I can't find an equivalent to it. The com.vmware.vim.jar in the vSphere SDK doesn't seem to have all of the classes that are mentioned in the API reference here:
http://www.vmware.com/support/developer/vc-sdk/
Specifically, in Java I can't figure out how to get a VirtualMachine instance. In C#, I can get all virtual machines on a stand alone hypervisor by doing the following:
String serviceUrl = "https://192.168.1.100/sdk/vimService";
String username = "root";
String password = "MyPassword";
VimClient client = new VimClient();
client.Connect(serviceUrl);
client.Login(username, password);
var virtualMachines = client.FindEntityViews(typeof(VirtualMachine), client.ServiceContent.RootFolder, null, null).OfType<VirtualMachine>();
How can I get this using Java?
Using VMware Infrastructure (vSphere) Java API i.e vijava below code works to find all VM's in inventory.
String serviceUrl = "https://Your IP Address/sdk";
String username = "root";
String password = "MyPassword";
ServiceInstance si = new ServiceInstance(new URL(serviceUrl), username , password , true);
Folder rootFolder = si.getRootFolder();
ManagedEntity[] entities = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
for (ManagedEntity e : entities) {
vm = (VirtualMachine) e;
System.out.println("vm=" + vm.getName());
}
OR
http://sourceforge.net/p/vijava/discussion/826592/thread/a6c44685#5b30 ---in cluster environment
I found that the VMware Infrastructure (vSphere) Java API can do this:
http://sourceforge.net/projects/vijava/files/vijava/

Calling SSRS Report Server it asked "Authentication Required" window

I have just started working in SSRS and I got a very strange problem i.e. When I am calling report server URL i.e. localhost/Reports
This URL requires Authentication window for Username and password. like this.
If I submitted local system user account information in that case it will appear me report server screen which we want. like this.
I have created a demo web-application and in the default.aspx page I am using ReportViewer to show report and configure it. here is the code which i am using
Default.aspx Page
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="100%">
</rsweb:ReportViewer>
Default.aspx.cs Page
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
IReportServerCredentials irsc = new CustomReportCredentials("username", "password", "India");
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/Reports");
ReportViewer1.ServerReport.ReportPath = "/SSRS_Demo/Report_CaseMain";
ReportViewer1.ServerReport.Refresh();
CustomReportCredentials.cs Class
public class CustomReportCredentials : IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord, _DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
And while i am running this web-application in that case it will gives me an error i.e.
Please help me out what will I do to resolve these all errors.....
After very long R&D I got a solution. I am using wrong SSRS service URL. I am using localhost/Reports but actually the SSRS Reporting Server URL is localhost/ReportServer. So by using this new Reporting Service URL i got the solution of that problem.
Click on your report on localhost/Reports then goto property of that report. On right hand side there is 'Data Source' click on that. Then chek the radio button 'Credentials stored securely in the report server', here you need to specify your SQL server credentials i.e. User name and password
One Time Activity: Once you click on report it will ask again the username and password first time, to overcome this follow below guidelines.
(i) Open Internet Explorer go to Setting click on Internet options
(ii) Go to Security :-> Local Intranet -> Click on Sites
(iii) Click Advanced:
(iv) Add Site: ServerIP Addr (ex.172.16.2.224 or localhost) and then Close.