Quantcast
Channel: Web API
Viewing all 4850 articles
Browse latest View live

Real time Web query/Web API

$
0
0

Hi, I am looking to do a web app that allow user to do a search and return list of results. My thinking are:

1. Real time web query, like skyscanner.com

2. web API? do i need to create an api for each company so that they could open the data for me to query  whenever there is a search from the user?

1 option would be best but think it would be very difficult and i have no idea how to go about this, 2 option is easier but i also need to learn how to do this. Please advice.


How to pass multiple complex objects to Web API action

$
0
0

suppose this is sample action

public void StartProcessiong([FromBody]Content content, [FromBody]Config config)
{

}

OR

public void StartProcessiong(Content content, Config config)
{

}

client code
-----------
using (var httpClient = new System.Net.Http.HttpClient())
{
    httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["Url"]);
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));   

    var response = httpClient.PutAsync("api/process/StartProcessiong", objectA, objectB);
}

taking code from http://stackoverflow.com/questions/24874490/pass-multiple-complex-objects-to-a-post-put-web-api-method

how to use http client to pass multiple complex object too....need sample code. thanks

WebApi2 - Retrieve ErrorMessage From DataAnnotations

$
0
0

I want to return the custom error message that I have specified in my data model class to return to user.  I've tried creating a filter for override OnActionExecuting(HttpActionContext) but I am still unable to access the custom message.  Am I going about this the wrong way or missing something else?

//In data model:
public class LogsDto 
{
        [Display(Name = "ip")]
        [Required(ErrorMessage = "IP Address is invalid.")]
        [DataMember]
        public string ip { get; set; }
}


//In WebApiConfig.cs:
config.Filters.Add(new ValidateModelAttribute());

//In OnActionExecuting:
public override void OnActionExecuting(HttpActionContext context)
{
if (!context.ModelState.IsValid)
{
    //have tried a variety of methods to locate errormessage

    context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState);
}

//In Controller:
public IHttpActionResult Post([FromBody()]LogsDto request)
{     
    try
{
    if (!ModelState.IsValid)
        return BadRequest();
    else
    { //do stuff }
}

I can get a result like below but when I dig down through the (HttpActionContext context), the ErrorMessage is empty and that is what I need.

{"Message": "The request is invalid.","ModelState": {"request.ip": ["Unexpected character encountered while parsing value: ,. Path ip, line 2, position 12.","After parsing a value an unexpected character was encountered: \". Path ip, line 3, position 2."
    ]
  }
}

Attribute routing issue - different route methods being blocked as duplicate routes

$
0
0

Hi there,

I was wondering whether this is a bug or I'm doing something wrong.

Simple example - two controllers, but override the RoutePrefix  in the second to be the same as the first:

using System.Web.Http;

namespace My.Controllers
{
    [RoutePrefix("first")]
    public class MyFirstTestController : ApiController
    {
        [AllowAnonymous, Route("{id:int}/data"), HttpGet]
        public dynamic GetSomething(int id)
        {
            return "";
        }
    }
}

using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace My.Controllers
{
    [RoutePrefix("second")]
    public class MySecondTestController : ApiController
    {
        [AllowAnonymous, Route("~/first/{id:int}/data"), HttpPost]
        public HttpResponseMessage PostSomething(int id)
        {
            return new HttpResponseMessage(HttpStatusCode.OK);
        }

    }
}

By my estimation, this should leave me with two routes:

GET /first/:id/data

POST /first/:id/data

When I try and call "GET /first/:id/data", I get a duplicate endpoint error:

{
 "message": "An error has occurred.",
 "exceptionMessage": "Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
    The request has found the following matching controller types:
    My.Controllers.MySecondTestController
    My.Controllers.MyFirstTestController",
 "exceptionType": "System.InvalidOperationException",
 "stackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerSelector.GetDirectRouteController(IHttpRouteData routeData)
       at System.Web.Http.Dispatcher.DefaultHttpControllerSelector.SelectController(HttpRequestMessage request)
       at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}

It looks like it's not considering the different method when mapping the route.
Is this a routing bug, or am I doing something wrong?

Thanks.

MEF Dependency injection to Self Hosted WebAPI v. 1

$
0
0

Hi,

I would like to use shared freamework in WEB API v1 which uses MEF for dependency injection in SelfHosted WEB API .

For this I created  a class derived from IDependencyResolver & implemented the methods as shown below.

public object GetService(Type serviceType)
        {
            var export = _container.GetExports(serviceType, null, null).SingleOrDefault();
            return null != export ? export.Value : null;
        }

And set the dependency resolver as

var config = new HttpSelfHostConfiguration("http://lonws21009:8080");
                ControllerBuilder
                config.DependencyResolver = new MefDependencyResolver(_container);

When invoking the services, I am getting the below error.

Controller does not have a default constructor

Get ClaimsPrincipal in Custom AuthorizeAttribute?

$
0
0

I can get bearer access token from embedded authorization server.

The problem is when I request resource from WebAPI, I could not get back the ClaimsPrincipal based on the access token sent along.

Below is the Http post: (1)

GET /api/v1/courses/categories HTTP/1.1
Host: localhost:8080
Authorization: Bearer QoHxP-MbGna2ekhZl-zV9C_3gW2LPBbe-i7DQDp1DFF0BGurjAsqx-rShhmTZlnvScnAdZHNnR1PLcVVuz8B3VwvsYwKKvp-tYw3sohf4B2m5IH97FeCRbA9_nv4DflZtUSSQnrdlKNHHQGgl8VZ5Pcdc09V5hAv5f3sGd-1qsIsKuON81mhlC2PKWNA6a0NTid_LyvzEY1zGQtrgx8ue2NFMNztXBYuy1jXgv6SPAdoOLU3mH38wXg4l7UmVJ10MAbcljNczDSgY9QOC439BmpscG_kIYONiqQaMGMQhmFqnaKIkCMy9PgQ9WvQaLpz
Cache-Control: no-cache
Postman-Token: bd0096e6-3471-bb49-460d-f198f7f516e4

Below is the Owin Startup: (2)

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);
        app.UseCors(CorsOptions.AllowAll);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new AuthorizationServerProvider(),
        };
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

Below is the WebAPI configuration: (3)

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Filters.Add(new CustomAuthorizeAttribute());
        config.SuppressDefaultHostAuthentication();
        config.SuppressHostPrincipal();
        config.Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

Grant access token: (4)

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        await Task.FromResult(context.Validated());
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType); // using Bearer
        identity.AddClaim(new Claim("AccountId", Guid.NewGuid()));
        context.Validated(identity);
    }
}

Lastly here is the problem part: (5)

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // I tried to access the - ((ClaimsPrincipal)actionContext.RequestContext.Principal).Claims- but the Claims were empty, I need the "AccountId" which was set during GrantResourceOwnerCredentials() - look code at(4).
    }
}

How to post a SOAP message to web API end point

$
0
0

Hi,
I want to paste a SOAP XML based message to Web API which i have created in ASP.NET core project template.

Right now i am getting unsupported media type error when i post it with content-type as application/soap+xml.

I know that we should be sending SOAP message to WCF based service but our requirement is like this only. I should be able to consume SOAP message in web API.

Thanks,

Sudama

multiple actions were found that match the request

$
0
0

Goodday All

I am using web API and  am quite bit new in this. I  ve a trouble in a routing problem. I have a controller with following actions

public class IndividualController : ApiController   {       static readonly IIndividualRepository repository = new IndividualRepository();       [AllowAnonymous]       [ResponseType(typeof(Individual))]       [HttpGet]       public IEnumerable<Individual> GetIndividual(string Ind)//       {          return repository.Get(Ind);                                       }       [HttpGet]       public IEnumerable<Individual> GetTCC(string TCCNo)//       {           return repository.GetTCC(TCCNo);       }       [HttpGet]       public IEnumerable<Individual> GetAllIndividual()       {           return repository.GetAll();       }
}


public static class WebApiConfig  {      public static void Register(HttpConfiguration config)      {          // Web API configuration and services          // Web API routes          config.MapHttpAttributeRoutes();          //  config.Routes.MapHttpRoute(          //     name: "WithActionApi",          //     routeTemplate: "api/{controller}/{action}/{Ind}"          // );          //  config.Routes.MapHttpRoute(          //    name: "WithActionApi2",          //    routeTemplate: "api/{controller}/{action}/{TCCNo}"          //);             config.Routes.MapHttpRoute("DefaultApiWithId""Api/{controller}/{Ind}"new { Ind = RouteParameter.Optional }, new { Ind = @"\d+" });          config.Routes.MapHttpRoute("DefaultApiWithAction""Api/{controller}/{action}");          config.Routes.MapHttpRoute("DefaultApiGet""Api/{controller}"new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });          config.Routes.MapHttpRoute("DefaultApiGet1""Api/{controller}"new { action = "GetTCC" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });          config.Routes.MapHttpRoute("DefaultApiPost""Api/{controller}"new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });          // config.Formatters.XmlFormatter.          config.Formatters.JsonFormatter.          SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));      }  }


The problem occur when i added this action  GetTCC given this error Multiple actions were found that match request.
Please can any help to solve this problem. It actually works when GetTCC was not included in the controller with the commented section of the routes used.
But the point now is that i needed to have this two Method Get and GetTCC in a single controller.

Thank You

ASP.NET Web API Contract Versioning

$
0
0

We would like to achieve version based API using content negotiation in accept header.

We are able to achieve for controller & API methods with some inheritance and extending the default HTTP selector.

Controller inheritance is achieved using following sample code,

public abstract class AbstractBaseController : ApiController
{
// common methods for all api
}

public abstract class AbstractStudentController : AbstractBaseController
{
// common methods for Student related API'sample

public abstract Post(Student student);
public abstract Patch(Student student);
}

public class StudentV1Controller : AbstractStudentController
{
public override Post([FromBody]Student student) // student should be instance of StudentV1 from JSON
{
// To Do: Insert V1 Student
}

public override Patch([FromBody]Student student) // student should be instance of StudentV1 from JSON
{
// To Do: Patch V1 Student
}
}

public class StudentV2Controller : AbstractStudentController
{
// 
public override Post([FromBody]Student student) // student should be instance of StudentV2 from JSON
{
// To Do: Insert V2 Student
}
}

public abstract class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

public class StudentV1 : Student
{ 
}

public class StudentV2 : Student
{ 
public string Email { get; set; }
}

We have created above architecture to do less code with change in version, say if version 1 has 10 API methods and there is a change in one API method than it should be available in version 2 code without modifying other 9(they are inherited from version 1).

Now, the main problem we are facing is in contract versioning as we cannot instantiate an instance of an abstract student. When someone is posting JSON to API version 1 instance of StudentV1 should be passed in methods and same in version 2.

Is there any way to achieve this?

Thanks in advance!!

The system cannot find the file specified -

$
0
0

Path = ""\\\\ServicerName\\\\TFSLocation\\\\ProjectName\\\\Process.exe""

OR

Path = "C:\\TFS\\Development\\Processes\\ProjectName\\Main\\ProjectDescription\\bin\\Debug\\ProcessEngine.exe"

process.Start() gives me an error Win32Exception was caught  "The System cannot find the file specified".

Is there anything not right with the path above. If I have the exe on my C: drive Project folder.  How would I pass the file name.

Why doesn't it recognize the path that I specify.

            var process = new Process
            {
                StartInfo =
                {
                    FileName = fileName,
                    Arguments = Arguments,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                },
                EnableRaisingEvents = true
            };


            bool started = process.Start();


Thank you,

MVC App, Web Api, CORS, OWIN Headache!!!!

$
0
0

Hi all, I have been tasked with reworking the security model for my company web app. Basically it is an MVC/Knockout.js/jQuery front app in it;s own domain and calls out to a web api (also in it's own domain) and uses basic authentication to manage authroization.

Now, I need to replace this setup. I want to be able to use OWIN & CORS in the Web Api that can issue bearer access & refresh tokens. I have created a basic proof of concept project that almost works. The problem that I have hit at the moment is that when I make a post request from the UI using $.ajax in Chrome to a web api controller that is decorated with the [Authroize] attribute all I see is in the debugger tools is the following error

'Response for preflight has invalid HTTP status code 405'

The POST request headers are as follows

Request URL:http://local.api.com/api/Test/helloWorld
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:80
Response Headers

Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept,Authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET
Content-Length:76
Content-Type:application/json; charset=utf-8
Date:Thu, 15 Sep 2016 15:08:24 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET
Request Headers

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:local.api.com
Origin:http://local.web.com
Pragma:no-cache
Referer:http://local.web.com/

And the response returned is 

<Message>Authorization has been denied for this request.</Message>

I am really confused as to why these 'preflight' requests are being made and also why they cannot be authenticated. Can anybody suggest anything or direct me to more detailed tutorial that I could follow?

Generate computer status report

$
0
0

I have a network of devices all having windows operating system. My requirement is to get the information from all these devices and generate a report. I would want details like OS version, latest update installed. Latest scan date of windows Defender. The latest update check done for windows defender. How can this be achieved ?

I am planning to create a Web API service. Each device to have a shell script or an exe application which will send the data in JSON format to the webapi. Have anyone done this before or is there any microsoft tolls to do this.

Root element missing error while trying to deserialize xml extracted from SOAP message

$
0
0
Hi I have used below controller action method for posting soap message and then trying to deserialize it into object but getting error:

 at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlReader.MoveToContent()
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderFind.Read6_Find()


XML :

<Find xmlns="http://Mywebsite.com/Portal"><szPackageName>string</szPackageName><szSessionID>string</szSessionID><szUserName>string</szUserName><szPassword>string</szPassword><structSearchCriteria><Text>string</Text><Items><AcceleratorItem><Key>string</Key><Value>string</Value></AcceleratorItem><AcceleratorItem><Key>string</Key><Value>string</Value></AcceleratorItem></Items></structSearchCriteria><szAddressFormat>string</szAddressFormat><szRelatedTypes>string</szRelatedTypes><szAddressLevel>string</szAddressLevel><nOffset>int</nOffset><nMaxReturns>int</nMaxReturns></Find>
[HttpPost]
public Find Post([FromBody] XmlDocument xmlDocument)
{
    var soapBody = xmlDocument.GetElementsByTagName("soap12:Body")[0];
    string innerObject = soapBody.InnerXml;
    XmlSerializer deserializer = new XmlSerializer(typeof(Find));
    using (StringReader reader = new StringReader(innerObject))
    {
      return (Find)deserializer.Deserialize(reader);
    }
}
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace My.Adapter.WebApi
{
    [Serializable]
    [XmlRoot(ElementName = "AcceleratorItem", Namespace = "http://Mywebsite.com/Portal")]
    public class AcceleratorItem
    {
        [XmlElement(ElementName = "Key", Namespace = "http://Mywebsite.com/Portal")]
        public string Key { get; set; }
        [XmlElement(ElementName = "Value", Namespace = "http://Mywebsite.com/Portal")]
        public string Value { get; set; }
    }

    [Serializable]
    [XmlRoot(ElementName = "Find", Namespace = "http://Mywebsite.com/Portal")]
    public class Find
    {
        [XmlElement(ElementName = "nMaxReturns", Namespace = "http://Mywebsite.com/Portal")]
        public string NMaxReturns { get; set; }
        [XmlElement(ElementName = "nOffset", Namespace = "http://Mywebsite.com/Portal")]
        public string NOffset { get; set; }
        [XmlElement(ElementName = "structSearchCriteria", Namespace = "http://Mywebsite.com/Portal")]
        public StructSearchCriteria StructSearchCriteria { get; set; }
        [XmlElement(ElementName = "szAddressFormat", Namespace = "http://Mywebsite.com/Portal")]
        public string SzAddressFormat { get; set; }
        [XmlElement(ElementName = "szAddressLevel", Namespace = "http://Mywebsite.com/Portal")]
        public string SzAddressLevel { get; set; }
        [XmlElement(ElementName = "szPackageName", Namespace = "http://Mywebsite.com/Portal")]
        public string SzPackageName { get; set; }
        [XmlElement(ElementName = "szPassword", Namespace = "http://Mywebsite.com/Portal")]
        public string SzPassword { get; set; }
        [XmlElement(ElementName = "szRelatedTypes", Namespace = "http://Mywebsite.com/Portal")]
        public string SzRelatedTypes { get; set; }
        [XmlElement(ElementName = "szSessionID", Namespace = "http://Mywebsite.com/Portal")]
        public string SzSessionID { get; set; }
        [XmlElement(ElementName = "szUserName", Namespace = "http://Mywebsite.com/Portal")]
        public string SzUserName { get; set; }
        [XmlAttribute(AttributeName = "xmlns")]
        public string Xmlns { get; set; }
    }

    [Serializable]
    [XmlRoot(ElementName = "Items", Namespace = "http://Mywebsite.com/Portal")]
    public class Items
    {
        [XmlElement(ElementName = "AcceleratorItem", Namespace = "http://Mywebsite.com/Portal")]
        public List<AcceleratorItem> AcceleratorItem { get; set; }
    }

    [Serializable]
    [XmlRoot(ElementName = "structSearchCriteria", Namespace = "http://Mywebsite.com/Portal")]
    public class StructSearchCriteria
    {
        [XmlElement(ElementName = "Items", Namespace = "http://Mywebsite.com/Portal")]
        public Items Items { get; set; }
        [XmlElement(ElementName = "Text", Namespace = "http://Mywebsite.com/Portal")]
        public string Text { get; set; }
    }

}

Error retrieving token ASP.NET Web API template

$
0
0

I’m working with a project that has been created as a ASP.Net Web Application with the ‘Web API’ template and ‘Individual User Accounts’ enabled as the authentication option. I have a console application that consumes the web api. But When I want to get the token it gives me an html string with 404 not found in stead of a json array. What am I doing wrong?

This is mij console app code:

using ConsoleApplication1.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
{
    const string userName = "user@user.com";
    const string password = "Password01!";
    const string apiBaseUri = "http://localhost/WebAPITest";
    const string apiGetPeoplePath = "/api/people";

    static void Main(string[] args)
    {
        //Get the token
        var token = GetAPIToken(userName, password, apiBaseUri).Result;
        Console.WriteLine("Token: {0}", token);

        //Make the call
        var response = GetRequest(token, apiBaseUri, apiGetPeoplePath).Result;
        Console.WriteLine("response: {0}", response);

        //wait for key press to exit
        Console.ReadKey();
    }

    private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
    {
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //setup login data
            var formContent = new FormUrlEncodedContent(new[]
            {
 new KeyValuePair<string, string>("grant_type", "password"),
 new KeyValuePair<string, string>("username", userName),
 new KeyValuePair<string, string>("password", password),
 });

            //send request
            HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);

            //get access token from response body
            var responseJson = await responseMessage.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseJson);
            return jObject.GetValue("access_token").ToString();
        }
    }

    static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
    {
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            //make request
            HttpResponseMessage response = await client.GetAsync(requestPath);
            var responseString = await response.Content.ReadAsStringAsync();
            return responseString;
        }
    }
}

}



Am I missing something? 

odata web api using EF

$
0
0

Hello,

I am pretty new to web api, EF and odata.  We are using oracle and want to use RAW sql to build out a model but allow for the odata querying options without having to translate and dynamically build the sql.   

A little additional information.  I have some models referencing views and tables currently built via the EF wizard and when we pass it odata parameters it works without issue building out the SQL needed for $filter, $skip, $top, etc.  I want this same functionality but using raw sql as a base for the query that needs to occur.  I don't know how to allow for this functionality using the code sample below without intercepting the request and attempting to translate $filter, $skip, etc  somehow.  I would guess there is a better way?

This is what I have so far which can query the dbase and return the result but when i send in $filter, $skip, etc for example these do not apply.   One thing, this query is simply a test to see how we would make this work.  The query we would end up using is much more complex.

 private static ODataValidationSettings _validationSettings = new ODataValidationSettings();

        //public IHttpActionResult GetName()
        //{ }

        // GET: odata/ShareData
        [ODataRoute("Orders")]
        [EnableQuery(PageSize = 50)]
        public IHttpActionResult GetOrders(ODataQueryOptions<Orders> queryOptions)
        {
            // validate the query.
            try
            {
                queryOptions.Validate(_validationSettings);
            }
            catch (ODataException ex)
            {
                return BadRequest(ex.Message);
            }
            try
            {
                string connectionString = ConfigurationManager.ConnectionStrings["DNATestConnectionString"].ConnectionString;
                var items = GetDataItems(connectionString);
                return Ok<IEnumerable<Orders>>(items);
            }
            catch (Exception ex)
            {
                return StatusCode(HttpStatusCode.InternalServerError);
            }
        }

        

        #region Load Data Methods
        private static List<Orders> GetDataItems(string connectionString)
        {
            List<Orders> items = new List<Orders>();

            using (OracleConnection con = new OracleConnection(connectionString))
            {
                con.Open();

                using (OracleCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "select po_header_id, segment1, vendor_id, vendor_site_id  from po_headers_all where vendor_id=4993";
                    using (OracleDataReader rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                            items.Add(ToOrders(rdr));
                    }
                }
            }

            return items;
        }

        private static Orders ToOrders(OracleDataReader rdr)
        {
            Orders data = new Orders();

            data.VENDOR_ID = ToInt32(rdr, "VENDOR_ID");
            data.VENDOR_SITE_ID = ToInt32(rdr, "VENDOR_SITE_ID");
            data.PO_HEADER_ID = ToInt32(rdr, "PO_HEADER_ID");
            data.SEGMENT1 = Convert.ToString(rdr["SEGMENT1"]);

            return data;
        }

        private static int ToInt32(OracleDataReader rdr, string name)
        {
            int index = rdr.GetOrdinal(name);
            return rdr.IsDBNull(index) ? 0 : Convert.ToInt32(rdr[index]);
        }
        #endregion

Any help would be appreciated.  

Thanks.


Deployment Question

$
0
0

I have just created a Web API project. We have an existing website, and I would like to deplore the API tohttp://[domain]/API.

Do I create a new website in IIS and configure it to point to the above url?

My Web API is a separate project from our web project, although they do share many projects.

Thanks for any guidance as IIS binding are not my usual cup of tea.

How to use asp.net winapi with angular js?

$
0
0

Should I use SPA pattern? Or just simple web api page in asp.net mvc project? I do not need interaction with db. So I want to know in what folders I should put angular js files - in Content or Scripts? Or I need write it directly in view page? Do content type of $http.get request means? What port of localhost to use?  

How to create invioce in Web Api 2 and angular JS using Visual Studio 2013

$
0
0

Hi,

I am developing a web application using Web API 2 and AngularJS in visual Studio 2013. Now I facing a problem regarding Invoice Printing. I have googled and didn't get solution.

I liked to provide user to design their own Invoice template and that invoice will be printed with data when item will be sold.

In worst case, If i use Crystal Report how can i print Invoice in web api 2 and angular js.

Please help me.

Bye-

With Regards,

Sadequzzaman Monoj

Bangladesh

Call Executable file through wcf service hosting in iis 8. windows server 2012

$
0
0

Hi all,

I really need your help.

I have an executable file which is call another executable file. 

It means, I have 2 files needed to run.

I tried to create wcf service to call this executable file.

it's working fine in my localhost.

After I hosting them in iis 8. windows server 2012. No file displayed in my desktop.

But both of my executable files registered in task manager.

I already enable iis admin, www publishing service as allow service to interact with desktop. and also gave full access for user.

Are there another option to solve my problem?

your help is very useful for me.

Thank you

We migrated from Self-hosted to OWIN, then FATAL error System.IndexOutOfRangeException

$
0
0

Hi,

We had Self-hosted Web API with log4net logging handler. Then we migrated to OWIN and add one LoggingMiddleware wiht log4net and deploy to PROD

One hour API was working ok, but after we got FATAL error

[Logentries Log Appender] FATAL Topshelf.Runtime.Windows.WindowsServiceHost The service threw an unhandled exception System.IndexOutOfRangeException: Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.

at System.Buffer.InternalBlockCopy(Array src, Int32 srcOffsetBytes, Array dst, Int32 dstOffsetBytes, Int32 byteCount)
at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.IO.TextWriter.SyncTextWriter.Write(Char[] buffer, Int32 index, Int32 count)
at Microsoft.Owin.Hosting.Tracing.DualWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.IO.TextWriter.WriteLine(String value)
at System.Diagnostics.TextWriterTraceListener.WriteLine(String message)
at System.Diagnostics.TraceInternal.WriteLine(String message)
at LogentriesCore.Net.AsyncLogger.WriteDebugMessages(String message)
at LogentriesCore.Net.AsyncLogger.Run()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

INFO XXXXXService ClientAPI TcpConnection closed:

Received bytes: 539304, Sent bytes: 127013
Send calls: 491, callbacks: 491
Receive calls: 549, callbacks: 549
Close reason: [Success] Socket closed

And then our API didn't response and every time we have error in log:

ERROR XXXX.WebApi.Host Exception thrown by subscription callback

Exception:

System.AggregateException: One or more errors occurred. ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "YYYYYYYYYYYYY", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, ZZZZZZZZZZZZZZZZZ, is an interface and cannot be constructed. Are you missing a type mapping?

---> System.InvalidOperationException: The current type, XXXXXXXXXXXX, is an interface and cannot be constructed. Are you missing a type mapping?

at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
--- End of inner exception stack trace ---
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)

Viewing all 4850 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>