/// <summary>
        ///
        /// </summary>
        /// <param name="callname"></param>
        /// <returns></returns>
        public CallMetricsEntry GetNewEntry(string callname)
        {
            CallMetricsEntry metrics = new CallMetricsEntry(callname);

            AddCallMetrics(metrics);
            return(metrics);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="callname"></param>
        /// <param name="logger"></param>
        /// <param name="metricsList"></param>
        private void GenerateReportPerCallname(string callname, ApiLogger logger, ArrayList metricsList)
        {
            mLogger = logger;
            Log("Call name: " + callname);
            Log("Number of calls recorded: " + metricsList.Count);
            Log("Total     Setup     Network   Server    Finish    Start Time          ");
            Log("======================================================================");
            for (int i = 0; i < metricsList.Count; i++)
            {
                CallMetricsEntry metrics = (CallMetricsEntry)metricsList[i];
                metrics.GenerateReport(logger);
            }
            string avgstring = "";

            if (metricsList.Count > 0)
            {
                long[] averages = GenerateAverage(metricsList);
                for (int i = 0; i < averages.Length; i++)
                {
                    avgstring += CallMetricsEntry.FormatNumber(averages[i]);
                }
            }
            Log("Average : ");
            Log(avgstring);
            Log("======================================================================");
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="metrics"></param>
		#region Public Methods
		public void AddCallMetrics(CallMetricsEntry metrics)
		{
			lock(this)
			{
				string callname = metrics.CallName;
				ArrayList metricsList = (ArrayList) mMetricsTable[callname];
				if (metricsList == null)
				{
					metricsList = new ArrayList();
					mMetricsTable[callname] = metricsList;
				}
				metricsList.Add(metrics);
			}
		}
 /// <summary>
 ///
 /// </summary>
 /// <param name="metrics"></param>
 #region Public Methods
 public void AddCallMetrics(CallMetricsEntry metrics)
 {
     lock (this)
     {
         string    callname    = metrics.CallName;
         ArrayList metricsList = (ArrayList)mMetricsTable[callname];
         if (metricsList == null)
         {
             metricsList             = new ArrayList();
             mMetricsTable[callname] = metricsList;
         }
         metricsList.Add(metrics);
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="metricsList"></param>
        /// <returns></returns>
        private long[] GenerateAverage(ArrayList metricsList)
        {
            long [] averages = new long[NUMBER_OF_COLUMNS];

            for (int i = 0; i < averages.Length; i++)
            {
                averages[i] = 0;
            }
            for (int i = 0; i < metricsList.Count; i++)
            {
                CallMetricsEntry metrics = (CallMetricsEntry)metricsList[i];
                metrics.UpdateTotals(averages);
            }
            for (int i = 0; i < averages.Length; i++)
            {
                averages[i] /= metricsList.Count;
            }
            return(averages);
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="callname"></param>
		/// <returns></returns>
		public CallMetricsEntry GetNewEntry(string callname)
		{
			CallMetricsEntry metrics = new CallMetricsEntry(callname);
			AddCallMetrics(metrics);
			return metrics;
		}
Example #7
0
        /// <summary>
        /// 
        /// </summary>
        internal void SendRequest()
        {
            try
            {
                if (AbstractRequest == null)
                    throw new ApiException("RequestType reference not set to an instance of an object.", new System.ArgumentNullException());
                if (ApiContext == null)
                    throw new ApiException("ApiContext reference not set to an instance of an object.", new System.ArgumentNullException());
                if (ApiContext.ApiCredential == null)
                    throw new ApiException("Credentials reference in ApiContext object not set to an instance of an object.", new System.ArgumentNullException());

                string apiName = AbstractRequest.GetType().Name.Replace("RequestType","");

                if (this.ApiContext.EnableMetrics)
                {
                    mCallMetrics = this.ApiContext.CallMetricsTable.GetNewEntry(apiName);
                    mCallMetrics.ApiCallStarted = System.DateTime.Now;
                }

                CustomSecurityHeaderType secHdr = this.GetSecurityHeader();

                // Get default constructor.
                /*
                ConstructorInfo svcCCTor = this.mServiceType.GetConstructor(
                    BindingFlags.Instance | BindingFlags.Public, null,
                    CallingConventions.HasThis, null, null);
                    */
                ConstructorInfo svcCCTor = this.mServiceType.GetConstructor(new Type[] {});

                object svcInst = svcCCTor.Invoke(null);

                PropertyInfo pi;

                pi = this.mServiceType.GetProperty("ApiLogManager");
                if( pi == null )
                    throw new SdkException("ApiLogManager was not found in InterfaceServiceType");
                pi.SetValue(svcInst, this.mApiContext.ApiLogManager, null);

                pi = this.mServiceType.GetProperty("EnableComression");
                if( pi == null )
                    throw new SdkException("EnableComression was not found in InterfaceServiceType");
                pi.SetValue(svcInst, this.mEnableCompression, null);

                pi = this.mServiceType.GetProperty("RequesterCredentials");
                if( pi == null )
                    throw new SdkException("RequesterCredentials was not found in InterfaceServiceType");
                pi.SetValue(svcInst, secHdr, null);

                pi = this.mServiceType.GetProperty("WebProxy");
                if (pi == null)
                    throw new SdkException("WebProxy was not found in InterfaceServiceType");
                pi.SetValue(svcInst, this.mApiContext.WebProxy, null);
                if (this.mApiContext.WebProxy != null)
                {
                    LogMessage("Proxy Server is Set", MessageType.Information, MessageSeverity.Informational);
                }

                pi = this.mServiceType.GetProperty("CallMetricsEntry");
                if( pi == null )
                    throw new SdkException("CallMetricsEntry was not found in InterfaceServiceType");
                if (this.ApiContext.EnableMetrics)
                    pi.SetValue(svcInst, this.mCallMetrics, null);
                else
                    pi.SetValue(svcInst, null, null);

                string url = "";
                try
                {
                    if (ApiContext.SoapApiServerUrl != null && ApiContext.SoapApiServerUrl.Length > 0)
                        url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap",
                            ApiContext.SoapApiServerUrl, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture));
                    else
                    {
                        url = (string)this.mServiceType.GetProperty("Url").GetValue(svcInst, null);
                        url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap",
                            url, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    //svcCCTor.Url = url;
                    this.mServiceType.GetProperty("Url").SetValue(svcInst, url, null);
                }
                catch(Exception ex)
                {
                    throw new ApiException(ex.Message, ex);
                }

                LogMessage(url, MessageType.Information, MessageSeverity.Informational);

                //svcCCTor.Timeout = Timeout;
                this.mServiceType.GetProperty("Timeout").SetValue(svcInst, Timeout, null);

                AbstractRequest.Version = Version;

                if (!mDetailLevelOverride && AbstractRequest.DetailLevel == null)
                {
                    AbstractRequest.DetailLevel = new DetailLevelCodeTypeCollection();
                    AbstractRequest.DetailLevel.AddRange(mDetailLevelList);
                }

                if (ApiContext.ErrorLanguage != ErrorLanguageCodeType.CustomCode)
                    AbstractRequest.ErrorLanguage = ApiContext.ErrorLanguage.ToString();

                //Populate the message
                AbstractRequest.MessageID = System.Guid.NewGuid().ToString();

                Type methodtype = svcInst.GetType();
                object[] reqparm = new object[] {AbstractRequest};

                int retries = 0;
                int maxRetries = 0;
                bool doretry = false;
                CallRetry retry = null;
                if (mCallRetry != null)
                {
                    retry = mCallRetry;
                    maxRetries = retry.MaximumRetries;
                }
                else if (ApiContext.CallRetry != null)
                {
                    retry = ApiContext.CallRetry;
                    maxRetries = retry.MaximumRetries;
                }

                do
                {
                    Exception callException = null;
                    try
                    {
                        mResponse = null;
                        mApiException = null;

                        if (retries > 0)
                        {
                            LogMessage("Invoking Call Retry", MessageType.Information, MessageSeverity.Informational);
                            System.Threading.Thread.Sleep(retry.DelayTime);
                        }

                        if( BeforeRequest != null )
                            BeforeRequest(this, new BeforeRequestEventArgs(AbstractRequest));

                        //Invoke the Service
                        DateTime start = DateTime.Now;
                        mResponse = (AbstractResponseType) methodtype.GetMethod(apiName).Invoke(svcInst, reqparm);
                        mResponseTime = DateTime.Now - start;

                        if( AfterRequest != null )
                            AfterRequest(this, new AfterRequestEventArgs(mResponse));

                        // Catch Token Expiration warning
                        if (mResponse != null && secHdr.HardExpirationWarning != null)
                        {
                            ApiContext.ApiCredential.TokenHardExpirationWarning(
                                System.Convert.ToDateTime(secHdr.HardExpirationWarning, System.Globalization.CultureInfo.CurrentUICulture));
                        }

                        if (mResponse != null && mResponse.Errors != null && mResponse.Errors.Count > 0)
                        {
                            throw new ApiException(new ErrorTypeCollection(mResponse.Errors));
                        }
                    }

                    catch (Exception ex)
                    {
                        // this catches soap faults
                        if (ex.GetType() == typeof(TargetInvocationException))
                        {
                            // we never care about the outer exception
                            Exception iex = ex.InnerException;

                            // Parse Soap Faults
                            if (iex.GetType() == typeof(SoapException))
                            {
                                ex = ApiException.FromSoapException((SoapException) iex);
                            }
                            else if (iex.GetType() == typeof(InvalidOperationException))
                            {
                                // Go to innermost exception
                                while (iex.InnerException != null)
                                    iex = iex.InnerException;
                                ex = new ApiException(iex.Message, iex);
                            }
                            else if (iex.GetType() == typeof(HttpException))
                            {
                                HttpException httpEx = (HttpException) iex;
                                String str = "HTTP Error Code: " + httpEx.StatusCode;
                                ex = new ApiException(str, iex);
                            }
                            else
                            {
                                ex = new ApiException(iex.Message, iex);
                            }
                        }
                        callException = ex;

                        // log the message - override current switches - *if* (a) we wouldn't normally log it, and (b)
                        // the exception matches the exception filter.

                        if (retry != null)
                            doretry = retry.ShouldRetry(ex);

                        if (!doretry || retries == maxRetries)
                        {
                            throw ex;
                        }
                        else
                        {
                            string soapReq = (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null);
                            string soapResp = (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null);

                            LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, ex);
                            MessageSeverity svr = ((ApiException) ex).SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning;
                            LogMessage(ex.Message, MessageType.Exception, svr);
                        }
                    }

                    finally
                    {
                        string soapReq = (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null);
                        string soapResp = (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null);

                        if (!doretry || retries == maxRetries)
                            LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, callException);

                        if (mResponse != null && mResponse.TimestampSpecified)
                            ApiContext.CallUpdate(mResponse.Timestamp);
                        else
                            ApiContext.CallUpdate(new DateTime(0));

                        mSoapRequest = soapReq;
                        mSoapResponse = soapResp;
                        retries++;
                    }

                } while (doretry && retries <= maxRetries);
            }

            catch (Exception ex)
            {
                ApiException aex = ex as ApiException;

                if (aex != null)
                {
                    mApiException = aex;
                }
                else
                {
                    mApiException = new ApiException(ex.Message, ex);
                }
                MessageSeverity svr = mApiException.SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning;
                LogMessage(mApiException.Message, MessageType.Exception, svr);

                if (mApiException.SeverityErrorCount > 0)
                    throw mApiException;

            }
            finally
            {
                if (this.ApiContext.EnableMetrics)
                    mCallMetrics.ApiCallEnded = DateTime.Now;
            }
        }