void Clear_Click(object sender, EventArgs e)
        {
            //var transaction = MainDatabase.BeginTransaction();

            //MainDatabase.DeleteAttendancies();
            //MainDatabase.DeleteDistributions();
            //MainDatabase.DeleteFinanceData();
            //MainDatabase.DeleteSaleData();

            //MainDatabase.DeleteItems<FinanceDataByMonth>();
            //MainDatabase.DeleteItems<FinanceDataByQuarter>();
            //MainDatabase.DeleteItems<SaleDataByMonth>();
            //MainDatabase.DeleteItems<SaleDataByQuarter>();

            //MainDatabase.DeleteItems<CoterieData>();
            //MainDatabase.DeleteItems<PresentationData>();
            //MainDatabase.DeleteItems<Employee>();
            //MainDatabase.DeleteItems<PromotionData>();
            //MainDatabase.DeleteItems<CompetitorData>();
            //MainDatabase.DeleteItems<MessageData>();
            //MainDatabase.DeleteItems<ResumeData>();
            //MainDatabase.DeleteItems<PhotoData>();
            //MainDatabase.DeleteItems<Material>();
            //MainDatabase.DeleteItems<ListedHospital>();

            //MainDatabase.DeleteItems<RouteItem>();


            //transaction.Commit();

            MainDatabase.ClearDB();
            MainDatabase.Dispose();
        }
        void CustomAction_Click(object sender, EventArgs e)
        {
            //var intent = new Intent(Intent.ActionGetContent);
            //intent.SetType("*/*");
            //intent.AddCategory(Intent.CategoryOpenable);
            //StartActivityForResult(intent, PICKFILE_REQUEST_CODE);
            string fileName       = "bd0712a3-a5e7-4704-b565-889f673a393b.realm";
            string dbFileLocation = Path.Combine(Helper.AppDir, fileName);

            if (File.Exists(dbFileLocation))
            {
                SDiag.Debug.WriteLine(dbFileLocation + " is Exists!");
            }

            if (File.Exists(MainDatabase.DBPath))
            {
                SDiag.Debug.WriteLine(MainDatabase.DBPath + " is Exists!");
                //var fi = new FileInfo(MainDatabase.DBPath);
                //var directory = fi.Directory.FullName;
                var newPath = Path.Combine(new FileInfo(MainDatabase.DBPath).Directory.FullName, fileName);
                if (!File.Exists(newPath))
                {
                    File.Copy(dbFileLocation, newPath, true);
                }

                if (File.Exists(newPath))
                {
                    SDiag.Debug.WriteLine(newPath + " is Exists!");
                    MainDatabase.Dispose();
                    Helper.C_DB_FILE_NAME = fileName;
                    MainDatabase.Username = Helper.Username;
                }
            }
        }
Example #3
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            // Create your application here
            SetContentView(Resource.Layout.Route);

            FindViewById <Button>(Resource.Id.raCloseB).Click += (s, e) => {
                MainDatabase.Dispose();
                Finish();
            };

            PharmacyTable            = FindViewById <ListView>(Resource.Id.raPharmacyTable);
            PharmacyTable.ItemClick += (sender, e) => {
                var ll      = (ListView)sender;
                var adapter = (RoutePharmacyAdapter)ll.Adapter;
                adapter.SwitchVisibility(e.Position);

                var row = LayoutInflater.Inflate(Resource.Layout.RouteItem, RouteTable, false);
                row.SetTag(Resource.String.Position, e.Position);

                RouteSearchItem item;
                if (string.IsNullOrEmpty(SearchEditor.Text))
                {
                    item = RouteSearchItems[e.Position];
                }
                else
                {
                    item = SearchedItems[e.Position];
                }

                //TODO: rename vars
                using (var trans = MainDatabase.BeginTransaction()){
                    var newRouteItem = MainDatabase.Create2 <RouteItem>();
                    newRouteItem.Pharmacy = item.UUID;
                    newRouteItem.Order    = RouteTable.ChildCount;
                    newRouteItem.Date     = SelectedDate;
                    trans.Commit();
                    row.SetTag(Resource.String.RouteItemUUID, newRouteItem.UUID);
                }
                row.SetTag(Resource.String.PharmacyUUID, item.UUID);

                row.FindViewById <TextView>(Resource.Id.riPharmacyTV).Text = item.Name;
                row.SetTag(Resource.String.RouteItemOrder, RouteTable.ChildCount);
                row.FindViewById <TextView>(Resource.Id.riOrderTV).Text = (RouteTable.ChildCount + 1).ToString();

                row.FindViewById <ImageView>(Resource.Id.riDeleteIV).Click += RowDelete_Click;
                row.LongClick += Row_LongClick;
                row.Drag      += Row_Drag;

                RouteTable.AddView(row);
            };

            RouteSearchItemsSource = new List <RouteSearchItem>();
            var pharmacies = MainDatabase.GetItems <Pharmacy>();

            foreach (var item in pharmacies)
            {
                RouteSearchItemsSource.Add(
                    new RouteSearchItem(
                        item.UUID,
                        string.IsNullOrEmpty(item.GetName()) ? string.Empty : item.GetName(),
                        string.IsNullOrEmpty(item.Subway) ? string.Empty : MainDatabase.GetItem <Subway>(item.Subway).name,
                        string.IsNullOrEmpty(item.Region) ? string.Empty : MainDatabase.GetItem <Region>(item.Region).name,
                        string.IsNullOrEmpty(item.Brand) ? string.Empty : item.Brand,
                        string.IsNullOrEmpty(item.Address) ? string.Empty : item.Address
                        )
                    );
            }
            SearchedItems  = new List <RouteSearchItem>();
            SearchSwitcher = FindViewById <ViewSwitcher>(Resource.Id.raSearchVS);
            SearchSwitcher.SetInAnimation(this, Android.Resource.Animation.SlideInLeft);
            SearchSwitcher.SetOutAnimation(this, Android.Resource.Animation.SlideOutRight);

            SearchImage        = FindViewById <ImageView>(Resource.Id.raSearchIV);
            SearchImage.Click += (sender, e) => {
                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

                SearchSwitcher.ShowNext();
            };

            SearchEditor = FindViewById <EditText>(Resource.Id.raSearchET);

            SearchEditor.AfterTextChanged += (sender, e) => {
                var text = e.Editable.ToString();

                if (string.IsNullOrEmpty(text))
                {
                    foreach (var item in RouteSearchItems)
                    {
                        item.Match = string.Empty;
                    }
                    PharmacyTable.Adapter = new RoutePharmacyAdapter(this, RouteSearchItems);
                    return;
                }

                var w = new SDiag.Stopwatch();
                w.Start();
                SearchedItems = new List <RouteSearchItem>();
                var matchFormat = @"Совпадение: {0}";
                var culture     = CultureInfo.GetCultureInfo("ru-RU");
                // 2 поиск
                foreach (var item in RouteSearchItems)
                {
                    if (item.IsVisible)
                    {
                        //item.Subway = null;
                        if (culture.CompareInfo.IndexOf(item.Subway, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"метро=" + item.Subway);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Region, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"район=" + item.Region);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Brand, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"бренд=" + item.Brand);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Address, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"адрес");
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }
                    }
                }
                w.Stop();
                SDiag.Debug.WriteLine(@"Search: поиск={0}", w.ElapsedMilliseconds);

                PharmacyTable.Adapter = new RoutePharmacyAdapter(this, SearchedItems);
            };

            RouteTable = FindViewById <LinearLayout>(Resource.Id.raRouteTable);

            FindViewById <Button>(Resource.Id.raSelectDateB).Click += (sender, e) => {
                DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime date) {
                    SDiag.Debug.WriteLine("DatePicker:{0}", date.ToLongDateString());
                    SDiag.Debug.WriteLine("DatePicker:{0}", new DateTimeOffset(date));
                    SelectedDate = new DateTimeOffset(date, new TimeSpan(0, 0, 0));;
                    RefreshTables();
                });
                frag.Show(FragmentManager, DatePickerFragment.TAG);
            };

            Info      = FindViewById <TextView>(Resource.Id.raInfoTV);
            Info.Text = string.Format(@"Период планирования: {0} недели ({1} дней)", Helper.WeeksInRoute, Helper.WeeksInRoute * 5);

            var switcher = FindViewById <ViewSwitcher>(Resource.Id.raSwitchViewVS);

            FindViewById <ImageView>(Resource.Id.raSwitchIV).Click += (sender, e) => {
                SDiag.Debug.WriteLine(@"switcher:{0}; Resource{1}", switcher.CurrentView.Id, Resource.Id.raContainerVP);
                if (switcher.CurrentView.Id != Resource.Id.raContainerVP)
                {
                    Info.Text = string.Format(
                        @"Период планирования: {0} недели ({1} дней). Номер недели: {2}",
                        Helper.WeeksInRoute, Helper.WeeksInRoute * 5, 1
                        );
                    var pager = FindViewById <ViewPager>(Resource.Id.raContainerVP);
                    pager.AddOnPageChangeListener(this);
                    pager.Adapter = new RoutePagerAdapter(SupportFragmentManager);
                }
                else
                {
                    Info.Text = string.Format(@"Период планирования: {0} недели ({1} дней)", Helper.WeeksInRoute, Helper.WeeksInRoute * 5);
                }
                switcher.ShowNext();
            };
        }
Example #4
0
        void Sync_Click(object sender, EventArgs e)
        {
            if (CancelSource != null && CancelToken.CanBeCanceled)
            {
                CancelSource.Cancel();
            }

            if (IsTokenExpired(ACCESS_TOKEN))
            {
                var input = new EditText(this);
                // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                input.InputType = Android.Text.InputTypes.ClassText | Android.Text.InputTypes.TextVariationPassword;

                new AlertDialog.Builder(this)
                .SetTitle("Ключ доступа просрочен. Введите пароль.")
                .SetView(input)
                .SetPositiveButton("OK", async(caller, arguments) => {
                    var progress = ProgressDialog.Show(this, string.Empty, @"Проверка данных. Получение ключа доступа.");
                    var login    = new RestClient(@"http://front-sblcrm.rhcloud.com/");
                    //var client = new RestClient(@"http://sbl-crm-project-pafik13.c9users.io:8080/");
                    login.CookieContainer = new CookieContainer();

                    string email    = Helper.Username + "@sbl-crm.ru";
                    string password = input.Text;
                    IRestResponse response;
                    try {
                        var request = new RestRequest(@"auth/login", Method.POST);
                        request.AddParameter("email", email, ParameterType.GetOrPost);
                        request.AddParameter("password", password, ParameterType.GetOrPost);
                        response = await login.ExecuteTaskAsync(request);
                        if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                        {
                            request  = new RestRequest(@"user/jwt", Method.GET);
                            response = await login.ExecuteTaskAsync <JsonWebToken>(request);
                            if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                            {
                                ACCESS_TOKEN = (response as IRestResponse <JsonWebToken>).Data.token;
                                GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private).Edit()
                                .PutString(SigninDialog.C_ACCESS_TOKEN, ACCESS_TOKEN)
                                .Commit();
                                Toast.MakeText(this, "Новый ключ получен. Попробуйте синхронизироваться!", ToastLength.Long).Show();
                                progress.Dismiss();
                            }
                            else
                            {
                                progress.Dismiss();
                            }
                        }
                        else
                        {
                            progress.Dismiss();
                        }
                    } catch (Exception ex) {
                        Toast.MakeText(this, string.Format(@"Error: {0}", ex.Message), ToastLength.Long).Show();
                        progress.Dismiss();
                    }
                })
                .SetNegativeButton(Resource.String.cancel_button, (caller, arguments) => {
                    if (caller is Dialog)
                    {
                        ((Dialog)caller).Dismiss();
                    }
                })
                .Show();

                return;
            }

            try {
                var dbFileInfo = new FileInfo(MainDatabase.DBPath);
                HockeyApp.MetricsManager.TrackEvent(
                    "SyncActivity.Sync_Click.DB",
                    new Dictionary <string, string> {
                    { "realm.path", dbFileInfo.FullName },
                    { "android_id", Helper.AndroidId },
                    { "agent_uuid", MainDatabase.AgentUUID }
                },
                    new Dictionary <string, double> {
                    { "realm.size", dbFileInfo.Length }
                }
                    );
            } catch (Exception exc) {
                HockeyApp.MetricsManager.TrackEvent(
                    "SyncActivity.Sync_Click.Exception",
                    new Dictionary <string, string> {
                    { "Message", exc.Message },
                    { "android_id", Helper.AndroidId },
                    { "agent_uuid", MainDatabase.AgentUUID }
                },
                    new Dictionary <string, double> {
                    { "HResult", exc.HResult }
                }
                    );
            }


            if (Count > 0 || MaterialFiles.Count > 0 || WorkTypes.Count > 0)
            {
                var progress = ProgressDialog.Show(this, string.Empty, @"Синхронизация");

                new Task(() => {
                    MainDatabase.Dispose();
                    Thread.Sleep(1000);                     // иначе не успеет показаться диалог

                    MainDatabase.Username = USERNAME;

                    // Обновление материалов
                    foreach (var materialFile in MaterialFiles)
                    {
                        if (!MainDatabase.IsSavedBefore <Material>(materialFile.material))
                        {
                            var client     = new RestClient(HOST_URL);
                            string pathURL = string.Format(@"Material/{0}?populate=false", materialFile.material);
                            var request    = new RestRequest(pathURL, Method.GET);

                            var response = client.Execute <Material>(request);

                            switch (response.StatusCode)
                            {
                            case HttpStatusCode.OK:
                            case HttpStatusCode.Created:
                                SDiag.Debug.WriteLine("Material: {0}", response.Data);
                                MainDatabase.SaveItem(response.Data);
                                SDiag.Debug.WriteLine(response.StatusDescription);
                                break;

                            default:
                                SDiag.Debug.WriteLine(response.StatusDescription);
                                continue;
                            }
                        }

                        // 79 Characters (72 without spaces)
                        ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
                        using (var wclient = new WebClient()) {
                            string path = new Java.IO.File(Helper.MaterialDir, materialFile.fileName).ToString();
                            try {
                                wclient.DownloadFile(materialFile.s3Location, path);
                                MainDatabase.SaveItem(materialFile);
                            } catch (Exception exc) {
                                // TODO: Add log info to HockeyApp
                                SDiag.Debug.WriteLine("Was exception: {0}", exc.Message);
                            }
                        }
                    }

                    // Обновление материалов
                    foreach (var workType in WorkTypes)
                    {
                        if (!MainDatabase.IsSavedBefore <WorkType>(workType.uuid))
                        {
                            MainDatabase.SaveItem(workType);
                        }
                    }

                    // Обновление файлов в библотеке
                    foreach (var libraryFile in LibraryFiles)
                    {
                        // 79 Characters (72 without spaces)
                        ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
                        using (var wclient = new WebClient()) {
                            string path = new Java.IO.File(Helper.LibraryDir, libraryFile.fileName).ToString();
                            try {
                                wclient.DownloadFile(libraryFile.s3Location, path);
                                MainDatabase.SaveItem(libraryFile);
                            } catch (Exception exc) {
                                // TODO: Add log info to HockeyApp
                                SDiag.Debug.WriteLine("Was exception: {0}", exc.Message);
                            }
                        }
                    }

                    SyncEntities(MainDatabase.GetItemsToSync <Attendance>());
                    SyncEntities(MainDatabase.GetItemsToSync <CompetitorData>());
                    SyncEntities(MainDatabase.GetItemsToSync <ContractData>());
                    SyncEntities(MainDatabase.GetItemsToSync <CoterieData>());
                    SyncEntities(MainDatabase.GetItemsToSync <DistributionData>());

                    SyncEntities(MainDatabase.GetItemsToSync <Employee>());
                    SyncEntities(MainDatabase.GetItemsToSync <ExcludeRouteItem>());
                    SyncEntities(MainDatabase.GetItemsToSync <GPSData>());
                    SyncEntities(MainDatabase.GetItemsToSync <Hospital>());
                    SyncEntities(MainDatabase.GetItemsToSync <HospitalData>());
                    SyncEntities(MainDatabase.GetItemsToSync <Entities.Message>());
                    SyncEntities(MainDatabase.GetItemsToSync <MessageData>());
                    SyncEntities(MainDatabase.GetItemsToSync <Pharmacy>());
                    SyncEntities(MainDatabase.GetItemsToSync <PresentationData>());
                    SyncEntities(MainDatabase.GetItemsToSync <PromotionData>());
                    SyncEntities(MainDatabase.GetItemsToSync <ResumeData>());
                    SyncEntities(MainDatabase.GetItemsToSync <RouteItem>());

                    MainDatabase.Dispose();

                    RunOnUiThread(() => {
                        MainDatabase.Username = USERNAME;
                        // Thread.Sleep(1000);
                        progress.Dismiss();
                        RefreshView();
                    });
                }).Start();
            }
        }
Example #5
0
        void UploadPhoto_Click(object sender, EventArgs e)
        {
            if (CancelSource != null && CancelToken.CanBeCanceled)
            {
                CancelSource.Cancel();
            }
            if (CSForLibraryFiles != null && CTForLibraryFiles.CanBeCanceled)
            {
                CSForLibraryFiles.Cancel();
            }
            var progress = ProgressDialog.Show(this, string.Empty, @"Выгрузка фото");

            new Task(() => {
                MainDatabase.Dispose();
                Thread.Sleep(1000);                 // иначе не успеет показаться диалог

                MainDatabase.Username = USERNAME;

                var client = new RestClient(HOST_URL);
                IRestRequest request;
                IRestResponse response;
                //var client = new RestClient("http://sbl-crm-project-pafik13.c9users.io:8080/");

                using (var trans = MainDatabase.BeginTransaction()) {
                    foreach (var photo in MainDatabase.GetItemsToSync <PhotoData>())
                    {
                        try {
                            //Toast.MakeText(this, string.Format(@"Загрузка фото с uuid {0} по посещению с uuid:{1}", photo.UUID, photo.Attendance), ToastLength.Short).Show();
                            SDiag.Debug.WriteLine(string.Format(@"Загрузка фото с uuid {0} по посещению с uuid:{1}", photo.UUID, photo.Attendance));

                            request = new RestRequest(@"PhotoData/upload", Method.POST);
                            request.AddQueryParameter(@"access_token", ACCESS_TOKEN);
                            //request.AddQueryParameter(@"Stamp", photo.Stamp.ToString());
                            request.AddQueryParameter(@"Attendance", photo.Attendance);
                            request.AddQueryParameter(@"PhotoType", photo.PhotoType);
                            request.AddQueryParameter(@"Brand", photo.Brand);
                            request.AddQueryParameter(@"Latitude", photo.Latitude.ToString(CultureInfo.CreateSpecificCulture(@"en-GB")));
                            request.AddQueryParameter(@"Longitude", photo.Longitude.ToString(CultureInfo.CreateSpecificCulture(@"en-GB")));
                            request.AddFile(@"photo", File.ReadAllBytes(photo.PhotoPath), Path.GetFileName(photo.PhotoPath), string.Empty);

                            response = client.Execute(request);

                            switch (response.StatusCode)
                            {
                            case HttpStatusCode.OK:
                            case HttpStatusCode.Created:
                                // TODO: переделать на вызов с проверкой открытой транзакции
                                photo.IsSynced = true;
                                if (!photo.IsManaged)
                                {
                                    MainDatabase.SavePhoto(photo);
                                }
                                //Toast.MakeText(this, "Фото ЗАГРУЖЕНО!", ToastLength.Short).Show();
                                SDiag.Debug.WriteLine("Фото ЗАГРУЖЕНО!");
                                continue;

                            default:
                                //Toast.MakeText(this, "Не удалось загрузить фото по посещению!", ToastLength.Short).Show();
                                SDiag.Debug.WriteLine("Не удалось загрузить фото по посещению!");
                                continue;
                            }
                        } catch (Exception ex) {
                            //Toast.MakeText(this, @"Error : " + ex.Message, ToastLength.Short).Show();
                            SDiag.Debug.WriteLine("Error : " + ex.Message);
                            continue;
                        }
                    }
                    trans.Commit();
                }

                MainDatabase.Dispose();
                RunOnUiThread(() => {
                    MainDatabase.Username = USERNAME;
                    // Thread.Sleep(1000);
                    progress.Dismiss();
                    RefreshView();
                });
            }).Start();
        }
Example #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            // Create your application here
            SetContentView(Resource.Layout.Profile);

            FindViewById <Button>(Resource.Id.paCloseB).Click += (sender, e) => {
                Finish();
            };

            FindViewById <Button>(Resource.Id.paExitAppB).Click += (sender, e) => {
                int count = 0;

                count += MainDatabase.CountItemsToSync <Attendance>();
                count += MainDatabase.CountItemsToSync <CompetitorData>();
                count += MainDatabase.CountItemsToSync <ContractData>();
                count += MainDatabase.CountItemsToSync <CoterieData>();
                count += MainDatabase.CountItemsToSync <DistributionData>();
                count += MainDatabase.CountItemsToSync <Pharmacy>();
                count += MainDatabase.CountItemsToSync <Employee>();

                count += MainDatabase.CountItemsToSync <GPSData>();

                count += MainDatabase.CountItemsToSync <Hospital>();
                count += MainDatabase.CountItemsToSync <HospitalData>();

                //var monthFinanceDatas = MainDatabase.GetItemsToSync<FinanceDataByMonth>();
                //var quarterFinanceDatas = MainDatabase.GetItemsToSync<FinanceDataByQuarter>();
                //var monthSaleDatas = MainDatabase.GetItemsToSync<SaleDataByMonth>();
                //var quarterSaleDatas = MainDatabase.GetItemsToSync<SaleDataByQuarter>();

                count += MainDatabase.CountItemsToSync <MessageData>();

                count += MainDatabase.CountItemsToSync <PresentationData>();
                count += MainDatabase.CountItemsToSync <PromotionData>();
                count += MainDatabase.CountItemsToSync <ResumeData>();
                count += MainDatabase.CountItemsToSync <RouteItem>();

                count += MainDatabase.CountItemsToSync <RouteItem>();

                count += MainDatabase.CountItemsToSync <PhotoData>();

                if (count > 0)
                {
                    new AlertDialog.Builder(this)
                    .SetTitle(Resource.String.warning_caption)
                    .SetMessage("Перед выходом необходимо синхронизировать все данные!!!")
                    .SetCancelable(true)
                    .SetPositiveButton("OK", (caller, arguments) => {
                        if (caller is Dialog)
                        {
                            (caller as Dialog).Dismiss();
                        }
                    })
                    .Show();
                }
                else
                {
                    GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private)
                    .Edit()
                    .PutString(SigninDialog.C_USERNAME, string.Empty)
                    .Commit();
                    MainDatabase.Dispose();
                    Finish();
                }
            };

            Content = FindViewById <LinearLayout>(Resource.Id.paAttendanceByWeekLL);
            Table   = FindViewById <ListView>(Resource.Id.paAttendanceByWeekTable);

            int weeksCount = 14;

            Dates = new DateTimeOffset[weeksCount];
            var header = (LinearLayout)LayoutInflater.Inflate(Resource.Layout.AttendanceByWeekTableHeader, Table, false);

            (header.GetChildAt(0) as TextView).Text = @"Недели";
            for (int w = 0; w < weeksCount; w++)
            {
                Dates[w] = DateTimeOffset.UtcNow.AddDays(-7 * (weeksCount - 1 - w));
                var hView = header.GetChildAt(w + 1);
                if (hView is TextView)
                {
                    (hView as TextView).Text = Helper.GetIso8601WeekOfYear(Dates[w].UtcDateTime.Date).ToString();
                }
            }
            Content.AddView(header, 1);

            var shared = GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private);

            FindViewById <TextView>(Resource.Id.paUsernameTV).Text = shared.GetString(SigninDialog.C_USERNAME, string.Empty);

            var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);

            try {
                var agent = MainDatabase.GetItem <Agent>(agentUUID);
                FindViewById <TextView>(Resource.Id.paShortNameTV).Text = agent.shortName;
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            SearchSwitcher = FindViewById <ViewSwitcher>(Resource.Id.paSearchVS);
            SearchSwitcher.SetInAnimation(this, Android.Resource.Animation.SlideInLeft);
            SearchSwitcher.SetOutAnimation(this, Android.Resource.Animation.SlideOutRight);

            SearchImage        = FindViewById <ImageView>(Resource.Id.paSearchIV);
            SearchImage.Click += (sender, e) => {
                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

                SearchSwitcher.ShowNext();
            };

            SearchEditor = FindViewById <EditText>(Resource.Id.paSearchET);

            SearchEditor.AfterTextChanged += (sender, e) => {
                var text = e.Editable.ToString();

                (Table.Adapter as AttendanceByWeekAdapter).SetSearchText(text);
            };
        }