Inheritance: GeneralResponse
Esempio n. 1
0
        public void SendStatusRequestReturnsTooManyRequestsResponseImmediately()
        {
            // given
            var tooManyRequestsResponse = new StatusResponse(Substitute.For <ILogger>(), string.Empty, Response.HttpTooManyRequests, new Dictionary <string, List <string> >());

            context.IsShutdownRequested.Returns(false);
            httpClient.SendStatusRequest().Returns(tooManyRequestsResponse);

            // when
            var obtained = BeaconSendingRequestUtil.SendStatusRequest(context, 3, 1000);

            // then
            Assert.That(obtained, Is.SameAs(tooManyRequestsResponse));

            context.Received(1).GetHTTPClient();
            context.DidNotReceiveWithAnyArgs().Sleep(0);
            httpClient.Received(1).SendStatusRequest();
        }
        public async Task <IActionResult> Status()
        {
            StatusResponse response = new StatusResponse
            {
                Dev = new EnvironmentStatus
                {
                    Frontend = await this.GetServiceStatus(@"http://example.com"),
                    Backend  = await this.GetServiceStatus(@"http://example.com")
                },
                Stage = new EnvironmentStatus
                {
                    Frontend = await this.GetServiceStatus(@"http://example.com"),
                    Backend  = await this.GetServiceStatus(@"http://notexist.example.com")
                }
            };

            return(Json(response));
        }
Esempio n. 3
0
        public void TestGetStatus()
        {
            WebClient wc = WebClient.getInstance();

            TokenRequest tr = new TokenRequest();

            tr.username = username;
            tr.password = password;

            string         tok = wc.getToken(tr);
            StatusResponse sr  = wc.getStatus(tr);

            Assert.NotNull(sr);

            Assert.NotNull(sr.systemStatus[0]);

            Assert.AreEqual("Online", sr.systemStatus[0].status);
        }
Esempio n. 4
0
 private static void HandleStatusResponse(IBeaconSendingContext context, StatusResponse statusResponse)
 {
     if (statusResponse != null)
     {
         context.HandleStatusResponse(statusResponse);
     }
     // if initial time sync failed before
     if (context.IsTimeSyncSupported && !context.IsTimeSynced)
     {
         // then retry initial time sync
         context.CurrentState = new BeaconSendingTimeSyncState(true);
     }
     else if (statusResponse != null && context.IsCaptureOn)
     {
         // capturing is re-enabled again, but only if we received a response from the server
         context.CurrentState = new BeaconSendingCaptureOnState();
     }
 }
        private void ReceiveStatusResponse(byte[] body)
        {
            Log.Trace("Receiving Reveal Response", "ReceiveRevealResponse");

            StatusResponse response = StatusResponse.FromBytes(body);

            String result = "Server is ";

            result += response.ServerRunning ? "Running." : "Terminated.";

            Notification notice = new ChatNotification()
            {
                Text   = result,
                Sender = "GP"
            };

            notice.Raise();
        }
Esempio n. 6
0
        public void ProcessStatus(StatusRequest request)
        {
            StatusResponse response = new StatusResponse();

            response.AdoptHeader(request);
            response.Component                  = new StatusComponent();
            response.Component.Type             = "Mosaic";
            response.Component.Description      = "Mosaic Service";
            response.Component.State            = this.status;
            response.Component.StateDescription = this.stateDescriptions;

            if (request.IncludeDetails)
            {
                response.Component.SubComponents = this.statusSubComponentList.ToArray();
            }

            request.ConverterStream.Write(response);
        }
Esempio n. 7
0
        /// <summary>
        /// Updates the Spotify info.
        /// Disconnects if we can't a track.
        /// </summary>
        /// <param name="sender">Ignored.</param>
        /// <param name="e">Ignored.</param>
        private void _refreshTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _lastTrack       = _currentResponse?.Track?.TrackResource.Uri;
            _currentResponse = _spotify.GetStatus();

            if (_currentResponse.Track == null)
            {
                Disconnect();
                return;
            }

            if (_lastTrack != _currentResponse.Track.TrackResource.Uri)
            {
                CountedSeconds = 0;
                _counterTimer.Start();
                UpdateCurrentTrackInfo();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Retrieves a list of instances
        /// </summary>
        public static List <NutritionPlan_db> GetCollection(
            DbContext context, out StatusResponse statusResponse)
        {
            try
            {
                // Get from database
                DataTable table = context.ExecuteDataQueryCommand
                                  (
                    commandText: "SELECT * FROM nutritionPlans",
                    parameters: new Dictionary <string, object>()
                {
                },
                    message: out string message
                                  );
                if (table == null)
                {
                    throw new Exception(message);
                }

                //Parse data
                List <NutritionPlan_db> instances = new List <NutritionPlan_db>();
                foreach (DataRow row in table.Rows)
                {
                    instances.Add(new NutritionPlan_db
                                  (
                                      id: Convert.ToInt32(row["id"]),
                                      name: row["name"].ToString(),
                                      description: row["description"].ToString(),
                                      groceryList: row["grocery_list"].ToString(),
                                      mealPlan: row["meal_plan"].ToString()
                                  )
                                  );
                }

                //return value
                statusResponse = new StatusResponse("Nutrition Plans list has been retrieved successfully");
                return(instances);
            }
            catch (Exception exception)
            {
                statusResponse = new StatusResponse(exception);
                return(null);
            }
        }
Esempio n. 9
0
        public ActionResult Export(CustomerModels model)
        {
            try
            {
                if (model.ListStores == null)
                {
                    ModelState.AddModelError("ListStores", CurrentUser.GetLanguageTextFromKey("Please choose store."));
                    return(View(model));
                }

                XLWorkbook     wb        = new XLWorkbook();
                var            wsSetMenu = wb.Worksheets.Add("Sheet1");
                StatusResponse response  = _factory.Export(ref wsSetMenu, model.ListStores);

                if (!response.Status)
                {
                    ModelState.AddModelError("", response.MsgError);
                    return(View(model));
                }

                ViewBag.wb = wb;
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Charset         = UTF8Encoding.UTF8.WebName;
                Response.ContentEncoding = UTF8Encoding.UTF8;
                Response.ContentType     = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", CommonHelper.GetExportFileName("Customer").Replace(" ", "_")));

                using (var memoryStream = new System.IO.MemoryStream())
                {
                    wb.SaveAs(memoryStream);
                    memoryStream.WriteTo(HttpContext.Response.OutputStream);
                    memoryStream.Close();
                }
                HttpContext.Response.End();
                return(RedirectToAction("Export"));
            }
            catch (Exception e)
            {
                _logger.Error("Customer_Export: " + e);
                return(new HttpStatusCodeResult(400, e.Message));
            }
        }
Esempio n. 10
0
        /// <summary>
        /// These are all my Application.Current.Properties[]
        /// </summary>
        /// <param name="code"> Application.Current.Properties["VerificationCode"] </param>
        /// <returns></returns>


        public static async Task <StatusResponse> VerifyPhonenumberorEmail(string phonenumber, string email)
        {
            StatusResponse status = new StatusResponse();

            Random       random     = new Random();
            var          code       = random.Next(1000, 9999);
            const string accountSid = "AC1f815e6c6da5912897ef072beb251811";
            const string authToken  = "6b4b643a8683eec2bd69917fa4250c5c";

            Application.Current.Properties["VerificationCode"] = code;
            await Application.Current.SavePropertiesAsync();

            await Task.Run(() =>
            {
                TwilioClient.Init(accountSid, authToken);

                var message = MessageResource.Create(
                    body: $"Your Verification Code is {code}",
                    from: new Twilio.Types.PhoneNumber("+12029521263"),
                    to: new Twilio.Types.PhoneNumber($"+234{phonenumber}"));


                if (message.Status.ToString() == "queued")
                {
                    status.code = 200;

                    status.message = "success";
                }
                else
                {
                    status.code = 402;

                    status.message = "failed";
                }
            });

            if (status.code == 200)
            {
                await ExecuteEmail(email, code);
            }

            //  status.code = 200;
            return(status);
        }
Esempio n. 11
0
        //Version 1.0.4
        static void Main(string[] args)
        {
            //Create class with the API Key
            WhaleAlert whaleAlert = new WhaleAlert("API Key here");
            //Get request --> Reponse Status Object
            StatusResponse Status = whaleAlert.GetStatus();

            //Error Handling
            if (Status.Success == false)
            {
                Console.WriteLine(Status.Error.Message);
                return;
            }
            //Success
            Console.WriteLine(Status.Status.Result);

            //Blockchain Count
            Console.WriteLine(Status.Status.BlockchainCount);

            //List of all Blockchains
            foreach (Blockchain entry in Status.Status.Blockchains)
            {
                string symbols = "";
                foreach (string s in entry.Symbols)
                {
                    symbols += s + ",";
                }

                Console.WriteLine($"{entry.Name} [{symbols}]: {entry.Status}");
            }

            Console.WriteLine("\n");
            //Get request --> Reponse Transactions Object
            TransactionsResponse transactionsResponse = whaleAlert.GetTransactions(1550237797);

            //List of Transcations
            int counter = 0;

            foreach (Transactions entry in transactionsResponse.Transactions.Transactions)
            {
                counter++;
                Console.WriteLine($"{counter}. {entry.Symbol}: {entry.Amount}; USD: {entry.AmountUsd}");
            }
        }
Esempio n. 12
0
        public StatusResponse Export(ref IXLWorksheet ws, List <string> lstStore, List <string> lstMerchatIds)
        {
            StatusResponse Response = new StatusResponse();

            try
            {
                List <UnitOfMeasureModel> listData = new List <UnitOfMeasureModel>();
                listData = GetData(lstMerchatIds);
                listData = listData.OrderBy(x => x.Name).ToList();
                int cols = 5;
                //Header
                int row = 1;
                ws.Cell("A" + row).Value = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Index") /*"Index"*/;
                ws.Cell("B" + row).Value = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Code") /*"Code"*/;
                ws.Cell("C" + row).Value = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Name") /*"Name"*/;
                ws.Cell("D" + row).Value = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Description") /*"Description"*/;
                ws.Cell("E" + row).Value = _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Status") /*"Status"*/;
                //Item
                row = 2;
                int countIndex = 1;
                foreach (var item in listData)
                {
                    ws.Cell("A" + row).Value = countIndex;
                    ws.Cell("B" + row).Value = item.Code;
                    ws.Cell("C" + row).Value = item.Name;
                    ws.Cell("D" + row).Value = item.Description;
                    ws.Cell("E" + row).Value = item.IsActive ? _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("Active")/*"Active"*/
                                    : _AttributeForLanguage.CurrentUser.GetLanguageTextFromKey("InActive") /*"InActive"*/;
                    row++;
                    countIndex++;
                }
                FormatExcelExport(ws, row, cols);
                Response.Status = true;
            }
            catch (Exception e)
            {
                Response.Status   = false;
                Response.MsgError = e.Message;
            }
            finally
            {
            }
            return(Response);
        }
Esempio n. 13
0
        /// <summary>
        /// Read track info from Spotify API and update local variables
        /// </summary>
        private static void UpdateTrack()
        {
            if (Spotify == null)
            {
                return;
            }

            StatusResponse status = Spotify.GetStatus();

            //check if an ad is playing
            if (status == null || status.Track == null)
            {
                SpotifyIsAdPlaying = true;
                return;
            }
            else
            {
                SpotifyIsAdPlaying = false;
            }

            SpotifyCurrentTrack = status.Track;

            if ((!status.NextEnabled && !status.PrevEnabled) ||
                (SpotifyCurrentTrack.AlbumResource == null || SpotifyCurrentTrack.ArtistResource == null))
            {
                //invalid
                return;
            }

            if (SpotifyCurrentTrack != null)
            {
                SpotifyTrackNumber++;
                if (SpotifyTrackNumber % TriggerMod == 0)
                {
                    //Launch a new async task
                    new Task(TriggerAction).Start();
                }

                Console.WriteLine(String.Format("Spotify is playing: {0}: {1} - {2}", SpotifyTrackNumber, SpotifyCurrentTrack.ArtistResource.Name, SpotifyCurrentTrack.TrackResource.Name));

                SpotifyLastTrack = SpotifyCurrentTrack;
            }
        }
Esempio n. 14
0
        private async Task <StatusResponse> ProcessGradeLevel(GradeLevelRequest request)
        {
            StatusResponse response   = new StatusResponse();
            var            gradeLevel = _mapper.Map <GradeLevel>(request);

            if (request.Id.HasValue)
            {
                response.Success = await _dbHelper.UpdateGradeLevel(gradeLevel);

                response.Message = response.Success ? "Successfully updated grade level" : "Failed to update grade level";
            }
            else
            {
                response.Success = await _dbHelper.InsertGradeLevel(gradeLevel);

                response.Message = response.Success ? "Successfully inserted grade level" : "Failed to insert grade level";
            }
            return(response);
        }
        public void UnsuccessfulFinishedSessionsAreNotRemovedFromCache()
        {
            //given
            var statusResponse = new StatusResponse(logger, string.Empty, Response.HttpBadRequest, new Dictionary <string, List <string> >());
            var target         = new BeaconSendingCaptureOnState();

            var finishedSession = new SessionWrapper(CreateValidSession("127.0.0.1"));

            finishedSession.UpdateBeaconConfiguration(new BeaconConfiguration(1, DataCollectionLevel.OFF, CrashReportingLevel.OFF));
            finishedSessions.Add(finishedSession);
            httpClient.SendBeaconRequest(Arg.Any <string>(), Arg.Any <byte[]>()).Returns(statusResponse);

            //when calling execute
            target.Execute(context);

            var tmp = context.Received(1).FinishedAndConfiguredSessions;

            context.Received(0).RemoveSession(finishedSession);
        }
Esempio n. 16
0
        public async Task Delete()
        {
            var expectedUri = new Uri("https://api.soundcloud.com/playlists/130208739?");

            var gatewayMock = new Mock <ISoundCloudApiGateway>(MockBehavior.Strict);

            var statusResponse = new StatusResponse();

            gatewayMock.Setup(x => x.SendDeleteRequestAsync <StatusResponse>(expectedUri)).ReturnsAsync(statusResponse);

            // Act
            var playlist = new Playlist {
                Id = PlaylistId
            };
            var result = await new Playlists(gatewayMock.Object).DeleteAsync(playlist);

            // Assert
            Assert.That(result, Is.SameAs(statusResponse));
        }
        public StatusResponse Delete(Guid identifier)
        {
            StatusResponse response = new StatusResponse();

            try
            {
                StatusViewModel Status = new StatusViewModel();
                Status.Identifier = identifier;
                response          = WpfApiHandler.SendToApi <StatusViewModel, StatusResponse>(Status, "Delete");
            }
            catch (Exception ex)
            {
                response.Status  = new StatusViewModel();
                response.Success = false;
                response.Message = ex.Message;
            }

            return(response);
        }
Esempio n. 18
0
        public async Task Follow()
        {
            var expectedUri = new Uri("https://api.soundcloud.com/me/followings/164386753?");

            var gatewayMock = new Mock <ISoundCloudApiGateway>(MockBehavior.Strict);

            var statusResponse = new StatusResponse();

            gatewayMock.Setup(x => x.SendPutRequestAsync <StatusResponse>(expectedUri)).ReturnsAsync(statusResponse);

            // Act
            var userToFollow = new User {
                Id = UserId
            };
            var result = await new Me(gatewayMock.Object).FollowAsync(userToFollow);

            // Assert
            Assert.That(result, Is.SameAs(statusResponse));
        }
Esempio n. 19
0
        public async Task DeleteWebProfile()
        {
            var expectedUri = new Uri("https://api.soundcloud.com/me/web-profiles/123?");

            var gatewayMock = new Mock <ISoundCloudApiGateway>(MockBehavior.Strict);

            var statusResponse = new StatusResponse();

            gatewayMock.Setup(x => x.SendDeleteRequestAsync <StatusResponse>(expectedUri)).ReturnsAsync(statusResponse);

            // Act
            var profile = new WebProfile {
                Id = 123
            };
            var result = await new Me(gatewayMock.Object).DeleteWebProfileAsync(profile);

            // Assert
            Assert.That(result, Is.SameAs(statusResponse));
        }
Esempio n. 20
0
        /// <summary>
        /// Status gets the status of the member in async.
        /// </summary>
        /// <param name="request">Status Request</param>
        /// <returns>Status response</returns>
        public async Task <StatusResponse> StatusASync(StatusRequest request)
        {
            StatusResponse response = new StatusResponse();

            try
            {
                response = await _maintenanceClient.StatusAsync(request);
            }
            catch (RpcException)
            {
                ResetConnection();
                throw;
            }
            catch
            {
                throw;
            }
            return(response);
        }
Esempio n. 21
0
        public async Task <IActionResult> Refund(RefundRequest request)
        {
            PaymentRequest paymentRequest = new PaymentRequest
            {
                Amount          = request.Amount,
                AuthorizationId = request.AuthorizationId
            };
            TransactionOutput serviceResponse = await _service.RefundPayment(paymentRequest);

            StatusResponse response = new StatusResponse
            {
                AmountAvailable = serviceResponse.AmountAvailable,
                Currency        = serviceResponse.Currency,
                Error           = serviceResponse.Error,
                Success         = serviceResponse.Success
            };

            return(Ok(response));
        }
Esempio n. 22
0
 private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     status = LocalAPI.GetStatus();
     if (status == null)
     {
         return;                 // Spotify is probably not running
     }
     if (status.Track == null)
     {
         // Spotify is running, but we are not recieving track info, reconnect
         try
         {
             LocalAPI.Connect();
         }
         catch (System.Net.WebException)
         {
         }
     }
 }
Esempio n. 23
0
        private bool RegisterFunction(object caller, StatusEventArgs args)
        {
            if (args.SendingClient.ClientProtocol.Format == NetworkProtocol.JavaNetty)
            {
                if (args.SendingClient.Data.StatusRequest && !args.SendingClient.Data.StatusRespond)
                {
                    StatusResponse packet = new StatusResponse()
                    {
                        StatusData = new Data.DataTypes.Chat("{\"version\":{\"name\":\"Wak, 1.15.x\",\"protocol\":" + args.SendingClient.ClientProtocol.Version + "},\"players\":{\"max\":300,\"online\":0,\"sample\":[{\"name\":\"Wak\"" +
                                                             ",\"id\":\"00000000-0000-0000-0000-000000000000\"}" +
                                                             "]},\"description\":{\"extra\":[{\"color\":\"white\",\"text\":\"grief survival!\\n\"},{\"color\":\"dark_purple\",\"text\":\"DRAGONS!\"}],\"text\":\"\"}}")
                    };
                    PacketManager.WriteToClient(args.SendingClient, packet);

                    return(true);
                }
            }
            return(false);
        }
Esempio n. 24
0
        public IActionResult GetStatus()
        {
            var response = new StatusResponse();

            response.response_code       = 0;
            response.power               = "on";
            response.sleep               = 0;
            response.volume              = 30;
            response.mute                = false;
            response.max_volume          = 60;
            response.input               = "mc_link";
            response.distribution_enable = false;
            response.equalizer           = new Equalizer {
                low = 0, mid = 0, high = 0
            };
            response.link_control  = "standard";
            response.disable_flags = 0;
            return(new ObjectResult(response));
        }
Esempio n. 25
0
        public ActionResult Get()
        {
            _logger.LogInformation("Get Status");
            var query = new StatusResponse
            {
                Status    = WorkStatus.Work,
                Work      = ModStatus.GWC,
                Heater    = false,
                ByPass    = false,
                Errors    = 0,
                BateryLow = true,
                //TODO: Remove Changed flags to sse ping response
                ChangedParameters = true,
                ChangedCalendar   = true,
                ChangedMod        = true,
            };

            return(Ok(query));
        }
        public async Task <bool> MarkReadMesages(string userName, string token, string uuid, List <int> messageIDList)
        {
            if (userName == "" || token == "" || uuid == "" || messageIDList == null)
            {
                return(false);
            }

            if (messageIDList.Count == 0)
            {
                return(true);
            }

            StatusResponse response = await awsHttpClient.MarkReadMassagesAsync(new MarkMessageRequest()
            {
                Username = userName, Token = token, UID = uuid, MessageIDList = messageIDList
            });

            return(response != null);
        }
Esempio n. 27
0
        /// <summary>
        /// Status gets the status of the member.
        /// </summary>
        /// <param name="request">Status Request</param>
        /// <returns>Status response</returns>
        public StatusResponse Status(StatusRequest request)
        {
            StatusResponse response = new StatusResponse();

            try
            {
                response = _maintenanceClient.Status(request);
            }
            catch (RpcException)
            {
                ResetConnection();
                throw;
            }
            catch
            {
                throw;
            }
            return(response);
        }
Esempio n. 28
0
        /// <summary>
        /// Retrieves a list of instances
        /// </summary>
        public static List <SleepLog_db> GetCollection(
            DbContext context, out StatusResponse statusResponse)
        {
            try
            {
                // Get from database
                DataTable table = context.ExecuteDataQueryCommand
                                  (
                    commandText: "SELECT * FROM sleepLogs",
                    parameters: new Dictionary <string, object>()
                {
                },
                    message: out string message
                                  );
                if (table == null)
                {
                    throw new Exception(message);
                }

                //Parse data
                List <SleepLog_db> instances = new List <SleepLog_db>();
                foreach (DataRow row in table.Rows)
                {
                    instances.Add(new SleepLog_db
                                  (
                                      id: Convert.ToInt32(row["id"]),
                                      date: Convert.ToDateTime(row["date"]),
                                      time: TimeSpan.Parse(row["time"].ToString()),
                                      sleepDuration: TimeSpan.Parse(row["sleep_duration"].ToString())
                                  )
                                  );
                }

                //return value
                statusResponse = new StatusResponse("Sleep logs list has been retrieved successfully");
                return(instances);
            }
            catch (Exception exception)
            {
                statusResponse = new StatusResponse(exception);
                return(null);
            }
        }
Esempio n. 29
0
        public async Task Unlike()
        {
            var expectedUri = new Uri("https://api.soundcloud.com/me/favorites/215850263?");

            var gatewayMock = new Mock <ISoundCloudApiGateway>(MockBehavior.Strict);

            var statusResponse = new StatusResponse();

            gatewayMock.Setup(x => x.SendDeleteRequestAsync <StatusResponse>(expectedUri)).ReturnsAsync(statusResponse);

            // Act
            var trackToLike = new Track {
                Id = TrackId
            };
            var result = await new Me(gatewayMock.Object).UnlikeAsync(trackToLike);

            // Assert
            Assert.That(result, Is.SameAs(statusResponse));
        }
Esempio n. 30
0
        public void SendStatusRequestIsAbortedIfNumberOfRetriesIsExceeded()
        {
            // given
            var erroneousResponse = new StatusResponse(Substitute.For <ILogger>(), string.Empty, Response.HttpBadRequest, new Dictionary <string, List <string> >());

            context.IsShutdownRequested.Returns(false);
            httpClient.SendStatusRequest().Returns(erroneousResponse);

            // when
            var obtained = BeaconSendingRequestUtil.SendStatusRequest(context, 3, 1000);

            // then
            Assert.That(obtained, Is.SameAs(erroneousResponse));

            context.Received(4).GetHTTPClient();
            context.ReceivedWithAnyArgs(3).Sleep(0);

            httpClient.Received(4).SendStatusRequest();
        }
Esempio n. 31
0
        private void syncWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Utils.writeLog("syncWorker_DoWork: Started sync..");
            // This should work, but I don't know for the life of me why it doesn't

            /*
            RestClient client = new RestClient("http://" + Configuration.server);
            RestRequest request = new RestRequest("sync", Method.POST);

            request.AddParameter("added", Indexer.getAddedJson());
            request.AddParameter("removed", Indexer.getRemovedJson());

            RestResponse<StatusResponse> response = (RestResponse<StatusResponse>)client.Execute<StatusResponse>(request);
            e.Result = response.Data;
            */

            using (var wb = new WebClient())
            {
                var data = new NameValueCollection();
                data["added"] = Indexer.getAddedJson();
                data["removed"] = Indexer.getRemovedJson();

                String response = null;

                try
                {
                    response = Encoding.ASCII.GetString(wb.UploadValues("http://" + Configuration.server + "/sync", "POST", data));
                    //MessageBox.Show(response);
                }
                catch (Exception we)
                {
                    Utils.writeLog("syncWorker_DoWork: " + we);
                    response = "";
                }
                StatusResponse sr = new StatusResponse();
                sr.status = (response.Contains("OK")) ? "OK" : "Error";
                sr.text = (response.Contains("OK")) ? "Synced successfully" : "Failed to sync";

                if (response == "")
                    sr = null;

                syncStatusPictureBox.Image = Resources.sync_failed;
                e.Result = sr;
            }
        }
Esempio n. 32
0
        protected override async Task WriteResponseAsync(string request, IOutputStream os)
        {
            var response = new StatusResponse();

            if (request.StartsWith("/api/seed"))
            {
                var sql = new SqlHelper();

                sql.SeedDatabase();
            }

            if (request.StartsWith("/api/status"))
            {
                var sql = new SqlHelper();

                var info = sql.Get();

                response.Status = info.CurrentStatus.ToString();

                if (info.CurrentStatus == DishwasherStatus.Clean)
                {
                    response.Details = new StatusResponse.CleanStatusDetails
                    {
                        DishwasherRun = sql.GetDishwasherRun()
                    };
                }
                else if (info.CurrentStatus == DishwasherStatus.Dirty)
                {
                    response.Details = new StatusResponse.DirtyStatusDetails
                    {
                        DirtyTime = info.DirtyDateTime
                    };
                }
                else if (info.CurrentStatus == DishwasherStatus.Running)
                {
                    response.Details = new StatusResponse.RunningStatusDetails
                    {
                        StartTime = info.CurrentRunStart,
                        RunCycle = info.CurrentCycle
                    };
                }
            }
            
            // Show the html 
            using (Stream resp = os.AsStreamForWrite())
            {
                string json;
                using (MemoryStream jsonStream = new MemoryStream())
                {
                    var serializer = new DataContractJsonSerializer(typeof(StatusResponse));
                    serializer.WriteObject(jsonStream, response);
                    jsonStream.Position = 0;
                    StreamReader sr = new StreamReader(jsonStream);
                    json = sr.ReadToEnd();
                }

                byte[] bodyArray = Encoding.UTF8.GetBytes(json);
                using (MemoryStream stream = new MemoryStream(bodyArray))
                {
                    string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                  "Content-Length: {0}\r\n" +
                                                  "Content-Type: application/json\r\n" +
                                                  "Connection: close\r\n\r\n",
                        stream.Length);
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                    await stream.CopyToAsync(resp);
                }
                await resp.FlushAsync();
            }
        }