Friday, November 24, 2017

Override 'ToString()' Function in a class (c# / .NET)



Let's suppose 'MyClass' is the name of the class for which you want to override 'ToString()' function.
Then, you can override the function as below.

public class MyClass
    {

        // This function will override the ToString() function when called for MyClass Object.
        public override string ToString()
        {           
            string yourReturnString = "String which you want to return when ToString() for this class object is called.";

            return yourReturnString;
        }
    }


Now let's create an object for the class and call 'ToString()' function.


MyClass obj = new MyClass();
var overriddenString = obj.ToString();


Try it yourself and see the result.

Thursday, November 23, 2017

String vs StringBuilder and its uses ( c# / .NET)


string


String uses heap memory and is immutable. Whenever a string is modified, i.e concatenated,replaced or removed, a new heap memory is allocated each time. Hence, multiple modification of string can affect performance. String can be used and is efficient when string modifications are not done multiple time.

Use in cases like this:

string myStr = "This is my test string. It can be simple strings such as headers, texts or some static strings to be displayed";

Do not use in cases like this:

string myStr = "Many times to be concatenated";
for(int i = 1;i<100;i++)
{
myStr = myStr + "Some additional strings";
}

StringBuilder


StringBuilder uses stack memory and is mutable. Whenever string is appended to StringBuilder, no new memory is allocated but strings are appended into string builder itself. This has great performance implication and hence faster in cases like appending/concatenating many strings.

Use in cases like this:

StringBuilder myStringBuilder = new StringBuilder();
            for (int i = 1; i < 100; i++)
            {
                myStringBuilder.Append("Some additional strings");
            }

Do not use in cases like this:

   StringBuilder myStringBuilder = new StringBuilder();
            myStringBuilder.Append("This is my test string.");
            Console.WriteLine(myStringBuilder.ToString()); // output to console window

Wednesday, November 22, 2017

Fill DataTable from sql query string (c# , SQL)


In c#, we can directly query the database from a query string using SqlConnection. We need to open a connection to the database, pass our query using SqlCommand, fetch and load the result in a DataTable and finally close the connection.

Below is a sample function for this operation. Further, you can modify it to meet your need.

Use the following namespace:

using System.Data;
 using System.Data.SqlClient; 

The connection string and query string can be modified or passed as the arguments in the function.

private DataTable GetFromDatabase()
{
DataTable returnTable = new DataTable();
using (SqlConnection con = new SqlConnection("Your_ConnectionString"))
{
con.Open();
using (SqlCommand command = new SqlCommand("Your_sql_query_string", con))
using (SqlDataReader reader = command.ExecuteReader()) { returnTable.Load(reader); }
con.Close();
}
return returnTable;
}

Remove/Replace invalid characters in string (c# / .NET)


To remove/replace invalid characters in a string, try implementing the below function. filename is the name of file and replaceChar is the character that you want to replace with the invalid characters.


private string RemoveInvalidFilePathCharacters(string filename, string replaceChar)
        {
            string regexSearch = new string(System.IO.Path.GetInvalidFileNameChars()) + new string(System.IO.Path.GetInvalidPathChars());
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(string.Format("[{0}]", System.Text.RegularExpressions.Regex.Escape(regexSearch)));
            return r.Replace(filename, replaceChar);
        }

Tuesday, November 21, 2017

Split string by one or multiple characters (c# / .NET)


Splitting string to string array is a very common and frequent task in development. Here are some ways to split string by one or multiple characters.

Split string by one character


Lets split the following sentence by ','
            string str = "my,name,is,computer";
     string[] charArray = str.Split(',');

Also, you can split string my multiple characters
            string str = "my,name-is,computer";
     char[] splitCharArray = new char[] { ',', '-' };
     string[] charArray = str.Split(splitCharArray);

Split string by multiple characters


lets split the following sentence by string(s)
string str = "my&&name&&is%%computer";
string[] splitStringArray = new string[] { "&&"}; 
string[] charArray = str.Split(splitStringArray,StringSplitOptions.None);

Try this and check the difference

 string str = "my&&name&&is%%computer";
 string[] splitStringArray = new string[] { "&&", "%%" }; // strings to split the sentence
 string[] charArray = str.Split(splitStringArray,StringSplitOptions.None);


Thursday, November 16, 2017

SKIP and TAKE in sql query (simple work around)


Sometimes we might need not just to filter the records but also to skip and/or take specific rows from it. Using LINQ in c#, it can be easy for developers to skip and take records but they might be scratching their head if they need to do the same in SQL query and hence we get stuck.

Below are some query examples which I have been using to perform these actions.We can customize our query to skip and/or take records.

To get exact records, you can sort the records by any field like I did below.

Note: Replace Your_SkipCount and  Your_TakeCount by numbers your numbers

To skip only


SELECT * FROM
(
         SELECT
ROW_NUMBER() OVER(ORDER BY id) AS rowid,
Column1, ..
         FROM dbo.YourTable
        ) AS tbl
WHERE rowid > Your_skipCount

To Skip and Take


SELECT * FROM
(
           SELECT
ROW_NUMBER() OVER(ORDER BY id) AS rowid,
Column1, ..
           FROM dbo.YourTable
         ) AS tbl
WHERE rowid BETWEEN (Your_SkipCount +1) AND (Your_Skipcount + Your_TakeCount)

To Take Only


SELECT TOP Your_TakeCount
id,
Name
FROM dbo.YourTable
ORDER BY id


Wednesday, November 15, 2017

Read/Use Stored Procedure result data in SQL query


It is better to use a 'User defined function' or a 'View' instead of the Stored procedure if
you want to access the result records in your query. 

Anyway, if you want to access the data from a stored procedure, you need to store the
result first in some temporary table and use it in your query. 

You can use a table variable as below.

DECLARE @tbl TABLE(field1 int ,field2 varchar(500) ,...)      
    INSERT INTO @tbl        
    EXEC myprocedure @param ..


SELECT * FROM @tbl