private List <AccountItem> GetAccountDetails(string token)
        {
            string address = string.Format("Accounts/GetAccounts?accountId={0}&subaccountId={1}", null, SubaccountId);

            string resultString;

            using (var client = CreateClient(token))
            {
                resultString = client.DownloadString(address);
            }

            ResponseContainer <List <AccountItem> > response = JsonConvert.DeserializeObject <ResponseContainer <List <AccountItem> > >(resultString);

            if (response.ResponseCode == (int)enumResponseCode.Success)
            {
                AccountId = response.Payload.First().AccountId;
                Console.WriteLine("Received account details: " + response.Payload);
            }
            else
            {
                Console.WriteLine("Failed to receive account details. Code: " + response.ResponseCode);
            }

            return(response.Payload);
        }
        public InterventionResult Handle(ResponseContainer offendingTask)
        {
            // Build login request
            HttpRequestMessage loginReq = _client.PrepareLogin();

            return(new InterventionResult(InterventionResultState.RetryCurrentTask, loginReq));
        }
示例#3
0
        protected virtual ResponseMessage QueryAndVerify(RequestMessage reqMsg)
        {
            reqMsg.WriteTo(GetOutStream());
            ResponseMessage          respMsg   = new ResponseMessage(inStream);
            List <Command>           commands  = reqMsg.Commands();
            List <ResponseContainer> responses = respMsg.Responses();

            if (commands.Count() > responses.Count())
            {
                throw new TraCIException("not enough responses received");
            }
            for (int i = 0; i < commands.Count(); i++)
            {
                Command           cmd          = commands[i];
                ResponseContainer responsePair = responses[i];
                StatusResponse    statusResp   = responsePair.GetStatus();
                Verify("command and status IDs match", cmd.Id(), statusResp.Id());
                if (statusResp.Result() != Constants.RTYPE_OK)
                {
                    throw new TraCIException("SUMO error for command " + statusResp.Id() + ": " + statusResp.Description());
                }
            }

            return(respMsg);
        }
示例#4
0
        public override IEnumerable <DataObject> ProcessInternal(ClientBase client, ResponseContainer container)
        {
            HtmlDocument       doc        = container.ResponseHtml.Value;
            HtmlNodeCollection worldNodes = doc.DocumentNode.SelectNodes("//div[@id='myWorlds']/div[@id='planetList']/div[starts-with(@id, 'planet-')]");

            if (worldNodes == null)
            {
                yield break;
            }

            foreach (HtmlNode node in worldNodes)
            {
                int    id         = int.Parse(PlanetIdRegex.Match(node.GetAttributeValue("id", null)).Groups[1].Value, client.ServerCulture);
                string name       = node.SelectSingleNode(".//span[contains(@class, 'planet-name')]").InnerText;
                string coordinate = node.SelectSingleNode(".//span[contains(@class, 'planet-koords')]").InnerText;

                PlanetListItem item = new PlanetListItem
                {
                    Id         = id,
                    Name       = name,
                    Coordinate = Coordinate.Parse(coordinate, CoordinateType.Planet)
                };

                yield return(item);
            }
        }
        public PrintSertifikatSvarFixture()
        {
            var xmlDocument      = XmlResource.Response.GetPrintCertificate();
            var responseDokument = new ResponseContainer(xmlDocument);

            PrintSertifikatSvar = DtoConverter.ToDomainObject(SerializeUtil.Deserialize <HentPrintSertifikatRespons>(responseDokument.BodyElement.InnerXml));
        }
        public EndringerSvarFixture()
        {
            var xmlDokument      = XmlResource.Response.GetEndringer();
            var responseDokument = new ResponseContainer(xmlDokument);

            EndringerSvar = DtoConverter.ToDomainObject(SerializeUtil.Deserialize <HentEndringerRespons>(responseDokument.BodyElement.InnerXml));
        }
示例#7
0
        public async Task <ResponseContainer> UpdatePassword(UserViewModel model)
        {
            try
            {
                ResponseContainer response = new ResponseContainer();
                var res = await _apiFactory.PutAsync <UserViewModel, int>(model, "Authentication/UpdatePassword", HostConstants.ApiAuthentication, _userSession.BearerToken);

                //var currentUser = await _userManager.FindByEmailAsync(model.Username);
                //if (currentUser != null)
                //{
                //    var result = await _userManager.ChangePasswordAsync(currentUser, model.OldPassword, model.NewPassword);
                //    return Json(result);
                //}
                if (res > 0)
                {
                    response.Activity = "Đổi mật khẩu";
                    return(response);
                }
                else
                {
                    response.Activity = "Sai mật khẩu. Đổi mật khẩu không";
                    return(response);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public override IEnumerable <DataObject> ProcessInternal(ClientBase client, ResponseContainer container)
        {
            var response = new FleetCheck();

            try
            {
                var post = container.OriginalRequest.Content.ReadAsStringAsync().Sync();
                NameValueCollection postParams = HttpUtility.ParseQueryString(post);

                response.Coords = new Coordinate(byte.Parse(postParams["galaxy"]), short.Parse(postParams["system"]), byte.Parse(postParams["planet"]), (CoordinateType)int.Parse(postParams["type"]));

                if (container.Raw.Value == "0")
                {
                    response.Status = FleetCheckStatus.OK;
                }
                else if (container.Raw.Value == "1d")
                {
                    response.Status = FleetCheckStatus.NoDebrisField;
                }
            }
            catch (Exception ex)
            {
                Logging.Logger.Instance.LogException(ex, nameof(FleetCheckParser));
            }
            yield return(response);
        }
        public string Inject(OgamePageInfo info, string body, ResponseContainer response, string host, int port)
        {
            if (!response.RequestMessage.RequestUri.PathAndQuery.Contains("page=eventList"))
            {
                return(body);
            }

            var events = response.GetParsed <EventInfo>();


            var totalAttack    = TotalFor(events.Where(ei => ei.IsReturning && ei.MissionType == MissionType.Attack));
            var totalTransport = TotalFor(events.Where(ei => !ei.IsReturning && (ei.MissionType == MissionType.Transport || ei.MissionType == MissionType.Deployment)));

            StringBuilder repl = new StringBuilder();


            string wrapper = "<tr class='eventFleet'><td colspan=11>Total cargo from {0}: <span class='textBeefy friendly'>{1}</span></td></tr>";

            if (totalAttack.Total > 0)
            {
                repl.Append(string.Format(wrapper, "attacks", totalAttack));
            }
            if (totalTransport.Total > 0)
            {
                repl.Append(string.Format(wrapper, "transport", totalTransport));
            }

            if (repl.Length > 0)
            {
                body = body.Replace(@"<tbody>", $@"<tbody>{repl.ToString()}");
            }

            return(body);
        }
示例#10
0
        public void CheckExampleJsonParses()
        {
            string input, output;

            StreamReader reader = new StreamReader(@"Tests\TestData.json");

            input = reader.ReadToEnd();
            reader.Close();

            Assert.IsTrue(JsonParser.TryParseRequest(input, out output));

            reader = new StreamReader(@"Tests\ExpectedResponse.json");
            ResponseContainer expectedResponse = JsonConvert.DeserializeObject <ResponseContainer>(reader.ReadToEnd());

            reader.Close();
            ResponseContainer receivedResponse = JsonConvert.DeserializeObject <ResponseContainer>(output);

            Assert.IsTrue(receivedResponse.response.Count == expectedResponse.response.Count);
            for (int i = 0; i < receivedResponse.response.Count; i++)
            {
                Assert.AreEqual(receivedResponse.response[i].image, expectedResponse.response[i].image);
                Assert.AreEqual(receivedResponse.response[i].slug, expectedResponse.response[i].slug);
                Assert.AreEqual(receivedResponse.response[i].title, expectedResponse.response[i].title);
            }
        }
示例#11
0
 public static void ThrowExceptionIfFailed <T>(this ResponseContainer <T> response)
 {
     if (response.Status == "FAILED")
     {
         throw new LimpStatsException(response.Comment);
     }
 }
示例#12
0
        private OrderConfirmation UseCancelOrder(string token, int orderId, int?clientRefId)
        {
            Order order = InitOrder();

            order.OrderId     = orderId;
            order.ClientRefId = clientRefId;

            string responseString;

            using (var client = ApiClient.CreateClient(token))
            {
                responseString = client.UploadString("Orders/CancelOrder", "POST", JsonConvert.SerializeObject(order));
            }

            ResponseContainer <OrderConfirmation> response = JsonConvert.DeserializeObject <ResponseContainer <OrderConfirmation> >(responseString);

            if (response.ResponseCode == (int)enumResponseCode.Success)
            {
                Console.WriteLine("Successfully cancelled order. Response: " + response.Payload);
            }
            else
            {
                Console.WriteLine("Failed to cancel order. Code: " + response.ResponseCode);
            }

            return(response.Payload);
        }
示例#13
0
        public void CheckStructureConversion()
        {
            PayloadStructure payload = new PayloadStructure();

            payload.drm             = true;
            payload.episodeCount    = 5;
            payload.image.showImage = "some/image/url";
            payload.slug            = "some/url";
            payload.title           = "Show Title";

            ResponseContainer container = new ResponseContainer();

            container.response.Add(new ResponseStructure(payload));
            Assert.AreEqual(container.response.Count, 1);
            Assert.AreEqual(payload.image.showImage, container.response[0].image);
            Assert.AreEqual(payload.slug, container.response[0].slug);
            Assert.AreEqual(payload.title, container.response[0].title);

            try
            {
                payload.image = null;
                container.response.Add(new ResponseStructure(payload));
            }
            catch (NullReferenceException)
            {
                Assert.AreEqual(container.response.Count, 1);
            }
        }
示例#14
0
        /// <summary>
        /// Performs a simple POST operation composed of one object corresponding to the entity type that the object was sent to.
        /// </summary>
        /// <param name="type">The type of object that needs to be resolved.</param>
        /// <param name="postBody">The POST body to be processed.</param>
        /// <returns>The response <see cref="Negotiator"/> with either a success or failure.</returns>
        protected Negotiator PerformSimplePost(dynamic type, string postBody)
        {
            var           instance = Activator.CreateInstance(type);
            IEntityObject savedThing;

            try
            {
                JsonConvert.PopulateObject(postBody, instance);
            }
            catch (Exception e)
            {
                return(ApiHelper.ConstructFailResponse(this.Negotiate, "create",
                                                       "The request was not properly formatted and could not be used to create the object!", this.Context,
                                                       HttpStatusCode.BadRequest, e));
            }

            // give a new uuid to the instance
            instance.Uuid = Guid.NewGuid();

            try
            {
                // acquire the response
                IEntityObject resp;

                try
                {
                    resp =
                        (IEntityObject)type.GetMethod("Find",
                                                      BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
                        .Invoke(null, new[] { instance.Uuid });

                    if (resp != null)
                    {
                        // if there is an object of this type in the database then this POST is invalid
                        return(ApiHelper.ConstructFailResponse(this.Negotiate, type.Name,
                                                               "An object with this Uuid already exists and cannot be created!", this.Context,
                                                               HttpStatusCode.Conflict));
                    }
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                var transaction = DatabaseSession.Instance.CreateTransaction();
                savedThing = instance.Save(transaction: transaction);
                DatabaseSession.Instance.CommitTransaction(transaction);
            }
            catch (Exception e)
            {
                return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
            }

            var container = new ResponseContainer();

            container.AddToResponse(savedThing);

            return(ApiHelper.ConstructSuccessResponse(this.Negotiate, container, this.Context,
                                                      HttpStatusCode.Created));
        }
        protected override async Task <IResponseContainer> GetResultAsync(UpdateConnectorRequest request)
        {
            IResponseContainer result = new ResponseContainer();
            var connector             = await connectorRepository.GetByChargeStationIdAndLineNoAsync(request.ChargeStationId, request.LineNo);

            if (connector is null)
            {
                result.AddErrorMessage($"Connector with ID={request.ChargeStationId} is not found.");
                return(result);
            }

            var updateResponseContainer = await connector.UpdateMaxCurrentInAmps(request.MaxCurrentInAmps, groupRepository);

            result.JoinWith(updateResponseContainer);

            if (result.IsSuccess)
            {
                var previousValue = connector.MaxCurrentInAmps;
                await connectorRepository.UpdateAsync(connector);

                Log.Info($"Connector with ID={connector.GetNumericId()} is updated with new value {request.MaxCurrentInAmps}, previous value was {previousValue}.");
            }
            else
            {
                Log.Error(result.Messages);
            }

            return(result);
        }
示例#16
0
        private Resources Attack(IEnumerable <EspionageReport> messages)
        {
            Progress = "Attacking";
            //Check if the planet wasn't changed in the meantime (ie. by user action), we'd be sending cargos for a long trip
            ResponseContainer resp = Client.IssueRequest(RequestBuilder.GetPage(PageType.Fleet, PlanetId));
            OgamePageInfo     info = resp.GetParsedSingle <OgamePageInfo>();

            Resources totalPlunder = new Resources();

            foreach (var farm in Strategy.GetTargets(messages))
            {
                Thread.Sleep(3000 + _sleepTime.Next(2000));
                totalPlunder += farm.ExpectedPlunder;
                Logger.Instance.Log(LogLevel.Info, $"Attacking planet {farm.Destination} to plunder {farm.ExpectedPlunder}");

                SendFleetCommand attack = new SendFleetCommand()
                {
                    Mission     = farm.Mission,
                    Destination = farm.Destination,
                    PlanetId    = PlanetId,
                    Fleet       = farm.Fleet
                };
                attack.Run();
            }

            return(totalPlunder);
        }
示例#17
0
        protected ResponseMessage queryAndVerify(RequestMessage paramRequestMessage)

        {
            paramRequestMessage.writeTo(getOutStream());
            ResponseMessage          localResponseMessage = new ResponseMessage(this.inStream);
            List <Command>           localList1           = paramRequestMessage.Commands();
            List <ResponseContainer> localList2           = localResponseMessage.responses();

            if (localList1.Count > localList2.Count)
            {
                throw new TraCIException("not enough responses received");
            }
            for (int i = 0; i < localList1.Count; i++)
            {
                Command           localCommand           = (Command)localList1[i];
                ResponseContainer localResponseContainer = (ResponseContainer)localList2[i];
                StatusResponse    localStatusResponse    = localResponseContainer.getStatus();
                verify("command and status IDs match", Convert.ToInt32(localCommand.Id()), Convert.ToInt32(localStatusResponse.Id()));
                if (localStatusResponse.Result() != 0)
                {
                    throw new TraCIException("SUMO error for command " + localStatusResponse.Id() + ": " + localStatusResponse.Description());
                }
            }
            return(localResponseMessage);
        }
示例#18
0
        public async Task <ResponseContainer> UpdateProfile(UserInsertViewModel model, IFormFile fHinh)
        {
            ResponseContainer response = new ResponseContainer();

            if (fHinh != null)
            {
                var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "Images", "Avatar", fHinh.FileName);
                using (var file = new FileStream(fullPath, FileMode.Create))
                {
                    await fHinh.CopyToAsync(file);

                    model.Avatar = fHinh.FileName;
                }
            }
            var res = await _apiFactory.PutAsync <UserInsertViewModel, int>(model, "Authentication/Update", HostConstants.ApiAuthentication, _userSession.BearerToken);

            if (res > 0)
            {
                response.Activity = "Chỉnh sửa";
                response.Action   = "update";
            }
            else
            {
                response.Activity  = "Chỉnh sửa";
                response.Action    = "update";
                response.Succeeded = false;
            }
            return(response);
        }
示例#19
0
 public override bool ShouldProcessInternal(ResponseContainer container)
 {
     return(container.RequestMessage.RequestUri.Query.Contains("page=overview") ||
            container.RequestMessage.RequestUri.Query.Contains("page=resources") ||
            container.RequestMessage.RequestUri.Query.Contains("page=station") ||
            container.RequestMessage.RequestUri.Query.Contains("page=research"));
 }
        internal string GetToken()
        {
            TokenRequest request = new TokenManager().CreateTokenRequest();

            string responseString;

            using (var client = CreateClient())
            {
                try
                {
                    responseString = client.UploadString("Auth/token", "POST", JsonConvert.SerializeObject(request));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(null);
                }
            }

            ResponseContainer <string> response = JsonConvert.DeserializeObject <ResponseContainer <string> >(responseString);

            if (response.ResponseCode == (int)enumResponseCode.Success)
            {
                Console.WriteLine("Received Token: " + response.Payload);
                return(response.Payload);
            }
            else
            {
                Console.WriteLine("Failed to get Token. Response Code: " + response.ResponseCode);
                return(null);
            }
        }
        public PersonerSvarTests()
        {
            var xmlDocument        = XmlResource.Response.GetPerson();
            var responseDokumenter = new ResponseContainer(xmlDocument);

            _personerSvar = DtoConverter.ToDomainObject(SerializeUtil.Deserialize <HentPersonerRespons>(responseDokumenter.BodyElement.InnerXml));
        }
        private double[] GetStrikes(string token, string underlyingSymbol, DateTime expiration, OptionExpirationTime time)
        {
            string expiryString = expiration.ToString("yyyy-MM-dd");

            //string address = string.Format("Chains/GetStrikes?underlyingSymbol={0}&expiration={1}&time={2}", underlyingSymbol, expiryString, time);
            string address = string.Format("Chains/GetStrikes?underlyingSymbol={0}&expiration={1}", underlyingSymbol, expiryString);

            string resultString;

            using (var client = CreateClient(token))
            {
                resultString = client.DownloadString(address);
            }

            ResponseContainer <double[]> response = JsonConvert.DeserializeObject <ResponseContainer <double[]> >(resultString);

            if (response.ResponseCode == (int)enumResponseCode.Success)
            {
                Console.WriteLine(string.Format("Received {0} strikes for underlyingSymbol {1} with expiration {2}", response.Payload.Length, underlyingSymbol, expiryString));
            }
            else
            {
                Console.WriteLine(string.Format("Failed to receive strikes for underlyingSymbol {0} with expiration {1}. Code: {2}", response.ResponseCode, expiryString, response.ResponseCode));
            }

            return(response.Payload);
        }
        public string Inject(OgamePageInfo current, string body, ResponseContainer response, string host, int port)
        {
            if (current == null)
            {
                return(body);
            }

            _port = port;
            _host = host;

            StringBuilder sb = new StringBuilder("$1");


            sb.Append("<hr/>");
            sb.Append(InjectHelper.GenerateCommandLink("farm?cp=$2", "Farm"))
            .Append(" (")
            .Append(InjectHelper.GenerateCommandLink("farm?cp=$2&slots=0", "0 slots"))
            .Append(")")
            .Append(NewLine);

            sb.Append(InjectHelper.GenerateCommandLink("hunt?cp=$2", "Hunt"))
            .Append(", range: ")
            .Append(InjectHelper.GenerateCommandLink("hunt?cp=$2&range=100", "100"))
            .Append(" ")
            .Append(InjectHelper.GenerateCommandLink("hunt?cp=$2&range=40", "40"))
            .Append(" ")
            .Append(InjectHelper.GenerateCommandLink("hunt?cp=$2&range=20", "20"))
            .Append(NewLine);

            sb.Append("Transport All: ")
            .Append(InjectHelper.GenerateCommandLink($"transport?from=$2&to={current.PlanetId}", "From"))
            .Append(" / ")
            .Append(InjectHelper.GenerateCommandLink($"transport?from={current.PlanetId}&to=$2", "To"))
            .Append(NewLine);

            sb.Append("Fleetsave: ")
            .Append(InjectHelper.GenerateCommandLink($"fs?cp=$2&in=360", "6h"))
            .Append(" ")
            .Append(InjectHelper.GenerateCommandLink($"fs?cp=$2&in=390", "6.5h"))
            .Append(" ")
            .Append(InjectHelper.GenerateCommandLink($"fs?cp=$2&in=420", "7h"))
            .Append(" ")
            .Append(InjectHelper.GenerateCommandLink($"fs?cp=$2&in=450", "7.5h"))
            .Append(" ")
            .Append(InjectHelper.GenerateCommandLink($"fs?cp=$2&in=480", "8h"))
            .Append(NewLine);


            sb.Append(InjectHelper.GenerateCommandLink("expedition?cp=$2", "Expedition"));

            if (current.PlanetCoord.Type == CoordinateType.Moon)
            {
                sb.Append(NewLine);
                sb.Append(InjectHelper.GenerateCommandLink($"jump?from={current.PlanetId}&to=$2", "Gate Jump"));
            }

            body = submenuRegex.Replace(body, InjectHelper.EncodeTooltip(sb.ToString()));
            return(body);
        }
示例#24
0
        protected ResponseContainer AssistedIssue(HttpRequestMessage request)
        {
            ResponseContainer result = Client.IssueRequest(request);

            ParsedObjects.AddRange(result.ParsedObjects);

            return(result);
        }
示例#25
0
        public bool ShouldProcess(ResponseContainer container)
        {
            if (ProcessOnlySuccesses && !container.WasSuccess)
            {
                return(false);
            }

            return(ShouldProcessInternal(container));
        }
示例#26
0
        private void PageChanged(ResponseContainer resp)
        {
            string minifleetToken = resp.GetParsedSingle <OgamePageInfo>(false)?.MiniFleetToken;

            if (minifleetToken != null)
            {
                _token = minifleetToken;
            }
        }
示例#27
0
        /* Extract to IFarmingStrategy
         * private IEnumerable<Planet> GetFarmsToScanForFleet()
         * {
         *
         * }
         */

        private void SendProbes(IEnumerable <Planet> farms)
        {
            Progress = "Sending probes";
            HttpRequestMessage req  = RequestBuilder.GetPage(PageType.Galaxy, PlanetId);
            ResponseContainer  resp = Client.IssueRequest(req);

            Coordinate self       = resp.GetParsedSingle <OgamePageInfo>().PlanetCoord;
            Coordinate selfPlanet = Coordinate.Create(self, CoordinateType.Planet);
            Coordinate selfMoon   = Coordinate.Create(self, CoordinateType.Moon);

            var farmList = farms.OrderBy(f => f.LocationId).ToList();

            int count        = farmList.Count;
            int retry        = 0;
            int failedInARow = 0;

            foreach (Planet farm in farmList)
            {
                if (farm.Coordinate == selfPlanet || farm.Coordinate == selfMoon)
                {
                    continue;
                }

                MinifleetResponse minifleet;
                retry = 0;
                do
                {
                    req       = RequestBuilder.GetMiniFleetSendMessage(MissionType.Espionage, farm.Coordinate, Strategy.ProbeCount, _token);
                    resp      = Client.IssueRequest(req);
                    minifleet = resp.GetParsedSingle <MinifleetResponse>();
                    _token    = minifleet.NewToken;

                    // If there are no probes (or error), wait for 5s, otherwise 1s
                    Thread.Sleep((minifleet.Response.Probes > 0 ? 1000 : 5000) + _sleepTime.Next(1000));
                    retry++;
                }while (!minifleet.Response.IsSuccess && retry < 5);

                if (minifleet.Response.IsSuccess)
                {
                    failedInARow = 0;
                }
                else
                {
                    Logger.Instance.Log(LogLevel.Error, $"Sending probes to {farm.Coordinate} failed, last error: {minifleet.Response.Message}");
                    if (++failedInARow == 3)
                    {
                        Logger.Instance.Log(LogLevel.Error, $"Failed to send probe {failedInARow} times in a row, aborting further scan");
                        break;
                    }
                }

                if (--count % 10 == 0 && count > 0)
                {
                    Logger.Instance.Log(LogLevel.Info, $"{count} remaining to scan...");
                }
            }
        }
示例#28
0
 internal ResponseValidator(XmlDocument sentDocument, ResponseContainer responseContainer,
                            X509Certificate2 xmlDekrypteringsSertifikat = null)
 {
     SentDocument      = sentDocument;
     ResponseContainer = responseContainer;
     if (xmlDekrypteringsSertifikat != null)
     {
         DecryptDocument(xmlDekrypteringsSertifikat);
     }
 }
示例#29
0
        public async Task <ResponseContainer> Delete(int id)
        {
            var response = new ResponseContainer();
            var result   = await _apiFactory.DeleteAsync <int>(this.ApiResources("Delete?id=" + id), HostConstants.ApiCore, _userSession.BearerToken);

            response.Activity  = $"Xóa thể loại ";
            response.Action    = "delete";
            response.Succeeded = result > 0 ? true : false;
            return(response);
        }
示例#30
0
        public IEnumerable <DataObject> Process(ClientBase client, ResponseContainer container)
        {
            string typeName = GetType().FullName;

            foreach (DataObject dataObject in ProcessInternal(client, container))
            {
                dataObject.ParserType = typeName;
                yield return(dataObject);
            }
        }
示例#31
0
 public void AddResponseContainer(ResponseContainer a_rcon)
 {
     rc.Add(a_rcon);
 }
示例#32
0
        private byte[] Extracthandler(NameValueCollection boundVariables,
            JsonObject operationInput,
            string outputFormat,
            string requestProperties,
            out string responseProperties)
        {
            responseProperties = null;
            var errors = new ResponseContainer(HttpStatusCode.BadRequest, "");

            string base64Geometry;
            var found = operationInput.TryGetString("geometry", out base64Geometry);

            if (!found || string.IsNullOrEmpty(base64Geometry))
            {
                errors.Message = "geometry parameter is required.";

                return Json(errors);
            }

            JsonObject queryCriteria;
            found = operationInput.TryGetJsonObject("criteria", out queryCriteria);

            if (!found)
            {
                errors.Message = "criteria parameter is required.";

                return Json(errors);
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "Params received");
            #endif

            IGeometry geometry;
            int read;
            var factory = new GeometryEnvironmentClass() as IGeometryFactory3;
            factory.CreateGeometryFromWkbVariant(Convert.FromBase64String(base64Geometry), out geometry, out read);

            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            if (geometry.SpatialReference == null)
            {
                //Create a projected coordinate system and define its domain, resolution, and x,y tolerance.
                var spatialReferenceResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(3857) as ISpatialReferenceResolution;
                spatialReferenceResolution.ConstructFromHorizon();
                var spatialReferenceTolerance = spatialReferenceResolution as ISpatialReferenceTolerance;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                var spatialReference = spatialReferenceResolution as ISpatialReference;

                geometry.SpatialReference = spatialReference;
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "Geometry converted");
            #endif

            if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon)
            {
                var filterGeometry = (ITopologicalOperator4) geometry;
                filterGeometry.IsKnownSimple_2 = false;

                filterGeometry.Simplify();

                if (((IArea)geometry).Area < 0)
                {
                    ((ICurve)geometry).ReverseOrientation();
                }
            }

            var filter = new SpatialFilter
            {
                Geometry = geometry,
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            var utmResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(26912) as ISpatialReferenceResolution;
            utmResolution.ConstructFromHorizon();
            var utmTolerance = utmResolution as ISpatialReferenceTolerance;
            utmTolerance.SetDefaultXYTolerance();
            var utmSr = utmResolution as ISpatialReference;

            var notEsri = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(queryCriteria.ToJson());
            var searchResults = new Dictionary<string, IList<IntersectAttributes>>();

            foreach (var keyValue in notEsri)
            {
                var container = _featureClassIndexMap.Single(x => x.Index == int.Parse(keyValue.Key));
                var fields = keyValue.Value.Select(x => x.ToUpper());
                var fieldMap = container.FieldMap.Select(x => x.Value)
                    .Where(y => fields.Contains(y.Field.ToUpper()))
                    .ToList();
            #if !DEBUG
                _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Querying {0} at index {1}", container.LayerName, container.Index));
            #endif
                var cursor = container.FeatureClass.Search(filter, true);
                IFeature feature;
                while ((feature = cursor.NextFeature()) != null)
                {
                    var values = new GetValueAtIndexCommand(fieldMap, feature).Execute();
                    var attributes = new IntersectAttributes(values);

                    // line over polygon = 1D
                    // polygon over polygon = 2D

                    switch (geometry.GeometryType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                        {
            #if !DEBUG
                            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "User input polygon, intersecting " + container.LayerName);
            #endif
                            var gis = (ITopologicalOperator4)geometry;
                            gis.Simplify();

                            if (feature.ShapeCopy.GeometryType == esriGeometryType.esriGeometryPolygon)
                            {
                                try
                                {
                                    var intersection = gis.Intersect(feature.ShapeCopy, esriGeometryDimension.esriGeometry2Dimension);

                                    intersection.Project(utmSr);

                                    var utm = (IArea) intersection;
                                    attributes.Intersect = Math.Abs(utm.Area);
            #if !DEBUG
                                    _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Area: {0}", utm.Area));
            #endif
                                }
                                catch (Exception ex)
                                {
                                    return Json(new ResponseContainer(HttpStatusCode.InternalServerError, ex.Message));
                                }
                            }
                            else if (feature.ShapeCopy.GeometryType == esriGeometryType.esriGeometryPolyline)
                            {
                                var intersection = gis.Intersect(feature.ShapeCopy, esriGeometryDimension.esriGeometry1Dimension);

                                intersection.Project(utmSr);

                                var utm = (IPolyline5) intersection;
                                attributes.Intersect = Math.Abs(utm.Length);
            #if !DEBUG
                                _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Length: {0}", utm.Length));
            #endif
                            }

                        }
                            break;
                        case esriGeometryType.esriGeometryPolyline:
                        {
            #if !DEBUG
                            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "User input polyline, acting on " + container.LayerName);
            #endif
                            var gis = (ITopologicalOperator5) geometry;
                            gis.Simplify();

                            var intersection = gis.Intersect(feature.ShapeCopy, esriGeometryDimension.esriGeometry1Dimension);

                            intersection.Project(utmSr);

                            var utm = (IPolyline) intersection;
                            attributes.Intersect = Math.Abs(utm.Length);
            #if !DEBUG
                            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Length: {0}", utm.Length));
            #endif
                        }
                            break;
                    }

                    if (searchResults.ContainsKey(container.LayerName))
                    {
                        if (searchResults[container.LayerName].Any(x => new MultiSetComparer<object>().Equals(x.Attributes, attributes.Attributes)))
                        {
                            var duplicate = searchResults[container.LayerName]
                                .Single(x => new MultiSetComparer<object>().Equals(x.Attributes, attributes.Attributes));

                            duplicate.Intersect += attributes.Intersect;
                        }
                        else
                        {
                            searchResults[container.LayerName].Add(attributes);
                        }
                    }
                    else
                    {
                        searchResults[container.LayerName] = new Collection<IntersectAttributes> {attributes};
                    }
                }
            }

            var response = new IntersectResponse(searchResults);

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Returning results {0}", searchResults.Count));
            #endif

            return Json(new ResponseContainer<IntersectResponse>(response));
        }
示例#33
0
        private byte[] AreasAndLengthsHandler(NameValueCollection boundVariables,
            JsonObject operationInput,
            string outputFormat,
            string requesetProperties,
            out string responseProperties)
        {
            responseProperties = null;
            var errors = new ResponseContainer(HttpStatusCode.BadRequest, "");

            string base64Geometry;
            var found = operationInput.TryGetString("geometry", out base64Geometry);

            if (!found || string.IsNullOrEmpty(base64Geometry))
            {
                errors.Message = "geometry parameter is required.";

                return Json(errors);
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, "Params received");
            #endif

            IGeometry geometry;
            int read;
            var factory = new GeometryEnvironmentClass() as IGeometryFactory3;
            factory.CreateGeometryFromWkbVariant(Convert.FromBase64String(base64Geometry), out geometry, out read);

            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            if (geometry.SpatialReference == null)
            {
                //Create a projected coordinate system and define its domain, resolution, and x,y tolerance.
                var spatialReferenceResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(3857) as ISpatialReferenceResolution;
                spatialReferenceResolution.ConstructFromHorizon();
                var spatialReferenceTolerance = spatialReferenceResolution as ISpatialReferenceTolerance;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                var spatialReference = spatialReferenceResolution as ISpatialReference;

                geometry.SpatialReference = spatialReference;
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, "Geometry converted");
            #endif

            if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon)
            {
                var filterGeometry = (ITopologicalOperator4)geometry;
                filterGeometry.IsKnownSimple_2 = false;

                filterGeometry.Simplify();

                if (((IArea)geometry).Area < 0)
                {
                    ((ICurve)geometry).ReverseOrientation();
                }
            }

            var utmResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(26912) as ISpatialReferenceResolution;
            utmResolution.ConstructFromHorizon();
            var utmTolerance = utmResolution as ISpatialReferenceTolerance;
            utmTolerance.SetDefaultXYTolerance();
            var utmSr = utmResolution as ISpatialReference;

            geometry.Project(utmSr);

            var size = 0D;
            switch (geometry.GeometryType)
            {
                case esriGeometryType.esriGeometryPolygon:
                    size = ((IArea) geometry).Area;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    size = ((IPolyline5) geometry).Length;
                    break;
            }
            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, string.Format("Returning size {0}", size.ToString(CultureInfo.InvariantCulture)));
            #endif
            return Json(new ResponseContainer<SizeResponse>(new SizeResponse(size)));
        }