public async Task <IGetLabelResponse> GetLabelAsync(ILabelConfiguration labelConfiguration, string zpl)
        {
            GetLabelResponse returnValue = new();

            try
            {
                using (HttpClient client = new())
                {
                    using (StringContent content = new(zpl, Encoding.UTF8, "application/x-www-form-urlencoded"))
                    {
                        double width  = (new Length(labelConfiguration.LabelWidth, labelConfiguration.Unit)).ToUnit(UnitsNet.Units.LengthUnit.Inch).Value;
                        double height = (new Length(labelConfiguration.LabelHeight, labelConfiguration.Unit)).ToUnit(UnitsNet.Units.LengthUnit.Inch).Value;

                        if (width <= 15 && height <= 15)
                        {
                            string url = $"{BaseUrl}/{labelConfiguration.Dpmm}dpmm/labels/{width:#.##}x{height:#.##}/0/";
                            using (HttpResponseMessage response = await client.PostAsync(url, content))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    returnValue.Result = true;
                                    returnValue.Label  = await response.Content.ReadAsByteArrayAsync();

                                    returnValue.Error = null;
                                }
                                else
                                {
                                    string error = await response.Content.ReadAsStringAsync();

                                    returnValue.Result = false;
                                    returnValue.Label  = this.CreateErrorImage(labelConfiguration, "Labelary Error", error ?? response.ReasonPhrase);
                                    returnValue.Error  = error ?? response.ReasonPhrase;
                                }
                            }
                        }
                        else
                        {
                            string message = "Height and Width must be less than or equal to 15 inches.";
                            returnValue.Result = false;
                            returnValue.Label  = this.CreateErrorImage(labelConfiguration, "Invalid Size", message);
                            returnValue.Error  = message;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                returnValue.Result = false;
                returnValue.Label  = this.CreateErrorImage(labelConfiguration, "Exception", ex.Message);
                returnValue.Error  = ex.Message;
            }

            return(returnValue);
        }
Exemple #2
0
        public async Task StartSessionAsync(TcpClient client, ILabelConfiguration labelConfiguration, string imagePathRoot)
        {
            //
            // Set parameters.
            //
            client.ReceiveTimeout    = 1000;
            client.SendTimeout       = 1000;
            client.LingerState       = new LingerOption(false, 0);
            client.NoDelay           = true;
            client.ReceiveBufferSize = 8192;
            client.SendBufferSize    = 8192;

            //
            // Get the network stream.
            //
            NetworkStream stream = client.GetStream();

            while (client.Connected && stream.CanRead)
            {
                if (stream.DataAvailable)
                {
                    try
                    {
                        //
                        // Create a buffer for the data that is available.
                        //
                        byte[] buffer = new byte[client.Available];

                        //
                        // Read the data into the buffer.
                        //
                        int bytesRead = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length));

                        if (bytesRead > 0)
                        {
                            //
                            // Get the label image
                            //
                            string zpl = Encoding.UTF8.GetString(buffer);

                            if (zpl != "NOP")
                            {
                                IGetLabelResponse response = await this.LabelService.GetLabelAsync(labelConfiguration, zpl);

                                //
                                // Save the image.
                                //
                                IStoredImage storedImage = await this.ImageCacheRepository.StoreImageAsync(imagePathRoot, response.Label);

                                //
                                // Publish the new label.
                                //
                                this.EventAggregator.GetEvent <LabelCreatedEvent>().Publish(new LabelCreatedEventArgs()
                                {
                                    PrintRequest = new PrintRequestEventArgs()
                                    {
                                        LabelConfiguration = labelConfiguration,
                                        Zpl = zpl
                                    },
                                    Label   = storedImage,
                                    Result  = response.Result,
                                    Message = response.Result ? "Label successfully created." : response.Error
                                });
                            }
                        }
                    }
                    finally
                    {
                        client.Close();
                    }
                }
            }
        }
        protected byte[] CreateErrorImage(ILabelConfiguration labelConfiguration, string title, string error)
        {
            byte[] returnValue = null;

            //
            // Get the label size in mm
            //
            double labelWidthMm  = (new Length(labelConfiguration.LabelWidth, labelConfiguration.Unit)).ToUnit(UnitsNet.Units.LengthUnit.Millimeter).Value;
            double labelHeightMm = (new Length(labelConfiguration.LabelHeight, labelConfiguration.Unit)).ToUnit(UnitsNet.Units.LengthUnit.Millimeter).Value;

            //
            // Get the size in pixels
            //
            int width  = (int)(labelWidthMm * labelConfiguration.Dpmm);
            int height = (int)(labelHeightMm * labelConfiguration.Dpmm);

            const int TOP_HEIGHT = 145;
            const int MARGIN     = 10;
            const int BORDER     = 20;
            const int IMAGE      = 128;

            //
            // Create an image.
            //
            using (Bitmap bmp = new(width, height))
            {
                Rectangle rect = new(0, 0, width, height);

                using (Graphics graphics = Graphics.FromImage(bmp))
                {
                    Pen linePen = new Pen(new SolidBrush(Color.FromArgb(58, 97, 132)));
                    graphics.FillRectangle(SystemBrushes.Window, rect);

                    //
                    // Draw the label border.
                    //
                    graphics.DrawRectangle(linePen, BORDER, BORDER, width - (2 * BORDER), height - (2 * BORDER));

                    //
                    // Draw the image
                    //
                    Rectangle imageRect = new(BORDER, BORDER, IMAGE, IMAGE);
                    graphics.DrawImage(Image.FromFile("./Assets/label.png"), imageRect);

                    //
                    // Draw the title.
                    //
                    Rectangle titleLayout = new()
                    {
                        X      = BORDER + IMAGE + MARGIN,
                        Y      = BORDER,
                        Width  = width - IMAGE - (2 * BORDER) - MARGIN,
                        Height = TOP_HEIGHT
                    };

                    using (Font font = new("Arial", 16, FontStyle.Bold))
                    {
                        StringFormat stringFormat = new()
                        {
                            Alignment     = StringAlignment.Near,
                            LineAlignment = StringAlignment.Center
                        };

                        graphics.DrawString(title, font, new SolidBrush(Color.FromArgb(58, 97, 132)), titleLayout, stringFormat);
                    }

                    //
                    // Draw the dividing line.
                    //
                    graphics.DrawLine(linePen, BORDER, titleLayout.Bottom, width - (1 * BORDER), titleLayout.Bottom);

                    //
                    // Draw the error text.
                    //
                    Rectangle bodyLayout = new()
                    {
                        X      = BORDER + MARGIN,
                        Y      = titleLayout.Bottom + MARGIN,
                        Width  = width - (2 * BORDER) - (2 * MARGIN),
                        Height = height - titleLayout.Bottom - BORDER - (2 * MARGIN)
                    };

                    using (Font font = new("Arial", 14))
                    {
                        StringFormat stringFormat = new()
                        {
                            Alignment = StringAlignment.Near,
                        };

                        graphics.DrawString(error, font, new SolidBrush(Color.FromArgb(75, 75, 75)), bodyLayout, stringFormat);
                    }

                    graphics.Flush();
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    bmp.Save(stream, ImageFormat.Png);
                    returnValue = stream.ToArray();
                }
            }

            return(returnValue);
        }
    }
}