示例#1
0
 public static void SendBytesAsync(this Socket socket, byte[] bytes, int offset, int count, Action <bool> callback)
 {
     if (!MiscHelpers.Try(() => socket.BeginSend(bytes, offset, count, SocketFlags.None, result => socket.OnBytesSent(result, bytes, offset, count, callback), null)))
     {
         callback(false);
     }
 }
示例#2
0
 public static void ReceiveBytesAsync(this Socket socket, byte[] bytes, int offset, int count, Action <byte[]> callback)
 {
     if (!MiscHelpers.Try(() => socket.BeginReceive(bytes, offset, count, SocketFlags.None, result => socket.OnBytesReceived(result, bytes, offset, count, callback), null)))
     {
         callback(null);
     }
 }
示例#3
0
        private static void ReceiveMessageAsyncWorker(WebSocket webSocket, WebSocketMessageType type, byte[] bytes, Action <byte[], WebSocketCloseStatus, string> callback)
        {
            var buffer = new byte[bufferSize];

            webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None).ContinueWith(task =>
            {
                WebSocketReceiveResult result;
                if (!MiscHelpers.Try(out result, () => task.Result) || (result == null))
                {
                    callback(null, WebSocketCloseStatus.ProtocolError, "Could not receive data from web socket");
                }
                else if (result.MessageType == WebSocketMessageType.Close)
                {
                    callback(null, result.CloseStatus ?? WebSocketCloseStatus.Empty, MiscHelpers.EnsureNonBlank(result.CloseStatusDescription, "Could not determine web socket close status"));
                }
                else if (result.MessageType != type)
                {
                    callback(null, WebSocketCloseStatus.ProtocolError, "Received unrecognized data from web socket");
                }
                else
                {
                    bytes = bytes.Concat(buffer.Take(result.Count)).ToArray();
                    if (!result.EndOfMessage)
                    {
                        ReceiveMessageAsyncWorker(webSocket, type, bytes, callback);
                    }
                    else
                    {
                        callback(bytes, WebSocketCloseStatus.Empty, null);
                    }
                }
            });
        }
        private static string GetFullTypeName(string name, string assemblyName, bool useAssemblyName, int typeArgCount)
        {
            var fullTypeName = name;

            if (typeArgCount > 0)
            {
                fullTypeName += MiscHelpers.FormatInvariant("`{0}", typeArgCount);
            }

            if (useAssemblyName)
            {
                Assembly assembly;
                if (MiscHelpers.Try(out assembly, () => Assembly.Load(AssemblyTable.GetFullAssemblyName(assemblyName))))
                {
                    // ReSharper disable AccessToModifiedClosure

                    string result;
                    if (MiscHelpers.Try(out result, () => assembly.GetType(fullTypeName).AssemblyQualifiedName))
                    {
                        return(result);
                    }

                    // ReSharper restore AccessToModifiedClosure
                }

                fullTypeName += MiscHelpers.FormatInvariant(", {0}", AssemblyTable.GetFullAssemblyName(assemblyName));
            }

            return(fullTypeName);
        }
示例#5
0
 private void OnTimer(object state)
 {
     if (!disposedFlag.IsSet())
     {
         MiscHelpers.Try(callback.Invoke);
     }
 }
        public static string GetFullAssemblyName(string name)
        {
            // ReSharper disable AccessToModifiedClosure

            if (string.IsNullOrWhiteSpace(name))
            {
                return(name);
            }

            Assembly assembly;

            if (MiscHelpers.Try(out assembly, () => Assembly.Load(name)))
            {
                return(assembly.FullName);
            }

            var fileName = name;

            if (!string.Equals(Path.GetExtension(fileName), ".dll", StringComparison.OrdinalIgnoreCase))
            {
                fileName = Path.ChangeExtension(fileName + '.', "dll");
            }

            AssemblyName assemblyName;

            if (MiscHelpers.Try(out assemblyName, () => AssemblyName.GetAssemblyName(fileName)))
            {
                return(assemblyName.FullName);
            }

            var dirPath = Path.GetDirectoryName(typeof(string).Assembly.Location);

            if (!string.IsNullOrWhiteSpace(dirPath))
            {
                var path = Path.Combine(dirPath, fileName);
                if (File.Exists(path) && MiscHelpers.Try(out assemblyName, () => AssemblyName.GetAssemblyName(path)))
                {
                    return(assemblyName.FullName);
                }

                IEnumerable <string> subDirPaths;
                if (MiscHelpers.Try(out subDirPaths, () => Directory.EnumerateDirectories(dirPath, "*", SearchOption.AllDirectories)))
                {
                    foreach (var subDirPath in subDirPaths)
                    {
                        path = Path.Combine(subDirPath, fileName);
                        if (File.Exists(path) && MiscHelpers.Try(out assemblyName, () => AssemblyName.GetAssemblyName(path)))
                        {
                            return(assemblyName.FullName);
                        }
                    }
                }
            }

            return(name);

            // ReSharper restore AccessToModifiedClosure
        }
        public static Assembly TryLoad(AssemblyName name)
        {
            Assembly assembly;

            if (MiscHelpers.Try(out assembly, () => Assembly.Load(name)))
            {
                return(assembly);
            }

            return(null);
        }
 private static bool WriteAssemblyTable(string rootPath)
 {
     return(MiscHelpers.Try(() =>
     {
         var filePath = GetFilePath(rootPath);
         using (var stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
         {
             var formatter = new BinaryFormatter();
             formatter.Serialize(stream, table);
         }
     }));
 }
示例#9
0
        public bool Change(int dueTime, int period)
        {
            if (!disposedFlag.IsSet())
            {
                bool result;
                if (MiscHelpers.Try(out result, () => timer.Change(dueTime, period)))
                {
                    return(result);
                }
            }

            return(false);
        }
示例#10
0
 public static void SendMessageAsync(this WebSocket webSocket, WebSocketMessageType type, byte[] bytes, Action <bool, WebSocketCloseStatus, string> callback)
 {
     webSocket.SendAsync(new ArraySegment <byte>(bytes), type, true, CancellationToken.None).ContinueWith(task =>
     {
         if (!MiscHelpers.Try(task.Wait))
         {
             callback(false, WebSocketCloseStatus.ProtocolError, "Could not send data to web socket");
         }
         else
         {
             callback(true, WebSocketCloseStatus.Empty, null);
         }
     });
 }
            private static bool ReadAssemblyTable(string rootPath)
            {
                var succeeded = MiscHelpers.Try(() =>
                {
                    var filePath = GetFilePath(rootPath);
                    if (File.Exists(filePath))
                    {
                        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            var formatter = new BinaryFormatter();
                            table         = (ConcurrentDictionary <string, string>)formatter.Deserialize(stream);
                        }
                    }
                });

                return(succeeded && (table != null));
            }
示例#12
0
        public static void OnBytesSent(this Socket socket, IAsyncResult result, byte[] bytes, int offset, int count, Action <bool> callback)
        {
            int sentCount;

            if (MiscHelpers.Try(out sentCount, () => socket.EndReceive(result)) && (sentCount > 0))
            {
                if (sentCount >= count)
                {
                    callback(true);
                }
                else
                {
                    socket.SendBytesAsync(bytes, offset + sentCount, count - sentCount, callback);
                }
            }
            else
            {
                callback(false);
            }
        }
示例#13
0
        public static void OnBytesReceived(this Socket socket, IAsyncResult result, byte[] bytes, int offset, int count, Action <byte[]> callback)
        {
            int receivedCount;

            if (MiscHelpers.Try(out receivedCount, () => socket.EndReceive(result)) && (receivedCount > 0))
            {
                if (receivedCount >= count)
                {
                    callback(bytes);
                }
                else
                {
                    socket.ReceiveBytesAsync(bytes, offset + receivedCount, count - receivedCount, callback);
                }
            }
            else
            {
                callback(null);
            }
        }
示例#14
0
        private static bool IsImplicitlyConvertibleInternal(Type definingType, Type sourceType, Type targetType, ref object value)
        {
            foreach (var converter in definingType.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(method => method.Name == "op_Implicit"))
            {
                var parameters = converter.GetParameters();
                if ((parameters.Length == 1) && parameters[0].ParameterType.IsAssignableFrom(sourceType) && targetType.IsAssignableFrom(converter.ReturnType))
                {
                    // ReSharper disable AccessToForEachVariableInClosure

                    var    args = new[] { value };
                    object result;
                    if (MiscHelpers.Try(out result, () => converter.Invoke(null, args)))
                    {
                        value = result;
                        return(true);
                    }

                    // ReSharper restore AccessToForEachVariableInClosure
                }
            }

            return(false);
        }
            private static bool BuildAssemblyTable()
            {
                var succeeded = MiscHelpers.Try(() =>
                {
                    var key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework");
                    if (key != null)
                    {
                        var dirPath = Path.Combine((string)key.GetValue("InstallRoot"), GetRuntimeVersionDirectoryName());

                        table = new ConcurrentDictionary <string, string>();
                        foreach (var filePath in Directory.EnumerateFiles(dirPath, "*.dll", SearchOption.AllDirectories))
                        {
                            var path = filePath;
                            MiscHelpers.Try(() =>
                            {
                                var assemblyName = Assembly.ReflectionOnlyLoadFrom(path).GetName();
                                table.TryAdd(assemblyName.Name, assemblyName.FullName);
                            });
                        }
                    }
                });

                return(succeeded && (table != null));
            }