GithubHelp home page GithubHelp logo

zzzprojects / z.extensionmethods Goto Github PK

View Code? Open in Web Editor NEW
1.4K 106.0 290.0 6.43 MB

C# Extension Methods | Over 1000 extension methods:

Home Page: https://csharp-extension.com

License: MIT License

C# 64.94% Visual Basic .NET 35.06%
csharp dotnet dotnet-core extensionmethods extension-methods

z.extensionmethods's People

Contributors

adamfisher avatar falwickster avatar jonathanmagnan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

z.extensionmethods's Issues

Lack of namespaces?

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).

Add SkipLines() method for StreamReader

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();
		}
	}
}

GetDeclaration fails on nested generic types

Description

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.

Add SplitOnChunkSize() to FileInfo

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();
}

Please add WhereIf for IQueryable

Description

    /// <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);
    }

Add String.EqualsIgnoreCase() to Z.Core

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);

Example does not match provided source

Here is what to include in your request to make sure we implement a solution as quickly as possible.

1. Description

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.

Negative Numbers & IsNumeric?

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?

Add DownloadFileInfoTaskAsync for WebClient

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));
}

.NET Standard / Core support?

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?

Add Count() to FileInfo

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;
	}
}

GetSigniature fails on nested generic types

Description

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.

FileInfo.ExtractGZipToDirectory Not Working

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);
		}
	}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.