示例#1
0
 private void device_VideoSourceError(object sender, VideoSourceErrorEventArgs e)
 {
     log.ErrorFormat("Error from device {0}: {1}", summary.Alias, e.Description);
 }
示例#2
0
        private static DrawingTool ParseTool(XmlReader r)
        {
            r.MoveToContent();
            r.ReadStartElement();

            string version = r.ReadElementContentAsString("FormatVersion", "");

            if (version != "1.0")
            {
                log.ErrorFormat("Unsupported format version ({0}) for tool description.", version);
                return(null);
            }

            Guid         id          = Guid.Empty;
            string       name        = "";
            string       displayName = "";
            Bitmap       icon        = null;
            Type         drawingType = null;
            bool         attached    = true;
            bool         keepToolAfterDrawingCreation = false;
            bool         keepToolAfterFrameChange     = false;
            DrawingStyle style = null;

            while (r.NodeType == XmlNodeType.Element)
            {
                switch (r.Name)
                {
                case "Id":
                    id = new Guid(r.ReadElementContentAsString());
                    break;

                case "Name":
                    name = r.ReadElementContentAsString();
                    break;

                case "DisplayName":
                    displayName = r.ReadElementContentAsString();
                    break;

                case "Icon":
                    string iconReference = r.ReadElementContentAsString();
                    if (!string.IsNullOrEmpty(iconReference))
                    {
                        icon = Properties.Drawings.ResourceManager.GetObject(iconReference) as Bitmap;
                    }
                    break;

                case "DrawingClass":
                    string drawingClass = r.ReadElementContentAsString();
                    drawingType = FindType(drawingClass);
                    break;

                case "Attached":
                    attached = XmlHelper.ParseBoolean(r.ReadElementContentAsString());
                    break;

                case "KeepToolAfterDrawingCreation":
                    keepToolAfterDrawingCreation = XmlHelper.ParseBoolean(r.ReadElementContentAsString());
                    break;

                case "KeepToolAfterFrameChange":
                    keepToolAfterFrameChange = XmlHelper.ParseBoolean(r.ReadElementContentAsString());
                    break;

                case "DefaultStyle":
                    style = new DrawingStyle(r);
                    break;

                default:
                    string unparsed = r.ReadOuterXml();
                    log.DebugFormat("Unparsed content in Drawing Tool XML: {0}", unparsed);
                    break;
                }
            }

            r.ReadEndElement();

            if (icon == null)
            {
                icon = Properties.Drawings.generic_posture;
            }

            DrawingTool tool = new DrawingTool(id, name, displayName, icon, drawingType, attached, keepToolAfterDrawingCreation, keepToolAfterFrameChange, style);

            return(tool);
        }
示例#3
0
 protected virtual void Dispose(bool isDisposing)
 {
     try { activeRequests.Clear(); }
     catch (Exception ex) { _log.ErrorFormat("Failed to dispose LoginPage", activeRequests.Count, ex); }
 }
示例#4
0
        /// <summary>
        /// In the case there being nowhere to start/resume the VM (NO_HOSTS_AVAILABLE), shows the reason why the VM could not be started
        /// on each host. If the start failed due to HA_OPERATION_WOULD_BREAK_FAILOVER_PLAN, offers to decrement ntol and try the operation
        /// again.
        /// </summary>
        /// <param name="vm"></param>
        /// <param name="f"></param>
        /// <param name="kind">The kind of the operation that failed. Must be one of Start/StartOn/Resume/ResumeOn.</param>
        public static void StartDiagnosisForm(VMStartAbstractAction VMStartAction, Failure failure)
        {
            if (failure.ErrorDescription[0] == Failure.NO_HOSTS_AVAILABLE)
            {
                // Show a dialog displaying why the VM couldn't be started on each host
                StartDiagnosisForm(VMStartAction.VM);
            }
            else if (failure.ErrorDescription[0] == Failure.HA_OPERATION_WOULD_BREAK_FAILOVER_PLAN)
            {
                // The action was blocked by HA because it would reduce the number of tolerable server failures.
                // With the user's consent, we'll reduce the number of configured failures to tolerate and try again.
                Pool pool = Helpers.GetPool(VMStartAction.VM.Connection);
                if (pool == null)
                {
                    log.ErrorFormat("Could not get pool for VM {0} in StartDiagnosisForm()", Helpers.GetName(VMStartAction.VM));
                    return;
                }

                long ntol    = pool.ha_host_failures_to_tolerate;
                long newNtol = Math.Min(pool.ha_plan_exists_for - 1, ntol - 1);
                if (newNtol <= 0)
                {
                    // We would need to basically turn HA off to start this VM
                    string msg = String.Format(VMStartAction.IsStart ? Messages.HA_VM_START_NTOL_ZERO : Messages.HA_VM_RESUME_NTOL_ZERO,
                                               Helpers.GetName(pool).Ellipsise(100),
                                               Helpers.GetName(VMStartAction.VM).Ellipsise(100));
                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.HIGH_AVAILABILITY)).ShowDialog(Program.MainWindow);
                    });
                }
                else
                {
                    // Show 'reduce ntol?' dialog
                    string msg = String.Format(VMStartAction.IsStart ? Messages.HA_VM_START_NTOL_DROP : Messages.HA_VM_RESUME_NTOL_DROP,
                                               Helpers.GetName(pool).Ellipsise(100), ntol,
                                               Helpers.GetName(VMStartAction.VM).Ellipsise(100), newNtol);

                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        DialogResult r = new ThreeButtonDialog(
                            new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.HIGH_AVAILABILITY),
                            ThreeButtonDialog.ButtonYes,
                            new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)).ShowDialog(Program.MainWindow);

                        if (r == DialogResult.Yes)
                        {
                            DelegatedAsyncAction action = new DelegatedAsyncAction(VMStartAction.VM.Connection, Messages.HA_LOWERING_NTOL, null, null,
                                                                                   delegate(Session session)
                            {
                                // Set new ntol, then retry action
                                XenAPI.Pool.set_ha_host_failures_to_tolerate(session, pool.opaque_ref, newNtol);
                                // ntol set succeeded, start new action
                                VMStartAction.Clone().RunAsync();
                            });
                            action.RunAsync();
                        }
                    });
                }
            }
        }
示例#5
0
        public void LoadPlugins(MainForm mainForm)
        {
            // Copy ContextMenu
            mainMenu = mainForm.MainMenu;

            List <string> pluginFiles = new List <string>();

            if (IniConfig.IsPortable && Directory.Exists(pafPath))
            {
                foreach (string pluginFile in Directory.GetFiles(pafPath, "*.gsp", SearchOption.AllDirectories))
                {
                    pluginFiles.Add(pluginFile);
                }
            }
            else
            {
                if (Directory.Exists(pluginPath))
                {
                    foreach (string pluginFile in Directory.GetFiles(pluginPath, "*.gsp", SearchOption.AllDirectories))
                    {
                        pluginFiles.Add(pluginFile);
                    }
                }

                if (Directory.Exists(applicationPath))
                {
                    foreach (string pluginFile in Directory.GetFiles(applicationPath, "*.gsp", SearchOption.AllDirectories))
                    {
                        pluginFiles.Add(pluginFile);
                    }
                }
            }

            Dictionary <string, PluginAttribute> tmpAttributes = new Dictionary <string, PluginAttribute>();
            Dictionary <string, Assembly>        tmpAssemblies = new Dictionary <string, Assembly>();

            // Loop over the list of available files and get the Plugin Attributes
            foreach (string pluginFile in pluginFiles)
            {
                LOG.DebugFormat("Checking the following file for plugins: {0}", pluginFile);
                try {
                    Assembly          assembly         = Assembly.LoadFile(pluginFile, Assembly.GetExecutingAssembly().Evidence);
                    PluginAttribute[] pluginAttributes = assembly.GetCustomAttributes(typeof(PluginAttribute), false) as PluginAttribute[];
                    if (pluginAttributes.Length > 0)
                    {
                        PluginAttribute pluginAttribute = pluginAttributes[0];

                        if (string.IsNullOrEmpty(pluginAttribute.Name))
                        {
                            AssemblyProductAttribute[] assemblyProductAttributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false) as AssemblyProductAttribute[];
                            if (assemblyProductAttributes.Length > 0)
                            {
                                pluginAttribute.Name = assemblyProductAttributes[0].Product;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        if (string.IsNullOrEmpty(pluginAttribute.CreatedBy))
                        {
                            AssemblyCompanyAttribute[] assemblyCompanyAttributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false) as AssemblyCompanyAttribute[];
                            if (assemblyCompanyAttributes.Length > 0)
                            {
                                pluginAttribute.CreatedBy = assemblyCompanyAttributes[0].Company;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        pluginAttribute.Version = assembly.GetName().Version.ToString();
                        pluginAttribute.DllFile = pluginFile;

                        // check if this plugin is already available
                        PluginAttribute checkPluginAttribute = null;
                        if (tmpAttributes.ContainsKey(pluginAttribute.Name))
                        {
                            checkPluginAttribute = tmpAttributes[pluginAttribute.Name];
                        }

                        if (checkPluginAttribute != null)
                        {
                            LOG.WarnFormat("Duplicate plugin {0} found", pluginAttribute.Name);
                            if (isNewer(pluginAttribute.Version, checkPluginAttribute.Version))
                            {
                                // Found is newer
                                tmpAttributes[pluginAttribute.Name] = pluginAttribute;
                                tmpAssemblies[pluginAttribute.Name] = assembly;
                                LOG.InfoFormat("Loading the newer plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
                            }
                            else
                            {
                                LOG.InfoFormat("Skipping (as the duplicate is newer or same version) the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
                            }
                            continue;
                        }
                        else
                        {
                            if (conf.ExcludePlugins != null && conf.ExcludePlugins.Contains(pluginAttribute.Name))
                            {
                                LOG.WarnFormat("Exclude list: {0}", conf.ExcludePlugins.ToArray());
                                LOG.WarnFormat("Skipping the excluded plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
                                continue;
                            }
                            if (conf.IncludePlugins != null && conf.IncludePlugins.Count > 0 && !conf.IncludePlugins.Contains(pluginAttribute.Name))
                            {
                                // Whitelist is set
                                LOG.WarnFormat("Include list: {0}", conf.IncludePlugins.ToArray());
                                LOG.WarnFormat("Skipping the not included plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
                                continue;
                            }
                            LOG.InfoFormat("Loading the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
                            tmpAttributes[pluginAttribute.Name] = pluginAttribute;
                            tmpAssemblies[pluginAttribute.Name] = assembly;
                        }
                    }
                    else
                    {
                        LOG.ErrorFormat("Can't find the needed Plugin Attribute ({0}) in the assembly of the file \"{1}\", skipping this file.", typeof(PluginAttribute), pluginFile);
                    }
                } catch (Exception e) {
                    LOG.Warn("Can't load file: " + pluginFile, e);
                }
            }
            foreach (string pluginName in tmpAttributes.Keys)
            {
                try {
                    PluginAttribute pluginAttribute = tmpAttributes[pluginName];
                    Assembly        assembly        = tmpAssemblies[pluginName];
                    Type            entryType       = assembly.GetType(pluginAttribute.EntryType);
                    if (entryType == null)
                    {
                        LOG.ErrorFormat("Can't find the in the PluginAttribute referenced type {0} in \"{1}\"", pluginAttribute.EntryType, pluginAttribute.DllFile);
                        continue;
                    }
                    try {
                        IGreenshotPlugin plugin = (IGreenshotPlugin)Activator.CreateInstance(entryType);
                        if (plugin != null)
                        {
                            if (plugin.Initialize(this, pluginAttribute))
                            {
                                plugins.Add(pluginAttribute, plugin);
                            }
                            else
                            {
                                LOG.InfoFormat("Plugin {0} not initialized!", pluginAttribute.Name);
                            }
                        }
                        else
                        {
                            LOG.ErrorFormat("Can't create an instance of the in the PluginAttribute referenced type {0} from \"{1}\"", pluginAttribute.EntryType, pluginAttribute.DllFile);
                        }
                    } catch (Exception e) {
                        LOG.Error("Can't load Plugin: " + pluginAttribute.Name, e);
                    }
                } catch (Exception e) {
                    LOG.Error("Can't load Plugin: " + pluginName, e);
                }
            }
        }
示例#6
0
 /// <summary>
 /// Logs the error message.
 /// </summary>
 /// <param name="format">The format.</param>
 /// <param name="arg0">The arg0.</param>
 public void ErrorFormat(string format, object arg0)
 {
     m_Log.ErrorFormat(format, arg0);
 }
示例#7
0
        public TDSListener(TDSProxyService service, Configuration.ListenerElement configuration)
        {
            var insideAddresses = Dns.GetHostAddresses(configuration.ForwardToHost);

            if (0 == insideAddresses.Length)
            {
                log.ErrorFormat("Unable to resolve forwardToHost=\"{0}\" for listener {1}", configuration.ForwardToHost, configuration.Name);
                _stopped = true;
                return;
            }
            ForwardTo = new IPEndPoint(insideAddresses.First(), configuration.ForwardToPort);

            _service = service;

            var bindToEP = new IPEndPoint(configuration.BindToAddress ?? IPAddress.Any, configuration.ListenOnPort);

            try
            {
                var catalog = new AssemblyCatalog(configuration.AuthenticatorDll);
                _mefContainer = new CompositionContainer(catalog);
                var exports = _mefContainer.GetExports <IAuthenticator>().ToList();
                var export  = exports.FirstOrDefault(a => a.Value.GetType().FullName == configuration.AuthenticatorClass);
                if (null == export)
                {
                    log.ErrorFormat(
                        "Found dll {0} but not authenticator implementation {1} (DLL exported: {2})",
                        configuration.AuthenticatorDll,
                        configuration.AuthenticatorClass,
                        string.Join("; ", exports.Select(exp => exp.Value.GetType().FullName)));
                    Dispose();
                    return;
                }
                _export       = export;
                Authenticator = _export.Value;
                _mefContainer.ReleaseExports(exports.Where(e => e != _export));
            }
            catch (CompositionException ce)
            {
                log.Error(
                    "Failed to find an authenticator. Composition errors:\r\n\t" +
                    string.Join("\r\n\t", ce.Errors.Select(err => "Element: " + err.Element.DisplayName + ", Error: " + err.Description)),
                    ce);
                Dispose();
                throw;
            }
            catch (Exception e)
            {
                log.Error("Failed to find an authenticator", e);
                Dispose();
                throw;
            }

            try
            {
                log.DebugFormat("Opening SSL certificate store {0}.{1}", configuration.SslCertStoreLocation, configuration.SslCertStoreName);
                var store = new X509Store(configuration.SslCertStoreName, configuration.SslCertStoreLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var matching = store.Certificates.Find(X509FindType.FindByThumbprint, configuration.SslCertSubjectThumbprint, false);
                if (0 == matching.Count)
                {
                    var message = string.Format(
                        "Failed to find SSL certification with thumbprint '{0}' in location {1}, store {2}.",
                        configuration.SslCertSubjectThumbprint,
                        configuration.SslCertStoreLocation,
                        configuration.SslCertStoreName);
                    log.Error(message);
                    Dispose();
                    throw new InvalidOperationException(message);
                }
                Certificate = matching[0];
            }
            catch (Exception e)
            {
                log.Error("Failed to load SSL certificate", e);
                Dispose();
                throw;
            }

            _tcpListener = new TcpListener(bindToEP);
            _tcpListener.Start();
            _tcpListener.BeginAcceptTcpClient(AcceptConnection, _tcpListener);

            _service.AddListener(this);

            log.InfoFormat(
                "Listening on {0} and forwarding to {1} (SSL cert DN {2}; expires {5} serial {3}; authenticator {4})",
                bindToEP,
                ForwardTo,
                Certificate.Subject,
                Certificate.GetSerialNumberString(),
                Authenticator.GetType().FullName,
                Certificate.GetExpirationDateString());
        }
        protected static bool PreloadLootOTDs()
        {
            lock (m_mobOTDList)
            {
                m_mobOTDList.Clear();
                IList <LootOTD> lootOTDs;

                try
                {
                    lootOTDs = GameServer.Database.SelectAllObjects <LootOTD>();
                }
                catch (Exception e)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("LootGeneratorOneTimeDrop: Drops could not be loaded:", e);
                    }

                    return(false);
                }

                if (lootOTDs != null && lootOTDs.Count > 0)
                {
                    int count = 0;

                    foreach (LootOTD l in lootOTDs)
                    {
                        IList <Mob> mobs = GameServer.Database.SelectObjects <Mob>("`Name` = @Name", new QueryParameter("@Name", l.MobName));

                        if (mobs == null || mobs.Count == 0)
                        {
                            log.ErrorFormat("Can't find MobName {0} for OTD {1}", l.MobName, l.ItemTemplateID);
                            continue;
                        }

                        ItemTemplate item = GameServer.Database.FindObjectByKey <ItemTemplate>(l.ItemTemplateID);

                        if (item == null)
                        {
                            log.ErrorFormat("Can't find ItemTemplate {0} for OTD MobName {1}", l.ItemTemplateID, l.MobName);
                            continue;
                        }

                        if (m_mobOTDList.ContainsKey(l.MobName.ToLower()))
                        {
                            List <LootOTD> drops = m_mobOTDList[l.MobName.ToLower()];

                            if (drops.Contains(l) == false)
                            {
                                drops.Add(l);
                                count++;
                            }
                            else
                            {
                                log.ErrorFormat("Same OTD ItemTemplate {0} specified multiple times for MobName {1}", l.ItemTemplateID, l.MobName);
                            }
                        }
                        else
                        {
                            List <LootOTD> drops = new List <LootOTD>();
                            drops.Add(l);
                            m_mobOTDList.Add(l.MobName.ToLower(), drops);
                            count++;
                        }
                    }

                    log.InfoFormat("One Time Drop generator pre-loaded {0} drops.", count);
                }
            }

            return(true);
        }
示例#9
0
 public void ErrorFormat(string format, params object[] args)
 {
     log4netLogger.ErrorFormat(CultureInfo.InvariantCulture, format, args);
 }
示例#10
0
 public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
 {
     _logger.ErrorFormat(formatProvider, format, args);
 }
示例#11
0
        internal static void DumpConsumerGroupOffsets(ConsumeGroupMonitorHelperOptions consumeGroupMonitorOption)
        {
            List <ConsumeGroupMonitorUnit> units = new List <ConsumeGroupMonitorUnit>();

            if (string.IsNullOrEmpty(consumeGroupMonitorOption.ConsumeGroupTopicArray))
            {
                if (!string.IsNullOrEmpty(consumeGroupMonitorOption.ConsumerGroupName))
                {
                    units.Add(new ConsumeGroupMonitorUnit(consumeGroupMonitorOption.File, consumeGroupMonitorOption.ConsumerGroupName, consumeGroupMonitorOption.Topic));
                }
                else
                {
                    danymicAllConsumeGroupTopic = true;
                }
            }
            else
            {
                string[] cgs = consumeGroupMonitorOption.ConsumeGroupTopicArray.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var cg in cgs)
                {
                    string[] temp = cg.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    if (temp.Length != 2)
                    {
                        Logger.ErrorFormat("Wrong parameter, Exmaple  G1:t1,G2:t2.  The value:{0} is invalid.", cg);
                    }
                    else
                    {
                        units.Add(new ConsumeGroupMonitorUnit(string.Format("{0}_{1}_{2}.txt", consumeGroupMonitorOption.File, temp[0], temp[1]), temp[0], temp[1]));
                    }
                }
            }
            long count = 0;
            int  cycle = consumeGroupMonitorOption.RefreshConsumeGroupIntervalInSeconds / consumeGroupMonitorOption.IntervalInSeconds;

            using (ZooKeeperClient zkClient = new ZooKeeperClient(consumeGroupMonitorOption.Zookeeper,
                                                                  ZooKeeperConfiguration.DefaultSessionTimeout, ZooKeeperStringSerializer.Serializer))
            {
                zkClient.Connect();
                while (true)
                {
                    DateTime time       = DateTime.Now;
                    string   dateFolder = string.Format("{0}_{1}_{2}", time.Year, time.Month, time.Day);
                    if (!Directory.Exists(dateFolder))
                    {
                        Directory.CreateDirectory(dateFolder);
                    }

                    if (danymicAllConsumeGroupTopic && count % cycle == 0)
                    {
                        units = new List <ConsumeGroupMonitorUnit>();
                        RefreshConsumeGroup(consumeGroupMonitorOption, zkClient, units);
                    }

                    int countSuccess = 0;
                    foreach (var unit in units)
                    {
                        unit.subFolder = dateFolder;
                        if (unit.Run(zkClient, consumeGroupMonitorOption.Zookeeper))
                        {
                            countSuccess++;
                        }
                    }

                    if (countSuccess == units.Count)
                    {
                        Logger.InfoFormat("===========All {0} consume group PASS=================", countSuccess);
                    }
                    else
                    {
                        Logger.ErrorFormat("===========All {0} consume group only {1} succ.  FAIL=================", units.Count, countSuccess);
                    }

                    Thread.Sleep(consumeGroupMonitorOption.IntervalInSeconds * 1000);
                    count++;
                }
            }
        }
示例#12
0
        /// <summary>
        /// get all part masters
        /// </summary>
        /// <returns></returns>
        public List <IV00101_Part_Master> GetPartMasters()
        {
            var parts = new List <IV00101_Part_Master>();

            try
            {
                parts = _dynamicsContext.IV00101_Part_Master.ToList();
            }
            catch (Exception ex)
            {
                logger.ErrorFormat("Error getting master parts: {0} ", ex.ToString());
            }

            return(parts);
        }
示例#13
0
        public void runUpload(System.Threading.CancellationToken serviceStop)
        {
            DateTime startTime   = DateTime.UtcNow;
            string   uploadToken = "";
            Session  session     = new Session(connection.Hostname, 80);

            session.APIVersion = API_Version.LATEST;

            try
            {
                session.login_with_password(connection.Username, connection.Password);
                connection.LoadCache(session);
                var pool = Helpers.GetPoolOfOne(connection);
                if (pool != null)
                {
                    try
                    {
                        string opaqueref = Secret.get_by_uuid(session, pool.HealthCheckSettings.UploadTokenSecretUuid);
                        uploadToken = Secret.get_value(session, opaqueref);
                    }
                    catch (Exception e)
                    {
                        log.Error("Exception getting the upload token from the xapi secret", e);
                        uploadToken = null;
                    }
                }

                if (string.IsNullOrEmpty(uploadToken))
                {
                    if (session != null)
                    {
                        session.logout();
                    }
                    session = null;
                    log.ErrorFormat("The upload token is not retrieved for {0}", connection.Hostname);
                    updateHealthCheckSettings(false, startTime);
                    server.task = null;
                    ServerListHelper.instance.UpdateServerInfo(server);
                    return;
                }
            }
            catch (Exception e)
            {
                if (session != null)
                {
                    session.logout();
                }
                session = null;
                log.Error(e, e);
                updateHealthCheckSettings(false, startTime);
                server.task = null;
                ServerListHelper.instance.UpdateServerInfo(server);
                return;
            }

            try
            {
                CancellationTokenSource cts    = new CancellationTokenSource();
                Func <string>           upload = delegate()
                {
                    try
                    {
                        return(bundleUpload(connection, session, uploadToken, cts.Token));
                    }
                    catch (OperationCanceledException)
                    {
                        return("");
                    }
                };
                System.Threading.Tasks.Task <string> task = new System.Threading.Tasks.Task <string>(upload);
                task.Start();

                // Check if the task runs to completion before timeout.
                for (int i = 0; i < TIMEOUT; i += INTERVAL)
                {
                    // If the task finishes, set HealthCheckSettings accordingly.
                    if (task.IsCompleted || task.IsCanceled || task.IsFaulted)
                    {
                        if (task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
                        {
                            string upload_uuid = task.Result;
                            if (!string.IsNullOrEmpty(upload_uuid))
                            {
                                updateHealthCheckSettings(true, startTime, upload_uuid);
                            }
                            else
                            {
                                updateHealthCheckSettings(false, startTime);
                            }
                        }
                        else
                        {
                            updateHealthCheckSettings(false, startTime);
                        }

                        server.task = null;
                        ServerListHelper.instance.UpdateServerInfo(server);
                        return;
                    }

                    // If the main thread (XenServerHealthCheckService) stops,
                    // set the cancel token to notify the working task to return.
                    if (serviceStop.IsCancellationRequested)
                    {
                        cts.Cancel();
                        updateHealthCheckSettings(false, startTime);
                        task.Wait();
                        server.task = null;
                        ServerListHelper.instance.UpdateServerInfo(server);
                        return;
                    }

                    System.Threading.Thread.Sleep(INTERVAL);
                }

                // The task has run for 24h, cancel the task and mark it as a failure upload.
                cts.Cancel();
                updateHealthCheckSettings(false, startTime);
                task.Wait();
                server.task = null;
                ServerListHelper.instance.UpdateServerInfo(server);
                return;
            }
            catch (Exception e)
            {
                if (session != null)
                {
                    session.logout();
                }
                session = null;
                log.Error(e, e);
                server.task = null;
                ServerListHelper.instance.UpdateServerInfo(server);
            }
        }
示例#14
0
        public override LootList GenerateLoot(GameNPC mob, GameObject killer)
        {
            LootList loot = base.GenerateLoot(mob, killer);

            try
            {
                GamePlayer player = killer as GamePlayer;
                if (killer is GameNPC && ((GameNPC)killer).Brain is IControlledBrain)
                {
                    player = ((ControlledNpcBrain)((GameNPC)killer).Brain).GetPlayerOwner();
                }
                if (player == null)
                {
                    return(loot);
                }

                // allow the leader to decide the loot realm
                if (player.Group != null)
                {
                    player = player.Group.Leader;
                }

                List <MobDropTemplate> killedMobXLootTemplates;
                // MobDropTemplate contains a loot template name and the max number of drops allowed for that template.
                // We don't need an entry in MobDropTemplate in order to drop loot, only to control the max number of drops.

                // DropTemplateXItemTemplate contains a template name and an itemtemplateid (id_nb).
                // TemplateName usually equals Mob name, so if you want to know what drops for a mob:
                // select * from DropTemplateXItemTemplate where templatename = 'mob name';
                // It is possible to have TemplateName != MobName but this works only if there is an entry in MobDropTemplate for the MobName.
                if (!m_mobXLootTemplates.TryGetValue(mob.Name.ToLower(), out killedMobXLootTemplates))
                {
                    Dictionary <string, DropTemplateXItemTemplate> lootTemplatesToDrop;
                    // We can use DropTemplateXItemTemplate.Count to determine how many of a item can drop
                    if (m_lootTemplates.TryGetValue(mob.Name.ToLower(), out lootTemplatesToDrop))
                    {
                        foreach (DropTemplateXItemTemplate lootTemplate in lootTemplatesToDrop.Values)
                        {
                            ItemTemplate drop = GameServer.Database.FindObjectByKey <ItemTemplate>(lootTemplate.ItemTemplateID);

                            if (drop.Realm == (int)player.Realm || drop.Realm == 0 || player.CanUseCrossRealmItems)
                            {
                                if (lootTemplate.Chance == 100)
                                {
                                    loot.AddFixed(drop, lootTemplate.Count);
                                }
                                else
                                {
                                    loot.AddRandom(lootTemplate.Chance, drop, lootTemplate.Count);
                                }
                            }
                        }
                    }
                }
                else
                {
                    // MobDropTemplate exists and tells us the max number of items that can drop.
                    // Because we are restricting the max number of items to drop we need to traverse the list
                    // and add every 100% chance items to the loots Fixed list and add the rest to the Random list
                    // due to the fact that 100% items always drop regardless of the drop limit
                    List <DropTemplateXItemTemplate> lootTemplatesToDrop = new List <DropTemplateXItemTemplate>();
                    foreach (MobDropTemplate mobXLootTemplate in killedMobXLootTemplates)
                    {
                        loot           = GenerateLootFromMobXLootTemplates(mobXLootTemplate, lootTemplatesToDrop, loot, player);
                        loot.DropCount = Math.Max(mobXLootTemplate.DropCount, loot.DropCount);
                        foreach (DropTemplateXItemTemplate lootTemplate in lootTemplatesToDrop)
                        {
                            ItemTemplate drop = GameServer.Database.FindObjectByKey <ItemTemplate>(lootTemplate.ItemTemplateID);

                            if (drop.Realm == (int)player.Realm || drop.Realm == 0 || player.CanUseCrossRealmItems)
                            {
                                loot.AddRandom(lootTemplate.Chance, drop, lootTemplate.Count);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error in LootGeneratorTemplate for mob {0}.  Exception: {1}", mob.Name, ex.Message);
            }

            return(loot);
        }
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, sr.Name());

            String result;

            log.DebugFormat("Creating vdi of size {0} bytes on SR '{1}'", diskSize, sr.Name());

            VDI          vdi    = NewVDI(sr);
            XenRef <VDI> vdiRef = null;

            try
            {
                vdiRef = VDI.create(Session, vdi);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", "Failed to create VDI", ex.Message);
                throw;
            }

            log.DebugFormat("Uploading file '{0}' to VDI '{1}' on SR '{2}'", suppPackFilePath, vdi.Name(), sr.Name());

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

            if (localStorageHost == null)
            {
                Uri uri = new Uri(Session.Url);
                hostUrl = uri.Host;
            }
            else
            {
                log.DebugFormat("SR is not shared -- redirecting to {0}", localStorageHost.address);
                hostUrl = localStorageHost.address;
            }

            log.DebugFormat("Using {0} for import", hostUrl);

            try
            {
                HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent)
                {
                    var actionPercent = (int)(((totalUploaded * 100) + percent) / totalCount);
                    Tick(actionPercent, Description);
                };

                Session session = NewSession();
                RelatedTask = Task.create(Session, "uploadTask", hostUrl);

                result = HTTPHelper.Put(progressDelegate, GetCancelling, true, Connection, RelatedTask, ref session, suppPackFilePath, hostUrl,
                                        (HTTP_actions.put_sss)HTTP_actions.put_import_raw_vdi,
                                        session.uuid, vdiRef.opaque_ref);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", "Failed to import a virtual disk over HTTP.", ex.Message);

                if (vdiRef != null)
                {
                    log.DebugFormat("Removing the VDI on a best effort basis.");

                    try
                    {
                        RemoveVDI(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        //best effort
                        log.Error("Failed to remove the VDI.", removeEx);
                    }
                }

                //after having tried to remove the VDI, the original exception is thrown for the UI
                if (ex is TargetInvocationException && ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw ex;
                }
            }
            finally
            {
                Task.destroy(Session, RelatedTask);
                RelatedTask = null;
            }

            if (localStorageHost != null)
            {
                VdiRefsToCleanUp.Add(localStorageHost, vdiRef);
            }
            else // shared SR
            {
                foreach (var server in servers)
                {
                    VdiRefsToCleanUp.Add(server, vdiRef);
                }
            }

            //introduce ISO for Ely and higher
            if (Helpers.ElyOrGreater(Connection))
            {
                try
                {
                    var poolUpdateRef = Pool_update.introduce(Connection.Session, vdiRef);
                    poolUpdate = Connection.WaitForCache(poolUpdateRef);

                    if (poolUpdate == null)
                    {
                        throw new Exception(Messages.UPDATE_ERROR_INTRODUCE); // This should not happen, because such case will result in a XAPI Failure. But this code has to be protected at this point.
                    }
                    VdiRefsToCleanUp.Clear();
                }
                catch (Failure ex)
                {
                    if (ex.ErrorDescription != null && ex.ErrorDescription.Count > 1 && string.Equals("UPDATE_ALREADY_EXISTS", ex.ErrorDescription[0], StringComparison.InvariantCultureIgnoreCase))
                    {
                        string uuidFound = ex.ErrorDescription[1];

                        poolUpdate = Connection.Cache.Pool_updates.FirstOrDefault(pu => string.Equals(pu.uuid, uuidFound, System.StringComparison.InvariantCultureIgnoreCase));

                        //clean-up the VDI we've just created
                        try
                        {
                            RemoveVDI(Session, vdiRef);

                            //remove the vdi that have just been cleaned up
                            var remaining = VdiRefsToCleanUp.Where(kvp => kvp.Value != null && kvp.Value.opaque_ref != vdiRef.opaque_ref).ToList();
                            VdiRefsToCleanUp.Clear();
                            remaining.ForEach(rem => VdiRefsToCleanUp.Add(rem.Key, rem.Value));
                        }
                        catch
                        {
                            //best effort cleanup
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("Upload failed when introducing update from VDI {0} on {1}: {2}", vdi.opaque_ref, Connection, ex.Message);
                    poolUpdate = null;

                    throw;
                }
            }
            else
            {
                poolUpdate = null;
            }

            totalUploaded++;
            Description = String.Format(Messages.SUPP_PACK_UPLOADED, sr.Name());
            return(result);
        }
        private void DownloadFile()
        {
            int  errorCount  = 0;
            int  nextSleepMs = 0;
            bool needToRetry = true;

            while (errorCount < MAX_NUMBER_OF_TRIES && needToRetry)
            {
                needToRetry = false;

                using (var client = new WebClient())
                {
                    try
                    {
                        //register download events
                        client.DownloadProgressChanged += client_DownloadProgressChanged;
                        client.DownloadFileCompleted   += client_DownloadFileCompleted;
                        //start the download
                        client.DownloadFileAsync(address, outFileName);

                        patchDownloadState = DownloadState.InProgress;
                        bool patchDownloadCancelling = false;

                        //wait for the file to be downloaded
                        while (patchDownloadState == DownloadState.InProgress)
                        {
                            if (!patchDownloadCancelling && (Cancelling || Cancelled))
                            {
                                Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC;
                                client.CancelAsync();
                                patchDownloadCancelling = true;
                            }
                            Thread.Sleep(SLEEP_TIME_TO_CHECK_DOWNLOAD_STATUS_MS);
                        }

                        if (patchDownloadState == DownloadState.Cancelled)
                        {
                            throw new CancelledException();
                        }

                        if (patchDownloadState == DownloadState.Error)
                        {
                            needToRetry = true;

                            // this many errors so far - including this one
                            errorCount++;

                            // logging only, it will retry again.
                            log.ErrorFormat("Error while downloading from '{0}'. Number of errors so far (including this): {1}. Trying maximum {2} times.", address, errorCount, MAX_NUMBER_OF_TRIES);
                            log.Error(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN));

                            // wait for some randomly increased amount of time after each retry
                            nextSleepMs += random.Next(5000);
                            Thread.Sleep(nextSleepMs);
                        }
                    }
                    finally
                    {
                        //deregister download events
                        client.DownloadProgressChanged -= client_DownloadProgressChanged;
                        client.DownloadFileCompleted   -= client_DownloadFileCompleted;
                    }
                }
            }

            //if this is still the case after having retried MAX_RETRY number of times.
            if (patchDownloadState == DownloadState.Error)
            {
                log.ErrorFormat("Giving up - MAX_NUMBER_OF_RETRIES_IF_FAILED has been reached.");

                MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN));
            }
        }
        /// <summary>
        /// 使用串口发送检测命令,等待检测板返回数据
        /// </summary>
        /// <param name="command">命令字节</param>
        /// <param name="timeOutValue">超时时间,以ms为单位</param>
        /// <returns>检测板返回的数据</returns>
        private byte[] WriteCommand(byte[] command, int timeOutValue)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Settings.Default.Language);

            if (serialPort == null || !serialPort.IsOpen)
            {
                throw new CommunicationException(Resources.SerialPortNoOpen);
            }

            for (int i = 0; i < retransmissionCount; i++)  //检测板未回复消息 则重传retransmissionCount次
            {
                try
                {
                    serialPort.Write(command, 0, command.Length);//发送数据
                }
                catch (Exception ex)
                {
                    throw new CommunicationException(ex.Message);
                }

                //阻塞,直到检测板返回数据
                bool waitResult = WaitForByte(timeOutValue);

                if (waitResult)
                {
                    break;
                }

                if (!waitResult && i < retransmissionCount - 1)
                {
                    continue;
                }
                else
                {
                    throw new CommunicationException(Resources.PcbTesterClient_NoBoard);
                }
            }

            //开一个足够大的buffer,用于读串口数据
            byte[] buffer = new byte[4096];
            int    length = 0;

            while (true)
            {
                try
                {
                    length += serialPort.Read(buffer, length, buffer.Length - length);//将每次读到的字节数做累加,得到总共读到的字节数
                    if (IsIecComplete(buffer, length))
                    {
                        byte[] result = new byte[length];

                        Array.Copy(buffer, 0, result, 0, result.Length);
                        logger.DebugFormat("Received bytes:{0}", Microstar.Utility.Hex.ToString(result, 0, result.Length));
                        return(result);
                    }
                }

                catch (TimeoutException ex)
                {
                    byte[] result = new byte[length];

                    Array.Copy(buffer, 0, result, 0, result.Length);
                    logger.ErrorFormat("TimeoutException, Received bytes:{0}", Microstar.Utility.Hex.ToString(result, 0, result.Length));
                    throw new CommunicationException(ex.Message);
                }
            }
        }
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var account = AccountService.GetAccountByProfileId(QueryUserId);

            if (account == null)
            {
                _logger.ErrorFormat("Account could not be loaded. Account ID={{{0}}}", QueryUserId);
                Response.Redirect("/customer/customer_default.aspx?" + QueryKey.MSG_TYPE + "=" + (int)MessageType.AccountNotLoaded);
            }

            account.Name          = txtName.Text.Trim();
            account.DOB           = txtDOB.Text.Trim();
            account.ContactNumber = txtPhone.Text.Trim();
            account.DisplayContactNumberInDespatch = cbDisplayContactNumber.Checked;
            account.Note  = txtNote.Text.Trim();
            account.Email = txtUsername.Text.Trim();

            // Set roles
            var isAdministrator = Roles.IsUserInRole("Administrator");

            if (isAdministrator)
            {
                List <string> roles = new List <string>();
                for (int i = 0; i < cblRoles.Items.Count; i++)
                {
                    if (cblRoles.Items[i].Selected)
                    {
                        roles.Add(cblRoles.Items[i].Value);
                    }
                }

                account.Roles = roles.ToArray();
            }

            string newPassword = string.Empty;

            // TODO: Need to change for setting/adding password
            // Set new password
            if (txtPwd.Text.Trim() != string.Empty && !cbSendAutoPwd.Checked)
            {
                newPassword = txtPwd.Text.Trim();
            }

            // TODO: Need to change for setting/adding password
            // Auto generate password
            if (cbSendAutoPwd.Checked)
            {
                newPassword = AdminStoreUtility.GenerateRandomPasswordGUID(8);
            }

            var points = Convert.ToInt32(txtLoyaltyPoint.Text.Trim());

            var result  = AccountService.ProcessAccountUpdate(account, points, cbNewUsername.Checked);
            var message = string.Empty;

            switch (result)
            {
            case AccountUpdateResults.Successful:
                message = "Account was updated successfully.";
                break;

            case AccountUpdateResults.MemberNotExist:
                message = "Account was failed to update. Membership could not be found.";
                break;

            case AccountUpdateResults.ExistingEmail:
                message = "Account was failed to update. Another existing membership with same email is found.";
                break;

            default:
                break;
            }

            txtPwd.Text                 = string.Empty;
            cbSendAutoPwd.Checked       = false;
            cbNotificationEmail.Checked = false;

            enbNotice.Message = message;
        }
示例#19
0
        public Subscriber.Listener.ListenerResponse NotifyEvent(Subscriber.Listener.ListenerRequest request)
        {
            _logger.Info("BEGIN");

            Subscriber.Listener.ListenerResponse response = new Subscriber.Listener.ListenerResponse();

            try
            {
                List <Subscriber.Rules.RuleResponse> ruleResponseList = new List <Subscriber.Rules.RuleResponse>();

                // Reperimento delle regole definite per l'istanza
                RuleInfo[] instanceRules = Subscriber.DataAccess.RuleDataAdapter.GetRules(request.ChannelInfo.Id);

                if (instanceRules != null)
                {
                    foreach (RuleInfo r in instanceRules)
                    {
                        Type t = Type.GetType(r.RuleClassFullName, false);

                        if (t == null)
                        {
                            // Regola non istanziata
                            _logger.ErrorFormat(string.Format(ErrorDescriptions.INVALID_RULE_TYPE, r.RuleClassFullName));

                            r.Error = new ErrorInfo
                            {
                                Id      = ErrorCodes.INVALID_RULE_TYPE,
                                Message = string.Format(ErrorDescriptions.INVALID_RULE_TYPE, r.RuleClassFullName)
                            };

                            ruleResponseList.Add(new Rules.RuleResponse
                            {
                                Rule = r
                            });
                        }
                        else
                        {
                            // Esecuzione delle azioni che estendono la classe astratta "AvvocaturaBaseRule"
                            using (Subscriber.Rules.IRule rule = (Subscriber.Rules.IRule)Activator.CreateInstance(t))
                            {
                                _logger.InfoFormat("Creazione RULE '{0}'", rule.GetType().FullName);

                                // Inizializzazione ed esecuzione della regola
                                rule.InitializeRule(request, r);

                                _logger.InfoFormat("Inizializzazione RULE '{0}'", rule.GetType().FullName);

                                if (rule.Response.Rule.Enabled)
                                {
                                    _logger.InfoFormat("RULE '{0}' abilitata", rule.GetType().FullName);

                                    // Se la regola risulta abilitata, viene eseguita
                                    rule.Execute();

                                    _logger.InfoFormat("RULE '{0}' eseguita", rule.GetType().FullName);

                                    // Esito del calcolo della regola
                                    Subscriber.Rules.RuleResponse ruleResponse = rule.Response;

                                    ruleResponseList.Add(ruleResponse);
                                }
                                else
                                {
                                    _logger.InfoFormat("RULE '{0}' non abilitata", rule.GetType().FullName);
                                }
                            }
                        }
                    }
                }

                // Esito dell'esecuzione delle regole
                response.RuleResponseList = ruleResponseList.ToArray();
            }
            catch (Exception ex)
            {
                // Errore non gestito nel listener

                _logger.Error(ex.Message, ex);

                response.Error = new ErrorInfo
                {
                    Id      = ErrorCodes.UNHANDLED_ERROR,
                    Message = ex.Message,
                    Stack   = ex.ToString()
                };
            }
            finally
            {
                _logger.Info("END");
            }

            return(response);
        }
示例#20
0
 private void LogError(Exception e, string additionalErrorMessage)
 {
     log.ErrorFormat("Error received trying to get a thumbnail for {0}", summary.Alias);
     log.Error(e.ToString());
     log.Error(additionalErrorMessage);
 }
        private SpecificInfo SpecificInfoDeserialize(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return(null);
            }

            SpecificInfo info = null;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(new StringReader(xml));

                info = new SpecificInfo();

                float selectedFramerate = -1;
                int   index             = -1;

                XmlNode xmlSelectedFrameRate = doc.SelectSingleNode("/DirectShow/SelectedFramerate");
                if (xmlSelectedFrameRate != null)
                {
                    selectedFramerate = float.Parse(xmlSelectedFrameRate.InnerText, CultureInfo.InvariantCulture);
                }

                XmlNode xmlIndex = doc.SelectSingleNode("/DirectShow/MediaTypeIndex");
                if (xmlIndex != null)
                {
                    index = int.Parse(xmlIndex.InnerText, CultureInfo.InvariantCulture);
                }

                Dictionary <string, CameraProperty> cameraProperties = new Dictionary <string, CameraProperty>();

                XmlNodeList props = doc.SelectNodes("/DirectShow/CameraProperties/CameraProperty2");
                foreach (XmlNode node in props)
                {
                    XmlAttribute keyAttribute = node.Attributes["key"];
                    if (keyAttribute == null)
                    {
                        continue;
                    }

                    string         key      = keyAttribute.Value;
                    CameraProperty property = new CameraProperty();
                    property.Supported = true;

                    string  xpath            = string.Format("/DirectShow/CameraProperties/CameraProperty2[@key='{0}']", key);
                    XmlNode xmlPropertyValue = doc.SelectSingleNode(xpath + "/Value");
                    if (xmlPropertyValue != null)
                    {
                        property.CurrentValue = xmlPropertyValue.InnerText;
                    }
                    else
                    {
                        property.Supported = false;
                    }

                    XmlNode xmlPropertyAuto = doc.SelectSingleNode(xpath + "/Auto");
                    if (xmlPropertyAuto != null)
                    {
                        property.Automatic = XmlHelper.ParseBoolean(xmlPropertyAuto.InnerText);
                    }
                    else
                    {
                        property.Supported = false;
                    }

                    cameraProperties.Add(key, property);
                }

                info.MediaTypeIndex    = index;
                info.SelectedFramerate = selectedFramerate;
                info.CameraProperties  = cameraProperties;
            }
            catch (Exception e)
            {
                log.ErrorFormat(e.Message);
            }

            return(info);
        }
        private void DownloadFile()
        {
            int  errorCount  = 0;
            bool needToRetry = false;

            client = new WebClient();
            //register download events
            client.DownloadProgressChanged += client_DownloadProgressChanged;
            client.DownloadFileCompleted   += client_DownloadFileCompleted;

            // register event handler to detect changes in network connectivity
            NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChanged;

            try
            {
                do
                {
                    if (needToRetry)
                    {
                        Thread.Sleep(SLEEP_TIME_BEFORE_RETRY_MS);
                    }

                    needToRetry = false;

                    client.Proxy = XenAdminConfigManager.Provider.GetProxyFromSettings(null, false);

                    //start the download
                    patchDownloadState = DownloadState.InProgress;
                    client.DownloadFileAsync(address, outputFileName);

                    bool patchDownloadCancelling = false;

                    //wait for the file to be downloaded
                    while (patchDownloadState == DownloadState.InProgress)
                    {
                        if (!patchDownloadCancelling && (Cancelling || Cancelled))
                        {
                            Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC;
                            client.CancelAsync();
                            patchDownloadCancelling = true;
                        }

                        Thread.Sleep(SLEEP_TIME_TO_CHECK_DOWNLOAD_STATUS_MS);
                    }

                    if (patchDownloadState == DownloadState.Cancelled)
                    {
                        throw new CancelledException();
                    }

                    if (patchDownloadState == DownloadState.Error)
                    {
                        needToRetry = true;

                        // this many errors so far - including this one
                        errorCount++;

                        // logging only, it will retry again.
                        log.ErrorFormat(
                            "Error while downloading from '{0}'. Number of errors so far (including this): {1}. Trying maximum {2} times.",
                            address, errorCount, MAX_NUMBER_OF_TRIES);
                        log.Error(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN));
                    }
                } while (errorCount < MAX_NUMBER_OF_TRIES && needToRetry);
            }
            finally
            {
                //deregister download events
                client.DownloadProgressChanged -= client_DownloadProgressChanged;
                client.DownloadFileCompleted   -= client_DownloadFileCompleted;

                NetworkChange.NetworkAvailabilityChanged -= NetworkAvailabilityChanged;

                client.Dispose();
            }

            //if this is still the case after having retried MAX_NUMBER_OF_TRIES number of times.
            if (patchDownloadState == DownloadState.Error)
            {
                log.ErrorFormat("Giving up - Maximum number of retries ({0}) has been reached.", MAX_NUMBER_OF_TRIES);

                MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN));
            }
        }
示例#23
0
        private static void LoadInSpecificTarget(ScreenManagerKernel manager, int targetScreen, string path, ScreenDescriptionPlayback screenDescription)
        {
            AbstractScreen screen = manager.GetScreenAt(targetScreen);

            if (screen is CaptureScreen)
            {
                // Loading a video onto a capture screen should not close the capture screen.
                // If there is room to add a second screen, we add a playback screen and load the video there, otherwise, we don't do anything.
                if (manager.ScreenCount == 1)
                {
                    manager.AddPlayerScreen();
                    manager.UpdateCaptureBuffers();
                    LoadInSpecificTarget(manager, 1, path, screenDescription);
                }
            }
            else if (screen is PlayerScreen)
            {
                PlayerScreen playerScreen = screen as PlayerScreen;

                if (playerScreen.IsWaitingForIdle)
                {
                    // The player screen will yield its thread after having loaded the first frame and come back later.
                    // We must not launch a new video while it's waiting.
                    log.ErrorFormat("Player screen is currently busy loading the previous video. Aborting load.");
                    return;
                }

                bool confirmed = manager.BeforeReplacingPlayerContent(targetScreen);
                if (!confirmed)
                {
                    return;
                }

                LoadVideo(playerScreen, path, screenDescription);

                bool prefsNeedSaving = false;
                if (screenDescription != null && screenDescription.IsReplayWatcher)
                {
                    PreferencesManager.FileExplorerPreferences.AddRecentWatcher(path);
                    PreferencesManager.FileExplorerPreferences.LastReplayFolder = path;
                    prefsNeedSaving = true;
                }

                if (playerScreen.FrameServer.Loaded)
                {
                    NotificationCenter.RaiseFileOpened(null, path);

                    if (screenDescription != null && screenDescription.IsReplayWatcher)
                    {
                        // At this point we have lost the actual file that was loaded. The path here still contaiins the special '*' to indicate the watched folder.
                        // The actual file is the latest file in the folder this was computed right before loading.
                        string actualPath = FilesystemHelper.GetMostRecentFile(Path.GetDirectoryName(path));
                        PreferencesManager.FileExplorerPreferences.AddRecentFile(actualPath);
                    }
                    else
                    {
                        PreferencesManager.FileExplorerPreferences.AddRecentFile(path);
                    }

                    prefsNeedSaving = true;
                }

                if (prefsNeedSaving)
                {
                    PreferencesManager.Save();
                }

                manager.OrganizeScreens();
                manager.OrganizeCommonControls();
                manager.OrganizeMenus();
                manager.UpdateStatusBar();
            }
        }
        public PhoneData Query(string number, PhoneData data, Dictionary <PhoneData, string> values)
        {
            PhoneData left = data;

            string uri = string.Format(URI, number);

            List <KeyValuePair <string, string> > headers = new List <KeyValuePair <string, string> >();

            headers.Add(new KeyValuePair <string, string>("Authorization", string.Format("APPCODE {0}", APPCode)));

            byte[] bytes = HttpClient.Post(uri, headers);
            string json  = Encoding.UTF8.GetString(bytes);

            JToken token = JsonConvert.DeserializeObject(json) as JToken;
            int    code  = token["code"].Value <int>();

            if (code != 0)
            {
                string reason = token["reason"].ToString();
                logger.ErrorFormat("访问阿里云服务失败, code = {0}, reason = {1}", code, reason);
                return(left);
            }

            if (data.HasFlag(PhoneData.City))
            {
                values[PhoneData.City] = token["result"]["Area"].ToString();
                left &= ~PhoneData.City;
            }

            if (data.HasFlag(PhoneData.CurrentISP))
            {
                values[PhoneData.CurrentISP] = token["result"]["Now_isp"].ToString();
                left &= ~PhoneData.CurrentISP;
            }

            if (data.HasFlag(PhoneData.IsVirtual))
            {
                string res = token["result"]["res"].ToString();
                if (res == "0")
                {
                    // 没转网
                    values[PhoneData.IsVirtual] = "false";
                }
                else if (res == "3" || res == "4")
                {
                    values[PhoneData.IsVirtual] = "true";
                }
                else if (res == "1")
                {
                    values[PhoneData.IsVirtual] = "false";
                }

                left &= ~PhoneData.IsVirtual;
            }

            if (data.HasFlag(PhoneData.OrignalISP) || data.HasFlag(PhoneData.Transfered))
            {
                string res = token["result"]["res"].ToString();
                if (res == "1")
                {
                    // 转网后才有原始运营商
                    values[PhoneData.OrignalISP] = token["result"]["Init_isp"].ToString();
                    values[PhoneData.Transfered] = "true";
                }
                else
                {
                    values[PhoneData.OrignalISP] = token["result"]["Init_isp"].ToString();
                    values[PhoneData.Transfered] = "false";
                }
                left &= ~PhoneData.OrignalISP;
                left &= ~PhoneData.Transfered;
            }

            return(left);
        }
 private void LogError(Exception e, string additionalErrorMessage)
 {
     log.ErrorFormat("Error during Basler camera operation. {0}", summary.Alias);
     log.Error(e.ToString());
     log.Error(additionalErrorMessage);
 }
示例#26
0
        /// <summary>
        /// LogUserLogin - This method retrieves data from LDAP and update the UserData object in the database
        /// </summary>
        /// <param name="userData">UserData - users data from UserData table</param>
        /// <param name="UpdateLastLogin">bool - default value is true</param>
        /// <returns>UserData - updated with current LDAP data</returns>
        public UserData LogUserLogin(UserData userData, bool UpdateLastLogin = true)
        {
            string         ManagerDNID = null;
            string         ManagerEID  = null;
            string         EmployeeEID = null;
            LdapProcessing LDAP        = new LdapProcessing();

            string domainID = userData.UserDomain.ToString() + ":" + userData.UserNTID.ToString();

            try
            {
                // Define Properties to Return
                // These properties are defined in your local LDAP and the values are returned from the directory search

                string ADManagerEmailProperty = "manager";
                string ADOProperty            = "hpOrganizationChart";
                string ABUProperty            = "hpBusinessGroup";
                string ADCNProperty           = "cn";
                string ADCNManagerNum         = "managerEmployeeNumber";
                string ADEmailProperty        = "mail";

                // Load the Properties into a list of strings
                List <string> loadProperties = new List <string>();
                loadProperties.Add(ADManagerEmailProperty);
                loadProperties.Add(ADOProperty);
                loadProperties.Add(ABUProperty);
                loadProperties.Add(ADCNProperty);
                loadProperties.Add(ADCNManagerNum);
                loadProperties.Add(ADEmailProperty);

                // Search for the User
                SearchResult result = LDAP.FormatAndSearchForUser("ntuserdomainid", domainID, loadProperties);

                // Found the User
                if (result != null)
                {
                    // Parse name into first/last
                    string[] names     = result.Properties[ADCNProperty][0].ToString().Split(' ');
                    string   firstName = null;
                    string   lastName  = null;

                    foreach (string name in names)
                    {
                        if (firstName != null)
                        {
                            lastName = lastName + name + " ";
                        }
                        else
                        {
                            firstName = name;
                        }
                    }

                    if (firstName != null)
                    {
                        userData.FirstName = firstName.Trim();
                    }
                    else
                    {
                        userData.FirstName = "";
                    }

                    if (lastName != null)
                    {
                        userData.LastName = lastName.Trim();
                    }
                    else
                    {
                        userData.LastName = "";
                    }


                    // Get Manager, Organization, Business Unit
                    ManagerDNID           = result.Properties[ADManagerEmailProperty][0].ToString();
                    userData.OrgName      = result.Properties[ADOProperty][0].ToString();
                    userData.BusinessUnit = result.Properties[ABUProperty][0].ToString();

                    userData.ManagerEID = result.Properties[ADCNManagerNum][0].ToString();
                    ManagerEID          = result.Properties[ADCNManagerNum][0].ToString();
                    EmployeeEID         = result.Properties[ADEmailProperty][0].ToString();
                }
                else
                {
                    // User Not Found
                    logger.ErrorFormat("User {0} Not Found in LDAP", domainID);
                    throw new ApplicationException("User Not Found in LDAP: " + domainID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw new ApplicationException("Error LDAPInterface.GetUserWithDomainIdentity: " + Environment.NewLine + "User: "******"ntuserdomainid";
                    string ADMgrCNProperty     = "cn";

                    // Load the Properties to Load
                    List <string> loadProperties = new List <string>();
                    loadProperties.Add(ADManagerIDProperty);
                    loadProperties.Add(ADMgrCNProperty);

                    // Search for the Manager info using Employee Number
                    SearchResult result = LDAP.FormatAndSearchForEID("employeeNumber", ManagerEID, loadProperties);

                    // Found the User
                    if (result != null)
                    {
                        string[] names        = result.Properties[ADMgrCNProperty][0].ToString().Split(' ');
                        string   MGRfirstName = null;
                        string   MGRlastName  = null;

                        foreach (string name in names)
                        {
                            if (MGRfirstName != null)
                            {
                                MGRlastName = MGRlastName + name + " ";
                            }
                            else
                            {
                                MGRfirstName = name;
                            }
                        }

                        if (MGRfirstName != null)
                        {
                            userData.MgrFirstName = MGRfirstName.Trim();
                        }
                        else
                        {
                            userData.MgrFirstName = "";
                        }

                        if (MGRlastName != null)
                        {
                            userData.MgrLastName = MGRlastName.Trim();
                        }
                        else
                        {
                            userData.MgrLastName = "";
                        }

                        userData.ManagerID = result.Properties[ADManagerIDProperty][0].ToString().Replace(@":", @"\").ToUpper();
                    }
                    else
                    {
                        // User Not Found
                        throw new ApplicationException("Manager Not Found in AD: " + ManagerEID);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);

                    // Error in Search
                    throw new ApplicationException("Error LDAPInterface.FormatAndSearchForEmail: " + Environment.NewLine + "Mgr Email: " + ManagerEID, ex);
                }
            }


            // Now check to see if the user belongs to either the Admin Group or the Business Unit Owner LDAP groups
            bool GCSOwaspSAMMUser = false;

            List <string> SAMMGroups = new List <string>();

            SAMMGroups.Add(System.Web.Configuration.WebConfigurationManager.AppSettings["LDAPAdminGroup"]);

            SortedList <string, List <string> > tempSAMMGroupsMembers = new SortedList <string, List <string> >(StringComparer.OrdinalIgnoreCase);

            // Get the Members
            LDAP.GetMembers(SAMMGroups, tempSAMMGroupsMembers);

            // Process all the Groups for the Role
            foreach (string SAMMGroup in SAMMGroups)
            {
                // Find the Group in the Group/Members List
                List <string> members = tempSAMMGroupsMembers[SAMMGroup];

                // Interrogate the list for this group to see if the current users email is in it
                foreach (string member in members)
                {
                    // If users email is found set Boolean to true
                    if (member == EmployeeEID)
                    {
                        GCSOwaspSAMMUser = true;
                    }
                }
            }


            // Business Unit Owner LDAP group
            bool GCSSAMMBURep = false;

            SAMMGroups = new List <string>();
            SAMMGroups.Add(System.Web.Configuration.WebConfigurationManager.AppSettings["LDAPBUOwnerGroup"]);

            tempSAMMGroupsMembers = new SortedList <string, List <string> >(StringComparer.OrdinalIgnoreCase);

            // Get the Members
            LDAP.GetMembers(SAMMGroups, tempSAMMGroupsMembers);

            // Process all the Groups for the Role
            foreach (string SAMMGroup in SAMMGroups)
            {
                // Find the Group in the Group/Members List
                List <string> members = tempSAMMGroupsMembers[SAMMGroup];

                // Interrogate the list for this group to see if the current users email is in it
                foreach (string member in members)
                {
                    // If users email is found set Boolean to true
                    if (member == EmployeeEID)
                    {
                        GCSSAMMBURep = true;
                    }
                }
            }

            userData.Manager       = DAL.IsUserAManager(userData.UserID);
            userData.BUOwner       = GCSSAMMBURep;
            userData.Administrator = GCSOwaspSAMMUser;

            if (UpdateLastLogin)
            {
                userData.LastLoginDate = DateTime.Now;
            }

            var success = DAL.UpdateUserData(userData);

            return(userData);
        }
示例#27
0
        protected override void Run()
        {
            SafeToExit = false;
            bool isTemplate;

            try
            {
                string vmRef;

                if (m_filename.EndsWith("ova.xml"))                //importing version 1 from of VM
                {
                    m_filename = m_filename.Replace("ova.xml", "");
                    vmRef      = GetVmRef(applyVersionOneFiles());
                }
                else                //importing current format of VM
                {
                    vmRef = GetVmRef(applyFile());
                }

                if (Cancelling)
                {
                    throw new CancelledException();
                }

                // Now lets try and set the affinity and start the VM

                if (string.IsNullOrEmpty(vmRef))
                {
                    return;
                }

                while (!Cancelling && (VM = Connection.Resolve(new XenRef <VM>(vmRef))) == null)
                {
                    Thread.Sleep(100);
                }

                if (Cancelling)
                {
                    throw new CancelledException();
                }

                isTemplate  = VM.get_is_a_template(Session, vmRef);
                Description = isTemplate ? Messages.IMPORT_TEMPLATE_UPDATING_TEMPLATE : Messages.IMPORTVM_UPDATING_VM;
                VM.set_name_label(Session, vmRef, DefaultVMName(VM.get_name_label(Session, vmRef)));

                if (!isTemplate && m_affinity != null)
                {
                    VM.set_affinity(Session, vmRef, m_affinity.opaque_ref);
                }

                // Wait here for the wizard to finish
                Description = isTemplate ? Messages.IMPORT_TEMPLATE_WAITING_FOR_WIZARD : Messages.IMPORTVM_WAITING_FOR_WIZARD;
                lock (monitor)
                {
                    while (!(m_wizardDone || Cancelling))
                    {
                        Monitor.Wait(monitor);
                    }
                }

                if (Cancelling)
                {
                    throw new CancelledException();
                }

                if (m_proxyVIFs != null)
                {
                    Description = isTemplate ? Messages.IMPORT_TEMPLATE_UPDATING_NETWORKS : Messages.IMPORTVM_UPDATING_NETWORKS;

                    // For ElyOrGreater hosts, we can move the VIFs to another network,
                    // but for older hosts we need to destroy all vifs and recreate them

                    List <XenRef <VIF> >  vifs     = VM.get_VIFs(Session, vmRef);
                    List <XenAPI.Network> networks = new List <XenAPI.Network>();

                    bool canMoveVifs = Helpers.ElyOrGreater(Connection);

                    foreach (XenRef <VIF> vif in vifs)
                    {
                        // Save the network as we may have to delete it later
                        XenAPI.Network network = Connection.Resolve(VIF.get_network(Session, vif));
                        if (network != null)
                        {
                            networks.Add(network);
                        }

                        if (canMoveVifs)
                        {
                            var vifObj = Connection.Resolve(vif);
                            if (vifObj == null)
                            {
                                continue;
                            }
                            // try to find a matching VIF in the m_proxyVIFs list, based on the device field
                            var matchingProxyVif = m_proxyVIFs.FirstOrDefault(proxyVIF => proxyVIF.device == vifObj.device);
                            if (matchingProxyVif != null)
                            {
                                // move the VIF to the desired network
                                VIF.move(Session, vif, matchingProxyVif.network);
                                // remove matchingProxyVif from the list, so we don't create the VIF again later
                                m_proxyVIFs.Remove(matchingProxyVif);
                                continue;
                            }
                        }
                        // destroy the VIF, if we haven't managed to move it
                        VIF.destroy(Session, vif);
                    }

                    // recreate VIFs if needed (m_proxyVIFs can be empty, if we moved all the VIFs in the previous step)
                    foreach (Proxy_VIF proxyVIF in m_proxyVIFs)
                    {
                        VIF vif = new VIF(proxyVIF)
                        {
                            VM = new XenRef <VM>(vmRef)
                        };
                        VIF.create(Session, vif);
                    }

                    // now delete any Networks associated with this task if they have no VIFs

                    foreach (XenAPI.Network network in networks)
                    {
                        if (!network.other_config.ContainsKey(IMPORT_TASK))
                        {
                            continue;
                        }

                        if (network.other_config[IMPORT_TASK] != RelatedTask.opaque_ref)
                        {
                            continue;
                        }

                        try
                        {
                            if (XenAPI.Network.get_VIFs(Session, network.opaque_ref).Count > 0)
                            {
                                continue;
                            }

                            if (XenAPI.Network.get_PIFs(Session, network.opaque_ref).Count > 0)
                            {
                                continue;
                            }

                            XenAPI.Network.destroy(Session, network.opaque_ref);
                        }
                        catch (Exception e)
                        {
                            log.ErrorFormat("Exception while deleting network {0}. Squashing.", network.Name);
                            log.Error(e, e);
                        }
                    }
                }

                if (!VM.get_is_a_template(Session, vmRef))
                {
                    if (m_startAutomatically)
                    {
                        Description = Messages.IMPORTVM_STARTING;
                        VM.start(Session, vmRef, false, false);
                    }
                }
            }
            catch (CancelledException)
            {
                Description = Messages.CANCELLED_BY_USER;
                throw;
            }

            Description = isTemplate ? Messages.IMPORT_TEMPLATE_IMPORTCOMPLETE : Messages.IMPORTVM_IMPORTCOMPLETE;
        }
示例#28
0
 public void ErrorFormat(string format, params object[] args)
 {
     _log.ErrorFormat(format, args);
 }
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, _updateName, sr.Name());
            log.DebugFormat("Creating vdi of size {0} bytes on SR '{1}'", _totalUpdateSize, sr.Name());

            VDI vdi    = NewVDI(sr);
            var vdiRef = VDI.create(Session, vdi);

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

            if (localStorageHost == null)
            {
                Uri uri = new Uri(Session.Url);
                hostUrl = uri.Host;
            }
            else
            {
                log.DebugFormat("SR is not shared -- redirecting to {0}", localStorageHost.address);
                hostUrl = localStorageHost.address;
            }

            log.DebugFormat("Using {0} for import", hostUrl);

            string result;

            try
            {
                log.DebugFormat("Uploading file '{0}' to VDI '{1}' on SR '{2}'", suppPackFilePath, vdi.Name(), sr.Name());

                HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent)
                {
                    var sr1   = sr;
                    var descr = string.Format(Messages.UPLOAD_PATCH_UPLOADING_TO_SR_PROGRESS_DESCRIPTION, _updateName, sr1.Name(),
                                              Util.DiskSizeString(percent * _totalUpdateSize / 100, "F1"), Util.DiskSizeString(_totalUpdateSize));

                    var actionPercent = (int)((totalUploaded * 100 + percent) / totalCount);
                    ByteProgressDescription = descr;
                    Tick(actionPercent, descr);
                };

                Session session = NewSession();
                RelatedTask = Task.create(Session, "put_import_raw_vdi_task", hostUrl);
                log.DebugFormat("HTTP PUTTING file from {0} to {1}", suppPackFilePath, hostUrl);

                HTTP_actions.put_import_raw_vdi(progressDelegate,
                                                () => XenAdminConfigManager.Provider.ForcedExiting || GetCancelling(),
                                                XenAdminConfigManager.Provider.GetProxyTimeout(true),
                                                hostUrl,
                                                XenAdminConfigManager.Provider.GetProxyFromSettings(Connection),
                                                suppPackFilePath, RelatedTask.opaque_ref, session.opaque_ref, vdiRef.opaque_ref);

                PollToCompletion();
                result = Result;
            }
            catch (Exception ex)
            {
                PollToCompletion(suppressFailures: true);

                if (vdiRef != null)
                {
                    try
                    {
                        log.ErrorFormat("Failed to import a virtual disk over HTTP. Deleting VDI '{0}' on a best effort basis.", vdiRef.opaque_ref);
                        VDI.destroy(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        log.Error("Failed to remove VDI.", removeEx);
                    }
                }

                if (ex is CancelledException || ex is HTTP.CancelledException || ex.InnerException is CancelledException)
                {
                    throw new CancelledException();
                }

                log.Error("Failed to import a virtual disk over HTTP", ex);

                //after having tried to remove the VDI, the original exception is thrown for the UI
                if (ex is TargetInvocationException && ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw;
                }
            }

            //introduce ISO for Ely and higher
            if (Helpers.ElyOrGreater(Connection))
            {
                try
                {
                    var poolUpdateRef = Pool_update.introduce(Connection.Session, vdiRef);
                    poolUpdate = Connection.WaitForCache(poolUpdateRef);

                    if (poolUpdate == null)
                    {
                        throw new Exception(Messages.UPDATE_ERROR_INTRODUCE); // This should not happen, because such case will result in a XAPI Failure. But this code has to be protected at this point.
                    }
                }
                catch (Exception ex)
                {
                    //clean-up the VDI we've just created
                    try
                    {
                        log.ErrorFormat("Deleting VDI '{0}' on a best effor basis.", vdiRef);
                        VDI.destroy(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        log.Error("Failed to remove VDI", removeEx);
                    }

                    var failure = ex as Failure;
                    if (failure != null && failure.ErrorDescription != null && failure.ErrorDescription.Count > 1 && failure.ErrorDescription[0] == Failure.UPDATE_ALREADY_EXISTS)
                    {
                        string uuidFound = failure.ErrorDescription[1];

                        poolUpdate = Connection.Cache.Pool_updates.FirstOrDefault(pu => string.Equals(pu.uuid, uuidFound, StringComparison.InvariantCultureIgnoreCase));
                    }
                    else
                    {
                        log.Error("Failed to introduce the update", ex);
                        poolUpdate = null;
                        throw;
                    }
                }
            }
            else
            {
                poolUpdate = null;
            }

            if (localStorageHost != null)
            {
                VdiRefsPerHost.Add(localStorageHost, vdiRef);
            }
            else // shared SR
            {
                foreach (var server in servers)
                {
                    VdiRefsPerHost.Add(server, vdiRef);
                }
            }

            totalUploaded++;
            Description = string.Format(Messages.SUPP_PACK_UPLOADED, sr.Name());

            foreach (Host host in servers)
            {
                SrsWithUploadedUpdatesPerHost[host] = sr;
            }

            return(result);
        }
示例#30
0
 public void ErrorFormat(string message, params object[] args)
 {
     log.ErrorFormat(message, args);
 }