public IActionResult CreateEdition(string org, string service, EditionConfiguration editionConfig)
        {
            if (ModelState.IsValid)
            {
                IList <EditionConfiguration> editions = _repository.GetEditions(org, service);
                List <string> editionNames            = editions.Select(edition => edition.Code).ToList();

                if (!editionNames.Contains(editionConfig.Code))
                {
                    _repository.CreateEdition(org, service, editionConfig);
                    var metadata = new ServiceMetadata
                    {
                        Edition = editionConfig.Code,
                        Org     = org,
                        Service = service
                    };
                    _repository.CreateServiceMetadata(metadata);

                    return(RedirectToAction("Index", "Edition", new { org, service, edition = editionConfig.Code }));
                }
                else
                {
                    ViewBag.editionNameAlreadyExists = true;
                    return(View());
                }
            }
            else
            {
                return(View(editionConfig));
            }
        }
Exemple #2
0
        private IEnumerable <EditionStatusViewModel.UserMessage> ServiceMetadataMessages(
            ServiceMetadata serviceMetadata,
            IEnumerable <ViewMetadata> viewMetadatas)
        {
            if (serviceMetadata == null)
            {
                yield return(EditionStatusViewModel.UserMessage.Error("Tjenestens metadata mangler"));

                yield break;
            }

            var routParameters =
                new { org = serviceMetadata.Org, service = serviceMetadata.Service, edition = serviceMetadata.Edition };

            if (serviceMetadata.Elements == null || !serviceMetadata.Elements.Any())
            {
                var dataModellMissing = EditionStatusViewModel.UserMessage.Error("Tjenestens datamodell mangler");
                dataModellMissing.Link = new KeyValuePair <string, string>(
                    Url.Action("Index", "Model", routParameters),
                    "Til Datamodell");
                yield return(dataModellMissing);
            }

            if (viewMetadatas == null || !viewMetadatas.Any())
            {
                var visningerAdvarsel =
                    EditionStatusViewModel.UserMessage.Warning("Tjenesten har ingen visninger");
                visningerAdvarsel.Link =
                    new KeyValuePair <string, string>(
                        Url.Action("Index", "UI", routParameters),
                        "Til Visninger");
                yield return(visningerAdvarsel);
            }
        }
Exemple #3
0
        void Expòrt()
        {
            log = new StringBuilder();
            foreach (Fwk.Bases.ServiceConfiguration s in _Services)
            {
                try
                {
                    Fwk.Bases.ServiceConfiguration sclon = s.Clone();

                    sclon.ApplicationId = txtAppId.Text;

                    ServiceMetadata.AddServiceConfiguration(_SelectedProvider.Name, sclon);
                    log.AppendLine(string.Concat(s.Name, " OK"));
                }
                catch (Fwk.Exceptions.TechnicalException te)
                {
                    if (te.ErrorId.Equals("7002"))
                    {
                        log.AppendLine(string.Concat(s.Name, " already exist"));
                    }
                    else
                    {
                        log.AppendLine(string.Concat(s.Name, Fwk.Exceptions.ExceptionHelper.GetAllMessageException(te)));
                    }
                    _HasErrors = true;
                }
            }
            textBox1.Text = log.ToString();
        }
Exemple #4
0
        public void ConvertServiceModel()
        {
            Dictionary <string, Dictionary <string, string> > textDictionary = new Dictionary <string, Dictionary <string, string> >();

            Mock <IRepository> moqRepository = new Mock <IRepository>();

            moqRepository
            .Setup(r => r.GetServiceTexts(It.IsAny <string>(), It.IsAny <string>())).Returns(textDictionary);

            var       seresParser = new SeresXsdParser(moqRepository.Object);
            XDocument mainXsd     = XDocument.Load("Common/xsd/ServiceModel.xsd");

            ServiceMetadata serviceMetadata = seresParser.ParseXsdToServiceMetadata("123", "app", mainXsd, null);

            string metadataAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(serviceMetadata);

            File.WriteAllText("service-model.json", metadataAsJson);

            JsonMetadataParser metadataParser = new JsonMetadataParser();
            string             classMeta      = metadataParser.CreateModelFromMetadata(serviceMetadata);

            File.WriteAllText("service-model.cs", classMeta);

            File.WriteAllText("servcie-model-texts.txt", Newtonsoft.Json.JsonConvert.SerializeObject(textDictionary));
        }
Exemple #5
0
        private static void SetupIoCContainer()
        {
            ContainerBuilder builder = new ContainerBuilder();

            // Let AspComet put its registrations into the container
            foreach (ServiceMetadata metadata in ServiceMetadata.GetMinimumSet())
            {
                if (metadata.IsPerRequest)
                {
                    builder.RegisterType(metadata.ActualType).As(metadata.ServiceType);
                }
                else
                {
                    builder.RegisterType(metadata.ActualType).As(metadata.ServiceType).SingleInstance();
                }
            }

            // Add our own stuff to the container
            builder.RegisterType <AuthenticatedClientFactory>().As <IClientFactory>().SingleInstance();
            builder.RegisterType <HandshakeAuthenticator>().SingleInstance();
            builder.RegisterType <BadLanguageBlocker>().SingleInstance();
            builder.RegisterType <SubscriptionChecker>().SingleInstance();
            builder.RegisterType <Whisperer>().SingleInstance();

            // Set up the common service locator
            container = builder.Build();
        }
Exemple #6
0
        public void ConvertNæringsoppgave()
        {
            string xsdFileName = "Common/xsd/melding-2-12186.xsd";
            string outName     = "melding-2-12186-output";

            Dictionary <string, Dictionary <string, string> > textDictionary = new Dictionary <string, Dictionary <string, string> >();

            Mock <IRepository> moqRepository = new Mock <IRepository>();

            moqRepository
            .Setup(r => r.GetServiceTexts(It.IsAny <string>(), It.IsAny <string>())).Returns(textDictionary);

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreWhitespace = true;

            var       doc     = XmlReader.Create(xsdFileName, settings);
            XDocument mainXsd = XDocument.Load(doc);

            var             seresParser     = new SeresXsdParser(moqRepository.Object);
            ServiceMetadata serviceMetadata = seresParser.ParseXsdToServiceMetadata("123", "app", mainXsd, null);

            string metadataAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(serviceMetadata);

            File.WriteAllText(outName + ".json", metadataAsJson);

            JsonMetadataParser metadataParser = new JsonMetadataParser();
            string             classMeta      = metadataParser.CreateModelFromMetadata(serviceMetadata);

            File.WriteAllText(outName + ".cs", classMeta);

            File.WriteAllText(outName + "-texts.json", Newtonsoft.Json.JsonConvert.SerializeObject(textDictionary));
        }
Exemple #7
0
        void LoadConfig()
        {
            SetProviderSource();
            SetProviderDest();


            //cargo la grilla izquierda
            ucbServiceGrid1.Services     = ServiceMetadata.GetAllServices(_SourceProvider.Name);
            ucbServiceGrid1.Applications = ServiceMetadata.GetAllApplicationsId(_SourceProvider.Name);

            //lleno el combo de posibles proveedores destino
            foreach (ServiceProviderElement p in ServiceMetadata.ProviderSection.Providers)
            {
                if (!_SourceProvider.Name.Equals(p.Name))
                {
                    cmb2.Items.Add(p.Name);
                }
            }


            cmb2.SelectedIndex = 0;
            _SelectedProvider  = ServiceMetadata.ProviderSection.GetProvider(cmb2.SelectedItem.ToString());

            cmb2.SelectedValueChanged += new EventHandler(cb_SelectedValueChanged);


            this.Text = string.Concat("Export data from ", _SourceProvider.Name, " to ", _SourceProvider.Name);
        }
        public IActionResult CreateService(string org, ServiceConfiguration serviceConfiguration)
        {
            if (ModelState.IsValid)
            {
                string serviceName = serviceConfiguration.Code;
                IList <ServiceConfiguration> services  = _repository.GetServices(org);
                List <string> serviceNames             = services.Select(c => c.Code.ToLower()).ToList();
                bool          serviceNameAlreadyExists = serviceNames.Contains(serviceName.ToLower());

                if (!serviceNameAlreadyExists)
                {
                    _repository.CreateService(org, serviceConfiguration);
                    var metadata = new ServiceMetadata
                    {
                        Org     = org,
                        Service = serviceName,
                    };
                    _repository.CreateServiceMetadata(metadata);
                    return(RedirectToAction("Index", "Service", new { org, service = serviceConfiguration.Code }));
                }
                else
                {
                    ViewBag.serviceNameAlreadyExists = true;
                    return(View());
                }
            }
            else
            {
                return(View(serviceConfiguration));
            }
        }
Exemple #9
0
 public MetadataInfo ServiceGetMetadata()
 {
     try
     {
         ServiceMetadata metadata     = this.EnsureMetadataInitialized();
         var             metadataInfo = new MetadataInfo();
         metadataInfo.methods = metadata.methodDescriptions;
         metadataInfo.associations.AddRange(metadata.associations.Values);
         foreach (var dbInfo in metadata.dbSets.Values)
         {
             var copy = dbInfo.ShallowCopy();
             copy.permissions = new DbSetPermit();
             metadataInfo.dbSets.Add(copy);
         }
         metadataInfo.dbSets.ForEach((dbSetInfo) =>
         {
             dbSetInfo.CalculatePermissions(this.authorizer);
         });
         return(metadataInfo);
     }
     catch (Exception ex)
     {
         this.OnError(ex);
         throw;
     }
 }
Exemple #10
0
        protected ServiceStackHost(string serviceName, params Assembly[] assembliesWithServices)
        {
            this.StartedAt = DateTime.UtcNow;

            ServiceName = serviceName;
            AppSettings = new AppSettings();
            Container   = new Container {
                DefaultOwner = Owner.External
            };
            ServiceController = CreateServiceController(assembliesWithServices);

            ContentTypes                      = Host.ContentTypes.Instance;
            RestPaths                         = new List <RestPath>();
            Routes                            = new ServiceRoutes(this);
            Metadata                          = new ServiceMetadata(RestPaths);
            PreRequestFilters                 = new List <Action <IRequest, IResponse> >();
            GlobalRequestFilters              = new List <Action <IRequest, IResponse, object> >();
            GlobalTypedRequestFilters         = new Dictionary <Type, ITypedFilter>();
            GlobalResponseFilters             = new List <Action <IRequest, IResponse, object> >();
            GlobalTypedResponseFilters        = new Dictionary <Type, ITypedFilter>();
            GlobalMessageRequestFilters       = new List <Action <IRequest, IResponse, object> >();
            GlobalTypedMessageRequestFilters  = new Dictionary <Type, ITypedFilter>();
            GlobalMessageResponseFilters      = new List <Action <IRequest, IResponse, object> >();
            GlobalTypedMessageResponseFilters = new Dictionary <Type, ITypedFilter>();
            ViewEngines                       = new List <IViewEngine>();
            ServiceExceptionHandlers          = new List <HandleServiceExceptionDelegate>();
            UncaughtExceptionHandlers         = new List <HandleUncaughtExceptionDelegate>();
            AfterInitCallbacks                = new List <Action <IAppHost> >();
            OnDisposeCallbacks                = new List <Action <IAppHost> >();
            RawHttpHandlers                   = new List <Func <IHttpRequest, IHttpHandler> > {
                HttpHandlerFactory.ReturnRequestInfo,
                MiniProfilerHandler.MatchesRequest,
            };
            CatchAllHandlers        = new List <HttpHandlerResolverDelegate>();
            CustomErrorHttpHandlers = new Dictionary <HttpStatusCode, IServiceStackHandler> {
                { HttpStatusCode.Forbidden, new ForbiddenHttpHandler() },
                { HttpStatusCode.NotFound, new NotFoundHttpHandler() },
            };
            StartUpErrors = new List <ResponseStatus>();
            PluginsLoaded = new List <string>();
            Plugins       = new List <IPlugin> {
                new HtmlFormat(),
                new CsvFormat(),
                new MarkdownFormat(),
                new PredefinedRoutesFeature(),
                new MetadataFeature(),
                new NativeTypesFeature(),
            };
            ExcludeAutoRegisteringServiceTypes = new HashSet <Type> {
                typeof(AuthenticateService),
                typeof(RegisterService),
                typeof(AssignRolesService),
                typeof(UnAssignRolesService),
                typeof(NativeTypesService),
                typeof(PostmanService),
            };

            // force deterministic initialization of static constructor
            using (JsConfig.BeginScope()) { }
        }
Exemple #11
0
        private void CreateClassFromTemplate(
            string org,
            string service,
            Dictionary <ServiceEventType, string> eventLogic,
            Dictionary <string, string> methods,
            ServiceMetadata serviceMetadata)
        {
            eventLogic.OrderBy(x => x.Key);

            // Read the serviceImplemenation template
            string textData = File.ReadAllText(_generalSettings.GeneratedMethodsTemplate, Encoding.UTF8);

            // Replace the template default namespace
            List <string> formattingElements = eventLogic.Values.ToList();

            formattingElements.Add(string.Join("\n", methods.Values));

            textData = textData.Replace(CodeGeneration.ServiceNamespaceTemplateDefault, string.Format(CodeGeneration.ServiceNamespaceTemplate, org, service));
            textData = string.Format(textData, formattingElements.ToArray());

            // Create the service implementation folder
            Directory.CreateDirectory(_settings.GetImplementationPath(org, service, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)));

            // Get the file path
            string generatedMethodsFilePath = _settings.GetImplementationPath(org, service, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext))
                                              + _settings.GeneratedMethodsFileName;

            textData = textData.Replace(CodeGeneration.DefaultServiceModelName, serviceMetadata.Elements.Values.First(el => el.ParentElement == null).ID);

            File.WriteAllText(generatedMethodsFilePath, textData, Encoding.UTF8);
        }
Exemple #12
0
        private Dictionary <string, Iterator> CreateIterator(
            int containerId,
            string elementId,
            ServiceMetadata serviceMetadata,
            List <char> reservedIndexNames,
            Dictionary <string, Iterator> iterators)
        {
            List <string> idParts   = elementId.Split('.').ToList();
            string        currentId = idParts[0];

            for (int i = 0; i < idParts.Count; i++)
            {
                ElementMetadata currentElement = serviceMetadata.Elements[currentId];
                if (currentElement.MaxOccurs > 1)
                {
                    // Need iterator
                    if (!iterators.ContainsKey($"{currentId}_{containerId}"))
                    {
                        iterators.Add($"{currentId}_{containerId}", CreateIterator(currentId, iterators, serviceMetadata, reservedIndexNames));
                    }
                }

                if ((i + 1) < idParts.Count)
                {
                    currentId += '.' + idParts[i + 1];
                }
            }

            return(iterators);
        }
Exemple #13
0
        public static RequestInfoResponse GetRequestInfo(IHttpRequest httpReq)
        {
            ServiceMetadata serviceMetadata = EndpointHost.Config.MetadataMap[httpReq.ServicePath];
            var             response        = new RequestInfoResponse
            {
                Host                = EndpointHost.Config.DebugHttpListenerHostEnvironment + "_v" + Env.AntServiceStackVersion + "_" + serviceMetadata.FullServiceName,
                Date                = DateTime.UtcNow,
                ServiceName         = serviceMetadata.FullServiceName,
                UserHostAddress     = httpReq.UserHostAddress,
                HttpMethod          = httpReq.HttpMethod,
                AbsoluteUri         = httpReq.AbsoluteUri,
                RawUrl              = httpReq.RawUrl,
                ResolvedPathInfo    = httpReq.PathInfo,
                ContentType         = httpReq.ContentType,
                Headers             = ToKeyValuePairList(httpReq.Headers),
                QueryString         = ToKeyValuePairList(httpReq.QueryString),
                FormData            = ToKeyValuePairList(httpReq.FormData),
                AcceptTypes         = new List <string>(httpReq.AcceptTypes ?? new string[0]),
                ContentLength       = httpReq.ContentLength,
                ServicePath         = httpReq.ServicePath,
                OperationName       = httpReq.OperationName,
                ResponseContentType = httpReq.ResponseContentType,
            };

            return(response);
        }
Exemple #14
0
        /// <summary>
        /// Recupera la configuración del servicio de negocio.
        /// </summary>
        /// <remarks>Lee la configuración utilizando un ServiceConfigurationManager del tipo especificado en los settings de la aplicación.</remarks>
        /// <param name="providerName">Nombre del proveedor de la metadata de servicio</param>
        /// <param name="serviceName">Nombre del servicio de negocio.</param>
        /// <returns>configuración del servicio de negocio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public static ServiceConfiguration GetServiceConfiguration(string providerName, string serviceName)
        {
            // obtención de la configuración del servicio.
            ServiceConfiguration wResult = ServiceMetadata.GetServiceConfiguration(providerName, serviceName);

            return(wResult);
        }
        /// <summary>
        /// The invokes the Component async.
        /// </summary>
        /// <param name="org"> The org. </param>
        /// <param name="service"> The service. </param>
        /// <param name="edition"> The edition. </param>
        /// <param name="serviceMetadata"> The service Metadata. </param>
        /// <param name="viewMetadatas">The view metadata list</param>
        /// <param name="codeCompilationResult"> The code Compilation Result. </param>
        /// <returns> The <see cref="Task"/>.  </returns>
        public async Task <IViewComponentResult> InvokeAsync(
            string org,
            string service,
            string edition,
            ServiceMetadata serviceMetadata             = null,
            IList <ViewMetadata> viewMetadata           = null,
            CodeCompilationResult codeCompilationResult = null)
        {
            ServiceEditionIdentifier serviceEdition = new ServiceEditionIdentifier {
                Org = org, Service = service, Edition = edition
            };
            CodeCompilationResult compilation = null;

            if (string.IsNullOrEmpty(_generalSettings.RuntimeMode) || !_generalSettings.RuntimeMode.Equals("ServiceContainer"))
            {
                compilation = codeCompilationResult ?? await Compile(serviceEdition);


                var metadata = serviceMetadata ?? await GetServiceMetadata(serviceEdition);

                EditionStatusViewModel model = CreateModel(serviceEdition, compilation, metadata);

                return(View(model));
            }

            return(View(new EditionStatusViewModel()));
        }
Exemple #16
0
        /// <summary>
        /// Method which generates a class containing calculation and validation logic for a service based on the
        /// given input
        /// </summary>
        /// <param name="org">The organization code</param>
        /// <param name="service">The service code</param>
        /// <param name="ruleContainers">The rule containers to generate logic based on</param>
        /// <param name="serviceMetadata">The service metadata of the service to generate the class for</param>
        public void CreateCalculationsAndValidationsClass(
            string org,
            string service,
            List <RuleContainer> ruleContainers,
            ServiceMetadata serviceMetadata)
        {
            List <char> reservedIndexNames             = new List <char>();
            Dictionary <string, Iterator> allIterators = new Dictionary <string, Iterator>();
            Dictionary <string, string>   allMethods   = new Dictionary <string, string>();

            string finalRule = string.Empty;

            foreach (RuleContainer ruleContainer in ruleContainers)
            {
                finalRule += CreateRulesRecursive(ruleContainer, allIterators, allMethods, serviceMetadata, reservedIndexNames);
            }

            var eventLogic = new Dictionary <ServiceEventType, string>
            {
                { ServiceEventType.BeforeRender, string.Empty },
                { ServiceEventType.Calculation, finalRule }, // TODO: Add option to choose which event rules should be linked to
                { ServiceEventType.Instantiation, string.Empty },
                { ServiceEventType.ValidateInstantiation, string.Empty },
                { ServiceEventType.Validation, string.Empty },
            };

            CreateClassFromTemplate(org, service, eventLogic, allMethods, serviceMetadata);
        }
Exemple #17
0
        private string GenerateAritmeticMethod(
            string fieldId,
            string methodName,
            string body,
            string variableType,
            string variableName,
            ServiceMetadata serviceMetadata)
        {
            Dictionary <string, Iterator> iterators = new Dictionary <string, Iterator>();
            List <char> reservedIndexNames          = new List <char>();

            iterators = CreateIterator(1, fieldId, serviceMetadata, reservedIndexNames, iterators);

            string modelName     = serviceMetadata.Elements.Values.First(v => string.IsNullOrEmpty(v.ParentElement)).ID;
            string methodWrapper = "public " + variableType + " " + methodName + "_{0}({1} {2}) {3}";
            string variable      = variableType + " " + variableName + " = 0;\n";

            body = string.Format(body, GetIndexedElementId(fieldId, iterators));

            string codeFriendlyElementId = GetCodeFriendlyElementId(fieldId);
            string iteratorCode          = CreateIteratorCode(iterators.Values.ToList());
            string iterator = string.Format(iteratorCode.Replace("{", "{{").Replace("}", "}}").Replace("{{0}}", "{0}"), body);

            return(string.Format(
                       methodWrapper,
                       codeFriendlyElementId,
                       modelName,
                       modelName,
                       "{\n" + variable + "\n" + iterator + "\n return " + variableName + ";\n}"));
        }
Exemple #18
0
        public void HandleMessage(IChannel channel, RpcRequest request)
        {
            RpcResponse response = new RpcResponse()
            {
                RequestId = request.RequestId
            };

            ServiceMetadata serviceMetadata = _cacheContainer.Application.ServiceMetadatas.Find(m => m.ServiceName == request.ServiceName);

            if (serviceMetadata == null)
            {
            }

            object service = Activator.CreateInstance(serviceMetadata.ServiceImplType);

            MethodMetadata methodMetadata = serviceMetadata.MethodMetadatas.Find(m => m.MethodName == request.MethodName);

            if (methodMetadata == null)
            {
            }

            response.Result = methodMetadata.Method.Invoke(service, request.Parameters);

            channel.Write(response);
        }
Exemple #19
0
        private Iterator CreateIterator(
            string elementId,
            Dictionary <string, Iterator> existingIterators,
            ServiceMetadata serviceMetadata,
            List <char> reservedIndexNames)
        {
            ElementMetadata elementMetadata = serviceMetadata.Elements[elementId];

            string variableName = elementId;

            foreach (Iterator i in existingIterators.Values)
            {
                // Property -> Property[a] etc. when there are parent iterators
                variableName = variableName.Replace(i.ElementNameLastPart + '.', i.ElementNameWithIndexLastPart + '.');
            }

            string indexName = GetFirstAvailableIndexName(reservedIndexNames).ToString();

            var iterator = new Iterator
            {
                IndexName   = indexName,
                ElementName = variableName,
            };

            return(iterator);
        }
        public void CanUploadIso8859EncodedXmlFiles()
        {
            // Arrange
            ServiceMetadata serviceMetadata = null;
            XDocument       xmlDocument     = null;

            Mock <IRepository> moqRepository = new Mock <IRepository>();

            moqRepository.Setup(r => r.CreateModel(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ServiceMetadata>(), It.IsAny <XDocument>()))
            .Returns(true)
            .Callback <string, string, ServiceMetadata, XDocument>((o, s, m, d) =>
            {
                serviceMetadata = m;
                xmlDocument     = d;
            });

            ModelController controller = new ModelController(moqRepository.Object, new TestLoggerFactory());

            IFormFile formFile = AsMockIFormFile("Designer/Edag-latin1.xsd");

            ActionResult result = controller.Upload("Org", "service2", formFile);

            Assert.NotNull(serviceMetadata);

            Assert.True(serviceMetadata.Elements.ContainsKey("melding.LeveranseæøåÆØÅ"));
        }
        internal static void LogMessage(IHttpRequest httpRequest, IHttpResponse httpResponse)
        {
            try
            {
                ServiceMetadata serviceMetadata = EndpointHost.Config.MetadataMap[httpRequest.ServicePath];

                Dictionary <string, string> requestData = new Dictionary <string, string>();
                if (httpRequest.RequestObject != null &&
                    httpRequest.ContentLength > 0 &&
                    httpRequest.ContentLength <= MessageLogConfig.RequestLogMaxSize &&
                    serviceMetadata.CanLogRequest(httpRequest.OperationName))
                {
                    requestData.Add("request", JsonSerializer.SerializeToString(httpRequest.RequestObject));
                }


                Dictionary <string, string> responseData = new Dictionary <string, string>();
                if (httpResponse.ResponseObject != null &&
                    httpResponse.ExecutionResult != null &&
                    httpResponse.ExecutionResult.ResponseSize > 0 &&
                    httpResponse.ExecutionResult.ResponseSize <= MessageLogConfig.ResponseLogMaxSize &&
                    serviceMetadata.CanLogResponse(httpRequest.OperationName))
                {
                    responseData.Add("response", JsonSerializer.SerializeToString(httpResponse.ResponseObject));
                }
            }
            catch (Exception ex)
            {
                Log.Warn("Failed to log request/response messages!", ex, new Dictionary <string, string>()
                {
                    { "ErrorCode", "FXD300032" }
                });
            }
        }
        protected ServiceStackHost(string serviceName, params Assembly[] assembliesWithServices)
        {
            this.StartedAt = DateTime.UtcNow;

            ServiceName = serviceName;
            Container   = new Container {
                DefaultOwner = Owner.External
            };
            ServiceController = CreateServiceController(assembliesWithServices);

            ContentTypes              = Host.ContentTypes.Instance;
            RestPaths                 = new List <RestPath>();
            Routes                    = new ServiceRoutes(this);
            Metadata                  = new ServiceMetadata(RestPaths);
            PreRequestFilters         = new List <Action <IRequest, IResponse> >();
            GlobalRequestFilters      = new List <Action <IRequest, IResponse, object> >();
            GlobalResponseFilters     = new List <Action <IRequest, IResponse, object> >();
            ViewEngines               = new List <IViewEngine>();
            ServiceExceptionHandlers  = new List <HandleServiceExceptionDelegate>();
            UncaughtExceptionHandlers = new List <HandleUncaughtExceptionDelegate>();
            RawHttpHandlers           = new List <Func <IHttpRequest, IHttpHandler> > {
                HttpHandlerFactory.ReturnRequestInfo,
                MiniProfilerHandler.MatchesRequest,
            };
            CatchAllHandlers        = new List <HttpHandlerResolverDelegate>();
            CustomErrorHttpHandlers = new Dictionary <HttpStatusCode, IServiceStackHandler>();
            Plugins = new List <IPlugin> {
                new HtmlFormat(),
                new CsvFormat(),
                new MarkdownFormat(),
                new PredefinedRoutesFeature(),
                new MetadataFeature(),
            };
        }
Exemple #23
0
        /// <inheritdoc/>
        public Task <bool> IsAuthorizedAsync(HttpContext ctx, ServiceMetadata metadata)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }
            if (metadata == null)
            {
                throw new ArgumentNullException(nameof(metadata));
            }

            IEnumerable <object> authenticationAttributes;

            if (!_cachedAuthAttributes.TryGetValue(metadata.Ident, out authenticationAttributes))
            {
                var serviceAuthAttributes = new List <object>();
                serviceAuthAttributes.AddRange(metadata.Service.GetCustomAttributes <AuthorizeAttribute>());
                serviceAuthAttributes.AddRange(metadata.Service.GetCustomAttributes <AllowAnonymousAttribute>());

                serviceAuthAttributes.AddRange(metadata.Method.GetCustomAttributes <AuthorizeAttribute>());
                serviceAuthAttributes.AddRange(metadata.Method.GetCustomAttributes <AllowAnonymousAttribute>());

                _cachedAuthAttributes.TryAdd(metadata.Ident, serviceAuthAttributes);
                authenticationAttributes = serviceAuthAttributes;
            }

            return(IsAuthorizedAsync(ctx, authenticationAttributes));
        }
Exemple #24
0
        public ActionResult Upload(string org, string service, string edition, IFormFile thefile, IEnumerable <IFormFile> secondaryFiles)
        {
            XDocument mainXsd       = null;
            var       secondaryXsds = new Dictionary <string, XDocument>();

            string mainFileName = ContentDispositionHeaderValue.Parse(new StringSegment(thefile.ContentDisposition)).FileName.ToString();

            using (var reader = new StreamReader(thefile.OpenReadStream()))
            {
                mainXsd = XDocument.Parse(reader.ReadToEnd());
            }

            secondaryXsds.Clear();

            foreach (IFormFile file in secondaryFiles)
            {
                string filename = ContentDispositionHeaderValue.Parse(new StringSegment(file.ContentDisposition)).FileName.ToString();
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    secondaryXsds.Add(filename, XDocument.Parse(reader.ReadToEnd()));
                }
            }

            var             seresParser     = new SeresXsdParser(_repository);
            ServiceMetadata serviceMetadata = seresParser.ParseXsdToServiceMetadata(org, service, edition, mainXsd, secondaryXsds);

            if (_repository.CreateModel(org, service, edition, serviceMetadata, mainXsd))
            {
                return(RedirectToAction("Index", new { org, service, edition }));
            }

            return(Json(false));
        }
Exemple #25
0
        /// <summary>
        /// CAmbia el proveedor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cb_SelectedValueChanged(object sender, EventArgs e)
        {
            _SelectedProvider = ServiceMetadata.ProviderSection.GetProvider(cmb2.SelectedItem.ToString());

            SetProviderDest();


            try
            {
                //cargo la grilla derecha
                ucbServiceGrid2.Services     = ServiceMetadata.GetAllServices(_SelectedProvider.Name);
                ucbServiceGrid2.Applications = ServiceMetadata.GetAllApplicationsId(_SelectedProvider.Name);



                //muestro el titulo
                this.Text = string.Concat("Export data from ", _SelectedProvider.Name, " to ", _SelectedProvider.Name);
            }
            catch (Exception ex)
            {
                base.ExceptionViewer.Show(ex);

                ucbServiceGrid1.Services = null;
            }
        }
        public MetadataPagesConfig(
            ServiceMetadata metadata,
            ServiceEndpointsMetadataConfig metadataConfig,
            HashSet <string> ignoredFormats,
            List <string> contentTypeFormats)
        {
            this.ignoredFormats = ignoredFormats;
            this.metadata       = metadata;

            metadataConfigMap = new Dictionary <string, MetadataConfig> {
                { "xml", metadataConfig.Xml },
                { "json", metadataConfig.Json },
                { "jsv", metadataConfig.Jsv },
#if !NETSTANDARD2_0
                { "soap11", metadataConfig.Soap11 },
                { "soap12", metadataConfig.Soap12 },
#endif
            };

            AvailableFormatConfigs = new List <MetadataConfig>();

            var config = GetMetadataConfig("xml");
            if (config != null)
            {
                AvailableFormatConfigs.Add(config);
            }
            config = GetMetadataConfig("json");
            if (config != null)
            {
                AvailableFormatConfigs.Add(config);
            }
            config = GetMetadataConfig("jsv");
            if (config != null)
            {
                AvailableFormatConfigs.Add(config);
            }

            foreach (var format in contentTypeFormats)
            {
                metadataConfigMap[format] = metadataConfig.Custom.Create(format);

                config = GetMetadataConfig(format);
                if (config != null)
                {
                    AvailableFormatConfigs.Add(config);
                }
            }

            config = GetMetadataConfig("soap11");
            if (config != null)
            {
                AvailableFormatConfigs.Add(config);
            }
            config = GetMetadataConfig("soap12");
            if (config != null)
            {
                AvailableFormatConfigs.Add(config);
            }
        }
Exemple #27
0
		protected MetadataTestBase()
		{
            Metadata = new ServiceMetadata();
		    var dummyServiceType = GetType();
            Metadata.Add(dummyServiceType, typeof(GetCustomer), typeof(GetCustomerResponse));
            Metadata.Add(dummyServiceType, typeof(GetCustomers), typeof(GetCustomersResponse));
            Metadata.Add(dummyServiceType, typeof(StoreCustomer), null);
		}
Exemple #28
0
 public MetadataPagesConfig CreateMetadataPagesConfig(ServiceMetadata metadata)
 {
     return(new MetadataPagesConfig(
                metadata,
                ServiceEndpointsMetadataConfig,
                IgnoreFormatsInMetadata,
                EndpointHost.ContentTypeFilter.ContentTypeFormats.Keys.ToList()));
 }
        /// <summary>
        /// Returns the list of code list for a service.
        /// </summary>
        /// <param name="org">The Organization code for the service owner.</param>
        /// <param name="service">The service code for the current service.</param>
        /// <returns>List of code lists.</returns>
        public Dictionary <string, CodeList> GetCodelists(string org, string service)
        {
            Dictionary <string, CodeList> codeLists = new Dictionary <string, CodeList>();

            ServiceMetadata metaData = _repository.GetServiceMetaData(org, service);

            return(codeLists);
        }
Exemple #30
0
        private static ServiceMetadata SeresXSDParse(Mock <IRepository> moqRepository, string file)
        {
            SeresXsdParser  seresParser     = new SeresXsdParser(moqRepository.Object);
            XDocument       mainXsd         = XDocument.Load(file);
            ServiceMetadata serviceMetadata = seresParser.ParseXsdToServiceMetadata("org", "service", mainXsd, null);

            return(serviceMetadata);
        }
Exemple #31
0
 public TodoReadBootstrap()
 {
     _meta = new ServiceMetadata
     {
         Name        = nameof(TodoReadService),
         Description = "Read side of Todo Service",
     };
 }
        //public ServiceOperations ServiceOperations { get; set; }
        //public ServiceOperations AllServiceOperations { get; set; }

		public ServiceManager(params Assembly[] assembliesWithServices)
		{
			if (assembliesWithServices == null || assembliesWithServices.Length == 0)
				throw new ArgumentException(
					"No Assemblies provided in your AppHost's base constructor.\n"
					+ "To register your services, please provide the assemblies where your web services are defined.");

			this.Container = new Container { DefaultOwner = Owner.External };
            this.Metadata = new ServiceMetadata();
            this.ServiceController = new ServiceController(() => GetAssemblyTypes(assembliesWithServices), this.Metadata);
		}
        /// <summary>
        /// Inject alternative container and strategy for resolving Service Types
        /// </summary>
        public ServiceManager(Container container, ServiceController serviceController)
        {
            if (serviceController == null)
                throw new ArgumentNullException("serviceController");

            this.Container = container ?? new Container();
            this.Metadata = serviceController.Metadata; //always share the same metadata
            this.ServiceController = serviceController;

            typeFactory = new ContainerResolveCache(this.Container);
        }
        public static MethodInfo GetMethod(ServiceMetadata metadata, string urlTemplate, HttpMethod httpMethod)
        {
            List<ServiceMethodMetadata> methods;

            if (!serviceMethods.TryGetValue(metadata, out methods))
            {
                return null;
            }

            foreach (var method in methods)
            {
                if (String.Equals(method.UrlInfo.UrlTemplate, urlTemplate) && method.UrlInfo.HttpMethods.Contains(httpMethod))
                {
                    return method.MethodInfo;
                }
            }

            return null;
        }
Exemple #35
0
 public ChangeSetGraph(ChangeSet changeSet, ServiceMetadata metadata)
 {
     this._changeSet = changeSet;
     this._metadata = metadata;
 }
 public string From(ServiceMetadata evidence)
 {
     throw new System.NotImplementedException();
 }
 public override void SetMetadata(ServiceMetadata metadata)
 {
     _quiet = metadata.Quiet;
     _silent = metadata.Silent;
     _serviceName = metadata.ServiceName;
     SetController(ServiceControllerProxy.GetInstance(metadata.ServiceName));
 }
 /// <summary>Renders the operations.</summary>
 ///
 /// <param name="writer">  The writer.</param>
 /// <param name="httpReq"> The HTTP request.</param>
 /// <param name="metadata">The metadata.</param>
 protected abstract void RenderOperations(HtmlTextWriter writer, IHttpRequest httpReq, ServiceMetadata metadata);
 public abstract void SetMetadata(ServiceMetadata metadata);