/// <summary> /// 获取内网IP /// </summary> /// <returns></returns> public static string GetLanIp() { try { //foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName())) //{ // if (hostAddress.AddressFamily == AddressFamily.InterNetwork) // { // return hostAddress.ToString(); // } //} var nets = NetworkInterface.GetAllNetworkInterfaces() .Select(p => p.GetIPProperties()).SelectMany(p => p.UnicastAddresses) .Where(p => p.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !System.Net.IPAddress.IsLoopback(p.Address)) .ToList(); if (nets.Count > 0) { string[] ip = nets.Where(s => s.IsDnsEligible).Select(s => s.Address.ToString()).ToArray(); return(string.Join(',', ip)); } } catch (Exception ex) { LoggerHelper.Exception(ex); } return(string.Empty); }
public static void RegisterOmnitureAnalyticsScript(Page currentPage, IGlobalContext globalContext) { try { if (globalContext == null || globalContext.CultureConfiguration == null) { throw new ArgumentException("Global Context is null"); // nameof has been removed to fix mobile build } if (globalContext.CultureConfiguration == null) { throw new ArgumentException("Culture Configuration is null"); // nameof has been removed to fix mobile build } string browseScheme = globalContext.CurrentExperience.BrowseScheme.ToString(); AppendCommonItems(currentPage.Title, null, currentPage.Request, currentPage.User.Identity, globalContext.CurrentDistributor, browseScheme); var writer = new StringWriter(); writer.WriteLine(string.Format("<!-- {0} -->", CommonItemsScriptName)); AnalyticsProvider.Render(writer); currentPage.ClientScript.RegisterClientScriptBlock(currentPage.GetType(), CommonItemsScriptName, writer.GetStringBuilder().ToString(), false); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "Error setting Omniture Analytics variables. "); } }
private static Catalog_V01 GetCatalogFromCache(string isoCountryCode) { if (string.IsNullOrEmpty(isoCountryCode)) { return(null); } string cacheKey = GetCacheKey(isoCountryCode); var catalog = HttpRuntime.Cache[cacheKey] as Catalog_V01; if (catalog == null || catalog.Items == null) { try { catalog = LoadCatalogFromService(isoCountryCode); if (catalog != null) { SaveCatalogToCache(cacheKey, catalog); } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex); } } return(catalog); }
private Dictionary <int, string> GetTaxAreaIdFromService(string memberId, DateTime current, int daysToPurge) { var proxy = ServiceClientProvider.GetShippingServiceProxy(); var request = new GetTaxAreaIdListRequest_V01 { Current = current, DaysToPurge = daysToPurge, MemberId = memberId }; try { var response = proxy.GetTaxAreaIdList(new GetTaxAreaIdListRequest1(request)).GetTaxAreaIdListResult; if (null != response && response.Status == ServiceResponseStatusType.Success) { var responseV01 = response as GetTaxAreaIdListResponse_V01; if (null != responseV01) { return(responseV01.TaxAreaIds); } } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "Error occured while getting TaxAreaId for " + memberId); } finally { proxy.Close(); } return(null); }
private static ProductInfoCatalog_V01 GetProductInfoFromCache(string locale) { if (string.IsNullOrEmpty(locale)) { return(null); } locale = locale.Replace('_', '-'); var cacheKey = GetProductInfoCacheKey(locale); var productInfo = HttpRuntime.Cache[cacheKey] as ProductInfoCatalog_V01; if (productInfo == null) { try { productInfo = LoadProductInfoFromService(locale); if (productInfo != null) { HttpRuntime.Cache.Insert(cacheKey, productInfo, null, DateTime.Now.AddMinutes(ProductinfoCacheMinutes), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCategoryCacheRemove); } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex); } } return(productInfo); }
public static bool RescheduleMailing(string distributorID, int mailingID, DateTime?newSendDateUTC) { try { using (var proxy = ServiceProvider.ServiceClientProvider.GetDistributorCRMServiceProxy()) { var response = proxy.SaveMailing(new SaveMailingRequest1(new SaveMailingScheduleRequest { DistributorID = distributorID, MailingID = mailingID, NewSendDate = newSendDateUTC })).SaveMailingResult; if (response.Status == ServiceResponseStatusType.Success) { // expire cache SimpleCache.Expire(typeof(DataTable), mailingHistoryCacheKey(distributorID)); SimpleCache.Expire(typeof(DataTable), mailingHistoryDetailCacheKey(distributorID, mailingID)); return(true); } return(false); } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", new Exception(String.Format("RescheduleMailing distributorID:{0} mailingid:{1} newDate:{2} failed", distributorID, mailingID, newSendDateUTC.HasValue ? newSendDateUTC.Value : DateTime.MaxValue), ex)); return(false); } }
public static int?GetMailingQuotaInPastHours(string distributorID, int numberOfHours) { try { DateTime utcYesterday = DateTime.UtcNow.AddHours(-numberOfHours); TimeSpan durationTime = new TimeSpan(numberOfHours, 0, 0); using (var proxy = ServiceProvider.ServiceClientProvider.GetDistributorCRMServiceProxy()) { var response = proxy.CheckMailingQuota(new CheckMailingQuotaRequest1(new CheckMailingQuotaRequest_V01 { DistributorID = distributorID, StartDate = utcYesterday, Duration = durationTime })).CheckMailingQuotaResult as CheckMailingQuotaResponse_V01; if (response != null && response.Status == ServiceResponseStatusType.Success) { return(response.Count); } else { return(null); } } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", new Exception(String.Format("GetMailingQuotaInLast24Hours distributorID:{0} failed", distributorID), ex)); return(null); } }
public static bool DeleteMailing(string distributorID, params int[] mailingIDs) { try { using (var proxy = ServiceProvider.ServiceClientProvider.GetDistributorCRMServiceProxy()) { var response = proxy.SaveMailing(new SaveMailingRequest1(new SaveMailingStatusRequest { DistributorID = distributorID, MailingIDList = mailingIDs.ToList(), MailingStatus = HL.DistributorCRM.ValueObjects.Email.MailingStatusType.HIDDEN.Key })).SaveMailingResult; if (response.Status == ServiceResponseStatusType.Success) { // expire cache SimpleCache.Expire(typeof(DataTable), mailingHistoryCacheKey(distributorID)); foreach (int mailingID in mailingIDs) { SimpleCache.Expire(typeof(DataTable), mailingHistoryDetailCacheKey(distributorID, mailingID)); } return(true); } return(false); } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", new Exception(String.Format("DeleteMailing distributorID:{0} mailingid count:{1} failed", distributorID, mailingIDs == null ? 0 : mailingIDs.Length), ex)); return(false); } }
public static DataTable GetMailingHistoryDetail(string distributorID, int mailingID) { try { return(SimpleCache.Retrieve( h => { using (var proxy = ServiceProvider.ServiceClientProvider.GetDistributorCRMServiceProxy()) { var response = proxy.GetMailingHistoryDetail(new GetMailingHistoryDetailRequest1(new GetMailingHistoryDetailRequest_V01 { DistributorID = distributorID, MailingID = mailingID })).GetMailingHistoryDetailResult as GetMailingHistoryDetailResponse; //return response.Data; return new DataTable(); } }, mailingHistoryDetailCacheKey(distributorID, mailingID), TimeSpan.FromMinutes(1) )); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", new Exception( String.Format("GetMailingHistoryDetail distributorID:{0} mailingid:{1} failed", distributorID, mailingID), ex)); return(null); } }
public static bool SaveOptOut(int mailingID, int uniqueEmailID, bool optOutFromSender, bool optOutFromAll, string reactivationUrl, string locale) { try { using (var proxy = ServiceProvider.ServiceClientProvider.GetDistributorCRMServiceProxy()) { var response = proxy.SaveOptOut(new SaveOptOutRequest1(new SaveOptOutRequest_V01 { MailingID = mailingID, OptOutFromAll = optOutFromAll, OptOutFromSender = optOutFromSender, UniqueEmailID = uniqueEmailID, OptInUrlTemplate = reactivationUrl, Locale = locale })); return(response != null && response.SaveOptOutResult.Status == ServiceResponseStatusType.Success); } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", new Exception( String.Format("SaveOptOut mailingid:{0} email master ID:{1} sender:{2} all:{3}", mailingID, uniqueEmailID, optOutFromSender, optOutFromAll), ex)); return(false); } }
private static void OnCatalogCacheRemove(string key, object sender, CacheItemRemovedReason reason) { switch (reason) { case CacheItemRemovedReason.Underused: case CacheItemRemovedReason.Expired: try { var parts = key.Split('_'); var result = LoadCatalogFromService(parts[1]); if (result != null) { SaveCatalogToCache(key, result); } else { SaveCatalogToCache(key, (Catalog_V01)sender); } } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex); } break; } }
/// <summary> /// 参数转为对象T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> public T GetPostObject <T>(string name = "") { string json; try { if (string.IsNullOrEmpty(name)) { if (!_bodyJson.IsEmpty()) { return(_bodyJson.ToObject <T>()); } } else { json = GetPostString(name); return(json.ToObject <T>()); } } catch (Exception ex) { LoggerHelper.Exception(ex); } return(default(T)); }
/// <summary> /// Registers script emmitting newly added cart items /// </summary> /// <param name="currentPage"></param> /// <param name="cartItems"></param> /// <param name="addedItems"></param> public static void RegisterOmnitureAddCartScript(Page currentPage, List <DistributorShoppingCartItem> cartItems, List <ShoppingCartItem_V01> addedItems) { try { if (addedItems == null || cartItems == null) { return; } var items = new List <object>(); foreach (var addedItem in addedItems.Join( cartItems, sci => sci.SKU, dsci => dsci.SKU, (s1, s2) => s1)) { var analyticsCartItem = CreateAnalyticsCartItem(addedItem.SKU, addedItem.Quantity, 0, null, 0, 0); items.Add(analyticsCartItem); } AnalyticsProvider.Set(AnalyticsFact.AddedToCart, items); var writer = new StringWriter(); writer.WriteLine(string.Format("<!-- {0} -->", AddedCartItemScriptName)); AnalyticsProvider.Render(writer); currentPage.ClientScript.RegisterStartupScript(currentPage.GetType(), AddedCartItemScriptName, writer.GetStringBuilder().ToString()); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "Error setting Omniture Analytics variables Added To Cart:"); } }
public void OnException(ExceptionContext context) { if (context.ExceptionHandled == false) { LoggerHelper.Exception(context.Exception); //context.Result = new ContentResult //{ // Content =JsonConvert.SerializeObject(result), // StatusCode = StatusCodes.Status500InternalServerError, // ContentType = "text/html;charset=utf-8" //}; context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; //var requestHelper = AutofacUtil.GetScopeService<IAtlassRequest>(); //if (requestHelper.IsAjax()) //{ // var result = new { status = false, msg = "系统异常,请稍后再试" }; // context.Result = new JsonResult(result); //} //else //{ // context.Result = new RedirectResult("~/Login/InternalError"); //} } context.ExceptionHandled = true; //异常已处理了 }
public static List <CustomShippingMethodViewModel> GetCustomShippingMethods(string memberId, ShippingAddress_V01 address, string locale) { try { var country = locale.Substring(3); var shippingProvider = ShippingProvider.GetShippingProvider(locale.Substring(3)); if (shippingProvider == null) { return(null); } var deliveryOptions = shippingProvider.GetDeliveryOptionsListForMobileShipping(country, locale, address, memberId); if (null == deliveryOptions || !deliveryOptions.Any()) { return(null); } var customShippingModels = deliveryOptions.Select(option => new CustomShippingMethodViewModel { Code = option.FreightCode, Title = option.Description, OrderTypes = "RSO" }).ToList(); return(customShippingModels); } catch (Exception ex) { LoggerHelper.Exception("General", ex, "Failed while getting mobile GetCustomShippingMethods"); return(null); } }
private static string IncludeDirectory = "Template/include"; //包含文件 /// <summary> /// 模板生成 /// </summary> /// <param name="templateType">模板类型,1-首页,2-栏目,3-内容页,4-单页</param> /// <param name="templateName">模板文件名称</param> /// <param name="templateContent">模板内容</param> public static void Create(int templateType, string templateName, string templateContent) { try { switch (templateType) { case 1: CreateHome(templateName, templateContent); break; case 2: CreateChannel(templateName, templateContent); break; case 3: CreateContent(templateName, templateContent); break; case 4: // CreateContent(templateName, templateContent); break; case 5: CreateInclude(templateName, templateContent); break; default: break; } }catch (Exception ex) { LoggerHelper.Exception(ex); } }
public string GetTaxAreaId(string postalCode) { try { if (string.IsNullOrEmpty(postalCode)) { return(string.Empty); } if (null == taxAreaIds || taxAreaIds.Count == 0) { return(string.Empty); } if (taxAreaIds.ContainsKey(postalCode)) { return(taxAreaIds[postalCode]); } return(string.Empty); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "GetTaxAreaId " + postalCode); return(string.Empty); } }
public ActionResult Index(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, _wxSetting.Token)) { return(Content("参数错误!")); } #region 打包 PostModel 信息 postModel.Token = _wxSetting.Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = _wxSetting.EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = _wxSetting.WeixinAppId; //根据自己后台的设置保持一致(必须提供) #endregion try { var messageHandler = new CustomMessageHandler(RequestHelper.Request().GetRequestMemoryStream(), postModel, 10); messageHandler.Execute(); //执行微信处理过程 //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(Content(messageHandler.ResponseDocument.ToString())); } catch (Exception ex) { LoggerHelper.Exception(ex); return(Content("")); } }
public bool SetTaxAreadId(string postalCode, string taxAreaId) { try { if (null == taxAreaIds) { taxAreaIds = new Dictionary <string, string>(); } if (string.IsNullOrEmpty(postalCode) || string.IsNullOrEmpty(taxAreaId)) { return(false); } if (taxAreaIds.ContainsKey(postalCode)) { return(false); } taxAreaIds.Add(postalCode, taxAreaId); return(true); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "SetTaxAreadId " + postalCode + " " + taxAreaId); return(false); } }
/// <summary> ///异常处理 /// </summary> /// <param name="context"></param> /// <param name="exception"></param> /// <returns></returns> private static async Task HandleExceptionAsync(HttpContext context, System.Exception exception) { if (exception == null) { return; } LoggerHelper.Exception(exception); await WriteExceptionAsync(context, exception).ConfigureAwait(false); }
internal void Start() { int origin = Interlocked.CompareExchange(ref _state, _connecting, _none); if (origin == _disposed) { throw new ObjectDisposedException("This tcp socket session has been disposed when connecting."); } else if (origin != _none) { throw new InvalidOperationException("This tcp socket session is in invalid state when connecting."); } try { _stream = NegotiateStream(_tcpClient.GetStream()); if (_receiveBuffer == default(ArraySegment <byte>)) { _receiveBuffer = _bufferManager.BorrowBuffer(); } _receiveBufferOffset = 0; if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting) { Close(false); //connecting with wrong state throw new ObjectDisposedException("This tcp socket session has been disposed after connected."); } bool isErrorOccurredInUserSide = false; try { _server.RaiseClientConnected(this); } catch (Exception ex) { isErrorOccurredInUserSide = true; HandleUserSideError(ex); } if (!isErrorOccurredInUserSide) { ContinueReadBuffer(); } else { Close(true); //user side handle tcp connection error occurred } } catch (Exception ex)// catch exceptions then log then re-throw { _log.Exception(ex); Close(true); // handle tcp connection error occurred throw; } }
public void ConfigureContainer(ContainerBuilder builder) { try { builder.RegisterModule(new AtlassAutofacDI()); } catch (Exception e) { LoggerHelper.Exception(e); } }
public static int ActivityLog(object request, object response, string distributorID, bool isSuccess, string url, string HLHeaders, string userAgent, string locale) { try { var proxy = ServiceClientProvider.GetMobileAnalyticsServiceProxy(); var requestSvc = new InsertActivityLogRequest { ActivityTypeID = 28, PlatformTypeID = 1, EventTypeID = 2, Success = isSuccess, OrderNumber = string.Empty, DistributorID = distributorID, Locale = locale, Protocol = 0,//protocol, OrderRequest = JsonConvert.SerializeObject(request), RawUrl = url, RawHeaders = HLHeaders, RawResponse = JsonConvert.SerializeObject(response), OrderRequestXml = null, OrderResponseXml = null, UserAgent = userAgent ?? string.Empty, AppName = "WebApiOrdering" }; //Clean Credit Card Info //requestSvc.OrderRequest = CleanCreditCardInfo(requestSvc.OrderRequest); //requestSvc.RawResponse = CleanCreditCardInfo(requestSvc.RawResponse); using (proxy) { int activityLogId = 0; var proxyResponse = proxy.InsertActivityLog(new InsertActivityLogRequest1(requestSvc)).InsertActivityLogResult; if (proxyResponse.ActivityLogId != null) { activityLogId = (int)proxyResponse.ActivityLogId; } return(activityLogId); } } catch (Exception ex) { LoggerHelper.Exception("General", ex, "ActivityLog exception"); return(0); } }
public IActionResult UpdateAvatar() { var user = RequestHelper.AdminInfo(); var files = RequestHelper.Request().Form.Files; if (files.Count == 0) { return(Error("上传失败")); } string url = $"/upfiles/heads"; var folder = GlobalParamsDto.WebRoot + url; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var file = files[0]; var extName = FileUtils.GetExtensionByContentType(file.ContentType.ToLower()); string guidFileName = IdHelper.ObjectId() + extName; //这个hostingEnv.WebRootPath就是要存的地址可以改下 string filename = $"{folder}/{guidFileName}"; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } string imgurl = $"{url}/{guidFileName}"; if (user.Avatar != "/ui/images/profile.jpg") { string oldAvatar = GlobalParamsDto.WebRoot + user.Avatar; try { if (System.IO.File.Exists(oldAvatar)) { System.IO.File.Delete(oldAvatar); } }catch (Exception ex) { LoggerHelper.Exception(ex); } } _userApp.UpdateAvatar(user.LoginName, imgurl); user.Avatar = imgurl; string claimstr = user.ToJson(); RequestHelper.SetCookie(claimstr); return(Success("头像已更新")); }
public static List <MobileSandboxResponseViewModel> GetSandboxEvents(int page, int pageSize, string distributorId, string locale, string appName, DateTime startDate, DateTime endDate) { var proxy = ServiceClientProvider.GetMobileAnalyticsServiceProxy(); var response = new List <MobileSandboxResponseViewModel>(); try { var request = new GetActivityLogRequest { AppName = appName, StartDate = startDate, EndDate = endDate, Locale = locale, DistributorId = distributorId, Page = page, PageSize = pageSize }; using (proxy) { var ActivityLog = proxy.GetActivityLog(new GetActivityLogRequest1(request)).GetActivityLogResult; response = ActivityLog.Select(x => new MobileSandboxResponseViewModel { ActivityLogID = x.activityLogId, ActivityTypeID = x.activityTypeId, ActivityTypeDesc = x.ActivityTypeDesc, AppName = x.AppName, CreatedDate = x.CreatedDate, DistributorId = x.DistributorId, EventTypeID = x.EventTypeID, Locale = x.Locale, OrderNumber = x.OrderNumber, OrderRequest = x.OrderRequest, OrderRequestXml = x.OrderRequestXml, OrderResponseXml = x.OrderResponseXml, PlatformTypeID = x.PlatformTypeID, RawHeaders = x.RawHeaders, RawResponse = x.RawResponse, RawUrl = x.RawUrl, Success = x.Success, UserAgent = x.UserAgent } ).ToList(); } } catch (Exception ex) { LoggerHelper.Exception("General", ex, "GetSandboxEvents exception"); } return(response); }
public int InsertToPaymentGatewayRecord(OrderViewModel orderViewModel, Guid authToken, ref decimal amount) { try { var errors = new List <ValidationErrorViewModel>(); var myHlShoppingCart = _mobileQuoteHelper.PriceCart(ref orderViewModel, ref errors); if (null != errors && errors.Any()) { return(0); } var orderTotalsV01 = myHlShoppingCart.Totals as ServiceProvider.OrderSvc.OrderTotals_V01; var orderTotalsV02 = myHlShoppingCart.Totals as ServiceProvider.OrderSvc.OrderTotals_V02; var order = MobileOrderProvider.ModelConverter.ConvertOrderViewModelToOrderV01(orderViewModel, ref errors, orderTotalsV02, orderTotalsV01, out amount); var countryCode = orderViewModel.Locale.Substring(3, 2); if (amount > 0) { var orderNumber = GetOrderNumber(amount, countryCode, orderViewModel.OrderMemberId); orderViewModel.OrderNumber = orderNumber; } else { return(0); } var btOrder = OrderProvider.CreateOrder(order, myHlShoppingCart, countryCode, null, "Mobile"); if (((ServiceProvider.SubmitOrderBTSvc.Order)btOrder).Payments != null) { ((ServiceProvider.SubmitOrderBTSvc.Order)btOrder).OrderID = orderViewModel.OrderNumber; ((ServiceProvider.SubmitOrderBTSvc.Order)btOrder).Payments[0].NumberOfInstallments = 1; ((ServiceProvider.SubmitOrderBTSvc.Order)btOrder).Payments[0].NameOnAccount = "China User"; ((ServiceProvider.SubmitOrderBTSvc.Order)btOrder).Payments[0].Currency = "RMB"; } var holder = OrderProvider.GetSerializedOrderHolder(btOrder, order, myHlShoppingCart, authToken == Guid.Empty ? Guid.NewGuid() : authToken); var orderData = OrderSerializer.SerializeOrder(holder); return(OrderProvider.InsertPaymentGatewayRecord(orderViewModel.OrderNumber, orderViewModel.MemberId, "WechatPayment", orderData, orderViewModel.Locale)); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "Exception in InsertToPaymentGatewayRecord method MobileWechatProvider"); return(0); } }
/// <summary> /// cpu使用率 /// </summary> /// <returns></returns> public string GetCPURate() { //string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage"); //string cpuRate = output.Replace("LoadPercentage", string.Empty).Trim(); try { //ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor"); //var cpuTimes = searcher.Get() // .Cast<ManagementObject>() // .Select(mo => new // { // Name = mo["Name"], // Usage = mo["PercentProcessorTime"] // }).ToList(); //var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage); //var cpuUsage = query.SingleOrDefault(); //if (cpuUsage == null) //{ // return "0"; //} //return cpuUsage.ToString() + "%"; var startTime = DateTime.UtcNow; var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; var stopWatch = new Stopwatch(); // Start watching CPU stopWatch.Start(); // Meansure something else, such as .Net Core Middleware Thread.Sleep(100); // Stop watching to meansure stopWatch.Stop(); var endTime = DateTime.UtcNow; var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds; var totalMsPassed = (endTime - startTime).TotalMilliseconds; var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed); var cpuUsagePercentage = cpuUsageTotal * 100; return(cpuUsagePercentage.ToString()); } catch (Exception ex) { LoggerHelper.Exception(ex); } return(""); }
/// <summary> /// 返回渲染后的页面文件 /// </summary> /// <param name="content"></param> /// <param name="template"></param> /// <returns></returns> public (bool genStatus, string contentHtml) GenerateContentHtml(int channelId, int id) { try { Stopwatch watcher = new Stopwatch(); watcher.Start(); var templateModel = ChannelManagerCache.GetContentTemplate(channelId); if (templateModel == null) { return(false, ""); } var content = _contentApp.GetContentInfo(id); if (content == null) { return(false, ""); } //加载模板 先取缓存,没有再初始化一个并且加入缓存 this.Document = RenderDocumentCache.GetRenderDocument(templateModel.id); if (this.Document == null) { string templateFile = Path.Combine(GlobalContext.WebRootPath, templateModel.template_file); this.Document = new TemplateDocument(templateModel.template_content, GlobalContext.WebRootPath, templateFile); RenderDocumentCache.AddRenderDocument(templateModel.id, this.Document); } this.Document.Variables.SetValue("this", this); //站点基本信息 var site = SiteManagerCache.GetSiteInfo(); this.Document.Variables.SetValue("site", site); //设置顶部导航条数据 var navigations = _contentApp.GetChannelTree(); this.Document.Variables.SetValue("navigations", navigations); //获取当前文章信息 this.Document.Variables.SetValue("content", content); string renderHtml = this.Document.GetRenderText(); renderHtml = HtmlPlayerHandler.CreateVideo(renderHtml); watcher.Stop(); string msg = $"渲染内容页耗时:{watcher.ElapsedMilliseconds} ms"; LoggerHelper.Info(msg); return(true, renderHtml); } catch (Exception ex) { LoggerHelper.Exception(ex); } return(false, ""); }
internal List <ContactViewModel> Get(string id) { try { var model = _contactsSource.GetContacts(id); return(model); } catch (Exception ex) { LoggerHelper.Exception("Error", ex, "Failed loading contactsViewModel list for id" + id); } return(null); }
public static void RegisterOmnitureCartScript(Page currentPage, OrderTotals_V01 totals, List <DistributorShoppingCartItem> shoppingCartItems, string eventState) { try { AppendCartItems(totals, shoppingCartItems, eventState); var writer = new StringWriter(); writer.WriteLine(string.Format("<!-- {0} -->", CartItemListScriptName)); AnalyticsProvider.Render(writer); currentPage.ClientScript.RegisterClientScriptBlock(currentPage.GetType(), CartItemListScriptName, writer.GetStringBuilder().ToString(), false); } catch (Exception ex) { LoggerHelper.Exception("System.Exception", ex, "Error setting Omniture Analytics variables:"); } }