Tuesday, April 11, 2017

Sample SQL Server Function to Truncate a string

Below is the sample SQL Server function to Truncate a string to the given number of characters.

If the string is smaller than the given limit, it is returned as-is; otherwise, it is truncated to 3 characters less than the given limit, and '...' is placed at its end..

SQL Server Function :
create function [dbo].[TruncateString]
(
    @Str varchar(max),
    @MaxLength int
)
returns varchar(8000)
as begin
    if @MaxLength is null or @MaxLength < 3 set @MaxLength = 3
    if @MaxLength > 8000 set @MaxLength = 8000

return case
    when datalength(@Str) <= @MaxLength then @Str
    else left(@Str, @MaxLength - 3) + '...'
    end
end

Sample SQL Server Function to Trim a string

Below is a sample SQL Server function to Trim a string. It removes leading & trailing whitespace characters from a string.

This function differs from rtrim() and ltrim() in that it removes tab, newline, and carriage return characters in addition to spaces. Like ltrim() and rtrim(), if you pass null in, you get null back.

SQL Server Function :
create function [dbo].[TrimString]
(
    @Str varchar(max)
)
returns varchar(max)
as begin
    declare @First int = 1,
    @Last int = datalength(@Str)

    while ascii(substring(@Str, @First, 1)) in (32, 9, 10, 13)
    set @First += 1

    if @First > @Last begin
    -- the string is all whitespace (or empty)
    return ''
 end

    while ascii(substring(@Str, @Last, 1)) in (32, 9, 10, 13)
    set @Last -= 1

    return substring(@Str, @First, @Last - @First + 1)
end

Monday, April 10, 2017

Sample C# program to generate a random string

You know well where it is required to generate a random string. It might be for a password generation or any other reason. Here is a sample C# program to generate a random string. You might required to pass a parameters length of the random string also a boolean param to say whether to include upper case characters.

/// 
/// Gets a random alphanumeric string of the specified length,
/// optionally using either all lowercase, or mixed lower and upper case.
/// 
/// Length of the string.
/// Whether to include uppercase characters.
public string GetRandomString(int length, bool includeUppercase)
{
    string chars = "abcdefghiklmnopqrstuvwxyz1234567890";
    if (includeUppercase) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    StringBuilder sb = new StringBuilder(length);
    for (int chNum = 0; chNum < length; ++chNum)
    {
        int rand = this.GetRandomInt(0, chars.Length);
        sb.Append(chars[rand]);
    }

    return sb.ToString();
}


/// 
/// Gets a random boolean, based on the passed percentage.
/// It will return true in truePercentage percent of calls.
/// 
/// The percentage of the time true should be returned.
public bool GetRandomBoolean(int truePercentage)
{
    int rand = this.GetRandomInt(0, 100);  // [0-100), can be zero, can't be 100
    return (rand < truePercentage);
}