Exemple #1
0
        /// <summary>
        /// Формирует XML тело сообщения на основе структуры GisDataPack.
        /// </summary>
        /// <param name="gisRequest">Структура типа GisDataPack</param>
        /// <returns>Строковое представление сформированного XML</returns>
        private static string GetBodyXML(DataPack gisRequest)
        {
            var soapFormatter = new GisSoapFormatter
            {
                Template         = PathHelper.ToAppAbsolutePath(gisRequest.TemplatePath),
                SchemaVersion    = gisRequest.SchemaVersion,
                AddOrgPPAGuid    = gisRequest.AddOrgPPAGUID,
                ValuesDictionary = gisRequest.Xpath2Values,
                OrgPPAGuid       = gisRequest.OrgPPAGUID,
                Config           = gisRequest.SoapConfig
            };
            var soapString = soapFormatter.GetSoapRequest(gisRequest.RequesterMessageGuid);

#if DEBUG
            Notificator.Write(soapString);
#endif

            if (gisRequest.AddSignature && gisRequest.Action != "urn:getState")
            {
                var soapXml = XmlDocumentHelper.Create(soapString);
                soapString = SignNode(soapXml, Constants.SoapContentXpath, gisRequest.CertificateThumbprint, gisRequest.SignPasswd, gisRequest.RequesterMessageGuid);
#if DEBUG
                Notificator.Write(soapString);
#endif
                return(soapString);
            }
            return(soapString);
        }
        protected void SendRequest(string serviceName, string methodName, IEnumerable <Tuple <string, string> > xpath2Values)
        {
            var service = _serviceConfig.Services[serviceName];

            if (service == null)
            {
                throw new ConfigurationErrorsException($"Конфигурация для сервиса {serviceName} не задана");
            }

            var method = service.Methods[methodName];

            if (method == null)
            {
                throw new ConfigurationErrorsException($"Конфигурация для метода {methodName} не задана");
            }

            if (method.RequiredBody && !xpath2Values.Any())
            {
                throw new ConfigurationErrorsException($"Метод {methodName} имеет обязательные параметры для запроса (-с файл)");
            }

            Info("Создание запроса...");
            var soapFormatter = new GisSoapFormatter
            {
                Template = PathHelper.ToAppAbsolutePath(method.Template),
                //SchemaVersion = _serviceConfig.SchemaVersion, TODO  Удалить если всё норм
                AddOrgPPAGuid    = service.AddSenderId,
                ValuesDictionary = xpath2Values,
                // TODO обратить внимание на эту строчку, нужно ли из конфига брать? или из базы guid организации.
                OrgPPAGuid  = _serviceConfig.RIRCorgPPAGUID,
                Config      = _serviceConfig.SoapConfiguration,
                MessageGuid = ""
            };

            var soapString = soapFormatter.GetSoapRequest(soapFormatter.MessageGuid);

            System.IO.File.WriteAllText(@"soapString.txt", soapString);
            if (IsSignatureRequired && service.AddSignature)
            {
                Info("Добавление подписи в запрос...");
                var soapXml = XmlDocumentHelper.Create(soapString);
                soapString = SignNode(soapXml, Constants.SoapContentXpath);
                System.IO.File.WriteAllText(@"soapStringSign.txt", soapString);
            }



            IEnumerable <Tuple <string, string> > resultValues;

            try
            {
                Info($"Отправка запроса по адресу: {_serviceConfig.BaseUrl}{service.Path}/{method.Action}");

                Console.WriteLine($"Отправка запроса по адресу: {_serviceConfig.BaseUrl}{service.Path}/{method.Action}");

                var response = CallGisService($"{_serviceConfig.BaseUrl}{service.Path}", method.Action, soapString, _serviceConfig.Login, _serviceConfig.Password);

                Console.WriteLine(response);

                Info("Обработка ответа на запрос...");
                resultValues = ProcessSoapResponse(response);
                Console.WriteLine(resultValues);
            }
            catch (XadesBesValidationException ex)
            {
                Error($"Подпись ответа от ГИС ЖКХ не прошла проверку: {ex.Message}", ex);
                return;
            }
            catch (WebException ex)
            {
                Warning($"Сервер ответил с ошибкой: {ex.Message}");
                using (var streamWriter = new StreamReader(ex.Response.GetResponseStream()))
                {
                    var response = streamWriter.ReadToEnd();
                    resultValues = ProcessSoapResponse(response);
                }
            }

            Info($"Сохранение ответа ...");
            Console.WriteLine(resultValues);
            Success("Запрос успешно выполнен");
        }
        protected void SendRequest(string serviceName, string methodName, IEnumerable <Tuple <string, string> > xpath2Values, string outputFile)
        {
            var service = _serviceConfig.Services[serviceName];

            if (service == null)
            {
                throw new ConfigurationErrorsException(string.Format("Конфигурация для сервиса {0} не задана", serviceName));
            }

            var method = service.Methods[methodName];

            if (method == null)
            {
                throw new ConfigurationErrorsException(string.Format("Конфигурация для метода {0} не задана", methodName));
            }

            if (method.RequiredBody && !xpath2Values.Any())
            {
                throw new ConfigurationErrorsException(string.Format("Метод {0} имеет обязательные параметры для запроса (-с файл)", methodName));
            }

            Info("Создание запроса...");
            var soapFormatter = new GisSoapFormatter
            {
                Template         = PathHelper.ToAppAbsolutePath(method.Template),
                AddSenderId      = service.AddOrgPpaGuid,
                ValuesDictionary = xpath2Values,
                OrgPpaGuid       = _serviceConfig.OrgPpaGuid,
                Config           = _serviceConfig.SoapConfiguration
            };

            var soapString = soapFormatter.GetSoapRequest();

            if (IsSignatureRequired && service.AddSignature)
            {
                Info("Добавление подписи в запрос...");
                var soapXml = XmlDocumentHelper.Create(soapString);
                soapString = SignNode(soapXml, Constants.SoapContentXpath);
            }

            IEnumerable <Tuple <string, string> > resultValues;

            try
            {
                Info(string.Format("Отправка запроса по адресу: {0}{1}/{2}", _serviceConfig.BaseUrl, service.Path, method.Action));
                var response = CallGisService(_serviceConfig.BaseUrl + service.Path, method.Action, soapString, Option.BasicAuthorization);
                Info("Обработка ответа на запрос...");
                resultValues = ProcessSoapResponse(response);
            }
            catch (XadesBesValidationException ex)
            {
                Error(string.Format("Подпись ответа от ГИС ЖКХ не прошла проверку: {0}", ex.Message), ex);
                return;
            }
            catch (WebException ex)
            {
                Warning(string.Format("Сервер ответил с ошибкой: {0}", ex.Message));
                using (var streamWriter = new StreamReader(ex.Response.GetResponseStream()))
                {
                    var response = streamWriter.ReadToEnd();
                    resultValues = ProcessSoapResponse(response);
                }
            }

            Info(string.Format("Сохранение ответа в файл {0}...", outputFile));
            Helpers.CsvHelper.WriteCsv(outputFile, resultValues);
            Success("Запрос успешно выполнен");
        }