예제 #1
0
 public async Task GenerateRandomDirectory()
 {
     try
     {
         DataBaseManager databaseManager = new DataBaseManager();
         Employees = new ObservableCollection <Employee>();
         Random   rdn    = new Random();
         string[] photos =
         {
             //"http://www.femside.com/wp-content/uploads/2013/06/suit-woman.jpg",
             //	"http://previews.123rf.com/images/phakimata/phakimata1103/phakimata110300023/9030612-Experienced-female-business-lawyer-in-suit-Beautiful-Senior-old-woman-with-arms-crossed-isolated--Stock-Photo.jpg",
             //	"https://angrymiddleagewoman.files.wordpress.com/2011/12/woman-in-suit.jpg",
             "http://steezo.com/wp-content/uploads/2012/12/man-in-suit2.jpg",
             "http://attractmen.org/wp-content/uploads/2015/10/attractmen.org-libra-men.jpg",
         };
         ImageClient client = new ImageClient();
         for (int i = 0; i < 16; i++)
         {
             var name        = "Nombre" + i;
             var photo       = photos[rdn.Next(0, 2)];
             var newEmployee = new Employee(
                 name,
                 await client.GetImage(photo),
                 (JobPosition)rdn.Next(0, 4),
                 name + "@mycompany.com"
                 );
             Employees.Add(newEmployee);
             await databaseManager.SaveValueAsync <Employee>(newEmployee);
         }
     }catch (Exception e)
     {
     }
 }
예제 #2
0
        private void MessageCallBack(IAsyncResult Result)
        {
            Tuple <byte[], int, int> RData = (Tuple <byte[], int, int>)Result.AsyncState;

            byte[] SendData    = RData.Item1;
            byte[] SendBytesR  = new byte[SizeForOne + 4];
            int    SendCount   = RData.Item2;
            int    TotalLength = RData.Item3;

            //ChatBox.Items.Add(SendCount.ToString() + ":" + TotalLength.ToString());
            SendCount++;
            if (SendCount * (SizeForOne) > TotalLength)
            {
                return;
            }
            else if ((SendCount + 1) * (SizeForOne) >= TotalLength)
            {
                //ImageClient.BeginSendTo(SendData, SizeForOne * SendCount, TotalLength - (SizeForOne * SendCount), SocketFlags.None, IPBindPoint_ForImage, new AsyncCallback(MessageCallBack), Tuple.Create(SendData, SendCount, TotalLength));
                Client.Send(new byte[4]);
                ImageClient.SendTo(SendData, (SendData.Length / SizeForOne) * SizeForOne, SendData.Length - (SendData.Length / SizeForOne) * SizeForOne, SocketFlags.None, IPBindPoint_ForImage);
            }
            else
            {
                Array.Copy(BitConverter.GetBytes(SendCount), 0, SendBytesR, 0, 4);
                Array.Copy(SendData, SendCount * SizeForOne, SendBytesR, 4, SizeForOne);
                ImageClient.BeginSendTo(SendBytesR, 0, SizeForOne + 4, SocketFlags.None, IPBindPoint_ForImage, new AsyncCallback(MessageCallBack), Tuple.Create(SendData, SendCount, TotalLength));
            }
        }
예제 #3
0
 //- @SaveImage -//
 public static BlogImage GetImage(String blogImageGuid)
 {
     using (ImageClient imageClient = new ImageClient(BlogSection.GetConfigSection().Service.Endpoint.Image))
     {
         imageClient.ClientCredentials.UserName.UserName = BlogSection.GetConfigSection().Service.Authentication.DefaultUserName;
         imageClient.ClientCredentials.UserName.Password = BlogSection.GetConfigSection().Service.Authentication.DefaultPassword;
         //+
         return(imageClient.GetImage(blogImageGuid));
     }
 }
예제 #4
0
 //- @SaveImage -//
 public static BlogImage GetImage(String blogImageGuid)
 {
     using (ImageClient imageClient = new ImageClient(MinimaConfiguration.ActiveImageServiceEndpoint))
     {
         imageClient.ClientCredentials.UserName.UserName = MinimaConfiguration.DefaultServiceUserName;
         imageClient.ClientCredentials.UserName.Password = MinimaConfiguration.DefaultServicePassword;
         //+
         return(imageClient.GetImage(blogImageGuid));
     }
 }
예제 #5
0
        public LKQImageClient()
        {
            VerificationCode = new Guid(ConfigurationManager.AppSettings["Key"]);
            User             = new UserInformation()
            {
                VerificationCode = VerificationCode
            };
            PartnerID   = Convert.ToInt16(ConfigurationManager.AppSettings["ParnerId"]);
            ImageClient = new ImageClient();

            var connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        }
예제 #6
0
        public void SendCapture(Bitmap C_Image, int Pos)
        {
            MemoryStream ms = new MemoryStream();

            C_Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            ms.Position = 0;
            Byte[] SendBytes = new Byte[(int)ms.Length];
            ms.Read(SendBytes, 0, SendBytes.Length);
            ImageClient.Send(BitConverter.GetBytes(SendBytes.Length));
            ImageClient.Send(BitConverter.GetBytes(Pos));
            ImageClient.Send(SendBytes);
        }
예제 #7
0
        public override void Dispose()
        {
            imageClient = null;

            logger.Dispose();
            logger = null;

            utility = null;
            helper  = null;

            hub.Unsubscribe <IInputMessage>(this.IInputMessageProcessor);
        }
예제 #8
0
 public MyDataComunication CloseCommunication()
 {
     IsRecording = false;
     WaveIn.StopRecording();
     WaveOut.Stop();
     Capture.Stop();
     ImageClient.CloseConnection();
     ImageServer.CloseConnection();
     VoiceClient.CloseConnection();
     VoiceServer.CloseConnection();
     return(this);
 }
예제 #9
0
        private void GrabImageAndSend()
        {
            ImageClient.OpenConnection();
            Capture = new VideoCapture();
            var frame = new Mat();

            Capture.ImageGrabbed += (s, ex) =>
            {
                Capture.Read(frame);
                ImageClient.Send(frame.Bitmap);
            };
            Capture.Start();
        }
예제 #10
0
        public ICANSEE() : base("ICANSEEv1")
        {
            imageClient = new ImageClient();

            brokerHubHost = System.Configuration.ConfigurationSettings.AppSettings["ChatInterfaceHost"];
            brokerHubPort = System.Configuration.ConfigurationSettings.AppSettings["ChatInterfacePort"];

            logger  = new ICANSEELogger();
            utility = new ICANSEEUtility(logger, imageClient, brokerHubHost, brokerHubPort);
            helper  = new ICANSEEHelper(logger, utility, imageClient, brokerHubHost, brokerHubPort);

            hub.Subscribe <IInputMessage>(this.IInputMessageProcessor);
        }
예제 #11
0
 private void DisConnectButton_Click(object sender, EventArgs e)
 {
     GetData_From_Client.Abort();
     SendImage_To_Server_Thread.Abort();
     Client.Disconnect(false);
     Client.Shutdown(SocketShutdown.Both);
     Client.Close();
     ImageClient.Disconnect(false);
     ImageClient.Shutdown(SocketShutdown.Both);
     ImageClient.Close();
     SendButton.Enabled       = false;
     DisConnectButton.Enabled = false;
     ConnectButton.Enabled    = true;
     SendImageButton.Enabled  = false;
 }
        public ICANSEEHelper(ICANSEEUtility utility, ImageClient imageClient, string brokerHubHost, string brokerHubPort)
        {
            this.utility       = utility;
            this.imageClient   = imageClient;
            this.brokerHubHost = brokerHubHost;
            this.brokerHubPort = brokerHubPort;

            computeDeviceList = utility.GetComputeDevicesList();

            if (computeDeviceList.Count <= 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("No compute devices available (Check ComputeDeviceConfig file for extensive list)");
                Console.ResetColor();
            }
        }
예제 #13
0
        public void OnlineImage()
        {
            for (int i = 1; i < 4; i++)
            {
                byte[] array = File.ReadAllBytes($"{i}.png");

                var packet = new ImagePacketPb
                {
                    ImageData = ByteString.CopyFrom(array, 0, array.Length),
                };

                var response = ImageClient.Handle(packet);
                Assert.True(response.ErrType == ErrorStatusPb.Types.ErrorStatusEnum.Succeeded, response.Message);

                Thread.Sleep(1000);
            }
        }
예제 #14
0
        static void Main(string[] args)
        {
            ImageRepository poseRepo = new ImageRepository();
            ImageClient     client   = new ImageClient();

            foreach (byte[] data in poseRepo.GetImageData())
            {
                try
                {
                    Task.Run(() => client.PublishImage(data)).Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Message: {0}\nStackTrace: {1}", e.Message, e.StackTrace);
                }
            }
        }
예제 #15
0
        public void UploadImageinformationTest()
        {
            var vehicle = new ImageInformationDto();
            var large   = "https://cvis.iaai.com/thumbnail?imageKeys=18693774~SID~I1";

            vehicle.StockNumber    = "18693774";
            vehicle.FileName       = "18693774_1";
            vehicle.ImageByteArray = new WebClient().DownloadData(large);

            var request = new ImageUploadRequest()
            {
                UserRequestInfo = User, ImageInformation = vehicle
            };
            var uploadStockImage = ImageClient.UploadImageInformation(request);

            Assert.IsTrue(uploadStockImage.WasSuccessful);
        }
예제 #16
0
        public PttViewModel(
            RopuClient ropuClient,
            ISettingsManager settingsManager,
            IGroupsClient groupsClient,
            IUsersClient usersClient,
            ImageClient imageClient,
            IColorService <ColorT> colorService,
            Action <Func <Task> > invoke,
            IPermissionService permissionService,
            RopuWebClient webClient,
            INavigator navigator)
        {
            _navigator  = navigator;
            _ropuClient = ropuClient;
            _webClient  = webClient;

            _ropuClient.StateChanged += (sender, args) =>
            {
                invoke(ChangeState);
            };
            _ropuClient.IdleGroupChanged += async(sender, args) =>
            {
                await UpdateIdleGroup();
                await ChangeState();
            };
            _groupsClient = groupsClient;
            _usersClient  = usersClient;
            _imageClient  = imageClient;

            _settingsManager   = settingsManager;
            _colorService      = colorService;
            _permissionService = permissionService;

            Blue  = _colorService.FromRgb(0x3193e3);
            Green = _colorService.FromRgb(0x31e393);
            Gray  = _colorService.FromRgb(0x999999);
            Red   = _colorService.FromRgb(0xFF6961);

            _pttColor          = Gray;
            _receivingColor    = Red;
            _transmittingColor = Green;

            _state = _ropuClient.State.ToString();
        }
예제 #17
0
        private void SendImageButton_Click(object sender, EventArgs e)
        {
            Bitmap ImageBit = (Bitmap)ImagePictureBox.Image;

            byte[]       ImageByte;
            Image        GetImageBit = ImagePictureBox.Image;
            MemoryStream ms          = new MemoryStream();

            ImageBit.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            //GetImageBit.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            ms.Position = 0;
            ImageByte   = new byte[(int)ms.Length];
            ms.Read(ImageByte, 0, (int)ms.Length);
            int L = (int)ms.Length;

            ChatBox.Items.Add(L.ToString());
            ImageClient.Send(BitConverter.GetBytes(ImageByte.Length), 0, 4, SocketFlags.None);
            ImageClient.Send(ImageByte);
            Thread.Sleep(200);
        }
예제 #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("上传图片");
            var nvc = new NameValueCollection {
                { "deviceId", "2" }
            };
            var result = ImageClient.Upload(@"C:\Users\Administrator\Desktop\公共数据库系统建设\新建文件夹\slide_02.png", new NameValueCollection());

            Console.WriteLine(result);

            Console.WriteLine("写入数据库");
            var entity = new Images
            {
                ImageUrl = result.ImageUrl,
            };
            var providre = new ImageDataRepository();

            providre.Add(entity);

            Console.ReadLine();
        }
예제 #19
0
        public Result AddItemImage(string filePath)
        {
            var ocrText =
                ImageClient.GetImageText(
                    new Entry
            {
                Name     = $"Test_{DateTime.Now.Day}",
                Contents = filePath,
            });

            Console.WriteLine(ocrText);

            var itemName = NormalizeText(ocrText.Text);

            return(this.currentBoard.AddItem(
                       new BoardItem
            {
                Name = itemName,
                Count = 1,
                Image = filePath,
            }));
        }
예제 #20
0
 private void CloseAll(object sender, FormClosingEventArgs e)
 {
     try
     {
         if (Client[0].Connected)
         {
             Client[0].Close();
         }
         if (InputClient.Connected)
         {
             InputClient.Close();
         }
         if (ImageClient.Connected)
         {
             ImageClient.Close();
         }
         ServerOpenThread.Abort();
         ReceiveImageThread.Abort();
     }
     catch (Exception E)
     {
     }
 }
예제 #21
0
 private void CloseAll(object sender, FormClosingEventArgs e)
 {
     try
     {
         if (Client.Connected)
         {
             Client.Close();
         }
         if (ImageClient.Connected)
         {
             ImageClient.Close();
         }
         if (InputClient.Connected)
         {
             InputClient.Close();
         }
         GetData_From_Client.Abort();
         SendImage_To_Server_Thread.Abort();
         GetInput_Thread.Abort();
     }
     catch (Exception E)
     {
     }
 }
예제 #22
0
        public ICANSEEHelper(ICANSEELogger logger, ICANSEEUtility utility, ImageClient imageClient, string brokerHubHost, string brokerHubPort)
        {
            this.logger        = logger;
            this.utility       = utility;
            this.imageClient   = imageClient;
            this.brokerHubHost = brokerHubHost;
            this.brokerHubPort = brokerHubPort;

            computeDeviceList = utility.GetComputeDevicesList();

            if (computeDeviceList.Count <= 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("No compute devices available (Check ComputeDeviceConfig file for extensive list)");
                Console.ResetColor();
            }
            else
            {
                foreach (var computeDevice in computeDeviceList)
                {
                    computeDeviceStateMap[computeDevice] = new Dictionary <int, ComputeDeviceState>();
                }
            }
        }
예제 #23
0
파일: Program.cs 프로젝트: trampster/Ropu
        static void Main(string[] args)
        {
            const ushort controlPortStarting = 5061;

            var settingsManager = new CommandLineClientSettingsReader();

            if (!settingsManager.ParseArgs(args))
            {
                return;
            }

            var settings = settingsManager.ClientSettings;

            var webClient = new RopuWebClient("https://192.168.1.9:5001/", settingsManager);

            var keysClient       = new KeysClient(webClient, false, encryptionKey => new CachedEncryptionKey(encryptionKey, key => new AesGcmWrapper(key)));
            var packetEncryption = new PacketEncryption(keysClient);

            var protocolSwitch    = new ProtocolSwitch(controlPortStarting, new PortFinder(), packetEncryption, keysClient, settings);
            var servingNodeClient = new ServingNodeClient(protocolSwitch);

            IAudioSource audioSource =
                settings.FileMediaSource != null ?
                (IAudioSource) new FileAudioSource(settings.FileMediaSource) :
                (IAudioSource) new PulseAudioSimple(StreamDirection.Record, "RopuInput");

            var audioPlayer            = new PulseAudioSimple(StreamDirection.Playback, "RopuOutput");
            var audioCodec             = new OpusCodec();
            var jitterBuffer           = new AdaptiveJitterBuffer(2, 50);
            var mediaClient            = new MediaClient(protocolSwitch, audioSource, audioPlayer, audioCodec, jitterBuffer, settings);
            var callManagementProtocol = new LoadBalancerProtocol(new PortFinder(), 5079, packetEncryption, keysClient);

            var beepPlayer = new BeepPlayer(new PulseAudioSimple(StreamDirection.Playback, "RopuBeeps"));


            var ropuClient = new RopuClient(protocolSwitch, servingNodeClient, mediaClient, callManagementProtocol, settings, beepPlayer, webClient, keysClient);

            var application = new RopuApplication(ropuClient);

            var imageService = new ImageService();

            //TODO: get web address from config
            var imageClient  = new ImageClient(webClient);
            var groupsClient = new GroupsClient(webClient, imageClient);
            var usersClient  = new UsersClient(webClient);
            //settings.UserId = usersClient.GetCurrentUser().Result.Id;
            var pttPage = new PttPage(imageService);

            var navigator = new Navigator();

            var colorService = new ColorService();

            navigator.Register <LoginViewModel, LoginView>(() => new LoginView(new LoginViewModel(navigator, webClient, settingsManager), imageService));

            navigator.Register <SignupViewModel, SignupPage>(() => new SignupPage(new SignupViewModel(navigator, usersClient), imageService));

            Action <Func <Task> > invoke = toDo => Application.Instance.Invoke(toDo);

            var permissionServices = new PermissionServices();

            var pttView = new PttView(new PttViewModel <Color>(ropuClient, settingsManager, groupsClient, usersClient, imageClient, colorService, invoke, permissionServices, webClient, navigator), pttPage);

            navigator.Register <PttViewModel <Color>, PttView>(() => pttView);
            navigator.RegisterView("HomeRightPanel", "PttView", () => pttView);


            var homeView = new HomeView(new HomeViewModel(navigator), navigator, colorService);

            navigator.Register <HomeViewModel, HomeView>(() => homeView);

            var browseGroupsView = new BrowseGroupsView(new BrowseGroupsViewModel(groupsClient, navigator));

            navigator.Register <BrowseGroupsViewModel, BrowseGroupsView>(() => browseGroupsView);

            Func <Group, BrowseGroupView> browseGroupViewBuilder = group => new BrowseGroupView(new BrowseGroupViewModel(group, groupsClient, settings, navigator), imageService, navigator, colorService);

            navigator.Register <BrowseGroupViewModel, BrowseGroupView, Group>(group => browseGroupViewBuilder(group));

            var selectIdleGroupView = new SelectIdleGroupView(new SelectGroupViewModel(groupsClient, navigator, ropuClient));

            navigator.RegisterView("HomeRightPanel", "SelectIdleGroupView", () => selectIdleGroupView);

            var mainForm = new MainView(navigator, new MainViewModel(settings, navigator));

            mainForm.Icon = imageService.Ropu;

            var ignore = navigator.ShowModal <HomeViewModel>();

            ignore = navigator.ShowPttView();
            application.Run(mainForm);
        }
예제 #24
0
        //run every 10 minutes
        public bool PushImageData()
        {
            bool successWhilePushing = true;

            try
            {
                clsLog.LogInfo("PushImageData - Getting StockImage URLs to push");

                var       connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
                DataTable dt         = new DataTable();

                using (SqlConnection con = new SqlConnection(connection))
                    using (SqlCommand cmd = new SqlCommand("dyndata.dbo.SP_PUSHIMAGEDATA", con))
                    {
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            da.Fill(dt);
                        }
                    }
                var stocks = dt.Rows.OfType <DataRow>().ToList().ConvertAll(c => new Stock()
                {
                    ImageIndex = Convert.ToInt16(c["imageindex"]), ImageURL = c["ImageUrl"].ToString().Trim(), StockNumber = c["stocknumber"].ToString().Trim()
                });
                var stack = new ConcurrentStack <Stock>(stocks);

                clsLog.LogInfo("PushImageData - Got StockImage URLs to push");


                Parallel.ForEach(stack, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 10
                }, p =>
                                 //stocks.ForEach(p =>
                {
                    clsLog.LogInfo("PushImageData - Sending Stock Image URLs " + p.StockNumber);

                    var imageinfo = new ImageInformationDto()
                    {
                        StockNumber    = p.StockNumber,
                        FileName       = p.StockNumber + "_" + p.ImageIndex,
                        ImageByteArray = GetImageBytes(p.ImageURL)
                    };

                    try
                    {
                        var request = new ImageUploadRequest()
                        {
                            UserRequestInfo = User, ImageInformation = imageinfo
                        };
                        var response = ImageClient.UploadImageInformation(request);
                        if (response.WasSuccessful)
                        {
                            clsLog.LogInfo("PushImageData - Sent Stock Image URLs " + p.StockNumber + "_" + p.ImageIndex);
                            p.Pushed = true;

                            File.Delete(p.ImageURL);
                        }
                        else
                        {
                            clsLog.LogInfo("PushImageData - Unable to send Stock Image URLs " + p.StockNumber + "_" + p.ImageIndex);
                        }
                    }
                    catch (Exception ex1)
                    {
                        clsLog.LogError("PushImageData - Error while sending HighRes stock Image urls. Stock" + p.StockNumber + "_" + p.ImageIndex + " Error " + ex1.Message);
                        successWhilePushing = false;
                    }
                });

                using (SqlConnection con = new SqlConnection(connection))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("dyndata.dbo.SP_UpdatePushedStatus", con))
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@stocknumbers", string.Join(",", stack.Where(w => w.Pushed).Select(s => s.StockNumber).ToArray()));
                            cmd.ExecuteNonQuery();
                        }
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                clsLog.LogError("PushImageData - Error while sending HighRes stock Image urls. Error " + ex.Message);
            }

            return(successWhilePushing);
        }
예제 #25
0
        public void ProcessImage()
        {
            var connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;

            DataSet   imageDS = new DataSet("root");
            DataTable imageDT = new DataTable("stock");

            imageDT.Columns.Add("StockNumber", typeof(string));
            imageDT.Columns.Add("ImageIndex", typeof(int));
            imageDT.Columns.Add("ImageUrl", typeof(string));
            imageDS.Tables.Add(imageDT);

            Dictionary <string, int> push = new Dictionary <string, int>();

            try
            {
                clsLog.LogInfo("ProcessImage - Getting stock numbers for downloading");
                var       ds = clsDB.funcExecuteSQLDS("SP_GETSTOCKNUMBER '" + Environment.MachineName + "'", connection, 300);
                DataTable dt = ds.Tables[0];
                clsLog.LogInfo("ProcessImage - Got stock numbers for downloading");

                dt.Rows.OfType <DataRow>().ToList().ForEach(p =>
                {
                    var imageUrls = GetImage(p["StockNumber"].ToString());
                    clsLog.LogInfo("ProcessImage - Got Image URLs for Stock " + p["StockNumber"].ToString());


                    //if (imageUrls[0] == "Specialty" || imageUrls[0] == "Offsite")
                    //    clsDB.funcExecuteSQL(string.Format("SP_UpdateStockImages @xml='{0}',@stockstatus=3", imageDS.GetXml()), connection);
                    //else if (string.IsNullOrEmpty(imageUrls[0]))
                    //    clsDB.funcExecuteSQL(string.Format("SP_UpdateStockImages @xml='{0}',@stockstatus=2", imageDS.GetXml()), connection);
                    //else
                    //{
                    //    imageDT.Rows.Clear();
                    for (int i = 0; i < 10; i++)
                    {
                        imageDT.Rows.Add(imageDT.NewRow());
                        imageDT.Rows[imageDT.Rows.Count - 1]["StockNumber"] = p["StockNumber"].ToString();
                        imageDT.Rows[imageDT.Rows.Count - 1]["ImageIndex"]  = i;
                        imageDT.Rows[imageDT.Rows.Count - 1]["ImageUrl"]    = imageUrls[i];
                    }
                    //clsDB.funcExecuteSQL(string.Format("SP_UpdateStockImages @xml='{0}'", imageDS.GetXml()), connection);
                    //}
                    clsLog.LogInfo("ProcessImage - HighRes Image URLs saved");


                    clsLog.LogInfo("ProcessImage - Sending Stock Image URLs " + p["StockNumber"].ToString());

                    var pushedSuccessful = true;
                    if (imageUrls[0] == "Specialty" || imageUrls[0] == "Offsite")
                    {
                        push.Add(p["StockNumber"].ToString(), 3);
                    }
                    else if (string.IsNullOrEmpty(imageUrls[0]))
                    {
                        push.Add(p["StockNumber"].ToString(), 2);
                    }
                    else
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            var imageinfo = new ImageInformationDto()
                            {
                                StockNumber    = p["StockNumber"].ToString(),
                                FileName       = p["StockNumber"].ToString() + "_" + i,
                                ImageByteArray = GetImageBytes(imageUrls[i])
                            };

                            clsLog.LogInfo("ProcessImage - Sending Stock Image URLs " + p["StockNumber"].ToString() + " Index " + i);
                            var request = new ImageUploadRequest()
                            {
                                UserRequestInfo = User, ImageInformation = imageinfo
                            };
                            var response = ImageClient.UploadImageInformation(request);
                            if (response.WasSuccessful)
                            {
                                clsLog.LogInfo("ProcessImage - Sent Stock Image URLs " + p["StockNumber"] + "_" + i);

                                File.Delete(imageUrls[i]);
                            }
                            else
                            {
                                pushedSuccessful = false;
                                clsLog.LogError("ProcessImage - Unable to send Stock Image URLs " + p["StockNumber"] + "_" + i);
                            }
                        }

                        if (!push.Keys.ToList().Exists(e => p["StockNumber"].ToString() == e))
                        {
                            push.Add(p["StockNumber"].ToString(), pushedSuccessful ? 1 : 5);
                        }
                    }

                    //clsDB.funcExecuteSQL(string.Format("SP_UpdatePushedStatus @stocknumbers='{0}', @status='{1}'", p["StockNumber"].ToString(), pushedSuccessful ? 1 : 5), connection);
                });



                //-------------------------------------
                clsDB.funcExecuteSQL(string.Format("SP_UpdateStockImages @xml='{0}'", imageDS.GetXml()), connection);
                clsDB.funcExecuteSQL(string.Format("SP_UpdatePushedStatus @stocknumbers='{0}', @status='{1}'", string.Join(",", push.Keys), string.Join(",", push.Values)), connection);
            }
            catch (Exception ex)
            {
                clsLog.LogError("ProcessImage - Error while executing. " + ex.Message);
            }
        }
예제 #26
0
        public void SendCaptureImageMethod()
        {
            MemoryStream ms = new MemoryStream();
            Bitmap       OrgImage;

            try
            {
                Bitmap C_Image   = CaptureImage(1920, 1080, 800, 700);
                Byte[] SendBytes = new Byte[(int)ms.Length];
                Byte[] SendBytesR;
                byte[] testbytes = new byte[15];
                int    width, height;
                width    = Screen.PrimaryScreen.Bounds.Width;
                height   = Screen.PrimaryScreen.Bounds.Height;
                OrgImage = C_Image;
                Client.Send(BitConverter.GetBytes(Screen.PrimaryScreen.Bounds.Width));
                Client.Send(BitConverter.GetBytes(Screen.PrimaryScreen.Bounds.Height));
                do
                {
                    ms      = new MemoryStream();
                    C_Image = CaptureImage(width, height, width, height);
                    C_Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //CheckChange(C_Image,OrgImage);
                    var CompressedStream = new MemoryStream();
                    //var CompressStream = new DeflateStream(CompressedStream, CompressionMode.Compress,true);
                    var CompressStream = new GZipStream(CompressedStream, CompressionMode.Compress, true);
                    //ms = new MemoryStream();
                    ms.Position = 0;
                    Client.Send(BitConverter.GetBytes((int)ms.Length));
                    ms.CopyTo(CompressStream);
                    CompressStream.Close();
                    SendBytes = new byte[(int)CompressedStream.Length];
                    //SendBytes = new byte[3004];
                    CompressedStream.Position = 0;
                    CompressedStream.Read(SendBytes, 0, SendBytes.Length);
                    ChatBox.Items.Add(ms.Length + " : " + CompressedStream.Length);
                    CompressedStream.Position = 0;
                    Client.Send(BitConverter.
                                GetBytes(SendBytes.Length));
                    ms.Close();
                    CompressedStream.Close();
                    sw = false;
                    int count = 0;
                    do
                    {
                        SendBytesR = new Byte[SizeForOne + 4];
                        Client.Receive(new byte[4]);
                        Thread.Sleep(50);
                        for (int i = 0; i < SendBytes.Length / SizeForOne; i++)
                        {
                            Array.Copy(BitConverter.GetBytes(i), 0, SendBytesR, 0, 4);
                            Array.Copy(SendBytes, i * SizeForOne, SendBytesR, 4, SizeForOne);
                            //SendBytes.CopyTo(SendBytesR, 4);
                            //ImageClient.SendTo(SendBytes, i * SizeForOne, SizeForOne, SocketFlags.None, IPBindPoint_ForImage);
                            ImageClient.SendTo(SendBytesR, 0, SizeForOne + 4, SocketFlags.None, IPBindPoint_ForImage);
                            //ChatBox.Items.Add(ImageClient.ReceiveBufferSize);
                            Thread.Sleep(25);
                            //ImageClient.BeginSendTo(SendBytesR, 0, SizeForOne + 4, SocketFlags.None, IPBindPoint_ForImage,new AsyncCallback(MessageCallBack),Tuple.Create(SendBytes,count,(int)ms.Length));
                            //if((i+1)%5==0) Thread.Sleep(30);
                            //ChatBox.Items.Add(i + "번째");
                        }
                        Client.Send(new byte[4]);
                        //Thread.Sleep(10);
                        if (SendBytes.Length % SizeForOne != 0)
                        {
                            ImageClient.SendTo(SendBytes, (SendBytes.Length / SizeForOne) * SizeForOne, SendBytes.Length - (SendBytes.Length / SizeForOne) * SizeForOne, SocketFlags.None, IPBindPoint_ForImage);
                        }
                        Client.Receive(testbytes, 0, 4, SocketFlags.None);
                        count = BitConverter.ToInt32(testbytes, 0);
                    } while (count != -1);
                    GC.Collect(0);
                    GC.Collect(1);
                    ms.Close();
                    SendBytes  = null;
                    SendBytesR = null;
                    Client.Receive(testbytes, 0, 4, SocketFlags.None);
                } while (Client.Connected);
            }
            catch (OverflowException Ex)
            {
                ChatBox.Items.Add(Ex.ToString());
            }
        }
예제 #27
0
        public void LoginService(string ip, string port)
        {
            _imageClient = new ImageClient(ip, port);

            _systemClient = new SystemClient(ip, port);
        }
예제 #28
0
        public void Handle(IStateMachine <string, INetworkGameScreen> machine)
        {
            machine.SharedContext.Messages.Add(nameof(UpdateInventoryImagesState));


            if (machine.SharedContext.LastMetadataBag == null)
            {
                machine.SharedContext.Messages.Add("last meta data bag is not available");
                return;
            }

            if (machine.SharedContext.LastMetadataBag.Items == null)
            {
                machine.SharedContext.Messages.Add("last meta data bag items is not available");
                return;
            }

            // if(!machine.SharedContext.LastMetadataBag.Items.Any())
            // {
            //     machine.SharedContext.Messages.Add("last meta data bag has no items");
            //     return;
            // }

            if (machine.SharedContext.LastMetadataBag.Items.Count > 0)
            {
                //udpate old images
                var newImgs    = new List <ImageData>();
                var itemImages = machine.SharedContext.LastMetadataBag.Items.OrderByDescending(itm => itm.Order).Select(itm => itm.CurrentImage);
                if (machine.SharedContext.LastMetadataBag.Items.Count == 0)
                {
                    foreach (var imageToDispose in machine.SharedContext.InventoryImages)
                    {
                        machine.SharedContext.Messages.Add(imageToDispose.ServerData.Id);
                        imageToDispose.UnloadContent();
                    }
                    machine.SharedContext.InventoryImages.Clear();
                    return;
                }

                foreach (var newImg in itemImages)
                {
                    var foundOldImg = machine.SharedContext.InventoryImages.FirstOrDefault(oldImg => oldImg.ServerData.Id == newImg.Id);
                    if (foundOldImg == default(ImageClient))
                    {
                        //no registered img in old
                        var newImageClient = new ImageClient(newImg, machine.SharedContext.GameSheet.Frames);
                        newImageClient.LoadContent(ScreenService.Instance.Content);
                        machine.SharedContext.InventoryImages.Add(newImageClient);
                    }
                    else
                    {
                        foundOldImg.ApplyImageData(newImg);
                    }
                }
                var newImgBundle = machine.SharedContext.InventoryImages.Where(img => itemImages.Any(gImg => gImg.Id == img.ServerData.Id)).ToList();

                // //clean up old inventory images
                var imagesToDispose = machine.SharedContext.InventoryImages.Except(newImgBundle);
                foreach (var imageToDispose in imagesToDispose)
                {
                    machine.SharedContext.Messages.Add(imageToDispose.ServerData.Id);
                    imageToDispose.UnloadContent();
                }

                machine.SharedContext.InventoryImages.AddRange(imagesToDispose.Where(img => !img.Disposed));
                TransformToGrid(machine);
            }
        }
예제 #29
0
        public static void Main(string[] args)
        {
            ConsoleLogger.Init("Kotori", args.Contains("rawlogs"));
            Logger.OnAdd += (e) => ConsoleLogger.WriteLine(e);
            Logger log = new Logger("Kotori");

            log.Add($"Kotori version {Version.Major}.{Version.Minor}", LogLevel.Info);

            using (ConfigManager config = new ConfigManager("Kotori.ini"))
            {
                Logger.Verbose = config.Get("Kotori", "VerboseLogging", false);

                log.Add($"Build date: {BuildDate}");

                string consumerKey    = config.Get("Bot", "ConsumerKey", string.Empty);
                string consumerSecret = config.Get("Bot", "ConsumerSecret", string.Empty);

                if (string.IsNullOrEmpty(consumerKey) ||
                    string.IsNullOrEmpty(consumerSecret))
                {
                    log.Add("Looks like you're running the bot for the first time!", LogLevel.Important);
                    log.Add("Please go to https://apps.twitter.com/ and create a new app with Write permissions.", LogLevel.Info);
                    log.Add("You can paste in the Windows Console by right clicking on the top-left icon", LogLevel.Info);
                    log.Add(" and then going to the Edit submenu.", LogLevel.Info);
                    log.Add("After you did that go to the Keys and Access Tokens tab and enter the following values here:", LogLevel.Info);

                    log.Add("Consumer Key (API Key):", LogLevel.Info);
                    consumerKey = Console.ReadLine();
                    config.Set("Bot", "ConsumerKey", consumerKey);

                    log.Add("Consumer Secret (API Secret):", LogLevel.Info);
                    consumerSecret = Console.ReadLine();
                    config.Set("Bot", "ConsumerSecret", consumerSecret);

                    config.Save();
                }

                using (ManualResetEvent mre = new ManualResetEvent(false))
                {
                    Console.CancelKeyPress += (s, e) =>
                    {
                        e.Cancel = true;
                        mre.Set();
                    };

                    log.Add("Creating Image Clients...");
                    ImageClient[] clients = Assembly.GetExecutingAssembly()
                                            .GetTypes()
                                            .Where(x => x.GetCustomAttributes(typeof(ImageClientAttribute), false).Length > 0)
                                            .ToList()
                                            .Select(x => {
                        ImageClient client = Activator.CreateInstance(x) as ImageClient;
                        log.Add($"Created Image Client '{x.Name}'");
                        return(client);
                    })
                                            .ToArray();

                    string rawActiveBots = config.Get("Bot", "Active", string.Empty);

                    if (string.IsNullOrEmpty(rawActiveBots))
                    {
                        log.Add("You haven't configured any bot accounts yet!", LogLevel.Important);

                        log.Add("Enter a name without spaces or other special characters for the bot, this is not used anywhere on Twitter and is only used for local storage:", LogLevel.Info);
                        rawActiveBots = Console.ReadLine().Trim();
                        config.Set("Bot", "Active", rawActiveBots);

                        log.Add("Next you'll specify the tags the bot should look for on the image sources, you can leave them empty if you want it to skip that source.", LogLevel.Info);

                        foreach (ImageClient ic in clients)
                        {
                            log.Add($"Specify search tags for {ic.Name}:", LogLevel.Info);
                            string tags = Console.ReadLine().Trim();
                            config.Set($"Bot.{rawActiveBots}.Source.{ic.Name}", "Tags", tags);
                        }

                        config.Save();
                    }

                    string[] botKeys = rawActiveBots.Split(' ');
                    Bot[]    bots    = new Bot[botKeys.Length];

                    if (botKeys.Length < 1)
                    {
                        log.Add("No bots have been configured!", LogLevel.Error);
                        return;
                    }

                    for (int i = 0; i < bots.Length; i++)
                    {
                        bots[i] = new Bot(botKeys[i].Trim(), clients, config);
                        log.Add($"Created Bot '{bots[i].Name}'");
                        bots[i].Start();
                    }

                    mre.WaitOne();
                    log.Add("Stopping...", LogLevel.Info);

                    log.Add("Disposing bots...");
                    foreach (Bot bot in bots)
                    {
                        bot.Dispose();
                    }
                }
            }
        }
예제 #30
0
        public void should_call_imageUploader_to_upload_image()
        {
            var nvc = new NameValueCollection();

            ImageClient.Upload(TestConstants.TestFileName, nvc);
        }