public FileInfo DownloadImage(string imageId, string outputPath, Func<decimal, bool> progressCallback)
 {
     RequestManager requestManager = new RequestManager(_identity);
     var uri = string.Format("/v2/images/{0}/file", imageId);
     FileInfo result = requestManager.Download(imageId, outputPath,"glance", progressCallback);
     return result;
 }
 public FileInfo DownloadImage(string imageId, string outputPath, Identity identity)
 {
     RequestManager requestManager = new RequestManager(identity);
     var uri = string.Format("/v2/images/{0}/file", imageId);
     FileInfo result = requestManager.Download(imageId, outputPath,"glance");
     return result;
 }
        public Instance CreateInstance(string instanceName, string imageId, string keypairName, string flavorId, Identity identity)
        {
            RequestManager requestManager = new RequestManager(identity);
            var uri = string.Format("/servers");

            var bodyObject = new InstanceRequestBodyWrapper()
            {
                server = new InstanceRequestBody()
                {
                    name = instanceName,
                    imageRef = imageId,
                    key_name = keypairName,
                    flavorRef = flavorId,
                }
            };
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string body = oSerializer.Serialize(bodyObject);
            JObject response = requestManager.Post(uri, body, "nova");

            if (response != null)
            {
                var tempinstance = response["server"];
                var instance = new Instance()
                {
                    Id = tempinstance["id"].ToString(),
                };

                return instance;
            }
            return null;
        }
Example #4
0
		public void RequestManager_ProcessEncryptedDocument()
		{
			Request request = LoadRequestFromFile(Path.Combine(TestPath, "EmailEncryptedWordDocument.request"));
			string[] contentItems = RequestResponseUtilities.ListAttachmentNames(request);
			IPolicyClientUIManager2 uiManager = new MockPolicyClientUIManager2(contentItems, CallerEnum.Email, TestPolicyClientDialogOperationsEnum.All);
			RequestManager rm = new RequestManager(request, uiManager);

			rm.ProcessRequest(null, false, false);
		}
 public DynamicControllerManager(HttpRequestBase request, ControllerManager controllerManager, IDynamicRepository dynamicRepository, UrlHelper urlHelper)
 {
     RequestManager = new RequestManager(request);
     DynamicEntitySearcher = new DynamicEntitySearcher(RequestManager);
     RequestManager.QueryStringDictionary = RequestManager.QueryStringDictionary.RouteValueDictionaryTypeCorrection(DynamicEntitySearcher.DynamicEntityMetadata);
     ControllerManager = controllerManager;
     DynamicRepository = dynamicRepository;
     UrlManager = new UrlManager(urlHelper);
     ReturnUrlCalculator = new ReturnUrlCalculator(UrlManager);
 }
 public Flavor Get(string id, Identity identity)
 {
     Flavor flavor = new Flavor();
     RequestManager requestManager = new RequestManager(identity);
     var uri = String.Format("/flavors/{0}", id);
     JObject response = requestManager.Get(uri, "nova");
     flavor.Name = response["flavor"]["name"].ToString();
     flavor.Id = response["flavor"]["id"].ToString();
     return flavor;
 }
        protected void SendRequest()
        {
            RequestManager requestManager = new RequestManager();

            string jsonToSend = Newtonsoft.Json.JsonConvert.SerializeObject(requestValues);

            requestManager.SendPOSTRequest(uri, jsonToSend, "", "", false);
			if (requestManager.LastResponse == null)
			{
				responseValues = new JsonResponseDictionary();
				responseValues["Status"] = "error";
				responseValues["ErrorMessage"] = "Unable to connect to server";
			} else {
            	responseValues = JsonConvert.DeserializeObject<JsonResponseDictionary>(requestManager.LastResponse);
			}
			ProcessResponse();
        }
 public IList<Flavor> List(Identity identity)
 {
     IList<Flavor> list = new List<Flavor>();
     RequestManager requestManager = new RequestManager(identity);
     var uri = "/flavors/detail";
     JObject response = requestManager.Get(uri, "nova");
     var tempinstances = response["flavors"];
     foreach (var tempinstance in tempinstances)
     {
         var instance = new Flavor()
         {
             Id = tempinstance["id"].ToString(),
             Name = tempinstance["name"].ToString()
         };
         list.Add(instance);
     }
     return list;
 }
        private async void GetNewListings()
        {
            ListingsProgressBar.Visibility = Visibility.Visible;
            var manager = new RequestManager();
            var newListings = await manager.GetListings();

            if (newListings != null)
            {
                _listings = new ObservableCollection<Listing>(newListings);
            }

            ListingsView.ItemsSource = _listings;
            ListingsProgressBar.Visibility = Visibility.Collapsed;

            if (_listings.Count > 0)
            {
                ListingsView.SelectedIndex = 0;
            }
        }
 public IList<Keypair> ListKeypairs(Identity identity)
 {
     IList<Keypair> list = new List<Keypair>();
     RequestManager requestManager = new RequestManager(identity);
     var uri = "/os-keypairs";
     JObject response = requestManager.Get(uri, "nova");
     var tempinstances = response["keypairs"];
     foreach (var tempinstance in tempinstances)
     {
         var tmp = tempinstance["keypair"];
         var keyPair = new Keypair()
         {
             name = tmp["name"].ToString(),
             publicKey = tmp["public_key"].ToString(),
             fingerprint=tmp["fingerprint"].ToString(),
         };
         list.Add(keyPair);
     }
     return list;
 }
        public void CreateKeypair(string name, Identity identity, FileInfo output)
        {
            Keypair keypair = new Keypair();
            RequestManager requestManager = new RequestManager(identity);

            Keypair bodyObject = new Keypair()
            {
                name = name
            };
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string body = oSerializer.Serialize(bodyObject);

            var uri = String.Format("/os-keypairs");
            JObject response = requestManager.Post(uri, "{\"keypair\":" + body + "}", "nova");
            keypair.publicKey = response["keypair"]["public_key"].ToString();
            keypair.privateKey = response["keypair"]["private_key"].ToString();
            keypair.userId = response["keypair"]["user_id"].ToString();
            keypair.name = response["keypair"]["name"].ToString();
            keypair.fingerprint = response["keypair"]["fingerprint"].ToString();
            StreamWriter stream = new StreamWriter(output.FullName + name + ".pem");
            stream.Write(keypair.privateKey);
            stream.Close();
        }
 public void Delete(string imageId)
 {
     RequestManager requestManager = new RequestManager(_identity);
     var uri = string.Format("/v2/images/{0}", imageId);
     requestManager.Delete(uri, "glance");
     ImageManager imageManager = new ImageManager(_identity);
     var deleteFinished = false;
     if (imageId != null)
     {
         while (!deleteFinished)
         {
             OpenstackImage image = imageManager.GetImage(imageId);
             if (image != null)
             {
                 Thread.Sleep(10000);
             }
             else
             {
                 deleteFinished = true;
             }
         }
     }
 }
 public IList<OpenstackImage> ListImages(Identity identity)
 {
     IList<OpenstackImage> list = new List<OpenstackImage>();
     RequestManager requestManager = new RequestManager(identity);
     var uri = "/images/detail";
     JObject response = requestManager.Get(uri, "nova");
     var tempinstances = response["images"];
     foreach (var tempinstance in tempinstances)
     {
         var instance = new OpenstackImage()
         {
             Id = tempinstance["id"].ToString(),
             Name = tempinstance["name"].ToString(),
             Status = tempinstance["status"].ToString(),
         };
         list.Add(instance);
     }
     return list;
 }
Example #14
0
        public override bool SetupRequestToProperDatabase(RequestManager rm)
        {
            var tenantId = DatabaseName;

            if (string.IsNullOrWhiteSpace(tenantId) || tenantId == "<system>")
            {
                landlord.LastRecentlyUsed.AddOrUpdate("System", SystemTime.UtcNow, (s, time) => SystemTime.UtcNow);
                var args = new BeforeRequestWebApiEventArgs
                {
                    Controller    = this,
                    IgnoreRequest = false,
                    TenantId      = "System",
                    Database      = landlord.SystemDatabase
                };
                rm.OnBeforeRequest(args);
                if (args.IgnoreRequest)
                {
                    return(false);
                }
                return(true);
            }

            Task <DocumentDatabase> resourceStoreTask;
            bool hasDb;

            try
            {
                hasDb = landlord.TryGetOrCreateResourceStore(tenantId, out resourceStoreTask);
            }
            catch (Exception e)
            {
                var msg = "Could not open database named: " + tenantId;
                Logger.WarnException(msg, e);
                throw new HttpException(503, msg, e);
            }
            if (hasDb)
            {
                try
                {
                    if (resourceStoreTask.Wait(TimeSpan.FromSeconds(30)) == false)
                    {
                        var msg = "The database " + tenantId +
                                  " is currently being loaded, but after 30 seconds, this request has been aborted. Please try again later, database loading continues.";
                        Logger.Warn(msg);
                        throw new TimeoutException(msg);
                    }
                    var args = new BeforeRequestWebApiEventArgs()
                    {
                        Controller    = this,
                        IgnoreRequest = false,
                        TenantId      = tenantId,
                        Database      = resourceStoreTask.Result
                    };
                    rm.OnBeforeRequest(args);
                    if (args.IgnoreRequest)
                    {
                        return(false);
                    }
                }
                catch (Exception e)
                {
                    string exceptionMessage   = e.Message;
                    var    aggregateException = e as AggregateException;
                    if (aggregateException != null)
                    {
                        exceptionMessage = aggregateException.ExtractSingleInnerException().Message;
                    }
                    var msg = "Could not open database named: " + tenantId + Environment.NewLine + exceptionMessage;

                    Logger.WarnException(msg, e);
                    throw new HttpException(503, msg, e);
                }

                landlord.LastRecentlyUsed.AddOrUpdate(tenantId, SystemTime.UtcNow, (s, time) => SystemTime.UtcNow);
            }
            else
            {
                var msg = "Could not find a database named: " + tenantId;
                Logger.Warn(msg);
                throw new HttpException(503, msg);
            }
            return(true);
        }
Example #15
0
 public void SetRequestManager(RequestManager requestManager)
 {
     _requestManager = requestManager;
 }
        public Instance GetInstance(string instanceId, Identity identity)
        {
            Instance instance;
            RequestManager requestManager = new RequestManager(identity);
            var uri = string.Format("/servers/{0}", instanceId);
            JObject response = requestManager.Get(uri, "nova");
            var tempinstance = response["server"];
            if (response != null)
            {
                instance = new Instance()
               {
                   Id = tempinstance["id"].ToString(),
                   Name = tempinstance["name"].ToString(),
                   status = (InstanceStatus)Enum.Parse(typeof(InstanceStatus), tempinstance["status"].ToString()),

               };

                return instance;
            }
            return null;
        }
Example #17
0
 public void TestTearDown()
 {
     _fakeRequestAccessor = null;
     _requestManager      = null;
 }
Example #18
0
 public BusinessManager(DataAccess dataAccess, EventLoggerAccess logger)
 {
     _StatusManager  = new StatusManager(dataAccess, logger);
     _RequestManager = new RequestManager(dataAccess, _StatusManager, logger);
 }
        public void TryToExecute_ResponseCaught_ShouldReturnTrueAndValue()
        {
            ConnectionFactory.Invocations.Clear();
            SenderProcessor.Invocations.Clear();

            var  message           = "{ test }";
            var  requestResult     = "test result";
            var  queueName         = "126_queue";
            var  timeToWait        = 5000;
            var  callbackQueueName = string.Empty;
            var  type       = string.Empty;
            var  queueName1 = string.Empty;
            var  message1   = string.Empty;
            bool?autoAck    = null;
            bool?durable    = null;
            bool?exclusive  = null;
            bool?autoDelete = null;

            var args = new BasicDeliverEventArgs {
                Body = Encoding.UTF8.GetBytes(requestResult)
            };

            Subscription.Setup(x => x.Next(It.IsAny <int>(), out args))
            .Returns(true);

            SubsctiptionFactory.Setup(x => x.CreateSubscription(It.IsAny <IModel>(), It.IsAny <string>(), It.IsAny <bool>()))
            .Callback <IModel, string, bool>((channelParam, callbackQueueNameParam, autoAckParam) =>
            {
                callbackQueueName = callbackQueueNameParam;
                autoAck           = autoAckParam;
            })
            .Returns(Subscription.Object);

            Model.Setup(x => x.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), null))
            .Callback <string, bool, bool, bool, IDictionary <string, object> >((queueParam, durableParam, exclusiveParam, autoDeleteParam, param) =>
            {
                queueName1 = queueParam;
                durable    = durableParam;
                exclusive  = exclusiveParam;
                autoDelete = autoDeleteParam;
            });
            Connection.Setup(x => x.CreateModel()).Returns(Model.Object);
            ConnectionFactory.Setup(x => x.CreateConnection()).Returns(Connection.Object);

            SenderProcessor.Setup(x => x.SendMessage(It.IsAny <string>(), It.IsAny <string>()))
            .Callback <string, string>((typeParam, messageParam) =>
            {
                type     = typeParam;
                message1 = messageParam;
            });

            var service = new RequestManager(ConnectionFactory.Object, SenderProcessor.Object, SubsctiptionFactory.Object, timeToWait);

            var taskType = "test";
            var result   = service.TryToExecute(taskType, message, queueName);

            ConnectionFactory.Verify(x => x.CreateConnection(), Times.Once);
            Connection.Verify(x => x.CreateModel(), Times.Once);
            Connection.Verify(x => x.Close(), Times.Once);
            Model.Verify(x => x.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), null), Times.Once);
            Connection.Verify(x => x.Close(), Times.Once);
            SenderProcessor.Verify(x => x.SendMessage(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            SubsctiptionFactory.Verify(x => x.CreateSubscription(It.IsAny <IModel>(), It.IsAny <string>(), It.IsAny <bool>()), Times.Once);
            Subscription.Verify(x => x.Next(It.IsAny <int>(), out args), Times.Once);
            Assert.AreEqual(result.Value, requestResult);
            Assert.IsTrue(result.Result);
            Assert.AreEqual(type, taskType);
            Assert.AreEqual(message1, message);
            Assert.AreEqual(callbackQueueName, queueName);
            Assert.AreEqual(queueName1, queueName);
            Assert.IsFalse(autoAck.Value);
            Assert.IsFalse(durable.Value);
            Assert.IsFalse(exclusive.Value);
            Assert.IsTrue(autoDelete.Value);
            Assert.AreEqual(autoAck, false);
            Assert.AreEqual(durable, false);
            Assert.AreEqual(exclusive, false);
            Assert.AreEqual(autoDelete, true);
        }
 public Instance Get(string id, Identity identity)
 {
     Instance instance = null;
     RequestManager requestManager = new RequestManager(identity);
     var uri = String.Format("/servers/{0}", id);
     JObject response = requestManager.Get(uri, "nova");
     var tempinstance = response["server"];
     instance = new Instance()
     {
         Id = tempinstance["id"].ToString(),
         Name = tempinstance["name"].ToString()
     };
     return instance;
 }
Example #21
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="configuration"></param>
        protected override void StartApplication(ApplicationConfiguration configuration)
        {
            lock (m_lock)
            {
                try
                {
                    // create the datastore for the instance.
                    m_serverInternal = new ServerInternalData(
                        ServerProperties,
                        configuration,
                        MessageContext,
                        new CertificateValidator(),
                        InstanceCertificate);

                    // create the manager responsible for providing localized string resources.
                    ResourceManager resourceManager = CreateResourceManager(m_serverInternal, configuration);

                    // create the manager responsible for incoming requests.
                    RequestManager requestManager = new RequestManager(m_serverInternal);

                    // create the master node manager.
                    MasterNodeManager masterNodeManager = new MasterNodeManager(m_serverInternal, configuration, null);

                    // add the node manager to the datastore.
                    m_serverInternal.SetNodeManager(masterNodeManager);

                    // put the node manager into a state that allows it to be used by other objects.
                    masterNodeManager.Startup();

                    // create the manager responsible for handling events.
                    EventManager eventManager = new EventManager(m_serverInternal, (uint)configuration.ServerConfiguration.MaxEventQueueSize);

                    // creates the server object.
                    m_serverInternal.CreateServerObject(
                        eventManager,
                        resourceManager,
                        requestManager);


                    // create the manager responsible for aggregates.
                    m_serverInternal.AggregateManager = CreateAggregateManager(m_serverInternal, configuration);

                    // start the session manager.
                    SessionManager sessionManager = new SessionManager(m_serverInternal, configuration);
                    sessionManager.Startup();

                    // start the subscription manager.
                    SubscriptionManager subscriptionManager = new SubscriptionManager(m_serverInternal, configuration);
                    subscriptionManager.Startup();

                    // add the session manager to the datastore.
                    m_serverInternal.SetSessionManager(sessionManager, subscriptionManager);

                    ServerError = null;

                    // set the server status as running.
                    SetServerState(ServerState.Running);

                    // monitor the configuration file.
                    if (!String.IsNullOrEmpty(configuration.SourceFilePath))
                    {
                        var m_configurationWatcher = new ConfigurationWatcher(configuration);
                        m_configurationWatcher.Changed += new EventHandler <ConfigurationWatcherEventArgs>(this.OnConfigurationChanged);
                    }

                    CertificateValidator.CertificateUpdate += OnCertificateUpdate;
                    //60s后开始清理过期服务列表,此后每60s检查一次
                    m_timer = new Timer(ClearNoliveServer, null, 60000, 60000);
                    Console.WriteLine("Discovery服务已启动完成,请勿退出程序!!!");
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Unexpected error starting application");
                    m_serverInternal = null;
                    ServiceResult error = ServiceResult.Create(e, StatusCodes.BadInternalError, "Unexpected error starting application");
                    ServerError = error;
                    throw new ServiceResultException(error);
                }
            }
        }
 public AuthenticateController(RequestManager requestManager)
 {
     _requestManager = requestManager;
 }
Example #23
0
 private void InitManager()
 {
     clientManager  = new ClientManager(this);
     requestManager = new RequestManager(this);
 }
Example #24
0
        /// <summary>
        /// Before "adding" an image to an object the client must upload a source file to a dated directory within intermediary storage.
        /// Pass in the source file info along with any cropping or enhancement instructions and you will get back the final image id after processing is complete/
        /// Intermediary directory MUST named by todays date: "DD-MM-YYYY", this directory will be garbage collected by the Custodian at a set interval
        /// </summary>
        public DataAccessResponseType ProcessImage(string accountId, ImageProcessingManifestModel imageManifest, ImageCropCoordinates imageCropCoordinates, string requesterId, RequesterType requesterType, ImageEnhancementInstructions imageEnhancementInstructions, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var account = AccountManager.GetAccount(accountId);

            #region Adjust negative crop coordinates for top/left pixel

            //if any top/left values fall below 0 we adjust to 0
            if (imageCropCoordinates.Top < 0)
            {
                imageCropCoordinates.Top = 0;
            }
            if (imageCropCoordinates.Left < 0)
            {
                imageCropCoordinates.Left = 0;
            }

            #endregion

            #region Validate Request

            var requesterName  = string.Empty;
            var requesterEmail = string.Empty;

            var requestResponseType = RequestManager.ValidateRequest(requesterId,
                                                                     requesterType, out requesterName, out requesterEmail,
                                                                     Sahara.Core.Settings.Platform.Users.Authorization.Roles.Manager,
                                                                     Sahara.Core.Settings.Accounts.Users.Authorization.Roles.Manager);

            if (!requestResponseType.isApproved)
            {
                //Request is not approved, send results:
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = requestResponseType.requestMessage
                });
            }

            #endregion

            #region Validate Plan Capabilities

            // If enhancement instructions are sent, verify that current plan allows for it
            if (imageEnhancementInstructions != null && account.PaymentPlan.AllowImageEnhancements == false)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Your account plan does not allow for image enhancements, please submit your job without enhancement instructions."
                });
            }

            //Verify that current image count is below maximum allowed by this plan
            //if (ApplicationImagesManager.GetApplicationImageCount(account) >= account.PaymentPlan.MaxProducts)
            //{
            //Log Limitation Issues (or send email) so that Platform Admins can immediatly contact Accounts that have hit their limits an upsell themm
            //Sahara.Core.Logging.PlatformLogs.Helpers.PlatformLimitationsHelper.LogLimitationAndAlertAdmins("images", account.AccountID.ToString(), account.AccountName);

            //return new DataAccessResponseType { isSuccess = false, ErrorMessage = "Your account plan does not allow for more than " + account.PaymentPlan.MaxProducts + " images, please update your plan." };
            //}

            #endregion

            var result = ApplicationImageProcessingManager.ProcessAndRecordApplicationImage(account, imageManifest, imageCropCoordinates, imageEnhancementInstructions);

            #region Log Account Activity


            if (result.isSuccess)
            {
                /*try
                 * {
                 *
                 *  //Object Log ---------------------------
                 *  AccountLogManager.LogActivity(
                 *      accountId,
                 *      CategoryType.ApplicationImage,
                 *      ActivityType.ApplicationImage_Created,
                 *      "Application image created",
                 *      requesterName + " created an application image",
                 *      requesterId,
                 *      requesterName,
                 *      requesterEmail,
                 *      null,
                 *      null,
                 *      result.SuccessMessage);
                 * }
                 * catch { }*/
            }

            #endregion

            #region Invalidate Account Capacity Cache

            //AccountCapacityManager.InvalidateAccountCapacitiesCache(accountId);

            #endregion

            #region Invalidate Account API Caching Layer

            Sahara.Core.Common.Redis.ApiRedisLayer.InvalidateAccountApiCacheLayer(account.AccountNameKey);

            #endregion

            return(result);
        }
Example #25
0
 /// <summary>
 /// Sends a request over the IQueue connection and runs the
 /// action when the response is received
 /// </summary>
 /// <typeparam name="R"></typeparam>
 /// <param name="pMessage"></param>
 /// <param name="pAction"></param>
 public void Request <R>(IRequestMessage pMessage, Action <R> pAction) where R : IResponseMessage
 {
     RequestManager.Request <R>(new Request <R>(this, pMessage, pAction));
 }
Example #26
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="requestManager">manager used to send/receive data from/to server</param>
 /// <param name="serverAddress">address of SmartLib server</param>
 public BaseDataManager(RequestManager requestManager, string serverAddress)
 {
     RequestManager = requestManager;
     ServerAddress = serverAddress;
 }
        public string CreateSnapshot(string instanceId, Identity identity)
        {
            var snapshotName = "Snapshot-" + Guid.NewGuid().ToString().Substring(0, 4);
            IList<OpenstackImage> list = new List<OpenstackImage>();
            RequestManager requestManager = new RequestManager(identity);
            var uri = string.Format("/servers/{0}/action", instanceId);

            var bodyObject = new RequestBodyWrapper()
            {
                createImage = new RequestBody()
                {
                    name = snapshotName,
                    metadata = new Metadata()
                    {
                        CreatedBy = "Created by Atlas"
                    }
                }
            };
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string body = oSerializer.Serialize(bodyObject);
            JObject response = requestManager.Action(uri, "nova", body, HttpStatusCode.Accepted);
            return snapshotName;
        }
        protected virtual void SendRequest(object sender, DoWorkEventArgs e)
        {
            JsonResponseDictionary responseValues;

            RequestManager requestManager = new RequestManager();
            string jsonToSend = getJsonToSend();

            requestManager.SendPOSTRequest(uri, jsonToSend, "", "", false);
            if (requestManager.LastResponse == null)
            {
                responseValues = new JsonResponseDictionary();
                responseValues["Status"] = "error";
                responseValues["ErrorMessage"] = "Unable to connect to server";
                responseValues["ErrorCode"] = "00";
            }
            else
            {
                try
                {
                    responseValues = JsonConvert.DeserializeObject<JsonResponseDictionary>(requestManager.LastResponse);
                }
                catch
                {
                    responseValues = new JsonResponseDictionary();
                    responseValues["Status"] = "error";
                    responseValues["ErrorMessage"] = "Unexpected response";
                    responseValues["ErrorCode"] = "01";
                }
            }

            e.Result = responseValues;
        }
 public OpenstackImage GetImage(string imageId, Identity identity)
 {
     OpenstackImage image;
     RequestManager requestManager = new RequestManager(identity);
     var uri = string.Format("/v2/images/{0}", imageId);
     JObject response = requestManager.Get(uri, "glance");
     var tempinstance = response;
     if (response != null)
     {
         image = new OpenstackImage()
         {
             Id = tempinstance["id"].ToString(),
             Name = tempinstance["name"].ToString(),
             Status = tempinstance["status"].ToString(),
         };
         if (tempinstance["container_format"] != null)
             image.ContainerFormat = tempinstance["container_format"].ToString();
         if (tempinstance["disk_format"] != null)
             image.DiskFormat = tempinstance["disk_format"].ToString();
         return image;
     }
     return null;
 }
 /// <summary>
 /// Constructor. For more information see parent constructor.
 /// </summary>
 /// <param name="requestManager"></param>
 /// <param name="server"></param>
 public ReviewRequestManager(RequestManager requestManager, string server)
         : base(requestManager, server)
 {
 }
Example #31
0
 public UserController(RequestAttributes requestAttributes, UserManager manager, ItemManager itemManager, RequestManager requestManager)
 {
     _requestAttributes = requestAttributes;
     _manager           = manager;
     _itemManager       = itemManager;
     _requestManager    = requestManager;
 }
Example #32
0
 public void TestSetup()
 {
     _fakeRequestAccessor = new FakeRequestAccessor();
     _requestManager      = new RequestManager(_fakeRequestAccessor);
 }
Example #33
0
        /// <summary>
        /// Constructor. For more information see parent constructor.
        /// </summary>
        /// <param name="requestManager"></param>
        /// <param name="serverAddress"></param>
        public BookRequestManager(RequestManager requestManager, string serverAddress)
            : base(requestManager, serverAddress)
        {

        }
        public override bool SetupRequestToProperDatabase(RequestManager rm)
        {
            var tenantId = CountersName;

            if (string.IsNullOrWhiteSpace(tenantId))
            {
                throw new HttpException(503, "Could not find a counter with no name");
            }

            Task <CounterStorage> resourceStoreTask;
            bool hasDb;

            try
            {
                hasDb = landlord.TryGetOrCreateResourceStore(tenantId, out resourceStoreTask);
            }
            catch (Exception e)
            {
                var msg = "Could open counter named: " + tenantId;
                Logger.WarnException(msg, e);
                throw new HttpException(503, msg, e);
            }
            if (hasDb)
            {
                try
                {
                    if (resourceStoreTask.Wait(TimeSpan.FromSeconds(30)) == false)
                    {
                        var msg = "The counter " + tenantId +
                                  " is currently being loaded, but after 30 seconds, this request has been aborted. Please try again later, file system loading continues.";
                        Logger.Warn(msg);
                        throw new HttpException(503, msg);
                    }
                    var args = new BeforeRequestWebApiEventArgs
                    {
                        Controller    = this,
                        IgnoreRequest = false,
                        TenantId      = tenantId,
                        Counters      = resourceStoreTask.Result
                    };
                    rm.OnBeforeRequest(args);
                    if (args.IgnoreRequest)
                    {
                        return(false);
                    }
                }
                catch (Exception e)
                {
                    var msg = "Could open counters named: " + tenantId;
                    Logger.WarnException(msg, e);
                    throw new HttpException(503, msg, e);
                }

                landlord.LastRecentlyUsed.AddOrUpdate(tenantId, SystemTime.UtcNow, (s, time) => SystemTime.UtcNow);
            }
            else
            {
                var msg = "Could not find a counter named: " + tenantId;
                Logger.Warn(msg);
                throw new HttpException(503, msg);
            }
            return(true);
        }
        public void TestDefaultDeal()
        {
            var deal = RequestManager.GetDeal(TargetURL.GenerateDefaultURL());

            Assert.IsTrue(deal.IsValidDeal());
        }
 public IList<Instance> ListInstances(Identity identity)
 {
     IList<Instance> list = new List<Instance>();
     RequestManager requestManager = new RequestManager(identity);
     var uri = "/servers/detail";
     JObject response = requestManager.Get(uri, "nova");
     var tempinstances = response["servers"];
     foreach (var tempinstance in tempinstances)
     {
         var instance = new Instance()
         {
             Id = tempinstance["id"].ToString(),
             Name = tempinstance["name"].ToString(),
             FlavorName = new FlavorManager(identity).Get(tempinstance["flavor"]["id"].ToString(), identity).Name
         };
         list.Add(instance);
     }
     return list;
 }
Example #37
0
        /// <summary>
        /// Constructor. For more information see parent constructor.
        /// </summary>
        /// <param name="requestManager"></param>
        /// <param name="serverAddress"></param>
        public UserReuqestManager(RequestManager requestManager, string serverAddress)
                : base(requestManager, serverAddress)
        {

        }
 public void Setup()
 {
     requestManager = new RequestManager(connStr);
 }