⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 services.cs

📁 微软的行业应用解决方案示例
💻 CS
📖 第 1 页 / 共 4 页
字号:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using HardwareDistributor.net.mappoint.staging;
using HardwareDistributor.Properties;
using HardwareDistributor.Synchronization;
using HardwareDistributor.Utilities;
using Microsoft.Mobile.Data;
using Microsoft.WindowsMobile.Status;

namespace HardwareDistributor.Business
{
    /// <summary>
    /// Business layer Services made available for 
    /// consumption by the UI layer
    /// </summary>
    public class Services
    {
        #region Fields
        private static DataStore _dataStore;
        private static Order _currentOrder;
        private static OrderDetail _currentOrderDetail;
		private static XDocument _configFile;
        #endregion


        #region Methods
        /// <summary>
        /// Caches a data source connection
        /// </summary>
        public static void CacheDataSourceConnection()
        {
            _dataStore = DataStore.GetDataStore(GlobalCache.Instance.ConnectionString);
            _dataStore.Trigger += new EventHandler<TriggerEventArgs>(DataStore_Trigger);
        }


        /// <summary>
        /// Instantiate MapPoint web services and call them as appropriate
        /// </summary>
        /// <param name="height">height of the image</param>
        /// <param name="width">width of the image</param>
        /// <param name="address">address to display</param>
        /// <param name="city">city of the address</param>
        /// <param name="state">state of the address</param>
        /// <returns>Map image with the address marked</returns>
        public static Bitmap CallMapPoint(int height, int width, string address, string city, string state)
        {
            //Configure Credentials
            NetworkCredential _credentials = new NetworkCredential(Business.GlobalCache.Instance.MapPointUserName, Business.GlobalCache.Instance.MapPointPassword);

            //Configure FindServiceSoap
            FindServiceSoap _find = new FindServiceSoap();
            _find.Credentials = _credentials;
            _find.PreAuthenticate = true;
            _find.Url = Business.GlobalCache.Instance.MapPointFindServiceUrl;

            //Configure RenderServiceSoap
            RenderServiceSoap _render = new RenderServiceSoap();
            _render.Credentials = _credentials;
            _render.PreAuthenticate = true;
            _render.Url = Business.GlobalCache.Instance.MapPointRenderServiceUrl;

            //Configure RouteServiceSoap
            RouteServiceSoap _route = new RouteServiceSoap();
            _route.Credentials = _credentials;
            _route.PreAuthenticate = true;
            _route.Url = Business.GlobalCache.Instance.MapPointRouteServiceUrl;

            //Get the Lat and Long for the distribution center starting point
            Location _start = GetLatLong("1 Microsoft Way", "Redmond", "WA", _find);
            //Get the Lat and Long for the customer end point
            Location _end = GetLatLong(address, city, state, _find);
            //Get the route from the distribution center to the customer
            return GetRoute(_start, _end, _route, _render, height, width);

        }


        /// <summary>
        /// Mark an order cancelled.
        /// </summary>
        /// <param name="orderId">Order to cancel</param>
        public static void CancelOrder(Guid orderId)
        {
            Order order;
            Parameters parameters;

            //get the order details
            order = GetOrder(orderId);

            //if items have been picked, then place them back in
            //the inventory
            if (order.OrderState >= OrderState.Picked)
            {
                parameters = new Parameters();
                string incrementInventorySQL = @"
                        UPDATE Inventory
                        SET InStock = InStock + @Increment
                        WHERE InventoryId = @InventoryId";

                foreach (OrderDetail item in order.OrderDetails)
                {
                    parameters["@Increment"] = item.Quantity;
                    parameters["@InventoryId"] = item.InventoryId;
                    _dataStore.Save(incrementInventorySQL, parameters);
                }
            }

            //udpate the order state to cancelled
            order.OrderState = Business.OrderState.Cancelled;
            SaveOrder(order);
        }


        /// <summary>
        /// Test to see if the replication ISAPI DLL is reachable
        /// </summary>
        /// <returns>true if it can hit the replication service</returns>
        public static bool CheckSynchronizationUrl()
        {
            //Create a NetworkCredential object
            NetworkCredential cred = new NetworkCredential(GlobalCache.Instance.InternetLogin,
                                                           GlobalCache.Instance.InternetPassword);
            //Pass the ISAPI DLL URL and the credentials to webcheck
            return WebCheck(GlobalCache.Instance.InternetUrl, cred);
        }


        /// <summary>
        /// Build an <see cref="HardwareDistributor.Business.Inventory"/> item 
        /// from a <see cref="Microsoft.Mobile.Data.DataRow"/>.
        /// </summary>
        /// <param name="currentRow">data row to build inventory</param>
        /// <returns>
        /// Unmodified inventory object with properties built from DataRow
        /// </returns>
        private static Inventory CreateInventory(DataRow currentRow)
        {
            return new Inventory(GetValue<Nullable<int>>(currentRow[Inventory.INVENTORYID_COLUMN]),
                                 GetValue<string>(currentRow[Inventory.NAME_COLUMN]),
                                 GetValue<byte[]>(currentRow[Inventory.PICTURE_COLUMN]),
                                 GetValue<Nullable<decimal>>(currentRow[Inventory.PRICE_COLUMN]),
                                 GetValue<Nullable<int>>(currentRow[Inventory.INSTOCK_COLUMN]),
                                 GetValue<Nullable<int>>(currentRow[Inventory.DISTRIBUTIONCENTER_COLUMN]),
                                 GetValue<Nullable<int>>(currentRow[Inventory.BIN_COLUMN]));
        }


        /// <summary>
        /// Build an <see cref="HardwareDistributor.Business.Order"/> item 
        /// from a <see cref="Microsoft.Mobile.Data.DataRow"/>.
        /// </summary>
        /// <param name="currentRow">data row to build order</param>
        /// <returns>
        /// Unmodified order object with properties built from DataRow
        /// </returns>
        private static Order CreateOrder(DataRow currentRow)
        {
            Nullable<int> customerId;
            Nullable<int> displayId;
            Nullable<DateTime> deliveryDate;
            Nullable<Guid> orderId;
            Nullable<OrderState> orderState;
            byte[] signature;

            customerId = GetValue<Nullable<int>>(currentRow[Order.CUSTOMERID_COLUMN]);
            deliveryDate = GetValue<Nullable<DateTime>>(currentRow[Order.DELIVERYDATE_COLUMN]);
            if (currentRow[Order.ORDERSTATE_COLUMN] != null)
            {
                orderState = (OrderState)(int)currentRow[Order.ORDERSTATE_COLUMN];
            }
            else
            {
                orderState = null;
            }
            orderId = GetValue<Nullable<Guid>>(new Guid(Convert.ToString((currentRow[Order.ORDERID_COLUMN]))));
            signature = GetValue<byte[]>(currentRow[Order.SIGNATURE_COLUMN]);
            displayId = GetValue<Nullable<int>>(currentRow[Order.DISPLAYID_COLUMN]);

            return new Order(orderId, customerId, deliveryDate, orderState, signature, displayId);
        }


        /// <summary>
        /// Tests to see if the SQL Server Everywhere database exists
        /// </summary>
        /// <returns></returns>
        public static bool DatabaseExists()
        {
            //Pass the application path plus the database name to the Exists method
            return (File.Exists(GlobalCache.Instance.AppPath + GlobalCache.Instance.SqlCeDatabase));
        }


        /// <summary>
        /// What to do when the datastore has an insert, modify or delete. In 
        /// this case only looking for Order and OrderDetail inserts to get 
        /// the new identity.
        /// </summary>
        /// <param name="sender">source of the event</param>
        /// <param name="e">trigger event object</param>
        static void DataStore_Trigger(object sender, TriggerEventArgs e)
        {
            Guid id;

            if (e.TriggerAction == TriggerType.Insert)
            {
                id = new Guid(Convert.ToString(_dataStore.GetValue(StoredProcs.GetIdentity)));
                switch (e.Identifier)
                {
                    case "Orders":
                        //Retrieve value of Identity column that was just incremented
                        _currentOrder.OrderId = id;
                        break;
                    case "OrderDetails":
                        _currentOrderDetail.OrderDetailId = id;
                        break;
                }
            }
        }


        /// <summary>
        /// Deletes a SQL Server Compact database
        /// </summary>
        public static void DeleteDatabase()
        {
            File.Delete(GlobalCache.Instance.AppPath + GlobalCache.Instance.SqlCeDatabase);
        }


        /// <summary>
        /// Retrieves setting from the xml config file
        /// </summary>
        /// <param name="appSettingName">setting to retrieve</param>
        /// <returns>value of the setting or empty string if not found</returns>
        private static string GetAppSetting(string appSettingName)
        {
            try
            {
                return GetAppSettingNode(appSettingName).Attribute("value").Value;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }


        /// <summary>
        /// Retrieves the matching xml element from the xml config file
        /// </summary>
        /// <param name="appSettingName">setting to retrieve</param>
        /// <returns>the node containing the requested setting</returns>
        private static XElement GetAppSettingNode(string appSettingName)
        {
            if (_configFile == null)
            {
                _configFile = XDocument.Load(GlobalCache.Instance.ConfigFile);
            }
            var appSettings = (from appSetting in _configFile.Descendants("add")
                               where appSetting.Attribute("key") != null &&
                               appSetting.Attribute("key").Value == appSettingName
                               select appSetting).Single();
            return appSettings;
        }


        /// <summary>
        /// Informs the caller of the device's current network 
        /// connection status in order to make networking decisions
        /// </summary>
        /// <returns></returns>
        public static bool GetConnectionStatus()
        {
            //See if there's one or more network connections
            return (SystemState.ConnectionsCount > 0);
        }


        /// <summary>
        /// Retrieve a Generic list of all Customer objects
        /// </summary>
        /// <returns>All customers</returns>
        public static List<Customer> GetCustomers()
        {
            // Build a Linq Query to build a list of customers
            // you could modify this to also find only specific customers
            // with a where clause
            var customerQuery = from currentRow in _dataStore.Read(StoredProcs.GetCustomers)
                                select new Customer(GetValue<Nullable<int>>(currentRow[Customer.CUSTOMERID_COLUMN]),
                                                    GetValue<string>(currentRow[Customer.NAME_COLUMN]),
                                                    GetValue<string>(currentRow[Customer.STREETADDRESS_COLUMN]),
                                                    GetValue<string>(currentRow[Customer.CITY_COLUMN]),

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -