LINQ LIST: Distinct method extension

While operating with collections, sometime we would like to perform Distinct on column, to achieve this we need to write the extension method.


public static class StaticDistinct
{
       public static IEnumerable<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
              HashSet<TKey> knownKeys = new HashSet<TKey>();
              foreach (TSource element in source)
               {
                    if (knownKeys.Add(keySelector(element)))
                    {
                         yield return element;
                    }
                }
          }
 }

// USAGE
var distinctUsers = users.DistinctBy(x => x.EmailId).ToList();

This example also demostrate what are extension methods and syntax of extension method.

Extension Methods:

#1) These are static methods, so these method should be surronded by static class

#2) These method signature would start this keyword. Let’s say you want to write extension method to string then the method would be some thing like below.


// DEFINE EXTENSION METHOD
 public static string ImExtensionMethod(this string value)
 {
   return "Hurray! I am EXTENSION method";
 }

//USAGE
  string whoAreYou = "Hello";
  whoAreYou.ImExtensionMethod();

By now you should be knowing why did we define DISTINCTBY as extension method

Happy Kooding…. Hope this helps!

Advertisements

How to use Kendo Validator / Kendo Validation

For example, I have form which has Salary as input field, now I would like to perform custom validation on this field.

HTML


<div id="DataEntryDiv" style="margin-top:20px">
<div class="editor-label">Salary</div>
<div class="editor-field">
<input id="Salary" type="number" class="input" name="Salary" data-bind="value: Salary" />
</div>
</div>

JAVASCRIPT


<script type="text/javascript">
var myValidator = $("#DataEntryDiv").kendoValidator({

rules: {
SalaryRule: function (input) {
if (input.is("[name=Salary]")) {
return !(parseInt($("#Salary").val()) <= 0);
}
return true;
}
},
messages: {
SalaryRule: "Value must be greater than 0",
},
validateOnBlur: false
}).data("kendoValidator");

function onSave(e) {
if (!myValidator.validate()) {
e.preventDefault();
}
}
</script>

This works with Kendo Grid Pop as well. All you have to do is hook up the save event for kend Grid


@(Html.Kendo().Grid<MyModelClass>()
.Name("myKendoGrid")

.Events(e => e.Save("onSave"))

Happy Kooding… Hope this helps!

Factory Design Patterns

Hi All,

In this article, we will discuss about Factory design pattern

This is type of creational patterns i.e. it helps us to create objects.
The key feature is to create concrete subclasses

Factory Pattern is defined as “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses”

Let’s consider the below issue & also we will see how to resolve this issue with design pattern
Lets say I am developing an application to Client, & client’s requirement is I should develop my application in such a way that if I enable config saying SQL my application should connect to SQL DB & if I enable config saying Oracle it should connect to Oracle.

This kind of issue can be resolved with Factory Design Pattern.
So to fix this I have to write all database related methods with respect SQL & Oracle. Also the connection to database should happen on config.

In this we will define Interface as IConnection, this define all the DB related methods


// Base Interface
public interface IConnection
{
void Display(string conString);
}

I will have class specific to SQL as shown below & this class has to implement IConnection


// A Connection Class that Implements the IConnection Interface
public class SqlConnect : IConnection
{
public void IConnection.Display(string conString)
{
// Method to display data by connecting to SQL Server DB
}
}

I will have class specific to Oracle as shown below & this class has to implement IConnection


// A Connection Class that Implements the IConnection Interface
public class OracleConnect : IConnection
{
public void IConnection.Display(string conString)
{
// Method to display data by connecting to Oracle Server DB
}
}

// The Connection Factory
public class ConnectionFactory
{
public static IConnection getConnection(string connectionType)
{
switch (connectionType)

{
case “Sql”:
return new SqlConnect();
case “Oracle”:
return new OracleConnect();
default:
throw new ApplicationException(string.Format(”ConnectionType ‘{0}’ cannot be created”, connectionType));
break;
}
}
}

Now Lets try with below example
Create a class & add the following code


public interface IConnection
{
string GetStudentById(int stdId);
}

public class SQlConnect : IConnection
{
public SQlConnect()
{
Console.WriteLine(”SQL Connection Class is Called!!!”);
}
public string GetStudentById(int stdId)
{
return “Student name is Mr. Prakash & his ID ” + stdId.ToString() + ” “;
}

}

public class OracleConnect : IConnection
{
public OracleConnect()
{
Console.WriteLine(”SQL Connection Class is Called!!!”);
}
public string GetStudentById(int stdId)
{
return “Student name is Mr. Prakash & his ID ” + stdId.ToString() + ” “;
}

}

Let’s create a web page & name the page as “FactoryPattern” and add the following code


public enum ConnectionType
{
Sql, Oracle
}

static FactoryPattern()
{
}
public static IConnection CreateConnectionObject(ConnectionType TypeOfConnection)
{
switch (TypeOfConnection)
{
case ConnectionType.Oracle:
return new OracleConnect();
case ConnectionType.Sql:
return new SQlConnect();
default:
throw new ArgumentException(”Invalid Connection Type!”);
}
}

In the page load event add the following code


IConnection connT;

if (ConfigurationManager.AppSettings[”ConnectionType”] == “1″)
{
connT = FactoryPattern.CreateConnectionObject(FactoryPattern.ConnectionType.Sql);
}
else
{
connT = FactoryPattern.CreateConnectionObject(FactoryPattern.ConnectionType.Oracle);

}

string str = connT.GetStudentById(1);

/* the above lines of codes clearly states that object return type is defined based on config entry only & in future we need to add another connection type we can still do it with lot minimal changes without affecting the existing changes */

Happy Koooding….. Hope this helps !!!!

Integrate Facebook LIKE button

  1. Open the below link

http://developers.facebook.com/docs/reference/plugins/like/

 

  1. Specify the url of your site in below text area with other appropriate values

  1. Now click, Get Code button & this would generate code as shown below

 

  1. Copy the code, click Okay & paste it in your web page, where you want to show LIKE button.

 

 

Similar way we generate Open Graph tags. Open Graph tags are <meta> tags that you add to the <head> of your website to describe the entity your page represents, whether it is a band, restaurant, blog, or something else.

 

An Open Graph tag looks like this:

<meta property="og:tag name" content="tag value"/>

 

Happy Kooding…. Hope this helps!!!

Google Analytics, Google Web Master Tool, Google Feed burner

Google Analytics, is the one which will help us in see the site traffic details like

  1. From which country we have huge hits
  2. Pages which are viewed the most
  3. And more, see the below pic

Google Web Master Tool: Using this tool we can ask google to crawl our site, doing so this create indexing our site in Google records, which intern increase site traffic. See below screen how to do

  1. First add our site in Google Web Master tool

Look at the options in left menu in below option.

We can create google gadets & submit. These gadgets can be added to iGoogle

Google Feed burner: This is another tool from google related to RSS Feeds

We need to use Google Meta Tag that will increase rankings of site

We need to create Email Account by our brand name, Funky Asian. Using this account we will manage all above thing

Blogs, Facebook, Twitter, Google, Yahoo, Hotmail etc.

If by change user is tying our brandname, then our funky site detail information will show which will help to increase traffic

Blogger & Word Press are free site where we can create blog & post our blogs.

We will find more similar site for this.

Calling Web Service from Javascript

Hi,

Now we will discuss how to call web service from javascript.

This example demonstrates of

1. Calling web service method from javascript after page loads completely (async) &

2. This method returns XML string &

3. Displays XML node content div &

4. Between if there is any delay from web service, we need to show loading image or loading text.

Lets get into details

  • Add new Item, select webservice from template & name it as “ServiceOne.asmx”
    • Add  [System.Web.Script.Services.ScriptService] attribute to ServiceOnce class
    • Add below method to ServiceOne class
    • [WebMethod]publicstring GetResponse(string callerName){string txt = string.Empty;txt = “<bookstore><book>”;txt = txt + “<title>Everyday Italian</title>”;txt = txt + “<author>Giada De Laurentiis</author>”;txt = txt + “<year>2005</year>”;txt = txt + “</book></bookstore>”;if (callerName == string.Empty)thrownewException(“Web Service Exception: invalid argument”);Thread.Sleep(5000); // To get response delay, forced to sleepreturnstring.Format(txt.ToString());}  
  • Add Script Manager and add Service reference to default.aspx as shown below

<asp:ScriptManagerID=”ScriptManager1″runat=”server”> <Services><asp:ServiceReferencePath=’~/ServiceOne.asmx’/></Services></asp:ScriptManager>

  • Now lets add DIV, which will show loading text if there is any delay response from Web Service & when there is response from web service it will  display XML NODE content

 <divid=”lblResponse”></div>

  • Now Lets the javascript function code which will call web method & the response from web method can be Success/Completed response, TimeOut response & Error response. Below sendRequest function is called in BodyLoad event, & first statement shows loading text in div until we get response from Web Service

This function pass static string value to web method & response will be either completed, timeout or error. So we define respective function names in web method calls.

ServiceOne is web service

GetResponse is web method defined in ServiceOne service class

function SendRequest() {document.getElementById(“lblResponse”).innerHTML = “Please wait loading……. “;ServiceOne.GetResponse(

“TESTING TO BE ……..”, OnComplete, OnError, OnTimeOut);}

  • On Success/Complete reponse we need to parse XML string & read the Title XML node from XML string & display in lblResponse DIV as shown below

function OnComplete(arg) {//alert(arg);

if (window.DOMParser) {parser = new DOMParser();xmlDoc = parser.parseFromString(arg,

“text/xml”);}

else// Internet Explorer

{

xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);xmlDoc.async = “false”;xmlDoc.loadXML(arg);

}

x = xmlDoc.getElementsByTagName(“title”)[0];y = x.childNodes[0];

txt = y.nodeValue;

document.getElementById(“lblResponse”).innerHTML = txt;}

  • Whenever there is ErrorReponse then below function will be called

function OnTimeOut(arg) {alert(“timeOut has occured”);}

  • Whenever there is TimeOut response below function will be called

function OnError(arg) {alert(“error has occured: “ + arg._message);}

  • Finally call sendRequest JS function in body load event as shown below

<bodyonload=”return SendRequest();”>

  • Now lets execute this & checkout the output

HTTP Error 500.19 – Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid

  1. Go to “C:\Windows\System32\inetsrv\config”. [Note: you need to have admin rights to modify applicationHost.config file]
  2. Now open applicationHost.config
  3. Look for “modules” or “handlers” based on error message
  4. Change the overrideModeDefault attribute from “Deny” to “Allow”. In my case it is with handlers. So I modified it accordingly.

<section name=”handlers” overrideModeDefault=”Allow” />