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!

ORACLE: Looping through data using CURSORS

Below the syntax for creating the cursors in Oracle. This example also demostrates creating of procedures in Oracle


CREATE OR REPLACE PROCEDURE MYSCHEMA.GET_EMAILS AS

 EMAIL_ID VARCHAR2(100);
 
 CURSOR CUR IS SELECT EMAIL_ADDRESS FROM MYSCHEMA.USERS; /* DEFINE CURSOR */
 
BEGIN
 
 OPEN CUR; /* OPEN THE CURSOR */
 
 LOOP /* LOOP */
 
 FETCH CUR INTO EMAIL_ID; /* READ THE CURSOR VALUE */
 
 EXIT WHEN CUR%NOTFOUND; /* EXIT WHEN DATA NOT FOUND */
 
 DBMS_OUTPUT.PUT_LINE(EMAIL_ID); /* PRINT THE VALUE / PROCESS ACCORDING TO YOUR NEED */
 
 
 END LOOP; /* END OF LOOP */
 
 CLOSE CUR; /* FINALLY RELASE/CLOSE THE CURSOR */
END;
/

Happy Kooding.. Hope this helps!

Error: multiple actions were found that match the request

If this error is happening with Web API then below is the reason

Usually App_Start/WebApiConfig contains route as


config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });

So change the above configuration to


config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });

Happing Kooding… !

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!

Tips/Tricks about KENDO

1) KENDO GRID: At anygiven time, if you want to access the edited or added data (before reload of grid/save)

var editableModel = $('#myGrid').data().kendoGrid.editable.options.model;

2) KENDO GRID: If you would like to update one of the property value manually for recent edited record in grid then


var editableModel = $('#myGrid').data().kendoGrid.editable.options.model;
editableModel.set("dobDate", '05/31/1983');

3) MONTH PICKER: Implementing month picker with Kendo. This would work with Grid Edit Pop also.

<input id="dobDate" type="date" class="input" name="dobDate" data-bind="value: dobDate" />
$(document).ready(function () {
 

$("#dobDate").kendoDatePicker({
start: "year",
depth: "year",
format: "MMMM yyyy",
parseFormats: ["MMMM yyyy"]
});


});

Month Picker cannot be achieved with Model binder as there is a known bug. The only available is the above

4) KENDO GRID: Format/Parse the date column (bound column)

columns.Bound(m =&amp;gt; m.DobDate).Width(50).Title("Dob Date").ClientTemplate("#= DobDate &amp;lt; 1/1/1900 ? '' : &nbsp; kendo.format('{0:MMMM yyyy}', DobDate) #")

5) KENDO DATE PICKER: Disable the control by editing it

<input id=”dobDate” type=”date” class=”input” name=”dobDate” onkeydown=”return false;”  data-bind=”value: dobDate” />

6) KENDO FILTER OPERATORS: Below are the few filter operators

  filter.push({ field: "IsNew", operator: "eq", value: 1 });

eqgtgteltteneq

7) READONLY:

 @(Html.Kendo().DatePicker().Value(DateTime.Now)
 .Name("myDate").Min(DateTime.Now)
 .HtmlAttributes(new { style = "width: 100%", @readonly="readonly" }))

or


$("#myDate").kendoDatePicker(); 

var myDate= $("#myDate").data("kendoDatePicker"); 

myDate.readonly(true);

8) NUMERIC TEXTBOX: Don’t allow decimal value and don’t allow negative value (define min value)

a) format allows you to ignore/avoid entering decimal value

b) min allows you to set the min value to zero


$("#Hours").kendoNumericTextBox({ decimals: 0, format: "#", min: 0 });

9) HIDE/SHOW KENDO DROPDOWNLIST: Below is the syntax to hide/show kendo dropdownlist
HIDE:

 $("#ddlCountries").closest(".k-widget").hide();

SHOW:

 $("#ddlCountries").closest(".k-widget").show();

10) Kendo Grid Filter Configuration : For a Kendo Grid, if you would like to customize the filter menu below is how you can do


@(Html.Kendo().Grid<UserModel>()
    .Name("MyGrid")
    .ColumnMenu()
    .Filterable(f => f.Operators(o => o.ForString(s => s
        .Clear()
        .Contains("Contains")
        .DoesNotContain("Does not contain")
        .EndsWith("Ends with")
    )))
// other configuration goes
)

If you would like to customize to a specific column then you would do same above filter configuration to a column rather than entire grid


@(Html.Kendo().Grid<UserModel>()
    .Name("MyGrid")
    .Columns(columns =>
          {
              columns.Bound(m => m.UserName)
              .Filterable(f => f.Operators(o =>
              o.ForString(s => s.Clear().Contains("Contains")
              .DoesNotContain("Does not contain")
              .EndsWith("Ends with")
    )))

})
)

11) Kendo Grid Clear Selected Row :


            var grid = $("#myGrid").data("kendoGrid");
            grid.clearSelection();

Happy Koooding…..  Hope this helps!….

Send Email from Oracle

Below is the procedure used to send email from Oracle. This proc takes email content in varchar datatype or clob datatype.


CREATE OR REPLACE PROCEDURE myschema.send_email(
p_from in varchar2,
p_to in varchar2,
p_subject in varchar2,
p_text in varchar2 default null,
p_html in varchar2 default null,
p_smtp_hostname in varchar2,
l_clob_html IN CLOB DEFAULT NULL)
is
l_boundary varchar2(255) default 'a1b2c3d4e3f2g1';
l_connection utl_smtp.connection;
l_body_html clob := empty_clob; --This LOB will be the email message
l_offset number;
l_ammount number;
l_temp varchar2(32767) default null;
begin
l_connection := utl_smtp.open_connection( p_smtp_hostname);
utl_smtp.helo( l_connection, p_smtp_hostname );
utl_smtp.mail( l_connection, p_from );
utl_smtp.rcpt( l_connection, p_to );

l_temp := l_temp || 'MIME-Version: 1.0' || chr(13) || chr(10);
l_temp := l_temp || 'To: ' || p_to || chr(13) || chr(10);
l_temp := l_temp || 'From: ' || p_from || chr(13) || chr(10);
l_temp := l_temp || 'Subject: ' || p_subject || chr(13) || chr(10);
l_temp := l_temp || 'Reply-To: ' || p_from || chr(13) || chr(10);
l_temp := l_temp || 'Content-Type: multipart/alternative; boundary=' ||
chr(34) || l_boundary || chr(34) || chr(13) ||
chr(10);

----------------------------------------------------
-- Write the headers
dbms_lob.createtemporary( l_body_html, false, 10 );
dbms_lob.write(l_body_html,length(l_temp),1,l_temp);

----------------------------------------------------
-- Write the text boundary
l_offset := dbms_lob.getlength(l_body_html) + 1;
l_temp := '--' || l_boundary || chr(13)||chr(10);
l_temp := l_temp || 'content-type: text/plain; charset=us-ascii' ||
chr(13) || chr(10) || chr(13) || chr(10);
dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);

----------------------------------------------------
-- Write the plain text portion of the email
if p_text is not null and p_text != ' ' then
l_offset := dbms_lob.getlength(l_body_html) + 1;
dbms_lob.write(l_body_html,length(p_text),l_offset,p_text);
end if;

----------------------------------------------------
-- Write the HTML boundary
l_temp := chr(13)||chr(10)||chr(13)||chr(10)||'--' || l_boundary ||
chr(13) || chr(10);
l_temp := l_temp || 'content-type: text/html;' ||
chr(13) || chr(10) || chr(13) || chr(10);
l_offset := dbms_lob.getlength(l_body_html) + 1;
dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);

----------------------------------------------------
-- Write the HTML portion of the message

if p_html is not null and p_html != ' ' then
l_offset := dbms_lob.getlength(l_body_html) + 1;
dbms_lob.write(l_body_html,length(p_html),l_offset,p_html);
end if;

if l_clob_html is not null then
l_offset := DBMS_LOB.GETLENGTH(l_body_html) + 1;
DBMS_LOB.COPY(L_BODY_HTML, l_clob_html, DBMS_LOB.GETLENGTH(l_clob_html), L_OFFSET, 1);
end if;

----------------------------------------------------
-- Write the final html boundary
l_temp := chr(13) || chr(10) || '--' || l_boundary || '--' || chr(13);
l_offset := dbms_lob.getlength(l_body_html) + 1;
dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);
--DBMS_OUTPUT.put_line (l_body_html);

----------------------------------------------------
-- Send the email in 1900 byte chunks to UTL_SMTP
l_offset := 1;
l_ammount := 1900;
utl_smtp.open_data(l_connection);
while l_offset &lt; dbms_lob.getlength(l_body_html) loop
utl_smtp.write_data(l_connection,
dbms_lob.substr(l_body_html,l_ammount,l_offset));
l_offset := l_offset + l_ammount ;
l_ammount := least(1900,dbms_lob.getlength(l_body_html) - l_ammount);
end loop;
utl_smtp.close_data(l_connection);
utl_smtp.quit( l_connection );
dbms_lob.freetemporary(l_body_html);
commit;
end;
/

Happy Kooding… Hope this helps!

ORACLE: QUERY TO FIND Nth HIGHEST SALARY (in all or in each DEPARTMENT)

Below query will give you N highest salary wrt all Departments


SELECT * FROM
(SELECT EMP.*, ROW_NUMBER() OVER (ORDER BY SALARY DESC) RN FROM EMPLOYEE EMP) EMP_RANK
WHERE EMP_RANK.RN = N;

Below query will give you N highest salart wrt to each department


SELECT * FROM

(SELECT EMP.*, DENSE_RANK() OVER(PARTITION BY DEPT_ID ORDER BY SALARY) RN
FROM EMPLOYEE EMP) EMP_RANK

WHERE EMP_RANK.RN = N;

Happy Kooding… Hope this helps!

Parse Date string using Kendo in Javascript

If your date is in /Date(“14201020200”)/ format and would like to format this date string to MM/dd/yyyy using Kendo??

If yes then the syntax to do that is


kendo.toString(kendo.parseDate(dateString), 'MM/dd/yyyy')

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!!!