| |
|
4851
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
|
en: 19 Septiembre 2015, 09:51 am
|
CursorUtil.vb, es una class que por el momento sirve cómo un simple wrapper de la función LoadCursorFromFile de la WinAPI, la cual nos permite evadir las limitaciones de un WindowsForms para poder cargar y utilizar un cursor que no sea blanco y negro. Source: ' *********************************************************************** ' Author : Elektro ' Modified : 08-September-2015 ' *********************************************************************** ' <copyright file="CursorUtil.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Imports " Imports System Imports System.ComponentModel Imports System.Diagnostics Imports System.IO Imports System.Linq Imports System.Runtime.InteropServices Imports System.Windows.Forms #End Region ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains related cursor utilities. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public NotInheritable Class CursorUtil #Region " P/Invoking " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Platform Invocation methods (P/Invoke), access unmanaged code. ''' This class does not suppress stack walks for unmanaged code permission. ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class. ''' This class is for methods that can be used anywhere because a stack walk will be performed. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' MSDN Documentation: <see href="http://msdn.microsoft.com/en-us/library/ms182161.aspx"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Private NotInheritable Class NativeMethods #Region " Functions " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Creates a cursor based on data contained in a file. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="filepath"> ''' The source of the file data to be used to create the cursor. ''' The data in the file must be in either .CUR or .ANI format. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' If the function is successful, the return value is an <see cref="IntPtr"/> to the new cursor. ''' If the function fails, the return value is <see cref="IntPtr.Zero"/>. ''' To get extended error information, call <see cref="Marshal.GetLastWin32Error"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' MSDN Documentation: <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms648392%28v=vs.85%29.aspx"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <DllImport("User32.dll", CharSet:=CharSet.Ansi, BestFitMapping:=False, ThrowOnUnmappableChar:=True, SetLastError:=True)> Friend Shared Function LoadCursorFromFile( ByVal filepath As String ) As IntPtr End Function #End Region End Class #End Region #Region " Constructors " ''' <summary> ''' Prevents a default instance of the <see cref="CursorUtil"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Creates a cursor based on data contained in a managed .Net resource. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="resource"> ''' The raw resource data. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="System.Windows.Forms.Cursor"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="Exception"> ''' </exception> ''' ''' <exception cref="Win32Exception"> ''' </exception> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Function LoadCursorFromResource(ByVal resource As Byte(), Optional cleanTempFile As Boolean = False) As Cursor Dim tmpFilepath As String = Path.GetTempFileName Try Using fs As New FileStream(tmpFilepath, FileMode.Create, FileAccess.Write, FileShare.Read) fs.Write(resource, 0, resource.Length) End Using Dim result As IntPtr = NativeMethods.LoadCursorFromFile(tmpFilepath) Dim win32Err As Integer = Marshal.GetLastWin32Error If (result = IntPtr.Zero) Then Throw New Win32Exception([error]:=win32Err) Else Return New Cursor(result) End If Catch ex As Exception Throw Finally If (cleanTempFile ) AndAlso (File. Exists(tmpFilepath )) Then End If End Try End Function #End Region End Class
SerializationUtil.vb, es una class para serializar y deserializar datos en binario o Xml de forma (más)sencilla y haciendo uso de Generics. ' *********************************************************************** ' Author : Elektro ' Modified : 05-September-2015 ' *********************************************************************** ' <copyright file="SerializationUtil.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Imports " Imports System Imports System.Data Imports System.IO Imports System.Linq Imports System.Runtime.Serialization.Formatters.Binary Imports System.Xml.Serialization #End Region ''' <summary> ''' Contains related serialization utilities. ''' </summary> Public NotInheritable Class SerializationUtil #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="SerializationUtil"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Sub New() End Sub #End Region #Region " Private Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the proper data serializer. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="format"> ''' The serialization format. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="System.ArgumentException"> ''' Wrong Serialization Format. ''' </exception> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Private Shared Function GetSerializer(Of T)(ByVal format As SerializationFormat) As Object Select Case format Case SerializationFormat.Binary Return New BinaryFormatter Case SerializationFormat.Xml Return New XmlSerializer(type:=GetType(T)) Case Else Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat") End Select End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the proper data serializer. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="obj"> ''' The object to check. ''' </param> ''' ''' <param name="format"> ''' The serialization format. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Private Shared Function GetSerializer(Of T)(ByVal obj As T, ByVal format As SerializationFormat) As Object Select format Case SerializationFormat.Binary Return New BinaryFormatter() Case SerializationFormat.Xml Return New XmlSerializer(obj.GetType) Case Else Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat") End Select End Function #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Serializes the data of an Object to the specified file, using the specified serialization format. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="obj"> ''' The object to be serialized. ''' </param> ''' ''' <param name="filepath"> ''' The filepath where to save the serialized data. ''' </param> ''' ''' <param name="format"> ''' The serialization format. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Sub Serialize(Of T)(ByVal obj As T, ByVal filepath As String, ByVal format As SerializationFormat) Dim serializer As Object = SerializationUtil.GetSerializer(obj, format) Using fs As New FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read) Select Case serializer.GetType Case GetType(BinaryFormatter) DirectCast(serializer, BinaryFormatter).Serialize(fs, obj) Case GetType(XmlSerializer) DirectCast(serializer, XmlSerializer).Serialize(fs, obj) End Select End Using End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Deserializes the data of an Object from the specified file, using the specified deserialization format. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="filepath"> ''' The filepath where from deserialize the serialized data. ''' </param> ''' ''' <param name="format"> ''' The serialization format. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Function Deserialize(Of T)(ByVal filepath As String, ByVal format As SerializationFormat) As T Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format) Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read) Select Case serializer.GetType Case GetType(BinaryFormatter) Return DirectCast(DirectCast(serializer, BinaryFormatter).Deserialize(fs), T) Case GetType(XmlSerializer) Return DirectCast(DirectCast(serializer, XmlSerializer).Deserialize(fs), T) End Select End Using End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Deserializes the data of an Object from the specified file, using the specified deserialization format. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="filepath"> ''' The filepath where from deserialize the serialized data. ''' </param> ''' ''' <param name="format"> ''' The serialization format. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Sub Deserialize(Of T)(ByRef refObj As T, ByVal filepath As String, ByVal format As SerializationFormat) refObj = SerializationUtil.Deserialize(Of T)(filepath, format) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the specified <see cref="Type"/> can be serialized. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' The <see cref="Type"/> to check. ''' </typeparam> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <c>True</c> if the specified <see cref="Type"/> can be serialized; otherwise, <c>False</c>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Function IsTypeSerializable(Of T)() As Boolean Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute)) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the specified <see cref="Type"/> can be serialized. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="type"> ''' The <see cref="Type"/> to check. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <c>True</c> if the specified <see cref="Type"/> can be serialized; otherwise, <c>False</c>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Function IsTypeSerializable(Of T)(ByVal type As T) As Boolean Return SerializationUtil.IsTypeSerializable(Of T)() End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the specified object can be serialized. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="obj"> ''' The object to check. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <c>True</c> if the specified object can be serialized; otherwise, <c>False</c>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Function IsObjectSerializable(Of T)(ByVal obj As T, ByVal format As SerializationFormat) As Boolean Dim serializer As Object = SerializationUtil.GetSerializer(obj, format) Using fs As New MemoryStream Try Select Case serializer.GetType Case GetType(BinaryFormatter) DirectCast(serializer, BinaryFormatter).Serialize(fs, obj) Case GetType(XmlSerializer) DirectCast(serializer, XmlSerializer).Serialize(fs, obj) End Select Return True Catch ex As InvalidOperationException Return False Catch ex As Exception Throw End Try End Using End Function #End Region End Class
|
|
|
|
|
4852
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
|
en: 19 Septiembre 2015, 09:35 am
|
IEnumerable(Of T) Extensions, cómo su propio nombre indica, expone varias extensiones de método para utilizarlas con una colección genérica. Las extensiones son las siguiente, si alguna no es lo suficientemente aclaratoria entonces pueden usar IntelliSense o el ObjectInspector para conocer el propósito de cada una: IEnumerable(Of T)().ConcatMultiple(IEnumerable(Of T)()) As IEnumerable(Of T) IEnumerable(Of T)().StringJoin As IEnumerable(Of T) IEnumerable(Of T).CountEmptyItems As Integer IEnumerable(Of T).CountNonEmptyItems As Integer IEnumerable(Of T).Duplicates As IEnumerable(Of T) IEnumerable(Of T).Randomize As IEnumerable(Of T) IEnumerable(Of T).RemoveDuplicates As IEnumerable(Of T) IEnumerable(Of T).SplitIntoNumberOfElements(Integer) As IEnumerable(Of T) IEnumerable(Of T).SplitIntoNumberOfElements(Integer, Boolean, T) As IEnumerable(Of T) IEnumerable(Of T).SplitIntoParts(Integer) As IEnumerable(Of T) IEnumerable(Of T).UniqueDuplicates As IEnumerable(Of T) IEnumerable(Of T).Uniques As IEnumerable(Of T)
Puse ejemplos de uso para cada extensión en la documentación XML del código fuente. Source: ' *********************************************************************** ' Author : Elektro ' Modified : 10-September-2015 ' *********************************************************************** ' <copyright file="IEnumerableExtensions.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' IEnumerable(Of T)().ConcatMultiple(IEnumerable(Of T)()) As IEnumerable(Of T) ' IEnumerable(Of T)().StringJoin As IEnumerable(Of T) ' IEnumerable(Of T).CountEmptyItems As Integer ' IEnumerable(Of T).CountNonEmptyItems As Integer ' IEnumerable(Of T).Duplicates As IEnumerable(Of T) ' IEnumerable(Of T).Randomize As IEnumerable(Of T) ' IEnumerable(Of T).RemoveDuplicates As IEnumerable(Of T) ' IEnumerable(Of T).SplitIntoNumberOfElements(Integer) As IEnumerable(Of T) ' IEnumerable(Of T).SplitIntoNumberOfElements(Integer, Boolean, T) As IEnumerable(Of T) ' IEnumerable(Of T).SplitIntoParts(Integer) As IEnumerable(Of T) ' IEnumerable(Of T).UniqueDuplicates As IEnumerable(Of T) ' IEnumerable(Of T).Uniques As IEnumerable(Of T) #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Imports System.Runtime.CompilerServices #End Region #Region " IEnumerableUtil " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with an <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Module IEnumerableExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Get All Duplicates. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0} ''' Debug.WriteLine(String.Join(", ", col.Duplicates)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets all the duplicated values of the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of T)"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function Duplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T) Return sender.GroupBy(Function(value As T) value). Where(Function(group As IGrouping(Of T, T)) group.Count > 1). SelectMany(Function(group As IGrouping(Of T, T)) group) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Get Unique Duplicates. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0} ''' Debug.WriteLine(String.Join(", ", col.UniqueDuplicates)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the unique duplicated values of the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of T)"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function UniqueDuplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T) Return sender.GroupBy(Function(value As T) value). Where(Function(group As IGrouping(Of T, T)) group.Count > 1). Select(Function(group As IGrouping(Of T, T)) group.Key) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Get Unique Values. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0} ''' Debug.WriteLine(String.Join(", ", col.Uniques)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the unique values of the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of T)"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function Uniques(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T) Return sender.Except(IEnumerableExtensions.UniqueDuplicates(sender)) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Remove Duplicates. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0} ''' Debug.WriteLine(String.Join(", ", col.RemoveDuplicates)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes duplicated values in the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of T)"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function RemoveDuplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T) Return sender.Distinct End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Split Collection Into Number Of Parts. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0} ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoParts(amount:=2) ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer)) ''' Debug.WriteLine(String.Join(", ", col)) ''' End Sub) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Splits the source <see cref="IEnumerable(Of T)"/> into the specified amount of secuences. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ''' <param name="amount"> ''' The target amount of secuences. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function SplitIntoParts(Of T)(ByVal sender As IEnumerable(Of T), ByVal amount As Integer) As IEnumerable(Of IEnumerable(Of T)) If (amount = 0) OrElse (amount > sender.Count) OrElse (sender.Count Mod amount <> 0) Then Throw New ArgumentOutOfRangeException(paramName:="amount", message:="value should be greater than '0', smallest than 'col.Count', and multiplier of 'col.Count'.") End If Dim chunkSize As Integer = CInt(Math.Ceiling(sender.Count() / amount)) Return From index As Integer In Enumerable.Range(0, amount) Select sender.Skip(chunkSize * index).Take(chunkSize) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Split Collection Into Number Of Elements. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9} ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoNumberOfElements(amount:=4) ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer)) ''' Debug.WriteLine(String.Join(", ", col)) ''' End Sub) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Splits the source <see cref="IEnumerable(Of T)"/> into secuences with the specified amount of elements. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ''' <param name="amount"> ''' The target amount of elements. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function SplitIntoNumberOfElements(Of T)(ByVal sender As IEnumerable(Of T), ByVal amount As Integer) As IEnumerable(Of IEnumerable(Of T)) Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(sender.Count() / amount))) Select sender.Skip(index * amount).Take(amount) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Split Collection Into Number Of Elements. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9} ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoNumberOfElements(amount:=4, fillEmpty:=True, valueToFill:=0) ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer)) ''' Debug.WriteLine(String.Join(", ", col)) ''' End Sub) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Splits the source <see cref="IEnumerable(Of T)"/> into secuences with the specified amount of elements. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ''' <param name="amount"> ''' The target amount of elements. ''' </param> ''' ''' <param name="fillEmpty"> ''' If set to <c>true</c>, generates empty elements to fill the last secuence's part amount. ''' </param> ''' ''' <param name="valueToFill"> ''' An optional value used to fill the last secuence's part amount. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function SplitIntoNumberOfElements(Of T)(ByVal sender As IEnumerable(Of T), ByVal amount As Integer, ByVal fillEmpty As Boolean, Optional valueToFill As T = Nothing) As IEnumerable(Of IEnumerable(Of T)) Return (From count As Integer In Enumerable.Range(0, CInt(Math.Ceiling(sender.Count() / amount)))). Select(Function(count) Select Case fillEmpty Case True If (sender.Count - (count * amount)) >= amount Then Return sender.Skip(count * amount).Take(amount) Else Return sender.Skip(count * amount).Take(amount). Concat(Enumerable.Repeat(Of T)( valueToFill, amount - (sender.Count() - (count * amount)))) End If Case Else Return sender.Skip(count * amount).Take(amount) End Select End Function) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Randomize Collection. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9} ''' Debug.WriteLine(String.Join(", ", col.Randomize)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Randomizes the elements of the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collection. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of T)"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function Randomize(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T) Dim rand As New Random Return From item As T In sender Order By rand.Next End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Concatenate Multiple Collections. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col1 As IEnumerable(Of Integer) = {1, 2, 3} ''' Dim col2 As IEnumerable(Of Integer) = {4, 5, 6} ''' Dim col3 As IEnumerable(Of Integer) = {7, 8, 9} ''' Debug.WriteLine(String.Join(", ", {col1, col2, col3}.ConcatMultiple)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Concatenates multiple <see cref="IEnumerable(Of T)"/> at once into a single <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source collections. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="IEnumerable(Of T)"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function ConcatMultiple(Of T)(ByVal sender As IEnumerable(Of T)()) As IEnumerable(Of T) Return sender.SelectMany(Function(col As IEnumerable(Of T)) col) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Join Multiple Collections Into Single String. ''' Author: Elektro ''' Date : 08-March-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim col1 As IEnumerable(Of Integer) = {1, 2, 3} ''' Dim col2 As IEnumerable(Of Integer) = {4, 5, 6} ''' Dim col3 As IEnumerable(Of Integer) = {7, 8, 9} ''' Debug.WriteLine({col1, col2, col3}.StringJoin(", "))) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Joins multiple <see cref="IEnumerable(Of T)"/> at once into a single string. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="separator"> ''' The string to use as a separator. ''' </param> ''' ''' <param name="sender"> ''' The source collections. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see cref="String"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function StringJoin(Of T)(ByVal sender As IEnumerable(Of T)(), ByVal separator As String) As String Dim sb As New System.Text.StringBuilder For Each col As IEnumerable(Of T) In sender sb.Append(String.Join(separator, col) & separator) Next col Return sb.Remove(sb.Length - separator.Length, separator.Length).ToString End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Count empty items of collection. ''' Author: Elektro ''' Date : 16-June-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> ''' Dim emptyItemCount As Integer = {"Hello", " ", "World!"}.CountEmptyItems ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Counts the empty items of the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="sender"> ''' The source <see cref="IEnumerable(Of T)"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The total amount of empty items. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function CountEmptyItems(Of T)(ByVal sender As IEnumerable(Of T)) As Integer Return (From item As T In sender Where (item.Equals(Nothing))).Count End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Count non-empty items of collection. ''' Author: Elektro ''' Date : 16-June-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> ''' Dim nonEmptyItemCount As Integer = {"Hello", " ", "World!"}.CountNonEmptyItems ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Counts the non-empty items of the source <see cref="IEnumerable(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="sender"> ''' The source <see cref="IEnumerable(Of T)"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The total amount of non-empty items. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function CountNonEmptyItems(Of T)(ByVal sender As IEnumerable(Of T)) As Integer Return (sender.Count - IEnumerableExtensions.CountEmptyItems(sender)) End Function End Module #End Region
IEnumerable(Of String) Extensions, cómo su propio nombre indica, expone varias extensiones de método para utilizarlas con una colección de strings. Las extensiones son las siguiente, si alguna no es lo suficientemente aclaratoria entonces pueden usar IntelliSense o el ObjectInspector para conocer el propósito de cada una: IEnumerable(Of String).BubbleSort As IEnumerable(Of String) IEnumerable(Of String).CountEmptyItems As Integer IEnumerable(Of String).CountNonEmptyItems As Integer IEnumerable(Of String).FindByContains(String, Boolean) As IEnumerable(Of String) IEnumerable(Of String).FindByLike(String, Boolean) As IEnumerable(Of String) IEnumerable(Of String).FindExact(String, StringComparison) As IEnumerable(Of String) IEnumerable(Of String).RemoveByContains(String, Boolean) As IEnumerable(Of String) IEnumerable(Of String).RemoveByLike(String, Boolean) As IEnumerable(Of String) IEnumerable(Of String).RemoveExact(String, StringComparison) As IEnumerable(Of String)
Puse ejemplos de uso para cada extensión en la documentación XML del código fuente. Source: http://pastebin.com/6XfLcMj8 Array Extensions, cómo su propio nombre indica, expone extensiones de método para utilizarlas con Arays. Aunque realmente, por el momento solo puse una extensión, pero de igual modo comparto el código para que puedan extender su funcionalidad o tomar la idea como base. La extensión es la siguiente, sirve para redimensionar el tamaño del array de forma automatizada y más veloz que la habitual. T().Resize As T()
Source: ' *********************************************************************** ' Author : Elektro ' Modified : 10-September-2015 ' *********************************************************************** ' <copyright file="Array Extensions.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' T().Resize As T() #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System Imports System.Diagnostics Imports System.Runtime.CompilerServices #End Region ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with an <see cref="Array"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Module ArrayExtensions #Region " Public Extension Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Resize Array. ''' Author: Elektro ''' Date : 10-September-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim myArray(50) As Integer ''' Console.WriteLine(String.Format("{0,-12}: {1}", "Initial Size", myArray.Length)) ''' ''' myArray = myArray.Resize(myArray.Length - 51) ''' Console.WriteLine(String.Format("{0,-12}: {1}", "New Size", myArray.Length)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Resizes the number of elements of the source <see cref="Array"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sender"> ''' The source <see cref="Array"/>. ''' </param> ''' ''' <param name="newSize"> ''' The new size. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resized <see cref="Array"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="System.ArgumentOutOfRangeException"> ''' newSize;Non-negative number required ''' </exception> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> <Extension> Public Function Resize(Of T)(ByVal sender As T(), ByVal newSize As Integer) As T() If (newSize <= 0) Then Throw New System.ArgumentOutOfRangeException(paramName:="newSize", message:="Value greater than 0 is required.") End If Dim preserveLength As Integer = Math.Min(sender.Length, newSize) If (preserveLength > 0) Then Dim newArray As Array = Array.CreateInstance(sender.GetType.GetElementType, newSize) Array.Copy(sender, newArray, preserveLength) Return DirectCast(newArray, T()) Else Return sender End If End Function #End Region End Module
|
|
|
|
|
4853
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
|
en: 19 Septiembre 2015, 09:20 am
|
NetworkUtil.vb, esta class expone varias funcionalidades relacionadas con los adaptadores de red, desde un evento compartido, NetworkUtil.NetworkStatusChanged, el cual se puede utilizar para monitorizar el estado de la conexión, hasta las classes NetworkUtil.NetworkTrafficMonitor, y NetworkUtil.ProcessTrafficMonitor
que, con sus respectivos eventos a los que uno se puede suscribir, sirven para monitorizar el consumo de tráfico de una red, o el de un proces en particular. Realmente tiene poco más que lo que acabo de mencionar xD. Source: http://pastebin.com/byCZSqGcEjemplo para monitorizar el estado de la red: Public Class Form1 Private Sub Form1_Shown() Handles MyBase.Load AddHandler NetworkUtil.NetworkStatusChanged, AddressOf DoNetworkStatusChanged End Sub Private Sub DoNetworkStatusChanged(ByVal sender As Object, e As NetworkUtil.NetworkStatusChangedArgs) If e.IsAvailable Then Console.WriteLine("Network is available.") Else Console.WriteLine("Network is not available.") End If End Sub End Class
Ejemplo para monitorizar el tráfico de red: Public NotInheritable Class Form1 : Inherits Form Dim WithEvents netMon As NetworkUtil.NetworkTrafficMonitor Private Sub Form1_Load() Handles MyBase.Load Me.netMon = New NetworkUtil.NetworkTrafficMonitor(NetworkUtil.NetworkTrafficMonitor.GetAvaliableInterfaceNames.First) Me.netMon.UpdateBehavior = NetworkUtil.NetworkTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick Me.netMon.UpdateInterval = 1000 ' 1 sec Me.netMon.Start() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Handles the <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChanged"/> event of the netMon instance. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="sender">T ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data. ''' </param> ''' ---------------------------------------------------------------------------------------------------- Private Sub NetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs) _ Handles netMon.TrafficChanged Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2")) Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2")) Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2")) Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2")) End Sub Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click Dim url As String = "http://download.thinkbroadband.com/10MB.zip" Dim client As New WebClient() client.DownloadFileAsync(New Uri(url), Path.GetTempFileName()) End Sub Private Sub BtPauseMon_Click() Handles BtPauseMon.Click If Me.netMon.IsActive Then Me.netMon.Stop() Else Me.netMon.Start() End If End Sub End Class
Ejemplo para monitorizar el tráfico de una aplicación .Net (que tenga los contadores de rendimiento habilitados): Public NotInheritable Class Form1 : Inherits Form Dim WithEvents procNetMon As NetworkUtil.ProcessTrafficMonitor Private Sub Form1_Load() Handles MyBase.Load Me.procNetMon = New NetworkUtil.ProcessTrafficMonitor(Process.GetCurrentProcess.Id) Me.procNetMon.UpdateBehavior = NetworkUtil.ProcessTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick Me.procNetMon.UpdateInterval = 1000 ' 1 sec Me.procNetMon.Start() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Handles the <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChanged"/> event of the procNetMon instance. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="sender">T ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data. ''' </param> ''' ----------------------------------------------------------------------------------------------------- Private Sub ProcNetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs) _ Handles procNetMon.TrafficChanged Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2")) Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2")) Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2")) Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2")) End Sub Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click Dim url As String = "http://download.thinkbroadband.com/10MB.zip" Dim client As New WebClient() client.DownloadFileAsync(New Uri(url), Path.GetTempFileName()) End Sub Private Sub BtPauseMon_Click() Handles BtPauseMon.Click If Me.procNetMon.IsActive Then Me.procNetMon.Stop() Else Me.procNetMon.Start() End If End Sub End Class
|
|
|
|
|
4854
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
|
en: 19 Septiembre 2015, 09:11 am
|
AppConfigUtil, es una class que expone un simple parser de uso genérico para comprovar el valor de una propiedad declarada en la configuración de aplicación (appconfig), el cual no he optimizado para los tipos de estructura del árbol de nodos del appconfig ...podría ser ineficiente en ciertos escenarios, pero es un comienzo. Por ejemplo, para saber si los contadores de rendimientos están activados en el appconfig de una aplicación .Net, lo podriamos utilizar de la siguiente manera: Dim isPerfCountersEnabled As boolean = GetAppConfigSetting(Of Boolean)("system.net", "settings", "performanceCounters", "enabled")
O utilizar el método IsPerformanceCountersEnabled definido expresamente para esa labor. Source: ' *********************************************************************** ' Author : Elektro ' Modified : 18-September-2015 ' *********************************************************************** ' <copyright file="AppConfigUtil.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' GetAppConfigSetting(Of T)(String, String, String, String, Optional:String) As T ' GetAppConfigSetting(Of T)(String, String, String, String) As T ' IsPerformanceCountersEnabled(Optional:String) As Boolean #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System Imports System.Configuration Imports System.Linq Imports System.Net.Configuration #End Region #Region " AppConfig Util " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains related AppConfig utilities. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public NotInheritable Class AppConfigUtil #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the value of a setting declared in the application configuration file (app.config) ''' of the specified application. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code> ''' Dim isPerfCountersEnabled As boolean = GetAppConfigSetting(Of Boolean)("system.net", "settings", "performanceCounters", "enabled") ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sectionGroupName"> ''' The name of the section group. ''' </param> ''' ''' <param name="sectionName"> ''' The name of the section. ''' </param> ''' ''' <param name="elementName"> ''' The name of the element. ''' </param> ''' ''' <param name="propertyName"> ''' The name of the property. ''' </param> ''' ''' <param name="exePath"> ''' The executable path of the current or an external .Net application. ''' If any path is specified, it assumes the current application. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' If the SectionGroup, the Section, the Element, or the Property doesn't exist, the return value is <see langword="Nothing"/>, ''' otherwise, the value. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Function GetAppConfigSetting(Of T)(ByVal sectionGroupName As String, ByVal sectionName As String, ByVal elementName As String, ByVal propertyName As String, Optional ByVal exePath As String = "") As T Dim appConfig As Configuration Dim group As ConfigurationSectionGroup Dim section As ConfigurationSection Dim sectionPropInfo As PropertyInformation Dim element As ConfigurationElement Dim elementPropInfo As PropertyInformation If Not String.IsNullOrEmpty(exePath) Then appConfig = ConfigurationManager.OpenExeConfiguration(exePath) Else appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) End If group = appConfig.GetSectionGroup(sectionGroupName) If group Is Nothing Then Return Nothing End If section = group.Sections(sectionName) If section Is Nothing Then Return Nothing End If sectionPropInfo = section.ElementInformation.Properties(elementName) If sectionPropInfo Is Nothing Then Return Nothing End If element = DirectCast(sectionPropInfo.Value, ConfigurationElement) If element Is Nothing Then Return Nothing End If elementPropInfo = element.ElementInformation.Properties(propertyName) If elementPropInfo Is Nothing Then Return Nothing End If Return DirectCast(elementPropInfo.Value, T) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the value of a setting declared in the application configuration file (app.config) ''' of the specified application. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' </typeparam> ''' ''' <param name="sectionName"> ''' The name of the section. ''' </param> ''' ''' <param name="elementName"> ''' The name of the element. ''' </param> ''' ''' <param name="propertyName"> ''' The name of the property. ''' </param> ''' ''' <param name="exePath"> ''' The executable path of the current or an external .Net application. ''' If any path is specified, it assumes the current application. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' If the Section, the Element, or the Property doesn't exist, the return value is <see langword="Nothing"/>, ''' otherwise, the value. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Function GetAppConfigSetting(Of T)(ByVal sectionName As String, ByVal elementName As String, ByVal propertyName As String, Optional ByVal exePath As String = "") As T Dim appConfig As Configuration Dim section As ConfigurationSection Dim sectionPropInfo As PropertyInformation Dim element As ConfigurationElement Dim elementPropInfo As PropertyInformation If Not String.IsNullOrEmpty(exePath) Then appConfig = ConfigurationManager.OpenExeConfiguration(exePath) Else appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) End If section = appConfig.GetSection(sectionName) If section Is Nothing Then Return Nothing End If sectionPropInfo = section.ElementInformation.Properties(elementName) If sectionPropInfo Is Nothing Then Return Nothing End If element = DirectCast(sectionPropInfo.Value, ConfigurationElement) If element Is Nothing Then Return Nothing End If elementPropInfo = element.ElementInformation.Properties(propertyName) If elementPropInfo Is Nothing Then Return Nothing End If Return DirectCast(elementPropInfo.Value, T) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the performance counters feature is enabled in the application configuration file (app.config) ''' of the specified application. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="exePath"> ''' The executable path of the current or an external .Net application. ''' If any path is specified, it assumes the current application. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' Returns <see langword="False"/> if the performance counters feature is disabled or if the "system.net" section is not defined; ''' otherwise, <see langword="True"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <DebuggerHidden> Public Shared Function IsPerformanceCountersEnabled(Optional ByVal exePath As String = "") As Boolean Dim appConfig As Configuration Dim group As NetSectionGroup If Not String.IsNullOrEmpty(exePath) Then appConfig = ConfigurationManager.OpenExeConfiguration(exePath) Else appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) End If group = DirectCast(appConfig.GetSectionGroup("system.net"), NetSectionGroup) Return (group IsNot Nothing AndAlso group.Settings.PerformanceCounters.Enabled) End Function #End Region End Class #End Region
|
|
|
|
|
4855
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
|
en: 19 Septiembre 2015, 09:01 am
|
Despues de un tiempo sin actualizar, volvemos a la carga con un par de snippets.
Ejemplo de uso de la librería CodeScales: http://www.codescales.com/Es un simple, muy simple cliente http que encapsula el código/miembros necesarios de la librería de classes de .Net para realizar peticiones Post con MultiPart, y otras, de forma muy sencilla: ' ********************* ' Get Method ' http://www.google.com ' ********************* ' ' Dim client As New HttpClient ' Dim getMethod As New HttpGet(New Uri("http://www.google.com/search")) ' ' With getMethod ' .Parameters.Add("q", "Hello") ' .Parameters.Add("lr", "lang_en") ' End With ' ' Dim response As HttpResponse = client.Execute(getMethod) ' Dim text As String = EntityUtils.ToString(response.Entity) ' ************************** ' Post Method with MultiPart ' http://9kw.eu/ ' ************************** ' ' Dim apiKey As String = "XXXXXXXXXXXX" ' Dim filepath As String = "C:\File.png" ' ' Dim client As New HttpClient ' Dim postMethod As New HttpPost(New Uri("http://www.9kw.eu/index.cgi")) ' ' Dim multipartEntity As New MultipartEntity ' postMethod.Entity = multipartEntity ' ' With multipartEntity ' .AddBody(New StringBody(Encoding.UTF8, "apikey", apiKey)) ' .AddBody(New StringBody(Encoding.UTF8, "action", "usercaptchaupload")) ' .AddBody(New StringBody(Encoding.UTF8, "source", "vbapi")) ' End With ' ' Dim fileBody As New FileBody("file-upload-01", filepath, New IO.FileInfo(filepath)) ' multipartEntity.AddBody(fileBody) ' ' Dim response As HttpResponse = client.Execute(postMethod) ' Dim text As String = EntityUtils.ToString(response.Entity)
9KW Captcha Helper http://9kw.eu/(veanse otros ejemplos de uso en el apartado de la API en la página oficial) Es una class para utilizar el servicio de solución de captchas de 9KW. Este servicio es de pago, se necesita una API key para podr utilizarlo. Por el momento cumple las dos labores más esenciales, la función GetCredits devuelve los créditos actuales del usuario, y el método SolveCaptcha soluciona el captcha especificado. ' *********************************************************************** ' Author : Elektro ' Modified : 18-September-2015 ' *********************************************************************** ' <copyright file="KWCaptchaHelper.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Public Members Summary " #Region " Properties " ' KWCaptchaHelper.ApiKey As String #End Region #Region " Functions " ' KWCaptchaHelper.GetCredits As String #End Region #Region " Methods " ' KWCaptchaHelper.SolveCaptcha(String) #End Region #End Region #Region " Usage Examples " ' Dim captchaSolver As New KWCaptchaHelper(apiKey:="XXXXXXXXXXXXXXXXXXX") ' Dim imagePath As String = "C:\captcha.png" ' Dim result As String = String.Empty ' Console.WriteLine(String.Format("User Credits: {0}", captchaSolver.GetCredits())) ' Console.WriteLine(String.Format("Captcha Img.: {0}", imagePath)) ' Console.WriteLine("Solving Captcha, please wait...") ' result = captchaSolver.SolveCaptcha(imagePath) ' Console.WriteLine(String.Format("Result: {0}", result)) 'Console.ReadKey() #End Region #Region " Imports " Imports CodeScales.Http Imports CodeScales.Http.Entity Imports CodeScales.Http.Methods Imports CodeScales.Http.Entity.Mime Imports System Imports System.IO Imports System.Linq Imports System.Text Imports System.Threading #End Region #Region " KWCaptchaHelper " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' 9KW Captcha service. Helper Class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Visit <see href="http://9kw.eu/"/> for further info. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public NotInheritable Class KWCaptchaHelper #Region " Properties " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the 9KW's API user key. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The 9KW's API user key. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public ReadOnly Property ApiKey As String Get Return Me.apiKeyB End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' ( Backing field ) ''' The 9KW's API user key. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private ReadOnly apiKeyB As String #End Region #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Initializes a new instance of the <see cref="KWCaptchaHelper"/> class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="apiKey"> ''' The 9KW's API user key. ''' </param> ''' ---------------------------------------------------------------------------------------------------- Public Sub New(ByVal apiKey As String) Me.apiKeyB = apiKey End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="KWCaptchaHelper"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Sub New() End Sub #End Region #Region " Private Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="data"> ''' The data. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' System.String. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Private Function Get9kwApi(ByVal data As String) As String Return Me.Get9kwHttp(String.Format("http://www.9kw.eu/index.cgi?source=vbapi&debug=0&apikey={0}&action=" & data, Me.apiKeyB)) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="url"> ''' The URL. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' System.String. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Private Function Get9kwHttp(ByVal url As String) As String Dim httpClient As New HttpClient Dim httpGet As New HttpGet(New Uri(url)) Dim httpResponse As HttpResponse = httpClient.Execute(httpGet) Return EntityUtils.ToString(httpResponse.Entity) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="data"> ''' The data. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' System.String. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Private Function Get9kwApiUpload(ByVal data As String) As String Dim client As New HttpClient Dim postMethod As New HttpPost(New Uri("http://www.9kw.eu/index.cgi")) Dim multipartEntity As New MultipartEntity postMethod.Entity = multipartEntity Dim stringBody As New StringBody(Encoding.UTF8, "apikey", Me.apiKeyB) multipartEntity.AddBody(stringBody) Dim stringBody3 As New StringBody(Encoding.UTF8, "source", "vbapi") multipartEntity.AddBody(stringBody3) Dim stringBody2 As New StringBody(Encoding.UTF8, "action", "usercaptchaupload") multipartEntity.AddBody(stringBody2) Dim fileInfo As New FileInfo(data) Dim fileBody As New FileBody("file-upload-01", data, fileInfo) multipartEntity.AddBody(fileBody) Dim response As HttpResponse = client.Execute(postMethod) Return EntityUtils.ToString(response.Entity) End Function #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the current remaining credits. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The current remaining credits. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Function GetCredits() As String Return Me.Get9kwApi("usercaptchaguthaben") End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Solves the specified captcha image. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="imagePath"> ''' The image path. ''' </param> ''' ''' <param name="checkInterval"> ''' The interval to check whether the captcha is solved. ''' </param> ''' ''' <param name="totalTries"> ''' The total intents. ( <paramref name="totalTries"/> * <paramref name="checkInterval"/> ). ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The solved text. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Function SolveCaptcha(ByVal imagePath As String, Optional ByVal checkInterval As Integer = 2000, Optional ByVal totalTries As Integer = 100) As String Dim newCaptchaID As String = Me.Get9kwApiUpload(imagePath) Dim checkdata As String = String.Empty Dim counter As Integer = 0 Do Until Not String.IsNullOrEmpty(checkdata) If Interlocked.Increment(counter) = totalTries Then Exit Do Else Thread.Sleep(checkInterval) End If checkdata = Me.Get9kwApi("usercaptchacorrectdata&id=" & newCaptchaID) Loop Return checkdata End Function #End Region End Class #End Region
|
|
|
|
|
4857
|
Foros Generales / Foro Libre / Re: Re: Señores, los chinos nos llevan AÑOS de ventaja
|
en: 19 Septiembre 2015, 08:32 am
|
Así que, pitoloko, creo que deberías replantearte tu modo de vida, sino seguirás sin novia y morirás virgen. Ay, ¡qué facil es juzgar a la gente sin conocerla!, tolay. No soy un sex symbol, eso está claro, pero a mis 29 años ya he tenido bastantes más novias y rollos de una semana o de una noche en discotecas de las que probablemente tu tendrás, la razón es simple, achacas lo contrario mientras que yo siempre he sabido buscármelas, e incluso me casé (casi 2 veces), tontito, ahora estoy divorciado, se lo que son las relaciones y lo que implican por ese motivo no me apetece más que un tipo de relación (la sexual). Y si, por que no decirlo también, a mi no me importa que los demás caigan en la hipocresía con tópicos machistas, sexuales o demás, pero yo he tenido la ocasión de estar con prostitutas (precisamente asiáticas, españolas nunca), más de una vez, tanto solo y con amigos (los cuales son mucho más agraciados que yo ligando), por disfrutar "la cultura", es algo normal. Intenta ver la realidad de alguien que habla con conoimiento de causa y que solo está dando una opinión crítica, que prejuzgar comparando con un abuelete que se queja por todo sin argumentos. Y mira, ya me has hecho hablar cuando dije que era el fin de mi opinión respecto a este tema, pero es que no se que cojones tienes que juzgar de los demás haciéndolo con tono ofensivo, así te irá muy mal. ¿Qué, te ha interesado mi vida? ...¿no?, pues entonces no vayas intentando provocar calificando a la gente por un juicio incorrecto sin conocerlos. El próximo comentario que haga alusiones a la vida personal sexual o de noviazgo o de lo que sea hacia otra persona, será censurado. Por favor, hablen de los chinos y sus costumbres, que ese es el tema. Dejen a un lado prejuicios.Saludos!
|
|
|
|
|
4858
|
Foros Generales / Foro Libre / Re: Señores, los chinos nos llevan AÑOS de ventaja
|
en: 18 Septiembre 2015, 20:51 pm
|
Y sera que cada vez que entran esas azafatas buenotas a la cabina de los aviones, los pilotos pierden la concentración y por eso se caen los aviones???... Pero las azafatas están ejerciendo su trabajo, mientras que las "cheerleaders" (por no llamarlas señoritas de compañia en el caso de la oficina) estarian zorreando sin querer hacerlo (calentando los bajos de los empleados...), y eso desconcentra, vaya. A mi me parece que es MUY distinto. Traducción de "mejora de la eficiencia" : están mas tiempo en la oficina. Claro que pasarían más tiempo en la oficina, pero más que para trabajar para ver si pueden mojar el churro  . Recordemos que no se habla precisamente de pausas de los trabajadores para ir a una zona de entretenimiento (al parecer), sino de mujeres deambulando por la oficina constantemente que, además de pasearse por ahí mostrándo todos sus pares de encantos, de tanto en cuanto también harían actividades "sociales" para desestresar, vamos, para desconcentrar. Que lo llamen "cheerleaders" o como quieran pero eso son Geishas modernas adoptadas del estilo japonés ...sin maquillaje, tan simple como eso. PD: Fin de mi opinión respecto a esto xD. Saludos!
|
|
|
|
|
4859
|
Foros Generales / Foro Libre / Re: Señores, los chinos nos llevan AÑOS de ventaja
|
en: 18 Septiembre 2015, 15:33 pm
|
Elektro que se vaya a programar a un monasterio budista (se que se baña en la playa con pantalón y camisa)... yo me quedo programando con las chinitas esas... jejejejeeee... lastima que no tengo ni idea de como programar, pero por unas chinas así puedo aprender... Imaginemos que una compañia que fabrica productos alimenticios, o albañiles que estén construyendo un edificio, o coches o aviones donde el factor humano necesario en la fábrica sea de un 80%, o cualquier otro oficio que se nos ocurra, pues van y les parezca una buena idea empezar a contratar a "animadoras" para subir la moral y la productividad de sus empleados al fabricar el producto (ilusos...), bien, sabiendo como somos los hombres, los empleados estarían pensando más en otras cosas que en asegurarse de que el producto sea de calidad. Creo que esto es indiscutible, el porcentajo de "fallos humanos" aumentaría con creces. ¿Tú te arriesgarías a comprar un coche de esa compañia que tiene unos controles de seguridad más que dudosos?, yo por supuesto no lo haría. Pues así con la programación lo mismo (calidad de software, compañias que contraten servicios web, etc, lo que tú quieras poner cómo ejemplo). Quizás exagero un poco, pero si esa "moda" se empieza a extender entre los distintos oficios y oficinas de todo el mundo ...al final acabariamos con productos mediocres, lamentables, y peligrosos en algunos casos. Yo solo digo eso. Si a mi me pones unas asiáticas en una playa, te diría todo lo contrario. Saludos!
|
|
|
|
|
4860
|
Foros Generales / Foro Libre / Re: Señores, los chinos nos llevan AÑOS de ventaja
|
en: 18 Septiembre 2015, 13:46 pm
|
1. La programación requiere completa concentración en lo que haces, hasta el zumbido de una mosca puede estropear ideas espontaneas que surgen durante el desarrollo, por ende, lo que cuentan en la imagen es más falso que una moneda de 10€, yo no me creo que mujeres tan provocativas y sexys cómo la de la última imagen, que solo por mirarla ya se te empalma hasta el día siguiente, pues no me creo que poner a chicas así desfilando en la oficina sea un método eficiente para aumentar la productividad de los empleados, sino más bien para todo lo contrario, ¿pero a quien quieren engañar?, y mucho menos si son chinos salidos, ¿salidos dije?, si, un tópico pero bien real ...ya que su sociedad parece estar "reprimida sexualmente" (aunque realmente yo no he ido a China para comprobarlo, pero todos lo hemos visto muchas veces en la TV/Documentales) así que tal vez todo eso de lucir mujeres con pechos grandes simplemente sea una excusa para saciar su sed de erotismo, para pasarlo bien y nada más, normal que digan que la idea es buena y demás (¿qué hombre diria lo contrario si le llenan su oficina de teens con escotes y minifaldas?), ya pueden inventar lo que quieran diciendo que ahora son más productivos... ja!. 2. No me estoy quejando, ya me gustaría a mi trabajar así (aunque poco iba a trabajar entonces) simplemente digo la verdad sobre algo que en la imagen pretenden transmitir como una idea prometedera y productiva, cuando es una simple excusa para seguir haciendo lo que hacen, una imagen con unos comentarios muy estúpidos y falsos. A ver quien iba a ser capaz de hacer un trabajo bien hecho con "animadoras" paseando el culo por su cara cada 5 minutos y haciendo grupitos para pegarse unos karaokes o tomarse unos chupitos con ellas, ¡en fin!, 3. Las feminazis tienen que estar muy, pero que muy contentas con esto...  . Saludos!
|
|
|
|
|
|
| |
|