zzzprojects / z.extensionmethods Goto Github PK
View Code? Open in Web Editor NEWC# Extension Methods | Over 1000 extension methods:
Home Page: https://csharp-extension.com
License: MIT License
C# Extension Methods | Over 1000 extension methods:
Home Page: https://csharp-extension.com
License: MIT License
Is there a reason you decided not to use namespaces?
The good is that the extension methods are available everywhere but the bad is that the take precedence over methods with the same name, even if that's not what you want (when using the RavenDB Linq extension methods for instance).
Sometimes you may want to skip the lines in a file when reading from it with a StreamReader
so having a SkipLines()
method would be super helpful.
public static class StreamReaderExtensions
{
/// <summary>
/// Skips the specified number of lines in a stream reader based on its current position.
/// </summary>
/// <param name="streamReader">The stream reader.</param>
/// <param name="skipCount">The number of lines to skip.</param>
private static void SkipLines(this StreamReader streamReader, int skipCount)
{
for (var i = 0; i < skipCount && !streamReader.EndOfStream; i++)
{
streamReader.ReadLine();
}
}
}
The String - NotIn
documentation (https://csharp-extension.com/en/method/1002063/string-notin) is showing the implementation for the String - In
method and the View Source link is pointing to the same incorrect source @ String.In, but should point to String.NotIn
Just FYI your "Type.GetDeclaration()" extension fails for nested generic types. Example:
class A
{
class B<D>
{
class C<E> { }
}
}
typeof(A.B<int>.C<string>).GetDeclaration();
It currently throws an InvalidOperationException
.
I'm not sure what you would want to do in these cases since it is a nested type and the declaration requires the parent type as well. In my opinion it should probably return the declaration for only that nested class (and not the parents)... But that is up to you of course.
At a minimum you should probably throw a custom ArgumentException
with a custom message.
If you remove types:
typeof(A.B<>.C<>).GetDeclaration()
It returns
"C<D, E>"
And that is definitely incorrect.
The page for String.Copy()
shows the wrong source.
The source shown is for String.Concat()
This issue is a proposal to add SplitOnChunkSize()
to FileInfo that would split a file into multiple files and return an array of the newly created files. The challenge with this one will be handling line breaks if the breakOnNewlines
is true and also taking into account large files means buffering a chunk of data at a time so as not to overload system resources.
/// <summary>
/// Splits a file into multiple files based on the specified chunk size of each file.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="chunkSize">The maximum number of bytes to store in each file.
/// If a chunk size is not provided, files will be split into 1 MB chunks by default.
/// The breakOnNewlines parameter can slightly affect the size of each file.</param>
/// <param name="targetPath">The destination where the split files will be saved.</param>
/// <param name="deleteAfterSplit">if set to <c>true</c>, the original file is deleted after creating the newly split files.</param>
/// <param name="breakOnNewlines">if set to <c>true</c> break the file on the next newline once the chunk size limit is reached.</param>
/// <returns>
/// An array of references to the split files.
/// </returns>
/// <exception cref="ArgumentNullException">file</exception>
/// <exception cref="ArgumentOutOfRangeException">chunkSize - The chunk size must be larger than 0 bytes.</exception>
public static FileInfo[] SplitOnChunkSize(
this FileInfo file,
int chunkSize = 1000000,
DirectoryInfo targetPath = null,
bool deleteAfterSplit = false,
bool breakOnNewlines = true
)
{
if (file == null)
throw new ArgumentNullException(nameof(file));
if (chunkSize < 1)
throw new ArgumentOutOfRangeException(nameof(chunkSize), chunkSize,
"The chunk size must be larger than 0 bytes.");
if (file.Length <= chunkSize)
return new[] {file};
var buffer = new byte[chunkSize];
var extraBuffer = new List<byte>();
targetPath = targetPath ?? file.Directory;
var chunkedFiles = new List<FileInfo>((int)Math.Abs(file.Length / chunkSize) + 1);
using (var input = file.OpenRead())
{
var index = 1;
while (input.Position < input.Length)
{
var chunkFileName = new FileInfo(Path.Combine(targetPath.FullName, $"{file.Name}.CHUNK_{index++}"));
chunkedFiles.Add(chunkFileName);
using (var output = chunkFileName.Create())
{
var chunkBytesRead = 0;
while (chunkBytesRead < chunkSize)
{
var bytesRead = input.Read(buffer,
chunkBytesRead,
chunkSize - chunkBytesRead);
if (bytesRead == 0)
{
break;
}
chunkBytesRead += bytesRead;
}
if (breakOnNewlines)
{
var extraByte = buffer[chunkSize - 1];
while (extraByte != '\n')
{
var flag = input.ReadByte();
if (flag == -1)
break;
extraByte = (byte)flag;
extraBuffer.Add(extraByte);
}
output.Write(buffer, 0, chunkBytesRead);
if (extraBuffer.Count > 0)
output.Write(extraBuffer.ToArray(), 0, extraBuffer.Count);
extraBuffer.Clear();
}
}
}
}
if (deleteAfterSplit)
file.Delete();
return chunkedFiles.ToArray();
}
Hi,
I upgraded to .net 5.0 and found "BinaryFormatter serialization and deserialization are disabled" in aspnet core.
the DeepClone method throws exception.
BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.
/// <summary>
/// Filters a sequence of values based on a predicate if the judgement is matched.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">An <see cref="IQueryable{T}"/> to filter.</param>
/// <param name="judgement">The judgement to decide whether the filter should take affect.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>
/// An <see cref="IQueryable{T}"/> that contains elements from the input sequence that satisfy the condition
/// specified by predicate.
/// </returns>
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool judgement, Expression<Func<TSource, bool>> predicate)
{
if (!judgement)
{
return source;
}
return source.Where(predicate);
}
The following is a proposal to add Z.ExtensionMethods/src/Z.Core/System.String/String.EqualsIgnoreCase.cs
which would contain the following convenience extension method. I miss it from my Java days and the .NET version is too verbose/cumbersome.
public static bool EqualsIgnoreCase(this string @string, string otherString);
https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/src/Z.Core/System.Object/Convert/ToValueType/Object.ToCharOrDefault.cs#L53
Convert.ToChar(null)
will throw a ArgumentNullException
,So no matter the useDefaultIfNull
is true
or false
the defaultValue always return
The comments in the source on the page for String.Concat
are broken. They are missing references to the parameter names (e.g. "The concatenation of and .").
There's no easy way to figure out what is in this package, given all of the overloads. Even disassembly yields too many methods.
I like how MoreLINQ handles this.
Here is what to include in your request to make sure we implement a solution as quickly as possible.
On the page String - PathCombine, the example shown is not valid for the extension method source shown on that same page. The example shows the use of the extension method that extends IEnumerable however the extension source displayed on that page extends string with the optional string[] parameter. If you were to take the code on that page by itself, it would not compile.
Why not write the extension of SqlServer or Oracle?
Shouldn't IsNumeric() return true for "-1"? I mean -1 is really a number so why does IsNumeric() only return true for 0 & positive numbers?
The WebClient
class defines DownloadFileTaskAsync
as:
public Task DownloadFileTaskAsync(string address, string fileName);
Which is nice but it does not return a reference to the file that was downloaded. An extension method like the following would be helpful (possibly good to do for the non-async version as well):
/// <summary>
/// Downloads the specified resource to a local file as an asynchronous operation using a task object.
/// </summary>
/// <param name="webClient">The web client.</param>
/// <param name="address">The URI of the resource to download.</param>
/// <param name="fileName">The name of the file to be placed on the local computer.</param>
/// <returns>
/// Returns <see cref="System.Threading.Tasks.Task"></see>.
/// The task object representing the asynchronous operation.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="address">address</paramref> parameter is null.
/// -or-
/// The <paramref name="fileName">fileName</paramref> parameter is null.</exception>
/// <exception cref="T:System.Net.WebException">The URI formed by combining <see cref="System.Net.WebClient.BaseAddress"></see> and <paramref name="address">address</paramref> is invalid.
/// -or-
/// An error occurred while downloading the resource.</exception>
/// <exception cref="T:System.InvalidOperationException">The local file specified by <paramref name="fileName">fileName</paramref> is in use by another thread.</exception>
public static Task<FileInfo> DownloadFileInfoTaskAsync(this WebClient webClient, string address, string fileName)
{
return webClient.DownloadFileTaskAsync(address, fileName)
.ContinueWith(task => new FileInfo(fileName));
}
I'm having trouble finding any statements on whether you support, or plan to support, .NET Standard / Core moving forward.
I'm getting a compatibility warning in my project though, so I'm guessing Z.ExtensionMethods currently is only for Full Framework, is that right?
String extension method .IsValidEmail() is incorrectly reporting e-mails such as
as invalid. This is a valid RFC e-mail address, and one recommended by Google to alias existing inboxes.
This issue is a proposal to add Count()
to FileInfo to provide the ability to count the total number of lines in a file (no filter specified) or count the specific number of occurrences of a string in a file (using the filter).
/// <summary>
/// Gets the total number of lines in a file.
/// Note this method is optimized for large files and must count each line so it may be expensive for large files.
/// </summary>
/// <param name="this">The file to perform the count on.</param>
/// <param name="filter">If specified, finds the number of concurrences of the string in the file.</param>
/// <returns>
/// A count of the number of lines in the file.
/// </returns>
public static long Count(this FileInfo @this, string filter = null)
{
using (var reader = @this.OpenText())
{
var count = 0L;
if (filter == null)
{
while (!reader.EndOfStream)
{
reader.ReadLine();
count++;
}
}
else
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if(line != null && line.Contains(filter))
count++;
}
}
return count;
}
}
I see the source code has comments on most methods/params, however the packaged/built version doesn't appear to? At least in my Visual Studio, they don't appear in the autocomplete list.
This is the same as #29 but for the GetSigniature extension method.
class A
{
class B<D>
{
class C<E> { }
}
}
typeof(A.B<int>.C<string>).GetSigniature();
typeof(A.B<>.C<>).GetSigniature();
It either throws an InvalidOperationException
or returns too many generics for the nested generic signiature.
I was unable to get ExtractGZipToDirectory()
working. It just created an empty file when I tried to decompress it. I ended up creating this method which did work:
private static FileInfo DecompressGZipFile(this FileInfo compressedFilePath)
{
using (var fs = compressedFilePath.OpenRead())
{
using (var zipStream = new GZipStream(fs, CompressionMode.Decompress))
{
var buffer1 = compressedFilePath.Name.Split('.');
var buffer2 = buffer1[0] + "." + buffer1[1];
var filePath = Path.Combine(compressedFilePath.DirectoryName, buffer2);
using (var fOutStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
var tempBytes = new byte[4096];
int i;
while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0)
{
fOutStream.Write(tempBytes, 0, i);
}
}
return new FileInfo(filePath);
}
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.