public string GetCurrentRequestUri()
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            string result = request.UriTemplateMatch.RequestUri.OriginalString;

            return(result);
        }
Exemple #2
0
        private DC_Message InsertDistributionLogNewEntryForMLDataAPI(DC_Distribution_MLDataRQ obj)
        {
            DC_Message msg = new DC_Message();

            try
            {
                using (ConsumerEntities context = new ConsumerEntities())
                {
                    IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;
                    string CallingAgent           = woc.Headers["CallingAgent"];
                    string CallingUser            = woc.Headers["CallingUser"];
                    DataLayer.DistributionLayerRefresh_Log objNew = new DistributionLayerRefresh_Log();
                    objNew.Id          = (obj.Logid ?? Guid.NewGuid());
                    objNew.Element     = obj.Element.Trim();
                    objNew.Type        = obj.Type.Trim();
                    objNew.Create_Date = DateTime.Now;
                    objNew.Create_User = CallingUser;
                    objNew.Status      = obj.Status;
                    context.DistributionLayerRefresh_Log.Add(objNew);
                    context.SaveChanges();
                    msg.StatusCode    = ReadOnlyMessage.StatusCode.Success;
                    msg.StatusMessage = "Sync has been scheduled successfully.";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(msg);
        }
Exemple #3
0
        public string RegisterProject(string xml)
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            LogControl    logControl          = new LogControl();
            CallApi       api = new CallApi();
            GenericAddDto dto = new GenericAddDto
            {
                Xml = xml
            };

            string user  = request.Headers["Usuario"];
            string senha = request.Headers["Senha"];

            string access_token = api.Login(user, senha).Result;

            if (String.IsNullOrEmpty(access_token))
            {
                logControl.Write("Usuário e senha não conferem");
                return(api.CAllApiMethod(dto, "/project", access_token));
            }
            else
            {
                logControl.Write("Usuário logado");
                return(api.CAllApiMethod(dto, "/project", access_token));
            }
        }
Exemple #4
0
        private string MapContentType(string project, string app, string format)
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            string contentType = request.ContentType;

            // if it's a known format then return it
            if (format != null && (format.ToLower() == "raw" || format.ToLower() == "dto" || format.ToLower() == "rdf" ||
                                   format.ToLower().Contains("xml") || format.ToLower().Contains("json")))
            {
                return(format);
            }

            if (string.IsNullOrEmpty(format))
            {
                format = "json";
            }

            if (contentType != null)
            {
                if (contentType.ToLower().Contains("application/xml"))
                {
                    format = "xml";
                }
                else if (contentType.ToLower().Contains("json"))
                {
                    format = "json";
                }
                else
                {
                    format = "raw";
                }
            }

            return(format);
        }
Exemple #5
0
        private string GetCameraImage(string url, string user, string password)
        {
            try
            {
                var client = new WebClient();
                client.UseDefaultCredentials = true;
                client.Credentials           = new NetworkCredential(user, password);
                var bytes = client.DownloadData(url);

                if (bytes.Length > 0)
                {
                    string fullpath           = System.Web.Hosting.HostingEnvironment.MapPath("~/imgs/") + string.Format("{0}.jpg", DateTime.Now.Ticks);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
                    System.IO.FileStream   fs = new System.IO.FileStream(fullpath, System.IO.FileMode.Create);
                    ms.WriteTo(fs);
                    ms.Close();
                    fs.Close();
                    fs.Dispose();
                    IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
                    return(_domainName + fullpath.Replace(System.Web.Hosting.HostingEnvironment.MapPath("~/imgs/"), "/imgs/").Replace(@"\", "/"));
                }

                return("");
            }
            catch (Exception ex)
            {
                _logger.Error("view-camera >> ERROR>" + ex.Message);
                return("");
            }
        }
Exemple #6
0
        protected OperationResult CheckAccessTokenHeader()
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headers = request.Headers;
            string authHeader = headers[HttpRequestHeader.Authorization];

            if (authHeader != null)
            {
                string[] ss = authHeader.Split(new char[] { ' ' });
                if (ss.Length > 1)
                {
                    string accessToken = ss[1];
                    IAccessTokenBusinessService accessTokenBs     = (IAccessTokenBusinessService)BusinessFactory.Create("Tools.OAuthServerManager.AccessToken");
                    OperationResult             accessTokenResult = accessTokenBs.CheckAccessToken(accessToken);
                    return(accessTokenResult);
                }
                else
                {
                    return(new OperationResult(false, null, "Invalid authorization header"));
                }
            }
            else
            {
                return(new OperationResult(false, null, "No authorization header"));
            }
        }
Exemple #7
0
            public virtual void DeserializeRequest(Message message, object [] parameters)
            {
                if (parameters == null)
                {
                    throw new ArgumentNullException("parameters");
                }
                CheckMessageVersion(message.Version);

                OperationContext.Current.Extensions.Add(new WebOperationContext(OperationContext.Current));

                IncomingWebRequestContext iwc = WebOperationContext.Current.IncomingRequest;

                Uri to = message.Headers.To;
                UriTemplateMatch match = UriTemplate.Match(Endpoint.Address.Uri, to);

                if (match == null)
                {
                    // not sure if it could happen
                    throw new SystemException(String.Format("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
                }
                iwc.UriTemplateMatch = match;

                MessageDescription md = GetMessageDescription(MessageDirection.Input);

                for (int i = 0; i < parameters.Length; i++)
                {
                    var    p    = md.Body.Parts [i];
                    string name = p.Name.ToUpperInvariant();
                    var    str  = match.BoundVariables [name];
                    parameters [i] = Converter.ConvertStringToValue(str, p.Type);
                }
            }
Exemple #8
0
        public static bool Authenticate(IncomingWebRequestContext context)
        {
            bool   Authenticated = false;
            string normalizedUrl;
            string normalizedRequestParameters;

            //context headers
            NameValueCollection pa = context.UriTemplateMatch.QueryParameters;

            if (pa != null && pa["oauth_consumer_key"] != null)
            {
                string    uri            = context.UriTemplateMatch.RequestUri.OriginalString.Replace(context.UriTemplateMatch.RequestUri.Query, "");
                string    consumerSecret = "MapSvc";
                OAuthBase oauth          = new OAuthBase();
                string    hash           = oauth.GenerateSignature(
                    new Uri(uri),
                    pa["oauth_consumer_key"],
                    consumerSecret,
                    null,             //token
                    null,             //token secret
                    "GET",
                    pa["oauth_timestamp"],
                    pa["oauth_nonce"],
                    out normalizedUrl,
                    out normalizedRequestParameters
                    );

                Authenticated = pa["oauth_signature"] == hash;
            }

            return(Authenticated);
        }
Exemple #9
0
        public HttpResponseMessage DeleteMovie(string deletById)
        {
            try
            {
                IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;
                string userPass = woc.Headers["userPass"];
                userPass = Encoding.UTF8.GetString(Convert.FromBase64String(userPass));

                string userID = usersRepository.ReturnUserIdByImdbPass(userPass);
                int    i      = moviesExtendRepository.DeleteMovie(deletById, userID);

                if (i > 0)
                {
                    HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.NoContent)
                    {
                    };
                    return(hrm);
                }
                HttpResponseMessage hr = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                };
                return(hr);
            }
            catch (Exception ex)
            {
                Errors errors          = ErrorsHelper.GetErrors(ex);
                HttpResponseMessage hr = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(errors.ToString())
                };
                return(hr);
            }
        }
 public void Save(string appName, Stream fileContent)
 {
     try
     {
         if (WebOperationContext.Current == null)
         {
             throw new InvalidOperationException("WebOperationContext is null.");
         }
         m_Request  = WebOperationContext.Current.IncomingRequest;
         m_Response = WebOperationContext.Current.OutgoingResponse;
         var file = CreateFileResource(fileContent, appName);
         if (!FileIsValid(file))
         {
             throw new WebFaultException(HttpStatusCode.BadRequest);
         }
         SaveFile(file);
         SetStatusAsCreated(file);
     }
     catch (Exception ex)
     {
         if (ex.GetType() == typeof(WebFaultException))
         {
             throw;
         }
         if (ex.GetType().IsGenericType&& ex.GetType().GetGenericTypeDefinition() == typeof(WebFaultException <>))
         {
             throw;
         }
         throw new WebFaultException <string>("An unexpected error occurred.", HttpStatusCode.InternalServerError);
     }
 }
        public Stream GET()
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;

            FormatServerResponse.AsyncDisplayMessage("GET request served to User agent " + request.UserAgent);

            string output =
                "<HTML>" +
                "<HEAD>" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />" +
                "<TITLE>" +
                "AS2 EDI Trading Partner Simulator" +
                "</TITLE>" +
                "</HEAD>" +
                "<BODY>" +

                "<H1>AS2 EDI Trading Partner Simulator</H1>" +
                "<P>" +
                "This tool simulates TP commuincation over AS2 Protocol and generates Sync and Async MDNs as response." +
                "</P> " +
                "<H3>Copyright © 2012 Intel Corporation. All rights reserved</H3>" +
                "<H4>Internal Use Only - Do Not Distribute</H4>" +
                "</BODY>" +
                "</HTML>";

            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(output));
            OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;

            response.ContentType = "text/html";
            return(stream);
        }
Exemple #12
0
        /// <summary>
        /// Resolves the <see cref="DataRequest" /> type based on the specified <see cref="IncomingWebRequestContext" />.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static DataRequest ResolveRequest(IncomingWebRequestContext request)
        {
            // Determine http verb - handle verb tunneling on post requests
            string method = (string.Equals(request.Method, "post", StringComparison.InvariantCultureIgnoreCase) &&
                             request.Headers.AllKeys.Contains("X-HTTP-Method")
                ? request.Headers["X-HTTP-Method"]
                : request.Method).ToLower();

            switch (method)
            {
            case "post":
                return(new DataCreateRequest <Entity>());

            case "merge":
            case "put":
                return(new DataUpdateRequest <Entity>());

            case "delete":
                return(new DataDeleteRequest <Entity>());

            case "get":
                return(new DataGetRequest <Entity>());

            default:
                return(null);
            }
        }
        private static Request CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody)
        {
            var address =
                ((RemoteEndpointMessageProperty)
                 OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]);

            var relativeUri = GetUrlAndPathComponents(webRequest.UriTemplateMatch.BaseUri).MakeRelativeUri(GetUrlAndPathComponents(webRequest.UriTemplateMatch.RequestUri));

            var expectedRequestLength =
                GetExpectedRequestLength(webRequest.Headers.ToDictionary());

            var nancyUrl = new Url {
                BasePath = webRequest.UriTemplateMatch.BaseUri.AbsolutePath,
                Scheme   = webRequest.UriTemplateMatch.RequestUri.Scheme,
                HostName = webRequest.UriTemplateMatch.BaseUri.Host,
                Port     = webRequest.UriTemplateMatch.RequestUri.IsDefaultPort ? null : (int?)webRequest.UriTemplateMatch.RequestUri.Port,
                Path     = string.Concat("/", relativeUri),
                Query    = webRequest.UriTemplateMatch.RequestUri.Query
            };

            return(new Request(
                       webRequest.Method,
                       nancyUrl,
                       RequestStream.FromStream(requestBody, expectedRequestLength, false),
                       webRequest.Headers.ToDictionary(),
                       address.Address));
        }
Exemple #14
0
        private bool IfMatch()
        {
            try
            {
                IncomingWebRequestContext context = WebOperationContext.Current.IncomingRequest;

                if (HasIfNonMatch(context) == false)
                {
                    return(false);
                }

                var etag = long.Parse(context.Headers["If-None-Match"]);

                DateTime etagTime = new DateTime(etag, DateTimeKind.Utc);
                if (DateTime.UtcNow > etagTime)
                {
                    return(false);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        private static HttpRequestMessage MakeHttpRequestMessageFrom(IncomingWebRequestContext oreq, Stream body, bool bufferBody)
        {
            var nreq = new HttpRequestMessage(new HttpMethod(oreq.Method), oreq.UriTemplateMatch.RequestUri);

            foreach (var name in oreq.Headers.AllKeys.Where(name => !_httpContentHeaders.Contains(name)))
            {
                nreq.Headers.TryAddWithoutValidation(name, oreq.Headers.Get(name));
            }
            if (body != null)
            {
                if (bufferBody)
                {
                    var ms = new MemoryStream();
                    body.CopyTo(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    nreq.Content = new StreamContent(ms);
                }
                else
                {
                    nreq.Content = new StreamContent(body);
                }

                foreach (var name in oreq.Headers.AllKeys.Where(name => _httpContentHeaders.Contains(name)))
                {
                    nreq.Content.Headers.TryAddWithoutValidation(name, oreq.Headers.Get(name));
                }
            }
            return(nreq);
        }
        private bool AuthenticateUser(IncomingWebRequestContext request)
        {
            bool authenticated = false;

            int hkeyNo = 0;

            WebHeaderCollection headers = request.Headers;

            foreach (string hkey in headers.AllKeys)
            {
                if (hkey.ToUpper().StartsWith("FACILITYID"))
                {
                    this.userID = headers.GetValues(hkeyNo)[0];
                }
                else if (hkey.ToUpper().EndsWith("USERKEY"))
                {
                    this.password = headers.GetValues(hkeyNo)[0];
                }
                hkeyNo++;
            }

            if (!string.IsNullOrEmpty(this.password))
            {
                ServiceInterface appSi = new ServiceInterface();
                authenticated = appSi.AuthenticateUser(userID, password);
            }

            return(authenticated);
        }
Exemple #17
0
    public static string USER_AGENT()
    {
        //Get FBID from header
        string objUSER_AGENT = "";

        try
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headers = request.Headers;
            objUSER_AGENT = request.Headers["User-Agent"];

            ////Console.WriteLine(request.Method + " " + request.UriTemplateMatch.RequestUri.AbsolutePath);
            //foreach (string headerName in headers.AllKeys)
            //{
            //    if (headerName == "User-Agent")
            //    {
            //        objUSER_AGENT = headers[headerName];
            //    }
            //    //Console.WriteLine(headerName + ": " + headers[headerName]);
            //}
        }
        catch (Exception)
        {
            objUSER_AGENT = "";
        }
        return(objUSER_AGENT);
    }
Exemple #18
0
        public DC_Message SyncGeographyData(DataContracts.DC_MongoDbSyncRQ RQ)
        {
            DC_Message _msg = new DC_Message();

            try
            {
                Guid LogId = new Guid();
                IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;
                string strURI = null;
                using (ConsumerEntities context = new ConsumerEntities())
                {
                    var iScheduledCount = context.DistributionLayerRefresh_Log.AsNoTracking()
                                          .Where(w => (w.Status.ToUpper().Trim() == "RUNNING" || w.Status.ToUpper().Trim() == "SCHEDULED") && w.Element.ToUpper().Trim() == RQ.Element.ToUpper().Trim() && w.Type.ToUpper().Trim() == RQ.Type.ToUpper().Trim()).Count();

                    if (iScheduledCount > 0)
                    {
                        _msg.StatusMessage = RQ.Element + " " + RQ.Type + " sync has already been scheduled.";
                        _msg.StatusCode    = ReadOnlyMessage.StatusCode.Information;
                        return(_msg);
                    }
                    else
                    {
                        LogId = Guid.NewGuid();
                        _msg  = InsertDistributionLogNewEntry(LogId, RQ.Element, RQ.Type, "Scheduled", woc.Headers["CallingUser"]);
                    }
                }
                using (DHSVCProxyAsync DHP = new DHSVCProxyAsync())
                {
                    string NewElement = RQ.Element.ToUpper().Trim();
                    string newType    = RQ.Type.ToUpper().Trim();
                    if (NewElement == "HOTEL" && newType == "MAPPING")
                    {
                        strURI = string.Format(System.Configuration.ConfigurationManager.AppSettings["Load_ProductMapping"], LogId.ToString(), (Guid.Empty).ToString());
                    }
                    else if (NewElement == "HOTEL" && newType == "MAPPINGLITE")
                    {
                        strURI = string.Format(System.Configuration.ConfigurationManager.AppSettings["Load_ProductMappingLite"], LogId.ToString(), (Guid.Empty).ToString());
                    }
                    else if (NewElement == "ZONE" && newType == "MASTER")
                    {
                        strURI = string.Format(System.Configuration.ConfigurationManager.AppSettings["Load_ZoneMaster"], LogId.ToString());
                    }
                    else if (NewElement == "ZONETYPE" && newType == "MASTER")
                    {
                        strURI = string.Format(System.Configuration.ConfigurationManager.AppSettings["Load_ZoneTypeMaster"], LogId.ToString());
                    }
                    if (strURI != null)
                    {
                        DHP.GetAsync(ProxyFor.SqlToMongo, strURI);
                    }
                }
                return(_msg);
            }
            catch (Exception ex)
            {
                return(new DC_Message {
                    StatusMessage = ex.Message, StatusCode = ReadOnlyMessage.StatusCode.Failed
                });
            }
        }
        public static string GetHeaderByName(string headerName)
        {
            IncomingWebRequestContext request          = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headerCollection = request.Headers;

            return(headerCollection[headerName]);
        }
Exemple #20
0
        public async Task <ElevationResponse> JsonRequest(string key, string locations, string source)
        {
            WebOperationContext       webOperationContext       = WebOperationContext.Current;
            IncomingWebRequestContext incomingWebRequestContext = webOperationContext.IncomingRequest;
            string uri = incomingWebRequestContext.UriTemplateMatch.RequestUri.ToString();

            Console.WriteLine("{0}: Request (JsonRequest) to {1}", DateTime.Now, uri);
            logger.Info("Request (JsonRequest) to {0}", uri);

            var elevationResponse = new ElevationResponse();
            var requestHandler    = new RequestHandler();

            try
            {
                //Stopwatch s = Stopwatch.StartNew();
                elevationResponse = await requestHandler.HandleRequest(key, locations, source);

                //Console.WriteLine("Request took {0} ms", s.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                logger.Error(e);
                elevationResponse.status = e.Message;
            }

            return(elevationResponse);
        }
Exemple #21
0
        public Response Select(string dataObject)
        {
            IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;

            string   fileName = woc.Headers["PhysicalFileName"];
            Response response = new Response();
            Object   obj      = new Object();

            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            ServiceAccess        serviceAccess        = new ServiceAccess();
            DatabaseAccess       dbAccess             = new DatabaseAccess();

            obj         = dbAccess.deserializeToDomain(fileName, dataObject);
            response.ID = 200;
            List <Object> list = new List <Object>();

            switch (fileName)
            {
            case "Accounts":
                response.Data = javaScriptSerializer.Serialize(serviceAccess.Select <Account>(fileName, obj));
                break;

            default:
                response.Data = "No records found";
                response.ID   = 300;
                break;
            }
            return(response);
        }
        public LoginResponse GetLoginPost(string name)
        {
            LoginResponse res = new LoginResponse();

            // get IP Address
            String                        ipaddr    = RemoteEndpointMessageProperty.Name;
            OperationContext              ctx       = OperationContext.Current;
            MessageProperties             mesgp     = ctx.IncomingMessageProperties;
            RemoteEndpointMessageProperty client_ep = mesgp[ipaddr] as RemoteEndpointMessageProperty;

            res.ipaddress = client_ep.Address;
            res.sessionid = ctx.SessionId;

            res.encoded_username = name;

            byte[] decoded_str = Convert.FromBase64String(name);
            res.username = Encoding.UTF8.GetString(decoded_str);

            //get header information
            IncomingWebRequestContext req     = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headers = req.Headers;

            res.listString = new List <String>();

            for (int i = 0; i < headers.Count; i++)
            {
                res.listString.Add(headers.Get(i).ToString());
            }
            return(res);
        }
        public LoginResponse GetLogin(string name)
        {
            LoginResponse res = new LoginResponse();

            // get IP Address
            String                        ipaddr    = RemoteEndpointMessageProperty.Name;
            OperationContext              ctx       = OperationContext.Current;
            MessageProperties             mesgp     = ctx.IncomingMessageProperties;
            RemoteEndpointMessageProperty client_ep = mesgp[ipaddr] as RemoteEndpointMessageProperty;

            res.ipaddress = client_ep.Address;
            res.sessionid = ctx.SessionId;

            //System.ServiceModel.DomainServices.Server.ApplicationServices
            //res.authtype = ServiceSecurityContext.Current.PrimaryIdentity.AuthenticationType;
            //res.username = ctx.ServiceSecurityContext.WindowsIdentity.Name;
            res.encoded_username = name;

            byte[] decoded_str = Convert.FromBase64String(name);
            res.username = Encoding.UTF8.GetString(decoded_str);

            this.saved_login_name = name;

            //get header information
            IncomingWebRequestContext req     = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headers = req.Headers;

            res.listString = new List <String>();

            for (int i = 0; i < headers.Count; i++)
            {
                res.listString.Add(headers.Get(i).ToString());
            }
            return(res);
        }
        public Response Insert(string dataObject)
        {
            IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;

            string fileName = woc.Headers["PhysicalFileName"];
            string key      = woc.Headers["SecretKey"];

            if (key != secretKey)
            {
                return(new Response {
                    Data = "Action Not authorized", ID = 500
                });
            }
            Response response = new Response();
            Object   obj      = new Object();

            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            iQueryProvider       queryProvider        = qFactory.GetQueryProvider("mssql");
            DatabaseAccess       dbAccess             = new DatabaseAccess();

            obj           = dbAccess.DeserializeToDomain(fileName, dataObject);
            response.Data = javaScriptSerializer.Serialize(queryProvider.Insert(fileName, obj));

            Logger("INSERT " + fileName + " - " + response.Data);
            return(response);
        }
Exemple #25
0
        public async Task <HttpResponseMessage> GetImdbByWord(string getByWord)
        {
            try
            {
                IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;
                string userPass = woc.Headers["userPass"];
                userPass = Encoding.UTF8.GetString(Convert.FromBase64String(userPass));

                string userID = userRepository.ReturnUserIdByImdbPass(userPass);

                HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(await imdbRepository.GetImdbByWord(userPass, getByWord, userID)))
                };
                return(hrm);
            }
            catch (Exception ex)
            {
                Errors errors           = ErrorsHelper.GetErrors(ex);
                HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(errors.ToString())
                };
                return(hrm);
            }
        }
        public static bool UseXmlFormat(IncomingWebRequestContext req)
        {
            string url = "";

            if (url.ToLower().Contains("/xml/"))
            {
                return(true);
            }

            if (!String.IsNullOrEmpty(req.Accept))
            {
                if (req.Accept.Contains("text/xml") || req.Accept.Contains("application/xml"))
                {
                    return(true);
                }
            }

            if (!String.IsNullOrEmpty(req.ContentType))
            {
                if (req.ContentType.Contains("text/xml") || req.ContentType.Contains("application/xml"))
                {
                    return(true);
                }
            }

            return(false);
        }
        public string GetSecurityTokenIdFromHeader()
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headers = request.Headers;

            return(headers["securitytokenid"]);
        }
Exemple #28
0
        public KlocModel.CommonReturnType GetAllFunds(string userid)
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
            WebHeaderCollection       headers = request.Headers;

            DataSet          dtdata = null;
            CommonReturnType cmd    = new CommonReturnType();

            try
            {
                string      xmldata = "";
                NexPurchase obj     = new NexPurchase();
                obj.UserID = userid;
                xmldata    = BllCommonUtility.SerializeToXml(obj);
                using (KlocDalServiceClient dalObjecet = new KlocDalServiceClient())
                {
                    dtdata     = dalObjecet.GetAllFunds(xmldata);
                    cmd.Status = true;
                }
            }
            catch (Exception ex)
            {
                Util.WriteLog(ex.Source, ex.Message, ex.StackTrace);
                defMsg     = "An Error Accoured While Data Processing!";
                cmd.Status = false;
                dtdata     = Util.GetErrorcode("1", defMsg);
            }
            finally
            {
                cmd.JSONData = cmd.Serialize_JsonData(dtdata);
                cmd.ds       = dtdata;
            }
            return(cmd);
        }
Exemple #29
0
        private static SearchResultPager GetSearchResultPager(IncomingWebRequestContext context, int pageSize, string token)
        {
            SearchResultPager p;

            if (token == null)
            {
                string               filter     = WebResponseHelper.GetFilterText(context);
                CultureInfo          locale     = WebResponseHelper.GetLocale();
                IEnumerable <string> attributes = WebResponseHelper.GetAttributes(context);

                if (attributes != null)
                {
                    p = Global.Client.GetResourcesPaged(filter, pageSize, attributes, locale);
                }
                else
                {
                    p = Global.Client.GetResourcesPaged(filter, pageSize, locale);
                }
            }
            else
            {
                p = (SearchResultPager)ResourceManagementWebServicev2.searchCache.Remove(ResourceManagementWebServicev2.BuildCacheKey(token));

                if (p == null)
                {
                    throw new ArgumentException("Invalid token");
                }
            }
            return(p);
        }
            public virtual void DeserializeRequest(Message message, object [] parameters)
            {
                if (parameters == null)
                {
                    throw new ArgumentNullException("parameters");
                }
                CheckMessageVersion(message.Version);

                IncomingWebRequestContext iwc = null;

                if (OperationContext.Current != null)
                {
                    OperationContext.Current.Extensions.Add(new WebOperationContext(OperationContext.Current));
                    iwc = WebOperationContext.Current.IncomingRequest;
                }

                Uri to = message.Headers.To;
                UriTemplateMatch match = UriTemplate.Match(Endpoint.Address.Uri, to);

                if (match == null)
                {
                    // not sure if it could happen
                    throw new SystemException(String.Format("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
                }
                if (iwc != null)
                {
                    iwc.UriTemplateMatch = match;
                }


                var wp  = message.Properties [WebBodyFormatMessageProperty.Name] as WebBodyFormatMessageProperty;
                var fmt = wp != null ? wp.Format : WebContentFormat.Xml;

                if (fmt == WebContentFormat.Raw)
                {
                    var rmsg = (RawMessage)message;
                    parameters [0] = rmsg.Stream;
                    return;
                }


                MessageDescription md = GetMessageDescription(MessageDirection.Input);

                for (int i = 0; i < parameters.Length; i++)
                {
                    var    p    = md.Body.Parts [i];
                    string name = p.Name.ToUpperInvariant();
                    var    str  = match.BoundVariables [name];
                    if (str != null)
                    {
                        parameters [i] = Converter.ConvertStringToValue(str, p.Type);
                    }
                    else
                    {
                        var serializer = GetSerializer(fmt, IsRequestBodyWrapped, p);
                        parameters [i] = DeserializeObject(serializer, message, md, IsRequestBodyWrapped, fmt);
                    }
                }
            }
		public IncomingWebRequestContextWrapper(IncomingWebRequestContext context)
		{
			this.context = context;
		}