private void configureResponse(ResponseFormat expectedFormat)
		{
			Request req;
			var url = new Url { Scheme = "http", Path = "/" };
			switch (expectedFormat)
			{
				case ResponseFormat.Html:
					req = new Request("GET", url, null, new Dictionary<string, IEnumerable<string>> { { "Accept", _acceptHtmlHeaders } },
									  null);
					break;
				case ResponseFormat.Json:
					req = new Request("GET", url, null, new Dictionary<string, IEnumerable<string>> { { "Accept", _acceptJsonHeaders } },
									  null);
					break;
				case ResponseFormat.Xml:
					req = new Request("GET", url, null, new Dictionary<string, IEnumerable<string>> { { "Accept", _acceptXmlHeaders } },
									  null);
					break;
				default:
					Assert.Fail("Invalid response format");
					return;
			}

			_euclidApi.Context = new NancyContext { Request = req };
			_euclidApi.Response = _formatter;
			A.CallTo(() => _formatter.Context).Returns(_euclidApi.Context);
		}
示例#2
0
        /// <summary>
        /// Get sentences
        /// </summary>
        /// <param name="wordCount">Number of sentences</param>
        /// <param name="allMeat">Meat only or meat mixed with miscellaneous ‘lorem ipsum’ filler.</param>
        /// <param name="startWithLorem">Start the first paragraph with ‘Bacon ipsum dolor...’.</param>
        /// <returns></returns>
        public static List<string> GetWords(int wordCount, ResponseFormat format, bool startWithLorem = false, bool allMeat = false)
        {
            var text = GetParagraphs(2, format, startWithLorem, allMeat);

            var chars = text.ToCharArray();
            List<char> nonWordChars = new List<char> { '"', '.', '?', ';', ':', ',', '\n', ' ', '\0' };
            List<string> words = new List<string>();
            StringBuilder currWord = new StringBuilder();

            foreach (char c in chars)
            {
                if (nonWordChars.Contains(c))
                {
                    words.Add(currWord.ToString());

                    if (words.Count >= wordCount)
                        break;
                    else
                        currWord = new StringBuilder();
                }
                else
                {
                    currWord.Append(c);
                }

            }
            return words;
        }
示例#3
0
		public static Response CreateResponse(this Exception e, ResponseFormat format, IResponseFormatter formatter)
		{
			// dumb ugliness b/c MSFT's xml serializer can't handle anonymous objects
			var exception = new FormattedException
			                	{
			                		name = e.GetType().Name,
			                		message = e.Message,
			                		callStack = e.StackTrace
			                	};

			Response r;
			switch (format)
			{
				case ResponseFormat.Json:
					r = formatter.AsJson(exception, HttpStatusCode.InternalServerError);
					break;
				case ResponseFormat.Xml:
					r = formatter.AsXml(exception);
					break;
				default:
					r = null;
					break;
			}

			if (r != null)
			{
				r.StatusCode = HttpStatusCode.InternalServerError;
			}

			return r;
		}
示例#4
0
        /// <summary>
        /// Perform a query and return the result as a string in either JSON (Default) or XML format
        /// </summary>
        /// <param name="searchTerm">The term to be queried for</param>
        /// <param name="applicationName">The application name identifying the requesting entity</param>
        /// <param name="apiClient">The class implementation of the IApiClient interface which fetches and returns the response body for a given URI</param>
        /// <param name="responseFormat">The format the response should be structured as. Either JSON (Default) or XML</param>
        /// <returns>The result as a string formatted as either JSON (Default) or XML</returns>
        public string TextQuery(string searchTerm, string applicationName, ResponseFormat responseFormat)
        {
            if (string.IsNullOrEmpty(searchTerm)) throw new ArgumentNullException("searchTerm");
            if (string.IsNullOrEmpty(applicationName)) throw new ArgumentNullException("applicationName");

            
            return ApiClient.Load(BuildRequestUri(searchTerm, applicationName, responseFormat));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SitecoreActionQuery" /> class.
        /// </summary>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="format">The format.</param>
        public SitecoreActionQuery(string actionName, ResponseFormat format = ResponseFormat.Xml)
        {
            ActionName = actionName;
            ResponseFormat = format;

            QueryType = SitecoreQueryType.Read;

            ErrorMessage = "You must provide an action name for an action query";
        }
        /// <summary>
        /// 取得函数的模版
        /// </summary>
        /// <param name="method"></param>
        /// <param name="format"></param>
        /// <param name="httpMethod"></param>
        /// <returns></returns>
        private static string GetFunctionTemplete(MethodInfo method, ResponseFormat format,string httpMethod)
        {
            StringBuilder func = new StringBuilder(method.DeclaringType.Name);
            func.Append(".prototype." + method.Name);
            func.Append("=function");
            func.Append("(");
            foreach (ParameterInfo p in method.GetParameters())
            {
                func.Append(p.Name + ",");
            }

            func.Append("callback)");
            func.AppendLine("{");
            {
                func.Append("\tvar args = {");
                foreach (ParameterInfo p in method.GetParameters())
                {
                    func.Append(p.Name + ":" + p.Name + ",");
                }
                //func.AppendLine("ajax:'jquery1.4.2'};");
                func.AppendLine("};");
                switch (format)
                {
                    case ResponseFormat.Html:
                        //func.AppendLine("\tvar options={dataType:'html'};");
                        func.AppendFormat("\tvar options={{dataType:'html',type:'{0}'}};",httpMethod);
                        break;
                    case ResponseFormat.Xml:
                        //func.AppendLine("\tvar options={dataType:'xml'};");
                        func.AppendFormat("\tvar options={{dataType:'xml',type:'{0}'}};", httpMethod);
                        break;
                    case ResponseFormat.Json:
                        //func.AppendLine("\tvar options={dataType:'json'};");
                        func.AppendFormat("\t var options={{dataType:'json',type:'{0}'}};", httpMethod);
                        break;
                    case ResponseFormat.Script:
                        //func.AppendLine("\tvar options={dataType:'script'};");
                        func.AppendFormat("\tvar options={{dataType:'script',type:'{0}'}};",httpMethod);
                        break;
                    case ResponseFormat.Text:
                        //func.AppendLine("\tvar options={dataType:'text'};");
                        func.AppendFormat("\tvar options={{dataType:'text',type:'{0}'}};",httpMethod);
                        break;
                    default:
                        //func.AppendLine("\tvar options={dataType:'text'};");
                        //func.AppendFormat("\tvar options={{dataType:'text',type:'{0}'}};",httpMethod);
                        break;
                }
                func.AppendLine("\t$.extend(true,options,{},this.Options);");
                func.AppendFormat("\t$.DotNet.CallWebMethod(options,'{0}', args, callback);", method.Name);
                func.AppendLine();
            }
            func.AppendLine("}\t\t");
            return func.ToString();
        }
示例#7
0
        /// <summary>
        /// method for shortening a URL utilizing the Bitly API
        /// </summary>
        /// <param name="longURL">URL to shorten</param>
        /// <param name="login">Login for our account</param>
        /// <param name="key">our Bitly API Key</param>
        /// <param name="format">Thef format we wish to have returned to us</param>
        /// <returns></returns>
        public string ShortenUrl(string longURL, string login, string key, ResponseFormat format = ResponseFormat.XML)
        {
            //this will hold the shortened URL
            string output;          
 
            //build the full URL for shortening the URL
            string url = string.Format(shortenUrl + @"{0}&apiKey={1}&longUrl={2}&format={3}", 
                login, key, HttpUtility.UrlEncode(longURL), format.ToString().ToLower());
 
            //get the finaly shortened URL (this is an external method that you will see later
            return getFinalValue(url, out output);
        }
        public void Setup()
        {
        	mimes = new MimeTypes();
			mimes.RegisterBuiltinTypes();

            mocks = new MockRepository();
            bridge = mocks.DynamicMock<IControllerBridge>();
            format = new ResponseFormat(mimes);
            handlerInvoked = "";

            ResponseFormatInternal iformat = (ResponseFormatInternal)format;
            iformat.AddRenderer("xml", x => handlerInvoked = "xml");
            iformat.AddRenderer("html", x => handlerInvoked = "html");
        }
        public void Setup()
        {
            mocks = new MockRepository();
            bridge = mocks.DynamicMock<IControllerBridge>();
            format = new ResponseFormat();
            handlerInvoked = "";

            ResponseFormatInternal iformat = format;

			iformat.AddRenderer("xml", delegate(Responder responder)
			{
				handlerInvoked = "xml";
			});
			iformat.AddRenderer("html", delegate(Responder responder)
			{
        	                           	handlerInvoked = "html";
        	                           });

            mimes = new MimeType[] {
                new MimeType("text/html", "html"),
                new MimeType("application/xml", "xml")
            };
        }
示例#10
0
        public HttpResponseMessage GetPdf([FromUri] string name, [FromUri] DateTime?fromDate = null, [FromUri] DateTime?toDate = null)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            if (!String.IsNullOrEmpty(name))
            {
                switch (name)
                {
                case "leads":
                {
                    //responseData.data = _reportService.Get
                    var reportName = "PotentialCustomerReport_" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".pdf";
                    var pdfManager = new PdfManager(reportName);
                    var fileName   = pdfManager.GenerateLeadsReport().fileName;
                    var results    = _fileService.GetFile(fileName);
                    if (results.file != null)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        response.Content    = results.file;
                        response.Content.Headers.ContentType        = new MediaTypeHeaderValue(results.mimeType);
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = results.fileName
                        };
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.Gone;
                        ResponseFormat responseData = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.SOMETHING_WRONG;
                        var json = JsonConvert.SerializeObject(responseData);
                        response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }
                    break;
                }

                case "accounts":
                {
                    //responseData.data = _reportService.Get
                    var reportName = "CustomerReport_" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".pdf";
                    var pdfManager = new PdfManager(reportName);
                    var fileName   = pdfManager.GenerateAccountsReport().fileName;
                    var results    = _fileService.GetFile(fileName);
                    if (results.file != null)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        response.Content    = results.file;
                        response.Content.Headers.ContentType        = new MediaTypeHeaderValue(results.mimeType);
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = results.fileName
                        };
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.Gone;
                        ResponseFormat responseData = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.SOMETHING_WRONG;
                        var json = JsonConvert.SerializeObject(responseData);
                        response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }
                    break;
                }

                case "deals":
                {
                    var reportName = "DealsReport_" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".pdf";
                    var pdfManager = new PdfManager(reportName);
                    var fileName   = pdfManager.GenerateDealsReport(fromDate, toDate).fileName;
                    var results    = _fileService.GetFile(fileName);
                    if (results.file != null)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        response.Content    = results.file;
                        response.Content.Headers.ContentType        = new MediaTypeHeaderValue(results.mimeType);
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = results.fileName
                        };
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.Gone;
                        ResponseFormat responseData = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.SOMETHING_WRONG;
                        var json = JsonConvert.SerializeObject(responseData);
                        response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }
                    break;
                }

                case "revenue":
                {
                    var reportName = "RevenueReport_" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".pdf";
                    var pdfManager = new PdfManager(reportName);
                    var fileName   = pdfManager.GenerateRevenueReport(fromDate, toDate).fileName;
                    var results    = _fileService.GetFile(fileName);
                    if (results.file != null)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        response.Content    = results.file;
                        response.Content.Headers.ContentType        = new MediaTypeHeaderValue(results.mimeType);
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = results.fileName
                        };
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.Gone;
                        ResponseFormat responseData = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.SOMETHING_WRONG;
                        var json = JsonConvert.SerializeObject(responseData);
                        response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }
                    break;
                }

                case "campaigns":
                {
                    //responseData.data = _reportService.Get
                    var reportName = "CampaignReport_" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".pdf";
                    var pdfManager = new PdfManager(reportName);
                    var fileName   = pdfManager.GenerateCampaignsReport().fileName;
                    var results    = _fileService.GetFile(fileName);
                    if (results.file != null)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        response.Content    = results.file;
                        response.Content.Headers.ContentType        = new MediaTypeHeaderValue(results.mimeType);
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = results.fileName
                        };
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.Gone;
                        ResponseFormat responseData = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.SOMETHING_WRONG;
                        var json = JsonConvert.SerializeObject(responseData);
                        response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }
                    break;
                }

                default:
                    break;
                }
            }
            else
            {
                response.StatusCode = HttpStatusCode.BadRequest;
                ResponseFormat responseData = ResponseFormat.Fail;
                responseData.message = ErrorMessages.INVALID_BODY;
                var json = JsonConvert.SerializeObject(responseData);
                response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            }
            return(response);
        }
示例#11
0
        /// <summary>
        /// Gets the specified URI.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request">The request.</param>
        /// <param name="responseFormat">The response format.</param>
        /// <param name="scResponse">The sc response.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">scResponse</exception>
        public virtual T Get <T>(HttpWebRequest request, ResponseFormat responseFormat, T scResponse) where T : class, IBaseResponse
        {
            if (scResponse == null)
            {
                throw new ArgumentNullException("scResponse");
            }

            try
            {
                var sw = Stopwatch.StartNew();

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var stream = response.GetResponseStream();

                    sw.Stop();

                    if (stream != null)
                    {
                        var sReader = new StreamReader(stream);

                        try
                        {
                            switch (responseFormat)
                            {
                            case ResponseFormat.Json:
                                scResponse = DeserializeJsonResponse <T>(sReader.ReadToEnd());
                                break;

                            case ResponseFormat.Xml:
                                scResponse = DeserializeXmlResponse <T>(sReader.ReadToEnd());
                                break;
                            }

                            if (scResponse != null)
                            {
                                scResponse.Info = new SitecoreWebResponseInfo
                                {
                                    Uri          = request.RequestUri,
                                    ResponseTime = sw.Elapsed
                                };

                                scResponse.StatusDescription = response.StatusDescription;

                                Log.WriteInfo(string.Format("{0}: {1} - {2}", request.Method,
                                                            scResponse.Info.ResponseTime,
                                                            scResponse.Info.Uri.PathAndQuery));
                            }
                            else
                            {
                                Log.WriteWarn("Could not convert deserialized response to IBaseResponse");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteError("Error deserializing the web service response", ex);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                SetExceptionMetaData(ex, scResponse);

                if (ex.Response != null)
                {
                    var response = (HttpWebResponse)ex.Response;

                    if (scResponse != null)
                    {
                        scResponse.StatusCode        = response.StatusCode;
                        scResponse.StatusDescription = response.StatusDescription;
                    }
                }
                else
                {
                    if (scResponse != null)
                    {
                        scResponse.StatusCode = HttpStatusCode.InternalServerError;
                    }
                }

                Log.WriteError("Web exception encountered when accessing the web service", ex);
            }
            catch (Exception ex)
            {
                SetExceptionMetaData(ex, scResponse);

                if (scResponse != null)
                {
                    scResponse.StatusCode = HttpStatusCode.InternalServerError;
                }

                Log.WriteError("Error accessing the web service", ex);
            }

            return(scResponse);
        }
        public async Task <IActionResult> InsertObjectWithNoId([FromRoute] DatabaseRouteParameters routeParameters, [FromBody] string json, [FromQuery] ResponseFormat responseFormat = ResponseFormat.EntireObject)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string document = await _service.InsertAsync(routeParameters.DatabaseName, routeParameters.CollectionName, null, json);

            string id = GetObjectId(document);

            if (responseFormat == ResponseFormat.OnlyId)
            {
                document = GetInsertedJsonResult(new string[] { id }).ToString();
            }
            return(CreatedAtAction(nameof(GetObject), new { id = id, db = routeParameters.DatabaseName, collection = routeParameters.CollectionName }, document));
        }
示例#13
0
文件: API.cs 项目: JoNMii/Pokemon3D
 private static string ResponseFormatToString(ResponseFormat format)
 {
     return(format.ToString().ToLowerInvariant());
 }
示例#14
0
        public HttpResponseMessage Get([FromUri] int currentPage = 1, [FromUri] int pageSize = 0, [FromUri] string query = "", [FromUri] string sort = "")
        {
            var                  response              = new HttpResponseMessage();
            ResponseFormat       responseData          = new ResponseFormat();
            AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.LEAD_VIEW_LIST);

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId       = Convert.ToInt32(payload["id"]);
                    var isAuthorized = _authorizationService.Authorize(userId);
                    if (isAuthorized)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        responseData        = ResponseFormat.Success;
                        var sortQ = new List <string>();
                        sortQ = sort.Split(',').ToList();
                        var leads = _leadService.GetLeadList(query, pageSize, currentPage, sortQ);
                        responseData.data = leads;
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
示例#15
0
        /// <summary>
        /// Builds the url to request ipsum
        /// </summary>
        /// <param name="allMeat">Meat only or meat mixed with miscellaneous ‘lorem ipsum’ filler.</param>
        /// <param name="sentenceCount">Number of sentences (this overrides paragraphs)</param>
        /// <param name="paragraphCount">Number of paragraphs, defaults to 5.</param>
        /// <param name="loremStart">Start the first paragraph with ‘Bacon ipsum dolor...’.</param>
        /// <returns></returns>
        private static string GetApiURL(ResponseFormat format, bool allMeat, int sentenceCount = 0, int paragraphCount = 1, bool startWithLorem = true)
        {
            StringBuilder requestUrl = new StringBuilder();
            requestUrl.Append(BASE_BACON_API_URI);
            requestUrl.AppendFormat("?type={0}", allMeat ? "all-meat" : "meat-and-filler");

            if (sentenceCount > 0)
                requestUrl.AppendFormat("&sentences={0}", sentenceCount.ToString());
            else
                requestUrl.AppendFormat("&paras={0}", paragraphCount.ToString());

            if (!startWithLorem)
                requestUrl.Append("&start-with-lorem=0");

            requestUrl.AppendFormat("&format={0}", format.ToString());

            return requestUrl.ToString();
        }
示例#16
0
        /// <summary>
        /// List all snapshots for the supplied sessionID
        /// </summary>
        /// <param name="format"></param>
        /// <param name="sessionID"></param>
        /// <returns></returns>
        public static string ListSnapshots(ResponseFormat format, int sessionID)
        {
            string endpoint = String.Format(@"http://{0}/API/ListSnapshots.aspx", GetTwiddlaHost(HttpContext.Current.Request));

            APICaller caller = new APICaller(endpoint);
            caller.Add("username", TwiddlaUsername);
            caller.Add("password", TwiddlaPassword);
            caller.Add("format", format.ToString().ToLower());
            if (sessionID > 0)
            {
                caller.Add("sessionid", sessionID);
            }

            if (caller.Call())
            {
                return caller.Html;
            }

            throw caller.LastException;
        }
示例#17
0
        public IEnumerator PostRequest(string url, Dictionary <string, string> payload, ResponseFormat format,
                                       Action <Response> callback)
        {
            if (Settings.GameId == 0 || Settings.PrivateKey == null)
            {
                callback(new Response("Bad Credentials"));
                yield break;
            }

            float timeout = Time.time + Settings.Timeout;

            using (var request = UnityWebRequest.Post(url, payload)) {
                request.SendWebRequest();
                while (!request.isDone)
                {
                    if (Time.time > timeout)
                    {
                        request.Abort();
                        callback(new Response("Timeout for " + url));
                        yield break;
                    }
                    yield return(new WaitForEndOfFrame());
                }

                callback(new Response(request, format));
            }
        }
示例#18
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="config"></param>
 public PagingResult(PagingConfig config)
 {
     Format = config.Format;
 }
示例#19
0
        /// <summary>
        /// Annotates a document publicly available under a given URL and tags and/or categorizes any images inside.
        /// </summary>
        /// <param name="documentUrl">the publicly accessible URL from where the document will be downloaded</param>
        /// <param name="documentMimeType">the MIME type of the document which will be annotated</param>
        /// <param name="serializationFormat">the serialization format of the output</param>
        /// <returns>Аn {@link InputStream} from where the serialized output can be read</returns>
        public Stream annotateDocumentAsStream(Uri documentUrl, SupportedMimeType documentMimeType, ResponseFormat serializationFormat, bool imageTagging, bool imageCategorization)
        {
            ServiceRequest rq = new ServiceRequest(documentUrl, documentMimeType, imageTagging, imageCategorization);

            try
            {
                return(client.requestForStream("", "POST", rq, constructHeaders(serializationFormat)));
            }
            catch (HttpClientException e)
            {
                String msg = handleErrors(e);
                throw new S4ServiceClientException(msg == null ? e.Message : msg, e);
            }
        }
示例#20
0
        public HttpResponseMessage ViewSaleDashboard()
        {
            var                  response              = new HttpResponseMessage();
            ResponseFormat       responseData          = new ResponseFormat();
            AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.DEAL_VIEW_LIST);

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = payload["id"];

                    var isAuthorized = _authorizationService.Authorize(Convert.ToInt32(userId));
                    if (isAuthorized)
                    {
                        response.StatusCode = HttpStatusCode.OK;
                        responseData        = ResponseFormat.Success;
                        var deals = db.DEALs.ToList();

                        DashboardApiModel apiModel = new DashboardApiModel();
                        apiModel.stages = new List <DashboardApiModel.S>();

                        var qualified        = new DashboardApiModel.S();
                        var valueProposition = new DashboardApiModel.S();
                        var findKeyContacts  = new DashboardApiModel.S();
                        var sendProposal     = new DashboardApiModel.S();
                        var review           = new DashboardApiModel.S();
                        var negotiate        = new DashboardApiModel.S();
                        var won  = new DashboardApiModel.S();
                        var lost = new DashboardApiModel.S();


                        var qualifiedStage        = db.STAGEs.Find((int)EnumStage.QUALIFIED);
                        var valuePropositionStage = db.STAGEs.Find((int)EnumStage.VALUE_PROPOSITION);
                        var findKeyContactsStage  = db.STAGEs.Find((int)EnumStage.FIND_KEY_CONTACTS);
                        var sendProposalStage     = db.STAGEs.Find((int)EnumStage.SEND_PROPOSAL);
                        var reviewStage           = db.STAGEs.Find((int)EnumStage.REVIEW);
                        var negotiateStage        = db.STAGEs.Find((int)EnumStage.NEGOTIATE);
                        var wonStage  = db.STAGEs.Find((int)EnumStage.WON);
                        var lostStage = db.STAGEs.Find((int)EnumStage.LOST);
                        #region stages
                        //qualified
                        qualified.stageID     = qualifiedStage.ID;
                        qualified.stageName   = qualifiedStage.Name;
                        qualified.probability = qualifiedStage.Probability.Value;
                        //value proposition
                        valueProposition.stageID     = valuePropositionStage.ID;
                        valueProposition.stageName   = valuePropositionStage.Name;
                        valueProposition.probability = valuePropositionStage.Probability.Value;
                        //find key contacts
                        findKeyContacts.stageID     = findKeyContactsStage.ID;
                        findKeyContacts.stageName   = findKeyContactsStage.Name;
                        findKeyContacts.probability = findKeyContactsStage.Probability.Value;
                        //send proposal
                        sendProposal.stageID     = sendProposalStage.ID;
                        sendProposal.stageName   = sendProposalStage.Name;
                        sendProposal.probability = sendProposalStage.Probability.Value;
                        //review
                        review.stageID     = reviewStage.ID;
                        review.stageName   = reviewStage.Name;
                        review.probability = reviewStage.Probability.Value;
                        //negotiate
                        negotiate.stageID     = negotiateStage.ID;
                        negotiate.stageName   = negotiateStage.Name;
                        negotiate.probability = negotiateStage.Probability.Value;
                        //won
                        won.stageID     = wonStage.ID;
                        won.stageName   = wonStage.Name;
                        won.probability = wonStage.Probability.Value;
                        //lost
                        lost.stageID     = lostStage.ID;
                        lost.stageName   = lostStage.Name;
                        lost.probability = lostStage.Probability.Value;
                        #endregion

                        foreach (var deal in deals)
                        {
                            var d = new DashboardApiModel.D();
                            d.dealID          = deal.ID;
                            d.dealName        = deal.Name;
                            d.ownerID         = deal.Owner.ID;
                            d.ownerUsername   = deal.Owner.Username;
                            d.accountID       = deal.ACCOUNT != null ? deal.ACCOUNT.ID : 0;
                            d.accountName     = deal.ACCOUNT != null ? deal.ACCOUNT.Name : "";
                            d.expectedRevenue = deal.ExpectedRevenue.HasValue ? deal.ExpectedRevenue.Value : 0;
                            d.priority        = deal.PRIORITY != null ? deal.PRIORITY.Name : "";

                            foreach (var tag in deal.TAG_ITEM)
                            {
                                var t = new DashboardApiModel.T();
                                t.tagID   = tag.TAG.ID;
                                t.tagName = tag.TAG.Name;
                                d.tags.Add(t);
                            }
                            var history = deal.STAGE_HISTORY.OrderByDescending(sh => sh.ModifiedAt).Take(1);
                            if (history.Count() != 0)
                            {
                                var stage = history.Select(c => c.STAGE_ID).First();
                                if (stage == (int)EnumStage.QUALIFIED)
                                {
                                    qualified.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.VALUE_PROPOSITION)
                                {
                                    valueProposition.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.FIND_KEY_CONTACTS)
                                {
                                    findKeyContacts.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.SEND_PROPOSAL)
                                {
                                    sendProposal.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.REVIEW)
                                {
                                    review.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.NEGOTIATE)
                                {
                                    negotiate.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.WON)
                                {
                                    won.deals.Add(d);
                                }
                                if (stage == (int)EnumStage.LOST)
                                {
                                    lost.deals.Add(d);
                                }
                            }
                        }

                        apiModel.stages.AddRange(new List <DashboardApiModel.S>()
                        {
                            qualified, valueProposition, findKeyContacts, sendProposal, review, negotiate, won, lost
                        });
                        responseData.data = apiModel;
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
示例#21
0
        public HttpResponseMessage ConvertLead([FromUri] int id)
        {
            var            response     = new HttpResponseMessage();
            ResponseFormat responseData = new ResponseFormat();
            //AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.LEAD_MODIFY);
            //read jwt

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = Convert.ToInt32(payload["id"]);
                    var owner  = _leadService.FindOwnerId(id);
                    if ((userId == owner) || (new AuthorizationService().SetPerm((int)EnumPermissions.LEAD_DELETE).Authorize(userId)))
                    {
                        var result = _leadService.Convert(id, userId);
                        if (result != null)
                        {
                            response.StatusCode = HttpStatusCode.OK;
                            responseData        = ResponseFormat.Success;
                            responseData.data   = result;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.InternalServerError;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.SOMETHING_WRONG;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
示例#22
0
        public HttpResponseMessage CreateNote([FromUri] int id)
        {
            var                  response     = new HttpResponseMessage();
            ResponseFormat       responseData = new ResponseFormat();
            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.NOTE_CREATE);
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId       = Convert.ToInt32(payload["id"]);
                    var isAuthorized = _authorizationService.Authorize(userId);
                    if (isAuthorized)
                    {
                        string noteBody = HttpContext.Current.Request.Form["body"];
                        if (!string.IsNullOrEmpty(noteBody))
                        {
                            //create a note
                            NoteApiModel apiModel = new NoteApiModel();
                            apiModel.body      = noteBody;
                            apiModel.createdBy = new UserLinkApiModel()
                            {
                                id = userId
                            };
                            apiModel.lead = id;
                            var createdNote = _noteService.Create(apiModel);

                            //create files and link them to note
                            if (HttpContext.Current.Request.Files.Count > 0)
                            {
                                var allFiles = HttpContext.Current.Request.Files;
                                foreach (string fileName in allFiles)
                                {
                                    HttpPostedFile   uploadedFile = allFiles[fileName];
                                    FileManager.File file         = new FileManager.File(uploadedFile);
                                    _noteService.AddFile(createdNote, file);
                                }
                            }
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.NOTE_ADDED;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.BadRequest;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.NOTE_EMPTY;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
示例#23
0
        /// <summary>
        /// Annotates a single document publicly available under a given URL.
        /// Returns the annotated document serialized into the specified format
        /// </summary>
        /// <param name="documentUrl">the publicly accessible URL from where the document will be downloaded</param>
        /// <param name="documentMimeType">the MIME type of the document which will be annotated</param>
        /// <param name="serializationFormat">the serialization format of the output</param>
        /// <returns>an {@link InputStream} from where the serialized output can be read</returns>
        public Stream annotateDocumentFromUrlAsStream(Uri documentUrl, SupportedMimeType documentMimeType, ResponseFormat serializationFormat)
        {
            ServiceRequest rq = new ServiceRequest(documentUrl, documentMimeType);

            try
            {
                WebHeaderCollection collection = new WebHeaderCollection();
                collection.Set(HttpRequestHeader.Accept, serializationFormat.ToStringValue());

                return(client.requestForStream("", "POST", rq, collection));
            }
            catch (HttpClientException e)
            {
                JsonObject response = e.getResponse();
                if (response == null)
                {
                    throw new S4ServiceClientException(e.Message, e);
                }
                String msg = response.ToString();
                throw new S4ServiceClientException(msg == null ? e.Message : msg, e);
            }
        }
示例#24
0
文件: API.cs 项目: nilllzz/Pokemon3D
        /// <summary>
        /// Executes one or more Game Jolt API calls.
        /// </summary>
        /// <param name="calls">The list of calls.</param>
        /// <param name="format">The response format of the calls.</param>
        /// <param name="responseHandler">The response handler method that accepts the response from the Game Jolt server as a <see cref="string"/>.</param>
        /// <param name="parallelProcessing">If the Game Jolt API should process the calls simultaniously.</param>
        /// <param name="stopOnError">If the Game Jolt API should stop processing, if an error occurred during one call.</param>
        public void ExecuteCalls(APICall[] calls, ResponseFormat format, Action<string> responseHandler, bool parallelProcessing = true, bool stopOnError = false)
        {
            string formatStr = ResponseFormatToString(format);

            // build url from parameters:
            string url = string.Format(FORMAT_CALL_URL, HOST, VERSION, GameId, formatStr);
            if (parallelProcessing)
                url += "&parallel=true";
            if (stopOnError)
                url += "&stop_on_error=true";

            // add signature to url:
            var urlSignature = CreateSignature(url);
            url += "&signature=" + urlSignature;

            // the request will be a POST request, and all actual api requests will be stored in the post data:
            StringBuilder postDataBuilder = new StringBuilder("data=");

            foreach (APICall call in calls)
            {
                string callUrl = call.CreateUrl(this);
                string callSignature = CreateSignature(callUrl);
                callUrl += "&signature=" + callSignature;

                postDataBuilder.Append("&requests[]=" + UrlEncoder.Encode(callUrl));
            }

            string postData = postDataBuilder.ToString();

            try
            {
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    // create post requests:
                    var request = (HttpWebRequest)WebRequest.Create(url);
                    request.AllowWriteStreamBuffering = true;
                    request.Method = "POST";
                    request.ContentLength = postData.Length;
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ServicePoint.Expect100Continue = false;

                    StreamWriter writer = null;
                    StreamReader reader = null;
                    string responseStr = string.Empty; // stores the result.

                    try
                    {
                        // write post data to stream:
                        writer = new StreamWriter(request.GetRequestStream());
                        writer.Write(postData);
                        writer.Close();

                        // get request response, read from stream:
                        reader = new StreamReader(request.GetResponse().GetResponseStream());
                        responseStr = reader.ReadToEnd();
                    }
                    catch { } // suppress exceptions
                    finally
                    {
                        if (writer != null)
                            writer.Close();
                        if (reader != null)
                            reader.Close();
                    }

                    // call handle:
                    responseHandler(responseStr);
                });
            }
            catch { } // suppress exceptions
        }
示例#25
0
        public LastfmRequest(string method, RequestType request_type, ResponseFormat response_format)
        {
            this.method = method;
            this.request_type = request_type;
            this.response_format = response_format;
            if (this.web_request_creator == null) {
                this.web_request_creator = new WebRequestCreator ();
            }

            Init ();
        }
示例#26
0
 /// <summary>
 /// Get sentences
 /// </summary>
 /// <param name="sentenceCount">Number of sentences</param>
 /// <param name="allMeat">Meat only or meat mixed with miscellaneous ‘lorem ipsum’ filler.</param>
 /// <param name="startWithLorem">Start the first paragraph with ‘Bacon ipsum dolor...’.</param>
 /// <returns></returns>
 public static string GetSentences(int sentenceCount, ResponseFormat format, bool startWithLorem = false, bool allMeat = false)
 {
     var sentences = GetApiURL(format, allMeat, sentenceCount: sentenceCount, startWithLorem: startWithLorem);
     return RequestIpsum(sentences);
 }
示例#27
0
 internal LastfmRequest(string method, RequestType request_type, ResponseFormat response_format, IWebRequestCreate web_request_creator)
     : this(method, request_type, response_format)
 {
     this.web_request_creator = web_request_creator;
 }
示例#28
0
        public HttpResponseMessage AddTag([FromUri] int id, [FromBody] TagCreateApiModel tag)
        {
            var            response     = new HttpResponseMessage();
            ResponseFormat responseData = new ResponseFormat();
            //AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.LEAD_MODIFY);
            //read jwt

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = Convert.ToInt32(payload["id"]);
                    var owner  = _taskTemplateService.GetCallOwner(id);
                    if ((userId == owner) || (new AuthorizationService().SetPerm((int)EnumPermissions.TASK_DELETE_ANY).Authorize(userId)))
                    {
                        //check if a tag exist

                        //if it is, create a tag item with current lead

                        // else create a new tag and a new tag item
                        var isAdded = _taskTemplateService.AddTagToCall(id, tag.name);
                        if (isAdded)
                        {
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.TAG_ADDED;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.InternalServerError;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = ErrorMessages.SOMETHING_WRONG;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
示例#29
0
        /// <summary>
        /// Populate the API parameters with common attributes.
        /// </summary>
        /// <param name="parameters">The API parameters.</param>
        /// <param name="requireVerified">Whether a signed in user is required <c>true</c> or not <c>false</c>.</param>
        /// <param name="format">The <see cref="ResponseFormat"/> to receive the <see cref="Response"/> in.</param>
        static string Prepare(ref Dictionary <string, string> parameters, bool requireVerified, ResponseFormat format)
        {
            if (parameters == null)
            {
                parameters = new Dictionary <string, string>();
            }

            if (requireVerified)
            {
                if (Manager.Instance.CurrentUser == null || !Manager.Instance.CurrentUser.IsAuthenticated)
                {
                    return("Missing Authenticated User.");
                }
                parameters.Add("username", Manager.Instance.CurrentUser.Name.ToLower());
                parameters.Add("user_token", Manager.Instance.CurrentUser.Token.ToLower());
            }

            parameters.Add("format", format.ToString().ToLower());

            return(null);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SitecoreQuery" /> class.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="format">The format.</param>
 protected SitecoreQuery(SitecoreQueryType type, ResponseFormat format = ResponseFormat.Json)
 {
     QueryType      = type;
     ResponseFormat = format;
 }
示例#31
0
		public Response(WWW www, ResponseFormat format = ResponseFormat.Json)
		{
			if (www.error != null)
			{
				this.success = false;
				Debug.LogWarning(www.error);
				return;
			}

			this.format = format;

			switch (format)
			{
			case ResponseFormat.Dump:
				this.success = www.text.StartsWith("SUCCESS");

				var returnIndex = www.text.IndexOf ('\n');
				if (returnIndex != -1)
				{
					this.dump = www.text.Substring(returnIndex + 1);
				}

				if (!this.success)
				{
					Debug.LogWarning(this.dump);
					this.dump = null;
				}

				break;
				
			case ResponseFormat.Json:
				this.json = JSON.Parse(www.text)["response"];
				this.success = this.json["success"].AsBool;

				if (!this.success)
				{
					Debug.LogWarning(this.json["message"]);
					this.json = null;
				}

				break;
			
			case ResponseFormat.Raw:
				this.success = true;
				this.bytes = www.bytes;

				break;

			case ResponseFormat.Texture:
				this.success = true;
				this.texture = www.texture;

				break;

			default:
				this.success = false;
				Debug.LogWarning("Unknown format. Cannot process response.");

				break;
			}
		}
示例#32
0
文件: API.cs 项目: JoNMii/Pokemon3D
        /// <summary>
        /// Executes one or more Game Jolt API calls.
        /// </summary>
        /// <param name="calls">The list of calls.</param>
        /// <param name="format">The response format of the calls.</param>
        /// <param name="responseHandler">The response handler method that accepts the response from the Game Jolt server as a <see cref="string"/>.</param>
        /// <param name="parallelProcessing">If the Game Jolt API should process the calls simultaniously.</param>
        /// <param name="stopOnError">If the Game Jolt API should stop processing, if an error occurred during one call.</param>
        public void ExecuteCalls(APICall[] calls, ResponseFormat format, Action <string> responseHandler, bool parallelProcessing = true, bool stopOnError = false)
        {
            string formatStr = ResponseFormatToString(format);

            // build url from parameters:
            string url = string.Format(FORMAT_CALL_URL, HOST, VERSION, GameId, formatStr);

            if (parallelProcessing)
            {
                url += "&parallel=true";
            }
            if (stopOnError)
            {
                url += "&stop_on_error=true";
            }

            // add signature to url:
            var urlSignature = CreateSignature(url);

            url += "&signature=" + urlSignature;

            // the request will be a POST request, and all actual api requests will be stored in the post data:
            StringBuilder postDataBuilder = new StringBuilder("data=");

            foreach (APICall call in calls)
            {
                string callUrl       = call.CreateUrl(this);
                string callSignature = CreateSignature(callUrl);
                callUrl += "&signature=" + callSignature;

                postDataBuilder.Append("&requests[]=" + UrlEncoder.Encode(callUrl));
            }

            string postData = postDataBuilder.ToString();

            try
            {
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    // create post requests:
                    var request = (HttpWebRequest)WebRequest.Create(url);
                    request.AllowWriteStreamBuffering = true;
                    request.Method        = "POST";
                    request.ContentLength = postData.Length;
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ServicePoint.Expect100Continue = false;

                    StreamWriter writer = null;
                    StreamReader reader = null;
                    string responseStr  = string.Empty; // stores the result.

                    try
                    {
                        // write post data to stream:
                        writer = new StreamWriter(request.GetRequestStream());
                        writer.Write(postData);
                        writer.Close();

                        // get request response, read from stream:
                        reader      = new StreamReader(request.GetResponse().GetResponseStream());
                        responseStr = reader.ReadToEnd();
                    }
                    catch { } // suppress exceptions
                    finally
                    {
                        if (writer != null)
                        {
                            writer.Close();
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }

                    // call handle:
                    responseHandler(responseStr);
                });
            }
            catch { } // suppress exceptions
        }
示例#33
0
        private static void BuildMethodInfo(ServiceInfo serviceInfo, XmlNode node)
        {
            XmlNodeList methodNodes = node.SelectNodes("method");

            foreach (XmlNode methodNode in methodNodes)
            {
                string name       = GetAttributeValue(methodNode, "name", true);
                string serverName = GetAttributeValue(methodNode, "serverName", false);
                if (serverName == null)
                {
                    serverName = name;
                }

                string getEnabled = GetAttributeValue(methodNode, "getEnabled", false);
                bool   get        = (getEnabled != null && String.Equals(getEnabled, "true", StringComparison.OrdinalIgnoreCase));

                ResponseFormat mode           = ResponseFormat.Json;
                string         responseFormat = GetAttributeValue(methodNode, "responseFormat", false);
                if (responseFormat != null && String.Equals(responseFormat, "xml", StringComparison.OrdinalIgnoreCase))
                {
                    mode = ResponseFormat.Xml;
                }

                BridgeMethodInfo methodInfo = new BridgeMethodInfo(name, serverName, get, mode);
                XmlNode          inputNode  = GetSingleNode(methodNode, "input", false);
                if (inputNode == null)
                {
                    methodInfo.Parameters = new Dictionary <string, BridgeParameterInfo>(0);
                }
                else
                {
                    methodInfo.Parameters = BuildParams(inputNode);
                }

                XmlNode requests = GetSingleNode(methodNode, "requestChain", false);
                if (requests != null)
                {
                    BuildMethodRequestChain(requests, methodInfo);
                }

                // REVIEW: Only used on Soap stuff currently
                XmlNodeList includeNodes = methodNode.SelectNodes("xmlinclude");
                foreach (XmlNode includeNode in includeNodes)
                {
                    methodInfo.XmlIncludes.Add(GetAttributeValue(includeNode, "type", true));
                }

                XmlNode transformNode = GetSingleNode(methodNode, "transforms", false);
                BuildTransforms(transformNode, methodInfo);

                XmlNode cachingNode = GetSingleNode(methodNode, "caching", false);
                BuildCaches(cachingNode, methodInfo);

                XmlNode authNode = methodNode.SelectSingleNode("authentication");
                if (authNode != null)
                {
                    methodInfo.Credentials = ParseCredentials(authNode);
                }

                serviceInfo.Methods[name] = methodInfo;
            }
        }
        public async Task <IActionResult> ReplaceObject([FromRoute] ItemRouteParameters routeParameters, [FromBody] string json, [FromQuery] ResponseFormat responseFormat = ResponseFormat.EntireObject)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string document = await _service.ReplaceAsync(routeParameters.DatabaseName, routeParameters.CollectionName, routeParameters.Id, json);

            if (string.IsNullOrEmpty(document))
            {
                return(ObjectNotFound(routeParameters.Id, routeParameters.CollectionName));
            }

            if (responseFormat == ResponseFormat.OnlyId)
            {
                string id = GetObjectId(document);
                document = GetReplacedJsonResult(new string[] { id }).ToString();
                return(Ok(document));
            }
            else
            {
                return(Ok(document));
            }
        }
示例#35
0
        /// <summary>
        /// Annotates the contents of a single file returning an {@link InputStream} from which the annotated content can be read
        /// </summary>
        /// <param name="documentContent">the file which will be annotated</param>
        /// <param name="documentEncoding">the encoding of the file which will be annotated</param>
        /// <param name="documentMimeType">the MIME type of the file which will be annotated</param>
        /// <param name="serializationFormat">the serialization format used for the annotated content</param>
        public Stream annotateDocumentAsStream(FileStream documentContent, String documentEncoding, SupportedMimeType documentMimeType, ResponseFormat serializationFormat)
        {
            String documentPath = Path.GetFullPath(documentContent.Name);

            if (!documentContent.CanRead)
            {
                throw new IOException("File " + documentPath + " is not readable.");
            }
            Byte[] buff;
            buff = File.ReadAllBytes(documentPath);
            Encoding encode  = System.Text.Encoding.GetEncoding(documentEncoding);
            String   content = new UTF8Encoding().GetString(buff);

            return(annotateDocumentAsStream(content, documentMimeType, serializationFormat));
        }
 public StripMethodAttribute(ResponseFormat json, bool UseHttpGet)
 {
     this.json       = json;
     this.UseHttpGet = UseHttpGet;
 }
示例#37
0
 public Helper(ResponseFormat responseFormat)
 {
     this._responseFormat = responseFormat;
     this.InitializeResponseVariables();
 }
示例#38
0
        /// <summary>
        /// Annotates a single document and returns an {@link InputStream} from
        /// which the contents of the serialized annotated document can be read
        /// </summary>
        /// <param name="documentText">the contents of the document which will be annotated</param>
        /// <param name="documentMimeType">the MIME type of the file which will be annotated</param>
        /// <param name="serializationFormat">the format which will be used for serialization of the annotated document</param>
        /// <returns>an {@link InputStream} from which the serialization of the annotated document can be read</returns>
        public Stream annotateDocumentAsStream(String documentText, SupportedMimeType documentMimeType, ResponseFormat serializationFormat)
        {
            ServiceRequest      rq      = new ServiceRequest(documentText, documentMimeType);
            WebHeaderCollection headers = new WebHeaderCollection();

            headers.Add("Accept", serializationFormat.ToStringValue());
            try
            {
                return(client.requestForStream("", "POST", rq, headers));
            }
            catch (HttpClientException e)
            {
                JsonObject response = e.getResponse();
                if (response == null)
                {
                    throw new S4ServiceClientException(e.Message);
                }
                String msg = response.ToString();
                throw new S4ServiceClientException(msg == null ? e.Message : msg.ToString());
            }
        }
示例#39
0
        /*
         * [WebMethod]
         * [ScriptMethod(UseHttpGet=true,ResponseFormat=ResponseFormat.Json|Xml)]
         * [XmlInclude(typeof<>) ...
         * public object Method(IDictionary args) {
         *   return Invoke(new BridgeRequest("Method", args);
         * }
         *
         * __invokeBridge takes the method as an argument
         */
        private static CodeMemberMethod GenerateWebMethodCode(String methodName, List <string> xmlIncludes, bool getEnabled, ResponseFormat responseFormat, bool invokeBridge)
        {
            CodeMemberMethod method = new CodeMemberMethod();

            method.Attributes = MemberAttributes.Public;
            method.Name       = methodName;
            method.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(WebMethodAttribute))));

            string format = "Json";

            if (responseFormat != ResponseFormat.Json)
            {
                format = "Xml";
            }
            CodeAttributeDeclaration webOp = new CodeAttributeDeclaration(new CodeTypeReference(typeof(ScriptMethodAttribute)),
                                                                          new CodeAttributeArgument("UseHttpGet", new CodePrimitiveExpression(getEnabled)),
                                                                          new CodeAttributeArgument("ResponseFormat", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(ResponseFormat)), format)));

            method.CustomAttributes.Add(webOp);

            if (invokeBridge)
            {
                method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "method"));
            }
            else
            {
                for (int i = 0; i < xmlIncludes.Count; ++i)
                {
                    method.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(GenerateScriptTypeAttribute)),
                                                                             new CodeAttributeArgument(new CodeTypeOfExpression(xmlIncludes[i]))));
                }
            }

            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IDictionary), "args"));

            method.ReturnType = new CodeTypeReference(typeof(object));
            CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression();

            expr.Method = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "Invoke");
            CodeExpression methodExpr = null;

            if (invokeBridge)
            {
                methodExpr = new CodeVariableReferenceExpression("method");
            }
            else
            {
                methodExpr = new CodePrimitiveExpression(methodName);
            }
            expr.Parameters.Add(new CodeObjectCreateExpression(typeof(BridgeRequest), methodExpr, new CodeVariableReferenceExpression("args")));
            method.Statements.Add(new CodeMethodReturnStatement(expr));
            return(method);
        }
示例#40
0
文件: API.cs 项目: nilllzz/Pokemon3D
 private static string ResponseFormatToString(ResponseFormat format)
 {
     return format.ToString().ToLowerInvariant();
 }
        /*
         * [WebMethod]
         * [ScriptMethod(UseHttpGet=true,ResponseFormat=ResponseFormat.Json|Xml)]
         * [XmlInclude(typeof<>) ...
         * public object Method(IDictionary args) {
         *   return Invoke(new BridgeRequest("Method", args);
         * }
         *
         * __invokeBridge takes the method as an argument
         */
        private static CodeMemberMethod GenerateWebMethodCode(String methodName, List<string> xmlIncludes, bool getEnabled, ResponseFormat responseFormat, bool invokeBridge) {
            CodeMemberMethod method = new CodeMemberMethod();
            method.Attributes = MemberAttributes.Public;
            method.Name = methodName;
            method.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(WebMethodAttribute))));

            string format = "Json";
            if (responseFormat != ResponseFormat.Json) {
                format = "Xml";
            }
            CodeAttributeDeclaration webOp = new CodeAttributeDeclaration(new CodeTypeReference(typeof(ScriptMethodAttribute)),
                new CodeAttributeArgument("UseHttpGet", new CodePrimitiveExpression(getEnabled)),
                new CodeAttributeArgument("ResponseFormat", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(ResponseFormat)), format)));
            method.CustomAttributes.Add(webOp);

            if (invokeBridge) {
                method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "method"));
            }
            else {
                for (int i = 0; i < xmlIncludes.Count; ++i) {
                    method.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(GenerateScriptTypeAttribute)),
                        new CodeAttributeArgument(new CodeTypeOfExpression(xmlIncludes[i]))));
                }
            }

            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IDictionary), "args"));

            method.ReturnType = new CodeTypeReference(typeof(object));
            CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression();
            expr.Method = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "Invoke");
            CodeExpression methodExpr = null;
            if (invokeBridge) {
                methodExpr = new CodeVariableReferenceExpression("method");
            }
            else {
                methodExpr = new CodePrimitiveExpression(methodName);
            }
            expr.Parameters.Add(new CodeObjectCreateExpression(typeof(BridgeRequest), methodExpr, new CodeVariableReferenceExpression("args")));
            method.Statements.Add(new CodeMethodReturnStatement(expr));
            return method;
        }
示例#42
0
 /// <summary>
 /// List all snapshots for this account
 /// </summary>
 /// <param name="format"></param>
 /// <returns></returns>
 public static string ListSnapshots(ResponseFormat format)
 {
     return ListSnapshots(format, 0);
 }
 public IRestRequest CreateRequest(ResponseFormat format)
 {
     _format = format;
     return CreateRequest();
 }
示例#44
0
 public static string GetParagraphs(int paragraphCount, ResponseFormat format, bool startWithLorem = false, bool allMeat = false)
 {
     var url = GetApiURL(format, allMeat, paragraphCount: paragraphCount, startWithLorem: startWithLorem);
     return RequestIpsum(url);
 }
示例#45
0
        /// <summary>
        /// Annotates a single document and returns an {@link InputStream} from
        /// which the contents of the serialized annotated document can be read
        /// </summary>
        /// <param name="documentText">the contents of the document which will be annotated</param>
        /// <param name="documentMimeType">the MIME type of the file which will be annotated</param>
        /// <param name="serializationFormat">the format which will be used for serialization of the annotated document</param>
        /// <returns>an {@link InputStream} from which the serialization of the annotated document can be read</returns>
        public Stream annotateDocumentAsStream(String documentText, SupportedMimeType documentMimeType, ResponseFormat serializationFormat)
        {
            ServiceRequest rq = new ServiceRequest(documentText, documentMimeType);

            try
            {
                return(client.requestForStream("", "POST", rq, constructHeaders(serializationFormat)));
            }
            catch (HttpClientException e)
            {
                String msg = handleErrors(e);
                throw new S4ServiceClientException(msg == null ? e.Message : msg.ToString());
            }
        }
示例#46
0
 public LastfmRequest(string method, RequestType request_type, ResponseFormat response_format)
 {
     this.method          = method;
     this.request_type    = request_type;
     this.response_format = response_format;
 }
 public BridgeMethodInfo(string name, string serverName, bool getEnabled, ResponseFormat responseFormat) {
     Name = name;
     ServerName = serverName;
     GetEnabled = getEnabled;
     ResponseFormat = responseFormat;
 }
示例#48
0
 /// <summary>
 /// Build the Uri for the request
 /// </summary>
 /// <param name="searchTerm">The term to be queried for</param>
 /// <param name="applicationName">The application name identifying the requesting entity</param>
 /// <param name="responseFormat">The format the response should be structured as. Either JSON (Default) or XML</param>
 /// <returns>The result as a string formatted as either JSON (Default) or XML</returns>
 private string BuildRequestUri(string searchTerm, string applicationName, ResponseFormat responseFormat)
 {
     return string.Format(
             Uri,
             HttpUtility.UrlEncode(searchTerm),
             HttpUtility.UrlEncode(applicationName),
             HttpUtility.UrlEncode(responseFormat.ToString().ToLower()),
             NoRedirects ? 1 : 0,
             NoHtml ? 1 : 0,
             SkipDisambiguation ? 1 : 0);
 }
 public SitecoreAdvanceCreateQuery(SitecoreQueryType type, ResponseFormat format = ResponseFormat.Json)
 {
     QueryType      = type;
     ResponseFormat = format;
 }
示例#50
0
 public ODataEdmxResponse(ODataUri uri, IEdmModel model) : base(uri)
 {
     _model = model;
     Format = ResponseFormat.Xml;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SitecoreQuery" /> class.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="format">The format.</param>
 protected SitecoreQuery(SitecoreQueryType type, ResponseFormat format = ResponseFormat.Json)
 {
     QueryType = type;
     ResponseFormat = format;
 }
示例#52
0
 public LastfmRequest (string method, RequestType request_type, ResponseFormat response_format)
 {
     this.method = method;
     this.request_type = request_type;
     this.response_format = response_format;
 }
示例#53
0
        public static string GetParagraphs(int paragraphCount, ResponseFormat format, bool startWithLorem = false, bool allMeat = false)
        {
            var url = GetApiURL(format, allMeat, paragraphCount: paragraphCount, startWithLorem: startWithLorem);

            return(RequestIpsum(url));
        }
 ///<summary>Sets the response data type.</summary>
 public ReportingRequest setResponseFormat(ResponseFormat format)
 {
     switch (format)
     {
         case ResponseFormat.XML1:
             addRequestField("xmlEncoding", "0");
             break;
         case ResponseFormat.XML2:
             addRequestField("xmlEncoding", "1");
             break;
         case ResponseFormat.CSV:
         default:
             removeField("xmlEncoding");
             break;
     }
     return this;
 }
示例#55
0
        /// <summary>
        /// Get sentences
        /// </summary>
        /// <param name="sentenceCount">Number of sentences</param>
        /// <param name="allMeat">Meat only or meat mixed with miscellaneous ‘lorem ipsum’ filler.</param>
        /// <param name="startWithLorem">Start the first paragraph with ‘Bacon ipsum dolor...’.</param>
        /// <returns></returns>
        public static string GetSentences(int sentenceCount, ResponseFormat format, bool startWithLorem = false, bool allMeat = false)
        {
            var sentences = GetApiURL(format, allMeat, sentenceCount: sentenceCount, startWithLorem: startWithLorem);

            return(RequestIpsum(sentences));
        }
示例#56
0
        public HttpResponseMessage Update([FromUri] int id, [FromBody] GroupCreateApiModel apiModel)
        {
            var                  response              = new HttpResponseMessage();
            ResponseFormat       responseData          = new ResponseFormat();
            AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.GROUP_MODIFY);
            //read jwt

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = payload["id"];

                    var isAuthorized = _authorizationService.Authorize(Convert.ToInt32(userId));
                    if (isAuthorized)
                    {
                        var isUpdated = _groupService.Update(id, apiModel);
                        if (isUpdated)
                        {
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.GROUP_MODIFIED;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
示例#57
0
        public WebMethodDef(WebServiceDef wsDef, MethodInfo method, WebMethodAttribute wmAttribute, ScriptMethodAttribute smAttribute, TransactionalMethodAttribute tmAttribute, ETagMethodAttribute emAttribute)
        {
            this.MethodType = method;
            this.WebMethodAtt = wmAttribute;
            this.ScriptMethodAtt = smAttribute;
            this.TransactionAtt = tmAttribute;

            if( null != emAttribute ) this.IsETagEnabled = emAttribute.Enabled;

            if (wmAttribute != null && !string.IsNullOrEmpty(wmAttribute.MessageName)) this.MethodName = wmAttribute.MessageName;
            else this.MethodName = method.Name;

            // HTTP GET method is allowed only when there's a [ScriptMethod] attribute and UseHttpGet is true
            this.IsGetAllowed = (this.ScriptMethodAtt != null && this.ScriptMethodAtt.UseHttpGet);

            this.ResponseFormat = (this.ScriptMethodAtt != null ? this.ScriptMethodAtt.ResponseFormat : ResponseFormat.Json);

            MethodInfo beginMethod = wsDef.WSType.GetMethod("Begin" + method.Name, BINDING_FLAGS);
            if (null != beginMethod)
            {
                // The BeginXXX method must have the [ScriptMethod] attribute
                object[] scriptMethodAttributes = beginMethod.GetCustomAttributes(typeof(ScriptMethodAttribute), false);
                if (scriptMethodAttributes.Length > 0)
                {
                    // Asynchronous methods found for the function
                    this.HasAsyncMethods = true;

                    this.BeginMethod = new WebMethodDef(wsDef, beginMethod, null, null, null, null);

                    MethodInfo endMethod = wsDef.WSType.GetMethod("End" + method.Name, BINDING_FLAGS);
                    this.EndMethod = new WebMethodDef(wsDef, endMethod, null, null, null, null);

                    // get all parameters of begin web method and then leave last two parameters in the input parameters list because
                    // last two parameters are for AsyncCallback and Async State
                    ParameterInfo[] allParameters = beginMethod.GetParameters();
                    ParameterInfo[] inputParameters = new ParameterInfo[allParameters.Length - 2];
                    Array.Copy(allParameters, inputParameters, allParameters.Length - 2);

                    this.BeginMethod.InputParameters = new List<ParameterInfo>(inputParameters);
                    this.BeginMethod.InputParametersWithAsyc = new List<ParameterInfo>(allParameters);
                }
            }

            this.InputParameters = new List<ParameterInfo>(method.GetParameters());
        }