Пример #1
0
 public static Image GetImageFromUrl(string url)
 {
     var h = new WebHelper(url);
     string contentType;
     byte[] data = h.ReadAllBytesFromUrl(new Uri(url), out contentType);
     return Bitmap.FromStream(new MemoryStream(data));
 }
        public BookingRequestController(ILog log, WebHelper webHelper)
        {
            _log = log;
            _webHelper = webHelper;

            Mapper.CreateMap<BookingRequest, UpdateStatusViewModel>();
        }
Пример #3
0
        public DownloadManager()
        {
            _webHelper = new WebHelper();

            DownLoadThreadPool = new SmartThreadPool();

            _downloadJobDict = HPPClient.DownloadJobDict;
        }
 public virtual Task<dynamic> ExecuteAsync()
 {
     var helper = new WebHelper(Credentials, BaseUrl);
     switch (Method)
     {
         case "GET":
             return helper.Get(BuildQuery(QueryParameters), Path, BuildHeaders(HeaderParameters));
         case "POST":
             return helper.PostQuery(BuildQuery(QueryParameters), Path, BuildHeaders(HeaderParameters));
         default:
             throw new SdkException("No appropriate HTTP method found for this request.");
     }
 }
Пример #5
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="serverPort">Port to start server on</param>
 public HttpServer(int serverPort)
 {
     helper = new WebHelper();
     listener = new StreamSocketListener();
     port = serverPort;
     listener.ConnectionReceived += (s, e) =>
     {
         try
         {
             // Process incoming request
             processRequestAsync(e.Socket);
         }catch(Exception ex)
         {
             Debug.WriteLine("Exception in StreamSocketListener.ConnectionReceived(): " + ex.Message);
         }
     };
 }
Пример #6
0
 public FormConfig()
 {
     InitializeComponent();
     this.Text = String.Format("esozh - v{0}", System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString());
     // init worker thread
     worker = new Worker(this);
     worker.UpdateText += delegate(String text)
     {
         this.BeginInvoke((Worker.UpdateTextDelegate)UpdateText, text);
     };
     webHelper = new WebHelper();
     if (webHelper.Port > 0)
     {
         webHelper.Run();
         textBoxPort.Text = webHelper.Port.ToString();
     }
     workerThread = new Thread(worker.Run);
     workerThread.Start();
     // load settings
     textBoxAppKey.Text = Properties.Settings.Default.appKey;
 }
Пример #7
0
        static HPPClient()
        {
            ClientThreadPool = new SmartThreadPool();
            HashFullNameDict = GetSerializeObject(DAT_HASH_FULLNAME) as Dictionary<string, string> ?? new Dictionary<string, string>();

            KnownDict = GetSerializeObject(DAT_HASH_KNOWN) as HashSet<string> ?? new HashSet<string>();

            DownloadJobDict = GetSerializeObject(DAT_HASH_JOB) as Dictionary<string, DownloadJob> ??
                              new Dictionary<string, DownloadJob>();

            _server = new CSServer(NUM_CONNECTION, Int16.MaxValue);
            _hashCalc = new HashCalculator(new Hash_MD5(), ClientThreadPool);

            _webHelper = new WebHelper();
            Sharedir = GetShareDir();
            DownloadManager = new DownloadManager();

            _serverIpEndPoint = new IPEndPoint(IPAddress.Any, 9998);

            _csServerIPEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.100"), 9999);
        }
Пример #8
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="serverPort">Port to start server on</param>
        internal HttpInterfaceManager(int serverPort, IPlaybackManager playbackManager, IPlaylistManager playlistManager, IDevicePowerManager powerManager)
        {
            this.playbackManager = playbackManager;
            this.playlistManager = playlistManager;
            this.powerManager = powerManager;

            helper = new WebHelper();
            listener = new StreamSocketListener();
            port = serverPort;
            listener.ConnectionReceived += (s, e) =>
            {
                try
                {
                    // Process incoming request
                    processRequestAsync(e.Socket);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception in StreamSocketListener.ConnectionReceived(): " + ex.Message);
                }
            };
        }
Пример #9
0
 public void QueueSettings(bool ruleChange = true)
 {
     var wc = new WebContextProxy();
     #if WEB
     var wh = new WebHelper();
     wc = wh.GetContextOfRequest();
     #endif
     Task.Factory.StartNew(() => SaveSettings(wc, ruleChange));
 }
Пример #10
0
 public void LoadUserScoreSheetList()
 {
     try
     {
         mListScoreSheetItems = new List <BasicScoreSheetItem>();
         WebRequest webRequest = new WebRequest();
         webRequest.Code    = (int)S3103Codes.GetUserScoreSheetList;
         webRequest.Session = CurrentApp.Session;
         webRequest.ListData.Add(selTaskRecord.RecoredReference.ToString());
         //if (selTaskRecord.TaskType == "2" || selTaskRecord.TaskType == "4")//如果是自动任务分配,在去匹配座席ID
         //{
         //    var item = App.ListCtrolAgentInfos.Where(a => a.AgentName == selTaskRecord.AgtOrExtID).FirstOrDefault();
         //    webRequest.ListData.Add(item.AgentID);
         //}
         //else
         //{
         //}
         webRequest.ListData.Add(selTaskRecord.AgtOrExtID);
         webRequest.ListData.Add("0");
         webRequest.ListData.Add(selTaskRecord.TaskID.ToString());
         //  Service31031Client client = new Service31031Client();
         Service31031Client client = new Service31031Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session), WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service31031"));
         //WebHelper.SetServiceClient(client);
         WebReturn webReturn = client.UMPTaskOperation(webRequest);
         client.Close();
         if (!webReturn.Result)
         {
             ShowException(string.Format("Fail.\t{0}\t{1}", webReturn.Code, webReturn.Message));
             return;
         }
         if (webReturn.ListData == null)
         {
             ShowException(string.Format("Fail.\tListData is null"));
             return;
         }
         for (int i = 0; i < webReturn.ListData.Count; i++)
         {
             string          strInfo   = webReturn.ListData[i];
             OperationReturn optReturn = XMLHelper.DeserializeObject <BasicScoreSheetInfo>(strInfo);
             if (!optReturn.Result)
             {
                 ShowException(string.Format("Fail.\t{0}\t{1}", optReturn.Code, optReturn.Message));
                 return;
             }
             BasicScoreSheetInfo info = optReturn.Data as BasicScoreSheetInfo;
             if (info == null)
             {
                 ShowException(string.Format("Fail.\tBaiscScoreSheetInfo is null"));
                 return;
             }
             BasicScoreSheetItem item = new BasicScoreSheetItem(info);
             item.RowNumber  = i + 1;
             item.Background = GetScoreSheetBackground(item);
             if (selTaskRecord.TaskType == "3" || selTaskRecord.TaskType == "4")
             {
                 if (item.ScoreSheetID == oldTemplateID)
                 {
                     item.Title = string.Format("({0})", CurrentApp.GetLanguageInfo("3103T00183", "1st Task")) + item.Title;
                 }
             }
             if (ParentPage.mViewScore)
             {
                 if (item.ScoreSheetID == selTaskRecord.TemplateID)
                 {
                     mListScoreSheetItems.Add(item);
                 }
             }
             else
             {
                 mListScoreSheetItems.Add(item);
             }
         }
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
Пример #11
0
        public ActionResult Add(UserModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                ModelState.AddModelError("Password", "密码不能为空");
            }

            if (AdminUsers.IsExistUserName(model.UserName))
            {
                ModelState.AddModelError("UserName", "名称已经存在");
            }

            if (AdminUsers.IsExistEmail(model.Email))
            {
                ModelState.AddModelError("Email", "email已经存在");
            }

            if (AdminUsers.IsExistMobile(model.Mobile))
            {
                ModelState.AddModelError("Mobile", "手机号已经存在");
            }

            if (ModelState.IsValid)
            {
                string salt = Users.GenerateUserSalt();
                string nickName;
                if (string.IsNullOrWhiteSpace(model.NickName))
                {
                    nickName = "bma" + Randoms.CreateRandomValue(7);
                }
                else
                {
                    nickName = model.NickName;
                }

                UserInfo userInfo = new UserInfo()
                {
                    UserName      = model.UserName,
                    Email         = model.Email == null ? "" : model.Email,
                    Mobile        = model.Mobile == null ? "" : model.Mobile,
                    Salt          = salt,
                    Password      = Users.CreateUserPassword(model.Password, salt),
                    UserRid       = model.UserRid,
                    StoreId       = 0,
                    MallAGid      = model.MallAGid,
                    NickName      = WebHelper.HtmlEncode(nickName),
                    Avatar        = model.Avatar == null ? "" : WebHelper.HtmlEncode(model.Avatar),
                    PayCredits    = model.PayCredits,
                    RankCredits   = AdminUserRanks.GetUserRankById(model.UserRid).CreditsLower,
                    VerifyEmail   = 0,
                    VerifyMobile  = 0,
                    LiftBanTime   = UserRanks.IsBanUserRank(model.UserRid) ? DateTime.Now.AddDays(WorkContext.UserRankInfo.LimitDays) : new DateTime(1900, 1, 1),
                    LastVisitTime = DateTime.Now,
                    LastVisitIP   = WorkContext.IP,
                    LastVisitRgId = WorkContext.RegionId,
                    RegisterTime  = DateTime.Now,
                    RegisterIP    = WorkContext.IP,
                    RegisterRgId  = WorkContext.RegionId,
                    Gender        = model.Gender,
                    RealName      = model.RealName == null ? "" : WebHelper.HtmlEncode(model.RealName),
                    Bday          = model.Bday ?? new DateTime(1970, 1, 1),
                    IdCard        = model.IdCard == null ? "" : model.IdCard,
                    RegionId      = model.RegionId,
                    Address       = model.Address == null ? "" : WebHelper.HtmlEncode(model.Address),
                    Bio           = model.Bio == null ? "" : WebHelper.HtmlEncode(model.Bio)
                };

                AdminUsers.CreateUser(userInfo);
                AddMallAdminLog("添加用户", "添加用户,用户为:" + model.UserName);
                return(PromptView("用户添加成功"));
            }
            Load(model.RegionId);

            return(View(model));
        }
Пример #12
0
 public OperatorModel GetCurrent()
 {
     return(DESEncrypt.Decrypt(WebHelper.GetSession(LoginUserKey)).ToObject <OperatorModel>());
 }
Пример #13
0
        public void DownloadStringTest()
        {
            var result = WebHelper.DownloadString(new Uri(@"https://www.google.com/"), clientId: "UNITTEST2");

            Assert.IsTrue(string.IsNullOrEmpty(result) == false);
        }
Пример #14
0
 public GoogleWeather()
 {
     webHelper = new WebHelper();
 }
Пример #15
0
        private void GetCurrentKeyGenServer()
        {
            Service24011Client client = null;

            try
            {
                WebReturn  webReturn  = null;
                WebRequest webRequest = new WebRequest();
                webRequest.Code    = (int)S2400RequestCode.GetCurrentKeyGenServer;
                webRequest.Session = CurrentApp.Session;
                client             = new Service24011Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session),
                                                            WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service24011"));
                webReturn = client.DoOperation(webRequest);
                CurrentApp.MonitorHelper.AddWebReturn(webReturn);
                if (!webReturn.Result)
                {
                    ShowException(string.Format("WSFail.\t{0}\t{1}", webReturn.Code, CurrentApp.GetLanguageInfo(webReturn.Code.ToString(), webReturn.Message)));
                    return;
                }
                if (webReturn.Result && string.IsNullOrEmpty(webReturn.Data))
                {
                    HasKeyGenServer = false;
                    return;
                }
                OperationReturn optReturn = XMLHelper.DeserializeObject <KeyGenServerEntry>(webReturn.Data.ToString());
                if (!optReturn.Result)
                {
                    HasKeyGenServer = false;
                    return;
                }
                KeyGenServerEntry keyGenServer = optReturn.Data as KeyGenServerEntry;
                //尝试连接服务 如果能连接成功 就显示可用的服务
                webRequest         = new WebRequest();
                webRequest.Code    = (int)S2400RequestCode.TryConnToKeyGenServer;
                webRequest.Session = CurrentApp.Session;
                webRequest.ListData.Add(keyGenServer.HostAddress);
                webRequest.ListData.Add(keyGenServer.HostPort);
                client = new Service24011Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session),
                                                WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service24011"));
                webReturn = client.DoOperation(webRequest);
                CurrentApp.MonitorHelper.AddWebReturn(webReturn);
                if (!webReturn.Result)
                {
                    HasKeyGenServer = false;
                    return;
                }

                HasKeyGenServer = true;
                keyGenEntry     = keyGenServer;
            }
            catch (Exception ex)
            {
                ShowException(ex.Message);
            }
            finally
            {
                if (client != null)
                {
                    if (client.State == System.ServiceModel.CommunicationState.Opened)
                    {
                        client.Close();
                    }
                }
            }
        }
Пример #16
0
        /// <summary>
        /// 启用或禁用策略
        /// </summary>
        /// <param name="strOptType">1 : 启用   2:禁用</param>
        private void EnableDisablePolicy(string strOptType)
        {
            if (lvEncryptionPolicyObject.SelectedItem == null)
            {
                return;
            }
            PolicyInfoInList   policyInList = lvEncryptionPolicyObject.SelectedItem as PolicyInfoInList;
            Service24021Client client       = null;

            try
            {
                WebRequest webRequest = new WebRequest();
                switch (strOptType)
                {
                case "1":
                    if (policyInList.PolicyIsEnabled == "1")
                    {
                        return;
                    }
                    webRequest.Code = (int)S2400RequestCode.EnablePolicy;
                    break;

                case "2":
                    if (policyInList.PolicyIsEnabled == "2")
                    {
                        return;
                    }
                    webRequest.Code = (int)S2400RequestCode.DisablePolicy;
                    break;
                }

                webRequest.Session = CurrentApp.Session;
                webRequest.ListData.Add(policyInList.PolicyID);
                client = new Service24021Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session),
                                                WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service24021"));
                WebReturn webReturn = client.DoOperation(webRequest);
                CurrentApp.MonitorHelper.AddWebReturn(webReturn);
                if (!webReturn.Result)
                {
                    ShowException(string.Format("WSFail.\t{0}\t{1}", webReturn.Code, CurrentApp.GetLanguageInfo(webReturn.Code.ToString(), webReturn.Message)));
                    return;
                }

                //写日志
                string strLog = string.Empty;
                if (strOptType == "1")
                {
                    strLog = string.Format("{0}{1}{2}", CurrentApp.Session.UserInfo.UserName, Utils.FormatOptLogString(string.Format("FO2402001")), policyInList.PolicyID);
                    CurrentApp.WriteOperationLog("2402001", ConstValue.OPT_RESULT_SUCCESS, strLog);
                }
                else if (strOptType == "2")
                {
                    strLog = string.Format("{0}{1}{2}", CurrentApp.Session.UserInfo.UserName, Utils.FormatOptLogString(string.Format("FO2402002")), policyInList.PolicyID);
                    CurrentApp.WriteOperationLog("2402002", ConstValue.OPT_RESULT_SUCCESS, strLog);
                }

                policyInList.PolicyIsEnabled = strOptType;
                if (strOptType == "1")
                {
                    UpdatePolicyList(policyInList, OperationType.Enable);
                }
                else
                {
                    UpdatePolicyList(policyInList, OperationType.Disable);
                }
            }
            catch (Exception ex)
            {
                ShowException(ex.Message);
                string strLog = string.Empty;
                if (strOptType == "1")
                {
                    strLog = string.Format("{0}{1}{2}", CurrentApp.Session.UserInfo.UserName, Utils.FormatOptLogString(string.Format("FO2402001")), policyInList.PolicyID);
                    CurrentApp.WriteOperationLog("2402001", ConstValue.OPT_RESULT_FAIL, strLog);
                }
                else if (strOptType == "2")
                {
                    strLog = string.Format("{0}{1}{2}", CurrentApp.Session.UserInfo.UserName, Utils.FormatOptLogString(string.Format("FO2402002")), policyInList.PolicyID);
                    CurrentApp.WriteOperationLog("2402002", ConstValue.OPT_RESULT_FAIL, strLog);
                }
            }
            finally
            {
                if (client != null)
                {
                    if (client.State == System.ServiceModel.CommunicationState.Opened)
                    {
                        client.Close();
                    }
                }
            }
        }
Пример #17
0
        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            #region Save as

            var save = new Microsoft.Win32.SaveFileDialog
            {
                FileName   = "ScreenToGif " + Global.UpdateModel.Version + (IsInstaller ? " Setup" : ""),
                DefaultExt = IsInstaller ? ".msi" : ".exe",
                Filter     = IsInstaller ? "ScreenToGif setup|*.msi" : "ScreenToGif executable|*.exe"
            };

            var result = save.ShowDialog();

            if (!result.HasValue || !result.Value)
            {
                return;
            }

            if (save.FileName == Assembly.GetExecutingAssembly().Location)
            {
                Dialog.Ok(Title, LocalizationHelper.Get("Update.Filename.Warning"), LocalizationHelper.Get("Update.Filename.Warning2"), Icons.Warning);
                return;
            }

            #endregion

            //After downloading, remove the notification and set the global variable to null;

            DownloadButton.IsEnabled = false;
            StatusBand.Info("Downloading...");
            DownloadProgressBar.Visibility = Visibility.Visible;

            var tempFilename = !IsInstaller?save.FileName.Replace(".exe", DateTime.Now.ToString(" hh-mm-ss fff") + ".zip") : save.FileName;

            #region Download

            try
            {
                using (var webClient = new WebClient())
                {
                    webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                    webClient.Proxy       = WebHelper.GetProxy();

                    await webClient.DownloadFileTaskAsync(new Uri(IsInstaller ? Global.UpdateModel.InstallerDownloadUrl : Global.UpdateModel.PortableDownloadUrl), tempFilename);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Download updates");

                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;
                StatusBand.Hide();

                Dialog.Ok("Update", "Error while downloading", ex.Message);
                return;
            }

            #endregion

            //If cancelled.
            if (!IsLoaded)
            {
                StatusBand.Hide();
                return;
            }

            #region Installer

            if (IsInstaller)
            {
                if (!Dialog.Ask(Title, LocalizationHelper.Get("Update.Install.Header"), LocalizationHelper.Get("Update.Install.Description")))
                {
                    return;
                }

                try
                {
                    Process.Start(tempFilename);
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Starting the installer");
                    StatusBand.Hide();

                    Dialog.Ok(Title, "Error while starting the installer", ex.Message);
                    return;
                }

                Global.UpdateModel = null;
                Environment.Exit(25);
            }

            #endregion

            #region Unzip

            try
            {
                //Unzips the only file.
                using (var zipArchive = ZipFile.Open(tempFilename, ZipArchiveMode.Read))
                    zipArchive.Entries.First(x => x.Name.EndsWith(".exe")).ExtractToFile(save.FileName, true);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Unziping update");

                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;
                StatusBand.Hide();

                Dialog.Ok("Update", "Error while unzipping", ex.Message);
                return;
            }

            #endregion

            Global.UpdateModel = null;

            #region Delete temporary zip and run

            try
            {
                File.Delete(tempFilename);

                Process.Start(save.FileName);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Finishing update");

                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;
                StatusBand.Hide();

                Dialog.Ok(Title, "Error while finishing the update", ex.Message);
                return;
            }

            #endregion

            GC.Collect();
            DialogResult = true;
        }
Пример #18
0
        /// <summary>
        /// 获得所有的加密策略
        /// </summary>
        private void GetAllPolicies()
        {
            lstAllPolicies.Clear();
            Service24021Client client = null;

            try
            {
                WebRequest webRequest = new WebRequest();
                webRequest.Code    = (int)S2400RequestCode.GetAllPolicies;
                webRequest.Session = CurrentApp.Session;
                webRequest.ListData.Add(CurrentApp.Session.UserInfo.UserID.ToString());
                client = new Service24021Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session),
                                                WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service24021"));
                WebReturn webReturn = client.DoOperation(webRequest);
                CurrentApp.MonitorHelper.AddWebReturn(webReturn);
                if (!webReturn.Result)
                {
                    ShowException(string.Format("WSFail.\t{0}\t{1}", webReturn.Code, CurrentApp.GetLanguageInfo(webReturn.Code.ToString(), webReturn.Message)));
                    return;
                }
                if (webReturn.DataSetData.Tables.Count <= 0)
                {
                    return;
                }
                DataTable        dt         = webReturn.DataSetData.Tables[0];
                PolicyInfoInList policyItem = null;
                foreach (DataRow row in dt.Rows)
                {
                    policyItem            = new PolicyInfoInList();
                    policyItem.PolicyID   = row["C001"].ToString();
                    policyItem.PolicyName = row["C002"].ToString();
                    //= row["004"].ToString();
                    string strType = row["C004"].ToString();
                    policyItem.PolicyType = strType == "U" ? CurrentApp.GetLanguageInfo("2402003", "Custom (user input)") : CurrentApp.GetLanguageInfo("2402002", "Periodic update key (randomly generated)");
                    if (strType == "C")
                    {
                        string strOccursFrequency = row["C007"].ToString();
                        switch (strOccursFrequency)
                        {
                        case "D":
                            policyItem.PolicyOccursFrequency = CurrentApp.GetLanguageInfo("2402ComboTagD", "Day");
                            break;

                        case "W":
                            policyItem.PolicyOccursFrequency = CurrentApp.GetLanguageInfo("2402ComboTagW", "Week");
                            break;

                        case "M":
                            policyItem.PolicyOccursFrequency = CurrentApp.GetLanguageInfo("2402ComboTagM", "Month");
                            break;

                        case "U":
                            policyItem.PolicyOccursFrequency = row["C010"].ToString() + CurrentApp.GetLanguageInfo("2402ComboTagD", "Day");
                            break;
                        }
                    }
                    else
                    {
                        policyItem.PolicyOccursFrequency = string.Empty;
                    }
                    policyItem.PolicyStartTime = CommonFunctions.StringToDateTime(row["C008"].ToString()).ToString();
                    long longTime = 0;
                    long.TryParse(row["C008"].ToString(), out longTime);
                    policyItem.PolicyStartTimeNumber = longTime;
                    DateTime dtEnd = CommonFunctions.StringToDateTime(row["C009"].ToString());
                    if (dtEnd.ToString("yyyy-MM-dd HH:mm:ss") != "2099-12-31 23:59:59")
                    {
                        policyItem.PolicyEndTime = CommonFunctions.StringToDateTime(row["C009"].ToString()).ToString();
                    }
                    else
                    {
                        policyItem.PolicyEndTime = CurrentApp.GetLanguageInfo("2402RB002", "Never expires");
                    }
                    long.TryParse(row["C009"].ToString(), out longTime);
                    policyItem.PolicyEndTimeNumber = longTime;
                    policyItem.PolicyIsEnabled     = row["C003"].ToString();
                    if (strType == "C")
                    {
                        policyItem.IsStrongPwd = row["C012"].ToString() == "1" ? CurrentApp.GetLanguageInfo("2402019", "Yes") : string.Empty;
                    }
                    else
                    {
                        policyItem.IsStrongPwd = string.Empty;
                    }
                    lstAllPolicies.Add(policyItem);
                }
            }
            catch (Exception ex)
            {
                ShowException("Failed." + ex.Message);
            }
            finally
            {
                if (client != null)
                {
                    if (client.State == System.ServiceModel.CommunicationState.Opened)
                    {
                        client.Close();
                    }
                }
            }
        }
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;
            ServiceStatus serviceStatus = ServiceStatus.GetInstance();
            TermDocuments termDocs = TermDocuments.GetInstance();
            DataFactory dFactory = DataFactory.Instance();
            var detail1 = new ExtensionRuleResultDetail(this.Name);
            var detail2 = new ExtensionRuleResultDetail(this.Name);
            var detail3 = new ExtensionRuleResultDetail(this.Name);
            var detail4 = new ExtensionRuleResultDetail(this.Name);
            Dictionary<string, Dictionary<KeyValuePair<string, string>, List<string>>> entityTypeInfos;
            if (!MetadataHelper.GetEntityTypesWithComplexProperty(serviceStatus.MetadataDocument, "Edm.String", out entityTypeInfos))
            {
                detail1.ErrorMessage = "To verify this rule it expects complex type containing a property with string type, but there is no this complex type in metadata so cannot verify this rule.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1);

                return passed;
            }

            var entityTypeInfo = new KeyValuePair<string, Dictionary<KeyValuePair<string, string>, List<string>>>();
            string entitySetName = string.Empty;
            foreach (var etInfo in entityTypeInfos)
            {
                entitySetName = etInfo.Key.MapEntityTypeShortNameToEntitySetName();
                var funcs = new List<Func<string, string, string, List<NormalProperty>, List<NavigProperty>, bool>>() 
                {
                    AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions, AnnotationsHelper.GetDeleteRestrictions
                };

                var restrictions = entitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, funcs);
                if (!string.IsNullOrEmpty(restrictions.Item1) ||
                    null != restrictions.Item2 || restrictions.Item2.Any() ||
                    null != restrictions.Item3 || restrictions.Item3.Any())
                {
                    entityTypeInfo = etInfo;

                    break;
                }
            }

            if (string.IsNullOrEmpty(entitySetName) ||
                string.IsNullOrEmpty(entityTypeInfo.Key) ||
                null == entityTypeInfo.Value ||
                !entityTypeInfo.Value.Any())
            {
                detail1.ErrorMessage = "Cannot find the entity-set which support insert, updata, delete restrictions at the same time.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1);

                return passed;
            }

            string entityTypeShortName = entityTypeInfo.Key;
            string entitySetUrl = entitySetName.MapEntitySetNameToEntitySetURL();
            string complexPropName = entityTypeInfo.Value.Keys.First().Key;
            string complexPropType = entityTypeInfo.Value.Keys.First().Value;
            string propertyNameWithSpecifiedType = entityTypeInfo.Value[new KeyValuePair<string, string>(complexPropName, complexPropType)].First();

            // Create a entity
            string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl;
            var additionalInfos = new List<AdditionalInfo>();
            var reqData = dFactory.ConstructInsertedEntityData(entitySetName, entityTypeShortName, null, out additionalInfos);
            reqData = dFactory.ReconstructNullableComplexData(reqData, new List<string>() { complexPropName });
            string reqDataStr = reqData.ToString();
            bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag);
            var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos);
            detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr);
            if (resp.StatusCode == HttpStatusCode.Created)
            {
                var entityId = additionalInfos.Last().EntityId;
                var hasEtag = additionalInfos.Last().HasEtag;

                // Get a complex property except key property
                string complexProUrl = entityId + @"/" + complexPropName;
                resp = WebHelper.Get(new Uri(complexProUrl), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders);
                detail2 = new ExtensionRuleResultDetail(this.Name, complexProUrl, HttpMethod.Get, StringHelper.MergeHeaders(Constants.AcceptHeaderJson, serviceStatus.DefaultHeaders), resp);

                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    JObject jo;
                    resp.ResponsePayload.TryToJObject(out jo);
                    //string newComplexProperty = VerificationHelper.ConstructUpdatedEntityData(jo, new List<string>() { propertyNameWithSpecifiedType }, out hasEtag);
                    string newComplexProperty = dFactory.ConstructUpdatedEntityData(jo, new List<string>() { propertyNameWithSpecifiedType }).ToString();

                    // Update the complex property
                    resp = WebHelper.UpdateEntity(complexProUrl, context.RequestHeaders, newComplexProperty, HttpMethod.Patch, hasEtag);
                    detail3 = new ExtensionRuleResultDetail(this.Name, complexProUrl, HttpMethod.Patch, string.Empty, resp, string.Empty, newComplexProperty);
                    if (resp.StatusCode == HttpStatusCode.NoContent)
                    {
                        // Check whether the complex property is updated to new value
                        if (WebHelper.GetContent(complexProUrl, context.RequestHeaders, out resp))
                        {
                            detail4 = new ExtensionRuleResultDetail(this.Name, complexProUrl, HttpMethod.Get, string.Empty, resp);
                            resp.ResponsePayload.TryToJObject(out jo);

                            if (jo != null && jo[propertyNameWithSpecifiedType] != null && jo[propertyNameWithSpecifiedType].Value<string>().Equals(Constants.UpdateData))
                            {
                                passed = true;
                            }
                            else if (jo == null)
                            {
                                passed = false;
                                detail4.ErrorMessage = "Can not get complex property after Patch it. ";
                            }
                            else if (jo != null && jo[propertyNameWithSpecifiedType] == null)
                            {
                                passed = false;
                                detail4.ErrorMessage = string.Format("Can not get the value of {0} property in complex property {1}. ", propertyNameWithSpecifiedType, complexProUrl);
                            }
                            else if (jo != null && jo[propertyNameWithSpecifiedType] != null && !jo[propertyNameWithSpecifiedType].Value<string>().Equals(Constants.UpdateData))
                            {
                                passed = false;
                                detail4.ErrorMessage = string.Format("The value of {0} property in complex is not updated by {1}. ", propertyNameWithSpecifiedType, complexProUrl);
                            }
                        }
                    }
                    else
                    {
                        passed = false;
                        detail3.ErrorMessage = "Update complex property in the created entity failed. ";
                    }
                }
                else if (resp.StatusCode == HttpStatusCode.NoContent)
                {
                    detail2.ErrorMessage = "The value of property with complex type is null.";
                }
                else
                {
                    passed = false;
                    detail2.ErrorMessage = "Get complex property in the created entity failed. ";
                }
                // Delete the entity
                var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos);
            }
            else
            {
                passed = false;
                detail1.ErrorMessage = "Created the new entity failed for above URI. ";
            }

            var details = new List<ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4 }.RemoveNullableDetails();
            info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details);

            return passed;
        }
Пример #20
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propTypes = new string[2] {
                "Edm.Date", "Edm.DateTimeOffset"
            };
            var propNames = MetadataHelper.GetPropertyNames(propTypes, out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName     = propNames[0];
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                var settings = new JsonSerializerSettings();
                settings.DateParseHandling = DateParseHandling.None;
                JObject jObj    = JsonConvert.DeserializeObject(resp.ResponsePayload, settings) as JObject;
                JArray  jArr    = jObj.GetValue(Constants.Value) as JArray;
                var     entity  = jArr.First as JObject;
                var     propVal = entity[propName].ToString();
                int     index   = propVal.IndexOf('-');
                propVal = propVal.Substring(0, index);
                url     = string.Format("{0}?$filter=year({1}) eq {2}", url, propName, propVal);
                resp    = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JsonConvert.DeserializeObject(resp.ResponsePayload, settings) as JObject;
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = et[propName].ToString().Substring(0, index) == propVal;
                    }
                }
                else
                {
                    passed = false;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;
            ExtensionRuleResultDetail detail = null;

            List <string> entitySetURLs = MetadataHelper.GetEntitySetURLs();

            passed = false;
            string entityTypeShortName = string.Empty;

            foreach (string entitySetUrl in entitySetURLs)
            {
                try
                {
                    entityTypeShortName = entitySetUrl.MapEntitySetNameToEntityTypeShortName();
                }
                catch (ArgumentNullException)
                { continue; }

                Tuple <string, string> key = MetadataHelper.GetKeyProperty(entityTypeShortName);

                List <XElement> properties = MetadataHelper.GetAllPropertiesOfEntity(ServiceStatus.GetInstance().MetadataDocument, entityTypeShortName, MatchPropertyType.Navigations);

                Response resp = WebHelper.Get(new Uri(context.ServiceBaseUri + "/" + entitySetUrl), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

                if (null == resp || HttpStatusCode.OK != resp.StatusCode)
                {
                    continue;
                }

                JObject feed;
                resp.ResponsePayload.TryToJObject(out feed);

                if (feed == null || JTokenType.Object != feed.Type)
                {
                    continue;
                }

                JArray entities = JsonParserHelper.GetEntries(feed);
                foreach (JToken entity in entities)
                {
                    string identity = entity[key.Item1].ToString();
                    foreach (XElement property in properties)
                    {
                        if (String.IsNullOrEmpty(property.Attribute("Name").Value))
                        {
                            continue;
                        }

                        string url = context.ServiceBaseUri + "/" + entitySetUrl + "(" + (key.Item2.Equals("Edm.String") ? "\'" + identity + "\'" : identity) + ")/" + property.Attribute("Name").Value;

                        resp   = WebHelper.Get(new Uri(url), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
                        detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, "");

                        if (null == resp || HttpStatusCode.OK != resp.StatusCode)
                        {
                            continue;
                        }

                        resp.ResponsePayload.TryToJObject(out feed);

                        if (feed == null || JTokenType.Object == feed.Type)
                        {
                            passed = true; break;
                        }
                    }
                    if (passed.Value)
                    {
                        break;
                    }
                }

                if (passed.Value)
                {
                    break;
                }
            }

            info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail);
            return(passed);
        }
Пример #22
0
        public static async Task<bool> UpdateDataAsync()
        {
            bool updated = false;
            WebHelper webHelper = new WebHelper();

            if (await webHelper.getAllData())
            {
                SQLiteAsyncConnection conn = new SQLiteAsyncConnection(Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\Data.db");
                await conn.DropTableAsync<Term>();
                await conn.DropTableAsync<Lesson>();
                await conn.DropTableAsync<Exam>();//删除之前的数据
                await conn.DropTableAsync<Course>();//不提示成绩更新情况下,直接删除成绩
                await conn.CreateTablesAsync<Course, Term, Lesson, Exam>();

                await conn.InsertAllAsync(webHelper.Exams);//update exams; 
                await conn.InsertAllAsync(webHelper.Terms);
                await conn.InsertAllAsync(webHelper.Lessons);
                await conn.InsertAllAsync(webHelper.Courses);
                Term.ClearData();
                Exam.ClearData();
                WeekDay.ClearData();

                updated = true;
            }

            return updated;
            ////区分有无成绩更新,方便后续扩展出成绩提示
            //var previousCourses = terms.SelectMany(term => term.Courses);

            //var updateCourses = from course in webHelper.Courses
            //                    let previousCourse = from tempCourse in previousCourses
            //                                         where tempCourse.CourseName == course.CourseName &&
            //                                         tempCourse.TermNumber == course.TermNumber &&
            //                                         (tempCourse.GradePoints != course.GradePoints | tempCourse.MakeUpExamGrades != course.MakeUpExamGrades)
            //                                         select tempCourse
            //                    where previousCourse.Any()
            //                    select course;

            //var newCourses = from course in webHelper.Courses
            //                 let previousCourse = from tempCourse in previousCourses
            //                                      where tempCourse.CourseName == course.CourseName &&
            //                                      tempCourse.TermNumber == course.TermNumber
            //                                      select tempCourse
            //                 where !previousCourse.Any()
            //                 select course;

            //var updatedCourse = updateCourses.ToList();
            // var newcourses = newCourses.ToList();
            //if (updateCourses.Any() | newCourses.Any())
            //{
            //    try
            //    {
            //        await conn.InsertAllAsync(newCourses);
            //        await conn.UpdateAllAsync(updateCourses);

            //    }
            //    catch (Exception)
            //    {
            //        await conn.DropTableAsync<Course>();
            //        var message = new Windows.UI.Popups.MessageDialog("更新本地数据出错,建议或重试,或进入设置删除本地账号和数据或重启应用后再导入");
            //        await message.ShowAsync();
            //    }
            //    updated = true;
            //}
        }
Пример #23
0
        /// <summary>
        /// 添加套装到购物车
        /// </summary>
        public ActionResult AddSuit()
        {
            int pmId     = WebHelper.GetQueryInt("pmId");     //套装id
            int buyCount = WebHelper.GetQueryInt("buyCount"); //购买数量

            //当商城不允许游客使用购物车时
            if (WorkContext.MallConfig.IsGuestSC == 0 && WorkContext.Uid < 1)
            {
                return(AjaxResult("nologin", "请先登录"));
            }

            //购买数量不能小于1
            if (buyCount < 1)
            {
                return(AjaxResult("buycountmin", "请填写购买数量"));
            }

            //获得套装促销活动
            SuitPromotionInfo suitPromotionInfo = Promotions.GetSuitPromotionByPmIdAndTime(pmId, DateTime.Now);

            //套装促销活动不存在时
            if (suitPromotionInfo == null)
            {
                return(AjaxResult("nosuit", "请选择套装"));
            }

            //店铺信息
            StoreInfo storeInfo = Stores.GetStoreById(suitPromotionInfo.StoreId);

            if (storeInfo.State != (int)StoreState.Open)
            {
                return(AjaxResult("nosuit", "请选择套装"));
            }

            //购物车商品列表
            List <OrderProductInfo> orderProductList     = Carts.GetCartProductList(WorkContext.Uid, WorkContext.Sid);
            List <OrderProductInfo> suitOrderProductList = Carts.GetSuitOrderProductList(pmId, orderProductList, false);

            if (suitOrderProductList.Count == 0)
            {
                if ((WorkContext.Uid > 0 && orderProductList.Count >= WorkContext.MallConfig.MemberSCCount) || (WorkContext.Uid < 1 && orderProductList.Count >= WorkContext.MallConfig.GuestSCCount))
                {
                    return(AjaxResult("full", "购物车已满"));
                }
            }

            //扩展套装商品列表
            List <ExtSuitProductInfo> extSuitProductList = Promotions.GetExtSuitProductList(suitPromotionInfo.PmId);

            if (extSuitProductList.Count < 1)
            {
                return(AjaxResult("noproduct", "套装中没有商品"));
            }

            //套装商品id列表
            StringBuilder pidList = new StringBuilder();

            foreach (ExtSuitProductInfo extSuitProductInfo in extSuitProductList)
            {
                pidList.AppendFormat("{0},", extSuitProductInfo.Pid);
            }
            pidList.Remove(pidList.Length - 1, 1);

            //套装商品库存列表
            List <ProductStockInfo> productStockList = Products.GetProductStockList(pidList.ToString());

            foreach (ProductStockInfo item in productStockList)
            {
                if (item.Number < buyCount)
                {
                    return(AjaxResult("stockout", item.Pid.ToString()));
                }
            }

            buyCount = suitOrderProductList.Count == 0 ? buyCount : suitOrderProductList[0].BuyCount / suitOrderProductList[0].ExtCode2 + buyCount;
            Carts.AddSuitToCart(ref orderProductList, extSuitProductList, suitPromotionInfo, buyCount, WorkContext.Sid, WorkContext.Uid, DateTime.Now);
            //将购物车中商品数量写入cookie
            Carts.SetCartProductCountCookie(Carts.SumOrderProductCount(orderProductList));

            return(AjaxResult("success", "添加成功"));
        }
Пример #24
0
        private XElement[] getChildNodes(string sDir)
        {
            Boolean addFile = true;
               FileInfo finfo;
               ArrayList childNodes = new ArrayList();
               WebHelper wh = new WebHelper();

               foreach (string f in Directory.GetFiles(sDir, "*.*"))
               {
               addFile = true;
               finfo = new FileInfo(f);
               foreach (string includeExt in includeFiles)
               {
                   if (finfo.Extension == includeExt)
                   {
                       addFile = true;
                       break;
                   }
                   else
                   {
                       addFile = false;
                   }

               }
               if (addFile)
               {
                   foreach (string filter in excludeFiles)
                   {
                       if (f.Contains(filter))
                       {
                           addFile = false;
                           break;
                       }
                   }

                   if (addFile)
                   {
                       string fileTitle = wh.GetTitleFromHtmlFile(f);
                       childNodes.Add(createSiteMapNode(ns, replaceWithVirtualPath(f), fileTitle, ""));
                   }
               }
               }

               return (XElement[])childNodes.ToArray(typeof(XElement));
        }
Пример #25
0
        /// <summary>
        /// 修改购物车中套装数量
        /// </summary>
        public ActionResult ChangeSuitCount()
        {
            //当商城不允许游客使用购物车时
            if (WorkContext.MallConfig.IsGuestSC == 0 && WorkContext.Uid < 1)
            {
                return(AjaxResult("nologin", "请先登录"));
            }

            int    pmId     = WebHelper.GetQueryInt("pmId");                                      //套装id
            int    buyCount = WebHelper.GetQueryInt("buyCount");                                  //购买数量
            string selectedCartItemKeyList = WebHelper.GetQueryString("selectedCartItemKeyList"); //选中的购物车项键列表

            //购物车商品列表
            List <OrderProductInfo> orderProductList = Carts.GetCartProductList(WorkContext.Uid, WorkContext.Sid);
            //套装商品列表
            List <OrderProductInfo> suitOrderProductList = Carts.GetSuitOrderProductList(pmId, orderProductList, true);

            if (suitOrderProductList.Count > 0) //当套装已经存在
            {
                if (buyCount < 1)               //当购买数量小于1时,删除此套装
                {
                    Carts.DeleteCartSuit(ref orderProductList, pmId);
                }
                else
                {
                    OrderProductInfo orderProductInfo = suitOrderProductList.Find(x => x.Type == 3);
                    int oldBuyCount = orderProductInfo.RealCount / orderProductInfo.ExtCode2;
                    if (buyCount != oldBuyCount)
                    {
                        Carts.AddExistSuitToCart(ref orderProductList, suitOrderProductList, buyCount);
                    }
                }
            }

            //商品数量
            int pCount = Carts.SumOrderProductCount(orderProductList);
            //店铺购物车列表
            List <StoreCartInfo> storeCartList = Carts.TidyMallOrderProductList(StringHelper.SplitString(selectedCartItemKeyList), orderProductList);

            //商品总数量
            int totalCount = Carts.SumMallCartOrderProductCount(storeCartList);
            //商品合计
            decimal productAmount = Carts.SumMallCartOrderProductAmount(storeCartList);
            //满减折扣
            int fullCut = Carts.SumMallCartFullCut(storeCartList);
            //订单合计
            decimal orderAmount = productAmount - fullCut;

            CartModel model = new CartModel
            {
                TotalCount    = totalCount,
                ProductAmount = productAmount,
                FullCut       = fullCut,
                OrderAmount   = orderAmount,
                StoreCartList = storeCartList
            };

            //将购物车中商品数量写入cookie
            Carts.SetCartProductCountCookie(pCount);

            return(View("ajaxindex", model));
        }
        internal async Task<Token> GetAccessToken()
        {
            if (CredentialType != CredentialType.ClientCredentials && CredentialType != CredentialType.ResourceOwner &&
                CredentialType != CredentialType.RefreshToken
                ||
                (_accessToken != null && _accessToken.Expiration >= DateTime.UtcNow.AddMinutes(-5)))
            {
                return _accessToken;
            }

            var helper = new WebHelper(this, _baseUrl);
            var response = await helper.PostForm(GetCredentialsDictionary(), Oauth2TokenPath, null, null, false);
            _accessToken = new Token
            {
                AccessToken = response.access_token.ToString(),
                Expiration =
                    DateTime.UtcNow.Add(TimeSpan.FromSeconds((double) response.expires_in)),
                RefreshToken = response.refresh_token
            };

            return _accessToken;
        }
Пример #27
0
        /// <summary>
        /// 添加满赠到购物车
        /// </summary>
        public ActionResult AddFullSend()
        {
            //当商城不允许游客使用购物车时
            if (WorkContext.MallConfig.IsGuestSC == 0 && WorkContext.Uid < 1)
            {
                return(AjaxResult("nologin", "请先登录"));
            }

            int    pmId = WebHelper.GetQueryInt("pmId");                                          //满赠id
            int    pid  = WebHelper.GetQueryInt("pid");                                           //商品id
            string selectedCartItemKeyList = WebHelper.GetQueryString("selectedCartItemKeyList"); //选中的购物车项键列表

            //添加的商品
            PartProductInfo partProductInfo = Products.GetPartProductById(pid);

            if (partProductInfo == null)
            {
                return(AjaxResult("noproduct", "请选择商品"));
            }

            //店铺信息
            StoreInfo storeInfo = Stores.GetStoreById(partProductInfo.StoreId);

            if (storeInfo.State != (int)StoreState.Open)
            {
                return(AjaxResult("noproduct", "请选择商品"));
            }

            //商品库存
            int stockNumber = Products.GetProductStockNumberByPid(pid);

            if (stockNumber < 1)
            {
                return(AjaxResult("stockout", "商品库存不足"));
            }

            //满赠促销活动
            FullSendPromotionInfo fullSendPromotionInfo = Promotions.GetFullSendPromotionByPmIdAndTime(pmId, DateTime.Now);

            if (fullSendPromotionInfo == null)
            {
                return(AjaxResult("nopromotion", "满赠促销活动不存在或已经结束"));
            }

            //购物车商品列表
            List <OrderProductInfo> orderProductList = Carts.GetCartProductList(WorkContext.Uid, WorkContext.Sid);

            //满赠主商品列表
            List <OrderProductInfo> fullSendMainOrderProductList = Carts.GetFullSendMainOrderProductList(pmId, orderProductList);

            if (fullSendMainOrderProductList.Count < 1)
            {
                return(AjaxResult("nolimit", "不符合活动条件"));
            }
            decimal amount = Carts.SumOrderProductAmount(fullSendMainOrderProductList);

            if (fullSendPromotionInfo.LimitMoney > amount)
            {
                return(AjaxResult("nolimit", "不符合活动条件"));
            }

            if (!Promotions.IsExistFullSendProduct(pmId, pid, 1))
            {
                return(AjaxResult("nofullsendproduct", "此商品不是满赠商品"));
            }

            //赠送商品
            OrderProductInfo fullSendMinorOrderProductInfo = Carts.GetFullSendMinorOrderProduct(pmId, orderProductList);

            if (fullSendMinorOrderProductInfo != null)
            {
                if (fullSendMinorOrderProductInfo.Pid != pid)
                {
                    Carts.DeleteCartFullSend(ref orderProductList, fullSendMinorOrderProductInfo);
                }
                else
                {
                    return(AjaxResult("exist", "此商品已经添加"));
                }
            }

            //添加满赠商品
            Carts.AddFullSendToCart(ref orderProductList, partProductInfo, fullSendPromotionInfo, WorkContext.Sid, WorkContext.Uid, DateTime.Now);

            //商品数量
            int pCount = Carts.SumOrderProductCount(orderProductList);
            //店铺购物车列表
            List <StoreCartInfo> storeCartList = Carts.TidyMallOrderProductList(StringHelper.SplitString(selectedCartItemKeyList), orderProductList);

            //商品总数量
            int totalCount = Carts.SumMallCartOrderProductCount(storeCartList);
            //商品合计
            decimal productAmount = Carts.SumMallCartOrderProductAmount(storeCartList);
            //满减折扣
            int fullCut = Carts.SumMallCartFullCut(storeCartList);
            //订单合计
            decimal orderAmount = productAmount - fullCut;

            CartModel model = new CartModel
            {
                TotalCount    = totalCount,
                ProductAmount = productAmount,
                FullCut       = fullCut,
                OrderAmount   = orderAmount,
                StoreCartList = storeCartList
            };

            //将购物车中商品数量写入cookie
            Carts.SetCartProductCountCookie(pCount);

            return(View("ajaxindex", model));
        }
Пример #28
0
 public static Weather GoogleWeather(string city)
 {
     const string baseUrl = @"https://www.google.com";
     WebHelper connectionBase = new WebHelper();
     UrlBuilder parameters = new UrlBuilder(string.Format(@"{0}/ig/api", baseUrl));
     parameters.Add("hl","zh-cn");
     parameters.Add("weather",city);
     XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(connectionBase.Get(parameters.ToString()));
     XmlNodeList nodeCity = xmlDocument.SelectNodes("xml_api_reply/weather/forecast_information");
     Weather.CityInfomaition cityInfo = new Weather.CityInfomaition(
         nodeCity.Item(0).SelectSingleNode("city").Attributes["data"].InnerText,
         nodeCity.Item(0).SelectSingleNode("postal_code").Attributes["data"].InnerText,
         nodeCity.Item(0).SelectSingleNode("latitude_e6").Attributes["data"].InnerText,
         nodeCity.Item(0).SelectSingleNode("longitude_e6").Attributes["data"].InnerText,
         nodeCity.Item(0).SelectSingleNode("unit_system").Attributes["data"].InnerText,
         Convert.ToDateTime(nodeCity.Item(0).SelectSingleNode("forecast_date").Attributes["data"].InnerText),
         Convert.ToDateTime(nodeCity.Item(0).SelectSingleNode("current_date_time").Attributes["data"].InnerText));
     XmlNodeList nodeToday = xmlDocument.SelectNodes("xml_api_reply/weather/current_conditions");
     Weather.TodayWeather today = new Weather.TodayWeather(
         Convert.ToInt16(nodeToday.Item(0).SelectSingleNode("temp_c").Attributes["data"].InnerText),
         Convert.ToInt16(nodeToday.Item(0).SelectSingleNode("temp_f").Attributes["data"].InnerText),
         nodeToday.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText,
         nodeToday.Item(0).SelectSingleNode("humidity").Attributes["data"].InnerText,
         nodeToday.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerText,
         ImageHelper.GetImage(baseUrl + nodeToday.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText));
     XmlNodeList nodeList = xmlDocument.SelectNodes("xml_api_reply/weather/forecast_conditions");
     Weather.DayWeather tomorrow = new Weather.DayWeather(
         Convert.ToInt16(nodeList.Item(1).SelectSingleNode("high").Attributes["data"].InnerText),
         Convert.ToInt16(nodeList.Item(1).SelectSingleNode("low").Attributes["data"].InnerText),
         nodeList.Item(1).SelectSingleNode("condition").Attributes["data"].InnerText,
         ImageHelper.GetImage(baseUrl + nodeToday.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText));
     Weather.DayWeather third = new Weather.DayWeather(
         Convert.ToInt16(nodeList.Item(2).SelectSingleNode("high").Attributes["data"].InnerText),
         Convert.ToInt16(nodeList.Item(2).SelectSingleNode("low").Attributes["data"].InnerText),
         nodeList.Item(2).SelectSingleNode("condition").Attributes["data"].InnerText,
         ImageHelper.GetImage(baseUrl + nodeToday.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText));
     Weather.DayWeather fourth = new Weather.DayWeather(
         Convert.ToInt16(nodeList.Item(3).SelectSingleNode("high").Attributes["data"].InnerText),
         Convert.ToInt16(nodeList.Item(3).SelectSingleNode("low").Attributes["data"].InnerText),
         nodeList.Item(3).SelectSingleNode("condition").Attributes["data"].InnerText,
         ImageHelper.GetImage(baseUrl + nodeToday.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText));
     Weather weather = new Weather(cityInfo,today, tomorrow, third, fourth);
     return weather;
 }
Пример #29
0
        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        public ActionResult AddProduct()
        {
            int pid      = WebHelper.GetQueryInt("pid");      //商品id
            int buyCount = WebHelper.GetQueryInt("buyCount"); //购买数量

            //当商城不允许游客使用购物车时
            if (WorkContext.MallConfig.IsGuestSC == 0 && WorkContext.Uid < 1)
            {
                return(AjaxResult("nologin", "请先登录"));
            }

            //判断商品是否存在
            PartProductInfo partProductInfo = Products.GetPartProductById(pid);

            if (partProductInfo == null)
            {
                return(AjaxResult("noproduct", "请选择商品"));
            }

            //店铺信息
            StoreInfo storeInfo = Stores.GetStoreById(partProductInfo.StoreId);

            if (storeInfo.State != (int)StoreState.Open)
            {
                return(AjaxResult("noproduct", "请选择商品"));
            }

            //购买数量不能小于1
            if (buyCount < 1)
            {
                return(AjaxResult("buycountmin", "请填写购买数量"));
            }

            //商品库存
            int stockNumber = Products.GetProductStockNumberByPid(pid);

            if (stockNumber < buyCount)
            {
                return(AjaxResult("stockout", "商品库存不足"));
            }

            //购物车中已经存在的商品列表
            List <OrderProductInfo> orderProductList = Carts.GetCartProductList(WorkContext.Uid, WorkContext.Sid);
            OrderProductInfo        orderProductInfo = Carts.GetCommonOrderProductByPid(pid, orderProductList);

            if (orderProductInfo == null)
            {
                if ((WorkContext.Uid > 0 && orderProductList.Count >= WorkContext.MallConfig.MemberSCCount) || (WorkContext.Uid < 1 && orderProductList.Count >= WorkContext.MallConfig.GuestSCCount))
                {
                    return(AjaxResult("full", "购物车已满"));
                }
            }

            buyCount = orderProductInfo == null ? buyCount : orderProductInfo.BuyCount + buyCount;
            //将商品添加到购物车
            Carts.AddProductToCart(ref orderProductList, buyCount, partProductInfo, WorkContext.Sid, WorkContext.Uid, DateTime.Now);
            //将购物车中商品数量写入cookie
            Carts.SetCartProductCountCookie(Carts.SumOrderProductCount(orderProductList));

            return(AjaxResult("success", "添加成功"));
        }
Пример #30
0
 public void RemoveCurrent()
 {
     WebHelper.RemoveSession(LoginUserKey.Trim());
 }
Пример #31
0
        public static void InitControledOrg(string OrgID)
        {
            try
            {
                WebRequest webRequest = new WebRequest();
                webRequest.Session = App.Session;
                webRequest.Code    = (int)S3104Codes.GetControlOrgInfoList;
                webRequest.ListData.Add(OrgID);
                //Service31041Client client = new Service31041Client();
                Service31041Client client    = new Service31041Client(WebHelper.CreateBasicHttpBinding(Session), WebHelper.CreateEndpointAddress(App.Session.AppServerInfo, "Service31041"));
                WebReturn          webReturn = client.UMPClientOperation(webRequest);
                client.Close();
                if (!webReturn.Result)
                {
                    App.ShowExceptionMessage(string.Format("Fail.\t{0}\t{1}", webReturn.Code, webReturn.Message));
                    return;
                }
                if (webReturn.ListData == null)
                {
                    App.ShowExceptionMessage(string.Format("Fail.\tListData is null"));
                    return;
                }
                for (int i = 0; i < webReturn.ListData.Count; i++)
                {
                    string   strInfo = webReturn.ListData[i];
                    string[] arrInfo = strInfo.Split(new[] { ConstValue.SPLITER_CHAR },
                                                     StringSplitOptions.RemoveEmptyEntries);
                    if (arrInfo.Length < 2)
                    {
                        continue;
                    }
                    CtrolOrg ctrolOrg = new CtrolOrg();
                    ctrolOrg.ID      = arrInfo[0];
                    ctrolOrg.OrgName = arrInfo[1];

                    ListCtrolOrgInfos.Add(ctrolOrg);
                }
            }
            catch (Exception ex)
            {
                App.ShowExceptionMessage(ex.Message);
            }
        }
Пример #32
0
        public ActionResult Edit(UserModel model, int uid = -1)
        {
            UserInfo userInfo = AdminUsers.GetUserById(uid);

            if (userInfo == null)
            {
                return(PromptView("用户不存在"));
            }

            int uid2 = AdminUsers.GetUidByUserName(model.UserName);

            if (uid2 > 0 && uid2 != uid)
            {
                ModelState.AddModelError("UserName", "用户名已经存在");
            }

            int uid3 = AdminUsers.GetUidByEmail(model.Email);

            if (uid3 > 0 && uid3 != uid)
            {
                ModelState.AddModelError("Email", "邮箱已经存在");
            }

            int uid4 = AdminUsers.GetUidByMobile(model.Mobile);

            if (uid4 > 0 && uid4 != uid)
            {
                ModelState.AddModelError("Mobile", "手机号已经存在");
            }

            if (ModelState.IsValid)
            {
                string nickName;
                if (string.IsNullOrWhiteSpace(model.NickName))
                {
                    nickName = userInfo.NickName;
                }
                else
                {
                    nickName = model.NickName;
                }

                userInfo.UserName = model.UserName;
                userInfo.Email    = model.Email == null ? "" : model.Email;
                userInfo.Mobile   = model.Mobile == null ? "" : model.Mobile;
                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    userInfo.Password = Users.CreateUserPassword(model.Password, userInfo.Salt);
                }
                userInfo.UserRid     = model.UserRid;
                userInfo.MallAGid    = model.MallAGid;
                userInfo.NickName    = WebHelper.HtmlEncode(nickName);
                userInfo.Avatar      = model.Avatar == null ? "" : WebHelper.HtmlEncode(model.Avatar);
                userInfo.PayCredits  = model.PayCredits;
                userInfo.RankCredits = userInfo.UserRid == model.UserRid ? userInfo.RankCredits : AdminUserRanks.GetUserRankById(model.UserRid).CreditsLower;
                userInfo.LiftBanTime = UserRanks.IsBanUserRank(model.UserRid) ? DateTime.Now.AddDays(WorkContext.UserRankInfo.LimitDays) : new DateTime(1900, 1, 1);
                userInfo.Gender      = model.Gender;
                userInfo.RealName    = model.RealName == null ? "" : WebHelper.HtmlEncode(model.RealName);
                userInfo.Bday        = model.Bday ?? new DateTime(1970, 1, 1);
                userInfo.IdCard      = model.IdCard == null ? "" : model.IdCard;
                userInfo.RegionId    = model.RegionId;
                userInfo.Address     = model.Address == null ? "" : WebHelper.HtmlEncode(model.Address);
                userInfo.Bio         = model.Bio == null ? "" : WebHelper.HtmlEncode(model.Bio);

                AdminUsers.UpdateUser(userInfo);
                AddMallAdminLog("修改用户", "修改用户,用户ID为:" + uid);
                return(PromptView("用户修改成功"));
            }

            Load(model.RegionId);

            return(View(model));
        }
Пример #33
0
 public static void InitLanguageInfos()
 {
     try
     {
         if (Session == null || Session.LangTypeInfo == null)
         {
             return;
         }
         ListLanguageInfos.Clear();
         WebRequest webRequest = new WebRequest();
         webRequest.Code    = (int)RequestCode.WSGetLangList;
         webRequest.Session = Session;
         //ListParams
         //0     LangID
         //1     PreName(语言内容编码的前缀,比如 FO:模块、操作显示语言)
         //1     ModuleID
         //2     SubModuleID
         //3     Page
         //4     Name
         webRequest.ListData.Add(Session.LangTypeInfo.LangID.ToString());
         webRequest.ListData.Add(string.Empty);
         webRequest.ListData.Add("31");
         webRequest.ListData.Add("3104");
         webRequest.ListData.Add(string.Empty);
         webRequest.ListData.Add(string.Empty);
         Service11012Client client = new Service11012Client(WebHelper.CreateBasicHttpBinding(Session), WebHelper.CreateEndpointAddress(Session.AppServerInfo, "Service11012"));
         //Service11012Client client = new Service11012Client();
         WebReturn webReturn = client.DoOperation(webRequest);
         client.Close();
         if (!webReturn.Result)
         {
             ShowExceptionMessage(string.Format("{0}\t{1}", webReturn.Code, webReturn.Message));
         }
         for (int i = 0; i < webReturn.ListData.Count; i++)
         {
             OperationReturn optReturn = XMLHelper.DeserializeObject <LanguageInfo>(webReturn.ListData[i]);
             if (!optReturn.Result)
             {
                 ShowExceptionMessage(string.Format("{0}\t{1}", optReturn.Code, optReturn.Message));
                 return;
             }
             LanguageInfo langInfo = optReturn.Data as LanguageInfo;
             if (langInfo == null)
             {
                 ShowExceptionMessage(string.Format("LanguageInfo is null"));
                 return;
             }
             ListLanguageInfos.Add(langInfo);
         }
     }
     catch (Exception ex)
     {
         //ShowExceptionMessage(ex.Message);
     }
 }
Пример #34
0
 private void GetScoreTemplateID(long RecoredReference)
 {
     try
     {
         WebRequest webRequest = new WebRequest();
         webRequest.Code    = (int)S3103Codes.GetScoreTemplateID;
         webRequest.Session = CurrentApp.Session;
         webRequest.ListData.Add(selTaskRecord.RecoredReference.ToString());
         //Service31031Client client = new Service31031Client();
         Service31031Client client = new Service31031Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session), WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service31031"));
         //WebHelper.SetServiceClient(client);
         WebReturn webReturn = client.UMPTaskOperation(webRequest);
         client.Close();
         if (!webReturn.Result)
         {
             ShowException(string.Format("Fail.\t{0}\t{1}", webReturn.Code, webReturn.Message));
             return;
         }
         if (string.IsNullOrWhiteSpace(webReturn.Data))
         {
             ShowException(string.Format("Fail.\tData is null"));
             return;
         }
         oldTemplateID = Convert.ToInt64(webReturn.Data);
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
Пример #35
0
        /// <summary>
        /// 支付
        /// </summary>
        public ActionResult Pay()
        {
            //订单id列表
            string oidList = WebHelper.GetQueryString("oidList");

            LogUtil.WriteLog("oidList:" + oidList);

            decimal          allSurplusMoney = 0M;
            List <OrderInfo> orderList       = new List <OrderInfo>();

            foreach (string oid in StringHelper.SplitString(oidList))
            {
                //订单信息
                OrderInfo orderInfo = Orders.GetOrderByOid(TypeHelper.StringToInt(oid));
                if (orderInfo != null && orderInfo.OrderState == (int)OrderState.WaitPaying)
                {
                    orderList.Add(orderInfo);
                }
                else
                {
                    return(Redirect("/mob"));
                }
                allSurplusMoney += orderInfo.SurplusMoney;
            }

            if (orderList.Count < 1 || allSurplusMoney == 0M)
            {
                return(Redirect("/mob"));
            }

            string code = Request.QueryString["code"];

            if (string.IsNullOrEmpty(code))
            {
                string code_url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=lk#wechat_redirect", PayConfig.AppId, string.Format("http://{0}/mob/wechat/pay?oidList=" + oidList, BMAConfig.MallConfig.SiteUrl));
                LogUtil.WriteLog("code_url:" + code_url);
                return(Redirect(code_url));
            }

            LogUtil.WriteLog(" ============ 开始 获取微信用户相关信息 =====================");

            #region 获取支付用户 OpenID================
            string url       = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", PayConfig.AppId, PayConfig.AppSecret, code);
            string returnStr = HttpUtil.Send("", url);
            LogUtil.WriteLog("Send 页面  returnStr 第一个:" + returnStr);

            OpenModel openModel = JsonConvert.DeserializeObject <OpenModel>(returnStr);

            url       = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", PayConfig.AppId, openModel.refresh_token);
            returnStr = HttpUtil.Send("", url);
            openModel = JsonConvert.DeserializeObject <OpenModel>(returnStr);

            LogUtil.WriteLog("Send 页面  access_token:" + openModel.access_token);
            LogUtil.WriteLog("Send 页面  openid=" + openModel.openid);

            //url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", obj.access_token, obj.openid);
            //returnStr = HttpUtil.Send("", url);
            //LogUtil.WriteLog("Send 页面  returnStr:" + returnStr);
            #endregion

            LogUtil.WriteLog(" ============ 结束 获取微信用户相关信息 =====================");

            LogUtil.WriteLog("============ 单次支付开始 ===============");

            #region 支付操作============================


            #region 基本参数===========================
            //商户订单号
            string outTradeNo = oidList.Replace(',', 's') + Randoms.CreateRandomValue(10, true);
            //订单名称
            string subject = BMAConfig.MallConfig.SiteTitle + "购物";
            //付款金额
            string totalFee = ((int)(allSurplusMoney * 100)).ToString();
            //openId
            string openId = openModel.openid;
            //时间戳
            string timeStamp = TenpayUtil.getTimestamp();
            //随机字符串
            string nonceStr = TenpayUtil.getNoncestr();
            //服务器异步通知页面路径
            string notifyUrl = string.Format("http://{0}/mob/wechat/notify", BMAConfig.MallConfig.SiteUrl);

            LogUtil.WriteLog("totalFee" + totalFee);

            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(System.Web.HttpContext.Current);
            //初始化
            packageReqHandler.init();

            //设置package订单参数  具体参数列表请参考官方pdf文档,请勿随意设置
            packageReqHandler.setParameter("body", subject); //商品信息 127字符
            packageReqHandler.setParameter("appid", PayConfig.AppId);
            packageReqHandler.setParameter("mch_id", PayConfig.MchId);
            packageReqHandler.setParameter("nonce_str", nonceStr.ToLower());
            packageReqHandler.setParameter("notify_url", notifyUrl);
            packageReqHandler.setParameter("openid", openId);
            packageReqHandler.setParameter("out_trade_no", outTradeNo);                  //商家订单号
            packageReqHandler.setParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
            packageReqHandler.setParameter("total_fee", totalFee);                       //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.setParameter("trade_type", "JSAPI");
            //if (!string.IsNullOrEmpty(this.Attach))
            //    packageReqHandler.setParameter("attach", this.Attach);//自定义参数 127字符

            #endregion

            #region sign===============================
            string sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey);
            LogUtil.WriteLog("WeiPay 页面  sign:" + sign);
            #endregion

            #region 获取package包======================
            packageReqHandler.setParameter("sign", sign);

            string data = packageReqHandler.parseXML();
            LogUtil.WriteLog("WeiPay 页面  package(XML):" + data);

            string prepayXml = HttpUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder");
            LogUtil.WriteLog("WeiPay 页面  package(Back_XML):" + prepayXml);

            //获取预支付ID
            string      prepayId = "";
            string      package  = "";
            XmlDocument xdoc     = new XmlDocument();
            xdoc.LoadXml(prepayXml);
            XmlNode     xn  = xdoc.SelectSingleNode("xml");
            XmlNodeList xnl = xn.ChildNodes;
            if (xnl.Count > 7)
            {
                prepayId = xnl[7].InnerText;
                package  = string.Format("prepay_id={0}", prepayId);
                LogUtil.WriteLog("WeiPay 页面  package:" + package);
            }
            #endregion

            #region 设置支付参数 输出页面  该部分参数请勿随意修改 ==============
            RequestHandler paySignReqHandler = new RequestHandler(System.Web.HttpContext.Current);
            paySignReqHandler.setParameter("appId", PayConfig.AppId);
            paySignReqHandler.setParameter("timeStamp", timeStamp);
            paySignReqHandler.setParameter("nonceStr", nonceStr);
            paySignReqHandler.setParameter("package", package);
            paySignReqHandler.setParameter("signType", "MD5");
            string paySign = paySignReqHandler.CreateMd5Sign("key", PayConfig.AppKey);

            LogUtil.WriteLog("WeiPay 页面  paySign:" + paySign);
            #endregion
            #endregion

            Dictionary <string, string> model = new Dictionary <string, string>();
            model.Add("oidList", oidList);
            model.Add("timeStamp", timeStamp);
            model.Add("nonceStr", nonceStr);
            model.Add("package", package);
            model.Add("paySign", paySign);
            return(PartialView("~/plugins/BrnMall.PayPlugin.WeChat/views/wechat/pay.cshtml", model));
        }
Пример #36
0
 public void LoadUserScoreResultList()
 {
     try
     {
         WebRequest webRequest = new WebRequest();
         webRequest.Code    = (int)S3103Codes.GetUserScoreSheetList;
         webRequest.Session = CurrentApp.Session;
         webRequest.ListData.Add(selTaskRecord.RecoredReference.ToString());
         webRequest.ListData.Add(selTaskRecord.AgtOrExtID);
         webRequest.ListData.Add("1");
         webRequest.ListData.Add(selTaskRecord.ScoreUserID.ToString());
         //Service31031Client client = new Service31031Client();
         Service31031Client client = new Service31031Client(WebHelper.CreateBasicHttpBinding(CurrentApp.Session), WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service31031"));
         //WebHelper.SetServiceClient(client);
         WebReturn webReturn = client.UMPTaskOperation(webRequest);
         client.Close();
         if (!webReturn.Result)
         {
             ShowException(string.Format("Fail.\t{0}\t{1}", webReturn.Code, webReturn.Message));
             return;
         }
         if (webReturn.ListData == null)
         {
             ShowException(string.Format("Fail.\tListData is null"));
             return;
         }
         for (int i = 0; i < webReturn.ListData.Count; i++)
         {
             string          strInfo   = webReturn.ListData[i];
             OperationReturn optReturn = XMLHelper.DeserializeObject <BasicScoreSheetInfo>(strInfo);
             if (!optReturn.Result)
             {
                 ShowException(string.Format("Fail.\t{0}\t{1}", optReturn.Code, optReturn.Message));
                 return;
             }
             BasicScoreSheetInfo info = optReturn.Data as BasicScoreSheetInfo;
             if (info == null)
             {
                 ShowException(string.Format("Fail.\tBaiscScoreSheetInfo is null"));
                 return;
             }
             long orgID     = 0;
             var  agentInfo = S3103App.mListAllObjects.FirstOrDefault(a => a.ObjType == ConstValue.RESOURCE_AGENT && a.Name == selTaskRecord.AgtOrExtName);
             if (agentInfo != null)
             {
                 var orgInfo = agentInfo.Parent as ObjectItems;
                 if (orgInfo != null)
                 {
                     if (orgInfo.ObjType == ConstValue.RESOURCE_ORG)
                     {
                         orgID = orgInfo.ObjID;
                     }
                 }
             }
             info.OrgID = orgID;
             BasicScoreSheetItem item =
                 mListScoreSheetItems.FirstOrDefault(s => s.ScoreSheetID == info.ScoreSheetID);
             if (item != null && info.ScoreResultID == selTaskRecord.OldScoreID)
             {
                 item.ScoreSheetInfo = info;
                 item.ScoreResultID  = info.ScoreResultID;
                 item.Score          = info.Score;
                 item.Flag           = 1;
             }
         }
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
Пример #37
0
        public override async Task <VerifyResult> VerifyAsync(GatewayVerifyPaymentContext verifyPaymentContext)
        {
            if (verifyPaymentContext == null)
            {
                throw new ArgumentNullException(nameof(verifyPaymentContext));
            }

            var resultCode = verifyPaymentContext.RequestParameters.GetAs <string>("ResultCode");
            var token      = verifyPaymentContext.RequestParameters.GetAs <string>("Token");
            var merchantId = verifyPaymentContext.RequestParameters.GetAs <string>("MerchantId");

            // Reference ID
            var referenceId = verifyPaymentContext.RequestParameters.GetAs <string>("InvoiceNumber");

            // Transaction ID (IranKish's Reference ID is Transaction ID in our system)
            var transactionId = verifyPaymentContext.RequestParameters.GetAs <string>("ReferenceId");

            // Some data cheking for sure.
            if (merchantId != Configuration.MerchantId ||
                referenceId != verifyPaymentContext.OrderNumber.ToString() ||
                token.IsNullOrWhiteSpace())
            {
                return(new VerifyResult(Gateway.IranKish, referenceId, transactionId, VerifyResultStatus.NotValid, "Invalid data is received from the gateway"));
            }

            //  To translate gateway's result
            IGatewayResultTranslator gatewayResultTranslator = new IranKishGatewayResultTranslator();
            var translatedResult = gatewayResultTranslator.Translate(resultCode);

            if (resultCode != OkResult)
            {
                return(new VerifyResult(Gateway.IranKish, referenceId, transactionId, VerifyResultStatus.Failed, translatedResult));
            }


            //  Verify
            var webServiceVerify = CreateVerifyWebService(
                merchantId: Configuration.MerchantId,
                token: token,
                referenceId: transactionId);

            var headers = new Dictionary <string, string> {
                { "SOAPAction", "http://tempuri.org/IVerify/KicccPaymentsVerification" }
            };
            var serviceResult = await WebHelper.SendXmlWebRequestAsync(VerifyWebServiceUrl, webServiceVerify, headers);

            var result = XmlHelper.GetNodeValueFromXml(serviceResult, "KicccPaymentsVerificationResult");

            // The 'result' is actually the invoice's amount. It must equal to invoice's amount.
            if (!long.TryParse(result, out var integerResult))
            {
                return(new VerifyResult(Gateway.IranKish, referenceId, transactionId, VerifyResultStatus.Failed, "پاسخ دریافت شده از درگاه پرداخت قابل بررسی نیست."));
            }

            var isSuccess = integerResult != verifyPaymentContext.Amount;
            var status    = isSuccess ? VerifyResultStatus.Success : VerifyResultStatus.Failed;

            translatedResult = isSuccess ? "تراکنش با موفقیت انجام گردید." : gatewayResultTranslator.Translate(result);

            return(new VerifyResult(Gateway.IranKish, referenceId, transactionId, status, translatedResult));
        }
Пример #38
0
        public void LogTransaction(string clientAlias, string result, string duration, WebContextProxy context = null)
        {
            string ip = "";
            string method = "";
            string parameters = "";
            try
            {
            #if WEB
                WebHelper wh = new WebHelper();
                wh.GetContextOfRequest(out ip, out method, out parameters);
            #endif
                if (context != null)
                {
                    ip = context.ip;
                    method = context.method;
                    parameters = context.parameters;
                }
                LogTransaction(clientAlias, ip, method, parameters, result, duration);

                if (m_initCalled) //log the call that forced instantiation
                {
                    string message = "Call that forced instantiation:"
                                                + "\nip = " + ip
                                                + "\nmethod = " + method
                                                + "\nparameters = " + parameters;
                    BoostLog.Instance.WriteEntry(message, EventLogEntryType.Information, clientAlias);
                    m_initCalled = false;
                }
            }
            catch (Exception ex)
            {
                BoostLog log = BoostLog.Instance;
                if (log != null)
                {
                    log.Suffix = "ip = " + ip
                                        + "\nmethod = " + method
                                        + "\nparameters = " + parameters
                                        + "\nresult = " + result;
                    string errMsg = "Error logging transaction: " + ex.Message;
                    if (ex.InnerException != null)
                        errMsg += "\nInnerException: " + ex.InnerException.Message;
                    log.WriteEntry(errMsg, EventLogEntryType.Warning, clientAlias);
                }
            }
        }
Пример #39
0
        public async Task <IHttpActionResult> Order([FromBody] OrderParams orderParams)
        {
            // Diese Prüfung soll immer für den aktuellen Benutzer (also nicht für den Besteller) ablaufen gemäss Telefonat mit Marlies Hertig
            var basket = await GetBasket();

            if (basket == null || basket.Count(i => !i.EinsichtsbewilligungNotwendig) == 0)
            {
                throw new BadRequestException("Order not is allowed, because there are no items in basket");
            }

            var userAccess = GetUserAccess();

            var bestellerId = !string.IsNullOrWhiteSpace(orderParams.UserId)
                ? orderParams.UserId
                : ControllerHelper.GetCurrentUserId();
            var bestellungIstFuerAndererBenutzer = ControllerHelper.GetCurrentUserId() != bestellerId;

            if (bestellungIstFuerAndererBenutzer)
            {
                if (GetCurrentUserAccess().RolePublicClient != AccessRoles.RoleBAR)
                {
                    throw new BadRequestException(
                              "Es wird versucht, für einen anderen Benutzer als den aktuellen Benutzer zu bestellen. Dazu fehlt aber die Berechtigung.");
                }

                orderParams.Comment = string.Join(" ", orderParams.Comment,
                                                  FrontendSettingsViaduc.Instance.GetTranslation(WebHelper.GetClientLanguage(Request),
                                                                                                 "order.frombar", "(Diese Bestellung wurde durch das Bundesarchiv ausgelöst.)"));
            }

            var orderItemIdsToExclude = basket
                                        .Where(basketItem => basketItem.EinsichtsbewilligungNotwendig ||
                                               orderParams.Type == OrderType.Digitalisierungsauftrag &&
                                               orderParams.OrderIdsToExclude != null && orderParams.OrderIdsToExclude.Contains(basketItem.Id))
                                        .Select(item => item.Id)
                                        .ToList();

            DateTime?leseSaalDateAsDateTime = null;

            switch (orderParams.Type)
            {
            case OrderType.Verwaltungsausleihe:
                ValidateVerwaltungsausleiheBestellung(userAccess);
                break;

            case OrderType.Digitalisierungsauftrag:
                await ValidateDigitalisierungsauftragBestellung(bestellerId, bestellungIstFuerAndererBenutzer,
                                                                userAccess, basket, orderItemIdsToExclude);

                break;

            case OrderType.Lesesaalausleihen:
                leseSaalDateAsDateTime = orderParams.LesesaalDate.ParseDateTimeSwiss();
                ValidateLesesaalBestellung(leseSaalDateAsDateTime);
                break;

            default:
                throw new BadRequestException(
                          $"Bestelltyp {orderParams.Type.ToString()} ist hier nicht unterstützt.");
            }

            if (userAccess.RolePublicClient == AccessRoles.RoleAS)
            {
                orderParams.ArtDerArbeit = (int)verwaltungsausleiheSettings.ArtDerArbeitFuerAmtsBestellung;
            }

            var creationRequest = new OrderCreationRequest
            {
                OrderItemIdsToExclude = orderItemIdsToExclude,
                Type          = orderParams.Type,
                Comment       = orderParams.Comment,
                ArtDerArbeit  = orderParams.ArtDerArbeit,
                LesesaalDate  = leseSaalDateAsDateTime,
                CurrentUserId = ControllerHelper.GetCurrentUserId(),
                BestellerId   = bestellerId
            };

            var veInfoList = basket.Where(item => item.VeId.HasValue && !orderItemIdsToExclude.Contains(item.Id))
                             .Select(item => new VeInfo((int)item.VeId, item.Reason)).ToList();

            await kontrollstellenInformer.InformIfNecessary(userAccess, veInfoList);

            await client.CreateOrderFromBasket(creationRequest);

            return(Content <object>(HttpStatusCode.NoContent, null));
        }
Пример #40
0
        private string getDirTitle(string dir)
        {
            string defaultDoc = "Default.aspx";
            string defaultHtml = "Index.html";
            WebHelper wh = new WebHelper();
            string title = "";

            if (File.Exists(dir + folderSeparator + defaultDoc))
            {
                title = wh.GetTitleFromHtmlFile(dir + folderSeparator + defaultDoc);
            }
            else if (File.Exists(dir + folderSeparator + defaultHtml))
            {
                title = wh.GetTitleFromHtmlFile(dir + folderSeparator + defaultHtml);
            }

            return title;
        }
Пример #41
0
 public static string GetStringFromUrl(string url)
 {
     var h = new WebHelper(url);
     h.ImportFromWeb();
     return h._htmlContent;
 }
Пример #42
0
    ///////////////////////////////////////////////////////////////////////
    //  Name: DoNonSilentEnable
    //  Description:  Performs non-silent enable.
    /////////////////////////////////////////////////////////////////////////
    private void DoNonSilentEnable()
    {
        // Trust status for the URL.
        MFURLTrustStatus trustStatus = MFURLTrustStatus.Untrusted;

        int hr;
        string sURL;	            // Enable URL
        int cchURL = 0;             // Size of enable URL in characters.

        IntPtr pPostData;        // Buffer to hold HTTP POST data.
        int cbPostDataSize = 0;   // Size of buffer, in bytes.

        // Get the enable URL. This is where we get the enable data for non-silent enabling.
        hr = m_pEnabler.GetEnableURL(out sURL, out cchURL, out trustStatus);
        MFError.ThrowExceptionForHR(hr);

        Debug.WriteLine(string.Format("Content enabler: URL = {0}", sURL));
        LogTrustStatus(trustStatus);

        if (trustStatus != MFURLTrustStatus.Trusted)
        {
            throw new COMException("The enabler URL is not trusted. Failing.", E_Fail);
        }

        // Start the thread that monitors the non-silent enable action.
        hr = m_pEnabler.MonitorEnable();
        MFError.ThrowExceptionForHR(hr);

        // Get the HTTP POST data
        hr = m_pEnabler.GetEnableData(out pPostData, out cbPostDataSize);
        MFError.ThrowExceptionForHR(hr);

        try
        {
            WebHelper m_webHelper = new WebHelper();

            // Open the URL and send the HTTP POST data.
            m_webHelper.OpenURLWithData(sURL, pPostData, cbPostDataSize, m_hwnd);
        }
        finally
        {
            Marshal.FreeCoTaskMem(pPostData);
        }
    }
Пример #43
0
        public static string GoogleTranslate(string sourceWord, string fromLanguage, string toLanguage)
        {
            /* 
             调用: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=zh-CN|en&q=中国
             返回的json格式如下:
             {"responseData": {"translatedText":"Chinese people are good people"}, "responseDetails": null, "responseStatus": 200}*/
            string serverUrl = string.Format(@"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair={0}|{1}&q={2}", fromLanguage, toLanguage, sourceWord);

            string resJson = new WebHelper().Get(serverUrl);
            int textIndex = resJson.IndexOf("translatedText") + 17;
            int textLen = resJson.IndexOf("\"", textIndex) - textIndex;
            return resJson.Substring(textIndex, textLen);
        }
Пример #44
0
 public static Stream OpenStream(Uri uri)
 {
     WebHelper web = new WebHelper();
     web.SendRequest(uri);
     return web.Stream;
 }
Пример #45
0
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            JObject entry;

            context.ResponsePayload.TryToJObject(out entry);

            if (entry != null && entry.Type == JTokenType.Object && context.OdataMetadataType == ODataMetadataType.MinOnly)
            {
                JsonParserHelper.ClearProperyValsList();
                List <JToken> odataMetadataVals = JsonParserHelper.GetSpecifiedPropertyValsFromEntryPayload(entry, Constants.OdataV4JsonIdentity, MatchType.Equal);

                JsonParserHelper.ClearProperyValsList();
                List <JToken> navigationLinkVals = JsonParserHelper.GetSpecifiedPropertyValsFromEntryPayload(entry, Constants.OdataNavigationLinkPropertyNameSuffix, MatchType.Contained);

                string url = string.Empty;

                if (odataMetadataVals.Count == 1)
                {
                    string odataMetadataValStr = odataMetadataVals[0].ToString().Trim('"');
                    int    index = odataMetadataValStr.IndexOf(Constants.Metadata);
                    url = odataMetadataValStr.Remove(index, odataMetadataValStr.Length - index);

                    foreach (var navigationLinkVal in navigationLinkVals)
                    {
                        if (Uri.IsWellFormedUriString(navigationLinkVal.ToString().Trim('"'), UriKind.Relative))
                        {
                            url += navigationLinkVal.ToString().Trim('"');
                        }
                        else
                        {
                            url = navigationLinkVal.ToString().Trim('"');
                        }

                        Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);

                        // Send a request with "application/json;odata=minimalmetadata" in Accept header.
                        string   acceptHeader = Constants.V4AcceptHeaderJsonMinimalMetadata;
                        Response response     = WebHelper.Get(uri, acceptHeader, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

                        // If response's status code is not equal to 200, it will indicate the url cannot be computed.
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            passed = true;
                        }
                        else
                        {
                            passed = false;
                            info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                            break;
                        }
                    }
                }
            }

            return(passed);
        }
Пример #46
0
 public OrayClient()
 {
     _httpClient = new WebHelper();
 }
Пример #47
0
        public ActionResult Warnings()
        {
            var model = new List <SystemWarningModel>();
            var store = _services.StoreContext.CurrentStore;

            // Store URL
            // ====================================
            var storeUrl = store.Url.EnsureEndsWith("/");

            if (storeUrl.HasValue() && (storeUrl.IsCaseInsensitiveEqual(_services.WebHelper.GetStoreLocation(false)) || storeUrl.IsCaseInsensitiveEqual(_services.WebHelper.GetStoreLocation(true))))
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.URL.Match")
                });
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.URL.NoMatch"), storeUrl, _services.WebHelper.GetStoreLocation(false))
                });
            }

            // TaskScheduler reachability
            // ====================================
            string taskSchedulerUrl = null;

            try
            {
                taskSchedulerUrl = Path.Combine(_taskScheduler.BaseUrl.EnsureEndsWith("/"), "noop").Replace(Path.DirectorySeparatorChar, '/');
                var request = WebHelper.CreateHttpRequestForSafeLocalCall(new Uri(taskSchedulerUrl));
                request.Method  = "HEAD";
                request.Timeout = 5000;

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var status       = response.StatusCode;
                    var warningModel = new SystemWarningModel();
                    warningModel.Level = (status == HttpStatusCode.OK ? SystemWarningLevel.Pass : SystemWarningLevel.Fail);

                    if (status == HttpStatusCode.OK)
                    {
                        warningModel.Text = T("Admin.System.Warnings.TaskScheduler.OK");
                    }
                    else
                    {
                        warningModel.Text = T("Admin.System.Warnings.TaskScheduler.Fail", _taskScheduler.BaseUrl, status + " - " + status.ToString());
                    }

                    model.Add(warningModel);
                }
            }
            catch (WebException exception)
            {
                var msg = T("Admin.System.Warnings.TaskScheduler.Fail", _taskScheduler.BaseUrl, exception.Message);

                var xxx = T("Admin.System.Warnings.TaskScheduler.Fail");

                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = msg
                });

                Logger.Error(exception, msg);
            }

            // Sitemap reachability
            // ====================================
            string sitemapUrl = null;

            try
            {
                sitemapUrl = WebHelper.GetAbsoluteUrl(Url.RouteUrl("SitemapSEO"), this.Request);
                var request = WebHelper.CreateHttpRequestForSafeLocalCall(new Uri(sitemapUrl));
                request.Method  = "HEAD";
                request.Timeout = 15000;

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var status       = response.StatusCode;
                    var warningModel = new SystemWarningModel();
                    warningModel.Level = (status == HttpStatusCode.OK ? SystemWarningLevel.Pass : SystemWarningLevel.Warning);

                    switch (status)
                    {
                    case HttpStatusCode.OK:
                        warningModel.Text = T("Admin.System.Warnings.SitemapReachable.OK");
                        break;

                    default:
                        if (status == HttpStatusCode.MethodNotAllowed)
                        {
                            warningModel.Text = T("Admin.System.Warnings.SitemapReachable.MethodNotAllowed");
                        }
                        else
                        {
                            warningModel.Text = T("Admin.System.Warnings.SitemapReachable.Wrong");
                        }

                        warningModel.Text = string.Concat(warningModel.Text, " ", T("Admin.Common.HttpStatus", (int)status, status.ToString()));
                        break;
                    }

                    model.Add(warningModel);
                }
            }
            catch (WebException exception)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = T("Admin.System.Warnings.SitemapReachable.Wrong")
                });

                Logger.Warn(exception, T("Admin.System.Warnings.SitemapReachable.Wrong"));
            }

            // Primary exchange rate currency
            // ====================================
            var perCurrency = store.PrimaryExchangeRateCurrency;

            if (perCurrency != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Set"),
                });

                if (perCurrency.Rate != 1)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Rate1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.NotSet")
                });
            }

            // Primary store currency
            // ====================================
            var pscCurrency = store.PrimaryStoreCurrency;

            if (pscCurrency != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.Set"),
                });
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.NotSet")
                });
            }


            // Base measure weight
            // ====================================
            var bWeight = _measureService.Value.GetMeasureWeightById(_measureSettings.Value.BaseWeightId);

            if (bWeight != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Set"),
                });

                if (bWeight.Ratio != 1)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.NotSet")
                });
            }


            // Base dimension weight
            // ====================================
            var bDimension = _measureService.Value.GetMeasureDimensionById(_measureSettings.Value.BaseDimensionId);

            if (bDimension != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Set"),
                });

                if (bDimension.Ratio != 1)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.NotSet")
                });
            }

            // Shipping rate coputation methods
            // ====================================
            int activeShippingMethodCount = 0;

            try
            {
                activeShippingMethodCount = _shippingService.Value.LoadActiveShippingRateComputationMethods()
                                            .Where(x => x.Value.ShippingRateComputationMethodType == ShippingRateComputationMethodType.Offline)
                                            .Count();
            }
            catch { }

            if (activeShippingMethodCount > 1)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Shipping.OnlyOneOffline")
                });
            }

            // Payment methods
            // ====================================
            int activePaymentMethodCount = 0;

            try
            {
                activePaymentMethodCount = _paymentService.Value.LoadActivePaymentMethods().Count();
            }
            catch { }

            if (activePaymentMethodCount > 0)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.OK")
                });
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.NoActive")
                });
            }

            // Incompatible plugins
            // ====================================
            if (PluginManager.IncompatiblePlugins != null)
            {
                foreach (var pluginName in PluginManager.IncompatiblePlugins)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.IncompatiblePlugin"), pluginName)
                    });
                }
            }

            // Validate write permissions (the same procedure like during installation)
            // ====================================
            var dirPermissionsOk = true;
            var dirsToCheck      = FilePermissionHelper.GetDirectoriesWrite(_services.WebHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.Wrong"), WindowsIdentity.GetCurrent().Name, dir)
                    });
                    dirPermissionsOk = false;
                }
            }
            if (dirPermissionsOk)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.OK")
                });
            }

            var filePermissionsOk = true;
            var filesToCheck      = FilePermissionHelper.GetFilesWrite(_services.WebHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.FilePermission.Wrong"), WindowsIdentity.GetCurrent().Name, file)
                    });
                    filePermissionsOk = false;
                }
            }
            if (filePermissionsOk)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.FilePermission.OK")
                });
            }

            return(View(model));
        }
Пример #48
0
        private string GetSuffix()
        {
            var suffix = "";
            #if WEB
            try
            {
                var wh = new WebHelper();
                var wc = wh.GetContextOfRequest();
                suffix = wc.ToString();

                //get memory usage
                Process proc = Process.GetCurrentProcess();
                suffix += "\nCurrent RAM usage: " + proc.PrivateMemorySize64.ToString("N0");
            }
            catch (Exception ex)
            {
                suffix += "\n\nError getting context: " + ex.Message;
            }
            #endif
            return suffix;
        }
Пример #49
0
 public void AddCurrent(OperatorModel operatorModel)
 {
     WebHelper.WriteSession(LoginUserKey, DESEncrypt.Encrypt(operatorModel.ToJson()));
 }
Пример #50
0
        /// <summary>
        ///     Converts the database order items to an OrderItemDto array.
        ///     The OrderItemDto objects are returned to the calling UI.
        ///     For performance reasons security info is loaded when needed.
        /// </summary>
        /// <param name="orderItemsDb">The order items as fetched from the database.</param>
        /// <param name="orderType">Type of the order.</param>
        /// <param name="needsSecurityInfo">
        ///     if set to <c>true</c> the properties <c>EinsichtsbewilligungNotwendig</c> and <c>CouldNeedAReason</c> are
        ///     correctly filled using information from the elastic index.
        /// </param>
        /// <returns>OrderItemDto[].</returns>
        private OrderItemDto[] ConvertDbItemsToDto(List <OrderItem> orderItemsDb, OrderType orderType,
                                                   bool needsSecurityInfo)
        {
            var orderItemsRet = new List <OrderItemDto>();

            foreach (var itemDb in orderItemsDb)
            {
                orderItemsRet.Add(new OrderItemDto
                {
                    ReferenceCode                  = itemDb.Signatur,
                    Title                          = itemDb.Dossiertitel,
                    Period                         = itemDb.ZeitraumDossier,
                    VeId                           = itemDb.VeId,
                    Id                             = itemDb.Id,
                    Comment                        = itemDb.Comment,
                    BewilligungsDatum              = itemDb.BewilligungsDatum,
                    HasPersonendaten               = itemDb.HasPersonendaten,
                    Hierarchiestufe                = itemDb.Hierarchiestufe,
                    ZusaetzlicheInformationen      = itemDb.ZusaetzlicheInformationen,
                    Darin                          = itemDb.Darin,
                    Signatur                       = itemDb.Signatur,
                    ZustaendigeStelle              = itemDb.ZustaendigeStelle,
                    Publikationsrechte             = itemDb.Publikationsrechte,
                    Behaeltnistyp                  = itemDb.Behaeltnistyp,
                    IdentifikationDigitalesMagazin = itemDb.IdentifikationDigitalesMagazin,
                    ZugaenglichkeitGemaessBga      = itemDb.ZugaenglichkeitGemaessBga,
                    Standort                       = itemDb.ZugaenglichkeitGemaessBga,
                    Schutzfristverzeichnung        = itemDb.Schutzfristverzeichnung,
                    ExternalStatus                 = OrderStatusTranslator.GetExternalStatus(orderType, itemDb.Status),
                    Reason                         = itemDb.Reason,
                    Aktenzeichen                   = itemDb.Aktenzeichen,
                    DigitalisierungsKategorie      = itemDb.DigitalisierungsKategorie,
                    TerminDigitalisierung          = itemDb.TerminDigitalisierung,
                    EntscheidGesuch                = itemDb.EntscheidGesuch,
                    DatumDesEntscheids             = itemDb.DatumDesEntscheids,
                    Abbruchgrund                   = itemDb.Abbruchgrund
                });
            }

            // Fügt sicherheitsrelevante Informationen zum order item hinzu
            if (needsSecurityInfo)
            {
                var veIdList = orderItemsDb.Where(item => item.VeId != null).Select(item => (int)item.VeId).ToList();

                UserAccess access = null;
                List <Entity <ElasticArchiveRecord> > orderItemsElastic = null;

                if (veIdList.Count > 0)
                {
                    access = GetUserAccess(WebHelper.GetClientLanguage(Request));
                    // Need to call without security, as the list of manual added basket items could contain items that are not visible to the user
                    // but depending on the data we need to fill the properties EinsichtsbewilligungNotwendig and CouldNeedAReason
                    orderItemsElastic = elasticService.QueryForIdsWithoutSecurityFilter <ElasticArchiveRecord>(veIdList,
                                                                                                               new Paging {
                        Take = ElasticService.ELASTIC_SEARCH_HIT_LIMIT, Skip = 0
                    }).Entries;
                }

                if (orderItemsElastic != null)
                {
                    foreach (var itemDto in orderItemsRet.Where(i => i.VeId.HasValue))
                    {
                        var elasticData = orderItemsElastic
                                          .FirstOrDefault(item => itemDto.VeId.ToString() == item.Data.ArchiveRecordId)?.Data;
                        if (elasticData != null)
                        {
                            itemDto.EinsichtsbewilligungNotwendig = IsEinsichtsbewilligungNotwendig(elasticData, access,
                                                                                                    itemDto.BewilligungsDatum.HasValue);
                            itemDto.CouldNeedAReason = CouldNeedAReason(elasticData, access);
                        }
                    }
                }
            }

            return(orderItemsRet.ToArray());
        }
Пример #51
0
        public void DownloadStringAsyncTest()
        {
            var result = WebHelper.DownloadStringAsync(new Uri(@"https://dotnettips.com"), clientId: "UNITTEST1").Result;

            Assert.IsNotNull(result);
        }
Пример #52
0
        public OpenStackStorage(string url, Dictionary<string, string> options)
        {
            var uri = new Utility.Uri(url);

            m_container = uri.Host;
            m_prefix = "/" + uri.Path;
            if (!m_prefix.EndsWith("/"))
                m_prefix += "/";

            // For OpenStack we do not use a leading slash
            if (m_prefix.StartsWith("/"))
                m_prefix = m_prefix.Substring(1);

            options.TryGetValue(USERNAME_OPTION, out m_username);
            options.TryGetValue(PASSWORD_OPTION, out m_password);
            options.TryGetValue(TENANTNAME_OPTION, out m_tenantName);
            options.TryGetValue(AUTHURI_OPTION, out m_authUri);
            options.TryGetValue(APIKEY_OPTION, out m_apikey);
            options.TryGetValue(REGION_OPTION, out m_region);

            if (string.IsNullOrWhiteSpace(m_username))
                throw new Exception(Strings.OpenStack.MissingOptionError(USERNAME_OPTION));
            if (string.IsNullOrWhiteSpace(m_authUri))
                throw new Exception(Strings.OpenStack.MissingOptionError(AUTHURI_OPTION));

            if (string.IsNullOrWhiteSpace(m_apikey))
            {
                if (string.IsNullOrWhiteSpace(m_password))
                    throw new Exception(Strings.OpenStack.MissingOptionError(PASSWORD_OPTION));
                if (string.IsNullOrWhiteSpace(m_tenantName))
                    throw new Exception(Strings.OpenStack.MissingOptionError(TENANTNAME_OPTION));
            }

            m_helper = new WebHelper(this);
        }
Пример #53
0
 private UserAccess GetCurrentUserAccess()
 {
     return(GetUserAccess(WebHelper.GetClientLanguage(Request)));
 }