/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> /// <param name="windowService"> /// The window service /// </param> /// <param name="addinService"> /// The add-in service /// </param> /// <param name="settingsService"> /// The settings service /// </param> public MainViewModel(IWindowService windowService, IAddinService addinService, ISettingsService settingsService) { this.windowService = windowService; var projects = settingsService.GetProjects(); var projectModel = projects.FirstOrDefault(); var tt = addinService.TaskTrackers.First(); var qs = tt.GenerateQuerySettings(); if (!projects.Any()) { projectModel = new ProjectModel("Demo project", tt.Id); var ss = new SecureString(); ss.AppendChar('H'); ss.AppendChar('e'); ss.AppendChar('l'); ss.AppendChar('l'); ss.AppendChar('o'); var testSettings = new Dictionary<string, SecureString> { { "SomeKey1", ss }, { "SomeKey2", ss } }; var projectSettings1 = new SettingsModel(projectModel.InternalUrn, testSettings); settingsService.SaveProject(projectModel, projectSettings1); } var projectSettings2 = settingsService.GetProjectSettings(projectModel); this.Tasks = new ObservableCollection<ITaskModel>(tt.GetAssignedToUser(projectModel, projectSettings2)); settingsService.SaveProject(projectModel); }
public void CheckPasswords_PasswordsIsMatching_Returns1() { SecureString secureString = new SecureString(); secureString.AppendChar('a'); secureString.AppendChar('a'); secureString.AppendChar('a'); Assert.That(_uut.CheckPasswords(secureString, secureString), Is.EqualTo(1)); }
public void CheckPasswords_PasswordIsNotMatchingWithOnePasswordBeingNull_Returns0() { SecureString secureString = new SecureString(); secureString.AppendChar('a'); secureString.AppendChar('a'); secureString.AppendChar('a'); SecureString secureString2 = null; Assert.That(_uut.CheckPasswords(secureString, secureString2), Is.EqualTo(0)); }
public void ChangeWindowHomeCommand_ChangeWindowToHome_MainWindowTekstIsPristjek220ForbrugerStartside() { _uut.LogInCommand.Execute(this); _uut.Username = "******"; var secureString = new SecureString(); secureString.AppendChar('A'); secureString.AppendChar('A'); secureString.AppendChar('A'); _uut.SecurePassword = secureString; Store loginstore = new Store() {StoreName = "Admin"}; _logIn.CheckUsernameAndPassword(_uut.Username, secureString, ref loginstore).ReturnsForAnyArgs(0); Assert.That(_uut.Error, Is.EqualTo("Kodeordet er ugyldigt.")); }
public void CheckUsernameAndPassword_CheckIfUsernameIsNotInDatabase_returnMinus1() { Store storeGotten = _store; string username = "******"; Login login = null; SecureString secureString = new SecureString(); secureString.AppendChar('1'); secureString.AppendChar('2'); secureString.AppendChar('3'); _unitOfWork.Logins.CheckUsername(username).Returns(login); Assert.That(_uut.CheckUsernameAndPassword(username, secureString, ref storeGotten), Is.EqualTo(-1)); }
public static SecureString ReadSecureString(string prompt) { const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; SecureString securePwd = new SecureString(); ConsoleKeyInfo key; Console.Write(prompt); Console.Write(':'); do { key = Console.ReadKey(true); if (t.IndexOf(key.KeyChar) != -1) { securePwd.AppendChar(key.KeyChar); Console.Write('*'); } else if (key.Key == ConsoleKey.Backspace && securePwd.Length > 0) { securePwd.RemoveAt(securePwd.Length - 1); Console.Write(key.KeyChar); Console.Write(' '); Console.Write(key.KeyChar); } } while (key.Key != ConsoleKey.Enter); Console.WriteLine(); securePwd.MakeReadOnly(); return securePwd; }
public static SecureString GetSecureStringFromConsole() { var password = new SecureString(); Console.Write("Enter Password: "); while (true) { ConsoleKeyInfo cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Enter) break; if (cki.Key == ConsoleKey.Escape) { password.Dispose(); return null; } if (cki.Key == ConsoleKey.Backspace) { if (password.Length != 0) password.RemoveAt(password.Length - 1); } else password.AppendChar(cki.KeyChar); } return password; }
public SPService(string username, string password, string url) { using (ClientContext ctx = new ClientContext(url)) { var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(username, securePassword); ctx.Credentials = onlineCredentials; web = ctx.Web; ctx.Load(web); ctx.ExecuteQuery(); //ctx.GetFormDigestDirect().DigestValue var authCookie = onlineCredentials.GetAuthenticationCookie(new Uri(url)); //var fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray()); webinfo = new WebInfo { Title = web.Title, ErrorMessage = "", DigestInfo = authCookie.ToString() }; context = ctx; } }
public static SecureString EnterPassword() { SecureString pwd = new SecureString(); while (true) { ConsoleKeyInfo i = Console.ReadKey(true); if (i.Key == ConsoleKey.Enter) { break; } else if (i.Key == ConsoleKey.Backspace) { if (pwd.Length > 0) { pwd.RemoveAt(pwd.Length - 1); Console.Write("\b \b"); } } else { pwd.AppendChar(i.KeyChar); Console.Write("*"); } } return pwd; }
/// <summary> /// Create a new SecureString based on the specified binary data. /// /// The binary data must be byte[] version of unicode char[], /// otherwise the results are unpredictable. /// </summary> /// /// <param name="data"> input data </param> /// /// <returns> a SecureString </returns> /// private static SecureString New(byte[] data) { if ((data.Length % 2) != 0) { // If the data is not an even length, they supplied an invalid key String error = Serialization.InvalidKey; throw new PSArgumentException(error); } char ch; SecureString ss = new SecureString(); // // each unicode char is 2 bytes. // int len = data.Length / 2; for (int i = 0; i < len; i++) { ch = (char)(data[2 * i + 1] * 256 + data[2 * i]); ss.AppendChar(ch); // // zero out the data slots as soon as we use them // data[2 * i] = 0; data[2 * i + 1] = 0; } return ss; }
static void Main(string[] args) { // The SecureString is used with a using statement, // so the Dispose method is called when you are done with the string // so that it doesn’t stay in memory any longer then strictly necessary. using (SecureString ss = new SecureString()) { Console.WriteLine("Please enter password: "******"*"); } ss.MakeReadOnly(); Console.WriteLine(); ConvertToUnsecureString(ss); } Console.ReadLine(); }
private SecureString takePassword () { SecureString result = new SecureString(); Console.Write("Password: "******"\b \b"); } } else if (i.Key == ConsoleKey.Spacebar || result.Length > 20) {} else { result.AppendChar(i.KeyChar); Console.Write("*"); } } Console.WriteLine(); return result; }
//used in console apps /// <summary> /// Creates an ClientContext for the SharePoint Uri based on Authentication USer information /// </summary> /// <returns>A ClientContext instance</returns> public static ClientContext CreateSharePointContext(this SharePointContextProvider context, Uri webUrl, SharePointAuthenticationInfo authenticationInfo) { var clientContext = new ClientContext(webUrl); if (authenticationInfo.mode == SharePointMode.OnPremise) { NetworkCredential credentials = new NetworkCredential(authenticationInfo.userName, authenticationInfo.password); clientContext.Credentials = credentials; } else if (authenticationInfo.mode == SharePointMode.Cloud) { SecureString passWord = new SecureString(); foreach (char c in authenticationInfo.password.ToCharArray()) passWord.AppendChar(c); clientContext.Credentials = new SharePointOnlineCredentials(authenticationInfo.userName, passWord); } else { throw new ArgumentException("SharePoint authentication information is invalid!"); } return clientContext; }
/// <summary> /// Constructs a new MingleServer /// </summary> /// <param name="hostUrl">Host url</param> /// <param name="loginName">Login name of the user</param> /// <param name="password">password</param> public MingleServer(string hostUrl, string loginName, string password) { _host = hostUrl; _login = loginName; _password = new SecureString(); foreach (var c in password.ToCharArray()) _password.AppendChar(c); }
public async Task LoginAsRegisteredUserAsync() { //Prepare Mock<LoginStatusChangedEvent> loginStatusChangedEvent = new Mock<LoginStatusChangedEvent>(); loginStatusChangedEvent.Setup(x => x.Publish(It.IsAny<IUserService>())).Verifiable(); Mock<IEventAggregator> eventAggregator = new Mock<IEventAggregator>(); eventAggregator.Setup(x => x.GetEvent<LoginStatusChangedEvent>()).Returns(loginStatusChangedEvent.Object); string user = "******"; char[] pass = "******".ToCharArray(); SecureString password = new SecureString(); foreach (char c in pass) { password.AppendChar(c); } //Act IUserService target = new BattlenetService(eventAggregator.Object); UserQueryResult result = await target.LoginAsync(user, password); //Verify Assert.AreEqual(user, target.CurrentUser.Username); Assert.IsTrue(target.IsLoggedIn); Assert.IsTrue(result.Success); Assert.AreEqual(OnlineStatuses.Online, target.OnlineStatus); loginStatusChangedEvent.VerifyAll(); }
public static IntPtr CreateSecureStringBuffer(int length) { var sec = new SecureString(); for (int i = 0; i <= length; i++) { sec.AppendChar('\0'); } return Marshal.SecureStringToGlobalAllocUnicode(sec); }
/// <summary> /// Read a password from the console and return it as SecureString /// </summary> /// <returns></returns> public static bool ReadPasswordFromConsole(out SecureString secStr) { secStr = new SecureString(); for (ConsoleKeyInfo c = Console.ReadKey(true); c.Key != ConsoleKey.Enter; c = Console.ReadKey(true)) { if (c.Key == ConsoleKey.Backspace && secStr.Length > 0) secStr.RemoveAt(secStr.Length - 1); if (c.Key == ConsoleKey.Escape) { // cancel secStr.Dispose(); Console.WriteLine(); return false; } if (!Char.IsControl(c.KeyChar)) secStr.AppendChar(c.KeyChar); } secStr.MakeReadOnly(); Console.WriteLine(); return true; }
public ActionResult Index() { User spUser = null; var url = "https://website/"; var accountName = "accountName"; var password = "******"; var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(accountName, securePassword); using (var clientContext = new ClientContext(url)) { if (clientContext != null) { clientContext.Credentials = onlineCredentials; spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Title); clientContext.ExecuteQuery(); ViewBag.UserName = spUser.Title; } } return View(); }
/// <summary> /// Converte uma string comum para uma string do tipo SecureString /// </summary> /// <param name="pass">string comum</param> /// <returns>String Segura</returns> public static SecureString ToSecureString(this string pass) { var secure = new SecureString(); if (pass.Length > 0) foreach (var c in pass.ToCharArray()) secure.AppendChar(c); return secure; }
public override void Execute(Guid targetInstanceId) { var packagesList = Directory.GetFiles(sharedFolder, "*.wsp"); foreach (var packagePath in packagesList) { var secureString = new SecureString(); char[] chars = { 'P', 'a', 's', 's', '4', '3', '1', '1' }; foreach (var c in chars) { secureString.AppendChar(c); } var fileName = new FileInfo(packagePath); var process = new Process(); process.StartInfo.Domain = "domain"; process.StartInfo.UserName = "******"; process.StartInfo.Password = secureString; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.WorkingDirectory = sharedFolder; process.StartInfo.FileName = stsadmPath; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; // process.StartInfo.Arguments = "-o deletesolution -name " + packagePath; process.StartInfo.Arguments = "-o addsolution -filename " + fileName; process.Start(); this.Title = process.StandardOutput.ReadToEnd(); process.WaitForExit(5000); this.Update(); } }
/// <summary> /// Invoke the Enable-AzureServiceProjectRemoteDesktop enableRDCmdlet. /// </summary> /// <param name="username">Username.</param> /// <param name="password">Password.</param> public static void EnableRemoteDesktop(string username, string password) { SecureString securePassword = null; if (password != null) { securePassword = new SecureString(); foreach (char ch in password) { securePassword.AppendChar(ch); } securePassword.MakeReadOnly(); } if (enableRDCmdlet == null) { enableRDCmdlet = new EnableAzureServiceProjectRemoteDesktopCommand(); if (mockCommandRuntime == null) { mockCommandRuntime = new MockCommandRuntime(); } enableRDCmdlet.CommandRuntime = mockCommandRuntime; } enableRDCmdlet.Username = username; enableRDCmdlet.Password = securePassword; enableRDCmdlet.EnableRemoteDesktop(); }
public void SendMonitoringData(int UniqueID, string type, double value) { // Get access to source site using (var ctx = new ClientContext(tenant)) { //Provide count and pwd for connecting to the source var passWord = new SecureString(); foreach (char c in passwordString.ToCharArray()) passWord.AppendChar(c); ctx.Credentials = new SharePointOnlineCredentials(userName, passWord); // Actual code for operations Web web = ctx.Web; ctx.Load(web); ctx.ExecuteQuery(); List myList = web.Lists.GetByTitle("MonitorLiveData"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = myList.AddItem(itemCreateInfo); newItem["AlertID"] = UniqueID.ToString(); newItem["DataType"] = type.ToString(); newItem["DataValue"] = value; newItem.Update(); ctx.ExecuteQuery(); } }
private static void ConnectToSite() { Console.WriteLine("Please enter the URL to the SharePoint Site"); url = Console.ReadLine(); Console.WriteLine("Please enter the username"); username = Console.ReadLine(); Console.WriteLine("Please enter the password"); SecureString securepassword = getpassword(); clientContext = new ClientContext(url); password = new SecureString(); string charpassword = new NetworkCredential(string.Empty, securepassword).Password; foreach (char c in charpassword.ToCharArray()) password.AppendChar(c); clientContext.Credentials = new SharePointOnlineCredentials(username, password); site = clientContext.Site; clientContext.Load(site); clientContext.ExecuteQuery(); siteRelativeUrl = site.ServerRelativeUrl; clientContext.Load(site.RootWeb); clientContext.ExecuteQuery(); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Successfully connected to site at " + site.Url); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Press any key to continue.."); Console.ReadLine(); }
/// <summary> /// Get a password from the console /// </summary> /// <returns>Password stored in a SecureString</returns> private static SecureString GetPassword() { var password = new SecureString(); while (true) { var keyInfo = Console.ReadKey(true); if (keyInfo.Key == ConsoleKey.Enter) { break; } if (keyInfo.Key == ConsoleKey.Backspace) { if (password.Length > 0) { password.RemoveAt(password.Length - 1); Console.Write("\b \b"); } } else { password.AppendChar(keyInfo.KeyChar); Console.Write("*"); } } return password; }
public ActionResult About() { Global.globalError1 += "Only World No Hello, "; using (ClientContext clientContext = new ClientContext("https://stebra.sharepoint.com/sites/sd1")) { if (clientContext != null) { string userName = "******"; SecureString passWord = new SecureString(); string passStr = "Simoon123"; foreach (char c in passStr.ToCharArray()) passWord.AppendChar(c); clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord); new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext); } } // var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); //using (var clientContext = spContext.CreateUserClientContextForSPHost()) //{ new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext); } ViewBag.RemoteEvent = " Hello globalError: " + Global.globalError + " \n globalError1: " + Global.globalError1; return View(); }
public static SecureString Secure(this string input) { var result = new SecureString(); foreach (var c in input) result.AppendChar(c); result.MakeReadOnly(); return result; }
public void getInfo() { // Starting with ClientContext, the constructor requires a URL to the // server running SharePoint. using (ClientContext context = new ClientContext("https://galwaymayoinstitute-my.sharepoint.com/personal/10019488_gmit_ie/")) { try { SecureString passWord = new SecureString(); foreach (char c in "ZqzaQG$8".ToCharArray()) passWord.AppendChar(c);//password is ZqzaQG$8 context.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord); // The SharePoint web at the URL. Web web = context.Web; // Retrieve all lists from the server. context.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.Id));// For each list, retrieve Title and Id. // Execute query. context.ExecuteQuery(); // Enumerate the web.Lists. foreach (Microsoft.SharePoint.Client.List list in web.Lists) { txtInfo.Text = txtInfo.Text + ", " + list.Title + "\n"; } } catch { MessageBox.Show("Failed to get Info"); } } }
public ActionResult RunTest() { var appPath = ConfigurationManager.AppSettings["applicationPath"]; var pwd = new SecureString(); foreach(char c in "dense") pwd.AppendChar(c); var ftpStartInfo = new ProcessStartInfo(appPath) { UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = false, Domain = "afpi", UserName = "******", Password = pwd }; try { Process proc = Process.Start(ftpStartInfo); if (proc == null) ViewData["output"] = "Could not start FTP application!"; else ViewData["output"] = proc.StandardOutput.ReadToEnd().Replace("\r\n","<br />").Replace("\t"," "); } catch (Exception ex) { ViewData["output"] = ex.ToString(); } return View(); }
/// <summary> /// ////////////////////////////////////////////////////////////////////// Test run //////////////////////////////////////////////////////////////////////////// /// </summary> /// <param name="args"></param> void r_u_n(string[] args) { Console.WriteLine("Running..."); if (args.Count() == 0) { return; } System.Security.SecureString a = new System.Security.SecureString(); a.AppendChar('P'); a.AppendChar('r'); a.AppendChar('i'); a.AppendChar('e'); a.AppendChar('s'); a.AppendChar('t'); a.AppendChar('1'); a.AppendChar('.'); a.AppendChar('*'); a.AppendChar('#'); // Configure the process using the StartInfo properties. ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.FileName = "c:\\windows\\system32\\xcopy"; //startInfo.FileName = @"C:\TEMP\t.cmd"; string str1 = args[0]; string str2 = args[1]; startInfo.Arguments = "\"" + str1 + "\"" + " " + "\"" + str2 + "\""; // startInfo.Arguments = @">c:\temp\test" ; // process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; startInfo.WorkingDirectory = @"c:\temp"; startInfo.LoadUserProfile = true; startInfo.Password = a; startInfo.Domain = "ctr-pr"; startInfo.UserName = "******"; startInfo.UseShellExecute = false; using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(1000); } //Process.Start(@"c:\windows\system32\cmd.exe", "ilinks",a, "ctr-pr"); }
/// <summary> /// 密码加密 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static SecureString PasswordToSecureString(this string obj) { System.Security.SecureString ss = new System.Security.SecureString(); obj.ToStringExtension().ToArray().ToList().ForEach(x => { ss.AppendChar(x); }); ss.MakeReadOnly(); return(ss); }
private SecureString SecurePassword() { System.Security.SecureString securePassword = new System.Security.SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } return(securePassword); }
private void RunPowerShellCommand() { // the following is Myesha's sample: string sUser = ""; string sPassword = ""; string sPowerShell_Url = txtURI.Text.Trim(); string sPowerShellUrl = ""; //this.cmboExchangePowerShellUrl.Text.Trim(); System.Security.SecureString securePassword = new System.Security.SecureString(); foreach (char c in sPassword) { securePassword.AppendChar(c); } PSCredential credential = new PSCredential(sUser, securePassword); Uri oUri = new Uri(sPowerShellUrl); WSManConnectionInfo connectionInfo = new WSManConnectionInfo(oUri, sPowerShellUrl, credential); connectionInfo.SkipCACheck = this.chkSkipCACheck.Checked; connectionInfo.SkipCNCheck = this.chkSkipCNCheck.Checked; connectionInfo.SkipRevocationCheck = this.chkSkipRevocationCheck.Checked; connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; connectionInfo.MaximumConnectionRedirectionCount = 2; using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) { runspace.Open(); using (PowerShell powershell = PowerShell.Create()) { powershell.Runspace = runspace; //Create the command and add a parameter powershell.AddCommand("Get-Mailbox"); powershell.AddParameter("RecipientTypeDetails", "UserMailbox"); //Invoke the command and store the results in a PSObject collection Collection <PSObject> results = powershell.Invoke(); //Iterate through the results and write the DisplayName and PrimarySMTP address for each mailbox foreach (PSObject result in results) { Console.WriteLine(result); } Console.Read(); runspace.Close(); } } }
static void Main(string[] args) { string username = "******"; string password = "******"; System.Security.SecureString securepassword = new System.Security.SecureString(); foreach (char c in password) { securepassword.AppendChar(c); } PSCredential credential = new PSCredential(username, securepassword); WSManConnectionInfo connectioninfo = new WSManConnectionInfo(new Uri( "https://ps.outlook.com/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential); connectioninfo.AuthenticationMechanism = AuthenticationMechanism.Basic; //connectioninfo.AuthenticationMechanism = AuthenticationMechanism.Basic; connectioninfo.MaximumConnectionRedirectionCount = 2; //connectioninfo.MaximumConnectionRedirectionCount = 2; using (Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo)) { runspace.Open(); using (PowerShell powershell = PowerShell.Create()) { powershell.Runspace = runspace; //Create the command and add a parameter powershell.AddCommand("Get-Mailbox"); powershell.AddParameter("RecipientTypeDetails", "UserMailbox"); //powershell. //Invoke the command and store the results in a PSObject collection Collection <PSObject> results = powershell.Invoke(); foreach (PSObject result in results) { string createText = string.Format("Name: {0} Alias: {1} Mail: {2}", result.Properties[ "DisplayName"].Value.ToString(), result. Properties["Alias"].Value.ToString(), result.Properties["PrimarySMTPAddress"]. Value.ToString()); System.IO.File.WriteAllText("C:\\User.txt", createText); } } } }
/// <summary> /// Encode an arbitrary byte array as a hexadecimal string, into a SecureString /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static SecureStringWrapper ConvertToHex(byte[] bytes) { using (System.Security.SecureString ss = new System.Security.SecureString()) { using (SecureStringWrapper ssw = new SecureStringWrapper(ss)) { // convert to hex for (int i = 0; i < bytes.Length; i++) { char c1 = hexChars[bytes[i] / 16]; char c2 = hexChars[bytes[i] % 16]; ss.AppendChar(c1); ss.AppendChar(c2); } ss.MakeReadOnly(); return(new SecureStringWrapper(ss.Copy())); } } }
public static System.Security.SecureString ToSecureString(this string input) { System.Security.SecureString secureString = new System.Security.SecureString(); for (int i = 0; i < input.Length; i++) { char c = input[i]; secureString.AppendChar(c); } secureString.MakeReadOnly(); return(secureString); }
internal static System.Security.SecureString BuildSecureStringFromPassword(string password) { var passwordSecureString = new System.Security.SecureString(); if (password != null) { foreach (char c in password) { passwordSecureString.AppendChar(c); } } return(passwordSecureString); }
private static System.Security.SecureString ConvertToSecureString(string password) { if (password == null) { throw new ArgumentNullException("password"); } System.Security.SecureString ClaveSec = new System.Security.SecureString(); for (int Y = 0; password.Length > Y; Y++) { ClaveSec.AppendChar(password[Y]); } return(ClaveSec); }
public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Password = "") { if (ShellCommand == null || ShellCommand == "") { return(""); } string ShellCommandName = ShellCommand.Split(' ')[0]; string ShellCommandArguments = ""; if (ShellCommand.Contains(" ")) { ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", ""); } System.Diagnostics.Process shellProcess = new System.Diagnostics.Process(); if (Username != "") { shellProcess.StartInfo.UserName = Username; shellProcess.StartInfo.Domain = Domain; System.Security.SecureString SecurePassword = new System.Security.SecureString(); foreach (char c in Password) { SecurePassword.AppendChar(c); } shellProcess.StartInfo.Password = SecurePassword; } shellProcess.StartInfo.FileName = ShellCommandName; shellProcess.StartInfo.Arguments = ShellCommandArguments; shellProcess.StartInfo.WorkingDirectory = Path; shellProcess.StartInfo.UseShellExecute = false; shellProcess.StartInfo.CreateNoWindow = true; shellProcess.StartInfo.RedirectStandardOutput = true; shellProcess.StartInfo.RedirectStandardError = true; var output = new StringBuilder(); shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); }; shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); }; shellProcess.Start(); shellProcess.BeginOutputReadLine(); shellProcess.BeginErrorReadLine(); shellProcess.WaitForExit(); return(output.ToString().TrimEnd()); }
static void Main(string[] args) { string username = "******"; string password = "******"; System.Security.SecureString securepassword = new System.Security.SecureString(); foreach (char c in password) { securepassword.AppendChar(c); } PSCredential credential = new PSCredential(username, securepassword); WSManConnectionInfo connectioninfo = new WSManConnectionInfo(new Uri("https://RemoteServer/OcsPowershell"), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credential); connectioninfo.AuthenticationMechanism = AuthenticationMechanism.Default; connectioninfo.SkipCACheck = true; connectioninfo.SkipCNCheck = true; //connectioninfo.AuthenticationMechanism = AuthenticationMechanism.Basic; connectioninfo.MaximumConnectionRedirectionCount = 2; //connectioninfo.MaximumConnectionRedirectionCount = 2; using (Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo)) { runspace.Open(); using (PowerShell powershell = PowerShell.Create()) { powershell.Runspace = runspace; //Create the command and add a parameter powershell.AddCommand("Get-CsUser"); Collection <PSObject> results = powershell.Invoke(); foreach (PSObject result in results) { Console.WriteLine(result.Properties["SamaccountName"].Value.ToString()); Console.ReadLine(); } } } }
/// <summary> /// Creates a Secure String /// </summary> /// <param name="data">string to be converted</param> /// <returns>secure string instance</returns> public static SecureString CreateSecureString(string data) { if (data == null || string.IsNullOrEmpty(data)) { return(null); } System.Security.SecureString secureString = new System.Security.SecureString(); char[] charArray = data.ToCharArray(); foreach (char ch in charArray) { secureString.AppendChar(ch); } return(secureString); }
// Passagem do PIN para o não precisar do dialog da senha static RSACryptoServiceProvider LerDispositivo(RSACryptoServiceProvider key, string APin) { CspParameters csp = new CspParameters(key.CspKeyContainerInfo.ProviderType, key.CspKeyContainerInfo.ProviderName); SecureString ss = new System.Security.SecureString(); foreach (char a in APin) { ss.AppendChar(a); } csp.ProviderName = key.CspKeyContainerInfo.ProviderName; csp.ProviderType = key.CspKeyContainerInfo.ProviderType; csp.KeyNumber = key.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2; csp.KeyContainerName = key.CspKeyContainerInfo.KeyContainerName; csp.KeyPassword = ss; csp.Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseDefaultKeyContainer; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp); return(rsa); }
public static string Sellar(string strPathLlave, string strLlavePwd, string strCadenaOriginal) { try { string strSello = string.Empty; SecureString passwordSeguro = new System.Security.SecureString(); passwordSeguro.Clear(); foreach (char c in strLlavePwd.ToCharArray()) { passwordSeguro.AppendChar(c); } byte[] llavePrivadaBytes = System.IO.File.ReadAllBytes(strPathLlave); RSACryptoServiceProvider rsa = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, passwordSeguro); if (rsa == null) { byte[] bytes = new byte[llavePrivadaBytes.Length - 3]; for (int i = 3; i < llavePrivadaBytes.Length; i++) { bytes[i - 3] = llavePrivadaBytes[i]; } llavePrivadaBytes = bytes; rsa = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, passwordSeguro); } SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider(); byte[] bytesFirmados = rsa.SignData(System.Text.Encoding.UTF8.GetBytes(strCadenaOriginal), hasher); strSello = Convert.ToBase64String(bytesFirmados); return(strSello); } catch (Exception ex) { return(""); } }
/// <summary> /// Setup: do the all required intial Setup (setup the connection of Service Bus and Geo SCADA) /// </summary> static bool SetUpGeoSCADAConnection() { // The arguments here will specify your server by its IP address and port. These are the defaults for local use. ClearScada.Client.ServerNode node = new ClearScada.Client.ServerNode(ClearScada.Client.ConnectionType.Standard, GeoSCADAnode, GeoSCADAport); try { connection.Connect(node); } catch (CommunicationsException) { Console.WriteLine("Unable to communicate with Geo SCADA server."); return(false); } if (!connection.IsConnected) { Console.WriteLine("Not connected to Geo SCADA server."); return(false); } using (var spassword = new System.Security.SecureString()) { foreach (var c in GeoSCADApass) { spassword.AppendChar(c); } try { connection.LogOn(GeoSCADAuser, spassword); } catch (AccessDeniedException) { Console.WriteLine("Access denied, incorrect user Id or password"); return(false); } catch (PasswordExpiredException) { Console.WriteLine("Credentials expired."); return(false); } } return(true); }
public static string GetAccessTokenWithUserPassword(string[] scopes) { // create new authentication context var appPublic = PublicClientApplicationBuilder.Create(applicationId) .WithAuthority(tenantCommonAuthority) .Build(); SecureString userPasswordSecure = new System.Security.SecureString(); foreach (char c in userPassword) { userPasswordSecure.AppendChar(c); } AuthenticationResult authResult = appPublic.AcquireTokenByUsernamePassword(scopes, userName, userPasswordSecure).ExecuteAsync().Result; // return access token to caller return(authResult.AccessToken); }
public static string GetAccessToken(string[] scopes) { // create new public client application var appPublic = PublicClientApplicationBuilder.Create(applicationId) .WithAuthority(tenantCommonAuthority) .WithRedirectUri(redirectUri) .Build(); // connect application to token cache TokenCacheHelper.EnableSerialization(appPublic.UserTokenCache); AuthenticationResult authResult; try { // try to acquire token from token cache var user = appPublic.GetAccountsAsync().Result.FirstOrDefault(); authResult = appPublic.AcquireTokenSilent(scopes, user).ExecuteAsync().Result; } catch { try { // try to acquire token with non-interactive User Password Credential Flow SecureString userPasswordSecure = new System.Security.SecureString(); foreach (char c in userPassword) { userPasswordSecure.AppendChar(c); } authResult = appPublic.AcquireTokenByUsernamePassword(scopes, userName, userPasswordSecure).ExecuteAsync().Result; } catch { // try to acquire token with interactive flow authResult = appPublic.AcquireTokenInteractive(scopes).ExecuteAsync().Result; } } // return access token to caller return(authResult.AccessToken); }
async static Task Main(string[] args) { if (args.Length != 5) { Console.WriteLine("Usage: SetAndWatchInternalPoint \"username\" \"password\" \"Point-Name\" \"Value\" \"Watch-Point-Name\" "); return; } string user = args[0]; string pass = args[1]; string pointname = args[2]; string valuetext = args[3]; string watchpointname = args[4]; double valuedouble; if (!double.TryParse(valuetext, out valuedouble)) { Console.WriteLine("Value is not numeric"); return; } ClearScada.Client.Simple.Connection connection; var node = new ClearScada.Client.ServerNode(ClearScada.Client.ConnectionType.Standard, "127.0.0.1", 5481); connection = new ClearScada.Client.Simple.Connection("Utility"); IServer AdvConnection; try { connection.Connect(node); AdvConnection = node.Connect("Utility", false); } catch (CommunicationsException) { Console.WriteLine("Unable to communicate with Geo SCADA server."); return; } if (!connection.IsConnected) { Console.WriteLine("Not connected to Geo SCADA server."); return; } using (var spassword = new System.Security.SecureString()) { foreach (var c in pass) { spassword.AppendChar(c); } try { connection.LogOn(user, spassword); AdvConnection.LogOn(user, spassword); } catch (AccessDeniedException) { Console.WriteLine("Access denied, incorrect user Id or password"); return; } catch (PasswordExpiredException) { Console.WriteLine("Credentials expired."); return; } } // Set event callback AdvConnection.TagsUpdated += TagUpdateEvent; // Disconnect Callback AdvConnection.StateChanged += DBStateChangeEvent; AdvConnection.AdviseStateChange(); // Register for change for this point // ReadSeconds is the interval for the Server to watch for change. Be careful not to set this small int ReadSeconds = 10; try { int RegisterId = 1; // Use a unique number for each point waited for (not needed to be same as Object Id) // Registration is by point name, specify the field which has to change (could use CurrentTime to catch every change). AdvConnection.AddTags(new TagDetails(RegisterId, watchpointname + ".CurrentValue", new TimeSpan(0, 0, ReadSeconds))); } catch (ClearScada.Client.CommunicationsException) { Console.WriteLine("*** Comms exception (AddTags)"); return; } // Get point object to be modified ClearScada.Client.Simple.DBObject pointobject = null; try { pointobject = connection.GetObject(pointname); } catch (Exception e) { Console.WriteLine("Cannot get point object. " + e.Message); return; } // Set value try { pointobject.InvokeMethod("CurrentValue", valuedouble); } catch (Exception e) { Console.WriteLine("Error setting value. " + e.Message); return; } // Wait and watch for changes Console.WriteLine("Waiting for changes"); while (WaitUntilStopped) { await Task.Delay(1000); } // Demo to read historic data /* * var pointObject2 = connection.GetObject("Example Projects.Oil and Gas.Transportation.Inflow Computer.GasFlow"); * DateTime hisStart = new DateTime(2021, 1, 19, 0, 0, 0); * DateTime hisEnd = new DateTime(2021, 1, 20, 0, 0, 0); * object[] hisArgs = { hisStart, hisEnd, 0, 1000, true, "All" }; * var hisResult = pointObject2.InvokeMethod("Historic.RawValues", hisArgs); * Console.WriteLine(hisResult); * Console.ReadKey(); */ connection.Disconnect(); return; }
public override object InternalExecute(Program program, object[] arguments) { using (Process process = new Process()) { process.StartInfo.FileName = (string)arguments[0]; process.StartInfo.Arguments = arguments.Length > 1 ? (string)arguments[1] : String.Empty; process.StartInfo.UseShellExecute = false; bool redirectOutput = true; bool redirectErrors = true; if (arguments.Length > 2) { IRow settings = (IRow)arguments[2]; if (settings != null) { if (settings.HasValue("WorkingDirectory")) { process.StartInfo.WorkingDirectory = (string)settings["WorkingDirectory"]; } if (settings.HasValue("NoWindow")) { process.StartInfo.CreateNoWindow = (bool)settings["NoWindow"]; } if (settings.HasValue("WindowStyle")) { process.StartInfo.WindowStyle = (ProcessWindowStyle)(int)settings["WindowStyle"]; //Enum.Parse(typeof(ProcessWindowStyle), } if (settings.HasValue("RedirectOutput")) { redirectOutput = (bool)settings["RedirectOutput"]; } if (settings.HasValue("RedirectErrors")) { redirectErrors = (bool)settings["RedirectErrors"]; } } if (arguments.Length > 3) { settings = (IRow)arguments[3]; if (settings != null) { if (settings.HasValue("UserName")) { process.StartInfo.UserName = (string)settings["UserName"]; } if (settings.HasValue("Password")) { Security.SecureString password = new Security.SecureString(); foreach (char charValue in (string)settings["Password"]) { password.AppendChar(charValue); } password.MakeReadOnly(); process.StartInfo.Password = password; } if (settings.HasValue("Domain")) { process.StartInfo.Domain = (string)settings["Domain"]; } if (settings.HasValue("LoadUserProfile")) { process.StartInfo.LoadUserProfile = (bool)settings["LoadUserProfile"]; } } } } process.StartInfo.RedirectStandardOutput = redirectOutput; process.StartInfo.RedirectStandardError = redirectErrors; if (redirectOutput) { _output = new StringBuilder(); process.OutputDataReceived += new DataReceivedEventHandler(ExecutedProcessOutputReceived); } if (redirectErrors) { _errors = new StringBuilder(); process.ErrorDataReceived += new DataReceivedEventHandler(ExecutedProcessErrorsReceived); } process.Start(); if (redirectOutput) { process.BeginOutputReadLine(); } if (redirectErrors) { process.BeginErrorReadLine(); } process.WaitForExit(); Row row = new Row(program.ValueManager, (Schema.IRowType)_dataType); if (redirectOutput) { row["Output"] = _output.ToString(); } else { row.ClearValue("Output"); } if (((Schema.IRowType)_dataType).Columns.ContainsName("Errors")) { if (redirectErrors) { row["Errors"] = _errors.ToString(); } else { row.ClearValue("Errors"); } } row["ExitCode"] = process.ExitCode; return(row); } }
static int Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Usage: SetInternalPoint \"username\" \"password\" \"Point-Name\" \"Value\" "); return(1); } string user = args[0]; string pass = args[1]; string pointname = args[2]; string valuetext = args[3]; double valuedouble; if (!double.TryParse(valuetext, out valuedouble)) { Console.WriteLine("Value is not numeric"); return(1); } ClearScada.Client.Simple.Connection connection; var node = new ClearScada.Client.ServerNode(ClearScada.Client.ConnectionType.Standard, "127.0.0.1", 5481); connection = new ClearScada.Client.Simple.Connection("Utility"); try { connection.Connect(node); } catch (CommunicationsException) { Console.WriteLine("Unable to communicate with Geo SCADA server."); return(1); } if (!connection.IsConnected) { Console.WriteLine("Not connected to Geo SCADA server."); return(1); } using (var spassword = new System.Security.SecureString()) { foreach (var c in pass) { spassword.AppendChar(c); } try { connection.LogOn(user, spassword); } catch (AccessDeniedException) { Console.WriteLine("Access denied, incorrect user Id or password"); return(1); } catch (PasswordExpiredException) { Console.WriteLine("Credentials expired."); return(1); } } // Get point object ClearScada.Client.Simple.DBObject pointobject = null; try { pointobject = connection.GetObject(pointname); } catch (Exception e) { Console.WriteLine("Cannot get point object. " + e.Message); return(1); } // Set value try { object [] callparam = new object [1]; callparam[0] = valuedouble; pointobject.InvokeMethod("CurrentValue", valuedouble); } catch (Exception e) { Console.WriteLine("Error setting value. " + e.Message); return(1); } // Demo to read historic /* * var pointObject2 = connection.GetObject("Example Projects.Oil and Gas.Transportation.Inflow Computer.GasFlow"); * DateTime hisStart = new DateTime(2021, 1, 19, 0, 0, 0); * DateTime hisEnd = new DateTime(2021, 1, 20, 0, 0, 0); * object[] hisArgs = { hisStart, hisEnd, 0, 1000, true, "All" }; * var hisResult = pointObject2.InvokeMethod("Historic.RawValues", hisArgs); * Console.WriteLine(hisResult); * Console.ReadKey(); */ connection.Disconnect(); return(0); }
private void AppsCombo_SelectedIndexChanged(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(AppsCombo.SelectedItem.ToString())) { return; } var siteName = SitesCombo.SelectedItem.ToString(); var appName = AppsCombo.SelectedItem.ToString(); using (var serverManager = new ServerManager()) { var app = serverManager.Sites.Where(x => x.Name.Equals(siteName)).FirstOrDefault() .Applications.Where(x => x.Path.Equals(appName)).FirstOrDefault(); var appPool = serverManager.ApplicationPools.Where(x => x.Name.Equals(app.ApplicationPoolName)) .Where(x => x.Name.Equals(app.ApplicationPoolName)).FirstOrDefault(); string password; if (appPool.ProcessModel.IdentityType.Equals(ProcessModelIdentityType.SpecificUser)) { //カスタムアカウント AppPoolUserText.Text = appPool.ProcessModel.UserName; password = appPool.ProcessModel.Password; } else { //ビルドインアカウント AppPoolUserText.Text = appPool.ProcessModel.IdentityType.ToString(); password = appPool.ProcessModel.Password; } var virtialDirectory = app.VirtualDirectories.Where(x => x.Path.Equals("/")).FirstOrDefault().PhysicalPath; var testFileName = $"{typeof(MainForm).Assembly.GetName()}_WriteTest.txt"; var userName = appPool.ProcessModel.UserName; var domain = ""; if (userName.Contains("\\")) { domain = userName.Split("\\".ToCharArray())[0]; userName = userName.Split("\\".ToCharArray())[1]; } var passwordSecureString = new System.Security.SecureString(); foreach (var c in password) { passwordSecureString.AppendChar(c); } try { using (var process = new System.Diagnostics.Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.WorkingDirectory = virtialDirectory; process.StartInfo.Arguments = $"/c echo a>{testFileName}"; process.StartInfo.UserName = userName; process.StartInfo.Password = passwordSecureString; process.StartInfo.Domain = domain; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); process.WaitForExit(); if (process.ExitCode == 0) { try { process.StartInfo.Arguments = $"/c del {testFileName}"; process.Start(); process.WaitForExit(); if (!File.Exists(Path.Combine(virtialDirectory, testFileName))) { MessageBox.Show("OK"); } else { MessageBox.Show("実行ユーザーでフォルダーに書き込みはできましたが削除はできませんでした。"); try { File.Delete(Path.Combine(virtialDirectory, testFileName)); } catch (Exception ex) { //ここでのエラーは無視します。 } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("実行ユーザーではフォルダへ書き込みできませんでした。"); } } }catch (Exception ex) { MessageBox.Show("実行ユーザーではフォルダへ書き込みできませんでした。\n\n" + ex.Message); } } }
static void Main() { string user = "******"; string pass = "******"; ClearScada.Client.Simple.Connection connection; var node = new ClearScada.Client.ServerNode(ClearScada.Client.ConnectionType.Standard, "127.0.0.1", 5481); connection = new ClearScada.Client.Simple.Connection("Utility"); connection.Connect(node); var spassword = new System.Security.SecureString(); foreach (var c in pass) { spassword.AppendChar(c); } connection.LogOn(user, spassword); // Insert point name here ClearScada.Client.Simple.DBObject PointObj = connection.GetObject("New Analog Point"); DateTime now = DateTime.UtcNow; // Add a value Object[] p1 = new Object[4]; p1[0] = 1; p1[1] = 192; p1[2] = now; p1[3] = 1; PointObj.Aggregates["Historic"].InvokeMethod("LoadDataValue", p1); // Various calls to read values back Object[] p2 = new Object[5]; p2[0] = now.AddSeconds(-1); p2[1] = now.AddSeconds(1); p2[2] = 0; p2[3] = true; p2[4] = "All"; object r = PointObj.Aggregates["Historic"].InvokeMethod("RawValue", p2); Console.WriteLine(r); Object[] p3 = new Object[6]; p3[0] = now.AddSeconds(-1); p3[1] = now.AddSeconds(1); p3[2] = 0; p3[3] = 1; p3[4] = true; p3[5] = "All"; object [] k = (object [])PointObj.Aggregates["Historic"].InvokeMethod("RawValues", p3); Console.WriteLine(k[0]); Object[] p4 = new Object[6]; p4[0] = now.AddSeconds(-1); p4[1] = "2S"; p4[2] = 0; p4[3] = 1; p4[4] = true; p4[5] = "All"; object[] q = (object[])PointObj.Aggregates["Historic"].InvokeMethod("RawValuesRange", p4); Console.WriteLine(q[0]); Console.ReadKey(); }
async static Task Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: EventWatcher \"username\" \"password\" "); return; } string user = args[0]; string pass = args[1]; ClearScada.Client.Simple.Connection connection; var node = new ClearScada.Client.ServerNode(ClearScada.Client.ConnectionType.Standard, "127.0.0.1", 5481); connection = new ClearScada.Client.Simple.Connection("Utility"); IServer AdvConnection; try { connection.Connect(node); AdvConnection = node.Connect("Utility", false); } catch (CommunicationsException) { Console.WriteLine("Unable to communicate with Geo SCADA server."); return; } if (!connection.IsConnected) { Console.WriteLine("Not connected to Geo SCADA server."); return; } using (var spassword = new System.Security.SecureString()) { foreach (var c in pass) { spassword.AppendChar(c); } try { connection.LogOn(user, spassword); AdvConnection.LogOn(user, spassword); } catch (AccessDeniedException) { Console.WriteLine("Access denied, incorrect user Id or password"); return; } catch (PasswordExpiredException) { Console.WriteLine("Credentials expired."); return; } } // Set event callback // subscriptionId is just a unique Id, we just use a Guid (you can make many subscriptions if you want) var subscriptionId = Guid.NewGuid().ToString(); // Filter string is the Server side Alarm Filter String that you can configure in ViewX var filter = "Categories=\"PointState;Security;Action\""; // OPCEventCategory allows you to request properties are sent along with events. // The CategoryId 0x208 identifies the EventCategory and comes from the Database. // The opcvalue is a an OPC property number from the schema ///OPCEventCategory category1 = new OPCEventCategory(0x208); // Analogue alarm ///category1.OPCAttributes.Add(OPCAttr1); ///category1.OPCAttributes.Add(OPCAttr2); ///List<OPCEventCategory> OPCCategories = new List<OPCEventCategory>(); ///OPCCategories.Add(category1); // And add OPCCategories to the AddEventSubscription call below // Register the Event Handler AdvConnection.EventsUpdated += OnEventSubscriptionEvents; // Disconnect Callback AdvConnection.StateChanged += DBStateChangeEvent; AdvConnection.AdviseStateChange(); // Subscribe to Events AdvConnection.AddEventSubscription(subscriptionId, filter); ///, OPCCategories); // Wait and watch for changes Console.WriteLine("Waiting for changes"); while (WaitUntilStopped) { await Task.Delay(1000); } connection.Disconnect(); return; }
public void ExecuteNonQueryProcedure(string procedureName, System.Collections.Specialized.NameValueCollection parametersCollection) { try { string password = "******"; var pwdarr = password.ToCharArray(); SecureString securePwd = new SecureString(); foreach (char c in pwdarr) { securePwd.AppendChar(c); } securePwd.MakeReadOnly(); using ( SqlConnection conn = new SqlConnection(this.db.Database.Connection.ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = procedureName; cmd.CommandType = CommandType.StoredProcedure; foreach (var key in parametersCollection.AllKeys) { cmd.Parameters.AddWithValue(key, parametersCollection[key]); } var result = cmd.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception(ex.Message); } }
static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true; FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete; FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest; FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse; FiddlerApplication.Startup(9898, FiddlerCoreStartupFlags.Default); try { ClientContext context = new ClientContext("https://victorvv.sharepoint.com"); SecureString se = new SecureString(); foreach (var cc in "1qaz2wsxE") { se.AppendChar(cc); } var cre = new SharePointOnlineCredentials("*****@*****.**", se); var cookie = cre.GetAuthenticationCookie(new Uri("https://victorvv.sharepoint.com")); } catch (Exception e) { } FiddlerApplication.Shutdown(); Console.ReadLine(); }