Ejemplo n.º 1
0
        PostmanCollection PostmanCollectionForController()
        {
            var postManCollection = new PostmanCollection
            {
                Id          = Guid.NewGuid(),
                Name        = string.Format("Ises Backoffice Api (v{0})", Core.Common.Utils.GetHostVersion()),
                Timestamp   = DateTime.Now.Ticks,
                Order       = new Guid[0],
                Folders     = new Collection <PostmanFolder>(),
                Requests    = new Collection <PostmanRequest>(),
                Synced      = false,
                Description = "Ises Backoffice Api"
            };

            var apiExplorer = Configuration.Services.GetApiExplorer();
            var apiDescriptionsByController = apiExplorer.ApiDescriptions.GroupBy(description => description.ActionDescriptor.ActionBinding.ActionDescriptor.ControllerDescriptor.ControllerType);

            foreach (var apiDescriptionsByControllerGroup in apiDescriptionsByController)
            {
                var postManFolder = GetApiControllerDescription(apiDescriptionsByControllerGroup, postManCollection);

                postManCollection.Folders.Add(postManFolder);
            }

            return(postManCollection);
        }
Ejemplo n.º 2
0
        public PostmanCollection GetDiscovery(string name, Uri uri)
        {
            var explorer          = GlobalConfiguration.Configuration.Services.GetApiExplorer();
            var postManCollection = new PostmanCollection();

            postManCollection.Name      = name;
            postManCollection.Id        = Guid.NewGuid();
            postManCollection.Timestamp = DateTime.Now.Ticks;
            postManCollection.Requests  = new Collection <PostmanRequest>();

            foreach (var apiDescription in explorer.ApiDescriptions)
            {
                var relativePath = apiDescription.RelativePath;

                var request = new PostmanRequest
                {
                    CollectionId = postManCollection.Id,
                    Id           = Guid.NewGuid(),
                    Method       = apiDescription.HttpMethod.Method,
                    Url          = uri.GetRootDomain().TrimEnd('/') + "/" + relativePath,
                    Description  = apiDescription.Documentation,
                    Name         = apiDescription.RelativePath,
                    Data         = "",
                    Headers      = "",
                    DataMode     = "params",
                    Timestamp    = 0
                };

                postManCollection.Requests.Add(request);
            }

            return(postManCollection);
        }
        protected virtual void ProcessOperations(Stream responseStream, IHttpRequest httpReq)
        {
            var metadata = EndpointHost.Metadata;

            var collectionId = Guid.NewGuid().ToString();

            var req =
                GetRequests(httpReq, metadata, collectionId, metadata.Operations)
                .OrderBy(r => r.Folder)
                .ThenBy(r => r.Name);

            var collection = new PostmanCollection
            {
                Id        = collectionId,
                Name      = EndpointHost.Config.ServiceName,
                Timestamp = DateTime.UtcNow.ToUnixTimeMs(),
                Requests  = req.ToArray(),
                Order     = new List <string>(),
                Folders   = new List <PostmanFolder>()
            };

            AddToFolders(collection);
            if (SupportFolders && DoNotAllowFolderIfOnlyOneItem)
            {
                MoveOneItemFoldersOneLevelUp(collection);
            }

            using (var scope = JsConfig.BeginScope())
            {
                scope.EmitCamelCaseNames = true;
                JsonSerializer.SerializeToStream(collection, responseStream);
            }
        }
Ejemplo n.º 4
0
        public object Any(Postman request)
        {
            var feature = HostContext.GetPlugin <PostmanFeature>();

            if (request.ExportSession)
            {
                if (feature.EnableSessionExport != true)
                {
                    throw new ArgumentException("PostmanFeature.EnableSessionExport is not enabled");
                }

                var url = Request.GetBaseUrl()
                          .CombineWith(Request.PathInfo)
                          .AddQueryParam("ssopt", Request.GetItemOrCookie(SessionFeature.SessionOptionsKey))
                          .AddQueryParam("sspid", Request.GetPermanentSessionId())
                          .AddQueryParam("ssid", Request.GetTemporarySessionId());

                return(HttpResult.Redirect(url));
            }

            var id  = SessionExtensions.CreateRandomSessionId();
            var ret = new PostmanCollection
            {
                info = new PostmanCollectionInfo()
                {
                    version = "1",
                    name    = HostContext.AppHost.ServiceName,
                    schema  = "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
                },
                item = GetRequests(request, id, HostContext.Metadata.OperationsMap.Values),
            };

            return(ret);
        }
Ejemplo n.º 5
0
        private async Task <PostmanCollection> ReadFileAsync(string filePath)
        {
            using (var reader = new StreamReader(filePath))
            {
                string contents = await reader.ReadToEndAsync().ConfigureAwait(false);

                return(PostmanCollection.FromJson(contents));
            }
        }
Ejemplo n.º 6
0
        PostmanRequest GetApiActionDescription(ApiDescription apiDescription, PostmanCollection postManCollection)
        {
            TextSample sampleData       = null;
            var        sampleDictionary = helpPageSampleGenerator.GetSample(apiDescription, SampleDirection.Request);
            var        mediaTypeHeader  = GetMediaTypeHeaderValue();

            if (sampleDictionary.ContainsKey(mediaTypeHeader))
            {
                sampleData = sampleDictionary[mediaTypeHeader] as TextSample;
            }

            var nv = new NameValueCollection();

            foreach (var parameter in apiDescription.ParameterDescriptions)
            {
                var sampleObject = helpPageSampleGenerator.GetSampleObject(parameter.ParameterDescriptor.ParameterType);
                nv.Add(parameter.Name, sampleObject == null ? string.Empty : sampleObject.ToString());
            }

            var questionMark = apiDescription.RelativePath.IndexOf("?", StringComparison.Ordinal);

            var cleanedUrlParameterUrl = apiDescription.RelativePath;

            if (questionMark >= 0)
            {
                var queryString = nv.ConvertToQueryString();

                cleanedUrlParameterUrl  = apiDescription.RelativePath.Remove(questionMark);
                cleanedUrlParameterUrl += "?" + queryString;
            }
            // get path variables from url
            var pathVariables = pathVariableRegEx.Matches(cleanedUrlParameterUrl)
                                .Cast <Match>()
                                .Select(m => m.Value)
                                .Select(s => s.Substring(1, s.Length - 2))
                                .ToDictionary(s => s, s => string.Format("{0}-value", s));

            // change format of parameters within string to be colon prefixed rather than curly brace wrapped
            var postmanReadyUrl = pathVariableRegEx.Replace(cleanedUrlParameterUrl, ":$1");

            // prefix url with base uri
            var url     = string.Format("{0}/{1}", baseUri.TrimEnd('/'), postmanReadyUrl);
            var headers = new Dictionary <string, string>
            {
                { "Content-Type", "application/json" }
            };

            var sample       = sampleData != null ? sampleData.Text : null;
            var relativePath = string.Format("/{0}", apiDescription.RelativePath);
            var request      = CreatePostmanRequest(postManCollection, apiDescription.HttpMethod.Method, relativePath, url, headers, sample, "raw", apiDescription.Documentation);

            request.PathVariables = pathVariables;

            return(request);
        }
 private void MoveOneItemFoldersOneLevelUp(PostmanCollection collection)
 {
     for (int folderIdx = collection.Folders.Count - 1; folderIdx >= 0; folderIdx--)
     //Counting backwards to be able to remove folders
     {
         var folder = collection.Folders[folderIdx];
         if (folder.Order.Count == 1)
         {
             collection.Order.Add(folder.Order[0]);
             collection.Folders.RemoveAt(folderIdx);
         }
     }
 }
Ejemplo n.º 8
0
 static PostmanRequest CreatePostmanRequest(PostmanCollection postManCollection, string method, string name, string url, Dictionary <string, string> headers, object sampleData, string dataMode, string description)
 {
     return(new PostmanRequest
     {
         Name = name,
         Description = description,
         Url = url,
         Method = method,
         Headers = GetHeadersString(headers),
         Data = sampleData,
         DataMode = dataMode,
         Time = postManCollection.Timestamp,
         CollectionId = postManCollection.Id
     });
 }
Ejemplo n.º 9
0
        public JsonResult <PostmanCollection> GetPostmanCollection_Raw(string serviceName = "WebAPI2PostMan")
        {
            var collectionId = PostMan.GetId();
            var apis         = Configuration.Services.GetApiExplorer().ApiDescriptions.Where(x => x.Documentation != null);
            var requests     = GetPostmanRequests_Raw(apis, collectionId);
            var collection   = new PostmanCollection
            {
                id          = collectionId,
                name        = serviceName,
                description = "",
                order       = requests.Select(x => x.id).ToList(),
                timestamp   = 0,
                requests    = requests
            };

            return(Json(collection));
        }
Ejemplo n.º 10
0
        /// <summary>
        ///  Initializes a new instance of the <see cref="PostmanListener"/> class.
        /// </summary>
        /// <param name="name">name of the postMan collection</param>
        public PostmanListener(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("name of collection can't be null or empty", nameof(name));
            }

            Collection = new PostmanCollection
            {
                Info = new Info
                {
                    PostmanId = Guid.NewGuid().ToString(),
                    Name      = name,
                    Schema    = "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
                },
                Items = new List <Folder>()
            };
        }
Ejemplo n.º 11
0
        public override string Generate(Table table, GeneratorOptions options)
        {
            PostmanCollection collection = new PostmanCollection();

            collection.Info           = new Info();
            collection.Info.PostmanId = Guid.NewGuid();
            collection.Info.Name      = $"{table.TableName} Collection";
            collection.Info.Schema    = new Uri("https://schema.getpostman.com/json/collection/v2.1.0/collection.json");

            var creator = PostmanItemCreator.Instance;
            List <PostmanItem> items = new List <PostmanItem>();

            foreach (CRUDType c in Enum.GetValues(typeof(CRUDType)))
            {
                items.Add(creator.CreateItem(c, table));
            }

            collection.Item = items.ToArray();

            var postman_event = new PostmanEvent();

            postman_event.Listen = "prerequest";
            postman_event.Script = new Script()
            {
                Type = "text/javascript", Exec = new string[] { }
            };
            collection.Event = new PostmanEvent[] { postman_event };

            Variable variable = new Variable();

            variable.Key        = "url";
            variable.Value      = "https://localhost:44343";
            collection.Variable = new Variable[] { variable };


            return(collection.ToJson());
        }
        private void AddToFolders(PostmanCollection collection)
        {
            if (!collection.Requests.Any())
            {
                return;
            }

            foreach (var request in collection.Requests)
            {
                if (!SupportFolders || string.IsNullOrEmpty(request.Folder))
                {
                    collection.Order.Add(request.Id);
                }
                else
                {
                    var folder = collection.Folders.FirstOrDefault(f => f.Name.Equals(request.Folder));
                    if (folder == null)
                    {
                        folder = new PostmanFolder
                        {
                            CollectionId   = collection.Id,
                            CollectionName = collection.Name,
                            Id             = Guid.NewGuid().ToString(),
                            Name           = request.Folder,
                            Order          = new List <string> {
                                request.Id
                            }
                        };
                        collection.Folders.Add(folder);
                    }
                    else
                    {
                        folder.Order.Add(request.Id);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public PostmanCollection GetDescriptionForPostman()
        {
            var collection = Configuration.Properties.GetOrAdd("postmanCollection", k =>
            {
                var requestUri = Request.RequestUri;
                var baseUri    = requestUri.Scheme + "://" + requestUri.Host + ":" + requestUri.Port + HttpContext.Current.Request.ApplicationPath;

                var postManCollection       = new PostmanCollection();
                postManCollection.Name      = "Bloodhound API Service";
                postManCollection.Id        = Guid.NewGuid();
                postManCollection.Timestamp = DateTime.UtcNow.Ticks;
                postManCollection.Requests  = new Collection <PostmanRequest>();

                foreach (var apiDescription in Configuration.Services.GetApiExplorer().ApiDescriptions)
                {
                    var request = new PostmanRequest
                    {
                        CollectionId = postManCollection.Id,
                        Id           = Guid.NewGuid(),
                        Method       = apiDescription.HttpMethod.Method,
                        Url          = baseUri.TrimEnd('/') + "/" + apiDescription.RelativePath,
                        Description  = apiDescription.Documentation,
                        Name         = apiDescription.RelativePath,
                        Data         = "",
                        Headers      = "",
                        DataMode     = "params",
                        Timestamp    = 0
                    };

                    postManCollection.Requests.Add(request);
                }

                return(postManCollection);
            }) as PostmanCollection;

            return(collection);
        }
		private void WriteFile(PostmanCollection collection, string targetFilename)
		{
			var jsonSerializer = new JsonSerializer() { ContractResolver = new CamelCasePropertyNamesContractResolver() };
			var json = JObject.FromObject(collection, jsonSerializer);

			File.WriteAllText(targetFilename, json.ToString());
		}
Ejemplo n.º 15
0
        PostmanFolder GetApiControllerDescription(IGrouping <Type, ApiDescription> apiDescriptionsByControllerGroup, PostmanCollection postManCollection)
        {
            var controllerName = apiDescriptionsByControllerGroup.Key.Name.Replace("Controller", string.Empty);

            var postManFolder = new PostmanFolder
            {
                Id             = Guid.NewGuid(),
                CollectionId   = postManCollection.Id,
                Name           = controllerName,
                Description    = string.Format("Api Methods for {0}", controllerName),
                CollectionName = "api",
                Order          = new Collection <Guid>()
            };

            var apiDescriptions = apiDescriptionsByControllerGroup
                                  .OrderBy(description => description.HttpMethod, new HttpMethodComparator())
                                  .ThenBy(description => description.RelativePath)
                                  .ThenBy(description => description.Documentation == null ? string.Empty : description.Documentation.ToString(CultureInfo.InvariantCulture));

            foreach (var apiDescription in apiDescriptions)
            {
                var request = GetApiActionDescription(apiDescription, postManCollection);
                request.Time         = postManCollection.Timestamp;
                request.CollectionId = postManCollection.Id;

                postManFolder.Order.Add(request.Id); // add to the folder
                postManCollection.Requests.Add(request);
            }
            return(postManFolder);
        }