Пример #1
0
        /// <summary>
        ///  控件值给DataLink
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="dbConn"></param>
        /// <param name="txtHostName"></param>
        /// <param name="txtUserName"></param>
        /// <param name="txtPwd"></param>
        /// <param name="txtPort"></param>
        /// <param name="txtServerName"></param>
        /// <param name="labServerName"></param>
        /// <returns></returns>
        public static DataLink ControlsToData(string dbType, TextBox txtHostName, TextBox txtUserName, TextBox txtPwd,
                                              TextBox txtPort, TextBox txtServerName, Label labServerName, bool isLink = false, TextBox txtLinkName = null)
        {
            var item = new DataLink();

            item.dbType      = dbType;
            item.hostName    = txtHostName.Text.Trim();
            item.userName    = txtUserName.Text.Trim();
            item.userPwd     = txtPwd.Text.Trim();
            item.port        = txtPort.Text.Trim();
            item.serverValue = txtServerName.Text.Trim();
            item.serverName  = labServerName.Content.ToString();

            if (isLink)
            {
                if (txtLinkName.Text.Trim() == "")
                {
                    item.linkName = GetLinkName(AppCache.GetBuildLink());
                }
                else
                {
                    item.linkName = txtLinkName.Text.Trim();
                }
            }

            return(item);
        }
Пример #2
0
        public void Throws_On_Reentry()
        {
            // don't run for DictionaryAppCache - not making sense
            if (GetType() == typeof(DictionaryAppCacheTests))
            {
                Assert.Ignore("Do not run for DictionaryAppCache.");
            }

            Exception exception = null;
            var       result    = AppCache.Get("blah", () =>
            {
                try
                {
                    var result2 = AppCache.Get("blah");
                }
                catch (Exception e)
                {
                    exception = e;
                }
                return("value");
            });

            Assert.IsNotNull(exception);
            Assert.IsAssignableFrom <InvalidOperationException>(exception);
        }
Пример #3
0
        /// <summary>
        /// 删除多个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelMore_Item(object sender, RoutedEventArgs e)
        {
            var count    = 0;
            var listFrom = AppCache.GetFromList();

            foreach (var item in fromTable.Items)
            {
                var box = Common.GetTemplateColumn <CheckBox>(fromTable, 0, "fromBox", item);
                if (box != null && box.IsChecked == true)
                {
                    count++;
                    var colItem = item as FromItems;
                    listFrom.RemoveAll(a => a.colId == colItem.colId);
                }
            }

            AppCache.SetFromList(listFrom);

            if (count == 0)
            {
                CodeBox.Show("请选择要删除的列", this);
            }
            else
            {
                fromTable.ItemsSource = AppCache.GetFromList();
                Common.DataGridSort(fromTable, "tabName", ListSortDirection.Ascending);
            }
        }
Пример #4
0
        /// <summary>
        /// 生成实体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Build_Define(object sender, RoutedEventArgs e)
        {
            var table = new BaseTable();
            var info  = new EntityInfo();

            table.tabComments = txtComments.Text.Trim();
            table.tabName     = txtName.Text.Trim();

            info.columns     = AppCache.GetDefineColumnList();
            info.modelFile   = txtFile;
            info.nameSpace   = txtNameSpace.Text.Trim();
            info.table       = table;
            info.language    = language.SelectionBoxItem.ToString();
            info.isSerialize = (bool)isSerialize.IsChecked;
            info.isCheck     = (bool)isCheck.IsChecked;
            info.isModel     = (bool)isModel.IsChecked;

            if (!info.isCheck && !info.isSerialize && !info.isMap && !info.isModel)
            {
                CodeBox.Show("请选择模板", this);
            }

            info.columns = info.disColType(info.columns, info.language);

            if (Common.BuildCodeModel(info))
            {
                CodeBox.Show("生成成功", this);
                AppCache.SetDefineSoureTable(null);
                AppCache.SetDefineColumnList(null);
            }
            else
            {
                CodeBox.Show("生成失败", this);
            }
        }
Пример #5
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            dbConn = BaseLink.GetConnStr(dbType, txtUserName, txtPwd, txtHostName, txtPort, txtServerName);

            if (!BaseLink.CheckLink(dbType, dbConn))
            {
                CodeBox.Show("连接数据库失败!", this);
            }
            else
            {
                var buildLink = BaseLink.ControlsToData(dbType, txtHostName, txtUserName, txtPwd, txtPort, txtServerName, labServerName, true, txtLinkName);
                buildLink.LinkName = buildLink.LinkName == "" ? BaseLink.GetLinkName(buildLink) : buildLink.LinkName;
                buildLink.Id       = Guid.NewGuid().ToString();
                AppCache.SetLink(buildLink);

                if (FastRead.Query <Data_Source>(a => a.LinkName == buildLink.LinkName).ToCount() == 1)
                {
                    FastWrite.Update <Data_Source>(buildLink, a => a.LinkName == buildLink.LinkName,
                                                   a => new { a.Host, a.PassWord, a.Port, a.ServerName, a.Type, a.UserName });
                }
                else
                {
                    FastWrite.Add(buildLink);
                }

                CodeBox.Show("连接数据库成功!", this);
            }
        }
Пример #6
0
        public static void Set <T>(string key, T value, TimeSpan timeSpan, bool async = true, bool isCacheFile = false)
        {
            AppCache.Set(key, value, TimeSpan.FromSeconds(AutoAppCacheSeconds));

            if (async)
            {
                Task.Run(async() =>
                {
                    await Task.Delay(1);
                    if (isCacheFile)
                    {
                        var cacheResultJson = ConvertJson(value);
                        var cacheFileName   = CacheFile(key, cacheResultJson, typeof(T).FullName);
                    }
                    else
                    {
                        RedisCache.Set(key, value, timeSpan);
                        //RedisCache.Set3(key, value, timeSpan);
                    }
                });
            }
            else
            {
                if (isCacheFile)
                {
                    var cacheResultJson = ConvertJson(value);
                    var cacheFileName   = CacheFile(key, cacheResultJson, typeof(T).FullName);
                }
                else
                {
                    RedisCache.Set(key, value, timeSpan);
                    //RedisCache.Set3(key, value, timeSpan);
                }
            }
        }
Пример #7
0
        public static dynamic Get <T>(string key, double restoreAppCahcheSeconds = AutoAppCacheSeconds)
        {
            AppCache.TryGetValue <T>(key, out var value);

            if (value == null)
            {
                value = RedisCache.Get2 <T>(key);

                // 恢复本地缓存 todo 调整时间为1分钟?
                if (restoreAppCahcheSeconds != 0)
                {
                    Task.Run(async() =>
                    {
                        await Task.Delay(1);
                        if (restoreAppCahcheSeconds == -1)
                        {
                            var remainTime = RedisCache.KeyTimeToLive(key);
                            if (remainTime != null)
                            {
                                restoreAppCahcheSeconds = remainTime.Value.TotalSeconds;
                            }
                        }
                        AppCache.Set <T>(key, value, TimeSpan.FromSeconds(restoreAppCahcheSeconds));
                    });
                }
            }
            return(value);
        }
Пример #8
0
        /// <summary>
        /// 删除多个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelMore_Define(object sender, RoutedEventArgs e)
        {
            var count      = 0;
            var listTable  = AppCache.GetDefineSoureTable();
            var listColumn = AppCache.GetDefineColumnList();

            foreach (var item in DefineTable.Items)
            {
                var box = Common.GetTemplateColumn <CheckBox>(DefineTable, 0, "defBox", item);
                if (box != null && box.IsChecked == true)
                {
                    count++;
                    var colItem = item as DefineSoureTable;

                    listTable.RemoveAll(a => a.colId == colItem.colId);
                    listColumn.RemoveAll(a => a.colId == colItem.colId);
                }
            }

            AppCache.SetDefineColumnList(listColumn);
            AppCache.SetDefineSoureTable(listTable);

            if (count == 0)
            {
                CodeBox.Show("请选择要删除的列", this);
            }
            else
            {
                DefineTable.ItemsSource = AppCache.GetDefineSoureTable();
                Common.DataGridSort(DefineTable, "tabName", ListSortDirection.Ascending);
            }
        }
Пример #9
0
        public void Does_Not_Cache_Exceptions()
        {
            var counter = 0;

            object result;

            try
            {
                result = AppCache.Get("Blah", () =>
                {
                    counter++;
                    throw new Exception("Do not cache this");
                });
            }
            catch (Exception) {}

            try
            {
                result = AppCache.Get("Blah", () =>
                {
                    counter++;
                    throw new Exception("Do not cache this");
                });
            }
            catch (Exception) {}

            Assert.Greater(counter, 1);
        }
Пример #10
0
        private void JoinMeeting()
        {
            var currentWindow = Application.Current.Windows;
            var window        = currentWindow[0];

            //判断当前是否在课堂中

            if (window is IntoClassView)
            {
                MessageQueueManager.Instance.AddError("已经在课堂中");
                return;
            }

            //预约会议
            var course = DoUpdateCurriculumMeetingN0(GlobalData.Instance.Courses);

            AppCache.AddOrUpdate(CacheKey.MeetingId, course.MeetingId);
            GlobalData.Instance.Course = course;
            //判断该课堂视讯号与当前登录人的视讯号是否相同,如果相同,设置为主讲
            var mainclassroom = GlobalData.Instance.Classrooms.ToList().FirstOrDefault(o => o.Id == course.MainClassroomId.ToString());

            if (mainclassroom != null)
            {
                AppCache.AddOrUpdate(CacheKey.HostId, mainclassroom.SchoolRoomNum);
            }
            var intoClassView = new IntoClassView(IntoClassType.Join);

            intoClassView.Show();
            window?.Close();
        }
Пример #11
0
        public async Task <ServiceResponse <bool> > Login()
        {
            // get token
            var resultAuth = await _adAuthService.Authenticate(CrossCurrentActivity.Current);

            if (resultAuth == null)
            {
                return(false.AsServiceResponse());
            }

            // Crucial part : tie up with rest client
            _restClient.SetCurrentAuthToken(resultAuth.Data.authToken);

            var resultUser = await _userService.GetOrCreateUser(resultAuth.Data.UniqueId);

            if (!resultUser.IsOK() || resultUser.Data == null)
            {
                return(resultUser.ToServiceResponse <LinCUser, bool>());
            }

            AppCache.State.Member = resultUser.Data;

            //AppCache.State.Credential.AuthToken = resultAuth.Data.authToken;
            //AppCache.State.Credential.Username = resultAuth.Data.Username;
            //AppCache.State.Credential.UserID = resultAuth.Data.UniqueId;

            await AppCache.Save();

            return(true.AsServiceResponse());
        }
Пример #12
0
        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as AppBarButton;
            var msg    = "TODO: open " + button.Label + " page";

            switch (button.Label)
            {
            case "Menü":
                this.Frame.Navigate(typeof(FoodMenuPage));
                return;

            case "Kedvencek":
                this.Frame.Navigate(typeof(RecipesPage), new RecipesPageViewModel()
                {
                    Title   = "Kedvencek",
                    Recipes = AppCache.GetFavourites()
                });
                return;

            case "Mi van itthon?":
                //TODO:
                break;
            }
            //TODO: remove this
            new Windows.UI.Popups.MessageDialog(msg).ShowAsync();
        }
Пример #13
0
    public static void Application_Start()
    {
//		string connName = System.Diagnostics.Debugger.IsAttached ? "LocalConnectionString" : "AppConnectionString";
        connStr         = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
        providerFactory = new SqlServerProvider();
        connFactory     = providerFactory.CreateConnectionFactory(connStr);
        log             = new Log(null);
        log.Info("Application_Start");
        try
        {
            app      = new App(connFactory);
            appCache = new AppCache();

//			app.hhImport.Import(log);//!!! test

            timer.Interval = double.Parse(WebConfigurationManager.AppSettings["timerIntervalSec"]) * 1000;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Enabled  = true;
        }
        catch (Exception ex)
        {
            log.Exception(ex);
//			throw ex;
        }
    }
Пример #14
0
        public void Can_Add_Items_To_Cache()
        {
            // Arrange
            ICache<string, object> cache = new AppCache(2);

            var key1 = "key1";
            var key2 = "key2";
            var val1 = 1;
            var val2 = 2;

            // Act
            cache.AddOrUpdate(key1, val1);
            cache.AddOrUpdate(key2, val2);

            object actual1;
            cache.TryGetValue(key1, out actual1);

            object actual2;
            cache.TryGetValue(key2, out actual2);

            // Assert 
            cache.Count.Should().Be(2);
            actual1.Should().Be(val1);
            actual2.Should().Be(val2);
        }
Пример #15
0
        /// <summary>
        /// 加载
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            Common.InitWindows(this, ResizeMode.CanMinimize, WindowStartupLocation.CenterScreen);

            #region 托盘初始化
            var notifyIcon = new NotifyIcon();
            AppCache.SetTitle(this.Title);
            notifyIcon.BalloonTipText = AppCache.GetTitle();
            notifyIcon.Text           = AppCache.GetTitle();

            notifyIcon.Icon    = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
            notifyIcon.Visible = true;

            //打开菜单项
            var open = new System.Windows.Forms.MenuItem(string.Format("打开{0}", AppCache.GetTitle()));
            open.Click += new EventHandler(Show);

            //退出菜单项
            var exit = new System.Windows.Forms.MenuItem(string.Format("退出{0}", AppCache.GetTitle()));
            exit.Click += new EventHandler(Close);

            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit };
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);

            //双击
            notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) => { if (e.Button == MouseButtons.Left)
                                                                                                  {
                                                                                                      this.Show(o, e);
                                                                                                  }
                                                                                      });
            #endregion
        }
Пример #16
0
        private async Task SendInvitationAsync(TextWithButtonItem arg)
        {
            try
            {
                var invitName = GlobalData.Instance.Classrooms.FirstOrDefault(classroom => classroom.SchoolRoomNum == arg.Id)?.SchoolRoomName;
                //执行邀请方法

                object meetingIdObj = AppCache.TryGet(CacheKey.MeetingId);

                int meetingId;
                if (meetingIdObj != null && int.TryParse(meetingIdObj.ToString(), out meetingId))
                {
                    int[] invitees = new int[] { int.Parse(arg.Id) };
                    var   result   = await _meetingService.MeetingInvite(meetingId, invitees);

                    if (result.StatusCode != 0)
                    {
                        Log.Logger.Error($"邀请失败信息:{result.Message}");
                        MessageQueueManager.Instance.AddError(string.IsNullOrEmpty(result.Message) ? "邀请失败!" : result.Message);
                    }
                    else
                    {
                        arg.Content          = "已邀请";
                        arg.ButtonBackground = new SolidColorBrush(Colors.White);
                        arg.ButtonForeground = (SolidColorBrush)Application.Current.Resources["ThemeBrush"];
                        arg.ButtonVisibility = Visibility.Visible;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error($"邀请发生异常 exception:{ex}");
                MessageQueueManager.Instance.AddError("邀请失败!");
            }
        }
Пример #17
0
        private void UpdateMeeting(MeetingList meetingList, string creatorName, string createTime)
        {
            var currentMeeting =
                meetingList.MeetingInfos.FirstOrDefault(o => o.MeetingId == (int)AppCache.TryGet(CacheKey.MeetingId));

            if (currentMeeting == null)
            {
                MeetingItem meetingItem = new MeetingItem()
                {
                    LastActivityTime = DateTime.Now,
                    MeetingId        = (int)AppCache.TryGet(CacheKey.MeetingId),
                    CreatorName      = creatorName,
                    IsClose          = false,
                    CreatorId        = AppCache.TryGet(CacheKey.HostId).ToString(),
                };

                if (!string.IsNullOrEmpty(createTime))
                {
                    meetingItem.CreateTime = DateTime.Parse(createTime);
                }

                meetingList.MeetingInfos.Add(meetingItem);
            }
            else
            {
                currentMeeting.LastActivityTime = DateTime.Now;
            }
            _localDataManager.SaveMeetingList(meetingList);
        }
Пример #18
0
 public ShowQuestObjectRule(
     IObjectVisibilityService ovs,
     AppCache cache)
 {
     _ovs   = ovs;
     _cache = cache;
 }
Пример #19
0
        public void Can_Add_When_Not_Available()
        {
            var cacheContent1 = new MacroCacheContent();

            AppCache.Get("Test1", () => cacheContent1);
            Assert.AreEqual(1, GetTotalItemCount);
        }
Пример #20
0
        public static async Task <DateTime?> LoadItemsAsync <T>(CacheSettings settings, Func <Task <IEnumerable <T> > > loadDataAsync, Action <CachedContent <T> > parseItems, bool refreshForced = false)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrEmpty(settings.Key))
            {
                throw new ArgumentException("Cache key is required");
            }

            var dataInCache = await AppCache.GetItemsAsync <T>(settings.Key);

            if (dataInCache != null)
            {
                parseItems(dataInCache);
            }

            if (CanPerformLoad <T>(settings.NeedsNetwork) && (refreshForced || DataNeedToBeUpdated(dataInCache, settings.Expiration)))
            {
                dataInCache = dataInCache ?? new CachedContent <T>();

                dataInCache.Timestamp = DateTime.Now;
                dataInCache.Items     = await loadDataAsync();

                await AppCache.AddItemsAsync(settings.Key, dataInCache, settings.UseStorage);

                parseItems(dataInCache);
            }
            return(dataInCache?.Timestamp);
        }
        public static GroupedListViewModel CreateNew <TSchema>(SectionConfigBase <TSchema> sectionConfig) where TSchema : SchemaBase
        {
            var vm = new GroupedListViewModel
            {
                SectionName  = sectionConfig.Name,
                Title        = sectionConfig.ListPage.Title,
                PageTitle    = sectionConfig.ListPage.PageTitle,
                HasLocalData = !sectionConfig.NeedsNetwork,
                _orderType   = sectionConfig.ListPage.OrderType
            };

            var settings = new CacheSettings
            {
                Key          = sectionConfig.Name,
                Expiration   = vm.CacheExpiration,
                NeedsNetwork = sectionConfig.NeedsNetwork,
                UseStorage   = sectionConfig.NeedsNetwork,
            };

            //we save a reference to the load delegate in order to avoid export TSchema outside the view model
            vm.LoadDataInternal = (refresh) => AppCache.LoadItemsAsync <TSchema>(settings, sectionConfig.LoadDataAsyncFunc, (content) => vm.ParseItems(sectionConfig.ListPage, content), refresh);

            if (sectionConfig.NeedsNetwork)
            {
                vm.Actions.Add(new ActionInfo
                {
                    Command    = vm.Refresh,
                    Style      = ActionKnownStyles.Refresh,
                    Name       = "RefreshButton",
                    ActionType = ActionType.Primary
                });
            }

            return(vm);
        }
Пример #22
0
        private void CreateClass()
        {
            if (GlobalData.Instance.ConfigManager?.AudioInfo?.AudioSammpleDevice == null)
            {
                MessageQueueManager.Instance.AddError(MessageManager.NoAudioDevice);
                return;
            }
            if (string.IsNullOrEmpty(GlobalData.Instance.ConfigManager?.MainVideoInfo?.VideoDevice))
            {
                MessageQueueManager.Instance.AddError(MessageManager.NoVideoDevice);
                return;
            }

            var invitees = from classroom in Classrooms
                           where classroom.Selected
                           select new MeetingSdk.Wpf.Participant(new AccountModel(int.Parse(classroom.Classroom.SchoolRoomNum), classroom.Classroom.SchoolRoomName));

            AppCache.AddOrUpdate(CacheKey.Invitees, invitees);
            AppCache.AddOrUpdate(CacheKey.HostId, _windowManager.Participant.Account.AccountId);

            var intoClassView = new IntoClassView(IntoClassType.Create);

            intoClassView.Show();

            _createClassView.Close();
        }
Пример #23
0
        public void Cannot_Add_Item_With_Null_Key()
        {
            var cache = new AppCache(5);

            Action action = () => cache.AddOrUpdate(null, 5);

            action.Should().Throw<ArgumentException>();
        }
 public ApplicationContext()
 {
     Log = Environment.UserInteractive ? Console.WriteLine : new Action <string>(s1 => Debug.WriteLine(s1));
     ConfigureInstall = (installer, processInstaller) => { };
     Container        = () => { throw new NotImplementedException(); };
     Cache            = new AppCache();
     Services         = new List <IWindowsService>();
 }
Пример #25
0
 public static SessionInfo GetSessionByToken(string token)
 {
     if (string.IsNullOrEmpty(token))
     {
         return(null);
     }
     return(AppCache.GetCache <SessionInfo>(token));
 }
Пример #26
0
 /// <summary>
 /// 显示视图结构
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Show_View(object sender, RoutedEventArgs e)
 {
     if (!AppCache.ExistsView(AppCache.GetBuildLink()))
     {
         AppCache.SetViewList(DataSchema.ViewList(AppCache.GetBuildLink()) ?? new List <BaseTable>(), AppCache.GetBuildLink());
     }
     Dtable.DataContext = AppCache.GetViewList(AppCache.GetBuildLink());
 }
Пример #27
0
 public ObjectProcessingService(INWScript script,
                                AppCache cache,
                                IErrorService error)
 {
     _      = script;
     _cache = cache;
     _error = error;
 }
Пример #28
0
 public EnmityService(INWScript script,
                      AppCache cache,
                      IPlayerStatService playerStat)
 {
     _           = script;
     _cache      = cache;
     _playerStat = playerStat;
 }
 public ObjectProcessingService(INWScript script,
                                AppCache cache,
                                IErrorService error)
 {
     _            = script;
     _cache       = cache;
     _error       = error;
     _dateLastRun = DateTime.UtcNow;
 }
Пример #30
0
        public void Can_Get_When_Available()
        {
            var cacheContent1 = new MacroCacheContent();
            var result        = AppCache.Get("Test1", () => cacheContent1);
            var result2       = AppCache.Get("Test1", () => cacheContent1);

            Assert.AreEqual(1, GetTotalItemCount);
            Assert.AreEqual(result, result2);
        }