Friday 27 November 2020

CSS Basic Selectors - Learn CSS | Html with CSS Tutorials | Tricks | Front-end Development

CSS selectors are useful in front end development. In this tutorial I am going to show you what are the CSS basic selectors.

Below are the four basic selectors which we use on daily web development


1. Universal Selector

2. Type Selector

3. Class Selector

4. ID Selector


1. Universal Selector

The universal selector matches all elements of any type in HTML document. Consider the below scenario in where we have div, span and paragraph for which I want to set a a green font colour for all of them.

CSS

*{

     font-color:green;

 }

<div>div content</div>

<span>span content</span>

<p>paragraph content</p>

User Interface

div content
span content

paragraph content

2. Type Selector

Type selector matches all the HTML elements by the given HTML element name. This selector travels throughout the HTML document and find out the elements which are matched with the given element name and apply the styles on them. Cosider below where we have to set a light green background colour for all the paragraphs.

CSS

p{

background-color: lightgreen;

}

<span>Paragraph 1</p>

<p>dotnetcookie.blogspot.com contains the regular updates on C#.NET for the followers</p>

<span>Paragraph 2</p>

<p>dotnetcookie.blogspot.com contains the regular updates on UI Technologies for the followers</p>

<span>Paragraph 3</span>

<p>dotnetcookie.blogspot.com contains the regular updates on SQL Server for the followers</p>

User Interface


Paragraph 1

dotnetcookie.blogspot.com contains the regular updates on C#.NET for the followers

Paragraph 2

dotnetcookie.blogspot.com contains the regular updates on UI Technologies for the followers

Paragraph 3

dotnetcookie.blogspot.com contains the regular updates on SQL Server for the followers

3. Class Selector

The class selector matches all the HTML elements by their class attribute value. If any HTML element class attribute value is matches with the given class name selector then the changes will apply to them. Consider the below scenario in which we want to apply a light green colour background to the success message and light  yellow colour message to info message.

CSS

.success {

background-color: lightgreen;

}

.info {

background-color: #f4ff54;

}

<div class="success">Congratulations! Your are successfully completed CSS basic selectors blog post</div>

<div class="info">You need to go through the other tutorials to become an expert in CSS</div>

User Interface

Congratulations! Your are successfully completed CSS basic selectors blog post

You need to go through the other tutorials to become an expert in CSS

4. ID Selector

The ID selector applies the styles to the elements based on the value of their id attribute. The HTML elements should be identified by the unique ids. Lets take two containers , apply the background colour for the div container which id value is equal to "warningMessage".

CSS

#warningMessage{

background-color: lightgreen;

}

<div id="warningMessage">HTML does not allow the duplicate id values.</div>

<div>Please go through the other tutorials on this blog to become an expert in CSS</div>

User Interface

HTML does not allow the duplicate id values.
Please go through the other tutorials to become an expert in CSS

Above are the basic selectors which we use regularly in our web development.

Thursday 26 November 2020

C# - Truncate characters from string by keeping right side string with the specific length

 

Challenge

Consider a scenario where you are uploading a file in a website and prcoess the file by appending the date at the end of the file name and saves in a location and then saving the uploaded file name in the database. Post uploading the file you are displaying all the submitted files in a grid like below.

Uploaded filename: Developer_Profile.xlsx
Saved filename appended with date: Developer_Profile_11242020.xlsx
https://dotnetcookie.blogspot.com/
Consider the column length for the filename is 150. If the uploaded file name length is more than 150 and there is no length validation before inserting into database then database will throw the exception. So we need to add a validation before uploading. Assume that the client doesn't want to restrict the upload if the file name length is more than 150 characters. Instead client comes with the below requirement.

- If the file length is greater than 150
- Truncate filename to 150 characters, but keep the right side portion which is date part along with extension.

Example: Uploaded file with file name length more than 150
Filename: Developer_Profile_ dummy text of the printing and typesetting industrya Lorem Ipsum has been the industry's standard dummy text ever sinceweb page editors now use Lorestandard_11242020.xlsx

Keep the date part and remove/trim the additional characters highlighted above.

Truncated filename with 150: Developer_Profile_ dummy text of the printing and typesetting industrya Lorem Ipsum has been the industry's standard dummy text ever sinceweb page edit_11242020.xlsx

Below is the extesion method which will truncate the file name and the respective unit testcacses. Follow the code comments which is self explanatory.

Extension method to truncate string

        /// <summary>
        /// If input length is greater than the truncate length value
        /// Trims the input with length truncate length value.
        /// Keeps the right side of the input value
        /// </summary>
        /// <param name="value">Input value</param>
        /// <param name="truncateLength">Truncates input if the input length is greater than this</param>
        /// <param name="rightLengthToKeep">The right side string length which needs to take while truncating</param>
        /// <returns></returns>
        public static string TruncateRight(this string value, int truncateLength, int rightLengthToKeep)
        {
            var errorMessage = "Negative values are not allowed";

            // Handle empty, null and white spaces 
            if (string.IsNullOrWhiteSpace(value))
            {
                return value;
            }

            // Handle negative values
            if (truncateLength < 0)
            {
                throw new ArgumentOutOfRangeException("truncateLength", truncateLength, errorMessage);
            }

            // Handle negative values
            if (rightLengthToKeep < 0)
            {
                throw new ArgumentOutOfRangeException("rightLengthToKeep", rightLengthToKeep, errorMessage);
            }

            if (rightLengthToKeep > truncateLength)
            {
                errorMessage = $"rightLengthToKeep value ({rightLengthToKeep}) shoud be less than or equal to truncateLength ({truncateLength})";
                throw new ArgumentOutOfRangeException(errorMessage);
            }

            if (value.Length <= truncateLength)
            {
                return value;
            }

            // To skip middle range we need to take the left side end rage and right side start rage.
            int leftStringEndIndex = truncateLength - rightLengthToKeep;
            int rightStringStartIndex = value.Length - rightLengthToKeep;

            var finalResult = "";

            // Get left side value
            for (int i = 0; i < leftStringEndIndex; i++)
            {
                finalResult = finalResult + value[i];
            }

            // Get right side value
            for (int i = rightStringStartIndex; i < value.Length; i++)
            {
                finalResult = finalResult + value[i];
            }

            return finalResult;
        }

Unit tests

        [Fact]
        public void SkipRightThenTrimTest()
        {
            // Test filename: FileNameToTestWithTruncateLogicTruncateMe_11242020_ErroFile.csv
            // Total string length is 63

            // Null check
            string testString = null;
            Assert.Equal(null, testString.TruncateRight(40, 22));

            // Empty check
            testString = ""; 
            Assert.Equal("", testString.TruncateRight(40, 22));

            // Whitespace check
            testString = "  ";
            Assert.Equal("  ", testString.TruncateRight(40, 22));

            // Negative value check 
            testString = "FileNameToTestWithTruncateLogicTruncateMe_11242020_ErroFile.csv";
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(-22, 40));
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(22, -40));
            
            // Invalid range check
            Assert.Throws<ArgumentOutOfRangeException>(() => testString.TruncateRight(22, 40));

            // Truncate filename if it more than 22 chars and take right 22 characters
            Assert.Equal("_11242020_ErroFile.csv", testString.TruncateRight(22, 22)); 
           
            // Truncate filename if it is more than 40 chars and keep right 22 characters and left 18 chars
            Assert.Equal("FileNameToTestWith_11242020_ErroFile.csv", testString.TruncateRight(40, 22));
            
            // Take filename directly if the fielname lenth and truncate value length is equal
            Assert.Equal(testString, testString.TruncateRight(63, 22));
            
            // Take filename directly if the truncate value length is greater than the filename length
            Assert.Equal(testString, testString.TruncateRight(70, 22));
        }
    }