예제 #1
0
        /// <summary>
        /// Returns true if the data field (list) has at least some elements.
        /// </summary>
        /// <param name="value">The value of the object to validate.</param>
        /// <returns>
        /// true if the data field (list) has at least some elements; otherwise, false.
        /// </returns>
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return(AllowNull);
            }
            Preconditions.Check <ValidationException>(value is IEnumerable, $"The property should be a IEnumerable data.");

            var count = 0;

            if (value is ICollection)
            {
                count = (value as ICollection).Count;
            }
            else if (value is ICollection <object> )
            {
                count = (value as ICollection <object>).Count;
            }
            else
            {
                var enumerator = (value as IEnumerable).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    count++;
                }
            }
            return(count >= MinElementsCount);
        }
예제 #2
0
        /// <summary>
        /// 如果已经知道一个设备,则更新已有设备的信息。如果是一个新设备,把它添加到列表中。
        ///
        /// 改这个要慎重,它被LANDiscoverer调用,还被Device的Connect调用。
        /// </summary>
        /// <param name="device"></param>
        /// <param name="needMerge"></param>
        /// <returns></returns>

        public Device AddOrUpdateDevice(Device device, bool needMerge = true)
        {
            //检查这个Device是否已知。
            lock (locker)
            {
                Preconditions.Check(device != null && !string.IsNullOrEmpty(device.ID));
                if (device.ID == LocalDevice.ID)
                {
                    return(null);
                }

                var existingDevice = Devices.FirstOrDefault(o => o.ID == device.ID);
                if (existingDevice == null)
                {
                    Devices.Add(device);
                    device.IsFirstSeen = true;
                    _deviceDiscovered?.Invoke(device);
                }
                else
                {
                    if (needMerge)
                    {
                        //如果这个设备原来已经存在了,那么其实应该返回原来的设备,只是需要将新发现的不同的地方复制到原来的设备上
                        //各事件都是绑定到原来的设备的。
                        existingDevice.CopyFrom(device);
                    }
                    //不管是否Merge,都要修改IP。
                    existingDevice.DefaultIP = device.DefaultIP;
                    device             = existingDevice;
                    device.IsFirstSeen = false;
                }
                device.LastUpdateTime = Environment.TickCount;
                return(device);
            }
        }
예제 #3
0
        /// <summary>
        /// Shows the save file dialog box that allows a user to specify a filename to save a file as.
        /// </summary>
        /// <param name="owner">The window that owns this SaveFileDialog.</param>
        /// <param name="fileTypes">The supported file types.</param>
        /// <param name="defaultFileType">Default file type.</param>
        /// <param name="defaultFileName">Default filename. The directory name is used as initial directory when it is specified.</param>
        /// <returns>A FileDialogResult object which contains the filename entered by the user.</returns>
        /// <exception cref="System.ArgumentNullException">fileTypes must not be null.</exception>
        /// <exception cref="System.ArgumentException">fileTypes must contain at least one item.</exception>
        public FileDialogResult ShowSaveFileDialog(object owner, IEnumerable <FileType> fileTypes, FileType defaultFileType, string defaultFileName)
        {
            Preconditions.NotNull(fileTypes);
            Preconditions.Check(() => fileTypes.Any(), "The fileTypes collection must contain at least one item.");

            SaveFileDialog dialog = new SaveFileDialog();

            return(ShowFileDialog(owner, dialog, fileTypes, defaultFileType, defaultFileName));
        }
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileType"/> class.
        /// </summary>
        /// <param name="description">The description of the file type.</param>
        /// <param name="fileExtension">The file extension. This string has to start with a '.' point.</param>
        /// <exception cref="System.ArgumentException">description is null or an empty string.</exception>
        /// <exception cref="System.ArgumentException">fileExtension is null, an empty string or doesn't start with a '.' point character.</exception>
        public FileType(string description, string fileExtension)
        {
            Preconditions.NotNullOrWhiteSpace(description, "The argument description must not be null or empty.");
            Preconditions.NotNullOrWhiteSpace(fileExtension, "The argument fileExtension must not be null or empty.");
            Preconditions.Check(() => fileExtension[0] == '.', "The argument fileExtension must start with the '.' character.");

            this.description   = description;
            this.fileExtension = fileExtension;
        }
예제 #5
0
        public Task Compress(string sourceFile, string targetFile, bool viewFinalOutput, Progress <IProgressReport> progress)
        {
            Preconditions.NotNullOrWhiteSpace(sourceFile, nameof(sourceFile));
            Preconditions.Check(File.Exists(sourceFile), "Source should be an existed file.");
            Preconditions.Check(sourceFile.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase), "Source should be a file with pdf as extension.");

            return(Task.Factory.StartNew(() =>
            {
                Trace.Indent();
                Trace.TraceInformation($"Process the parameters target: {targetFile}.");
                if (string.IsNullOrWhiteSpace(targetFile))
                {
                    targetFile = "Merge_File.pdf";
                }
                if (!targetFile.EndsWith(".pdf"))
                {
                    targetFile += ".pdf";
                }
                Trace.TraceInformation($"Target hand been process to {targetFile}.");

                // Open the file
                PdfDocument inputDocument = PdfReader.Open(sourceFile, PdfDocumentOpenMode.Import);

                // Create new document
                PdfDocument outputDocument = new PdfDocument();
                outputDocument.Version = inputDocument.Version;
                outputDocument.Info.Title = inputDocument.Info.Title;
                outputDocument.Info.Creator = inputDocument.Info.Creator;
                outputDocument.Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
                outputDocument.Options.UseFlateDecoderForJpegImages = PdfUseFlateDecoderForJpegImages.Automatic;
                outputDocument.Options.NoCompression = false;
                outputDocument.Options.CompressContentStreams = true;

                Console.WriteLine($"Start compress the file. Total page number: {inputDocument.PageCount}.");
                for (int idx = 0; idx < inputDocument.PageCount; idx++)
                {
                    ReportProgress(progress, new ProgressReport(idx, inputDocument.PageCount));

                    // Add the page and save it
                    outputDocument.AddPage(inputDocument.Pages[idx]);
                }
                ReportProgress(progress, new ProgressReport(inputDocument.PageCount, inputDocument.PageCount));

                // Save the document
                Trace.TraceInformation($"Save the output file {targetFile}.");
                outputDocument.Save(targetFile);

                if (viewFinalOutput)   // start a viewer.
                {
                    Console.WriteLine($"Show the merged file {targetFile}.");
                    Process.Start(targetFile);
                }

                Trace.Unindent();
            }));
        }
예제 #6
0
        private CompareItem CompareWithAnother(Property property1, Property property2)
        {
            Preconditions.NotNull(property1, "property1");
            Preconditions.NotNull(property2, "property2");
            Preconditions.Check <NotSupportedException>(property1.Name.Equals(property2.Name, StringComparison.InvariantCulture), "Should not compare to property with different name.");

            return(CompareItem.WithBothData(property1.Name,
                                            property1.Select(item => FieldToCompare(item.Value)).ToList(),
                                            property2.Select(item => FieldToCompare(item.Value)).ToList()));
        }
        internal LANDiscoverer(Device localInfo, int port = DefaultBroadCastPort)
        {
            Preconditions.Check(localInfo != null);
            Preconditions.Check <ArgumentException>(port > -1);

            this.localInfo = localInfo;
            BroadcastPort  = port;
            udp            = UDP.Prepare(DefaultBroadcastAddress, port);
            //udp.OnPacketReceived += OnPacketReceived;
        }
예제 #8
0
        public Task ConvertImage(string sourceFile, string targetFile, bool landscape, bool usLetter, bool viewFinalOutput, Progress <IProgressReport> progress)
        {
            Preconditions.NotNullOrWhiteSpace(sourceFile, nameof(sourceFile));
            Preconditions.Check(File.Exists(sourceFile), "Source should be an existed file.");
            Preconditions.Check(sourceFile.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase), "Source should be a file with jpg as extension.");

            return(Task.Factory.StartNew(() =>
            {
                Trace.Indent();
                Trace.TraceInformation($"Process the parameters target: {targetFile}.");
                if (string.IsNullOrWhiteSpace(targetFile))
                {
                    targetFile = Path.GetFileNameWithoutExtension(sourceFile);
                }
                if (!targetFile.EndsWith(".pdf"))
                {
                    targetFile += ".pdf";
                }
                Trace.TraceInformation($"Target hand been process to {targetFile}.");

                PdfDocument document = new PdfDocument();
                PdfPage page = document.AddPage();
                if (landscape)
                {
                    page.Orientation = PageOrientation.Landscape;
                }
                else
                {
                    page.Orientation = PageOrientation.Portrait;
                }
                if (usLetter)
                {
                    page.Size = PageSize.Letter;
                }
                else
                {
                    page.Size = PageSize.A4;
                }

                Console.WriteLine($"Start convert image to pdf.");
                XGraphics gfx = XGraphics.FromPdfPage(page, XPageDirection.Downwards);
                gfx.DrawImage(XImage.FromFile(sourceFile), 0, 0);

                Trace.TraceInformation($"Save the output file {targetFile}.");
                document.Save(targetFile);

                if (viewFinalOutput)   // start a viewer.
                {
                    Console.WriteLine($"Show the merged file {targetFile}.");
                    Process.Start(targetFile);
                }

                Trace.Unindent();
            }));
        }
예제 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProgressReport" /> class.
        /// </summary>
        /// <param name="current">The current progress.</param>
        /// <param name="total">The total amount.</param>
        /// <param name="message">The message.</param>
        public ProgressReport(int current, int total, string message)
        {
            Preconditions.Check(current >= 0, "Parameter '{0}' in {1} should not less than 0", "current");
            Preconditions.Check(total >= 0, "Parameter '{0}' in {1} should not less than 0", "total");
            Preconditions.Check(total >= current, "Parameter '{0}' should not larger than total", "current");
            Preconditions.NotNull(message, "message");

            Current = current;
            Total   = total;
            Message = message;
        }
예제 #10
0
 public void Message()
 {
     try
     {
         Preconditions.Check <NotSupportedException>(!string.IsNullOrWhiteSpace(null), "Parameter '{0}' in '{1}' should not be empty string.", "param");
     }
     catch (NotSupportedException ex)
     {
         Assert.IsTrue(ex.Message.Contains("'param'"));
         Assert.IsTrue(ex.Message.Contains("'Message'"));
     }
 }
예제 #11
0
        //必须设置LocalDevice之后才能运行
        public void Start()
        {
            Preconditions.Check(LocalDevice != null, "Local Device Must be set before start");
            if (isRunning)
            {
                return;            //TODO 是否需要同步锁定?有没有别的实现?
            }
            isRunning = true;

            Discoverer.StartBroadcast();
            Discoverer.StartListen();
            ChannelManager.Start();
        }
 //是不是这个构造函数要允许ISendable进来?
 internal ListSequencable(string conversationID, List <Item> items)
 {
     Preconditions.Check(items != null);
     StopWhenSubItemError = true;
     ConversationID       = conversationID;
     items.Sort(SendableComparer <Item> .Instance);
     //注意,这里不要做深拷贝。
     this.items = items;
     items.ForEach((item) => {
         item.Parent = this;
         Length     += item.Length;
     });
 }
예제 #13
0
        /// <summary>
        /// Compares JSON files in 2 folder and output the result.
        /// </summary>
        /// <param name="path1">The directory path of JSON files.</param>
        /// <param name="path2">The another directory path of JSON files.</param>
        /// <param name="configFile">The configuration file.</param>
        /// <param name="progress">The progress update provider.</param>
        /// <returns>All compare result</returns>
        public async Task <IList <CompareFile> > Compare(string path1, string path2, string configFile, IProgress <IProgressReport> progress = null)
        {
            Preconditions.NotNullOrWhiteSpace(path1, "path1");
            Preconditions.NotNullOrWhiteSpace(path2, "path2");
            Preconditions.NotNullOrWhiteSpace(configFile, "configFile");
            Preconditions.Check(!path1.Equals(path2, StringComparison.OrdinalIgnoreCase), "Path1 should not be same as Path2");

            Trace.Indent();
            Trace.TraceInformation($"Start Read the Compare Config File: {configFile}.");
            var config = configDocumentType.Read(configFile);

            Trace.TraceInformation($"Start Compare the folder {path1} with folder {path2}.");
            var filesFromPath1 = Directory.EnumerateFiles(path1).Where(path => Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase)).ToList();

            Trace.TraceInformation($"Have {filesFromPath1.Count} files from {path1}.");
            var filesFromPath2 = Directory.EnumerateFiles(path2).Where(path => Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase)).ToList();

            Trace.TraceInformation($"Have {filesFromPath2.Count} files from {path2}.");

            var fileNames = filesFromPath1.Select(path => Path.GetFileName(path))
                            .Concat(filesFromPath2.Select(path => Path.GetFileName(path)))
                            .Distinct().ToList();;

            Console.WriteLine($"Start Compare the Files. Total Number: {fileNames.Count}.");
            var result = new List <CompareFile>(fileNames.Count);

            foreach (var fileName in fileNames)
            {
                reportProgress(progress, new ProgressReport(result.Count, fileNames.Count));

                JsonDocument file1, file2;

                try
                {
                    file1 = await readFileService.GetJsonDocument(Path.Combine(path1, fileName), config);
                }
                catch { file1 = null; }
                try
                {
                    file2 = await readFileService.GetJsonDocument(Path.Combine(path2, fileName), config);
                }
                catch { file2 = null; }

                result.Add(await analyzeService.Compare(file1, file2));
            }
            reportProgress(progress, new ProgressReport(fileNames.Count, fileNames.Count));

            Trace.Unindent();
            return(result);
        }
        public void NewSheet(CompareFile compareData, string path1, string path2, ExcelReportConfigurationDocument config)
        {
            Preconditions.NotNull(compareData, "compareData");
            Preconditions.Check(compareData.CompareItems.Count > 0, "CompareData should not be empty.");
            Preconditions.NotNullOrWhiteSpace(path1, "path1");
            Preconditions.NotNullOrWhiteSpace(path2, "path2");
            Preconditions.Check(!path1.Equals(path2, StringComparison.OrdinalIgnoreCase), "Path1 should not be same as Path2");

            var columns   = compareData.CompareItems.First().Data.Select(x => x.Key).ToList();
            var worksheet = workbook.Worksheets.Add(compareData.FileName);

            OutputHeader(worksheet, columns, path1, path2, config);
            FillData(worksheet, columns, compareData, config);
            UpdateWorksheetStyles(worksheet, compareData.CompareItems.Count, columns.Count, config);
        }
예제 #15
0
        /// <summary>
        /// Get the relative path fo the specific two path.
        /// </summary>
        /// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
        /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
        /// <returns>The relative path from the start directory to the end path.</returns>
        /// <exception cref="ArgumentException">This exception is thrown when the fromPath or toPath is not a valid path.</exception>
        /// <example>
        /// @"..\..\regedit.exe" = GetRelativePath(@"D:\Windows\Web\Wallpaper\", @"D:\Windows\regedit.exe" );
        /// </example>
        public static string GetRelativePath(this string fromPath, string toPath)
        {
            Preconditions.NotNullOrWhiteSpace(fromPath, "fromPath");
            Preconditions.NotNullOrWhiteSpace(toPath, "toPath");
            Preconditions.Check(() => Path.IsPathRooted(fromPath), "fromPath");
            Preconditions.Check(() => Path.IsPathRooted(toPath), "toPath");

            Uri fromUri = new Uri(fromPath);
            Uri toUri   = new Uri(toPath);

            Uri relativeUri  = fromUri.MakeRelativeUri(toUri);
            var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

            return(relativePath.Replace('/', Path.DirectorySeparatorChar));
        }
예제 #16
0
        public Task Split(string sourceFile, string targetDirectory, string namePrefix, IProgress <IProgressReport> progress)
        {
            Preconditions.NotNullOrWhiteSpace(sourceFile, nameof(sourceFile));
            Preconditions.Check(File.Exists(sourceFile), "Source should be an existed file.");
            Preconditions.Check(sourceFile.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase), "Source should be a file with pdf as extension.");

            return(Task.Factory.StartNew(() =>
            {
                Trace.Indent();
                Trace.TraceInformation($"Process the parameters prefix: {namePrefix}.");
                if (!targetDirectory.EndsWith("/"))
                {
                    targetDirectory += "/";
                }
                if (string.IsNullOrWhiteSpace(namePrefix))
                {
                    namePrefix = Path.GetFileNameWithoutExtension(sourceFile);
                }
                Trace.TraceInformation($"Prefix hand been process to {namePrefix}.");
                if (!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                }

                // Open the file
                PdfDocument inputDocument = PdfReader.Open(sourceFile, PdfDocumentOpenMode.Import);

                Console.WriteLine($"Start split the file. Total page number: {inputDocument.PageCount}.");
                for (int idx = 0; idx < inputDocument.PageCount; idx++)
                {
                    ReportProgress(progress, new ProgressReport(idx, inputDocument.PageCount));

                    // Create new document
                    PdfDocument outputDocument = new PdfDocument();
                    outputDocument.Version = inputDocument.Version;
                    outputDocument.Info.Title = $"{inputDocument.Info.Title} - Page {idx + 1} of {inputDocument.PageCount}";
                    outputDocument.Info.Creator = inputDocument.Info.Creator;

                    // Add the page and save it
                    outputDocument.AddPage(inputDocument.Pages[idx]);
                    outputDocument.Save($"{targetDirectory}{namePrefix} - Page {idx + 1}_{inputDocument.PageCount}.pdf");
                }
                ReportProgress(progress, new ProgressReport(inputDocument.PageCount, inputDocument.PageCount));

                Trace.Unindent();
            }));
        }
        private byte[] Receive(int length, out int count)
        {
            Preconditions.Check(length > 0);
            count = 0;
            var bytes  = new byte[length];
            var socket = client.Client;


            while (count < length && socket != null)
            {
                count += socket.Receive(bytes, count, length - count, SocketFlags.None);
                if (count == 0)
                {
                    //Thread.Sleep(200);
                    //throw new SocketException(); //TODO 这个地方再仔细研究一下。为什么会收到0?到底能不能重用?socket receive 可以收到0字节,error = connectionreset.
                }
            }
            return(bytes);
        }
예제 #18
0
 public Device FindDevice(Device device)
 {
     Preconditions.Check(device != null && !string.IsNullOrEmpty(device.ID));
     return(Devices.FirstOrDefault(d => d.ID == device.ID));
 }
예제 #19
0
 internal OfflineMessage(Device local) : this()
 {
     Preconditions.Check(local != null);
     InitFromDevice(local);
     Device.State = DeviceState.OffLine;
 }
예제 #20
0
        public static Config Load(Env container, string fileName)
        {
            Preconditions.Check(!string.IsNullOrEmpty(fileName), "必须指定配置文件路径。");

            bool   dirtdy = false;
            Config config = new Config();

            config.configFileName = fileName;

            string json = "";

            try
            {
                json = File.ReadAllText(fileName, Encoding.UTF8);
                JsonConvert.PopulateObject(json, config);
            }
            catch (Exception e)
            {
                dirtdy = true;
            }

            //检查反序列化后各个成员是否正确,如果不正确,配置默认值。
            //TODO DeviceInfo 序列化说明

            if (config.LocalDevice == null)
            {
                dirtdy = true;
                var device = new Device()
                {
                    Avatar     = Avatar.Facebook,
                    Name       = container.GetUserName(),   // Environment.UserName, //TODO
                    DeviceName = container.GetDeviceName(), // Environment.MachineName,
                    Version    = "1.0",
                    DeviceType = DeviceType.PC
                };


                if (string.IsNullOrEmpty(device.Name) || device.Name.ToLower().Equals("somebody"))
                {
                    device.Name = device.DeviceName;
                }


                config.LocalDevice = device;
            }
            if (string.IsNullOrEmpty(config.LocalDevice.DeviceName))
            {
                config.LocalDevice.DeviceName = container.GetDeviceName();
            }
            if (config.LocalDevice.ID == null)
            {
                config.LocalDevice.ID = StringHelper.NewRandomGUID();
                dirtdy = true;
            }
            if (config.LogLevel == null)
            {
                config.LogLevel = LogLevel.Error;
                dirtdy          = true;
            }
            if (config.TrustDevices == null)
            {
                config.TrustDevices = new List <Device>();
                dirtdy = true;
            }

            if (string.IsNullOrEmpty(config.DefaultDir) || !Directory.Exists(config.DefaultDir))
            {
                config.DefaultDir = container.GetRealPath(BrowseLocation.CONNECT2_DEFAULT);
                dirtdy            = true;
            }

            if (dirtdy)
            {
                config.Save();
            }
            return(config);
        }
예제 #21
0
        /// <summary>
        /// 在限定的时间内,每隔两秒钟,不停的尝试链接,直到连接成功。如果超时,调用timeoutAction. 在给定时间内,不限次数的连接。
        ///
        /// 注意!! 调用Connect之前,如果Device的状态已经是ConnectingOut,这个函数会直接返回。如果想要强制重连,需要先将Device状态设置成Idle.
        /// </summary>
        /// <param name="timeoutMilliSeconds">允许尝试连接的时间(包括等待对方应答的时间)。</param>
        /// <param name="socketTimeoutMilliSeconds">建立socket最大等待时间。默认值=timeoutMilliSeconds。如果在这个事件范围内未成功建立连接,则报错</param>
        public void Connect(double timeoutMilliSeconds = 10000d, Action timeoutAction = null, double?socketTimeoutMilliSeconds = null)
        {
            if (State == DeviceState.ConnectingOut)
            {
                return;                                      //不要重复的发连接消息。一个连接失败后,状态会改变。但在尝试期间,不得重复。
            }
#if DEBUG
            //在测试情况下输入IP地址,或者通过扫描二维码,得到了这个设备,去主动连接这个设备时,底层的设备列表中并没有发现这个设备。
            if (ID == null)
            {
                ID = IPAddress;
            }
#endif
            Preconditions.Check(timeoutMilliSeconds > 0, "允许连接尝试时间必须大于0");
            Preconditions.Check(ID != null);

            //如果对方也在尝试连接我。
            //TODO BUG? 这个地方和安全冲突。如果对方要求安全密码在连接我,我同时点击它,就不会要求输入密码了,再另一方会认证失败。这样倒也能接受。
            if (State == DeviceState.ConnectingIn)
            {
                //TODO 这样做是否合适?
                Accept();
                return;
            }

            State         = DeviceState.ConnectingOut;
            socketCreated = false;
            double _socketTimeoutMilliSeconds = socketTimeoutMilliSeconds ?? timeoutMilliSeconds;
            ConnectingOutSocketTimer?.Stop();
            if (_socketTimeoutMilliSeconds != timeoutMilliSeconds)
            {
                ConnectingOutSocketTimer = Util.DoLater(() =>
                {
                    OnConnectintOutTimeout(timeoutAction);
                }, _socketTimeoutMilliSeconds);
            }

            //一旦启动连接后,启动一个计时器。如果中间连接成功,则清除这个计时器。
            ConnectingOutTimer?.Stop(); //如果以前曾经尝试连接,忽略以前的结果
            ConnectingOutTimer = Util.DoLater(() =>
            {
                OnConnectintOutTimeout(timeoutAction);
            }, timeoutMilliSeconds);

            IsRequester = true;
            //超时时间与上面的计时器时间相同,所以不在设置超时行为。
            AppModel.Instance.ChannelManager.CreateChannel(
                this
                , (channel) =>
            {
                SwitchChannel(channel);
                //TODO 为什么要延时发送?对方执行ChannelCreated, 并为Channel设置PacketReceivedEvent好像需要执行时间
                //如果在这期间发送了Connect消息,会被对方忽略。
                //TODO 重构 如果这个问题真的存在,可以让对方准备好之后回一个消息,这边收到消息之后再发送connect消息
                Util.RunLater(
                    () =>
                {
                    //如果是主动连接别人,发送一个连接消息。不要调用Device的Post函数。
                    //如果这里给别人发了链接消息,但是对方一直没理你,还是会导致超时。
                    SendConnectMessage();
                }
                    , 100d);
            }
                , null
                , timeoutMilliSeconds
                , (int)RETRY_INTERVAL
                );
        }
예제 #22
0
        public Task <CompareFile> Compare(JsonDocument document1, JsonDocument document2)
        {
            Preconditions.Check(document1 != null || document2 != null, "Parameter 'document1' and 'document2' cannot be null at same time.");
            Preconditions.Check(document1 == null || document2 == null || document1.FileName.Equals(document2.FileName), "2 documents should with same name.");

            var compareItems = new List <CompareItem>();

            if (document1 == null)
            {
                return(Task.Factory.StartNew(() =>
                {
                    foreach (var property in document2)
                    {
                        compareItems.Add(NothingWithCompareData(property.Value));
                    }
                    ;
                    return new CompareFile(document2.FileName, compareItems);
                }));
            }

            if (document2 == null)
            {
                return(Task.Factory.StartNew(() =>
                {
                    foreach (var property in document1)
                    {
                        compareItems.Add(CompareWithNothing(property.Value));
                    }
                    ;
                    return new CompareFile(document1.FileName, compareItems);
                }));
            }

            var properties1 = document1.Properties;
            var properties2 = document2.Properties;
            var i = 0; var j = 0;

            return(Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (i == properties1.Count)
                    {
                        while (j < properties2.Count)
                        {
                            compareItems.Add(NothingWithCompareData(properties2[j++]));
                        }
                        break;
                    }
                    if (j == properties2.Count)
                    {
                        while (i < properties1.Count)
                        {
                            compareItems.Add(CompareWithNothing(properties1[i++]));
                        }
                        break;
                    }

                    var compareResult = properties1[i].Name.CompareTo(properties2[j].Name);
                    if (compareResult > 0)
                    {
                        compareItems.Add(NothingWithCompareData(properties2[j++]));
                    }
                    else if (compareResult < 0)
                    {
                        compareItems.Add(CompareWithNothing(properties1[i++]));
                    }
                    else
                    {
                        compareItems.Add(CompareWithAnother(properties1[i++], properties2[j++]));
                    }
                }
                return new CompareFile(document1.FileName, compareItems);
            }));
        }
예제 #23
0
 public void NotMath()
 {
     Preconditions.Check(!string.IsNullOrWhiteSpace(null));
 }
예제 #24
0
 public void Match()
 {
     Preconditions.Check(string.IsNullOrWhiteSpace(null));
 }
예제 #25
0
        public Task SplitBlock(string sourceFile, string targetDirectory, string settingFile, IProgress <IProgressReport> progress)
        {
            Preconditions.NotNullOrWhiteSpace(sourceFile, nameof(sourceFile));
            Preconditions.Check(File.Exists(sourceFile), "Source should be an existed file.");
            Preconditions.Check(sourceFile.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase), "Source should be a file with pdf as extension.");

            Preconditions.NotNullOrWhiteSpace(settingFile, nameof(settingFile));
            Preconditions.Check(File.Exists(settingFile), "Setting should be an existed file.");
            Preconditions.Check(settingFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase), "Setting should be a file with json as extension.");

            return(Task.Factory.StartNew(() =>
            {
                Trace.Indent();

                // Open the file
                PdfDocument inputDocument = PdfReader.Open(sourceFile, PdfDocumentOpenMode.Import);

                if (!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                }
                if (!targetDirectory.EndsWith("/"))
                {
                    targetDirectory += "/";
                }

                List <SplitBlockModel> settings = null;
                try
                {
                    Trace.TraceInformation($"Read setting from file {settingFile}.");
                    settings = JsonConvert.DeserializeObject <List <SplitBlockModel> >(File.ReadAllText(settingFile));

                    if (settings.Any(s => s.StartPage > s.EndPage))
                    {
                        Console.WriteLine("Setting not valid, start page index should not larger than end page index.");
                        return;
                    }

                    if (settings.Any(s => s.StartPage > inputDocument.PageCount || s.StartPage <= 0))
                    {
                        Console.WriteLine("Setting not valid, start page index should larger than 0 and smaller or equal to source file page count.");
                        return;
                    }

                    if (settings.Any(s => s.EndPage > inputDocument.PageCount || s.EndPage <= 0))
                    {
                        Console.WriteLine("Setting not valid, end page index should larger than 0 and smaller or equal to source file page count.");
                        return;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Cannot read the settings, please check the document and fix the setting file.");
                    return;
                }

                Console.WriteLine($"Start split the file to {settings.Count} block. Total page number: {inputDocument.PageCount}.");
                string name = Path.GetFileNameWithoutExtension(sourceFile);
                for (int idx = 0; idx < settings.Count; idx++)
                {
                    var setting = settings[idx];

                    ReportProgress(progress, new ProgressReport(idx, settings.Count));

                    // Create new document
                    PdfDocument outputDocument = new PdfDocument();
                    outputDocument.Version = inputDocument.Version;
                    outputDocument.Info.Title = $"{setting.Name}";
                    outputDocument.Info.Creator = inputDocument.Info.Creator;

                    // Add the pages and save it
                    for (int pageId = setting.StartPage; pageId <= setting.EndPage; pageId++)
                    {
                        outputDocument.AddPage(inputDocument.Pages[pageId - 1]);
                    }

                    outputDocument.Save($"{targetDirectory}{setting.Name}.pdf");
                }
                ReportProgress(progress, new ProgressReport(settings.Count, settings.Count));

                Trace.Unindent();
            }));
        }
예제 #26
0
 public void NotMath()
 {
     Preconditions.Check <NotSupportedException>(!string.IsNullOrWhiteSpace(null));
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="device"></param>
        /// <param name="channelCreated">连接成功回调</param>
        /// <param name="createChannelFailed">连接失败回调</param>
        /// <param name="timeout">最长连接时间</param>
        /// <param name="interval">若连接出现失败,多久后重试?现在不用这个值了</param>
        /// <param name="maxRetryCount">若连接失败,最多允许重试几次?</param>
        internal void CreateChannel(Device device, Action <IChannel> channelCreated, Action createChannelFailed, double timeout, int interval)
        {
            Preconditions.Check(interval > 1000);

            var ips = string.IsNullOrEmpty(device.IPAddress) ? new List <string>() : device.IPAddress.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries).ToList();

            if (!string.IsNullOrEmpty(device.DefaultIP))
            {
                //把default ip调整到前面
                if (ips.Any(ip => ip == device.DefaultIP))
                {
                    ips.Remove(device.DefaultIP);
                }
                ips.Insert(0, device.DefaultIP);
            }
            ips.RemoveAll(o => !IsValidRemoteIP(o, device));

            if (ips.Count == 0)
            {
                Env.Instance.Logger.Error("createChannelFailed, no available remote ip address");
                createChannelFailed?.Invoke();
                return;
            }



            ips.ForEach(ip =>
            {
                try {
#if WIN
                    var client = new TcpClient(new IPEndPoint(IPAddress.Any, TCPPortPool.Connect2TCPPortPool.GetPort()));
#else
                    var client = new TcpClient();

                    //TODO BUG 这样做之后,连接就变得特别困难,为什么?是出栈端口在一段时间之内不能复用吗?
                    //for (var i = 50001; i <= 51000; i++)
                    //{
                    //    try
                    //    {
                    //        client = new TcpClient(new IPEndPoint(IPAddress.Any, i));

                    //        break;
                    //    }
                    //    catch
                    //    {
                    //        // ignored
                    //    }
                    //}
#endif
                    var connectHolder = new ConnectHolder
                    {
                        Device         = device,
                        ChannelCreated = channelCreated,
                        TimeoutAction  = createChannelFailed
                    };
                    Util.RunLater(() => connectHolder.Timeout(), timeout);

                    client.BeginConnect(ip, port, connectHolder.BeginConnectCallback, client);
                }
                catch (Exception e)
                {
                    Env.Instance.Logger.Warn("ConnectSocket Error:" + e.StackTrace);
                }
            });
        }
예제 #28
0
        public Task Merge(string sourceDirectory, string targetFile, string filterPrefix, bool viewFinalOutput, IProgress <IProgressReport> progress)
        {
            Preconditions.NotNullOrWhiteSpace(sourceDirectory, nameof(sourceDirectory));
            Preconditions.Check(Directory.Exists(sourceDirectory), "Source sould be an existed directory.");

            return(Task.Factory.StartNew(() =>
            {
                Trace.Indent();
                Trace.TraceInformation($"Process the parameters target: {targetFile}.");
                if (string.IsNullOrWhiteSpace(targetFile))
                {
                    targetFile = "Merge_File.pdf";
                }
                if (!targetFile.EndsWith(".pdf"))
                {
                    targetFile += ".pdf";
                }
                Trace.TraceInformation($"Target hand been process to {targetFile}.");

                // Get the files
                Trace.TraceInformation($"Get the files from {sourceDirectory} with prefix {filterPrefix}.");
                var files = string.IsNullOrWhiteSpace(filterPrefix)
                    ? Directory.GetFiles(sourceDirectory, "*.pdf", SearchOption.TopDirectoryOnly)
                    : Directory.GetFiles(sourceDirectory, $"{filterPrefix}*.pdf", SearchOption.TopDirectoryOnly);

                files = files.OrderBy(file => file).ToArray();

                // Open the output document
                PdfDocument outputDocument = new PdfDocument();

                // Iterate files
                Console.WriteLine($"Start merge the files. Total number: {files.Length}.");
                int mergedFileCount = 0;
                foreach (string file in files)
                {
                    ReportProgress(progress, new ProgressReport(mergedFileCount, files.Length));

                    // Open the document to import pages from it.
                    PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);

                    // Iterate pages
                    int count = inputDocument.PageCount;
                    for (int idx = 0; idx < count; idx++)
                    {
                        // Get the page from the external document...
                        PdfPage page = inputDocument.Pages[idx];
                        // ...and add it to the output document.
                        outputDocument.AddPage(page);
                    }
                }
                ReportProgress(progress, new ProgressReport(files.Length, files.Length));

                // Save the document
                Trace.TraceInformation($"Save the output file {targetFile}.");
                outputDocument.Save(targetFile);

                if (viewFinalOutput)   // start a viewer.
                {
                    Console.WriteLine($"Show the merged file {targetFile}.");
                    Process.Start(targetFile);
                }

                Trace.Unindent();
            }));
        }
예제 #29
0
        //private string GetConnectCodeFromSecureStorage()
        //{
        //    string connectCodeKey = "Connect2_ConnectCode";

        //    SecurePassword secureConnectCode = Env.Instance.SecurityManager.LoadPassword(connectCodeKey);
        //    string connectCode = (secureConnectCode != null && secureConnectCode.IsValid == true)
        //        ? SecurePassword.GetStringFromSecureString(secureConnectCode.SecureString)
        //        : null;

        //    if (string.IsNullOrEmpty(connectCode) == true)
        //    {
        //        connectCode = StringHelper.NewRandomPassword();
        //        Env.Instance.SecurityManager.SavePassword(connectCodeKey, new SecurePassword(connectCode));
        //    }

        //    if (secureConnectCode != null)
        //    {
        //        secureConnectCode.Dispose();
        //        secureConnectCode = null;
        //    }

        //    return connectCode;
        //}

        internal void RemoveDevice(Device device)
        {
            Preconditions.Check(device != null && !string.IsNullOrEmpty(device.ID));
            Devices.RemoveWhere(d => d.ID == device.ID);
        }
예제 #30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MinimumElementsAttribute"/> class.
        /// </summary>
        /// <param name="minElementsCount">The minimum elements count.</param>
        public MinimumElementsAttribute(int minElementsCount)
        {
            Preconditions.Check(minElementsCount >= 0, "The minimum elements count cannot less than 0.");

            MinElementsCount = minElementsCount;
        }