Thursday, November 30, 2017

Simple function to check if the number is prime (c# / .NET)


The function is for the beginners as a sample function to check if the input number is a prime number. It takes a number as argument and returns a boolean result. I have used a very basic algorithm to check if the number is prime. Also, negative numbers are neglected.

public bool IsPrime(int number)
        {
            if (number < 2)
                return false;
            else if (number <= 3)
                return true;

            for (int i = 2; i < number; i++)
            {
                if (number % i == 0)
                    return false;
            }
            return true;
        }

Further, you can use the following facts and optimize above function to find if the number is prime.
  • The number divisible by itself and by 1 is a prime number.
  • 2 is only the even prime number. 
  • if the sum of individual digits of the number is divisible by 3, then the number is divisible by 3
  • We do not consider 0 and 1 as a prime number.
  • Except 5, no numbers ending with 5 is prime.


Override 'Equals(object obj)' Function in a class (c# / .NET)


Lets suppose 'MyClass' is the name of class for which you want to override 'Equals(object obj)' function. In order to override this function, we also need to override 'GetHashCode()' function. For further information you can check the links below :

https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.object.equals(v=vs.110).aspx
https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden


You can override the function as below.

public class MyClass
    {

        // This function will override the Equals(arg) function when called for MyClass Object.
        public override bool Equals(object obj)
        {

            bool yourReturnBoolean = base.Equals(obj); // write your logic to define this boolean value here.

            return yourReturnBoolean;
        }

        // This function will override the GetHashCode() function
        public override int GetHashCode()
        {
            return base.GetHashCode(); // logic to calculate the hash code
        }
       
    }


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

MyClass obj = new MyClass();           
bool booleanResult = obj.Equals(destinationObject);


Try it yourself and see the result.

Tuesday, November 28, 2017


Generate fibonacci Series (c# / .NET)


This function is for the beginners as a sample function to generate the Fibonacci series in c#. It takes a number 'n' as an argument ( i.e count of series ) and returns a dictionary with index and values. The basic algorithm is used to calculate the series. Also, the limitations and comments are written within the code.

// returns a dictionary with index and value of Fibonacci series for 'n' counts.
// Currently, the value should not be greater than 9223372036854775807, as we are using Int64 a value type. 
        public Dictionary<int,Int64> GetFibonacciSeries(int n)
        {
            // declaration of variables
            Int64 a = 0, b = 1, temp = 0;

            // declare returnlist as dictionary. It returns a dictionary with index and value of Fibonacci series.
            Dictionary<int, Int64> returnList = new Dictionary<int, Int64>();

            // by default add 0 and 1 to the dictionary.
            returnList.Add(1, a);
            returnList.Add(2, b);

            // perform calculations for remaining counts.
            for (int i = 3; i <= n; i++)
            {
                temp = a + b;
                returnList.Add(i, temp);
                a = b; b = temp;
            }

            // returns the populated dictionary.
            return returnList;
        }

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  

Tuesday, November 14, 2017

Common Table Expression in SQL (with multiple joined CTEs) 


CTE ( common table expression ) can be taken simply as temporary dataset within the query.
It is similar to temporary table but it is not stored as an object like temporary table and is alive
until the query execution.

You can use CTE like a normal table. Complicated joins can be simplified using CTE. Below you can find examples of simple CTE and CTE with joins. These techniques can be used as per your need to get the result data.

Simple CTE


;with cte1 as (

select
       field1,
       field2,
       field3
from dbo.table1
)
select * from cte1

Multiple CTEs with joins 


;with cte1 as (

select 
field1,
field2,
field3
from dbo.table1
), cte2 as (
select 
field4,
field5
from dbo.table2
)

select 
_cte1.*,
_cte2.* 
from cte1 _cte1
inner join cte2 _cte2 on _cte2.field4 = _cte1.field1


For detailed information click the link below :
 https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx



Reporting Services (SSRS Expression) : Get number of rows in dataset


The following ssrs expression will return you the total number of rows in the defined dataset.

=CountRows("MyDataSetName")


For detailed info checkout the linke below :

Get end of the month in mssql (2008 R2 / 2012 )


This is a simple workout to find the end day of the month for selected date in SQL server. For SQL server 2012, we have a built-in function to perform this task but for 2008, we need to write the logic manually. Here are the sql query samples to find out the end day of the selected month in mssql.

let's assume @dt is your declared DateTime

DECLARE @dt DATETIME = GETDATE()


In SQL 2012, we have an inbuilt function which will give directly the end of the month.

SELECT DAY(
EOMONTH(
@dt   -------- date to get end of the month
,0   -------- months to add ( optional )
)
)

-- In Short :
SELECT DAY(EOMONTH(@dt,0))

But in sql 2008 R2, we do not have this function, hence we need a workout. 

SELECT DAY(   --------------------------------------- returns the number of days of that month
DATEADD(d,-1, --------------------------- subtracts one day from the diff date
DATEADD( ------------------------ adds 1 month to the difference month: return type is DateTime                    
m
,DATEDIFF(M,0,@dt)+1  --- gets difference in months from the very beginning 
,0
)
)
   ) 
           
-- In Short :
SELECT DAY(DATEADD(d,-1,DATEADD(m,DATEDIFF(M,0,@dt)+1,0)))

Saturday, November 11, 2017

Exit application programmatically (c#/.NET) 


// Terminate process and return the exit code to the operating system. 
//0  indicates that process has completed successfully

                    Environment.Exit(0);

Tuesday, November 7, 2017

Run code as different user in c#


In our application, some tasks might need to be run as different user or as administrator. Below you can find a simple and effective solution for this purpose.

Simple Impersonation Library is a library which lets you to impersonate any user with its login credentials. From NuGet package, you can get this library.



Then you can implement your code inside a section as below:

using (SimpleImpersonation.Impersonation.LogonUser("domainname", "Username", "password", SimpleImpersonation.LogonType))
{
// Your running code as this user
}






Monday, November 6, 2017

Create/Save/Write/Append text in a txt file (c# / .NET)


Many requirements will come in application development where we have to create or update a text file for certain purpose. For example that may be a log file or any accumulative text files.

Here is a function which implements the code to create/save/write/append text in a text file. You can further modify the function or create a new one as per your need. You can pass texts and filepath as arguments and modify internal code based on your requirement.

       void MyFunction()
        {
            // path to your txt file
            string filePath = @"D:\myFile.txt";

            // if file does not exist, it will create a new file and dispose the resource used by stream
            if (!File.Exists(filePath))
            {
                File.Create(filePath).Dispose();
            }

            // instanciate a stream writer for the txt file.
            using (StreamWriter writer = File.AppendText(filePath))
            {
                // writes the line to the file and inserts a line break
                writer.WriteLine("I will insert a line break.");
                // writes the string to the stream
                writer.Write("I am written in a stream.");
                writer.Write("I am continued.");
                // NOTE : you can also write it asynchronously. check the functions in writer.
            }
        }

Thursday, November 2, 2017

XML to Object and vice versa in c# using DataContractSerializer


From conversion of XML to object and vice versa, we already have helper classes in .net. However, on this page, I have tried to implement a generic helper class for these operations. There are two functions in the helper which converts an xml string to class object and another function for converting class object to XML string.
To use DataContractSerializer class, you need to add reference System.Runtime.Serialization in your project.

Helper class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApp2
{
    /// <summary>
    /// Helper class for xml parsing
    /// </summary>
    /// <typeparam name="T">class object to/to be parsed</typeparam>
    public class DataContractSerializationHelper<T>
    {
        /// <summary>
        /// Converts xml string to Object
        /// </summary>
        /// <param name="xmlText"></param>
        /// <returns></returns>
        public  T Xml_To_Object(string xmlText)
        {

            T returnObject;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlText);

            using (StringReader stringReader = new StringReader(doc.OuterXml))
            {
                using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    returnObject = (T)serializer.ReadObject(xmlReader);
                }

            }

            return returnObject;
        }

        /// <summary>
        /// Converts object to xmldocument
        /// </summary>
        /// <param name="myObject"></param>
        /// <returns></returns>
        public XmlDocument Object_To_XML(T myObject)
        {

            XmlDocument xmlDocument = null;

            using (StringWriter stringWriter = new StringWriter())
            {
                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(xmlTextWriter, myObject);
                    xmlDocument = new XmlDocument();
                    xmlDocument.InnerXml = stringWriter.GetStringBuilder().ToString();
                }
            }

            return xmlDocument;
        }
    }   
}

Sample class ( to be passed as generic):

    public class testclass
    {
        public int id { getset; }
        public string name { getset; }
    }


Implementation of above helper class ( assuming the implementation done in console app) :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataContractSerializationHelper<testclass> helper = new                           DataContractSerializationHelper<testclass>();


            // conversion from object to xmldocument
            testclass obj = new testclass ();
            obj.id = 1;
            obj.name = "hello world";
            var xmldoc = helper.Object_To_XML(obj);


            // conversion from xmlstring to object
//note : in case you get namespace error replace 'ConsoleApp2' of testxml with the namespace of the class
            string testxml = "<testclass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/ConsoleApp2\"><id>1</id><name>hello world</name></testclass>";
            var testclassObject = helper.Xml_To_Object(testxml);


        }
    }
}



Note: If you need to have a function which will directly use the XML file URL or you need to export the class object to an XML file and save it in a location, you can give it a try it. Or leave a comment and I will update the post with other functions as well.







Wednesday, November 1, 2017

Free HTML to PDF library  .NET (c#)


You may find various libraries that convert HTML to pdf. But for me, I find SelectPDF the best. This library can help those developers who want it for free to convert few (not more than 5) pages long.
You can easily convert any webpage to pdf with different page settings parameters and custom pdf page breaks.
SelectPDF provides you a full featured free(community edition) .NET library for HTML to PDF conversion. Its only limitation is that it can generate pdf up to 5 pages. 

With few lines of codes, you can convert your URL or HTML to pdf content.

            // instantiate the html to pdf converter
     HtmlToPdf converter = new HtmlToPdf();

     // convert the URL to pdf
     PdfDocument doc = converter.ConvertUrl(url);

     // save pdf document
     doc.Save(file);

     // close pdf document
     doc.Close();



You can also get the library in visual studio from nuget.