Example #1
0
        /// <summary>
        /// Execute Stored Procedure with the Parameters passed
        /// </summary>
        /// <param name="Conn"></param>
        /// <param name="procname"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static DataTable ExecuteProcWithParamsDT(this SqlConnection Conn, string procname, Hashtable parameters)
        {
            DataSet dataSet;
            try
            {
                SqlDataAdapter dataAdaptor = new SqlDataAdapter();
                dataAdaptor.SelectCommand = new SqlCommand(procname, Conn);
                dataAdaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
                if (parameters != null)
                    foreach (DictionaryEntry de in parameters)
                    {
                        SqlParameter sp = new SqlParameter(de.Key.ToString(), de.Value.ToString());
                        dataAdaptor.SelectCommand.Parameters.Add(sp);
                    }

                dataSet = new DataSet();
                dataAdaptor.Fill(dataSet, "table");
                Conn.Close();
                return dataSet.Tables["table"];
            }
            catch (Exception ex)
            {
                dataSet = null;
                Conn.Close();
                return null;
            }
            finally
            {
                Conn.Close();
                dataSet = null;
            }
        }
 public static void Dispose(this ICommunicationObject communicationObject, TimeSpan? closeTimeout)
 {
     bool abort = true;
     try
     {
         if (closeTimeout.HasValue)
         {
             communicationObject.Close(closeTimeout.Value);
         }
         else
         {
             communicationObject.Close();
         }
         abort = false;
     }
     catch (Exception e) when (e is TimeoutException || e is CommunicationException)
     {
     }
     finally
     {
         if (abort)
         {
             Trace.TraceWarning($"{nameof(CommunicationObjectExtensionMethods)}.{nameof(Dispose)}: The communication object is being aborted.");
             communicationObject.Abort();
         }
     }
 }
Example #3
0
 public static void CloseIfNotNull(this ICloseable closable)
 {
     if (closable != null) {
         if (closable is Component) {
             if ((Component)closable) {
                 closable.Close();
             }
         } else {
             closable.Close();
         }
     }
 }
 ///<summary>Forces a document to close.</summary>
 ///<remarks>This method works around Office issues.</remarks>
 public static void CloseDoc(this _Document doc)
 {
     try {
         doc.Close(ref dontSave, ref Missing, ref Missing);
         doc.Close(ref Missing, ref Missing, ref Missing);
     } catch (COMException) {
         try {
             doc.Close(ref dontSave, ref Missing, ref Missing);
             doc.Close(ref dontSave, ref Missing, ref Missing);
         } catch (COMException) { }
     }
 }
 public static Task CloseAsync(this Logger target)
 {
     return Task.Factory.StartNew(()=>{
         target.Close();
         return;
     });
 }
Example #6
0
		public static IDataReader ReadOne(this IDataReader reader, Action<IDataReader> action)
		{
			if (reader.Read())
				action(reader);
			reader.Close();
			return reader;
		}
Example #7
0
 public static void PrintToFile(this FileStream fs, string content)
 {
     StreamWriter writer = new StreamWriter(fs);
     writer.WriteLine(content);
     writer.Close();
     fs.Close();
 }
Example #8
0
 public static bool smethod_7(this TcpClient tcpClient_0, string string_0, int int_0, int int_1)
 {
     IAsyncResult asyncResult = tcpClient_0.BeginConnect(string_0, int_0, null, null);
     WaitHandle asyncWaitHandle = asyncResult.AsyncWaitHandle;
     bool result;
     try
     {
         if (asyncWaitHandle.WaitOne(int_1))
         {
             tcpClient_0.EndConnect(asyncResult);
             result = true;
         }
         else
         {
             tcpClient_0.Close();
             result = false;
         }
     }
     catch (SocketException)
     {
         result = false;
     }
     finally
     {
         asyncWaitHandle.Close();
     }
     return result;
 }
        public static async Task<int> SendWithTimeoutAfter(this UdpClient client, Byte[] list, int delay,
            CancellationTokenSource cancel) {
            if (client == null)
                throw new NullReferenceException();

            if (list == null)
                throw new ArgumentNullException("list");

            var task = client.SendAsync(list, list.Length);

            if (task.IsCompleted || (delay == Timeout.Infinite))
                return await task;

            await Task.WhenAny(task, Task.Delay(delay, cancel.Token)).ConfigureAwait(false);

            if (!task.IsCompleted) {
                client.Close();
                try {
                    return await task.ConfigureAwait(false);
                } catch (ObjectDisposedException) {
                    throw new TimeoutException("Send timed out.");
                }
            }

            cancel.Cancel(); // Cancel the timer! 
            return await task.ConfigureAwait(false);
        }
Example #10
0
 public static void Close(this Solution sol, CloseOptions options)
 {
     var save = (options & CloseOptions.Save) == CloseOptions.Save;
     var wait = (options & CloseOptions.Wait) == CloseOptions.Wait;
     sol.Close(save);
     if (wait) WaitFor(null, () => sol.IsOpen == false, waitFor: TimeSpan.FromSeconds(20));
 }
        /**--------------------------------------------------------------------------------------------------
        <summary> A SqlConnection extension method that closes a safely. </summary>

        <param name="con"> The con to act on. </param>

        <returns> . </returns>
        **/
        public static void CloseSafely(this DbConnection con)
        {
            if (con.State == ConnectionState.Open)
                con.Close();

            //return con;
        }
 public static CouchResponseObject GetJObject(this HttpWebResponse response)
 {
     var resp = new CouchResponseObject(JObject.Parse(response.GetResponseString()));
     resp.StatusCode = (int)response.StatusCode;
     response.Close();
     return resp;
 }
Example #13
0
 public async static void SpecialClose(this Window window)
 {
     await window.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
     {
         window.Close();
     });
 }
Example #14
0
        public static void SafeCloseClientSocket(this Socket client, ILogger logger)
        {
            if(client == null)
                return;

            if (!client.Connected)
                return;
            
            try
            {
                client.Shutdown(SocketShutdown.Both);
            }
            catch(ObjectDisposedException)
            {
            }
            catch(Exception e)
            {
                if(logger != null)
                    logger.LogError(e);
            }
            
            try
            {
                client.Close();
            }
            catch(ObjectDisposedException)
            {
            }
            catch(Exception e)
            {
                if(logger != null)
                    logger.LogError(e);
            }
        }
 /// <summary>
 /// Closes the <see cref="ICommunicationObject"/> if it's not in the Faulted state, but Aborts it otherwise.
 /// Additionally, if Close throws an expected exception, that exception is swallowed and the operation is Aborted.
 /// </summary>
 /// <param name="client">The <see cref="ICommunicationObject"/> on which <see cref="ICommunicationObject.Close()"/>
 /// or <see cref="ICommunicationObject.Abort()"/> will be called.</param>
 /// <remarks>For more details, see:
 /// http://msdn2.microsoft.com/en-us/library/aa355056.aspx
 /// http://msdn2.microsoft.com/en-us/library/aa354510.aspx
 /// http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx
 /// http://blogs.breezetraining.com.au/mickb/2006/12/19/GreatArticleOnWCF.aspx
 /// </remarks>
 public static void CloseOrAbort(this ICommunicationObject client)
 {
     if (client.State != CommunicationState.Faulted)
     {
         // client is in non-faulted state; we can attempt to Close it
         try
         {
             client.Close();
         }
         catch (CommunicationException)
         {
             client.Abort();
         }
         catch (TimeoutException)
         {
             client.Abort();
         }
         catch (Exception)
         {
             // unexpected exception--still Abort the client, but re-throw it
             client.Abort();
             throw;
         }
     }
     else
     {
         // client has already failed; have to abort
         client.Abort();
     }
 }
Example #16
0
		public static IDataReader ReadAll(this IDataReader reader, Action<IDataReader> action)
		{
			while (reader.Read())
				action(reader);
			reader.Close();
			return reader;
		}
		/// <summary>
		/// 破棄
		/// </summary>
		/// <param name="device"></param>
		public static void Shutdown(this OutputDevice device)
		{
			if (device != null)
			{
				device.Close();
			}
		}
Example #18
0
        public static byte[] toArray(this Stream stream)
        {
            try
            {
                // Note: if we can seek, it's likely we have a length
                if (stream.CanSeek)
                {
                    if (stream.Length >= 0)
                    {
                        byte[] r = new byte[stream.Length];
                        NB.ReadFully(stream, r, 0, r.Length);
                        return r;
                    }
                }

                MemoryStream m = new MemoryStream();
                byte[] buf = new byte[2048];
                int n;
                while ((n = stream.Read(buf, 0, buf.Length)) > 0)
                    m.Write(buf, 0, n);
                return m.ToArray();
            }
            finally
            {
                stream.Close();
            }
        }
Example #19
0
        public static void Close( this Window window, bool? dialogResult )
        {
            Arg.NotNull( window, nameof( window ) );

            try
            {
                if ( ComponentDispatcher.IsThreadModal )
                    window.DialogResult = dialogResult;
                else
                    window.Close();
            }
            catch ( InvalidOperationException )
            {
                window.Close();
            }
        }
Example #20
0
 public static bool TableExists(this IDbConnection connection,string tableName)
 {
     bool exists;
     try
     {
         connection.Open();
         // ANSI SQL
         var cmd = connection.CreateCommand();
         cmd.CommandText = string.Format("select case when exists((select * from information_schema.tables " +
                                         "where table_name = '{0}')) then 1 else 0 end", tableName);
         exists = (int) cmd.ExecuteScalar() == 1;
     }
     catch
     {
         try
         {
             // Other RDBMS.
             exists = true;
             var cmd = connection.CreateCommand();
             cmd.CommandText = string.Format("select 1 from {0} where 1 = 0", tableName);
             cmd.ExecuteNonQuery();
         }
         catch
         {
             exists = false;
         }
     }
     finally
     {
         connection.Close();
     }
     return exists;
 }
        /// <summary>
        /// Closes an AMQP object asynchronously.
        /// </summary>
        /// <param name="amqpObject">The object to close.</param>
        /// <param name="timeout">The timeout in seconds.</param>
        /// <returns></returns>
        public static Task CloseAsync(this AmqpObject amqpObject, int timeout = 60000)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            try
            {
                amqpObject.Closed += (o, e) =>
                {
                    if (e != null)
                    {
                        tcs.SetException(new AmqpException(e));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                };

                amqpObject.Close(0);
            }
            catch (Exception exception)
            {
                tcs.SetException(exception);
            }

            return tcs.Task;
        }
        internal static void Dispose(this WaitHandle handle)
        {
            if (handle == null)
                throw new NullReferenceException();

            handle.Close();
        }
        /// <summary>
        /// Close and dispose of a RabbitMQ connection without throwing any exceptions
        /// </summary>
        /// <param name="connection">The channel (can be null)</param>
        /// <param name="replyCode"></param>
        /// <param name="message">Message for channel closure</param>
        public static void Cleanup(this IConnection connection, ushort replyCode = 200, string message = "Unknown")
        {
            if (connection != null)
            {
                try
                {
                    connection.Close(replyCode, message);
                }
                catch (AlreadyClosedException)
                {
                }
                catch (Exception ex)
                {
                    _log.Warn("Failed to close connection", ex);
                }

                try
                {
                    connection.Dispose();
                }
                catch (ObjectDisposedException)
                {
                }
                catch (Exception ex)
                {
                    _log.Warn("Failed to dispose connection", ex);
                }
            }
        }
        public static IObservable<DisposableByteBuffer> ToFrameClientObservable(this Socket socket, SocketFlags socketFlags, BufferManager bufferManager)
        {
            return Observable.Create<DisposableByteBuffer>(async (observer, token) =>
            {
                var headerBuffer = new byte[sizeof(int)];

                try
                {
                    while (!token.IsCancellationRequested)
                    {
                        if (await socket.ReceiveCompletelyAsync(headerBuffer, headerBuffer.Length, socketFlags, token) != headerBuffer.Length)
                            break;
                        var length = BitConverter.ToInt32(headerBuffer, 0);

                        var buffer = bufferManager.TakeBuffer(length);
                        if (await socket.ReceiveCompletelyAsync(buffer, length, socketFlags, token) != length)
                            break;

                        observer.OnNext(new DisposableByteBuffer(buffer, length, Disposable.Create(() => bufferManager.ReturnBuffer(buffer))));
                    }

                    observer.OnCompleted();

                    socket.Close();
                }
                catch (Exception error)
                {
                    observer.OnError(error);
                }
            });
        }
        internal static void Dispose(this Socket socket)
        {
            if (socket == null)
                throw new NullReferenceException();

            socket.Close();
        }
        /**--------------------------------------------------------------------------------------------------
        <summary> A SqlConnection extension method that closes a safely. </summary>

        <param name="con"> The con to act on. </param>

        <returns> . </returns>
        **/
        public static OracleConnection CloseSafely(this OracleConnection con)
        {
            if (con.State == ConnectionState.Open)
                con.Close();

            return con;
        }
        /// <summary>
        /// Tries to close the <see cref="ICommunicationObject"/>
        /// the recommended way. If this fails, an attempt is made
        /// to abort the object.
        /// </summary>
        /// <param name="communicationObject">The object to close safely.</param>
        public static void CloseSafely(this ICommunicationObject communicationObject)
        {
            if (communicationObject == null)
            {
                return;
            }

            try
            {
                communicationObject.Close();
            }
            catch (CommunicationException)
            {
                try
                {
                    communicationObject.Abort();
                }
                catch (Exception)
                {
                    try
                    {
                        // Nothing we can do here :-(
                    }
                    catch (Exception)
                    {                        
                    }
                }
            }
        }
Example #28
0
 public static void FullClose(this System.Net.Sockets.Socket s)
 {
     try
     {
         s.Shutdown(SocketShutdown.Both);
     }
     catch (Exception)
     {
     }
     try
     {
         s.Disconnect(false);
     }
     catch (Exception)
     {
     }
     try
     {
         s.Close();
     }
     catch (Exception)
     {
     }
     try
     {
         s.Dispose();
     }
     catch (Exception)
     {
     }
 }
Example #29
0
        /// <include file='../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.IO.BinaryReader.Close"]/*' />
        /// <param name="reader">Binary reader to be closed.</param>
        public static void Close(this BinaryReader reader)
         {
#if DOTNET || WINDOWS_PHONE || WINDOWS_PHONE_APP
             reader.Close();
#else
             reader.Dispose();
#endif
         }
Example #30
0
 public static void GravaRegistro90(this TextWriter file)
 {
     file.Write("90");
     file.Write("9".PadLeft(51, '9'));
     file.Write(' '.ToString().PadRight(306, ' '));
     file.Write("*");
     file.Close();
 }