Pages

Monday, 10 February 2014

Restful Service in c#

一Service Method:

 public Stream CartQuantity(Stream stmIncDecCartQty)
        {
            BLCart objBLCart = new BLCart();
            string strCartDtls = string.Empty;
            string strCartQtyPostDtls = string.Empty;
            int intLineItemId = 0;
            int intRequestedQty = 0;
            int intEsId = 0;
            try
            {
                strCartDtls = Helper.Authentication();
                if (!strCartDtls.Equals(string.Empty))
                    goto FinalResponse;
                var varCartDtls = new StreamReader(stmIncDecCartQty);
                strCartQtyPostDtls = varCartDtls.ReadToEnd();
                XDocument xmldata = XDocument.Parse(strCartQtyPostDtls);
                var q = from c in xmldata.Descendants("Cart")
                        select new
                        {
                            LineItemId = (string)c.Element("LineItemId").Value,
                            RequestedQty = (string)c.Element("RequestedQty").Value,
                            EsId = (string)c.Element("EsId").Value
                        };
                foreach (var strNodeValue in q)
                {
                    intLineItemId = Helper.GetValidInteger(strNodeValue.LineItemId);
                    intRequestedQty = Helper.GetValidInteger(strNodeValue.RequestedQty);
                    intEsId = Helper.GetValidInteger(strNodeValue.EsId);
                }
                strCartDtls = objBLCart.IncDecCartQty(intRequestedQty, intLineItemId, intEsId);
            }
            catch (Exception ex)
            {
                Helper.Logger("ERROR...! at CartQuantity()," + ex.Message);
                strCartDtls = Helper.ProcessFailure(Helper.CartDtlsObject, Helper.ErrorCode, "Input was not in correct format.");
            }
        FinalResponse:
            objARF.AppResponseFormat();
            //Helper.Logger("API URI ==> " + HttpContext.Current.Request.Url.ToString() + " Millisecond Time is ==>" + Helper.Timer(long.Parse(HttpContext.Current.Session["time"].ToString()), long.Parse(DateTime.Now.Ticks.ToString())));
            return new MemoryStream(Encoding.UTF8.GetBytes(strCartDtls));
        }

Service Call:

public static XDocument WebRequest(string strUri, string strPostData, int timeout = 0)
        {
            HttpWebRequest WebReq = null;
            XDocument xmlRes = null;
            string strResponse = string.Empty;
            try
            {
                byte[] buffer = Encoding.ASCII.GetBytes(strPostData);
                WebReq = (HttpWebRequest)HttpWebRequest.Create(strUri);
                WebReq.Method = "POST";
                WebReq.Proxy = null;
                if (AccessPointIdEnable == "true")
                {
                    WebReq.Headers.Add("NAT_ACCESS_POINT_ID", ServerAccessPointId);
                    WebReq.Headers.Add("NAT_AUTH_CODE", AuthCode);
                }
                WebReq.Headers.Add("DOMAIN", GetCurrentDomain());
                if (timeout == 0)
                {
                    int.TryParse(Helper.NatServiceTimeOut, out timeout);
                    WebReq.Timeout = timeout;
                }
                else
                    WebReq.Timeout = timeout;
                WebReq.ContentType = "application/x-www-form-urlencoded";
                WebReq.ContentLength = buffer.Length;
                Stream PostData = WebReq.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();
                using (HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse())
                {
                    using (Stream stmResp = WebResp.GetResponseStream())
                    {
                        using (StreamReader stmrdrResponse = new StreamReader(stmResp))
                        {
                            strResponse = stmrdrResponse.ReadToEnd().ToString();
                            xmlRes = XDocument.Parse(strResponse);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                xmlRes = GetResponseTemplate(Helper.GetExceptionDetails(ex), 408);
                Logger("Timeout exception for URL: " + strUri, EventLogEntryType.Error, 408);
            }
            catch (Exception ex)
            {
                xmlRes = GetResponseTemplate(Helper.GetExceptionDetails(ex), 500);
                Logger("Exception occured for " + strUri + " with Message " + Helper.GetExceptionDetails(ex), EventLogEntryType.Error, 500);
            }
            return xmlRes;
        }




Service Interface:

        [AspNetCacheProfile("User.Details.UserId")]
        [DataContractFormat]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = URITemplates.UserDtls)]
        Stream UserDetails(string strUserId);

Cache Web.config settings:

<caching>
      <outputCache enableOutputCache="true"/>
      <outputCacheSettings>
        <outputCacheProfiles>
          <!--Cache duration is stored in seconds-->
          <!--Client Profiles Starts-->
</outputCacheProfiles>
      </outputCacheSettings>
    </caching>
          <add name="User.Details.UserId" location="Client" duration="15" varyByParam="strUserId"/>

Service Interface:

        [DataContractFormat]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = URITemplates.User, RequestFormat = WebMessageFormat.Xml)]
        Stream User(Stream stmUser);    

URI Templates:

public const string UserDtls = "/usrdtls/{strUserId}";


Service call URL:

 xDocEs = Helper.WebRequest(Helper.ApiBasePathPrivate + "/usr/?fmt=xml", "<User><Mode>login</Mode><LoginId>" + UserLoginId + "</LoginId><Password>" + xDocEs.Element("Response").Element("UsrDtlsObject").Element("UsrDtls").Element("UserPwd").Value + "</Password><Name>" + UserFName + "</Name><SessionId>" + objEstore.SessionId + "</SessionId><EsId>" + objEstore.EsId + "</EsId><Currency>" + objEstore.EsCurrency + "</Currency></User>");


Content Type:

 public const string AppJsonChrUtf8 = "application/json; charset=utf-8";
        public const string AppXml = "text/xml";



 public void AppResponseFormat()
        {
            try
            {
                //if (Helper.GetValidString(HttpContext.Current.Request["device"]).ToLower() != null || Helper.GetValidString(HttpContext.Current.Request["device"]).ToLower() == "phone")
                //{
                switch (Helper.GetValidString(HttpContext.Current.Request["fmt"]).ToLower())
                {
                    case "xml":
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
                        WebOperationContext.Current.OutgoingResponse.ContentType = AppXml;
                        break;
                    case "json":
                    default:
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
                        WebOperationContext.Current.OutgoingResponse.ContentType = AppJsonChrUtf8;
                        break;
                }
                //}
            }
            catch
            {
                //throw ex;
            }
        }

No comments:

Post a Comment