Exemple #1
0
        public override bool Equals(object other)
        {
            if (other == null)
            {
                return(false);
            }
            if (object.ReferenceEquals(this, other))
            {
                return(true);
            }
            FailureException o = other as FailureException;

            if (o == null)
            {
                return(false);
            }
            if (this.reason == null)
            {
                if (o.reason != null)
                {
                    return(false);
                }
            }
            else
            {
                if (!this.reason.Equals(o.reason))
                {
                    return(false);
                }
            }
            return(true);
        }
        internal static bool IsError(string response, out Exception ex)
        {
            ex = null;
            if (!response.StartsWith("ACK"))
            {
                return(false);
            }

            ex = FailureException.FromResponseText(response);
            return(true);
        }
 public override void ErrorHandler(BaseClass sender, FailureException e)
 {
     base.ErrorHandler(sender, e);
     if (sender == _owner)
     {
         BaseForm.SetControlText(labelStatus, "复位出错:" + e.Message);
         _owner.UnsubcribeFromResponseEvent(this);
     }
     if (sender == currentSM)
     {
         currentSM.unsubscribeMeFromResponseEvents(this);
         BaseForm.SetControlText(labelStatus, "流程执行出错");
     }
 }
        private static async Task ExecSafe(Func <Task> action)
        {
            var logMessage = string.Empty;
            var exRethrow  = default(Exception);

            try
            {
                await action();
            }
            catch (SqlException ex)
            {
                // handle sql exceptions
                switch (ex.Number)
                {
                case 50001:
                    // NOT FOUND
                    exRethrow = new DuplicateItemException(ex.Message);
                    break;

                case 50002:
                    // ACCESS DENIED
                    exRethrow = new ForbiddenDataAccessException(ex.Message);
                    break;

                case 50003:
                    // DUPLICATE
                    exRethrow = new DuplicateItemException(ex.Message);
                    break;

                case 50004:
                    exRethrow = new UnauthorizedDataAccessException(ex.Message);
                    break;

                default:
                    // Well something horrible has gone wrong
                    exRethrow = new FailureException(ex.Message, "INTERNAL ERROR",
                                                     HttpStatusCode.InternalServerError);
                    break;
                }

                ExceptionUtility.TraceException(exRethrow);
                HomeHubEventSource.Log.Error($"Sql server error. Transaction rollback. {ex.Message}");
                throw exRethrow;
            }
        }
Exemple #5
0
        private void startService(string service, string entryPoint, string[] args)
        {
            _m.Lock();
            try
            {
            ServiceInfo info = new ServiceInfo();
            info.name = service;
            info.status = ServiceStatus.Stopped;
            info.args = args;

            //
            // Retrieve the assembly name and the type.
            //
            string err = "ServiceManager: unable to load service '" + entryPoint + "': ";
            int sepPos = entryPoint.IndexOf(':');
            if(sepPos != -1)
            {
                if(entryPoint.Length > 3 &&
                   sepPos == 1 &&
                   System.Char.IsLetter(entryPoint[0]) &&
                   (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if(sepPos == -1)
            {
                FailureException e = new FailureException();
                e.reason = err + "invalid entry point format: " + entryPoint;
                throw e;
            }

            System.Reflection.Assembly serviceAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            try
            {
                //
                // First try to load the assemby using Assembly.Load which will succeed
                // if full name is configured or partial name has been qualified in config.
                // If that fails, try Assembly.LoadFrom() which will succeed if a file name
                // is configured or partial name is configured and DEVPATH is used.
                //
                try
                {
                    serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch(System.IO.IOException ex)
                {
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch(System.IO.IOException)
                    {
                         throw ex;
                    }
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "unable to load assembly: " + assemblyName;
                throw e;
            }

            //
            // Instantiate the class.
            //
            string className = entryPoint.Substring(sepPos + 1);
            System.Type c = null;
            try
            {
                c = serviceAssembly.GetType(className, true);
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "GetType failed for '" + className + "'";
                throw e;
            }

            try
            {
                //
                // If the service class provides a constructor that accepts an Ice.Communicator argument,
                // use that in preference to the default constructor.
                //
                Type[] parameterTypes = new Type[1];
                parameterTypes[0] = typeof(Ice.Communicator);
                System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                if(ci != null)
                {
                    try
                    {
                        Object[] parameters = new Object[1];
                        parameters[0] = _communicator;
                        info.service = (Service)ci.Invoke(parameters);
                    }
                    catch(System.MethodAccessException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                        throw e;
                    }
                }
                else
                {
                    //
                    // Fall back to the default constructor.
                    //
                    try
                    {
                        info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                        if(info.service == null)
                        {
                            FailureException e = new FailureException();
                            e.reason = err + "no default constructor for '" + className + "'";
                            throw e;
                        }
                    }
                    catch(System.UnauthorizedAccessException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "unauthorized access to default service constructor for " + className;
                        throw e;
                    }
                }
            }
            catch(FailureException)
            {
                throw;
            }
            catch(System.InvalidCastException ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "service does not implement IceBox.Service";
                throw e;
            }
            catch(System.Reflection.TargetInvocationException ex)
            {
                if(ex.InnerException is IceBox.FailureException)
                {
                    throw ex.InnerException;
                }
                else
                {
                    FailureException e = new FailureException(ex.InnerException);
                    e.reason = "ServiceManager: exception in service constructor for " + className;
                    throw e;
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "exception in service constructor " + className;
                throw e;
            }

            //
            // Invoke Service::start().
            //
            try
            {
                //
                // If IceBox.UseSharedCommunicator.<name> is defined, create a
                // communicator for the service. The communicator inherits
                // from the shared communicator properties. If it's not
                // defined, add the service properties to the shared
                // commnunicator property set.
                //
                Ice.Communicator communicator;
                if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
                {
                    Debug.Assert(_sharedCommunicator != null);
                    communicator = _sharedCommunicator;
                }
                else
                {
                    //
                    // Create the service properties. We use the communicator properties as the default
                    // properties if IceBox.InheritProperties is set.
                    //
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties(service);
                    if(info.args.Length > 0)
                    {
                        //
                        // Create the service properties with the given service arguments. This should
                        // read the service config file if it's specified with --Ice.Config.
                        //
                        initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                        //
                        // Next, parse the service "<service>.*" command line options (the Ice command
                        // line options were parsed by the createProperties above)
                        //
                        info.args = initData.properties.parseCommandLineOptions(service, info.args);
                    }

                    //
                    // Clone the logger to assign a new prefix.
                    //
                    initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));

                    //
                    // Remaining command line options are passed to the communicator. This is
                    // necessary for Ice plug-in properties (e.g.: IceSSL).
                    //
                    info.communicator = Ice.Util.initialize(ref info.args, initData);
                    communicator = info.communicator;
                }

                try
                {
                    info.service.start(service, communicator, info.args);
                    info.status = ServiceStatus.Started;
                }
                catch(System.Exception)
                {
                    if(info.communicator != null)
                    {
                        try
                        {
                            info.communicator.shutdown();
                            info.communicator.waitForShutdown();
                        }
                        catch(Ice.CommunicatorDestroyedException)
                        {
                            //
                            // Ignore, the service might have already destroyed
                            // the communicator for its own reasons.
                            //
                        }
                        catch(System.Exception e)
                        {
                            _logger.warning("ServiceManager: exception while shutting down communicator for service "
                                            + service + "\n" + e.ToString());
                        }

                        try
                        {
                            info.communicator.destroy();
                        }
                        catch(System.Exception e)
                        {
                            _logger.warning("ServiceManager: exception while destroying communicator for service "
                                            + service + "\n" + e.ToString());
                        }
                    }
                    throw;
                }

                _services.Add(info);
            }
            catch(FailureException)
            {
                throw;
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = "ServiceManager: exception while starting service " + service;
                throw e;
            }
            }
            finally
            {
            _m.Unlock();
            }
        }
Exemple #6
0
        public int run()
        {
            try
            {
            Ice.Properties properties = _communicator.getProperties();

            //
            // Create an object adapter. Services probably should NOT share
            // this object adapter, as the endpoint(s) for this object adapter
            // will most likely need to be firewalled for security reasons.
            //
            Ice.ObjectAdapter adapter = null;
            if(properties.getProperty("IceBox.ServiceManager.Endpoints").Length != 0)
            {
                adapter = _communicator.createObjectAdapter("IceBox.ServiceManager");

                Ice.Identity identity = new Ice.Identity();
                identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox");
                identity.name = "ServiceManager";
                adapter.add(this, identity);
            }

            //
            // Parse the property set with the prefix "IceBox.Service.". These
            // properties should have the following format:
            //
            // IceBox.Service.Foo=Package.Foo [args]
            //
            // We parse the service properties specified in IceBox.LoadOrder
            // first, then the ones from remaining services.
            //
            string prefix = "IceBox.Service.";
            Dictionary<string, string> services = properties.getPropertiesForPrefix(prefix);
            string[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder");
            List<StartServiceInfo> servicesInfo = new List<StartServiceInfo>();
            for(int i = 0; i < loadOrder.Length; ++i)
            {
                if(loadOrder[i].Length > 0)
                {
                    string key = prefix + loadOrder[i];
                    string value = services[key];
                    if(value == null)
                    {
                        FailureException ex = new FailureException();
                        ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'";
                        throw ex;
                    }
                    servicesInfo.Add(new StartServiceInfo(loadOrder[i], value, _argv));
                    services.Remove(key);
                }
            }
            foreach(KeyValuePair<string, string> entry in services)
            {
                string name = entry.Key.Substring(prefix.Length);
                string value = entry.Value;
                servicesInfo.Add(new StartServiceInfo(name, value, _argv));
            }

            //
            // Check if some services are using the shared communicator in which
            // case we create the shared communicator now with a property set which
            // is the union of all the service properties (services which are using
            // the shared communicator).
            //
            if(properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").Count > 0)
            {
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties("SharedCommunicator");
                foreach(StartServiceInfo service in servicesInfo)
                {
                    if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0)
                    {
                        continue;
                    }

                    //
                    // Load the service properties using the shared communicator properties as
                    // the default properties.
                    //
                    Ice.Properties svcProperties = Ice.Util.createProperties(ref service.args, initData.properties);

                    //
                    // Erase properties from the shared communicator which don't exist in the
                    // service properties (which include the shared communicator properties
                    // overriden by the service properties).
                    //
                    Dictionary<string, string> allProps = initData.properties.getPropertiesForPrefix("");
                    foreach(string key in allProps.Keys)
                    {
                        if(svcProperties.getProperty(key).Length == 0)
                        {
                            initData.properties.setProperty(key, "");
                        }
                    }

                    //
                    // Add the service properties to the shared communicator properties.
                    //
                    foreach(KeyValuePair<string, string> entry in svcProperties.getPropertiesForPrefix(""))
                    {
                        initData.properties.setProperty(entry.Key, entry.Value);
                    }

                    //
                    // Parse <service>.* command line options (the Ice command line options
                    // were parsed by the createProperties above)
                    //
                    service.args = initData.properties.parseCommandLineOptions(service.name, service.args);
                }
                _sharedCommunicator = Ice.Util.initialize(initData);
            }

            foreach(StartServiceInfo s in servicesInfo)
            {
                startService(s.name, s.entryPoint, s.args);
            }

            //
            // We may want to notify external scripts that the services
            // have started. This is done by defining the property:
            //
            // PrintServicesReady=bundleName
            //
            // Where bundleName is whatever you choose to call this set of
            // services. It will be echoed back as "bundleName ready".
            //
            // This must be done after start() has been invoked on the
            // services.
            //
            string bundleName = properties.getProperty("IceBox.PrintServicesReady");
            if(bundleName.Length > 0)
            {
                Console.Out.WriteLine(bundleName + " ready");
            }

            //
            // Don't move after the adapter activation. This allows
            // applications to wait for the service manager to be
            // reachable before sending a signal to shutdown the
            //
            //
            Ice.Application.shutdownOnInterrupt();

            //
            // Register "this" as a facet to the Admin object and create Admin object
            //
            try
            {
                _communicator.addAdminFacet(this, "IceBox.ServiceManager");

                //
                // Add a Properties facet for each service
                //
                foreach(ServiceInfo info in _services)
                {
                    Ice.Communicator communicator = info.communicator != null ? info.communicator : _sharedCommunicator;
                    _communicator.addAdminFacet(new PropertiesAdminI(communicator.getProperties()),
                                                "IceBox.Service." + info.name + ".Properties");
                }

                _communicator.getAdmin();
            }
            catch(Ice.ObjectAdapterDeactivatedException)
            {
                //
                // Expected if the communicator has been shutdown.
                //
            }

            //
            // Start request dispatching after we've started the services.
            //
            if(adapter != null)
            {
                try
                {
                    adapter.activate();
                }
                catch(Ice.ObjectAdapterDeactivatedException)
                {
                    //
                    // Expected if the communicator has been shutdown.
                    //
                }
            }

            _communicator.waitForShutdown();
            // XXX:
            //Ice.Application.defaultInterrupt();

            //
            // Invoke stop() on the services.
            //
            stopAll();
            }
            catch(FailureException ex)
            {
            _logger.error(ex.ToString());
            stopAll();
            return 1;
            }
            catch(Exception ex)
            {
            _logger.error("ServiceManager: caught exception:\n" + ex.ToString());
            stopAll();
            return 1;
            }

            return 0;
        }
Exemple #7
0
            public StartServiceInfo(string service, string value, string[] serverArgs)
            {
                //
                // Separate the entry point from the arguments.
                //
                name = service;
                entryPoint = value;
                args = new string[0];
                int start = value.IndexOf(':');
                if(start != -1)
                {
                //
                // Find the whitespace.
                //
                int pos = value.IndexOf(' ', start);
                if(pos == -1)
                {
                    pos = value.IndexOf('\t', start);
                }
                if(pos == -1)
                {
                    pos = value.IndexOf('\n', start);
                }
                if(pos != -1)
                {
                    entryPoint = value.Substring(0, pos);
                    try
                    {
                        args = IceUtilInternal.Options.split(value.Substring(pos));
                    }
                    catch(IceUtilInternal.Options.BadQuote ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = "ServiceManager: invalid arguments for service `" + name + "'";
                        throw e;
                    }
                }
                }

                if(serverArgs.Length > 0)
                {
                ArrayList l = new ArrayList();
                for(int j = 0; j < args.Length; j++)
                {
                    l.Add(args[j]);
                }
                for(int j = 0; j < serverArgs.Length; j++)
                {
                    if(serverArgs[j].StartsWith("--" + service + ".", StringComparison.Ordinal))
                    {
                        l.Add(serverArgs[j]);
                    }
                }
                args = (string[])l.ToArray(typeof(string));
                }
            }
Exemple #8
0
        private void startService(string service, string entryPoint, string[] args)
        {
            lock(this)
            {
            //
            // Extract the assembly name and the class name.
            //
            string err = "ServiceManager: unable to load service '" + entryPoint + "': ";
            int sepPos = entryPoint.IndexOf(':');
            if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)
            {
                const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                if(entryPoint.Length > 3 &&
                   sepPos == 1 &&
                   driveLetters.IndexOf(entryPoint[0]) != -1 &&
                   (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if(sepPos == -1)
            {
                FailureException e = new FailureException();
                e.reason = err + "invalid entry point format";
                throw e;
            }

            System.Reflection.Assembly serviceAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            string className = entryPoint.Substring(sepPos + 1);

            try
            {
                //
                // First try to load the assembly using Assembly.Load, which will succeed
                // if a fully-qualified name is provided or if a partial name has been qualified
                // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                // if a file name is configured or a partial name is configured and DEVPATH is used.
                //
                try
                {
                    serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch(System.IO.IOException ex)
                {
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch(System.IO.IOException)
                    {
                         throw ex;
                    }
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "unable to load assembly: " + assemblyName;
                throw e;
            }

            //
            // Instantiate the class.
            //
            System.Type c = null;
            try
            {
                c = serviceAssembly.GetType(className, true);
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "GetType failed for '" + className + "'";
                throw e;
            }

            ServiceInfo info = new ServiceInfo();
            info.name = service;
            info.status = ServiceStatus.Stopped;
            info.args = args;

            //
            // If IceBox.UseSharedCommunicator.<name> is defined, create a
            // communicator for the service. The communicator inherits
            // from the shared communicator properties. If it's not
            // defined, add the service properties to the shared
            // commnunicator property set.
            //
            Ice.Communicator communicator;
            if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
            {
                Debug.Assert(_sharedCommunicator != null);
                communicator = _sharedCommunicator;
            }
            else
            {
                //
                // Create the service properties. We use the communicator properties as the default
                // properties if IceBox.InheritProperties is set.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties(service);
                if(info.args.Length > 0)
                {
                    //
                    // Create the service properties with the given service arguments. This should
                    // read the service config file if it's specified with --Ice.Config.
                    //
                    initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                    //
                    // Next, parse the service "<service>.*" command line options (the Ice command
                    // line options were parsed by the createProperties above)
                    //
                    info.args = initData.properties.parseCommandLineOptions(service, info.args);
                }

                //
                // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                // don't set any logger.
                //
                if(initData.properties.getProperty("Ice.LogFile").Length == 0 &&
                   (initData.properties.getPropertyAsInt("Ice.UseSyslog") <= 0 ||
                    IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows))
                {
                    initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                }

                //
                // If Admin is enabled on the IceBox communicator, for each service that does not set
                // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then
                // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>.
                //
                string serviceFacetNamePrefix = "IceBox.Service." + service + ".";
                bool addFacets = configureAdmin(initData.properties, serviceFacetNamePrefix);

                //
                // Remaining command line options are passed to the communicator. This is
                // necessary for Ice plug-in properties (e.g.: IceSSL).
                //
                info.communicator = Ice.Util.initialize(ref info.args, initData);
                communicator = info.communicator;

                if(addFacets)
                {
                    // Add all facets created on the service communicator to the IceBox communicator
                    // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet
                    // which is never added
                    foreach(KeyValuePair<string, Ice.Object> p in communicator.findAllAdminFacets())
                    {
                        if(!p.Key.Equals("Process"))
                        {
                            _communicator.addAdminFacet(p.Value, serviceFacetNamePrefix + p.Key);
                        }
                    }
                }
            }

            try
            {
                //
                // Instantiate the service.
                //
                try
                {
                    //
                    // If the service class provides a constructor that accepts an Ice.Communicator argument,
                    // use that in preference to the default constructor.
                    //
                    Type[] parameterTypes = new Type[1];
                    parameterTypes[0] = typeof(Ice.Communicator);
                    System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                    if(ci != null)
                    {
                        try
                        {
                            Object[] parameters = new Object[1];
                            parameters[0] = _communicator;
                            info.service = (Service)ci.Invoke(parameters);
                        }
                        catch(System.MethodAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                            throw e;
                        }
                    }
                    else
                    {
                        //
                        // Fall back to the default constructor.
                        //
                        try
                        {
                            info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                            if(info.service == null)
                            {
                                FailureException e = new FailureException();
                                e.reason = err + "no default constructor for '" + className + "'";
                                throw e;
                            }
                        }
                        catch(System.UnauthorizedAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unauthorized access to default service constructor for " + className;
                            throw e;
                        }
                    }
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.InvalidCastException ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "service does not implement IceBox.Service";
                    throw e;
                }
                catch(System.Reflection.TargetInvocationException ex)
                {
                    if(ex.InnerException is IceBox.FailureException)
                    {
                        throw ex.InnerException;
                    }
                    else
                    {
                        FailureException e = new FailureException(ex.InnerException);
                        e.reason = err + "exception in service constructor for " + className;
                        throw e;
                    }
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "exception in service constructor " + className;
                    throw e;
                }

                try
                {
                    info.service.start(service, communicator, info.args);
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = "exception while starting service " + service;
                    throw e;
                }

                info.status = ServiceStatus.Started;
                _services.Add(info);
            }
            catch(System.Exception)
            {
                if(info.communicator != null)
                {
                    destroyServiceCommunicator(service, info.communicator);
                }

                throw;
            }

            }
        }
Exemple #9
0
            public StartServiceInfo(string service, string value, string[] serverArgs)
            {
                //
                // Separate the entry point from the arguments.
                //
                name = service;

                try
                {
                args = IceUtilInternal.Options.split(value);
                }
                catch(IceUtilInternal.Options.BadQuote ex)
                {
                FailureException e = new FailureException();
                e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.Message;
                throw e;
                }

                Debug.Assert(args.Length > 0);

                entryPoint = args[0];

                //
                // Shift the arguments.
                //
                string[] tmp = new string[args.Length - 1];
                Array.Copy(args, 1, tmp, 0, args.Length - 1);
                args = tmp;

                if(serverArgs.Length > 0)
                {
                ArrayList l = new ArrayList();
                for(int j = 0; j < args.Length; j++)
                {
                    l.Add(args[j]);
                }
                for(int j = 0; j < serverArgs.Length; j++)
                {
                    if(serverArgs[j].StartsWith("--" + service + ".", StringComparison.Ordinal))
                    {
                        l.Add(serverArgs[j]);
                    }
                }
                args = (string[])l.ToArray(typeof(string));
                }
            }
Exemple #10
0
        /// <summary>
        /// Rollback the latest or a specific release for an app deployment
        /// </summary>
        /// <param name='deploymentName'>
        /// deployment name
        /// </param>
        /// <param name='ownerName'>
        /// The name of the owner
        /// </param>
        /// <param name='appName'>
        /// The name of the application
        /// </param>
        /// <param name='releaseLabel'>
        /// The specific release label that you want to rollback to
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="FailureException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <CodePushRelease> > RollbackWithHttpMessagesAsync(string deploymentName, string ownerName, string appName, CodePushReleaseLabel releaseLabel = default(CodePushReleaseLabel), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (deploymentName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName");
            }
            if (ownerName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "ownerName");
            }
            if (appName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "appName");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("deploymentName", deploymentName);
                tracingParameters.Add("releaseLabel", releaseLabel);
                tracingParameters.Add("ownerName", ownerName);
                tracingParameters.Add("appName", appName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Rollback", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/apps/{owner_name}/{app_name}/deployments/{deployment_name}/rollback_release").ToString();

            _url = _url.Replace("{deployment_name}", System.Uri.EscapeDataString(deploymentName));
            _url = _url.Replace("{owner_name}", System.Uri.EscapeDataString(ownerName));
            _url = _url.Replace("{app_name}", System.Uri.EscapeDataString(appName));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (releaseLabel != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(releaseLabel, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 201)
            {
                var ex = new FailureException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Failure _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Failure>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <CodePushRelease>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CodePushRelease>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Create a new CodePush release for the specified deployment
        /// </summary>
        /// <param name='deploymentName'>
        /// deployment name
        /// </param>
        /// <param name='ownerName'>
        /// The name of the owner
        /// </param>
        /// <param name='appName'>
        /// The name of the application
        /// </param>
        /// <param name='targetBinaryVersion'>
        /// the binary version of the application
        /// </param>
        /// <param name='package'>
        /// The upload zip file
        /// </param>
        /// <param name='deploymentName1'>
        /// This specifies which deployment you want to release the update to. Default
        /// is Staging.
        /// </param>
        /// <param name='description'>
        /// This provides an optional "change log" for the deployment.
        /// </param>
        /// <param name='disabled'>
        /// This specifies whether an update should be downloadable by end users or
        /// not.
        /// </param>
        /// <param name='mandatory'>
        /// This specifies whether the update should be considered mandatory or not
        /// (e.g. it includes a critical security fix).
        /// </param>
        /// <param name='noDuplicateReleaseError'>
        /// This specifies that if the update is identical to the latest release on the
        /// deployment, the CLI should generate a warning instead of an error.
        /// </param>
        /// <param name='rollout'>
        /// This specifies the percentage of users (as an integer between 1 and 100)
        /// that should be eligible to receive this update.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="FailureException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <CodePushRelease> > CreateWithHttpMessagesAsync(string deploymentName, string ownerName, string appName, string targetBinaryVersion, Stream package = default(Stream), string deploymentName1 = default(string), string description = default(string), bool?disabled = default(bool?), bool?mandatory = default(bool?), bool?noDuplicateReleaseError = default(bool?), int?rollout = default(int?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (deploymentName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName");
            }
            if (ownerName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "ownerName");
            }
            if (appName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "appName");
            }
            if (targetBinaryVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "targetBinaryVersion");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("deploymentName", deploymentName);
                tracingParameters.Add("ownerName", ownerName);
                tracingParameters.Add("appName", appName);
                tracingParameters.Add("package", package);
                tracingParameters.Add("targetBinaryVersion", targetBinaryVersion);
                tracingParameters.Add("deploymentName1", deploymentName1);
                tracingParameters.Add("description", description);
                tracingParameters.Add("disabled", disabled);
                tracingParameters.Add("mandatory", mandatory);
                tracingParameters.Add("noDuplicateReleaseError", noDuplicateReleaseError);
                tracingParameters.Add("rollout", rollout);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/apps/{owner_name}/{app_name}/deployments/{deployment_name}/releases").ToString();

            _url = _url.Replace("{deployment_name}", System.Uri.EscapeDataString(deploymentName));
            _url = _url.Replace("{owner_name}", System.Uri.EscapeDataString(ownerName));
            _url = _url.Replace("{app_name}", System.Uri.EscapeDataString(appName));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            MultipartFormDataContent _multiPartContent = new MultipartFormDataContent();

            if (package != null)
            {
                StreamContent _package = new StreamContent(package);
                _package.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data");
                _contentDispositionHeaderValue.Name = "package";
                // get filename from stream if it's a file otherwise, just use  'unknown'
                var _fileStream = package as FileStream;
                var _fileName   = (_fileStream != null ? _fileStream.Name : null) ?? "unknown";
                if (System.Linq.Enumerable.Any(_fileName, c => c > 127))
                {
                    // non ASCII chars detected, need UTF encoding:
                    _contentDispositionHeaderValue.FileNameStar = _fileName;
                }
                else
                {
                    // ASCII only
                    _contentDispositionHeaderValue.FileName = _fileName;
                }
                _package.Headers.ContentDisposition = _contentDispositionHeaderValue;
                _multiPartContent.Add(_package, "package");
            }
            if (targetBinaryVersion != null)
            {
                StringContent _targetBinaryVersion = new StringContent(targetBinaryVersion, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_targetBinaryVersion, "targetBinaryVersion");
            }
            if (deploymentName1 != null)
            {
                StringContent _deploymentName1 = new StringContent(deploymentName1, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_deploymentName1, "deploymentName");
            }
            if (description != null)
            {
                StringContent _description = new StringContent(description, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_description, "description");
            }
            if (disabled != null)
            {
                StringContent _disabled = new StringContent(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(disabled, Client.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8);
                _multiPartContent.Add(_disabled, "disabled");
            }
            if (mandatory != null)
            {
                StringContent _mandatory = new StringContent(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(mandatory, Client.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8);
                _multiPartContent.Add(_mandatory, "mandatory");
            }
            if (noDuplicateReleaseError != null)
            {
                StringContent _noDuplicateReleaseError = new StringContent(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(noDuplicateReleaseError, Client.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8);
                _multiPartContent.Add(_noDuplicateReleaseError, "noDuplicateReleaseError");
            }
            if (rollout != null)
            {
                StringContent _rollout = new StringContent(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(rollout, Client.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8);
                _multiPartContent.Add(_rollout, "rollout");
            }
            _httpRequest.Content = _multiPartContent;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 201)
            {
                var ex = new FailureException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Failure _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Failure>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <CodePushRelease>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CodePushRelease>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemple #12
0
 public void ErrorHandler(BaseClass sender, FailureException e)
 {
 }
        /// <summary>
        /// Gets a stacktrace for a specific crash
        /// </summary>
        /// <param name='crashGroupId'>
        /// id of a specific group
        /// </param>
        /// <param name='ownerName'>
        /// The name of the owner
        /// </param>
        /// <param name='appName'>
        /// The name of the application
        /// </param>
        /// <param name='groupingOnly'>
        /// true if the stacktrace should be only the relevant thread / exception.
        /// Default is false
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="FailureException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <Stacktrace> > GetStacktraceWithHttpMessagesAsync(string crashGroupId, string ownerName, string appName, bool?groupingOnly = false, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (crashGroupId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "crashGroupId");
            }
            if (ownerName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "ownerName");
            }
            if (appName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "appName");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("crashGroupId", crashGroupId);
                tracingParameters.Add("groupingOnly", groupingOnly);
                tracingParameters.Add("ownerName", ownerName);
                tracingParameters.Add("appName", appName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetStacktrace", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/apps/{owner_name}/{app_name}/crash_groups/{crash_group_id}/stacktrace").ToString();

            _url = _url.Replace("{crash_group_id}", System.Uri.EscapeDataString(crashGroupId));
            _url = _url.Replace("{owner_name}", System.Uri.EscapeDataString(ownerName));
            _url = _url.Replace("{app_name}", System.Uri.EscapeDataString(appName));
            List <string> _queryParameters = new List <string>();

            if (groupingOnly != null)
            {
                _queryParameters.Add(string.Format("grouping_only={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(groupingOnly, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new FailureException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Failure _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Failure>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <Stacktrace>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Stacktrace>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemple #14
0
    private void startService(string service, string entryPoint, string[] args)
    {
        _m.Lock();
        try
        {
            //
            // Extract the assembly name and the class name.
            //
            string err = "ServiceManager: unable to load service '" + entryPoint + "': ";
            int sepPos = entryPoint.IndexOf(':');
            if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)
            {
                const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                if(entryPoint.Length > 3 &&
                   sepPos == 1 &&
                   driveLetters.IndexOf(entryPoint[0]) != -1 &&
                   (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if(sepPos == -1)
            {
                FailureException e = new FailureException();
                e.reason = err + "invalid entry point format";
                throw e;
            }

            System.Reflection.Assembly serviceAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            string className = entryPoint.Substring(sepPos + 1);

            try
            {
                //
                // First try to load the assembly using Assembly.Load, which will succeed
                // if a fully-qualified name is provided or if a partial name has been qualified
                // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                // if a file name is configured or a partial name is configured and DEVPATH is used.
                //
                try
                {
                    serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch(System.IO.IOException ex)
                {
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch(System.IO.IOException)
                    {
                         throw ex;
                    }
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "unable to load assembly: " + assemblyName;
                throw e;
            }

            //
            // Instantiate the class.
            //
            System.Type c = null;
            try
            {
                c = serviceAssembly.GetType(className, true);
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "GetType failed for '" + className + "'";
                throw e;
            }

            ServiceInfo info = new ServiceInfo();
            info.name = service;
            info.status = ServiceStatus.Stopped;
            info.args = args;
            
            //
            // If IceBox.UseSharedCommunicator.<name> is defined, create a
            // communicator for the service. The communicator inherits
            // from the shared communicator properties. If it's not
            // defined, add the service properties to the shared
            // commnunicator property set.
            //
            Ice.Communicator communicator;
            IceInternal.MetricsAdminI metricsAdmin = null;
            if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
            {
                Debug.Assert(_sharedCommunicator != null);
                communicator = _sharedCommunicator;
                if(communicator.getObserver() is IceInternal.CommunicatorObserverI)
                {
                    IceInternal.CommunicatorObserverI o = (IceInternal.CommunicatorObserverI)communicator.getObserver();
                    metricsAdmin = o.getMetricsAdmin();
                }
            }
            else
            {
                //
                // Create the service properties. We use the communicator properties as the default
                // properties if IceBox.InheritProperties is set.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties(service);
                if(info.args.Length > 0)
                {
                    //
                    // Create the service properties with the given service arguments. This should
                    // read the service config file if it's specified with --Ice.Config.
                    //
                    initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                    //
                    // Next, parse the service "<service>.*" command line options (the Ice command
                    // line options were parsed by the createProperties above)
                    //
                    info.args = initData.properties.parseCommandLineOptions(service, info.args);
                }

                //
                // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                // don't set any logger.
                //
                if(initData.properties.getProperty("Ice.LogFile").Length == 0 &&
                   (initData.properties.getPropertyAsInt("Ice.UseSyslog") == 0 ||
                    IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows))
                {
                    initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                }

                //
                // If Ice metrics are enabled on the IceBox communicator, we also enable them on
                // the service communicator.
                // 
                if(_communicator.getObserver() is IceInternal.CommunicatorObserverI)
                {
                    metricsAdmin = new IceInternal.MetricsAdminI(initData.properties, initData.logger);
                    initData.observer = new IceInternal.CommunicatorObserverI(metricsAdmin);
                }

                //
                // Remaining command line options are passed to the communicator. This is
                // necessary for Ice plug-in properties (e.g.: IceSSL).
                //
                info.communicator = Ice.Util.initialize(ref info.args, initData);
                communicator = info.communicator;

                //
                // Ensure the metrics admin plugin uses the same property set as the
                // communicator. This is necessary to correctly deal with runtime 
                // property updates.
                //
                if(metricsAdmin != null)
                {
                    metricsAdmin.setProperties(communicator.getProperties());
                }
            }

            try
            {   
                //
                // Add a PropertiesAdmin facet to the service manager's communicator that provides
                // access to this service's property set. We do this prior to instantiating the
                // service so that the service's constructor is able to access the facet (e.g.,
                // in case it wants to set a callback).
                //
                string facetName = "IceBox.Service." + info.name + ".Properties";
                IceInternal.PropertiesAdminI propAdmin = new IceInternal.PropertiesAdminI(facetName, 
                                                                                          communicator.getProperties(), 
                                                                                          communicator.getLogger());
                _communicator.addAdminFacet(propAdmin, facetName);
                
                //
                // If a metrics admin facet is setup for the service, register
                // it with the IceBox communicator.
                //
                if(metricsAdmin != null)
                {
                    _communicator.addAdminFacet(metricsAdmin, "IceBox.Service." + info.name + ".Metrics");

                    // Ensure the metrics admin facet is notified of property updates.
                    propAdmin.addUpdateCallback(metricsAdmin);
                }

                //
                // Instantiate the service.
                //
                try
                {
                    //
                    // If the service class provides a constructor that accepts an Ice.Communicator argument,
                    // use that in preference to the default constructor.
                    //
                    Type[] parameterTypes = new Type[1];
                    parameterTypes[0] = typeof(Ice.Communicator);
                    System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                    if(ci != null)
                    {
                        try
                        {
                            Object[] parameters = new Object[1];
                            parameters[0] = _communicator;
                            info.service = (Service)ci.Invoke(parameters);
                        }
                        catch(System.MethodAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                            throw e;
                        }
                    }
                    else
                    {
                        //
                        // Fall back to the default constructor.
                        //
                        try
                        {
                            info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                            if(info.service == null)
                            {
                                FailureException e = new FailureException();
                                e.reason = err + "no default constructor for '" + className + "'";
                                throw e;
                            }
                        }
                        catch(System.UnauthorizedAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unauthorized access to default service constructor for " + className;
                            throw e;
                        }
                    }
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.InvalidCastException ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "service does not implement IceBox.Service";
                    throw e;
                }
                catch(System.Reflection.TargetInvocationException ex)
                {
                    if(ex.InnerException is IceBox.FailureException)
                    {
                        throw ex.InnerException;
                    }
                    else
                    {
                        FailureException e = new FailureException(ex.InnerException);
                        e.reason = err + "exception in service constructor for " + className;
                        throw e;
                    }
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "exception in service constructor " + className;
                    throw e;
                }


                try
                {
                    info.service.start(service, communicator, info.args);
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = "exception while starting service " + service;
                    throw e;
                }

                info.status = ServiceStatus.Started;
                _services.Add(info);
            }
            catch(Ice.ObjectAdapterDeactivatedException)
            {
                //
                // Can be raised by addAdminFacet if the service manager communicator has been shut down.
                //
                if(info.communicator != null)
                {
                    destroyServiceCommunicator(service, info.communicator);
                }
            }
            catch(System.Exception ex)
            {
                try
                {
                    _communicator.removeAdminFacet("IceBox.Service." + service + ".Properties");
                }
                catch(Ice.LocalException)
                {
                    // Ignored
                }

                if(info.communicator != null)
                {
                    destroyServiceCommunicator(service, info.communicator);
                }

                throw ex;
            }

        }
        finally
        {
            _m.Unlock();
        }
    }
Exemple #15
0
        /// <summary>
        /// Check for updates
        /// </summary>
        /// <param name='deploymentKey'>
        /// </param>
        /// <param name='appVersion'>
        /// </param>
        /// <param name='packageHash'>
        /// </param>
        /// <param name='label'>
        /// </param>
        /// <param name='clientUniqueId'>
        /// </param>
        /// <param name='isCompanion'>
        /// </param>
        /// <param name='previousLabelOrAppVersion'>
        /// </param>
        /// <param name='previousDeploymentKey'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="FailureException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <UpdateCheckResponse> > UpdateCheckWithHttpMessagesAsync(string deploymentKey, string appVersion, string packageHash = default(string), string label = default(string), string clientUniqueId = default(string), bool?isCompanion = default(bool?), string previousLabelOrAppVersion = default(string), string previousDeploymentKey = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (deploymentKey == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "deploymentKey");
            }
            if (appVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "appVersion");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("deploymentKey", deploymentKey);
                tracingParameters.Add("appVersion", appVersion);
                tracingParameters.Add("packageHash", packageHash);
                tracingParameters.Add("label", label);
                tracingParameters.Add("clientUniqueId", clientUniqueId);
                tracingParameters.Add("isCompanion", isCompanion);
                tracingParameters.Add("previousLabelOrAppVersion", previousLabelOrAppVersion);
                tracingParameters.Add("previousDeploymentKey", previousDeploymentKey);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UpdateCheck", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/public/codepush/update_check").ToString();
            List <string> _queryParameters = new List <string>();

            if (deploymentKey != null)
            {
                _queryParameters.Add(string.Format("deployment_key={0}", System.Uri.EscapeDataString(deploymentKey)));
            }
            if (appVersion != null)
            {
                _queryParameters.Add(string.Format("app_version={0}", System.Uri.EscapeDataString(appVersion)));
            }
            if (packageHash != null)
            {
                _queryParameters.Add(string.Format("package_hash={0}", System.Uri.EscapeDataString(packageHash)));
            }
            if (label != null)
            {
                _queryParameters.Add(string.Format("label={0}", System.Uri.EscapeDataString(label)));
            }
            if (clientUniqueId != null)
            {
                _queryParameters.Add(string.Format("client_unique_id={0}", System.Uri.EscapeDataString(clientUniqueId)));
            }
            if (isCompanion != null)
            {
                _queryParameters.Add(string.Format("is_companion={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(isCompanion, Client.SerializationSettings).Trim('"'))));
            }
            if (previousLabelOrAppVersion != null)
            {
                _queryParameters.Add(string.Format("previous_label_or_app_version={0}", System.Uri.EscapeDataString(previousLabelOrAppVersion)));
            }
            if (previousDeploymentKey != null)
            {
                _queryParameters.Add(string.Format("previous_deployment_key={0}", System.Uri.EscapeDataString(previousDeploymentKey)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new FailureException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Failure _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Failure>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <UpdateCheckResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <UpdateCheckResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemple #16
0
        /// <summary>
        /// Returns the acquisition service status to the caller
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="FailureException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <AcquisitionStatusSuccessResponse> > GetAcquisitionStatusWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetAcquisitionStatus", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/public/codepush/status").ToString();
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new FailureException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Failure _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Failure>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <AcquisitionStatusSuccessResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <AcquisitionStatusSuccessResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }