Saturday, December 30, 2017

Implement google map inside iframe


This blog is about implementing google map in your website using an iframe. Integrating map in website has never been so easy but now we can do it in just a moment. Here are the steps on how you can use google map inside your iframe.

  • Open maps.google.com in your browser.
  • Search your map location which you want to show in your website.


For example, I searched Frankfurt,Germany



  • Click menu button --> Share or embed map





  • Then Click 'Embed Map' tab. you can find an iframe link for your map.




Thursday, December 21, 2017

Web Application Vs Desktop Application


Web Application

  • Hosted in central server.
  • Easy maintenance, customization, integration and upgrade.
  • High scalability, accessibility and sharing.
  • Less resources required for clients. A compatible browser like Chrome or Firefox is enough.
  • Platform independent. Any sort of device within the network and a browsing application is enough.
  • High dependency on network ( internet or intranet )
  • Application failure can cause whole system down and affect all clients.
  • Hosting Servers need to be powerful and hence can be expensive( also online web hosting packages can be comparatively expensive)
  • Slow application development and complicated installation/hosting.

Desktop Application

  • Application installed on local machine ( i.e on client's computer)
  • Independent of networks and also able to work offline.
  • Faster to develop and install.
  • Secured due to local application installation
  • Highly compatible for softwares regarding hardwares
  • Requires manual installation by each client
  • Scalability limited due to resources
  • Local storage and resource usage eg. hardwares and memory
  • Low data portability.


Anyway, web and desktop applications have their own pros and cons. They have their own importance based on requirements and should be developed corresponding to the situation. We
cannot just rank any one of them as first or second.

Lets suppose if your clients are world wide spreaded and you need to perform frequent communication, data sharing or need to work on common business framework, then its good to have web application.

But lets suppose you want to build an application which will access your hardware (i.e camera, microphone, graphics card etc) or lets say you don't have a powerful central server which is able to hold multiple requests from your clients, you can think of a good desktop application which will use your client's resource for the application performance and you can use your server as a central database server.

So, based on the infrastructures you have and also the business requirements from your client, you have to choose the efficient type of application.

Wednesday, December 20, 2017

Select all files inside a directory/folder (c# / .NET)


The below function implements the inbuilt libraries in .net to get all possible files inside a folder/directory. No matter how many number of folders or child folders it contains, it searches all the folders and returns a list of all file paths. It is a recursive function and hence can be a good example for the beginners to understand how recursive function works. 

        // Returns List of file paths for given search directory path.
        public List<String> SearchFiles(string searchDirectoryPath)
        {
            try
            {
                //declaration of list of full filepaths
                List<String> fileList = new List<String>();

                // fetch all files in the directory
                foreach (string file in Directory.GetFiles(searchDirectoryPath))
                {
                    fileList.Add(file);
                }

                // recursive function call for other directories inside of the current directory
                foreach (string directory in Directory.GetDirectories(searchDirectoryPath))
                {
                    fileList.AddRange(SearchFiles(directory));
                }

                //return the list of filepaths
                return fileList;
            }
            catch (Exception ex)
            {
                // throws exception if caught
                throw ex;
            }
        }


Call this function to get list of full file paths like below :


var allFiles = SearchFiles(@"D:\YourFolder");

Note : You will need  System.IO to use Directory class.

ConnectionStrings and AppSettings value from config file. ( c# / .NET)


We have faced the issues and difficulties of hard coded strings and values in our application several times. Keys, connection strings, user credentials and other dynamic settings are not supposed to be hard coded during application development. If done so, they can causes many limitations to our application and even small changes might require recompilation of application and several human hours for development and deployment.

Hence, in our application, we can put these dynamic settings in a config file and read it from there. In .net, We have a library System.Configuration to read these settings and connection strings. Below you can find the code implementation of config file as well as the library in c#.

Code implementation in config file :


<connectionStrings>
<add name="_NameOfConnectionString_" connectionString="_ConnectionString_" providerName="System.Data.SqlClient" />
</connectionStrings>

<appSettings>
    <add key="_key1Name_" value="123" />
    <add key="_key2Name_" value="abc" />
</appSettings>

To access these configuration values in our code, we can write our code as following.

Code implementation in class file :


//used namespace
using System.Configuration;

// you can access the appsettings in your code like below
string key1Value = ConfigurationManager.AppSettings["_key1Name_"];
string key2value = ConfigurationManager.AppSettings["_key2Name_"];

// you can access the connection string in your code like below
string connectionstring = ConfigurationManager.ConnectionStrings["_NameOfConnectionString_"].ToString();

Monday, December 11, 2017

Get end day of the month ( jquery / javascript)


This is a simple workout to find the end day of the month for selected date in javascript. Below is the workout on how you can do it.

Lets suppose for May 2017, you want to find the end of the month. On you javascript code you can write the following.

var _Year = 2017;
var _Month = 5;
var _date = (new Date(_Year, _Month, 0, 0, 0, 0));
var endOfMonth = _date.getDate();

endOfMonth is the end day of the month for given year and given month. You can change the year and month yourself or make it dynamic based on arguments by creating a function.

For end of month in sql check the link : http://iamfixed.blogspot.com/2017/11/get-end-of-month-in-mssql-2008-r2-2012.html

jquery ajax cache false ( MVC / c# / jquery / ajax )


Not reaching debug point on jquery ajax call



It may happen that we are using jquery ajax call and the program does not reach debug point in your controller action. This happens when ajax cache is enabled. Disabling of the cache during your ajax call can solve this problem. Below you can see an example.


$.ajax({
                url: _your_url,              
                cache: false,
                success: function (result) {
                    // _success_
                },
                error: function (req, err) {
                   // _error_
                }
            });

Enable the cache only when your ajax call returns the same result even on multiple requests. But if you need to get fresh data from controller action each time on your ajax call, better disable the cache.

Friday, December 8, 2017

Zero (or any character) Padding in javascript / jquery


This is a small manual function written in javascript to pad a certain character to a string. In practical, the string usually can a number which needs to be formatted in order to display properly. These numbers can be days, months or year for a date viewer or any number which follows a padding pattern before some operations.

    // obj : string you want to pad.
    // _lenght : length of you padded result string
    // paddingChar : the padding character which you want to add
    function Padding(obj, _length, paddingChar) {

        var str = String(obj);             
        var returnStr = "";
        if (str.length < _length) {
            for (var i = str.length ; i < parseInt(_length) ; i++) { returnStr += paddingChar; }
        }

        return returnStr + str;
    }

Call the function like this :

var result = Padding(12,5,'0');

It should return '00012'.

Monday, December 4, 2017

CRM Dynamics - ExecuteMultipleRequest error


The request channel timed out while waiting for a reply after 00:01:59.8499880. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.



Set the time out for OrganizationServiceProxy . By default, the timeout is 2 minutes. i.e :

_yourOrganizationProxy.Timeout = new TimeSpan(0,10,0); // sets timeout for 10 minutes


To understand further about executing multiple requests from CRM SDK, check the following link :
https://msdn.microsoft.com/en-us/library/jj863631.aspx

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.