Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var distance        = 159.5;
            var product         = new { Name = "Xbox", Weight = 2.6 };
            var shippingService = new ShippingService();

            var correiosShipping = new Correios();
            var jadlogShipping   = new Jadlog();
            var tntShipping      = new Tnt();
            var upsShipping      = new Ups();

            shippingService.SetCalculateShipping(correiosShipping);
            double correiosShippingPrice = shippingService.Calculate(product.Weight, distance);

            shippingService.SetCalculateShipping(jadlogShipping);
            double jadlogShippingPrice = shippingService.Calculate(product.Weight, distance);

            shippingService.SetCalculateShipping(tntShipping);
            double tntShippingPrice = shippingService.Calculate(product.Weight, distance);

            shippingService.SetCalculateShipping(upsShipping);
            double upsShippingPrice = shippingService.Calculate(product.Weight, distance);

            System.Console.WriteLine($"Correios: {correiosShippingPrice:C2}");
            System.Console.WriteLine($"Jadlog: {jadlogShippingPrice:C2}");
            System.Console.WriteLine($"TNT: {tntShippingPrice:C2}");
            System.Console.WriteLine($"UPS: {upsShippingPrice:C2}");
        }
Ejemplo n.º 2
0
        protected override void ProcessRecord()
        {
            ServiceHelper helper = ServiceHelper.Create();

            Server server = new Server()
            {
                Address  = this.Address,
                Port     = this.Port,
                Username = this.Credential.UserName,
                UseSSL   = this.UseSSL,
                PreferredAddressFamily = this.PreferredAddressFamily,
                ServerSSLName          = this.ServerSSLName,
            };

            try
            {
                Ups ups = helper.Channel.AddUps(
                    server,
                    this.Credential.Password.GetDecrypted(),
                    this.UpsName,
                    this.NumPowerSupplies,
                    this.MonitorOnly,
                    this.Force.ToBool());

                this.WriteObject(ups);
            }
            catch (AggregateException e) when(e.InnerExceptions.Count == 1)
            {
                throw e.InnerExceptions.First();
            }
        }
Ejemplo n.º 3
0
        public List <Ups> GetUpsFromServer(Server server, string password, string upsName)
        {
            // Update the password on the server object since it can't be passed as a SecureString
            // over the WCF channel
            server.Password = SecureStringExtensions.FromString(password);
            ServerConfiguration serverConfiguration = ServerConfiguration.CreateFromServer(server);

            serverConfiguration.ValidateProperties();

            // Recreate the server object to ensure that it matches what would be created when it
            // is read from configuration at startup.
            server = Server.CreateFromConfiguration(serverConfiguration);

            ServerConnection serverConnection = new ServerConnection(server);

            serverConnection.ConnectAsync(CancellationToken.None).Wait();

            try
            {
                Dictionary <string, string> listResponse =
                    serverConnection
                    .ListUpsAsync(CancellationToken.None).Result;

                List <Ups> upsList = new List <Ups>();

                foreach (string thisUpsName in listResponse.Keys)
                {
                    if (!string.IsNullOrWhiteSpace(upsName) && !string.Equals(thisUpsName, upsName))
                    {
                        continue;
                    }

                    Dictionary <string, string> upsVars =
                        serverConnection
                        .ListVarsAsync(thisUpsName, CancellationToken.None).Result;

                    var ups = Ups.Create(thisUpsName, server, upsVars);

                    var upsContext =
                        ServiceRuntime.Instance.UpsContexts.FirstOrDefault(
                            ctx => ctx.Name == thisUpsName && ctx.ServerState.Name == server.Name);

                    ups.IsManaged = upsContext != null;

                    upsList.Add(ups);
                }

                return(upsList);
            }
            finally
            {
                serverConnection.Disconnect();
            }
        }
Ejemplo n.º 4
0
        private static Ups GetOrCreateState(UpsContext ctx)
        {
            if (ctx.State != null)
            {
                return(ctx.State);
            }

            return(Ups.Create(
                       ctx.Name,
                       ctx.ServerState,
                       new Dictionary <string, string>()));
        }
Ejemplo n.º 5
0
        private Ups ConvertirAUps(int idusuario)
        {
            Ups us = null;

            bdanexoDataSet.upsDataTable ups = upsTableAdapter1.GetUpsByUsuario(idusuario);
            if (ups.Rows.Count > 0)
            {
                us              = new Ups();
                us.marca        = ((bdanexoDataSet.upsRow)ups.Rows[0]).marca;
                us.noserie      = ((bdanexoDataSet.upsRow)ups.Rows[0]).noserie;
                us.modelo       = ((bdanexoDataSet.upsRow)ups.Rows[0]).modelo;
                us.noinventario = ((bdanexoDataSet.upsRow)ups.Rows[0]).noinventario;
                us.estado       = ((bdanexoDataSet.upsRow)ups.Rows[0]).estado;
                us.id           = ((bdanexoDataSet.upsRow)ups.Rows[0]).Id;
            }
            return(us);
        }
        public DevicePropertyViewModel(
            string header,
            Ups ups,
            string propertyName,
            Func <string> converter)
        {
            this.Header = header;

            this.Value = converter();

            ups.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == propertyName)
                {
                    this.Value = converter();
                }
            };
        }
Ejemplo n.º 7
0
 public static UpsConfiguration Create(Ups ups)
 {
     return(new UpsConfiguration
     {
         ServerConfiguration = new ServerConfiguration
         {
             Address = ups.Server.Address,
             Port = ups.Server.Port,
             Username = ups.Server.Username,
             Password = ups.Server.Password,
             UseSSL = ups.Server.UseSSL,
             ServerSSLName = ups.Server.ServerSSLName,
             PreferredAddressFamily = ups.Server.PreferredAddressFamily,
         },
         DeviceName = ups.Name,
         EnableEmailNotification = true,
         EnablePowerShellNotification = true
     });
 }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var laptop = new Laptop();

            var americanLaptop        = new AmericanLaptop();
            var adaptedAmericanLaptop = new Adapter(americanLaptop);

            var electricalDevices = new List <IElectricalDevice> {
                laptop, adaptedAmericanLaptop
            };

            var powerStrip = new PowerStrip(electricalDevices);

            var ups      = new Ups(powerStrip);
            var defender = new HighElectricityDefender(ups);

            defender.ConsumeElectricity(20);

            Console.WriteLine(defender.ToString());
        }
Ejemplo n.º 9
0
        public VActualizarDatos(string SelectedId)
        {
            InitializeComponent();
            listDiscosDuros      = new List <DiscoDuro>();
            listDiscosDurosVieja = new List <DiscoDuro>();
            usuario    = new Usuario();
            equipo     = new Equipo();
            discoduro  = new DiscoDuro();
            accesorios = new Accesorios();
            cdroom     = new CdRoom();
            disquete   = new Disquete();
            fx         = new Fax();
            fotoc      = new Fotocopiadora();
            impresora  = new Impresora();
            monitor    = new Monitor();
            scaner     = new Scanner();
            swt        = new Switch();
            bck        = new Ups();
            config     = new Configuracion();

            BuscarDatos(SelectedId);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Update...
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <remarks>
        /// Note: The caller must hold a reader lock from UpsMonitor prior to calling
        /// this method
        /// </remarks>
        private async Task UpdateStatusAsync(CancellationToken cancellationToken)
        {
            try
            {
                // Get the current status of the device from the server
                Dictionary <string, string> deviceVars =
                    await this.Connection
                    .ListVarsAsync(this.Name, cancellationToken)
                    .ConfigureAwait(false);

                //Dictionary<string, string> deviceRw =
                //    await this.Connection
                //        .ListRwAsync(this.Name, cancellationToken)
                //        .ConfigureAwait(false);

                //List<string> deviceCmd =
                //    await this.Connection
                //        .ListCmdAsync(this.Name, cancellationToken)
                //        .ConfigureAwait(false);

                //Dictionary<string, string> deviceEnum =
                //    await this.Connection
                //        .ListEnumAsync(this.Name + " input.transfer.low", cancellationToken)
                //        .ConfigureAwait(false);

                //Dictionary<string, string> deviceRange =
                //    await this.Connection
                //        .ListRangeAsync(this.Name + " input.transfer.low", cancellationToken)
                //        .ConfigureAwait(false);

                Logger.Debug(
                    "UpdateStatusAsync[Ups={0}]: Successfully queried server",
                    this.QualifiedName);

                var metricMeasurements = this.MetricDatabase.UpdateMetrics(deviceVars);

                if (this.State == null)
                {
                    // We haven't yet pulled the device information from the server yet, so
                    // do that now. Since this will be the first time pulling device state
                    // from the server, we won't have any previous state to compare it to,
                    // so don't bother comparing state.
                    this.State = Ups.Create(this.Name, this.ServerState, deviceVars);

                    // ReSharper disable once MethodSupportsCancellation
                    this.upsMonitor.Changes.Add(
                        new UpsStatusChangeData
                    {
                        // Pass null as the previous state to indicate that this is the first time
                        // receiving state information for this device
                        PreviousState = null,
                        UpsContext    = this
                    });
                }
                else
                {
                    // Create a copy of the current state in case we need it below
                    var previousState = this.State.Clone();

                    // Update the state object is with the new variables from the server
                    this.State.Update(deviceVars);

                    // The status has changed, so queue a status change notification
                    if (previousState.Status != this.State.Status)
                    {
                        // ReSharper disable once MethodSupportsCancellation
                        this.upsMonitor.Changes.Add(
                            new UpsStatusChangeData
                        {
                            // Create a copy of the device state to pass to UpsMonitor
                            PreviousState = previousState,
                            UpsContext    = this
                        });
                    }

#pragma warning disable 4014
                    Task.Run(() =>
                    {
                        foreach (IManagementCallback callbackChannel in
                                 ServiceRuntime.Instance.ClientCallbackChannels)
                        {
                            try
                            {
                                callbackChannel.UpsDeviceChanged(this.State, metricMeasurements.ToArray());
                            }
                            catch (Exception e)
                            {
                                Logger.Error("Caught exception while updating device. " + e.Message);
                                ServiceRuntime.Instance.ClientCallbackChannels.Remove(callbackChannel);
                                break;
                            }
                        }
                    }, cancellationToken);
#pragma warning restore 4014
                }

                // We successfully queried the server, so update the property for this
                this.State.LastPollTime = DateTime.Now;
            }
            catch (NutCommunicationException commEx)
            {
                Logger.Debug(
                    "UpdateStatusAsync[Ups={0}]: Caught exception querying server. {1}",
                    this.QualifiedName,
                    commEx);

                this.Disconnect(true, true);

                // We failed to communicate with the server, so raise a change notification
                // ReSharper disable once MethodSupportsCancellation
                this.upsMonitor.Changes.Add(
                    new UpsStatusChangeData
                {
                    // Create a copy of the device state to pass to UpsMonitor
                    PreviousState = this.State.Clone(),
                    UpsContext    = this,
                    Exception     = commEx
                });
            }

            Logger.Debug(
                "UpdateStatusAsync[Ups={0}]: Finished UpdateStatusAsync()",
                this.QualifiedName);
        }
Ejemplo n.º 11
0
        /* background worker that processing each order from the orderList */
        private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            // initialize all carrier fields
            Ups        ups        = new Ups();
            CanadaPost canadaPost = new CanadaPost();

            // start processing orders
            foreach (Order order in orderList)
            {
                // for sears order
                switch (order.Source)
                {
                case "Sears":
                {
                    #region Sears Order
                    // first get the detail for the order
                    SearsValues value = sears.GenerateValue(order.TransactionId);

                    // check if the order has been shipped before -> if not, ship it now
                    if (value.Package.TrackingNumber == "")
                    {
                        value.Package = new Package(value);

                        // second ship it
                        string[] digest = ups.PostShipmentConfirm(value);
                        if (ups.Error)
                        {
                            MessageBox.Show(ups.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        string[] result = ups.PostShipmentAccept(digest[1]);
                        if (ups.Error)
                        {
                            MessageBox.Show(ups.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        // get identification, tracking, label and shipment confirm with no cancellation of item
                        value.Package.IdentificationNumber = digest[0];
                        value.Package.TrackingNumber       = result[0];
                        ups.ExportLabel(result[1], value.TransactionId, false);
                    }
                    sears.GenerateXml(value, new System.Collections.Generic.Dictionary <int, string>());

                    // post order to brightpearl with no cancellation
                    bp.PostOrder(value, new int[0]);
                    #endregion
                }
                break;

                case "Shop.ca":
                {
                    #region Shop.ca Order
                    // first get the detail for the order
                    ShopCaValues value = shopCa.GenerateValue(order.TransactionId);

                    // check if the order has been shipped before -> if not, ship it now
                    if (value.Package.TrackingNumber == "")
                    {
                        value.Package = new Package(value);

                        // second ship it
                        string[] links = canadaPost.CreateShipment(value.ShipTo, value.Package);
                        if (canadaPost.Error)
                        {
                            MessageBox.Show(canadaPost.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        // get tracking, self link, label link and shipment confirm with no cancellation of item
                        value.Package.TrackingNumber = links[0];
                        value.Package.SelfLink       = links[1];
                        value.Package.LabelLink      = links[2];

                        System.Threading.Thread.Sleep(5000);

                        // get artifact and export it
                        byte[] binary = canadaPost.GetArtifact(links[2]);
                        canadaPost.ExportLabel(binary, value.OrderId, true, false);
                    }
                    shopCa.GenerateTxt(value, new System.Collections.Generic.Dictionary <int, string>());

                    // post order to brightpearl with no cancellation
                    bp.PostOrder(value, new int[0]);
                    #endregion
                }
                break;

                case "Giant Tiger":
                {
                    #region Giant Tiger Order
                    // first get the detail for the order
                    GiantTigerValues value = giantTiger.GenerateValue(order.TransactionId);

                    // check if the order has been shipped before -> if not, ship it now
                    if (value.Package.TrackingNumber == "")
                    {
                        value.Package = new Package(value);

                        // second ship it
                        string[] links = canadaPost.CreateShipment(value.ShipTo, value.Package);
                        if (canadaPost.Error)
                        {
                            MessageBox.Show(canadaPost.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        // get tracking, self link, label link and shipment confirm with no cancellation of item
                        value.Package.TrackingNumber = links[0];
                        value.Package.SelfLink       = links[1];
                        value.Package.LabelLink      = links[2];

                        System.Threading.Thread.Sleep(5000);

                        // get artifact and export it
                        byte[] binary = canadaPost.GetArtifact(links[2]);
                        canadaPost.ExportLabel(binary, value.PoNumber, true, false);
                    }
                    giantTiger.GenerateCsv(value, new System.Collections.Generic.Dictionary <int, string>());

                    // post order to brightpearl with no cancellation
                    bp.PostOrder(value, new int[0]);
                    #endregion
                }
                break;
                }
            }
        }
Ejemplo n.º 12
0
        private void BuscarDatos(string SelectedId)
        {
            bdanexoDataSet.expedienteDataTable exp = expedienteTableAdapter1.ExpedienteById(Convert.ToInt16(SelectedId));
            int idusuario = ((bdanexoDataSet.expedienteRow)exp.Rows[0]).idusuario;

            if (exp.Rows.Count > 0)
            {
                usuario = ConvertirAUsuario(idusuario);
                if (usuario != null)
                {
                    PagUsuario.PageVisible = true;
                    txtnombre.Text         = usuario.UsuarioNombre;
                    txtuser.Text           = usuario.usuario;
                    txtcorreo.Text         = usuario.Correo;
                    txtarea.Text           = usuario.Area;
                    labelControl3.Text     = "Id: " + usuario.id;
                }
            }

            equipo = ConvetirAEquipo(idusuario);
            if (equipo != null)
            {
                PagEquipo.PageVisible = true;
                groupEquipo.Enabled   = true;
                txtnombreequipo.Text  = equipo.nombre;
                txtnoinvequipo.Text   = equipo.noinventario;
                txtnoserieequipo.Text = equipo.noserie;
                txtdominiored.Text    = equipo.dominiored;

                memoobservaciones.Text = equipo.observaciones;
            }


            config = ConvertirAConfig(idusuario);
            if (config != null)
            {
                PagEquipo.PageVisible         = true;
                groupConfiguracion.Enabled    = true;
                txtplacabase.Text             = config.placabase;
                txtnoserieconfig.Text         = config.noserieplacabase;
                txtprocesador.Text            = config.procesador;
                txtvelocidad.Text             = config.velocidad;
                txtmemoria.Text               = config.memoria;
                txtcantidadconfiguracion.Text = config.cantidad;
                txttarjetagrafica.Text        = config.tarjetavideo;
                txttarjetasonido.Text         = config.tarjetasonido;
                txttarjetared.Text            = config.tarjetared;
            }

            bdanexoDataSet.discoduroDataTable dd = discoduroTableAdapter1.GetDiscoDuroByUsuario(((bdanexoDataSet.expedienteRow)exp.Rows[0]).Id);
            if (dd.Rows.Count > 0)
            {
                PagDiscoDuro.PageVisible = true;
                foreach (var item in dd.Rows)
                {
                    DiscoDuro disco = new DiscoDuro();
                    disco.descripcion = ((bdanexoDataSet.discoduroRow)item).descripcion;
                    disco.capacidad   = ((bdanexoDataSet.discoduroRow)item).capacidad;
                    disco.noserie     = ((bdanexoDataSet.discoduroRow)item).noserie;
                    disco.estado      = ((bdanexoDataSet.discoduroRow)item).estado;
                    listDiscosDuros.Add(disco);
                }
                listDiscosDurosVieja     = listDiscosDuros;
                gridControlDD.DataSource = listDiscosDuros;
            }

            // almacenamiento
            cdroom = ConvertirACD(idusuario);
            if (cdroom != null)
            {
                PagAlmacenamiento.PageVisible = true;
                groupLector.Enabled           = true;
                txtcddescripcion.Text         = cdroom.nombre;
                txtcdnoserie.Text             = cdroom.noserie;
                cbxestadocd.Text = cdroom.estadocdroom;
            }

            disquete = ConvertirADisquete(idusuario);
            if (disquete != null)
            {
                PagAlmacenamiento.PageVisible = true;
                groupDisquete.Enabled         = true;
                txtdescripciondisquete.Text   = disquete.nombre;
                txtdisquetenoserie.Text       = disquete.noserie;
                cbxestadodisq.Text            = disquete.estado;
            }

            // accesorios
            accesorios = ConvertirAAccesorios(idusuario);
            if (accesorios != null)
            {
                PagAccesorios.PageVisible = true;

                txtteclado.Text = accesorios.teclado;
                txtraton.Text   = accesorios.mouse;
                txtbocinas.Text = accesorios.bocina;

                cbxestadobocinas.Text = accesorios.estadobocina;
                cbxestadoraton.Text   = accesorios.estadomouse;
                cbxestadoteclado.Text = accesorios.estadoteclado;
            }

            //impresora
            impresora = ConvertirAImpresora(idusuario);
            if (impresora != null)
            {
                PagImpresora.PageVisible      = true;
                txtimpresoramarca.Text        = impresora.marca;
                txtimpresoramodelo.Text       = impresora.modelo;
                txtimpresoranoserie.Text      = impresora.noserie;
                txtimpresoranoinventario.Text = impresora.noinventario;
                cbxestadoimpresora.Text       = impresora.estado;
            }

            //monitor
            monitor = ConvertirAMonitor(idusuario);
            if (monitor != null)
            {
                PagMonitor.PageVisible = true;
                txtmonitormarca.Text   = monitor.marca;
                txtmonitornoserie.Text = monitor.noserie;
                txtmonitormodelo.Text  = monitor.modelo;
                txtmonitornoinv.Text   = monitor.noinventario;
                cbxestadomonitor.Text  = monitor.estado;
            }

            //switch
            swt = ConvertirASwitch(idusuario);
            if (swt != null)
            {
                PagSwitch.PageVisible = true;
                txtswitcmarca.Text    = swt.marca;
                txtswitchnoserie.Text = swt.noserie;
                txtswitchmodelo.Text  = swt.modelo;
                txtswitchnoinv.Text   = swt.noinventario;
                cbxestadoswitch.Text  = swt.estado;
            }

            //fax
            fx = ConvertirAFax(idusuario);
            if (fx != null)
            {
                PagFax.PageVisible = true;
                txtfaxmarca.Text   = fx.marca;
                txtfaxnoseie.Text  = fx.noserie;
                txtfaxmodelo.Text  = fx.modelo;
                txtfaxnoinv.Text   = fx.noinventario;
                cbxestadofax.Text  = fx.estado;
            }
            //Backup
            bck = ConvertirAUps(idusuario);
            if (bck != null)
            {
                PagBackup.PageVisible = true;
                txtbackupmarca.Text   = bck.marca;
                txtbackupnoserie.Text = bck.noserie;
                txtbackupmodelo.Text  = bck.modelo;
                txtbackupnoinv.Text   = bck.noinventario;
                cbxestadoups.Text     = bck.estado;
            }
            // escaner
            scaner = ConvertirAScaner(idusuario);
            if (scaner != null)
            {
                PagScaneer.PageVisible = true;
                txtscanermarca.Text    = scaner.marca;
                txtscanernoserie.Text  = scaner.noserie;
                txtscanermodelo.Text   = scaner.modelo;
                txtscanernoinv.Text    = scaner.noinventario;
                cbxestadoscaner.Text   = scaner.estado;
            }

            // fotocopiadora
            fotoc = ConvertirAFoct(idusuario);
            if (fotoc != null)
            {
                PagFotoc.PageVisible              = true;
                txtfotocopiadoramarca.Text        = fotoc.marca;
                txtfotocopiadoranoserie.Text      = fotoc.noserie;
                txtfotocopiadoramodelo.Text       = fotoc.modelo;
                txtfotocopiadoranoinventario.Text = fotoc.noinventario;
                cbxestadofotocopiadora.Text       = fotoc.estado;
            }
        }
Ejemplo n.º 13
0
 public IActionResult Ups(Ups model) => Save(model);
Ejemplo n.º 14
0
        /* void shipment button that void the current shipment for the order */
        private void voidShipmentButton_Click(object sender, EventArgs e)
        {
            switch (CHANNEL)
            {
            case "Sears":
                #region UPS
                // post void shipment request and get the response
                Ups ups = new Ups();
                ups.PostShipmentVoid(searsValues.Package.IdentificationNumber);

                // the case if is bad request
                if (ups.Error)
                {
                    MessageBox.Show(ups.ErrorMessage, "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // mark transaction as not shipped
                new Sears().PostVoid(new[] { searsValues.TransactionId });

                // set tracking and identification to nothing
                searsValues.Package.IdentificationNumber = string.Empty;
                searsValues.Package.TrackingNumber       = string.Empty;

                break;

                #endregion
            case "Shop.ca":
                #region Canada Post
            {
                // post void shipment request and get the response
                CanadaPost canadaPost = new CanadaPost();
                canadaPost.DeleteShipment(shopCaValues.Package.SelfLink);

                // the cas if is bad request
                if (canadaPost.Error)
                {
                    MessageBox.Show(canadaPost.ErrorMessage, "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // mar order as not shipped
                new ShopCa().PostVoid(new[] { shopCaValues.OrderId });

                // set tracking, self link, label link to nothing
                shopCaValues.Package.TrackingNumber = string.Empty;
                shopCaValues.Package.SelfLink       = string.Empty;
                shopCaValues.Package.LabelLink      = string.Empty;
            }
            break;

                #endregion
            case "Giant Tiger":
                #region Canada Post
            {
                // post void shipment request and get the response
                CanadaPost canadaPost = new CanadaPost();
                canadaPost.DeleteShipment(giantTigerValues.Package.SelfLink);

                // the cas if is bad request
                if (canadaPost.Error)
                {
                    MessageBox.Show(canadaPost.ErrorMessage, "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // mar order as not shipped
                new GiantTiger().PostVoid(new[] { giantTigerValues.PoNumber });

                // set tracking, self link, label link to nothing
                giantTigerValues.Package.TrackingNumber = string.Empty;
                giantTigerValues.Package.SelfLink       = string.Empty;
                giantTigerValues.Package.LabelLink      = string.Empty;
            }
            break;
                #endregion
            }

            // mark cancel as invisible, set tracking number text to not shipped, and enable create label button
            voidShipmentButton.Visible = false;
            trackingNumberTextbox.Text = "Not shipped";
            createLabelButton.Enabled  = true;
        }
Ejemplo n.º 15
0
        private void backgroundWorkerShip_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            switch (CHANNEL)
            {
            case "Sears":
                #region UPS
                // initialize field for shipment
                Ups ups = new Ups();

                // post shipment confirm and get the digest string from response
                string[] digest = ups.PostShipmentConfirm(searsValues);

                // error checking
                if (ups.Error)
                {
                    MessageBox.Show(ups.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Result = true;
                    return;
                }

                // post shipment accept and get tracking number and image
                string[] acceptResult = ups.PostShipmentAccept(digest[1]);

                // error checking
                if (ups.Error)
                {
                    MessageBox.Show(ups.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Result = true;
                    return;
                }

                // retrieve identification number and tracking number
                searsValues.Package.IdentificationNumber = digest[0];
                searsValues.Package.TrackingNumber       = acceptResult[0];

                // update database set the order's tracking number and identification number
                new Sears().PostShip(searsValues.Package.TrackingNumber, searsValues.Package.IdentificationNumber, searsValues.TransactionId);

                // get the shipment label and show it
                ups.ExportLabel(acceptResult[1], searsValues.TransactionId, true);
                break;

                #endregion
            case "Shop.ca":
                #region Canada Post
            {
                // initialize field for shipment
                CanadaPost canadaPost = new CanadaPost();

                // create shipment for canada post
                string[] result = canadaPost.CreateShipment(shopCaValues.ShipTo, shopCaValues.Package);

                // error checking
                if (canadaPost.Error)
                {
                    MessageBox.Show(canadaPost.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Result = true;
                    return;
                }

                // retrieve tracking number, refund link and label link
                shopCaValues.Package.TrackingNumber = result[0];
                shopCaValues.Package.SelfLink       = result[1];
                shopCaValues.Package.LabelLink      = result[2];

                // update database set the order's tracking number refund link and label link
                new ShopCa().PostShip(shopCaValues.Package.TrackingNumber, shopCaValues.Package.SelfLink, shopCaValues.Package.LabelLink, shopCaValues.OrderId);

                // get artifect
                Thread.Sleep(5000);
                byte[] artifect = canadaPost.GetArtifact(result[2]);

                // error checking
                if (canadaPost.Error)
                {
                    MessageBox.Show(canadaPost.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Result = true;
                    return;
                }

                // get the shipment label and show it
                canadaPost.ExportLabel(artifect, shopCaValues.OrderId, true, true);
            }
            break;

                #endregion
            case "Giant Tiger":
                #region Canada Post
            {
                // initialize field for shipment
                CanadaPost canadaPost = new CanadaPost();

                // create shipment for canada post
                string[] result = canadaPost.CreateShipment(giantTigerValues.ShipTo, giantTigerValues.Package);

                // error checking
                if (canadaPost.Error)
                {
                    MessageBox.Show(canadaPost.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Result = true;
                    return;
                }

                // retrieve tracking number, refund link and label link
                giantTigerValues.Package.TrackingNumber = result[0];
                giantTigerValues.Package.SelfLink       = result[1];
                giantTigerValues.Package.LabelLink      = result[2];

                // update database set the order's tracking number refund link and label link
                new GiantTiger().PostShip(giantTigerValues.Package.TrackingNumber, giantTigerValues.Package.SelfLink, giantTigerValues.Package.LabelLink, giantTigerValues.PoNumber);

                // get artifect
                Thread.Sleep(5000);
                byte[] artifect = canadaPost.GetArtifact(result[2]);

                // error checking
                if (canadaPost.Error)
                {
                    MessageBox.Show(canadaPost.ErrorMessage, "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Result = true;
                    return;
                }

                // get the shipment label and show it
                canadaPost.ExportLabel(artifect, giantTigerValues.PoNumber, true, true);
            }
            break;
                #endregion
            }

            // set bool flag to false
            e.Result = false;
        }
Ejemplo n.º 16
0
Archivo: Ups.cs Proyecto: erynet/IMS
        public static bool SetUps(Ups.Info ups)
        {
            try
            {
                using (var ctx = new LocalDB())
                {
                    var existUps =
                        (from u in ctx.Ups where u.Idx == ups.upsIdx select u).DefaultIfEmpty(null).First();
                    if (existUps == null)
                        return false;

                    //existCdu.GroupNo = cdu.
                    existUps.GroupNo = ups.groupNo;
                    existUps.No = ups.upsNo;
                    existUps.Name = ups.upsName;
                    existUps.MateList = ups.partnerNoList.ToString();
                    existUps.CduNo = ups.cduNo;
                    existUps.Specification = ups.batteryDescription;
                    existUps.Capacity = ups.batteryCapacity;
                    existUps.IpAddress = ups.ip;
                    existUps.Enabled = ups.isUsing;
                    existUps.InstallAt = ups.installDate;
                    //existCdu.Description = cdu.

                    using (var trx = new TransactionScope())
                    {
                        ctx.SaveChanges();
                        trx.Complete();
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"SetUps : {e.ToString()}");
                return false;
            }
        }
Ejemplo n.º 17
0
        public Ups AddUps(
            Server server,
            string password,
            string upsName,
            int numPowerSupplies,
            bool monitorOnly,
            bool force)
        {
            // Update the password on the server object since it can't be passed as a SecureString
            // over the WCF channel
            server.Password = SecureStringExtensions.FromString(password);
            ServerConfiguration serverConfiguration = ServerConfiguration.CreateFromServer(server);

            serverConfiguration.ValidateProperties();

            // Recreate the server object to ensure that it matches what would be created when it
            // is read from configuration at startup.
            server = Server.CreateFromConfiguration(serverConfiguration);

            UpsConfiguration upsConfiguration = new UpsConfiguration()
            {
                DeviceName          = upsName,
                MonitorOnly         = monitorOnly,
                NumPowerSupplies    = numPowerSupplies,
                ServerConfiguration = serverConfiguration
            };

            try
            {
                ServerConnection serverConnection = new ServerConnection(server);

                serverConnection.ConnectAsync(CancellationToken.None).Wait();

                Dictionary <string, string> upsVars =
                    serverConnection
                    .ListVarsAsync(upsName, CancellationToken.None).Result;

                Ups ups = Ups.Create(upsName, server, upsVars);

                // Success. Add the configuration and save
                ServiceRuntime.Instance.Configuration.UpsConfigurations.Add(
                    upsConfiguration);

                ServiceRuntime.Instance.SaveConfiguration();

                // Add to the running instances
                UpsContext upsContext = new UpsContext(upsConfiguration, server)
                {
                    State = ups
                };

                ServiceRuntime.Instance.UpsContexts.Add(upsContext);

#pragma warning disable 4014
                Task.Run(() =>
                {
                    foreach (IManagementCallback callbackChannel in
                             ServiceRuntime.Instance.ClientCallbackChannels)
                    {
                        try
                        {
                            callbackChannel.UpsDeviceAdded(ups);
                        }
                        catch (Exception e)
                        {
                            Logger.Error("Caught exception while updating device. " + e.Message);
                            ServiceRuntime.Instance.ClientCallbackChannels.Remove(callbackChannel);
                            break;
                        }
                    }
                });
#pragma warning restore 4014

                return(ups);
            }
            catch (Exception exception)
            {
                Logger.Error("Exception while adding UPS device. {0}", exception.Message);

                if (force)
                {
                    // Add the configuration and save
                    ServiceRuntime.Instance.Configuration.UpsConfigurations.Add(
                        upsConfiguration);

                    ServiceRuntime.Instance.SaveConfiguration();

                    return(null);
                }

                throw;
            }
        }
Ejemplo n.º 18
0
 public void UpsDeviceAdded(Ups ups)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 19
0
 public void UpsDeviceChanged(
     Ups ups,
     MetricMeasurement[] metricMeasurements)
 {
 }
Ejemplo n.º 20
0
Archivo: Ups.cs Proyecto: erynet/IMS
        public static bool AddUps(Ups.Info ups)
        {
            try
            {
                using (var ctx = new LocalDB())
                {
                    UPS newUps = new UPS()
                    {
                        GroupNo = ups.groupNo,
                        No = ups.upsNo,
                        Name = ups.upsName,
                        MateList = ups.partnerNoList.ToString(),
                        CduNo = ups.cduNo,
                        Specification = ups.batteryDescription,
                        Capacity = ups.batteryCapacity,
                        IpAddress = ups.ip,
                        Enabled = ups.isUsing,
                        InstallAt = ups.installDate,
                    };

                    using (var trx = new TransactionScope())
                    {
                        ctx.Ups.Add(newUps);
                        ctx.SaveChanges();
                        trx.Complete();
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"AddUps : {e.ToString()}");
                return false;
            }
        }