public TextManager(Map map) { _log = Logging.LogManager.GetLogger(this); _log.Info("TextManager is loading map text entries..."); _texts = new List<Text>(); _activeText = null; if (!map.HasLayer("text")) { _log.Info("No text layer detected on map, aborting..."); return; } foreach (var obj in map.FindObjects((l, o) => l.Name == "text")) { string title = obj.Properties.ContainsKey("title") ? obj.Properties["title"] : "<No Title>"; string subtitle = obj.Properties.ContainsKey("subtitle") ? obj.Properties["subtitle"] : null; _log.DebugFormat("Adding new text {0} of type {1}", obj.Name, obj.Type); _texts.Add(new Text(obj.Bounds, obj.Name, obj.Type, title, subtitle)); } _log.Debug("TextManager initialized!"); }
internal Song(string file, string name, float volume = 1.0f, bool loop = true, uint loopPoint = 0) { _log = Logging.LogManager.GetLogger(this); _file = file; _name = name; _volume = volume; _loop = loop; _loopPoint = loopPoint; _log.DebugFormat("New song {0} created: {1}", Name, FileName); }
internal SoundManager(FMOD.System system, bool hardware = true) { _log = Logging.LogManager.GetLogger(this); _log.Info("Initializing SoundManager..."); _system = system; _sounds = new List<Sound>(); _soundMode = hardware ? MODE.HARDWARE : MODE.SOFTWARE; _log.DebugFormat("Sound Mode == {0}", _soundMode); _log.Debug("SoundManager initialized!"); }
internal SongManager(FMOD.System system, bool hardware = true) { _log = Logging.LogManager.GetLogger(this); _log.Info("Initializing SongManager..."); _system = system; _songs = new List<Song>(); // ReSharper disable BitwiseOperatorOnEnumWihtoutFlags if (hardware) _soundMode = MODE._2D | MODE.HARDWARE | MODE.CREATESTREAM; else _soundMode = MODE._2D | MODE.SOFTWARE | MODE.CREATESTREAM; // ReSharper restore BitwiseOperatorOnEnumWihtoutFlags _log.DebugFormat("Sound Mode == {0}", _soundMode); _log.Debug("SongManager initialized!"); }
private void buttonAuthorize_Click(object sender, EventArgs e) { try { Exception delegateException = null; log.Debug("Testing logging in with the new credentials"); DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection, Messages.AUTHORIZING_USER, Messages.CREDENTIALS_CHECKING, Messages.CREDENTIALS_CHECK_COMPLETE, delegate { try { elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text); } catch (Exception ex) { delegateException = ex; } }); using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false)) dlg.ShowDialog(this); // The exception would have been handled by the action progress dialog, just return the user to the sudo dialog if (loginAction.Exception != null) { return; } if (HandledAnyDelegateException(delegateException)) { return; } if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession)) { elevatedUsername = TextBoxUsername.Text.Trim(); elevatedPassword = TextBoxPassword.Text; DialogResult = DialogResult.OK; Close(); return; } ShowNotAuthorisedDialog(); } catch (Exception ex) { log.DebugFormat("Exception when attempting to sudo action: {0} ", ex); using (var dlg = new ErrorDialog(string.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text))) dlg.ShowDialog(Parent); TextBoxPassword.Focus(); TextBoxPassword.SelectAll(); } finally { // Check whether we have a successful elevated session and whether we have been asked to log it out // If non successful (most likely the new subject is not authorized) then log it out anyway. if (elevatedSession != null && DialogResult != DialogResult.OK) { elevatedSession.Connection.Logout(elevatedSession); elevatedSession = null; } } }
/// <summary> /// Logs the debug message. /// </summary> /// <param name="format">The format.</param> /// <param name="arg0">The arg0.</param> public static void DebugFormat(string format, object arg0) { m_Log.DebugFormat(format, arg0); }
protected override void Run() { log.Debug("Running SR.Introduce"); log.DebugFormat("SR uuid='{0}'", _srUuid); log.DebugFormat("name='{0}'", _srName); log.DebugFormat("description='{0}'", _srDescription); log.DebugFormat("type='{0}'", _srType); log.DebugFormat("content type='{0}'", _srContentType); log.DebugFormat("is shared='{0}'", _srIsShared); Description = Messages.ACTION_SR_ATTACHING; // If SR is already attached, forget it (it may be in a broken invisible state with no PBDs) try { log.Debug("Performing preemptive SR.forget()"); RelatedTask = XenAPI.SR.async_forget(this.Session, XenAPI.SR.get_by_uuid(this.Session, _srUuid).opaque_ref); PollToCompletion(0, 5); } catch (Failure) { // Allow failure } // Introduce the existing SR RelatedTask = XenAPI.SR.async_introduce(this.Session, _srUuid, _srName, _srDescription, _srType.ToString(), _srContentType, _srIsShared, new Dictionary <string, string>()); PollToCompletion(5, 10); // cache result, in order to reassign it later string introducedSr = Result; // Now repair the SR with new PBDs for each host in the pool XenAPI.PBD pbdTemplate = new PBD(); pbdTemplate.currently_attached = false; pbdTemplate.device_config = _dconf; pbdTemplate.SR = new XenRef <SR>(Result); int delta = 90 / Connection.Cache.HostCount / 2; List <Host> _listHost = new List <Host>(Connection.Cache.Hosts); Util.masterFirst(_listHost); foreach (Host host in _listHost) { // Create the PBD log.DebugFormat("Creating PBD for host {0}", host.Name); this.Description = string.Format(Messages.ACTION_SR_REPAIR_CREATE_PBD, Helpers.GetName(host)); pbdTemplate.host = new XenRef <Host>(host.opaque_ref); RelatedTask = PBD.async_create(this.Session, pbdTemplate); PollToCompletion(PercentComplete, PercentComplete + delta); XenRef <PBD> pbdRef = new XenRef <PBD>(this.Result); // Now plug the PBD log.DebugFormat("Plugging PBD for host {0}", host.Name); this.Description = string.Format(Messages.ACTION_SR_REPAIR_PLUGGING_PBD, Helpers.GetName(host)); RelatedTask = XenAPI.PBD.async_plug(this.Session, pbdRef); PollToCompletion(PercentComplete, PercentComplete + delta); } // reassign result Result = introducedSr; if (isFirstSharedNonISOSR()) { SR new_sr = Connection.WaitForCache(new XenRef <SR>(Result), GetCancelling); if (Cancelling) { throw new CancelledException(); } if (new_sr == null) { throw new Failure(Failure.HANDLE_INVALID, "SR", Result); } // Set this SR to be the default new SrAction(SrActionKind.SetAsDefault, new_sr).RunExternal(Session); } Description = Messages.ACTION_SR_ATTACH_SUCCESSFUL; }
/// <summary> /// Initializes a new instance of the <see cref="BaseGriddedCatchmentObjectiveEvaluator"/> class. /// </summary> /// <param name="globalDefinitionFileInfo">The global definition file info.</param> /// <param name="objectivesDefinitionFileInfo">The objectives definition file info.</param> /// <param name="rank">The rank of the process in the 'world'</param> /// <param name="size">World communicator size</param> /// <param name="worldCommunicator">The world communicator</param> protected BaseGriddedCatchmentObjectiveEvaluator(FileInfo globalDefinitionFileInfo, FileInfo objectivesDefinitionFileInfo, int rank, int size, IIntracommunicatorProxy worldCommunicator) { // funny smell: WorldRank and rank are the same thing, always. Should remove one. this.rank = rank; this.size = size; WorldRank = GetWorldRank(); IsFirstRun = true; if (IsMaster && GetWorldSize() < 2) { throw new ConfigurationException("At least 2 MPI processes are required to run this application."); } ObjectiveDefinitionFileName = objectivesDefinitionFileInfo.FullName; Log.DebugFormat("Rank {0}: Loading global definition", WorldRank); //Added by Bill Wang on 27/10/2014 to read split catchment-based calibration definition files if (globalDefinitionFileInfo.FullName.EndsWith(".csv", true, null)) { StreamReader sr = null; GlobalDefinition = new GlobalDefinition(); try { sr = new StreamReader(globalDefinitionFileInfo.FullName); sr.ReadLine(); //skip the header line for (string line = sr.ReadLine(); line != null; line = sr.ReadLine()) { FileInfo catchmentFileInfo = new FileInfo(line.Split(new char[] { ',' })[1]); GlobalDefinition catchmentDef = SerializationHelper.XmlDeserialize <GlobalDefinition>(catchmentFileInfo); foreach (var cat in catchmentDef.Catchments) { GlobalDefinition.AddCatchment(cat); } } } catch (Exception e) { Log.Error(e.ToString()); throw e; } finally { if (sr != null) { sr.Close(); } } } else { GlobalDefinition = SerializationHelper.XmlDeserialize <GlobalDefinition>(globalDefinitionFileInfo); } Log.DebugFormat("Rank {0}: global definition complete", WorldRank); world = worldCommunicator; }
protected override void Run() { Status = ReportStatus.compiling; string hostname = Helpers.GetName(host); hostname = TarSanitization.SanitizeTarPathMember(hostname); if (hostname.Length > 20) { hostname = hostname.Truncate(20); } string filename = string.Format("{1}\\{2}-bugtool-{0}.tar", hostname, filePath, timeString); string entries_string = string.Join(",", capabilityKeys); log.DebugFormat("Getting system status for {0} on {1}", entries_string, hostname); try { if (Session == null) { throw new Exception(Messages.CONNECTION_IO_EXCEPTION); } HTTPHelper.Get(this, false, dataRxDelegate, filename, host.address, (HTTP_actions.get_ssss)HTTP_actions.get_system_status, Session.opaque_ref, entries_string, "tar"); log.DebugFormat("Getting system status from {0} successful", hostname); Status = ReportStatus.succeeded; Description = Messages.COMPLETED; PercentComplete = 100; } catch (HTTP.CancelledException) { throw new CancelledException(); } catch (CancelledException ce) { log.Info("Getting system status cancelled"); Status = ReportStatus.cancelled; Error = ce; Description = Messages.ACTION_SYSTEM_STATUS_CANCELLED; throw; } catch (Exception e) { log.Error(string.Format("Getting system status from {0} failed", hostname), e); Status = ReportStatus.failed; Error = e; if (Win32.GetHResult(e) == Win32.ERROR_DISK_FULL) { Description = Messages.ACTION_SYSTEM_STATUS_DISK_FULL; return; } if (!string.IsNullOrEmpty(Error.Message) && RBAC_FAIL_STRINGS.All(s => Error.Message.Contains(s))) { var roles = Host.Connection.Session.Roles; roles.Sort(); Description = string.Format(Messages.BUGTOOL_RBAC_FAILURE, roles[0].FriendlyName()); return; } Description = Messages.BUGTOOL_REPORTSTATUS_FAILED; } }
/// <summary> /// Configure an IP address, management purpose, and set the disallow_unplug flag on the given existing_pif. /// </summary> /// <param name="new_pif">The source of the new IP details</param> /// <param name="existing_pif">The PIF to configure</param> internal static void BringUp(AsyncAction action, PIF new_pif, string new_ip, PIF existing_pif, int hi) { bool primary = string.IsNullOrEmpty(new_pif.GetManagementPurpose()); int lo = action.PercentComplete; int inc = (hi - lo) / (primary ? 2 : 3); log.DebugFormat("Bringing PIF {0} {1} up as {2}/{3}, {4}, {5}...", existing_pif.Name(), existing_pif.uuid, new_ip, new_pif.netmask, new_pif.gateway, new_pif.DNS); action.Description = string.Format(Messages.ACTION_CHANGE_NETWORKING_BRINGING_UP, existing_pif.Name()); PIF p = (PIF)existing_pif.Clone(); p.disallow_unplug = !primary; p.SetManagementPurspose(new_pif.GetManagementPurpose()); p.SaveChanges(action.Session); action.PercentComplete = lo + inc; ReconfigureIP(action, new_pif, existing_pif, new_ip, action.PercentComplete + inc); if (!primary) { Plug(action, existing_pif, hi); } action.Description = string.Format(Messages.ACTION_CHANGE_NETWORKING_BRINGING_UP_DONE, existing_pif.Name()); log.DebugFormat("Brought PIF {0} {1} up.", existing_pif.Name(), existing_pif.uuid); }
public void Trace(string format, params object[] args) { // send all Trace message to Debug logger.DebugFormat(format, args); }
/// <summary> /// Method to be used for starting a new thread /// </summary> internal void Run() { foreach (PartitionTopicInfo partitionTopicInfo in _partitionTopicInfos) { Logger.InfoFormat("{0} start fetching topic: {1} part: {2} offset: {3} from {4}:{5}", _name, partitionTopicInfo.Topic, partitionTopicInfo.PartitionId, partitionTopicInfo.NextRequestOffset, _broker.Host, _broker.Port); } int reqId = 0; while (!_shouldStop && _partitionTopicInfos.Any()) { try { IEnumerable <PartitionTopicInfo> fetchablePartitionTopicInfos = _partitionTopicInfos.Where(pti => pti.NextRequestOffset - pti.ConsumeOffset < _fetchBufferLength); long read = 0; if (fetchablePartitionTopicInfos.Any()) { FetchRequestBuilder builder = new FetchRequestBuilder(). CorrelationId(reqId). ClientId(_config.ConsumerId ?? _name). MaxWait(_config.MaxFetchWaitMs). MinBytes(_config.FetchMinBytes); fetchablePartitionTopicInfos.ForEach(pti => builder.AddFetch(pti.Topic, pti.PartitionId, pti.NextRequestOffset, _config.FetchSize)); FetchRequest fetchRequest = builder.Build(); Logger.Debug("Sending fetch request: " + fetchRequest); FetchResponse response = _simpleConsumer.Fetch(fetchRequest); Logger.Debug("Fetch request completed"); var partitonsWithErrors = new List <PartitionTopicInfo>(); foreach (PartitionTopicInfo partitionTopicInfo in fetchablePartitionTopicInfos) { BufferedMessageSet messages = response.MessageSet(partitionTopicInfo.Topic, partitionTopicInfo.PartitionId); switch (messages.ErrorCode) { case (short)ErrorMapping.NoError: int bytesRead = partitionTopicInfo.Add(messages); // TODO: The highwater offset on the message set is the end of the log partition. If the message retrieved is -1 of that offset, we are at the end. if (messages.Messages.Any()) { partitionTopicInfo.NextRequestOffset = messages.Messages.Last().Offset + 1; read += bytesRead; } else { Logger.DebugFormat("No message returned by FetchRequest: {0}", fetchRequest.ToString()); } break; case (short)ErrorMapping.OffsetOutOfRangeCode: try { Logger.InfoFormat("offset for {0} out of range", partitionTopicInfo); long resetOffset = ResetConsumerOffsets(partitionTopicInfo.Topic, partitionTopicInfo.PartitionId); if (resetOffset >= 0) { partitionTopicInfo.FetchOffset = resetOffset; partitionTopicInfo.ConsumeOffset = resetOffset; Logger.InfoFormat("{0} marked as done.", partitionTopicInfo); } } catch (Exception ex) { Logger.ErrorFormat("Error getting offsets for partition {0} : {1}", partitionTopicInfo.PartitionId, ex.FormatException()); partitonsWithErrors.Add(partitionTopicInfo); } break; default: Logger.ErrorFormat("Error returned from broker {2} for partition {0} : KafkaErrorCode: {1}", partitionTopicInfo.PartitionId, messages.ErrorCode, partitionTopicInfo.BrokerId); partitonsWithErrors.Add(partitionTopicInfo); break; } } reqId = reqId == int.MaxValue ? 0 : reqId + 1; if (partitonsWithErrors.Any()) { RemovePartitionsFromProessing(partitonsWithErrors); } } if (read > 0) { Logger.Debug("Fetched bytes: " + read); } if (read == 0) { Logger.DebugFormat("backing off {0} ms", _config.BackOffIncrement); Thread.Sleep(_config.BackOffIncrement); } } catch (Exception ex) { if (_shouldStop) { Logger.InfoFormat("FetcherRunnable {0} interrupted", this); } else { Logger.ErrorFormat("error in FetcherRunnable {0}", ex.FormatException()); } } } Logger.InfoFormat("stopping fetcher {0} to host {1}", _name, _broker.Host); }
protected override void Run() { log.Debug("Running SR repair"); log.DebugFormat("SR='{0}'", SR.Name()); //CA-176935, CA-173497 - we need to run Plug for the master first - creating a new list of hosts where the master is always first var allHosts = new List <Host>(); var master = Helpers.GetMaster(Connection); if (master != null) { allHosts.Add(master); } foreach (var host in Connection.Cache.Hosts) { if (!allHosts.Contains(host)) { allHosts.Add(host); } } foreach (Host host in allHosts) { Host stoHost = SR.GetStorageHost(); if (SR.shared || (stoHost != null && host.opaque_ref == stoHost.opaque_ref)) { _hostList.Add(host); } } if (_hostList.Count == 0) { return; } for (int i = 0; i < _hostList.Count; i++) { log.DebugFormat("_hostList[{0}]='{1}'", i, _hostList[i].Name()); } int max = _hostList.Count * 2; int delta = 100 / max; try { if (SR.GetSRType(true) == SR.SRTypes.gfs2) { var cluster = Connection.Cache.Clusters.FirstOrDefault(); if (cluster != null) { Cluster.pool_resync(Session, cluster.opaque_ref); } } } catch (Exception e) { log.DebugFormat("Cluster pool resync failed with {0}", e.Message); } foreach (Host host in _hostList) { if (!host.HasPBDTo(SR) && SR.shared && SR.PBDs.Count > 0) { PBD template = SR.Connection.Resolve(SR.PBDs[0]); if (template != null) { this.Description = string.Format(Messages.ACTION_SR_REPAIR_CREATE_PBD, Helpers.GetName(host)); log.Debug(this.Description); var newPbd = new PBD { currently_attached = false, device_config = new Dictionary <string, string>(template.device_config), SR = template.SR, host = new XenRef <Host>(host.opaque_ref) }; try { RelatedTask = XenAPI.PBD.async_create(this.Session, newPbd); if (PercentComplete + delta <= 100) { PollToCompletion(PercentComplete, PercentComplete + delta); } else { PollToCompletion(PercentComplete, 100); PercentComplete = 100; } } catch (XenAPI.Failure f) { failure = f; failureDescription = Description; } } } else { PercentComplete += delta; } PBD thePBD = host.GetPBDTo(SR); if (thePBD != null && !thePBD.currently_attached) { this.Description = string.Format(Messages.ACTION_SR_REPAIR_PLUGGING_PBD, Helpers.GetName(host)); log.Debug(this.Description); try { RelatedTask = XenAPI.PBD.async_plug(this.Session, thePBD.opaque_ref); if (PercentComplete + delta <= 100) { PollToCompletion(PercentComplete, PercentComplete + delta); } else { PollToCompletion(PercentComplete, 100); PercentComplete = 100; } } catch (XenAPI.Failure f) { failure = f; failureDescription = Description; } } else { PercentComplete += delta; } } if (failure != null && failureDescription != null) { Description = failureDescription; throw failure; } // CA-14928: Sometimes we have too many PBDs if there has just been a host // eject and the GC hasn't collected the PBD yet. // //if (SR.PBDs.Count != _hostList.Count && SR.shared && !SR.IsToolsSR) //{ // throw new Exception(Messages.ACTION_SR_REPAIR_FAILED); //} if (isSharedAction) { Description = string.Format(Messages.ACTION_SR_SHARE_SUCCESSFUL, SR.NameWithoutHost()); } else { Description = string.Format(Messages.ACTION_SR_REPAIR_SUCCESSFUL, SR.NameWithoutHost()); } }
public void LIVE_Can_send_and_receive() { var client = CreateLiveClient(); var queue = "test-" + StringUtil.CreateAlphaNumericKey(8); client.CreateQueue(queue, new Result <AwsSqsResponse>()).Wait(); try { var body1 = "\"" %20+<>:?"; var r1 = client.Send(queue, AwsSqsMessage.FromBody(body1), new Result <AwsSqsSendResponse>()).Wait(); _log.DebugFormat("created message {0}", r1.MessageId); var doc = new XDoc("doc") .Elem("foo", StringUtil.CreateAlphaNumericKey(100)) .Start("baz") .Elem("bar", StringUtil.CreateAlphaNumericKey(100)) .Elem("baz", StringUtil.CreateAlphaNumericKey(100)) .End() .Elem("bing", StringUtil.CreateAlphaNumericKey(100)); var body2Str = "<deki-event wikiid=\"default\" event-time=\"2011-06-30T16:16:36Z\"><channel>event://default/deki/pages/dependentschanged/properties/update</channel><uri>http://ariel.mindtouch.com/@api/deki/pages/22?redirects=0</uri><pageid>22</pageid><user id=\"1\" anonymous=\"false\"><uri>http://ariel.mindtouch.com/@api/deki/users/1</uri></user><content.uri type=\"application/xml\">http://ariel.mindtouch.com/@api/deki/pages/22/contents?redirects=0&revision=45&format=xhtml</content.uri><revision.uri>http://ariel.mindtouch.com/@api/deki/pages/22/revisions?redirects=0&revision=45</revision.uri><tags.uri>http://ariel.mindtouch.com/@api/deki/pages/22/tags?redirects=0</tags.uri><comments.uri>http://ariel.mindtouch.com/@api/deki/pages/22/comments?redirects=0</comments.uri><path>Announcements/2008-10-03_-_Slide_Show_of_T2's_Big_Give</path><frommove>false</frommove></deki-event>"; var body2Doc = XDocFactory.From(body2Str, MimeType.XML); var body2 = body2Doc.ToCompactString(); var r2 = client.Send(queue, AwsSqsMessage.FromBodyDocument(body2Doc), new Result <AwsSqsSendResponse>()).Wait(); _log.DebugFormat("created message {0}", r2.MessageId); var messages = new List <AwsSqsMessage>(); Assert.IsTrue( Wait.For(() => { var r = client.Receive(queue, new Result <IEnumerable <AwsSqsMessage> >()).Wait(); foreach (var m in r) { _log.DebugFormat("retrieved message {0}", m.MessageId); messages.Add(m); } return(messages.Count == 2); }, 10.Seconds()), string.Format("only received {0} messages from queue before timeout", messages.Count) ); var msg1 = messages.Where(x => x.MessageId == r1.MessageId).FirstOrDefault(); var msg2 = messages.Where(x => x.MessageId == r2.MessageId).FirstOrDefault(); Assert.IsNotNull(msg1, "message 1 was not in response"); Assert.IsNotNull(msg2, "message 2 was not in response"); Assert.AreEqual(body1, msg1.Body, "msg 1 body didn't match"); Assert.AreEqual(body2, msg2.Body, "msg 2 body didn't match"); } finally { _log.DebugFormat("cleaning up queue '{0}'", queue); client.DeleteQueue(queue, new Result <AwsSqsResponse>()).Wait(); } }
protected void RaiseEndConversationEvent() { Log.DebugFormat("Signalling end of conversation with id {0}", ConversationId); OnConversationOver?.Invoke(this); }
private string applyVersionOneFiles() { RelatedTask = Task.create(Session, "importTask", Messages.IMPORTING); try { long totalSize = getSize(new DirectoryInfo(m_filename), 0); long bytesWritten = 0; if (totalSize == 0) { // We didn't find any .gz files, just bail out here throw new Exception(Messages.IMPORT_INCOMPLETE_FILES); } CommandLib.Config config = new CommandLib.Config { hostname = Connection.Hostname, username = Connection.Username, password = Connection.Password }; CommandLib.thinCLIProtocol tCLIprotocol = null; int exitCode = 0; tCLIprotocol = new CommandLib.thinCLIProtocol(delegate(string s) { throw new Exception(s); }, delegate { throw new Exception(Messages.EXPORTVM_NOT_HAPPEN); }, delegate(string s, CommandLib.thinCLIProtocol t) { log.Debug(s); }, delegate(string s) { log.Debug(s); }, delegate(string s) { log.Debug(s); }, delegate { throw new Exception(Messages.EXPORTVM_NOT_HAPPEN); }, delegate(int i) { exitCode = i; tCLIprotocol.dropOut = true; }, delegate(int i) { bytesWritten += i; PercentComplete = (int)(100.0 * bytesWritten / totalSize); }, config); string body = string.Format("vm-import\nsr-uuid={0}\nfilename={1}\ntask_id={2}\n", SR.uuid, m_filename, RelatedTask.opaque_ref); log.DebugFormat("Importing Geneva-style XVA from {0} to SR {1} using {2}", m_filename, SR.Name, body); CommandLib.Messages.performCommand(body, tCLIprotocol); // Check the task status -- Geneva-style XVAs don't raise an error, so we need to check manually. List <string> excep = TaskErrorInfo(); if (excep.Count > 0) { throw new Failure(excep); } // CA-33665: We found a situation before were the task handling had been messed up, we should check the exit code as a failsafe if (exitCode != 0) { throw new Failure(new[] { Messages.IMPORT_GENERIC_FAIL }); } return(Task.get_result(Session, RelatedTask)); } catch (Exception exn) { List <string> excep = TaskErrorInfo(); if (excep.Count > 0) { throw new Failure(excep); } else { throw exn; } } finally { Task.destroy(Session, RelatedTask); } }
private bool ExecuteOutfitGenerator(IList <Garment> addedGarments, bool createRecords) { newGarments = null; flavorCombinations.Clear(); outfits.Clear(); this.createRecords = createRecords; if (addedGarments != null) { newGarments = new HashSet <Garment>(); foreach (Garment g in addedGarments) { newGarments.Add(g); } } lstGarments = (from cg in currentGarments where !OutfitValidationService.IsAccessory(cg) select cg).ToList <Garment>(); logger.DebugFormat("Found {0} garments.", lstGarments.Count); lstAccesories = (from cg in currentGarments where OutfitValidationService.IsAccessory(cg) select cg).ToList <Garment>(); logger.DebugFormat("Found {0} accesories.", lstAccesories.Count); if (lstGarments.Count == 0 || lstAccesories.Count == 0) { return(false); } if (createRecords) { closetRepository.DbContext.BeginTransaction(); this.Closet.StartProcessing(); closetRepository.SaveOrUpdate(this.Closet); closetRepository.DbContext.CommitTransaction(); } bool retVal = ExecuteSet(); if (createRecords) { closetRepository.DbContext.BeginTransaction(); this.Closet.MarkAsProcessed(); closetRepository.SaveOrUpdate(this.Closet); closetRepository.DbContext.CommitTransaction(); } return(retVal); }
public LdapServer() { m_conn = null; m_cert = null; Timeout = Settings.Store.LdapTimeout; int encMethod = Settings.Store.EncryptionMethod; m_encryptionMethod = (Settings.EncryptionMethod)Enum.ToObject(typeof(Settings.EncryptionMethod), encMethod); m_verifyCert = Settings.Store.RequireCert; string certFile = Settings.Store.ServerCertFile; if ((m_encryptionMethod == Settings.EncryptionMethod.START_TLS || m_encryptionMethod == Settings.EncryptionMethod.TLS_SSL) && m_verifyCert) { m_logger.DebugFormat("Loading server certificate: {0}", certFile); if (!string.IsNullOrEmpty(certFile) && File.Exists(certFile)) { m_cert = new X509Certificate2(certFile); } else { m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile); } } string[] hosts = Settings.Store.LdapHost; int port = Settings.Store.LdapPort; m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false); m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, encryption = {2}, verifyCert = {3}", string.Join(", ", hosts), port, m_encryptionMethod.ToString(), m_verifyCert); this.Connect(); }
protected override void LoadApplications(object sender, System.ComponentModel.DoWorkEventArgs e) { foreach (string key in new[] { InstalledApps32Bit, InstalledApps64Bit }) { RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key); if (registryKey == null) { continue; // The InstalledApps64Bit registry key won't exist on 32 bit machines } for (int i = 0; i < registryKey.GetSubKeyNames().Length; i++) { string subKey = registryKey.GetSubKeyNames()[i]; if (_loadWorker.CancellationPending) { e.Cancel = true; return; } // Only care about steam applications (i.e. "Steam App 10143") Match match = Regex.Match(subKey, "^Steam App ([0-9]*)"); if (!match.Success) { continue; } RegistryKey propertyKey = registryKey.OpenSubKey(subKey); if (propertyKey == null) { continue; } string title = propertyKey.GetValue("DisplayName", null) as string; string icon = propertyKey.GetValue("DisplayIcon", null) as string; if (title.IsNullOrWhiteSpace()) { continue; } try { int appNumber = Int32.Parse(match.Groups[1].Value); ApplicationModel applicationModel = ApplicationModel.FromSteamApp(title, appNumber, icon, SelectedTab.Title); ApplicationViewModel application = new ApplicationViewModel(applicationModel); // Ignore applications already added to the dock if (!Tabs.Any(obj => obj.Applications.Contains(application))) { AddApplication(application); } } catch (FileNotFoundException ex) { Log.DebugFormat("Failed to add steam application to search view - {0}", ex.Message); } } // for } // foreach }
public void Debug(string format, object arg0) { log.DebugFormat(format, arg0); }
/// <summary> /// Get an Image from the IDataObject, don't check for FileDrop /// </summary> /// <param name="dataObject"></param> /// <returns>Image or null</returns> private static Image GetImage(IDataObject dataObject) { Image returnImage = null; if (dataObject != null) { IList <string> formats = GetFormats(dataObject); string[] retrieveFormats; // Found a weird bug, where PNG's from Outlook 2010 are clipped // So I build some special logik to get the best format: if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib)) { // Outlook ?? LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front..."); retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP_PLACEHOLDER, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF }; } else { retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP_PLACEHOLDER, FORMAT_FILECONTENTS, FORMAT_GIF }; } foreach (string currentFormat in retrieveFormats) { if (FORMAT_BITMAP_PLACEHOLDER.Equals(currentFormat)) { LOG.Info("Using default .NET Clipboard.GetImage()"); try { returnImage = Clipboard.GetImage(); if (returnImage != null) { return(returnImage); } else { LOG.Info("Clipboard.GetImage() didn't return an image."); } } catch (Exception ex) { LOG.Error("Problem retrieving Image via Clipboard.GetImage(): ", ex); } } else if (formats.Contains(currentFormat)) { LOG.InfoFormat("Found {0}, trying to retrieve.", currentFormat); if (currentFormat == DataFormats.Dib) { returnImage = GetDIBImage(dataObject); } else { returnImage = GetImageFormat(currentFormat, dataObject); } if (returnImage != null) { ImageHelper.Orientate(returnImage); return(returnImage); } } else { LOG.DebugFormat("Couldn't find format {0}.", currentFormat); } } } return(null); }
protected override void Run() { Description = Messages.ACTION_WLB_REPORT_DOWNLOADING; RelatedTask = XenAPI.Task.create(Session, string.Format(Messages.ACTION_WLB_REPORT_TASK_NAME, reportName), string.Format(Messages.ACTION_WLB_REPORT_TASK_DESCRIPTION, reportName)); UriBuilder uriBuilder = new UriBuilder(Session.Url); uriBuilder.Path = "wlb_report"; uriBuilder.Query = string.Format("session_id={0}&report={1}&task_id={2}", Uri.EscapeDataString(Session.uuid), Uri.EscapeDataString(report), Uri.EscapeDataString(RelatedTask.opaque_ref)); foreach (string k in parms.Keys) { string v = parms[k]; uriBuilder.Query = uriBuilder.Query.Substring(1) + string.Format("&{0}={1}", k, v); } log.DebugFormat("Downloading report {0} from {1}", report, uriBuilder.ToString()); // The DownloadFile call will block, so we need a separate thread to poll for task status. Thread taskThread = new Thread((ThreadStart)progressPoll); taskThread.Name = "Progress polling thread for WLBReportAction for " + report.Ellipsise(20); taskThread.IsBackground = true; taskThread.Start(); try { HttpGet(uriBuilder.Uri); } catch (Exception e) { if (XenAPI.Task.get_status(Session, RelatedTask.opaque_ref) == XenAPI.task_status_type.pending && XenAPI.Task.get_progress(Session, RelatedTask.opaque_ref) == 0) { // If task is pending and has zero progress, it probably hasn't been started, // which probably means there was an exception in the GUI code before the // action got going. Kill the task so that we don't block forever on // taskThread.Join(). Brought to light by CA-11100. DestroyTask(); } if (exception == null) { exception = e; } } taskThread.Join(); if (Cancelling || exception is CancelledException) { log.InfoFormat("WLB report download for {0} cancelled", report); Description = Messages.ACTION_WLB_REPORT_CANCELLED; throw new CancelledException(); } else if (exception != null) { log.Warn(string.Format("WLB report download for {0} failed", report), exception); // When using this method for acquiring report configuration information // we can hide the exception as a second attempt will be made with local // config approach if (!hideException) { if (exception.Message.Contains("HTTP/1.1 403")) { Description = Messages.WLB_REPORT_HTTP_403; } else if (exception.Message.Contains("HTTP/1.0 500")) { Description = Messages.WLB_REPORT_HTTP_500; } else { Description = Messages.ACTION_WLB_REPORT_FAILED; } throw exception; } } else { log.InfoFormat("WLB report download for {0} successful", report); Description = Messages.ACTION_WLB_REPORT_SUCCESSFUL; // filter out CDATA if (result.Contains("<![CDATA[")) { result = result.Replace("<![CDATA[", String.Empty).Replace("]]>", String.Empty); } Result = result; } }
public bool SomethingChanged() { bool isCustomerChanged = false; bool isCashRequestChanged = false; bool isLoanChanged = false; bool isLoanTransactionChanged = false; bool isBrokerChanged = false; var changed = Db.ExecuteEnumerable("EzTvIsChanged", CommandSpecies.StoredProcedure); foreach (SafeReader row in changed) { int val; string sTableName = row["Table"]; if (sTableName == "Security_User") { val = row["Val"]; isCustomerChanged = val > CustomerId; CustomerId = val; continue; } if (sTableName == "CashRequests") { val = row["Val"]; isCashRequestChanged = val > CashRequestsId; CashRequestsId = val; continue; } if (sTableName == "Loan") { val = row["Val"]; isLoanChanged = val > LoanId; LoanId = val; continue; } if (sTableName == "LoanTransaction") { val = row["Val"]; isLoanTransactionChanged = val > LoanTransactionId; LoanTransactionId = val; continue; } if (sTableName == "Broker") { val = row["Val"]; isBrokerChanged = val > BrokerId; BrokerId = val; continue; } } bool somethingChanged = isCustomerChanged || isCashRequestChanged || isLoanChanged || isLoanTransactionChanged || isBrokerChanged; if (somethingChanged) { Log.DebugFormat("Something changed, building model customer:{0}, cash request:{1}, loan:{2}, loan transaction:{3}, broker:{4}", isCustomerChanged, isCashRequestChanged, isLoanChanged, isLoanTransactionChanged, isBrokerChanged); DashboardModel = BuildModel(); return(true); } return(false); }
private static void Tick(DateTime now, TimeSpan elapsed) { lock (_syncRoot) { // check if resource manager has been idle for a while _idleTime += elapsed; if (_idleTime > IDLE_TIME_LIMIT) { int count = _threadReserve.ItemCount; if (count > _threadReserveCount) { _log.DebugFormat("Tick: idling with excessive thread reserve (count: {0})", count); _idleTime = TimeSpan.Zero; // try discarding an idle thread KeyValuePair <DispatchThread, Result <DispatchWorkItem> > entry; if (_threadReserve.TryDequeue(out entry)) { --_allocatedThreads; entry.Value.Throw(new DispatchThreadShutdownException()); } } } } // loop over hosts and determine if their target thread count needs to be adjusted lock (_hosts) { string reason = null; _saturationTime += elapsed; // check if the system is saturated with work float load = ProcessorLoad; if ((load >= CPU_SATURATION_THRESHOLD) && (_saturationTime > SATURATION_TIME_LIMIT)) { // TODO: be more selective on which host to decrease // request threads to be discarded foreach (IDispatchHost host in _hosts) { long itemCount = host.PendingWorkItemCount; int threadCount = host.ThreadCount; // check if host is starving (which means it has items to process, but no threads) if ((itemCount > 0) && (threadCount == 0)) { // take care of starving hosts (doesn't matter if we're saturated or not) host.IncreaseThreadCount(string.Format("starving (items: {0})", itemCount)); } else if (threadCount > 1) { if (reason == null) { reason = string.Format("throttle down (cpu: {0}%, threads: {1})", load, threadCount); } // tell host to decrease thread count host.DecreaseThreadCount(reason); } } } else if (load >= CPU_MAINTAIN_THRESHOLD) { // reset saturation counter if we're running below saturation level if (load < CPU_SATURATION_THRESHOLD) { _saturationTime = TimeSpan.Zero; } // stop new threads from being requested foreach (IDispatchHost host in _hosts) { long itemCount = host.PendingWorkItemCount; int threadCount = host.ThreadCount; // check if host is starving (which means it has items to process, but no threads) if ((itemCount > 0) && (threadCount == 0)) { // take care of starving hosts (doesn't matter if we're saturated or not) host.IncreaseThreadCount(string.Format("starving (items: {0})", itemCount)); } else { if (reason == null) { reason = string.Format("maintain (cpu: {0}%)", load); } // tell host to decrease thread count host.MaintainThreadCount(reason); } } } else { _saturationTime = TimeSpan.Zero; // allocate additional threads if we have capacity to do so foreach (IDispatchHost host in _hosts) { long itemCount = host.PendingWorkItemCount; // check if host is starving (which means it has items to process, but no threads) if ((itemCount > 0) && (host.ThreadCount == 0)) { // take care of starving hosts (doesn't matter if we're saturated or not) host.IncreaseThreadCount(string.Format("starving (items: {0})", itemCount)); } else if (itemCount > 0) { if (reason == null) { reason = string.Format("throttle up (cpu: {0}%, items: {1})", load, itemCount); } // tell host to increase thread count host.IncreaseThreadCount(reason); } } } } }
public void UpdateOrCreateLines(ISession session, IList <ReturnLine> toSave) { //确保换货退货不会执行该方法 if (this.OrderTypeCode == ORDER_TYPE_EXCHANGE_RTN) { return; } log.DebugFormat("to create or save rtn lines, count:{0}", toSave == null ? 0 : toSave.Count); if (toSave == null || toSave.Count <= 0) { return; } if (this.Status != ReturnStatus.New) { throw new Exception("退货单不是新建状态,无法更新"); } //物流退货、内部退货必须全退,不支持部分退货 if (this.OrderTypeCode == ORDER_TYPE_LOGISTICS_RTN || this.OrderTypeCode == ORDER_TYPE_INNER_RTN) { int snLineCount = session.CreateEntityQuery <CRMSNLine>().Where(Exp.Eq("SNID", this.RefOrderID)).Count(); if (snLineCount != toSave.Count) { throw new Exception("发货单" + this.RefOrderNumber + "明细(" + snLineCount.ToString() + "项)与退货明细(" + toSave.Count.ToString() + "项)不一致"); } } bool updateHeadLineNum = false; foreach (ReturnLine line in toSave) { if (line.RefOrderLineID <= 0 || line.Quantity <= 0M) { if (this.OrderTypeCode == ORDER_TYPE_LOGISTICS_RTN || this.OrderTypeCode == ORDER_TYPE_INNER_RTN) { throw new Exception("退货明细或者数量无效"); } continue; } bool checkCreate = true; if (this.OrderTypeCode == ORDER_TYPE_MBR_RTN) { //会员退货才可以分多次扫描退货明细 ReturnLine existsLine = ReturnLine.Retrieve(session, this.OrderNumber, line.RefOrderLineID); if (existsLine != null) { log.DebugFormat("rtn line({0}) exists, rtn qty:{1}", line.RefOrderLineID, line.Quantity); existsLine.Quantity += line.Quantity; existsLine.Update(session, "Quantity"); checkCreate = false; } } if (checkCreate) { CRMSNLine snline = CRMSNLine.Retrieve(session, line.RefOrderLineID); if (snline == null) { throw new Exception("发货单明细" + line.RefOrderLineID.ToString() + "不存在"); } //物流退货、内部退货必须全退 if ((this.OrderTypeCode == ORDER_TYPE_LOGISTICS_RTN || this.OrderTypeCode == ORDER_TYPE_INNER_RTN) && line.Quantity != snline.Quantity) { throw new Exception("退货数量不等于发货数量"); } ReturnLine existsLine = new ReturnLine(); existsLine.OrderNumber = this.OrderNumber; existsLine.LineNumber = this.NextLineNumber(); updateHeadLineNum = true; existsLine.RefOrderLineID = snline.ID; existsLine.SKUID = snline.SKUID; existsLine.TransTypeCode = " "; existsLine.Quantity = line.Quantity; existsLine.DeliverQuantity = snline.Quantity; existsLine.Price = snline.Price; IList <WHArea> areas = ERPUtil.GetWHArea(session, this.OrderTypeCode, null, this.LocationCode); if (areas.Count == 1) { existsLine.AreaCode = areas[0].AreaCode; } log.DebugFormat("to create rtn line, qty:{0}", line.Quantity); existsLine.Create(session); } } if (updateHeadLineNum) { this.Update(session, "CurrentLineNumber"); } }
protected override void Run() { log.Debug("Running SR.Create()"); log.DebugFormat("host='{0}'", Host.Name()); log.DebugFormat("name='{0}'", _srName); log.DebugFormat("description='{0}'", _srDescription); log.DebugFormat("type='{0}'", _srType); log.DebugFormat("content type='{0}'", _srContentType); log.DebugFormat("is shared='{0}'", _srIsShared); string secretuuid = null; string value; if (_dconf.TryGetValue("cifspassword", out value)) { secretuuid = CreateSecret("cifspassword", value); } else if (_dconf.TryGetValue("password", out value)) { secretuuid = CreateSecret("password", value); } else if (_dconf.TryGetValue("chappassword", out value)) { secretuuid = CreateSecret("chappassword", value); } Description = Messages.ACTION_SR_CREATING; XenRef <SR> sr; try { sr = XenAPI.SR.create(Session, Host.opaque_ref, _dconf, 0, _srName, _srDescription, _srType.ToString().ToLowerInvariant(), _srContentType, _srIsShared, _smconf ?? new Dictionary <string, string>()); Result = sr; } catch { if (!string.IsNullOrEmpty(secretuuid)) { string opaqref = Secret.get_by_uuid(Session, secretuuid); Secret.destroy(Session, opaqref); } throw; } finally { // Destroy secret after the SR creation is complete. This is safe // since all PBDs will have duplicated the secret (CA-113396). // // We do this on a best-effort basis because some types of errors // mean the secret was never actually created, so the operation will // fail, masking any earlier error (CA-145254), or causing a successful // SR.create to be reported as an error. The worst that can happen is // that an unused secret will be left lying around without warning. try { if (!string.IsNullOrEmpty(secretuuid) && Helpers.CreedenceOrGreater(Connection)) { string opaqref = Secret.get_by_uuid(Session, secretuuid); Secret.destroy(Session, opaqref); } } catch { } } log.Debug("Checking that SR.create() actually succeeded"); foreach (XenRef <PBD> pbdRef in XenAPI.SR.get_PBDs(Session, sr.opaque_ref)) { if (!XenAPI.PBD.get_currently_attached(Session, pbdRef)) { // The automatic plug done by the SR.create has failed to plug this PDB: // try the plug manually, and report the failure. Roll back the operation // by forgetting the SR. try { XenAPI.PBD.plug(this.Session, pbdRef); } catch (Exception exn) { if (exn is Failure) { Failure f = (Failure)exn; if (f.ErrorDescription[0] == Failure.HOST_OFFLINE || f.ErrorDescription[0] == Failure.HOST_STILL_BOOTING) { log.Warn("Unable to check storage settings, due to host being down", f); } } else { log.Debug("Plug failed on a PBD: performing SR.forget"); ForgetFailedSR(sr); throw; } } } } Dictionary <string, string> other_config = new Dictionary <string, string>(); other_config.Add("auto-scan", _srContentType == XenAPI.SR.Content_Type_ISO ? "true" : "false"); XenAPI.SR.set_other_config(Session, Result, other_config); if (isFirstSharedNonISOSR()) { SR new_sr = Connection.WaitForCache(new XenRef <SR>(Result), GetCancelling); if (Cancelling) { throw new CancelledException(); } if (new_sr == null) { throw new Failure(Failure.HANDLE_INVALID, "SR", Result); } // Set this SR to be the default new SrAction(SrActionKind.SetAsDefault, new_sr).RunExternal(Session); } Description = Messages.ACTION_SR_CREATE_SUCCESSFUL; }
protected override void Run() { Connection.ExpectDisruption = true; List <VIF> unplugged_vifs = new List <VIF>(); string old_network_name = Network == null ? "" : Network.Name; Exception e = null; if (!bostonOrGreater) { if (Network != null && NewNetworkName != null) { // Unplug all active VIFs, because we can't fiddle with the PIFs on the network while the // VIFs are active (xapi won't let us). foreach (VIF vif in Connection.ResolveAll(Network.VIFs)) { if (vif.currently_attached) { log.DebugFormat("Unplugging VIF {0} from network {1}...", vif.uuid, old_network_name); VIF.unplug(Session, vif.opaque_ref); unplugged_vifs.Add(vif); log.DebugFormat("VIF {0} unplugged from network {1}.", vif.uuid, old_network_name); } } } } BestEffort(ref e, ReconfigureManagementInterfaces); if (e != null) { throw e; } PercentComplete = 50; int inc = 40 / (Bonds.Count + Masters.Count + Slaves.Count); int lo = PercentComplete; foreach (Bond bond in Bonds) { Bond bond1 = bond; int lo1 = lo; BestEffort(ref e, delegate() { RelatedTask = Bond.async_destroy(Session, bond1.opaque_ref); }); PollToCompletion(lo1, lo1 + inc); lo += inc; } foreach (PIF master in Secondaries) { if (!bostonOrGreater) { ReconfigureSecondaryManagement(master, PercentComplete + inc); } PercentComplete += inc; } if (!bostonOrGreater) { foreach (PIF pif in Slaves) { NetworkingActionHelpers.Plug(this, pif, PercentComplete + inc); } } if (Network != null) { if (NewNetworkName == null) { // We can delete the whole network. log.DebugFormat("Destroying network {0} ({1})...", old_network_name, Network.uuid); BestEffort(ref e, delegate() { XenAPI.Network.destroy(Session, Network.opaque_ref); log.DebugFormat("Network {0} ({1}) destroyed.", old_network_name, Network.uuid); }); } else { // Rename the network, so that the VIFs still have somewhere to live. log.DebugFormat("Renaming network {0} ({1}) to {2}...", old_network_name, Network.uuid, NewNetworkName); XenAPI.Network n = (XenAPI.Network)Network.Clone(); n.name_label = NewNetworkName; BestEffort(ref e, delegate() { n.SaveChanges(Session); log.DebugFormat("Renaming network {0} ({1}) done.", NewNetworkName, n.uuid); }); // Replug all the VIFs that we unplugged before. if (!bostonOrGreater) { foreach (VIF vif in unplugged_vifs) { log.DebugFormat("Replugging VIF {0} into network {1}...", vif.opaque_ref, NewNetworkName); BestEffort(ref e, delegate() { VIF.plug(Session, vif.opaque_ref); log.DebugFormat("Replugging VIF {0} into network {1} done.", vif.opaque_ref, NewNetworkName); }); } } } } if (e != null) { throw e; } Description = string.Format(Messages.ACTION_DESTROY_BOND_DONE, Name); }
public PackagesNancyModule(IPackageService repository, IEdmModel odataModel) : base(basePath) { this.OnError.AddItemToEndOfPipeline(HandleError); base.Get("/contents/{id}/{version}", args => { string id = args.id; string v = args.version; NuGetVersion version; if (!NuGetVersion.TryParse(v, out version)) { _log.ErrorFormat("Bad version format {0}", v); return(HttpStatusCode.BadRequest); } var nupkg = repository.GetStream(new PackageIdentity(id, version)); if (nupkg == null) { _log.WarnFormat("Package contents not found {0}", base.Request.Path); return(HttpStatusCode.NotFound); } return(new StreamResponse(nupkg, "application/zip")); }); base.Get <Response>("/", args => { var serviceUrl = GetServiceUrl(); return(new Response() { StatusCode = HttpStatusCode.OK, ContentType = "application/xml; charset=utf-8", Contents = stream => { string text = $@"<?xml version=""1.0"" encoding=""utf-8""?> <service xml:base=""{serviceUrl}"" xmlns=""http://www.w3.org/2007/app"" xmlns:atom=""http://www.w3.org/2005/Atom""><workspace> <atom:title type=""text"">Default</atom:title><collection href=""Packages""><atom:title type=""text"">Packages</atom:title></collection></workspace> </service>"; var writer = new StreamWriter(stream, new UTF8Encoding(false)); writer.Write(text); writer.Flush(); } }); }); base.Put <Response>("/", args => { // client for reference - https://github.com/NuGet/NuGet.Client/blob/4eed67e7e159796ae486d2cca406b283e23b6ac8/src/NuGet.Core/NuGet.Protocol/Resources/PackageUpdateResource.cs#L273 if (this.Request.Files.Count() != 1) { _log.ErrorFormat("Bad request, tried to push {0} files {1}", this.Request.Files.Count(), string.Join(",", this.Request.Files.Select(f => f.Key))); return(HttpStatusCode.BadRequest); } var file = this.Request.Files.FirstOrDefault(); try { repository.PushPackage(file.Value); return(HttpStatusCode.Created); } catch (PackageDuplicateException dup) { _log.Error("Tried to push a package which already exists", dup); return(HttpStatusCode.Conflict); } catch (Exception ex) { _log.Error("Failed to push package", ex); return(HttpStatusCode.InternalServerError); } }); base.Get <object>(@"^(.*)$", args => { try { var serviceUrl = GetServiceUrl(); var uriParser = new ODataUriParser(odataModel, serviceUrl, base.Request.Url); var path = uriParser.ParsePath(); if (path.FirstSegment.Identifier == "FindPackagesById") { var idOrNull = uriParser.CustomQueryOptions.FirstOrDefault(o => o.Key.ToLowerInvariant() == "id").Value; //TODO semVer var semVer = ClientCompatibility.Max; if (idOrNull == null) { throw new ArgumentException();//TODO nice bad request } else { string id = idOrNull.TrimStart('\'').TrimEnd('\''); _log.DebugFormat("Request to FindPackagesById id={0}", id); var found = repository.FindPackagesById(id, semVer); return(new ODataResponse <IEnumerable <PackageWithUrls> >(serviceUrl.AbsoluteUri, found.Select(ToPackageWithUrls))); } } else if (path.FirstSegment.Identifier == "Packages") { if (path.Count == 2 && path.LastSegment is KeySegment) { KeySegment queryParams = (KeySegment)path.LastSegment; string id = queryParams.Keys.First(k => k.Key == "Id").Value as string; string version = queryParams.Keys.First(k => k.Key == "Version").Value as string; _log.DebugFormat("Request to find package by id={0} and version={1}", id, version); var found = repository.FindPackage(id, NuGetVersion.Parse(version)); if (found == null) { return(NoPackage404()); } return(new ODataResponse <PackageWithUrls>(serviceUrl.AbsoluteUri, ToPackageWithUrls(found))); } else { throw new ArgumentException("Bad or not supported query");//TODO nice bad request } } else { throw new NotSupportedException(string.Format("Not supported endpoint path {0} or action {1}", base.Request.Path, path.FirstSegment.Identifier)); } } catch (ODataUnrecognizedPathException odataPathError) { _log.Error("Bad odata query", odataPathError); return(HttpStatusCode.BadRequest); } }); base.Head <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); base.Post <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); base.Put <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); base.Delete <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); }
/// <summary> /// Runs a separate process and returns the standard output and error text. This is intended for command line apps only. /// </summary> /// <param name="command"></param> /// <param name="args"></param> /// <param name="killAfterSeconds"></param> /// <param name="echoCommand"> </param> /// <returns></returns> public static string RunCommand(string command, string args, int killAfterSeconds = 300, bool echoCommand = true) { Process proc = null; log4net.ILog logger = log4net.LogManager.GetLogger("CommandExecutor"); if (logger.IsDebugEnabled) { logger.DebugFormat("Running Commandline: {0} {1}", command, args); } try { var startInfo = new ProcessStartInfo(command, args) { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = System.Text.Encoding.Default }; proc = new Process { StartInfo = startInfo }; proc.ErrorDataReceived += CommandProcessErrorDataReceived; proc.Start(); proc.BeginErrorReadLine(); var retVal = proc.StandardOutput.ReadToEnd(); if (!proc.WaitForExit(killAfterSeconds * 1000)) { proc.Kill(); } if (Errors.ContainsKey(proc.Id)) { retVal += Environment.NewLine + "Error: " + Environment.NewLine + Errors[proc.Id]; } if (echoCommand) { // hide password from being displayed var regexObj = new Regex("--password\\s+\\S+\\s", RegexOptions.IgnoreCase); args = regexObj.Replace(args, "--password **** "); return(command + " " + args + Environment.NewLine + retVal); } else { return(retVal); } } catch (Exception ex) { logger.ErrorFormat("An error occurred running the command line: {2} {3}\n\n {0} \n\n {1}", ex.Message, ex.StackTrace, command, args); return(string.Empty); } finally { if (proc != null) { if (Errors.ContainsKey(proc.Id)) { Errors.Remove(proc.Id); } proc.Dispose(); } } }
public void Start(string id) { #if DEBUG if (!Enabled) { throw new InvalidProgramException(); } #endif if (!string.IsNullOrEmpty(id) && id == currentDeviceId) { return; } if (started) { // We must wait until the recorder is fully closed before restarting it. changeDeviceAsked = true; nextDeviceId = id; Stop(); return; } changeDeviceAsked = false; nextDeviceId = null; if (WaveIn.DeviceCount == 0) { log.DebugFormat("Audio input level monitor failed to start, no input device available."); return; } if (waveIn == null) { waveIn = new WaveInEvent(); waveIn.WaveFormat = new WaveFormat(22050, 1); waveIn.DataAvailable += WaveIn_DataAvailable; waveIn.RecordingStopped += WaveIn_RecordingStopped; } int deviceNumber = 0; if (!string.IsNullOrEmpty(id)) { int waveInDevices = WaveIn.DeviceCount; for (int i = 0; i < waveInDevices; i++) { WaveInCapabilities caps = WaveIn.GetCapabilities(i); if (caps.ProductGuid.ToString() == id) { deviceNumber = i; break; } } } waveIn.DeviceNumber = deviceNumber; started = true; waveIn.StartRecording(); WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveIn.DeviceNumber); currentDeviceId = deviceInfo.ProductGuid.ToString(); log.DebugFormat("Audio input level monitor started: {0}", deviceInfo.ProductName); }
private bool HandleReceive(NetState ns) { lock ( ns ) { ByteQueue buffer = ns.Buffer; if (buffer == null) { return(true); } int length = buffer.Length; if (!ns.Seeded) { if (length >= 4) { buffer.Dequeue(m_Peek, 0, 4); int seed = (m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]; if (log.IsDebugEnabled) { log.DebugFormat("Login: {0}: Seed is 0x{1:X8}", ns, seed); } if (seed == 0) { log.WarnFormat("Login: {0}: Invalid client detected, disconnecting", ns); ns.Dispose(); return(false); } ns.m_Seed = seed; ns.Seeded = true; } return(true); } while (length > 0 && ns.Running) { int packetID = buffer.GetPacketID(); if (!ns.SentFirstPacket && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 && packetID != 0x91 && packetID != 0xA4 && packetID != 0xBF) { log.WarnFormat("Client: {0}: Encrypted client detected, disconnecting", ns); ns.Dispose(); break; } PacketHandler handler = PacketHandlers.GetHandler(packetID); if (handler == null) { byte[] data = new byte[length]; length = buffer.Dequeue(data, 0, length); new PacketReader(data, length, false).Trace(ns); break; } int packetLength = handler.Length; if (packetLength <= 0) { if (length >= 3) { packetLength = buffer.GetPacketLength(); if (packetLength < 3) { ns.Dispose(); break; } } else { break; } } if (length >= packetLength) { if (handler.Ingame && ns.Mobile == null) { log.WarnFormat("Client: {0}: Sent ingame packet (0x{1:X2}) before having been attached to a mobile", ns, packetID); ns.Dispose(); break; } else if (handler.Ingame && ns.Mobile.Deleted) { ns.Dispose(); break; } else { ThrottlePacketCallback throttler = handler.ThrottleCallback; if (throttler != null && !throttler(ns)) { m_Throttled.Enqueue(ns); return(false); } PacketProfile profile = PacketProfile.GetIncomingProfile(packetID); DateTime start = (profile == null ? DateTime.MinValue : DateTime.Now); byte[] packetBuffer; if (BufferSize >= packetLength) { packetBuffer = m_Buffers.AquireBuffer(); } else { packetBuffer = new byte[packetLength]; } packetLength = buffer.Dequeue(packetBuffer, 0, packetLength); PacketReader r = new PacketReader(packetBuffer, packetLength, handler.Length != 0); try { handler.OnReceive(ns, r); } catch (Exception e) { log.Fatal(String.Format("Exception disarmed in HandleReceive from {0}", ns.Address), e); } length = buffer.Length; if (BufferSize >= packetLength) { m_Buffers.ReleaseBuffer(packetBuffer); } if (profile != null) { profile.Record(packetLength, DateTime.Now - start); } } } else { break; } } } return(true); }
public CachingProxyV3NancyModule(IHttpClient client, IV3JsonInterceptor interceptor, IUrlReplacementsProvider replacementsProvider, INupkgCacheProvider nupkgCache, IPackageMetadataCache metadataCache) : base(basePath) { this.metadataCache = metadataCache; this.client = client; this.interceptor = interceptor; this.replacementsProvider = replacementsProvider; this.OnError.AddItemToEndOfPipeline(HandleError); base.Get <Response>("/v3/registration3/{package}/index.json", async args => { string package = args.package; byte[] bytes = this.metadataCache.TryGet(package); if (bytes != null) { _log.DebugFormat("Cache hit. Serving {0} from cache", Request.Url); return(new Response() { StatusCode = Nancy.HttpStatusCode.OK, ContentType = "application/json", Contents = netStream => { try { netStream.Write(bytes, 0, bytes.Length); netStream.Flush(); _log.DebugFormat("Served {0} bytes from cache", bytes.Length); } catch (Exception ex) { _log.Error("Something went wrong when serving query from cache", ex); throw new Exception("Serving query from cache failed", ex); } } }); } string myV3Url = this.GetServiceUrl().AbsoluteUri; Dictionary <string, string> replacements = replacementsProvider.GetReplacements(myV3Url); var request = new HttpRequestMessage() { RequestUri = replacementsProvider.GetOriginUri(Request.Url), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _log.DebugFormat("Cache miss. Proxying {0} to {1}", Request.Url, request.RequestUri); var timestamp = DateTimeOffset.UtcNow; var originalResponse = await client.SendAsync(request); return(new DisposingResponse(originalResponse) { StatusCode = (Nancy.HttpStatusCode)(int) originalResponse.StatusCode, ContentType = originalResponse.Content.Headers.ContentType.MediaType, Contents = netStream => { Stream originalStream = null; try { originalStream = originalResponse.Content.ReadAsStreamAsync().Result; if (originalResponse.Content.Headers.ContentEncoding.Contains("gzip")) { originalStream = new GZipStream(originalStream, CompressionMode.Decompress); } using (var ms = new MemoryStream()) { interceptor.Intercept(replacements, originalStream, ms); bytes = ms.ToArray(); this.metadataCache.Insert(package, timestamp, bytes); netStream.Write(bytes, 0, bytes.Length); netStream.Flush(); } } catch (Exception ex) { _log.Error("Something went wrong when intercepting origin response", ex); throw new Exception("Intercepting origins response failed", ex); } finally { if (originalStream != null) { originalStream.Dispose(); } originalResponse.Dispose(); } } }); }); base.Get <Response>("/{path*}", async args => { string myV3Url = this.GetServiceUrl().AbsoluteUri; Dictionary <string, string> replacements = replacementsProvider.GetReplacements(myV3Url); var request = new HttpRequestMessage() { RequestUri = replacementsProvider.GetOriginUri(this.Request.Url), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _log.DebugFormat("Proxying {0} to {1}", this.Request.Url, request.RequestUri); var originalResponse = await client.SendAsync(request); if (!(200 <= (int)originalResponse.StatusCode && (int)originalResponse.StatusCode < 300)) { _log.WarnFormat("Origin server {0} response status is {1}", request.RequestUri, originalResponse.StatusCode); } return(new DisposingResponse(originalResponse) { StatusCode = (Nancy.HttpStatusCode)(int) originalResponse.StatusCode, ContentType = originalResponse.Content.Headers.ContentType.MediaType, Contents = netStream => { Stream originalStream = null; try { originalStream = originalResponse.Content.ReadAsStreamAsync().Result; if (originalResponse.Content.Headers.ContentEncoding.Contains("gzip")) { originalStream = new GZipStream(originalStream, CompressionMode.Decompress); } if (new MediaRange("application/json").Matches(new MediaRange(originalResponse.Content.Headers.ContentType.MediaType))) { interceptor.Intercept(replacements, originalStream, netStream); } else { originalStream.CopyTo(netStream); } } catch (Exception ex) { _log.Error("Something went wrong when intercepting origin response", ex); throw new Exception("Intercepting origins response failed", ex); } finally { if (originalStream != null) { originalStream.Dispose(); } originalResponse.Dispose(); } } }); }); base.Get <Response>("/v3-flatcontainer/{package}/{version}/{filename}", async args => { string package = args.package; string version = args.version; string path = package + "/" + version + "/" + args.filename; byte[] hit; using (var tx = nupkgCache.OpenTransaction()) { hit = tx.TryGet(args.package, args.version); } if (hit == null) { // cache miss var request = new HttpRequestMessage() { RequestUri = replacementsProvider.GetOriginUri(this.Request.Url), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream")); _log.DebugFormat("Cache miss. Proxying {0} to {1}", this.Request.Url, request.RequestUri); var originalResponse = await client.SendAsync(request); return(new DisposingResponse(originalResponse) { ContentType = originalResponse.Content.Headers.ContentType.MediaType, Contents = netStream => { Stream originalStream = null; try { using (var cacheTx = nupkgCache.OpenTransaction()) { originalStream = originalResponse.Content.ReadAsStreamAsync().Result; using (var ms = new MemoryStream((int)originalResponse.Content.Headers.ContentLength.GetValueOrDefault(4096))) { originalStream.CopyTo(ms); byte[] value = ms.ToArray(); var writing = netStream.WriteAsync(value, 0, value.Length); try { cacheTx.Insert(package, version, value); } catch (Exception cacheError) { _log.Error("Failed to insert package to cache", cacheError); } finally { writing.Wait(); netStream.Flush(); } } } } catch (Exception ex) { _log.Error("Something went wrong when serving nupkg", ex); throw new Exception("Serving nupkg failed", ex); } finally { if (originalStream != null) { originalStream.Dispose(); } originalResponse.Dispose(); } } }); } else { // cache hit, return from cache _log.DebugFormat("Cache hit. Serving {0} from cache", this.Request.Url); return(new DisposingResponse() { ContentType = "application/octet-stream", Contents = netStream => { try { netStream.Write(hit, 0, hit.Length); netStream.Flush(); } catch (Exception ex) { _log.Error("Something went wrong when serving nupkg from cache", ex); throw new Exception("Serving nupkg from cache failed", ex); } } }); } }); base.Head <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); base.Post <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); base.Put <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); base.Delete <object>(@"^(.*)$", new Func <dynamic, object>(ThrowNotSupported)); }
public void Debug(object message) { var activityId = Trace.CorrelationManager.ActivityId; _logger.DebugFormat("CorrelationId: {0} - {1}", activityId, message); }
/// <summary> /// Build up the command line arguments, determine which executable is being /// used and find the path to that executable and set the working /// directory. /// </summary> /// <param name="process">The process to prepare.</param> protected override void PrepareProcess(Process process) { // Although a global property can be set, take the property closest // to the task execution, which is the attribute on the task itself. if (!_isUseSharpCvsLibSet && (null == this.PropertyAccessor || null == this.PropertyAccessor[UseSharpCvsLibProp])) { // if not set and the global property is null then use the default _useSharpCvsLib = UseSharpCvsLib; } else if (!_isUseSharpCvsLibSet && null != this.PropertyAccessor[UseSharpCvsLibProp]) { try { _useSharpCvsLib = System.Convert.ToBoolean(this.PropertyAccessor[UseSharpCvsLibProp]); } catch (Exception) { throw new BuildException(UseSharpCvsLib + " must be convertable to a boolean."); } } Logger.DebugFormat("number of arguments: {0}", Arguments.Count); // if set, pass cvsroot to command line tool if (Root != null) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "-d{0}", Root))); } if (this.UseSharpCvsLib) { Managed = ManagedExecution.Auto; } // Set verbose logging on the #cvslib client if used. if (this.UseSharpCvsLib && this.Verbose) { SetGlobalOption("verbose", String.Format("-verbose"), true); } AppendGlobalOptions(); Arguments.Add(new Argument(CommandName)); AppendCommandOptions(); Log(Level.Debug, "Commandline args are null: {0}", ((null == CommandLineArguments) ? "yes" : "no")); Log(Level.Debug, "Commandline: {0}", CommandLineArguments); if (null != CommandLineArguments) { Arguments.Add(new Argument(CommandLineArguments)); } AppendSubCommandArgs(); AppendFiles(); if (IsModuleNeeded && null == Module) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Cvs module is required for this action."), Location); } if (IsModuleNeeded) { Arguments.Add(new Argument(Module)); } if (!Directory.Exists(DestinationDirectory.FullName)) { Directory.CreateDirectory(DestinationDirectory.FullName); } base.PrepareProcess(process); process.StartInfo.FileName = ExeName; process.StartInfo.WorkingDirectory = DestinationDirectory.FullName; Log(Level.Verbose, "Working directory: {0}", process.StartInfo.WorkingDirectory); Log(Level.Verbose, "Executable: {0}", process.StartInfo.FileName); Log(Level.Verbose, "Arguments: {0}", process.StartInfo.Arguments); }