Translate

Thursday, April 26, 2012

Linq join two generic lists (linq join two tables)


What are we trying to achieve?

Suppose you want to join  Employees Table  and  Players Table  on first name.



Employees Table:
FirstName
Employer
A
TJX
B
G4s
C
Google

Players Table:
FirstName
Club
A
Manchester United
D
Chelsea
C
Arsenal


Table that joins the above two tables on first name.
FirstName
Employer
Club
A
TJX
Manchester United
C
Google
Arsenal




How do we do it?


The way you would do this in C# is by creating two Lists and then combine them using join.  This is how the code that does the join looks like


Join:

var playerEmployee = from employee in empList
                    join player in soclist
                    on employee.FirstName equals player.FirstName
                    select new { employee, player };

foreach (var x in playerEmployee)
{

}


Left Join:

SoccerPlayer dummyPlayer = new SoccerPlayer();

var playerEmployeeLeftJoin = from employee in empList
join player in soclist
on employee.FirstName equals player.FirstName into playerAlias
from player in playerAlias.DefaultIfEmpty()
select new { employee, player = (player == null ? dummyPlayer : player) };

foreach (var x in playerEmployeeLeftJoin)
{

}


Sunday, April 15, 2012

Disable background when pop up appears (modal window using jquery)


In this article I will show you how to create a modal pop up window (like the one shown below) within a few minutes.  In the example shown below, when you click a button, a window will appear that will block out rest of the screen. You have to close this window to be able to interact with the main screen.

Screen before clicking the button:


Screen after clicking the button:













To follow the example below you will need to download the following two javascript libraries and one css file
1> jquery-1.4.1.min.js
2>jqModal.js
3>jqModal.css

Once you have these three files copy the .js files into a folder called Scripts. Copy the css to a folder called Styles. Then copy paste the html below into a file with .html extension.


<html>
<head>
    <title>Modal window</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript" src="Scripts/jqModal.js"></script>
    <link href="Styles/jqModal.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(document).ready(function () {

            $("#modalWindow").jqm({
                onShow: jqModalShowHandler,
                onHide: jqmHideModalHandler,
                modal: true
            });


            $("#btnShow").click(btnShowClick);

            function btnShowClick() {
                $("#modalWindow").jqmShow();
            }

            function jqModalShowHandler() {
                $('#modalWindow').show();
            }



            function jqmHideModalHandler(e) {

                e.w.hide(); // Hide window
                e.o.remove(); // Remove overlay
            }

        });
    </script>
</head>
<body>
    <input id="btnShow" type="button" value="Click Me to see modal" />
    <div class="Medium jqmWindow" id="modalWindow" style="display: none">
        <a class="jqmClose modal_tools_close" style="float: right;" href="#">X</a>
        <div class="modalContent">
            <br />
            <br />
            <br />
            <br />
            <br />
            This is a modal window
        </div>
    </div>
</body>
</html>

  This is how your final folder structure would look like. 




Now you're good to go. Play around with the div tag with id=modalWindow to customize it to your needs.



Show a modal window with javascript

To show a simple modal box (where background is NOT grayed out) use

var features="edge:sunken;scroll:no;status:no;unadorned:yes;help:no; ";
 
        var url = ....
 
window.showModalDialog(url ,"" , features);

Tuesday, April 10, 2012

CSS hide element


CSS attribute of display:none  hides the element without occupying any space on the page

Example:

<span id="xxx" style="display:none;" ></span>

Sunday, April 8, 2012

JQuery Ajax

Given below is a simple example of a jquery ajax call 


$.ajax({
    type: "POST",
    url: "http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit" ,
    contentType: "application/x-www-form-urlencoded",
    data: 'Celsius=75',
    dataType: "text/html"
    success: function (msg) {
   //code to handle success goes in there
    },
    error: function (xhr, msg) {
   //code to handle failure goes in there
    }
});

Given below are their definitions

Parameter
What it means
Possible values



type
Whether to get data from or post data to the webserver
Get:  If you just need to fetch a webpage. (default)
Post: If you need to send some data to the webserver and get a response based on that data. This is generally used to change the current state of the web page.
contentType
Tells the webserver what type of content is being sent by the browser


The common content  types include:

  • application/x-www-form-urlencoded (default)
  • application/json
  • text/html
  • text/plain

Check here for all possible values

url
The url to make the request to.
Any web url
data
The data to be sent to the webserver
Key, value pairs
dataType
The datatype that the Jquery code would prefer to get back from the webserver.
·         xml
     json
     jsonp
     script
     html
     text


To make a jquery call using JSON, you would do something like this



$.ajax({
            type: "POST",
            url: "WebServices/myWebService.asmx/MyMethod",
            contentType: "application/json; charset=utf-8",
            data: '{"param1":"' + param1+ '", "param2":"' + param2 + '"}',
            dataType: "json",
            success: function(msg) {
                 
                var jsonObj = msg.d;

                var returnParam1 = jsonObj['To'];
                var returnParam2 = jsonObj['Subject'];
                var returnParam3 = jsonObj['Body'];
            },
              error: function (xhr, msg) {              
                         //code to handle failure goes in there
                }

   }); //end of  $.ajax



Check this out on a detailed simple example on making an ajax call.

Saturday, April 7, 2012

Jquery Ajax Working Example (call a webservice using Jquery AJAX)

In this example I will show you how to call the webservice
http://itunes.apple.com/search?term=
using jquery ajax.

The return from this webservice is a json resultset that has the structure shown in the image below



















To make this call just copy paste the text below into notepad and save it with a .html extension


<html>
<head>
    <title>Ajax webservice example</title>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            //This means when the button btnWebserviceCaller is clicked the call the function CallWebService
            $("#btnWebserviceCaller").click(CallWebService);

            //This code means when user presses enter in the text box txtSearch then click the button btnWebserviceCaller
            $("#txtSearch").keyup(function (event) {
                if (event.keyCode == 13) {
                    $("#btnWebserviceCaller").click();
                }
            });


            function CallWebService() {

                $("#divResults").text("Please Wait...");
                var searchTerm = $("#txtSearch").val();
                var webMethod = "http://itunes.apple.com/search?term=" + searchTerm;

                //This is where the ajax call is made
                $.ajax({
                    type: "GET",
                    url: webMethod,
                    contentType: "application/x-www-form-urlencoded", //this is format to sent to the server
                    dataType: "jsonp", //format to expect back from the server
                    success: function (msg) {
                        //if success, come in here
                        var dislplayHtml = "<br/>";

                        $.each(msg.results, function () {
                            //come in here for every result in the array msg.results
                            $.each(this, function (key, value) {
                                //come in here for every key value pair with in a result
                                dislplayHtml = dislplayHtml + key + ":" + value + "<br/>";
                            });
                            dislplayHtml = dislplayHtml + "<br/><br/>";
                        });

                        $("#divResults").html(dislplayHtml);

                    }, //success function ends here
                    error: function (xhr, msg) {//if fail, come in here
                        $("#divResults").text(msg);
                    } //error function ends here
                }); //ajax function ends here

            } //function  CallWebService ends here


        });
    </script>
</head>
<body>
    Enter Search Term:
    <input type="text" id="txtSearch" value="Metallica" />
    <button id="btnWebserviceCaller" type="button">
        Search Itunes</button>
    <br />
    Results:
    <div id="divResults">
    </div>
</body>
</html>


Note: If you are making jquery ajax call to an external domain, the only call you can make is a GET call with  dataType: "jsonp". POST calls are possible only if you are making a call within the domain in which your ajax page is hosted. This is a security restriction enforced by the browser.

Check this out for more info on jquery ajax.

Tuesday, April 3, 2012

Jquery add text to multiline textbox with line breaks

If you select text from a multiline textbox using .text() then the line breaks get lost. Instead of text() use .val() to preserve line breaks in the textbox.


Example


Save the text below with a .htm extension. When you open the .htm file in a browser and click the button, you can see text being added with line breaks (in new line)

<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {

        $("#btn1").click(function () {
            changeTheText();
        });


        function changeTheText() {
            var x = $('#multiLinetxtBox').val() + '\r\n' + new Date();


            $(' #multiLinetxtBox ').val(x);

        };

    });
</script>
<html>
<body>

<textarea style="height: 500px;"  id="multiLinetxtBox" cols="20" rows="2">
line 1
line 2
line 3
</textarea>

<input id="btn1" type="button" value="ClickMe" />
</body>
</html>

Line breaks (textbox, HTML,SQL)

For HTML :    <br/>


For Plain text (use for multiline textbox, plain text email etc) :     \r\n


For SQL : CHAR(13)
example: select ('xx'+CHAR(13)+'yy')