public static HttpResponseValue Get(string uri, String username, String password)
 {
     try
     {
         log.Debug("URL to call : " + uri.ToString());
         System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
         if (username != null && password != null)
         {
             string credential = username + ":" + password;
             string authHeader = Convert.ToBase64String(Encoding.Default.GetBytes(credential));
             request.Headers["Authorization"] = "Basic " + authHeader;
         }
         request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
         {
             int statusCode  = (int)response.StatusCode;
             var contentType = response.Headers.Get("Content-Type");
             using (Stream stream = response.GetResponseStream())
                 using (StreamReader reader = new StreamReader(stream))
                 {
                     string            responseBody      = reader.ReadToEnd();
                     HttpResponseValue httpResponseValue = new HttpResponseValue(responseBody, contentType, statusCode);
                     return(httpResponseValue);
                 }
         }
     }
     catch (WebException e)
     {
         throw e;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Beispiel #2
0
        public static void process(Uri uri, string username, string password, string response, string outputFile)
        {
            //Console.WriteLine(output);
            var results     = JsonConvert.DeserializeObject <dynamic>(response);
            var metadataURI = results["@odata.context"].Value;
            var url         = new Uri(metadataURI);
            var host        = url.Host;
            int port        = url.Port;

            if (!(port == 80 || port == 443))
            {
                host = host + ":" + port;
            }

            var version  = "1.0.0";
            var protocol = url.Scheme;
            var basePath = url.AbsolutePath;

            basePath = basePath.Substring(0, basePath.LastIndexOf("/"));

            HttpResponseValue httpResponseValue = Util.Get(metadataURI, username, password);

            if (httpResponseValue.getStatusCode() == 200)
            {
                StringReader           stringReader = new StringReader(httpResponseValue.getResponseBody());
                XmlReader              reader       = XmlReader.Create(stringReader);
                IEdmModel              model;
                IEnumerable <EdmError> errors;
                CsdlReader.TryParse(reader, out model, out errors);
                JObject swaggerDoc = new JObject()
                {
                    { "swagger", "2.0" },
                    { "info", new JObject()
                      {
                          { "title", "OData Service" },
                          { "description", "The OData Service at " + metadataURI },
                          { "version", version },
                          { "x-odata-version", "4.0" }
                      } },
                    { "host", host },
                    { "schemes", new JArray(protocol) },
                    { "basePath", basePath },
                    { "consumes", new JArray("application/json") },
                    { "produces", new JArray("application/json") },
                };

                JObject swaggerPaths = new JObject();
                swaggerDoc.Add("paths", swaggerPaths);
                JObject swaggeDefinitions = new JObject();
                swaggerDoc.Add("definitions", swaggeDefinitions);

                foreach (var entitySet in model.EntityContainer.EntitySets())
                {
                    swaggerPaths.Add("/" + entitySet.Name + "*", CreateSwaggerPathForEntitySet(entitySet));
                    swaggerPaths.Add(GetPathForEntity(entitySet) + "*", CreateSwaggerPathForEntity(entitySet));
                }
                foreach (var operationImport in model.EntityContainer.OperationImports())
                {
                    swaggerPaths.Add(GetPathForOperationImport(operationImport) + "*", CreateSwaggerPathForOperationImport(operationImport));
                }

                foreach (var type in model.SchemaElements.OfType <IEdmStructuredType>())
                {
                    swaggeDefinitions.Add(type.FullTypeName(), CreateSwaggerDefinitionForStructureType(type));
                }

                foreach (var operation in model.SchemaElements.OfType <IEdmOperation>())
                {
                    // skip unbound operation
                    if (!operation.IsBound)
                    {
                        continue;
                    }
                    var boundParameter = operation.Parameters.First();
                    var boundType      = boundParameter.Type.Definition;
                    // skip operation bound to non entity (or entity collection)
                    if (boundType.TypeKind == EdmTypeKind.Entity)
                    {
                        IEdmEntityType entityType = boundType as IEdmEntityType;
                        foreach (var entitySet in
                                 model.EntityContainer.EntitySets().Where(es => es.EntityType().Equals(entityType)))
                        {
                            swaggerPaths.Add(GetPathForOperationOfEntity(operation, entitySet) + "*",
                                             CreateSwaggerPathForOperationOfEntity(operation, entitySet));
                        }
                    }

                    else if (boundType.TypeKind == EdmTypeKind.Collection &&
                             (boundType as IEdmCollectionType).ElementType.Definition.TypeKind == EdmTypeKind.Entity)
                    {
                        IEdmEntityType entityType = boundType as IEdmEntityType;
                        foreach (
                            var entitySet in
                            model.EntityContainer.EntitySets().Where(es => es.EntityType().Equals(entityType)))
                        {
                            swaggerPaths.Add(GetPathForOperationOfEntitySet(operation, entitySet) + "*",
                                             CreateSwaggerPathForOperationOfEntitySet(operation, entitySet));
                        }
                    }
                }

                swaggeDefinitions.Add("_Error", new JObject()
                {
                    {
                        "properties", new JObject()
                        {
                            {
                                "error", new JObject()
                                {
                                    { "$ref", "#/definitions/_InError" }
                                }
                            }
                        }
                    }
                });
                swaggeDefinitions.Add("_InError", new JObject()
                {
                    {
                        "properties", new JObject()
                        {
                            {
                                "code", new JObject()
                                {
                                    { "type", "string" }
                                }
                            },
                            {
                                "message", new JObject()
                                {
                                    { "type", "string" }
                                }
                            }
                        }
                    }
                });
                File.WriteAllText(outputFile, swaggerDoc.ToString());
            }
        }
Beispiel #3
0
        static void Main(string[] args)

        {
            //  log4net.Config.BasicConfigurator.Configure();
            log.Debug("Converting odatav3 document");
            string samlDisabled = "saml2=disabled";
            bool   disableSAML  = false;
            string username     = null;
            string password     = null;

            if (args.Length < 2)
            {
                Console.WriteLine("Invalid command line arguments");
                Console.WriteLine("Example OData 4: OdataSwaggerConverter.exe http://services.odata.org/V4/TripPinServiceRW trip.json");
                Console.WriteLine("Example OData 3: OdataSwaggerConverter.exe http://services.odata.org/V3/Northwind/Northwind.svc/$metadata northwind.json");
                return;
            }

            string outputFile  = args[1];
            string metadataURI = args[0];

            if (args.Length == 4)
            {
                username = args[2];
                password = args[3];
            }
            else if (args.Length == 5 || args.Length == 3)
            {
                username = args[2];
                password = args[3];
                string samlFlag = args[4].Trim();
                if (samlFlag.Equals(samlDisabled))
                {
                    disableSAML = true;
                    metadataURI = metadataURI + "?" + samlDisabled;
                }
            }

            try
            {
                var url = new Uri(metadataURI);
                HttpResponseValue httpResponseValue = Util.Get(metadataURI, username, password);
                int    statusCode   = httpResponseValue.getStatusCode();
                string responseBody = httpResponseValue.getResponseBody();
                string contentType  = httpResponseValue.getContentType();

                log.Debug("Response Http Status code : " + statusCode);
                log.Debug("Response from metadata URI : " + responseBody);
                log.Debug("Response Content-Type : " + contentType);

                if (statusCode == 200)
                {
                    if (contentType.Contains("application/json"))
                    {
                        log.Info("Processing odata 4 meta data");
                        OData4.process(url, username, password, httpResponseValue.getResponseBody(), outputFile);
                    }
                    else if (contentType.Contains("application/xml"))
                    {
                        StringReader stringReader = new StringReader(responseBody);
                        IEdmModel    model        = EdmxReader.Parse(System.Xml.XmlTextReader.Create(stringReader));
                        process(url, model, outputFile, disableSAML);
                    }
                }
            }catch (Exception e)
            {
                log.Error("Problem in reading meta data file", e);
                return;
            }
        }