Wednesday, May 25, 2016

Set content in an iframe or load scripts in it asynchronously

Sometimes you may have to load the scripts or content inside and iframe. This will be helpful especially if you are loading an ad or video on a web page and do not want to slow down the whole web page. Given below is an example on how to load content inside an iframe asynchronously.


    <iframe id="myiframe" height="300" width="700"></iframe>
    <script>
        window.setTimeout(setIframeContent,1000);
        function setIframeContent() {
            //set content or script
            var html = '<body><div>my content</div><scr' + 'ipt>alert("test")</' + 'script></body>';
            //get reference to iframe and load the content to iframe
            var iframe = document.getElementById("myiframe");
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(html);
            iframe.contentWindow.document.close();
           
        }

    </script>

Tuesday, April 19, 2016

Add HTTP access control (CORS) to response

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.  For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain unless CORS headers are added  in the response.

Given below is the code to add CORS header to response in asp.net

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "domain.com" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

If you want to include CORS header for requests from all domains, you have to format the referrer url to get the correct domain

public static string GetDomain(string referrer)
{
    string tmpReferrer = String.IsNullOrEmpty(referrer) || referrer.Length < 5 ? "" : referrer;

    // strip out the domain portion of the referring url, if there is a starting point
    if (tmpReferrer.Length > 0 && tmpReferrer.Substring(0, 4) == "http")
    {

        //remove string after first /
        if (tmpReferrer.IndexOf("/", 8) > 0)
        {
            tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("/", 8));
        }

        //remove string after first ?
        if (tmpReferrer.IndexOf("?") > 0)
        {
            tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("?"));
        }
    }
    else if (tmpReferrer.Length > 0)
    {
        //remove string after first /
        if (tmpReferrer.IndexOf("/") > 0)
        {
            tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("/", 8));
        }

    }
    return tmpReferrer;
}

And then call the function to add domain name to CORS header

string referrer = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", GetDomain(referrer));
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");



JS code to call endpoint

var httpRequest = new XMLHttpRequest();
 httpRequest.open("GET", "http://somedomain.com/endpoint", true);
 httpRequest.withCredentials = true;
 httpRequest.send();
   
 httpRequest.onreadystatechange =  function () {
     if (httpRequest.readyState == 4) {//wait for request to complete
               
         console.log(httpRequest.responseText);
               
     }
 };

How to add semi transparent background

You can set semi transparent background on a div or any html element by adding below style -

background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.5) 0%,rgba(255, 255, 255, 0.5) 100%), url(http://www.bestmanspeechestoasts.com/wp-content/themes/thesis/rotator/sample-4.jpg);


You can see the example here - http://codepen.io/deebujacob/pen/xVzRxw

Wednesday, December 2, 2015

LINQ - Group multiple columns or keys

Using .NET linq you can easily group data in a list. This is an example of grouping data based on multiple keys.

This is the class that I created for testing
public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public string SubDepartment { get; set; }
public float Salary { get; set; }
}

This is the multi- key grouping using LINQ
/*create employee list*/
List<Employee> emps = new List<Employee>();

/*Add test data */
emps.Add(new Employee() { Name = "Employee 1", Department = "HR", SubDepartment="Recruitment",  Salary = 4000 });
emps.Add(new Employee() { Name = "Employee 2", Department = "HR",SubDepartment="Recruitment", Salary = 4500 });
emps.Add(new Employee() { Name = "Employee 3", Department = "Tech",SubDepartment="Engineering", Salary = 5000 });
emps.Add(new Employee() { Name = "Employee 4", Department = "Tech",SubDepartment="Engineering", Salary = 5200 });

/*group data based on departments*/
List<Employee> newlist = (from x in emps
group x by new { x.Department, x.SubDepartment } into grp
select new Employee()
{
Department = grp.Key.Department,
SubDepartment = grp.Key.SubDepartment,
Salary = grp.Sum(x => x.Salary)
}
).ToList();


Tuesday, April 7, 2015

HTML help/info control

Given below is code to show help information next to controls(like textbox, dropdownlist etc). This will show help info next to the control “onfocus” event. This feature can be attached to other events also like “onmouseover”,”onclick” etc.


The control will look like this - 


Set the script and style in html head

<script>
    var prevmsgControlName;
    var timeoutVar;
    function showControlMessage(control, msg) {
        var msgControlName = 'message_' + control.id;

        if (prevmsgControlName) {
            document.getElementById(prevmsgControlName).style.display = "none";
        }
        if (document.getElementById(msgControlName) == null) {
            var tempDiv = document.createElement("div");
            tempDiv.id = msgControlName;
            var rect = control.getBoundingClientRect();
            tempDiv.innerHTML = msg;
            tempDiv.className = "client_message";

            tempDiv.style.left = Number(rect.left + control.offsetWidth + 5) + "px";
            tempDiv.style.top = rect.top + "px";
            control.parentNode.appendChild(tempDiv);
            clearTimeout(timeoutVar);
            timeoutVar = setTimeout(hideControlMessage, 8000);
            prevmsgControlName = msgControlName;
        }
        else {
            clearTimeout(timeoutVar);
            document.getElementById(msgControlName).style.display = "block";
            timeoutVar = setTimeout(hideControlMessage, 8000);
            prevmsgControlName = msgControlName;
        }
    }
    function hideControlMessage() {
        clearTimeout(timeoutVar);
        document.getElementById(prevmsgControlName).style.display = "none";
    }
</script>

<style>
.client_message {
    border:1px solid black;
    background-color:rgb(250, 250, 188);
    padding:5px;
    position:absolute;
    font-size:90%;
    width: 300px;
    border-radius:2px;
}
</style>

Once the script and style are set in head, you can add help info to control as given below.

<input id="control1" type="text" onfocus="showControlMessage(this,'Replace with help info you want to show for the control')" />



Friday, January 30, 2015

How to use SOLR.NET to add/search documents from SOLR

In this article we will look into how to use SOLR to add and query data using  SOLR.NET

Install Apache Tomcat and  SOLR

1. Install Java version 6 or above

2.Download Apache Tomcat -Core: 32-bit/64-bit Windows Service Installer (pgp, md5) http://tomcat.apache.org/download-70.cgi
After you install apache tomcat you can check if service is running by checking the location -http://localhost:8080/


Details on how to install and run SOLR is clearly stated in the below awesome articles

Use SOLR.NET to connect to SOLR

So now that we have Apache and SOLR running let’s look at how to use this in ASP.NET(C#)

1.Download SOLR.NET - https://github.com/mausch/SolrNet

2.Compile the project and get the dlls from SOLRNET project (there will be SolrNet.dll, Microsoft.Practices.ServiceLocation.dll, HttpWebAdapters.dll and the pdb and xml files)

3.Create an empty ASP.NET project

4.Create a new folder in this project and copy the dlls from SOLRNET project (step 2) to that folder.

5.Add references to the 3 dlls

6.Add Global.asax and initialize SOLR.NET connection in application start
  protected void Application_Start(object sender, EventArgs e)
        {
            Startup.Init<SOLRPOST.PostData.SolrSearchResult>("http://localhost:8080/solr");
        }


7.Create a class which has the same fields as the schema in SOLR. For testing purpose I added only 2 fields from schema
public class SolrSearchResult
        {
            [SolrField("id")]
            public string id { get; set; }

            [SolrField("title")]
            public string title { get; set; }
        }

8.Now we are ready to add documents to SOLR! Given below is the function to add documents to SOLR
public void AddData()
        {
            ISolrOperations<SolrSearchResult> solr = ServiceLocator.Current.GetInstance<ISolrOperations<SolrSearchResult>>();
            SolrSearchResult test = new SolrSearchResult() { id = "changeme2", title = "changeme2" };
            solr.Add(test);
            solr.Commit();
        }

9.To search data use the below function

public void SearchData()
        {
            ISolrOperations<SolrSearchResult> solr = ServiceLocator.Current.GetInstance<ISolrOperations<SolrSearchResult>>();
            SolrQueryResults<SolrSearchResult> results = solr.Query(new SolrQuery("id:\"changeme2\""));
            foreach (SolrSearchResult result in results)
            {
                Response.Write(result.title);
            }
        }







Thursday, January 29, 2015

Group and pivot data in SQL

Given below is an example of how to group and pivot data in SQL .This example shows you how to group data in CSV format and pivot it.

--Create temp table
CREATE TABLE  #car_data (company varchar(10), model varchar(20))

--Insert data
INSERT INTO #car_data (company,model) values ('Ford','Escape')
INSERT INTO #car_data (company,model) values ('Ford','Explorer')
INSERT INTO #car_data (company,model) values ('Ford','Expedition')

INSERT INTO #car_data (company,model) values ('Chevy','Cruze')
INSERT INTO #car_data (company,model) values ('Chevy','Impala')
INSERT INTO #car_data (company,model) values ('Chevy','Silverado')

-- Group data in CSV format
SELECT  t.company
    ,STUFF((SELECT ', ' + model
        FROM #car_data with(nolock)
        WHERE company = t.company
        FOR XML PATH(''), TYPE)
    .value('.','VARCHAR(400)'),1,2,' ') List_Output
FROM #car_data t with(nolock)
GROUP BY t.company