コード例 #1
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.SelectCustomer);

            Android.Widget.SearchView searchView = FindViewById <Android.Widget.SearchView>(Resource.Id.searchViewCustomers);

            //get all customers from database
            customers = DatabaseRequest.GetAllFromTable <Customer>().OrderBy(x => x.Company).ToList();

            //populate RecyclerView with all customers
            customersRecyclerView  = FindViewById <RecyclerView>(Resource.Id.customersRecyclerView);
            customersLayoutManager = new LinearLayoutManager(this);
            customersRecyclerView.SetLayoutManager(customersLayoutManager);
            customersAdapter            = new CustomersAdapter(customers);
            customersAdapter.ItemClick += OnItemClick;
            customersRecyclerView.SetAdapter(customersAdapter);

            searchView.QueryTextChange += delegate
            {
                string currentSearchViewValue   = searchView.Query;
                var    currentCustomersSearched = customers.Where(x => x.Company.ToLower().Contains(currentSearchViewValue.ToLower())).ToList();
                //repopulate RecyclerView with currentCustomersSearched
                customersAdapter            = new CustomersAdapter(currentCustomersSearched);
                customersAdapter.ItemClick += OnItemClick;
                customersRecyclerView.SetAdapter(customersAdapter);
            };
        }
コード例 #2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ArticlesList);

            //get all groups from database
            //using (var connection = new SQLiteConnection(System.IO.Path.Combine(GlobalVariables.databasePath, "MobileSell.db")))
            //{
            //	var allGroups = connection.Table<Group>();
            //	groups.AddRange(allGroups);
            //}

            var allGroups = DatabaseRequest.GetAllFromTable <Group>();

            groups.AddRange(allGroups);

            //fill in spinner with items
            spinner = FindViewById <MaterialSpinner>(Resource.Id.spinner);
            adapter = new ArrayAdapter <Group>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, groups);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;

            spinner.Background = Drawable.CreateFromXml(Resources, Resources.GetXml(Resource.Drawable.material_spinner_border));

            //on activity start get all articles
            allArticles = DatabaseRequest.GetAllFromTable <Article>().Select(x =>
                                                                             new ArticleViewModel
            {
                Id        = x.Id,
                Group     = x.Group,
                Name      = x.Name,
                SellPrice = x.SellPrice,
                Quantity  = x.Quantity
            }).ToList();

            //create line between recyclerview items
            DividerItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.Vertical);

            //pass all articles to the RecyclerView
            articlesRecyclerView = FindViewById <RecyclerView>(Resource.Id.articlesRecyclerView);
            articlesRecyclerView.AddItemDecoration(itemDecoration);
            articlesLayoutManager = new LinearLayoutManager(this);
            articlesRecyclerView.SetLayoutManager(articlesLayoutManager);
            articlesAdapter            = new ArticlesAdapter(allArticles);
            articlesAdapter.ItemClick += OnItemClick;
            articlesRecyclerView.SetAdapter(articlesAdapter);

            //get all articles from selected group
            spinner.ItemSelected += (s, e) =>
            {
                if (e.Position != -1)
                {
                    var groupId = groups.ElementAt(e.Position).Id;

                    //get all articles from group which is currently selected
                    List <ArticleViewModel> articlesFromGroup = allArticles.Where(x => x.Group == groupId).ToList();

                    //fill in the RecyclerView with articlesFromGroup;
                    articlesAdapter            = new ArticlesAdapter(articlesFromGroup);
                    articlesAdapter.ItemClick += OnItemClick;
                    articlesRecyclerView.SetAdapter(articlesAdapter);
                }
                else
                {
                    //if no group is selected display all articles on screen
                    articlesLayoutManager = new LinearLayoutManager(this);
                    articlesRecyclerView.SetLayoutManager(articlesLayoutManager);
                    articlesAdapter            = new ArticlesAdapter(allArticles);
                    articlesAdapter.ItemClick += OnItemClick;
                    articlesRecyclerView.SetAdapter(articlesAdapter);
                }
            };
        }
コード例 #3
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Inventory);

            //get all groups from database
            using (var connection = new SQLiteConnection(System.IO.Path.Combine(GlobalVariables.databasePath, "MobileSell.db")))
            {
                var allGroups = connection.Table <Group>();
                groups.AddRange(allGroups);
            }

            //fill in spinner with items
            spinner = FindViewById <MaterialSpinner>(Resource.Id.spinner);
            adapter = new ArrayAdapter <Group>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, groups);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;

            spinner.Background = Drawable.CreateFromXml(Resources, Resources.GetXml(Resource.Drawable.material_spinner_border));

            //on activity start get all articles
            allArticles = DatabaseRequest.GetAllFromTable <Article>().Select(x =>
                                                                             new ArticleViewModel
            {
                Id        = x.Id,
                Group     = x.Group,
                Name      = x.Name,
                SellPrice = x.SellPrice,
                Quantity  = x.Quantity
            }).ToList();

            //pass all articles to the RecyclerView
            articlesRecyclerView  = FindViewById <RecyclerView>(Resource.Id.articlesRecyclerView);
            articlesLayoutManager = new LinearLayoutManager(this);
            articlesRecyclerView.SetLayoutManager(articlesLayoutManager);
            articlesAdapter = new ArticlesAdapter(allArticles);
            articlesRecyclerView.SetAdapter(articlesAdapter);

            TextView totalValue = FindViewById <TextView>(Resource.Id.totalValue);
            //calculate total sum of all articles in RecyclerView and set it to totalValue TextView
            decimal totalSumAllArticles = articlesAdapter.listOfArticles.Sum(x => x.Sum);

            totalValue.Text = String.Format("{0:0.00}", totalSumAllArticles);

            //get all articles from selected group
            spinner.ItemSelected += (s, e) =>
            {
                if (e.Position != -1)
                {
                    var groupId = groups.ElementAt(e.Position).Id;
                    //get all articles from group which is currently selected
                    List <ArticleViewModel> articlesFromGroup = allArticles.Where(x => x.Group == groupId).ToList();

                    //fill in the RecyclerView with articlesFromGroup
                    //articlesLayoutManager = new LinearLayoutManager(this);
                    //articlesRecyclerView.SetLayoutManager(articlesLayoutManager);
                    articlesAdapter = new ArticlesAdapter(articlesFromGroup);
                    articlesRecyclerView.SetAdapter(articlesAdapter);

                    //calculate total value of articles
                    //decimal totalSum = 0;
                    //foreach(ArticleViewModel article in articlesFromGroup)
                    //{
                    //	totalSum += article.Sum;
                    //}

                    //calculate total sum of all articles in RecyclerView and set it to totalValue TextView
                    totalSumAllArticles = articlesAdapter.listOfArticles.Sum(x => x.Sum);
                    totalValue.Text     = String.Format("{0:0.00}", totalSumAllArticles);
                }
                else
                {
                    //if no group is selected display all articles on screen
                    //articlesLayoutManager = new LinearLayoutManager(this);
                    //articlesRecyclerView.SetLayoutManager(articlesLayoutManager);
                    articlesAdapter = new ArticlesAdapter(allArticles);
                    articlesRecyclerView.SetAdapter(articlesAdapter);
                    //calculate total sum of all articles in RecyclerView and set it to totalValue TextView
                    totalSumAllArticles = articlesAdapter.listOfArticles.Sum(x => x.Sum);
                    totalValue.Text     = String.Format("{0:0.00}", totalSumAllArticles);
                }
            };

            Button btnPrint = FindViewById <Button>(Resource.Id.btnPrint);

            btnPrint.Click += delegate {
                StartActivity(typeof(PrintingActivity));
            };
        }
コード例 #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Orders);

            settings = CurrentSettings.GetSettings();

            //isDataFolderEmpty = StateOrdersActivity.IsDataFolderEmpty();
            //isCreatingNewOrder = StateOrdersActivity.IsCreatingNewOrder();

            //ENABLE-DISABLE BUTTONS
            //check if orders folder is empty
            //if orders folder is empty disable all buttons except "Нова" else enable all buttons
            //btnSelectCustomer.Enabled = (OrdersFolder is not Empty) and (textViewCustomerName is not empty)
            //btnNewRow.Enabled = OrdersFolder is not Empty) and (textViewCustomerName is not empty)
            //buttonSave.Enable = (recyclerView is not empty)
            //leftArrow.Enabled = (OrdersFolder not empty) and (OrderFolder has more than one value)

            btnLeftArrow      = FindViewById <Button>(Resource.Id.btnLeftArrow);
            btnRightArrow     = FindViewById <Button>(Resource.Id.btnRightArrow);
            btnBon            = FindViewById <Button>(Resource.Id.btnBon);
            btnInvoice        = FindViewById <Button>(Resource.Id.btnInvoice);
            btnSaveOrder      = FindViewById <Button>(Resource.Id.btnSaveOrder);
            btnDatePicker     = FindViewById <Button>(Resource.Id.btnDatePicker);
            btnSelectCustomer = FindViewById <Button>(Resource.Id.btnSelectCustomer);
            btnNewOrder       = FindViewById <Button>(Resource.Id.btnNewOrder);
            btnNewRow         = FindViewById <Button>(Resource.Id.btnNewRow);

            totalPriceAllArticlesTextView = FindViewById <TextView>(Resource.Id.totalPriceAllArticlesTextView);
            orderArticlesRecyclerView     = FindViewById <RecyclerView>(Resource.Id.orderArticlesRecyclerView);

            textViewOrderNumber      = FindViewById <TextView>(Resource.Id.textViewOrderNumber);
            textViewOrderDateAndHour = FindViewById <TextView>(Resource.Id.textViewOrderDateAndHour);

            textViewCustomerName = FindViewById <TextView>(Resource.Id.textViewCustomerName);
            textViewCustomerId   = FindViewById <TextView>(Resource.Id.textViewCustomerId);

            //TODO:
            //if currently we are not creating an order display first order
            if (StateOrdersActivity.creatingNewOrder == false)
            {
                //fill in OrdersActivity views with data from xml orders
                //get all orders from data folder and map them to object OrderViewModel
                //string xmlFilePath = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Settings4/settings4.xml";
                //XmlSerializer deserializer = new XmlSerializer(typeof(Settings));
                //TextReader textReader = new StreamReader(xmlFilePath);
                //settings = (Settings)deserializer.Deserialize(textReader);
                //textReader.Close();
                EnableDisableButtons();
                //get all file names of saved orders in data folder in ascending order
                var allSavedOrdersFileNames = Directory.GetFiles(GlobalVariables.dataFolderPath, "*.xml").Select(System.IO.Path.GetFileName).OrderBy(f => f);
                if (allSavedOrdersFileNames.ToList().Count != 0)
                {
                    foreach (string xmlFileName in allSavedOrdersFileNames)
                    {
                        //map xml files to c# objects and add it to list of StateOrdersActivity.xmlOrders
                        string        xmlFullFilePath = GlobalVariables.dataFolderPath + "/" + xmlFileName;
                        XmlSerializer deserializer    = new XmlSerializer(typeof(XmlOrder));
                        TextReader    textReader      = new StreamReader(xmlFullFilePath);
                        XmlOrder      xmlOrder        = (XmlOrder)deserializer.Deserialize(textReader);
                        StateOrdersActivity.xmlOrders.Add(xmlOrder);
                        textReader.Close();
                    }

                    //display first order
                    DisplayOrder(StateOrdersActivity.DisplayOrderPosition);
                }
            }
            else
            {
                //set values to widgets again so that we don't loose them when we are navigating throught another activities
                EnableDisableButtons();
                //recieve the customer name and set it to textViewCustomerName
                textViewCustomerName.Text = CurrentOrder.orderCustomerName;
                //recieve the customer id and set it to textViewCustomerId
                textViewCustomerId.Text       = CurrentOrder.orderCustomerId;
                textViewOrderNumber.Text      = CurrentOrder.orderNumber;
                textViewOrderDateAndHour.Text = CurrentOrder.orderDateAndHour;
                orderArticlesLayoutManager    = new LinearLayoutManager(this);
                orderArticlesRecyclerView.SetLayoutManager(orderArticlesLayoutManager);
                orderArticlesAdapter = new OrderArticlesAdapter(CurrentOrder.listOfOrderArticles, this);
                orderArticlesRecyclerView.SetAdapter(orderArticlesAdapter);
                totalPriceAllArticlesTextView.Text = orderArticlesAdapter.CaltulateTotalPriceOfAllOrderArticles().ToString();
                btnDatePicker.Text = CurrentOrder.executionOrderDate.ToString("dd.MM.yyyy");
            }

            //TODO:
            //if StateOrdersActivity.creatingNewOrder == false display first order

            //datePickerDialog = new DatePickerDialog(this, this, CurrentOrder.executionOrderDate.Year, CurrentOrder.executionOrderDate.Month, CurrentOrder.executionOrderDate.Day);
            //datePickerDialog.DatePicker.MinDate = (long)(DateTime.Now.AddDays(1) - new DateTime(1970, 1, 1)).TotalMilliseconds;

            //set btnDatePicker's text to be DateTime.Now
            //btnDatePicker.Text = CurrentOrder.executionOrderDate;

            btnDatePicker.Click += delegate
            {
                datePickerDialog = new DatePickerDialog(this, this, CurrentOrder.executionOrderDate.Year, CurrentOrder.executionOrderDate.Month - 1, CurrentOrder.executionOrderDate.Day);
                datePickerDialog.DatePicker.MinDate = DateTimeOffset.Now.AddDays(1).AddSeconds(-1).ToUnixTimeMilliseconds();
                datePickerDialog.Show();
            };

            btnRightArrow.Click += delegate
            {
                StateOrdersActivity.DisplayOrderPosition += 1;

                //enable disable btnRightArrow depending on if current order is last order or not
                bool isLastOrder = StateOrdersActivity.DisplayOrderPosition == StateOrdersActivity.xmlOrders.Count - 1;
                btnRightArrow.Enabled = isLastOrder ? false : true;

                //enable disable btnLeftArrow depending on if current order is first order or not
                bool isFirstOrder = StateOrdersActivity.DisplayOrderPosition == 0;
                btnLeftArrow.Enabled = isFirstOrder ? false : true;


                DisplayOrder(StateOrdersActivity.DisplayOrderPosition);
            };

            btnLeftArrow.Click += delegate
            {
                StateOrdersActivity.DisplayOrderPosition -= 1;

                //enable disable btnRightArrow depending on if current order is last order or not
                bool isLastOrder = StateOrdersActivity.DisplayOrderPosition == StateOrdersActivity.xmlOrders.Count - 1;
                btnRightArrow.Enabled = isLastOrder ? false : true;

                //enable disable btnLeftArrow depending on if current order is first order or not
                bool isFirstOrder = StateOrdersActivity.DisplayOrderPosition == 0;
                btnLeftArrow.Enabled = isFirstOrder ? false : true;

                DisplayOrder(StateOrdersActivity.DisplayOrderPosition);
            };

            int    lastOrderNumber;
            string orderNumber;

            btnNewOrder.Click += delegate
            {
                //check if user is currently creating new order on clicking "Нова"
                if (StateOrdersActivity.creatingNewOrder == true)
                {
                    //ask user if he is sure he wants to start creating new order,
                    //the data of the order he was currently creating will be lost
                    AlertDialog.Builder alertClearCurrentOrderData = new AlertDialog.Builder(this);
                    alertClearCurrentOrderData.SetMessage("Сигурни ли сте че искате да създадете нова поръчка? \nДанните за текущата ще бъдат загубени");
                    alertClearCurrentOrderData.SetPositiveButton("ДA", delegate
                    {
                        StateOrdersActivity.creatingNewOrder = false;
                        ClearScreenData();
                        btnNewOrder.PerformClick();
                    });
                    alertClearCurrentOrderData.SetNegativeButton("НЕ", delegate
                    {
                        alertClearCurrentOrderData.Dispose();
                    });
                    alertClearCurrentOrderData.Create().Show();
                }
                else
                {
                    //clear screen data from OrdersActivity
                    ClearScreenData();

                    //Enable-Disable buttons on "Нова" button pressed
                    StateOrdersActivity.creatingNewOrder = true;
                    btnDatePicker.Text = CurrentOrder.executionOrderDate.ToString("dd.MM.yyyy");
                    EnableDisableButtons();

                    //create order number
                    if (StateOrdersActivity.dataFolderNumOrders == 0)
                    {
                        //get last order number from MobileSell/object.xml and set it to textViewOrderNumber
                        XmlDocument doc = new XmlDocument();
                        doc.Load(GlobalVariables.mobileSellFolderPath + "/object.xml");
                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                        nsmgr.AddNamespace("ab", "http://tempuri.org/DataSet1.xsd");
                        string f1 = doc.SelectSingleNode("//ab:f1", nsmgr).InnerText.ToString();
                        lastOrderNumber = Convert.ToInt32(f1);
                        orderNumber     = (lastOrderNumber + 1).ToString();
                        //set order number to global variable CurrentOrder.orderNumber so its value is not lost when going to another activities
                        CurrentOrder.orderNumber = orderNumber.ToString();
                        //textViewOrderNumber.Text = CurrentOrder.orderNumber;

                        ////get DateTime.Now + Hour and set it to global variable CurrentOrder.orderDateAndHour so its value is not lost when going to another activities
                        //CurrentOrder.orderDateAndHour = DateTime.Now.ToString("dd.MM.yyyy  HH:mm");
                        //textViewOrderDateAndHour.Text = CurrentOrder.orderDateAndHour;
                    }
                    else
                    {
                        //Всеки следващ е името на първия + 1
                        //get xml file name with the biggest name
                        string biggestXmlFileName = Directory.GetFiles(GlobalVariables.dataFolderPath, "*.xml").Select(System.IO.Path.GetFileNameWithoutExtension).
                                                    OrderByDescending(f => f).FirstOrDefault();
                        CurrentOrder.orderNumber = (Convert.ToInt32(biggestXmlFileName) + 1).ToString();
                    }

                    textViewOrderNumber.Text = CurrentOrder.orderNumber;

                    //set execution date
                    //CurrentOrder.executionOrderDate = DateTime.Now.AddDays(1).ToString("dd.MM.yyyy");
                    //btnDatePicker.Text = CurrentOrder.executionOrderDate;

                    //get DateTime.Now + Hour and set it to global variable CurrentOrder.orderDateAndHour so its value is not lost when going to another activities
                    CurrentOrder.orderDateAndHour = DateTime.Now.ToString("dd.MM.yyyy  HH:mm");
                    textViewOrderDateAndHour.Text = CurrentOrder.orderDateAndHour;
                }
            };

            btnSelectCustomer.Click += delegate
            {
                //desable btnSelectCustomer so user doesn't press it a second time while activity is loading
                //because it will throw exception
                btnSelectCustomer.Enabled = false;
                StartActivity(typeof(SelectCustomerActivity));
            };

            btnNewRow.Click += delegate
            {
                StartActivity(typeof(ArticlesListActivity));
            };

            btnSaveOrder.Click += delegate
            {
                //check if all data is entered by the user
                if (textViewCustomerName.Text != "" && btnDatePicker.Text != "" && orderArticlesAdapter.listOfOrderArticles.Count != 0)
                {
                    string xmlFullFilePath = GlobalVariables.dataFolderPath + "/" + textViewOrderNumber.Text + ".xml";
                    try
                    {
                        //SAVE ORDER IN XML FILE
                        //get the time when order creation was started
                        string orderCreationStarted = textViewOrderDateAndHour.Text;
                        //set textViewOrderDateAndHour.Text to be Datetime.Now
                        string orderCreationEnded = DateTime.Now.ToString("dd.MM.yyyy  HH:mm");
                        textViewOrderDateAndHour.Text = orderCreationEnded;
                        //get interval between start creating order and end creating order
                        string interval = orderCreationStarted + " - " + textViewOrderDateAndHour.Text;

                        //set textViewOrderDateAndHour to DateTime.Now
                        XmlWriterSettings xmlSettings = new XmlWriterSettings();
                        xmlSettings.Indent = true;
                        //get name and id from object.xml
                        XmlDocument doc = new XmlDocument();
                        doc.Load(GlobalVariables.mobileSellFolderPath + "/object.xml");
                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                        nsmgr.AddNamespace("ab", "http://tempuri.org/DataSet1.xsd");
                        string id   = doc.SelectSingleNode("//ab:id", nsmgr).InnerText.ToString();
                        string name = doc.SelectSingleNode("//ab:name", nsmgr).InnerText.ToString();

                        using (XmlWriter writer = XmlWriter.Create(xmlFullFilePath, xmlSettings))
                        {
                            writer.WriteStartElement("xmlOrder");
                            writer.WriteStartElement("DemandHeader");
                            writer.WriteElementString("id", textViewOrderNumber.Text);
                            writer.WriteElementString("sale_id", id);
                            writer.WriteElementString("sell_name", name);
                            writer.WriteElementString("datetime", textViewOrderDateAndHour.Text);
                            writer.WriteElementString("typedoc", "2");
                            writer.WriteElementString("docname", "ПОРЪЧКА");
                            writer.WriteElementString("cust_id", textViewCustomerId.Text);
                            writer.WriteElementString("cust_name", textViewCustomerName.Text);
                            writer.WriteElementString("worktime", interval);
                            writer.WriteElementString("tp", settings.Sales.TpId);
                            writer.WriteElementString("km", "");
                            writer.WriteElementString("paysum", "0");
                            writer.WriteElementString("f1", "");
                            writer.WriteElementString("f2", btnDatePicker.Text);
                            writer.WriteElementString("f3", "");
                            writer.WriteElementString("paytype", "1");
                            writer.WriteElementString("invoiceid", "");
                            writer.WriteElementString("bonid", "");
                            writer.WriteEndElement();
                            //write articles into xml file
                            foreach (OrderArticleViewModel orderArticle in orderArticlesAdapter.listOfOrderArticles)
                            {
                                //get article price without discount
                                decimal articlePriceWithoutDiscount = DatabaseRequest.GetAllFromTable <Article>()
                                                                      .Where(x => x.Id == orderArticle.ArticleId)
                                                                      .Select(x => x.SellPrice).FirstOrDefault();
                                writer.WriteStartElement("Demand");
                                writer.WriteElementString("id", CurrentOrder.orderNumber);
                                writer.WriteElementString("artid", orderArticle.ArticleId);
                                writer.WriteElementString("name", orderArticle.ArticleName);
                                writer.WriteElementString("quantity", orderArticle.ArticleQuantity);
                                writer.WriteElementString("price", articlePriceWithoutDiscount.ToString());
                                writer.WriteElementString("sum", orderArticle.ArticleTotalPrice);
                                writer.WriteElementString("discount", orderArticle.PriceDiscount);
                                writer.WriteElementString("pprice", orderArticle.ArticlePrice);
                                writer.WriteElementString("certificate", "");
                                writer.WriteElementString("f1", "");
                                writer.WriteElementString("f2", "");
                                writer.WriteElementString("f3", "");
                                writer.WriteEndElement();
                            }
                            writer.WriteEndElement();
                            writer.Flush();
                        }

                        ////add created order in xmlOrders list
                        //XmlSerializer deserializer = new XmlSerializer(typeof(XmlOrder));
                        //TextReader textReader = new StreamReader(xmlFullFilePath);
                        //XmlOrder xmlOrder = (XmlOrder)deserializer.Deserialize(textReader);
                        //StateOrdersActivity.xmlOrders.Add(xmlOrder);
                        //textReader.Close();

                        //Decrease quantity in tables article and sertif
                        DatabaseRequest.UpdateQuantities(orderArticlesAdapter.listOfOrderArticles);
                        //say to user "Записа беще успешен"
                        AlertDialog.Builder alertSaveSuccess = new AlertDialog.Builder(this);
                        alertSaveSuccess.SetMessage("Поръчката беше записана успешно");
                        alertSaveSuccess.SetPositiveButton("OK", delegate
                        {
                            //clear screen data from OrdersActivity
                            ClearScreenData();

                            //add created order in xmlOrders list
                            XmlSerializer deserializer = new XmlSerializer(typeof(XmlOrder));
                            TextReader textReader      = new StreamReader(xmlFullFilePath);
                            XmlOrder xmlOrder          = (XmlOrder)deserializer.Deserialize(textReader);
                            StateOrdersActivity.xmlOrders.Add(xmlOrder);
                            textReader.Close();

                            //set state ordersactivity creating new to false
                            StateOrdersActivity.creatingNewOrder = false;

                            //increase number of orders created by 1
                            StateOrdersActivity.dataFolderNumOrders += 1;

                            //set first order to be displayed
                            StateOrdersActivity.DisplayOrderPosition = 0;

                            //Recreate();
                            EnableDisableButtons();
                            DisplayOrder(StateOrdersActivity.DisplayOrderPosition);
                            //Finish();
                            alertSaveSuccess.Dispose();
                        });
                        alertSaveSuccess.Create().Show();
                    }
                    catch (InsufficientQuantityException ex)
                    {
                        //if error occurs during creating xml or decreasing the data in the database, delete created xml
                        if (File.Exists(xmlFullFilePath))
                        {
                            File.Delete(xmlFullFilePath);
                        }
                        //display error message "Insuficent quantity"
                        AlertDialog.Builder alertInsufficientQuantity = new AlertDialog.Builder(this);
                        alertInsufficientQuantity.SetMessage(ex.Message);
                        alertInsufficientQuantity.SetPositiveButton("OK", delegate
                        {
                            alertInsufficientQuantity.Dispose();
                        });
                        alertInsufficientQuantity.Create().Show();
                    }
                    catch (Exception ex)
                    {
                        //if error occurs during creating xml or decreasing the data in the database, delete created xml
                        if (File.Exists(xmlFullFilePath))
                        {
                            File.Delete(xmlFullFilePath);
                        }
                        //display error message "Insuficent quantity"
                        AlertDialog.Builder alertError = new AlertDialog.Builder(this);
                        string errorMessage            = "Грешка: " + ex.Message + "\n" + "поръчката не беше записана";
                        alertError.SetMessage(errorMessage);
                        alertError.SetPositiveButton("OK", delegate
                        {
                            alertError.Dispose();
                        });
                        alertError.Create().Show();
                    }
                }
                else
                {
                    //if some data is missing display error message
                    //create error message
                    string errorMessage = "Моля въведете: ";
                    errorMessage += String.IsNullOrEmpty(textViewCustomerName.Text) ? "име на клиент, " : "";
                    errorMessage += String.IsNullOrEmpty(btnDatePicker.Text) ? "дата на изпълнение на поръчка, " : "";
                    errorMessage += orderArticlesAdapter.listOfOrderArticles.Count == 0 ? "артикул" : "";
                    errorMessage  = errorMessage.TrimEnd(',', ' ');

                    //display error message
                    AlertDialog.Builder alertDataMissing = new AlertDialog.Builder(this);
                    alertDataMissing.SetMessage(errorMessage);
                    alertDataMissing.SetPositiveButton("OK", delegate
                    {
                        alertDataMissing.Dispose();
                    });
                    alertDataMissing.Create().Show();
                }
            };
        }
コード例 #5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.InputQuantityAndLot);

            //get id of selected article
            var articleId = Intent.GetStringExtra("articleId");

            //get article name and price from selected article and set it its TextViews
            var article = DatabaseRequest.GetAllFromTable <Article>()
                          .Where(x => x.Id == articleId).FirstOrDefault();

            TextView articleName = FindViewById <TextView>(Resource.Id.articleName);

            articleName.Text = article.Name;

            TextView articlePriceTextView = FindViewById <TextView>(Resource.Id.articlePriceTextView);

            articlePriceTextView.Text = article.SellPriceDisplay;

            TextView articlePriceAfterDiscountTextView = FindViewById <TextView>(Resource.Id.articlePriceAfterDiscountTextView);

            articlePriceAfterDiscountTextView.Text = articlePriceTextView.Text;

            TextView totalPriceTextView = FindViewById <TextView>(Resource.Id.totalPriceTextView);
            EditText quantityEditText   = FindViewById <EditText>(Resource.Id.quantityEditText);

            EditText discountEditText = FindViewById <EditText>(Resource.Id.discountEditText);

            discountEditText.SetFilters(new IInputFilter[] { new DecimalFilter(2) });
            discountEditText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
                //calculate article price after discount applied and set it to articlePriceAfterDiscountTextView
                decimal articlePrice = Convert.ToDecimal(articlePriceTextView.Text);
                decimal discountPercentage;
                if (!Decimal.TryParse(e.Text.ToString(), out discountPercentage))
                {
                    discountPercentage = 0;
                }
                decimal articleQuantity;
                if (!Decimal.TryParse(quantityEditText.Text, out articleQuantity))
                {
                    articleQuantity = 0;
                }
                ;
                decimal discountAmount            = Math.Round(articlePrice * (discountPercentage / 100), 4);
                decimal articlePriceAfterDiscount = articlePrice - discountAmount;
                articlePriceAfterDiscountTextView.Text = articlePriceAfterDiscount.ToString();
                //calculate total price
                decimal totalPrice = Math.Round(articlePriceAfterDiscount * articleQuantity, 2);
                totalPriceTextView.Text = totalPrice.ToString();
            };

            //EditText quantityEditText = FindViewById<EditText>(Resource.Id.quantityEditText);
            quantityEditText.SetFilters(new IInputFilter[] { new DecimalFilter(3) });
            quantityEditText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
                //calculate total price and set it to totalPriceTextView
                decimal articlePriceAfterDiscount = Convert.ToDecimal(articlePriceAfterDiscountTextView.Text);
                decimal articleQuantity;
                decimal totalPrice;
                //if entered value is not a number we set articleQuantity to 0
                if (!Decimal.TryParse(e.Text.ToString(), out articleQuantity))
                {
                    articleQuantity = 0;
                }
                ;

                totalPrice = Math.Round(articlePriceAfterDiscount * articleQuantity, 2);
                totalPriceTextView.Text = totalPrice.ToString();
            };

            //get all lots of selected article
            lots = DatabaseRequest.GetAllFromTable <Sertif>()
                   .Where(x => x.ArtId == articleId)
                   .Select(x => new LotViewModel
            {
                Name            = x.Name,
                ExpireDate      = x.ExpireDate,
                QuantityDisplay = x.QuantityDisplay,
                LotId           = x.Lotid,
            }).ToList();

            //fill in the RecyclerView with articles
            lotsRecyclerView  = FindViewById <RecyclerView>(Resource.Id.lotRecyclerView);
            lotsLayoutManager = new LinearLayoutManager(this);
            lotsRecyclerView.SetLayoutManager(lotsLayoutManager);
            lotsAdapter = new LotsAdapter(lots);
            lotsRecyclerView.SetAdapter(lotsAdapter);

            btnSelect = FindViewById <Button>(Resource.Id.btnSelect);

            btnSelect.Click += delegate
            {
                //Check if we have lot selected if not show alert message saying that we have to choose some lot
                if (!String.IsNullOrEmpty(lotsAdapter.currentLotIdChecked) || lotsAdapter.listOfLots.Count == 0)
                {
                    //Check if quantity typed from user is equal or greater ot equal to 0 than the quantity of selected lot
                    //if not display alert message saying: "Entered quantity is less that lot quantity"
                    decimal enteredQuantity = !String.IsNullOrEmpty(quantityEditText.Text) ? Convert.ToDecimal(quantityEditText.Text) : 0m;

                    decimal quantity;
                    bool    hasLots;
                    if (lotsAdapter.listOfLots.Count != 0)
                    {
                        hasLots = true;
                        decimal selectedLotQuantity = DatabaseRequest.GetAllFromTable <Sertif>()
                                                      .Where(x => x.Lotid == lotsAdapter.currentLotIdChecked)
                                                      .Select(x => x.Quantity).FirstOrDefault();
                        quantity = selectedLotQuantity;
                    }
                    else
                    {
                        hasLots = false;
                        decimal articleQuantity = DatabaseRequest.GetAllFromTable <Article>()
                                                  .Where(x => x.Id == articleId)
                                                  .Select(x => x.Quantity).FirstOrDefault();
                        quantity = articleQuantity;
                    }
                    if (enteredQuantity <= quantity && enteredQuantity > 0)
                    {
                        //redirect to OrdersActivity with articleId, lotid, price after discount, quantity
                        var ordersActivity = new Intent(this, typeof(OrdersActivity));
                        CurrentOrder.listOfOrderArticles.Add(
                            new OrderArticleViewModel
                        {
                            ArticleId         = articleId,
                            LotId             = lotsAdapter.currentLotIdChecked,
                            ArticleName       = articleName.Text,
                            PriceDiscount     = discountEditText.Text,
                            ArticlePrice      = articlePriceAfterDiscountTextView.Text,
                            ArticleQuantity   = quantityEditText.Text,
                            ArticleTotalPrice = totalPriceTextView.Text
                        });
                        StartActivity(ordersActivity);
                    }
                    else
                    {
                        AlertDialog.Builder alertQuantityNotValid = new AlertDialog.Builder(this);
                        alertQuantityNotValid.SetMessage("Въведеното количество е невалидно");
                        alertQuantityNotValid.SetPositiveButton("OK", delegate
                        {
                            alertQuantityNotValid.Dispose();
                        });
                        alertQuantityNotValid.Create().Show();
                    }
                }
                else
                {
                    AlertDialog.Builder alertLotNotChoosen = new AlertDialog.Builder(this);
                    alertLotNotChoosen.SetMessage("Моля изберете партида");
                    alertLotNotChoosen.SetPositiveButton("OK", delegate
                    {
                        alertLotNotChoosen.Dispose();
                    });

                    alertLotNotChoosen.Create().Show();
                }

                //Finish();
            };
        }