Tech NovoGeek

...Technology Simplified

Thursday, May 31, 2012

VB equivalent to C# typeof() keyword

No comments :

typeof(Foo)

In VB...it's...

GetType(Foo)

Triggers in Updatepanel [AJAX]

No comments :
The UpdatePanel control is allowing partial rendering of the area.
The tag has two childtags - the ContentTemplate and the Triggers tags.
The ContentTemplate tag is mandatory one,since it holds the content of the panel. The content can be anything that you would normally put on your page, from literal text to web controls.
The Triggers tag allows you to define certain triggers which will make the panel update it's content.
Here is an example which uses both childtags.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>UpdatePanel</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateButton2" eventname="Click" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateTimeLabel1" />
<asp:Button runat="server" id="UpdateButton1" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
<ContentTemplate>
<asp:Label runat="server" id="DateTimeLabel2" />
<asp:Button runat="server" id="UpdateButton2" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

protected void UpdateButton_Click(object sender, EventArgs e)
{
DateTimeLabel1.Text = DateTime.Now.ToString();
DateTimeLabel2.Text = DateTime.Now.ToString();
}
Build the application and click the two buttons.
You will notice that then first button updates only the first datestamp, while the second button updates both.

If you observe clearly the two buttons are placed in two update panels.

So First button in updatepanel 1 updates first timestamp.

Whereas second button in updatepanel2 updates both because the second update button is referred from first updatepanel using trigger tag.
As you can see, the first UpdatePanel carries a trigger which references the second button.
This will ensure that the first panel is updated even when a control on a different UpdatePanel is used.

The AsyncPostBackTrigger tag is pretty simple - it only takes two attributes

1.controlid, a reference to the control which can trigger it,

2.eventname, which tells which eventtype can cause the trigger to fire.

If you wish for the content of a UpdatePanel to be updated no matter what, you may change the updatemode property to Always.

Wednesday, May 30, 2012

Insert an image in select control

No comments :
 
select#colormenu option[value=&quot;Red&quot;]
{
background-image:url(red.png) ;
background-repeat:no-repeat;
}
select#colormenu option[value=&quot;Green&quot;]
{
background-image:url(red.png) ;
background-repeat:no-repeat;
}
select#colormenu option[value=&quot;Blue&quot;]
{
background-image:url(red.png) ;
background-repeat:no-repeat;
}
select.icon-menu option
{
background-repeat:no-repeat;
background-position:bottom left;
padding:0px 0px 0px 20px;
}


<select  id="colormenu" class="icon-menu">
<option value="none">Select color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>


clip_image001



But one issue with this code is it doesnt work on all browsers , but still it doesnt mess up the design..

Thursday, May 24, 2012

sampledata

No comments :

'
' Macro2 Macro
'
Dim i As Integer

For i = 1 To 20

'Cells(i, "D").Select
'  Selection.Copy
'  Cells(i, "G").Select
  '  ActiveSheet.Paste
  If Cells(i, "D") = Cells(i, "G") Then
  Cells(i, "A").Select
    With Selection.Font
        .Color = -16776961
        .TintAndShade = 0
    End With
  Else
 
  With Selection.Font
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With
  End If
 
 
Next

To get Tree Structure from Table using CTE in SQL Server

No comments :
Here is an example to get hierarchy of categories example
DECLARE	@CATEGORIES	TABLE	
(
CATEGORYID INT,
CATEGORYNAME VARCHAR(100),
PARENTCATEGORYID INT
)
INSERT @CATEGORIES VALUES (1,'VEHICLE' ,NULL)
INSERT @CATEGORIES VALUES (2,'CAR' ,1)
INSERT @CATEGORIES VALUES (3,'BMW' ,2)
INSERT @CATEGORIES VALUES (4,'MERCEDES BENZ',2)
INSERT @CATEGORIES VALUES (5,'BIKES' ,1)
INSERT @CATEGORIES VALUES (6,'YAMAHA' ,5)
SELECT *
FROM @CATEGORIES
/*
CATEGORYID CATEGORYNAME PARENTCATEGORYID
---------- ------------ -----------------
1 VEHICLE NULL
2 CAR 1
3 BMW 2
4 MERCEDES BENZ 2
5 BIKES 1
6 YAMAHA 5
*/

;WITH CTE AS(
SELECT CATEGORYID,
CATEGORYNAME,
PARENTCATEGORYID,
CONVERT(VARCHAR(MAX),CATEGORYNAME) TREE
FROM @CATEGORIES
WHERE PARENTCATEGORYID IS NULL
UNION ALL
SELECT C.CATEGORYID,
C.CATEGORYNAME,
C.PARENTCATEGORYID,
P.TREE + ' / ' + CONVERT(VARCHAR(MAX),C.CATEGORYNAME)
FROM @CATEGORIES C
JOIN CTE P
ON C.PARENTCATEGORYID = P.CATEGORYID
)
SELECT *
FROM CTE
/*
CATEGORYID CATEGORYNAME PARENTCATEGORYID TREE
---------- ------------ ---------------- ----
1 VEHICLE NULL VEHICLE
2 CAR 1 VEHICLE / CAR
5 BIKES 1 VEHICLE / BIKES
6 YAMAHA 5 VEHICLE / BIKES / YAMAHA
3 BMW 2 VEHICLE / CAR / BMW
4 MERCEDES BENZ 2 VEHICLE / CAR / MERCEDES BENZ
*/

Execute a function in C# for every 2 seconds–Windows application

No comments :

I have implemented a sample code to display incremented value of label on button click.
Timer event starts only after button is clicked.
Place label and button on the form and handle button click event.

        private void button1_Click(object sender, EventArgs e)
{
InitTimer();
}
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimerCounter();
}
int i = 0;
private void TimerCounter()
{
i = i + 1;
label1.Text = i.ToString();
}


timer

What is GUID

No comments :
GUIDs are large, enormous numbers that are nearly guaranteed to be unique. They are usually 128 bits long and look like this in hexadecimal:

30dd879c-ee2f-11db-8314-0800200c9a66

The format is a well-defined sequence of 32 hex digits grouped into chunks of 8-4-4-4-12. This gives us 2^128 or about 10^38 numbers.

Here’s the thinking behind GUIDs:

If you pick a huge random number (39 digits long), it’s really unlikely that someone will pick the same one.
GUIDs are not tied to a product. A GUID can be used for people, cars, files, webpages, colors, anything. With regular registration numbers, you start counting at 1 and numbers can overlap. Social Security Number 123-45-6789 is different from ISBN 123456789 which is different from barcode 123456789. This isn’t an issue with GUIDs.
It’s up to the person reading the GUID to figure out the context of the GUID. There are so many GUIDs that you can use them to number everything and not run out.
GUIDs give you a unique serial number that can be used on any item in the universe.

Open project created in VS 2010 to 2008

No comments :
If you are working with VS 2010 (any edition) and cannot open your 2010 solution on VS 2008, then just follow these 3 steps:

For .sln:

Open the solution file in your favorite text editor (example: Notepad++).
Find the following:
Microsoft Visual Studio Solution File, Format Version 11.00.
# Visual Studio 2010.
Replace with:
Microsoft Visual Studio Solution File, Format Version 10.00. (I)
# Visual Studio 2008. (II, optional)

For .csproj/vbproj:

Open project file in your favorite text editor (example: Notepad++).
Find the following:
.
Replace with:
. (III)
That's it.
Now you can open your solution file on VS2008.
Reverse of this will enable VS2008 solution to open in VS2010.

EDIT

After these changes, you may receive the below error:

---------------------------
Microsoft Visual Studio
---------------------------
Unable to read the project file 'XXX.csproj'.


C:\Project path\XXX.csproj(89,11): The imported project "C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found.
Confirm that the path in the declaration is correct, and that the file exists on disk.
---------------------------
OK Cancel

---------------------------


To fix this error, just change the VS version(v10.0 to v9.0) in your .csproj/vbproj file, that's all.

SQL Server 2012 - Always On Deep Dive

No comments :

I attended an event held in Microsoft,Dublin on 23 May 2012 on SQL Server 2012 – Always on Deep Dive.

It is presented by Bob Duffy,a SQL Server MVP from Dublin, Ireland who is both MCA and MCM certified.

During the demonstration he explained how to seamlessly upgrade a database from SQL 2005+ to Denali with ZERO down time and then use the Always on features to simplify reporting, availability and disaster recovery.

The demo included capabilities of the new "Always On" features such as read only secondaries and consistency groups.
This session will be helpful for anyone who is working in a high availability environment or currently using replication to provide reporting and looking for a neater solution.

Here is the attached demo presentation presented in MTUG.ie

EXPERTS EXCHANGE Certified C# Programming Language Master

No comments :

I have been Experts Exchange member since 09/09/2010. But been idle until Mid of March 2012 and haven't earned any points during the 2 years .

After good contribution to the community in the last 2 months, and earning 90000 points each month , I earned my first certification in C# -- Certified C# Programming Language Master.

Here is my certification

image

Wednesday, May 23, 2012

How to implement joins in LINQ

No comments :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQPractice
{
class Department
{
public int DeptId { get; set; }
public string DeptName { get; set; }
public string Location { get; set; }
}
class Joins
{
static void Main(string[] args)
{
List employees = new List
{
new Employee{EmpId=100,EmpName="sachin",Salary=15000,DeptName="sales"},
new Employee{EmpId= 101,EmpName="scott",Salary=12000,DeptName="hr"},
new Employee{EmpId=102,EmpName="rahul",Salary=13000,DeptName="it"},
new Employee{EmpId=103,EmpName="ilyas",Salary=13000,DeptName="sales"}
};

List departments = new List
{
new Department {DeptId=1,DeptName="sales",Location="Dublin"},
new Department {DeptId=1,DeptName="hr",Location="Dublin"},
new Department {DeptId=1,DeptName="it",Location="Hyderabad"}
};

Console.WriteLine("Join using LINQ Query");
var joinquery = from emp in employees
join dept in departments
on emp.DeptName equals dept.DeptName
select new { Name = emp.EmpName, Dept = dept.DeptName, Location = dept.Location };
foreach (var item in joinquery)
{
Console.WriteLine("{0,-8}{1,-7}{2,-10}", item.Name, item.Dept, item.Location);
}
Console.ReadLine();
}
}
}

How to Use Group By in LINQ

No comments :
When you are familiar with SQL Queries it is just the same way to implement in C# as well.

from emp in employees
group emp by emp.Salary into grp
select grp;


The above code indicates that --> based on employee salary group employees into group grp;
Key is the group column value;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQPractice
{
class GroupBy
{

static void Main(string[] args)
{
List employees = new List
{
new Employee{EmpId=100,EmpName="sachin",Salary=15000},
new Employee{EmpId=101,EmpName="scott",Salary=12000},
new Employee{EmpId=102,EmpName="rahul",Salary=13000},
new Employee{EmpId=103,EmpName="ilyas",Salary=13000}
};

Console.WriteLine("Group operators:");
var query = from emp in employees
group emp by emp.Salary into grp
select grp;
foreach (var group in query)
{
Console.WriteLine(group.Key);

foreach (var emp in group)
{
Console.WriteLine("{0,-5}{1,-8}{2,-6}",emp.EmpId ,emp.EmpName,emp.Salary);
}
}
Console.ReadLine( );
}
}
}

Getting started with LINQ

No comments :
Linq is integrated in Visual studio as Query language.
In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable interface.
The only requirement is that the project target .NET Framework 3.5 or later.

Lets get started with sample class implemented to explain LINQ.
Before we go straight into LINQ, there are couple of other features like Predicate Expression,delegates,Lambda expressions are explained in the same code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQPractice
{
public class Employee
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public double Salary { get; set; }
public string DeptName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Employee[] employees = new Employee[]
{
new Employee{EmpId=100,EmpName="sachin",Salary=15000},
new Employee{EmpId= 101,EmpName="scott",Salary=12000},
new Employee{EmpId=102,EmpName="rahul",Salary=13000},
new Employee{EmpId=103,EmpName="ilyas",Salary=14000}
};

Console.WriteLine("Display using predicate expression");
Console.WriteLine("----------------------------------");
Employee sachin = Array.Find(employees, FindEmployeePredicate);
Console.WriteLine("{0,-5}{1,-8}{2,-6}",sachin.EmpId,sachin.EmpName ,sachin.Salary );
Console.ReadLine();

Console.WriteLine("Display using Delegates");
Console.WriteLine("----------------------------------");
Employee scott = Array.Find(employees,
delegate(Employee emp)
{
return emp.EmpName == "scott";
});
Console.WriteLine("{0,-5}{1,-8}{2,-6}", scott.EmpId, scott.EmpName, scott.Salary);
Console.ReadLine();

Console.WriteLine("Display using Lambda expression");
Console.WriteLine("----------------------------------");
Employee rahul = Array.Find(employees,e=>e.EmpName =="rahul");
Console.WriteLine("{0,-5}{1,-8}{2,-6}", rahul.EmpId, rahul.EmpName, rahul.Salary);
Console.ReadLine();

Console.WriteLine("--------LINQ IMPLEMENTATION-------");
Console.WriteLine("Displaying single row query result");
Console.WriteLine("----------------------------------");
Employee ilyas = (from emp in employees
where emp.EmpName=="ilyas"
select emp).Single();
Console.WriteLine("{0,-5}{1,-8}{2,-6}", ilyas.EmpId, ilyas.EmpName, ilyas.Salary);
Console.ReadLine();

Console.WriteLine("Displaying list of rows query result");
Console.WriteLine("----------------------------------");
Employee[] list = (from emp in employees
select emp).ToArray();
foreach (var item in list)
{
Console.WriteLine("{0,-5}{1,-8}{2,-6}", item.EmpId, item.EmpName, item.Salary);
}
Console.ReadLine();

Console.WriteLine("Displaying query result -- with Order by");
Console.WriteLine("----------------------------------");
Employee[] list1 = (from emp in employees
orderby emp.EmpName
select emp).ToArray();
foreach (var item in list1)
{
Console.WriteLine("{0,-5}{1,-8}{2,-6}", item.EmpId, item.EmpName, item.Salary);
}
Console.ReadLine();

Console.WriteLine("Displaying specific columns of query result");
Console.WriteLine("----------------------------------");
var list2 = (from emp in employees
orderby emp.EmpName
select new {Name = emp.EmpName,Salary = emp.Salary});
foreach (var item in list2)
{
Console.WriteLine("{0,-8}{1,-6}", item.Name, item.Salary);
}
Console.ReadLine();

}

static bool FindEmployeePredicate(Employee emp)
{
return emp.EmpName == "sachin";
}
}
}

Tuesday, May 22, 2012

Play music in javascript alert

No comments :
you cannot put a sound to an alert. The alert sound - is what the user specifies on the computer. You can though make a function that plays a sound when the user hits okay on an alert. Use the sample code and change the mp3 file name which is in your system






Click Here



SQL GROUP BY techniques

No comments :
One aspect of SELECT statement that seems to confuse many people is the GROUP BY clause. It is very important to group your rows in the proper place. Always push GROUP BY aggregations as far into your nested SELECT statements as possible – if you have a situation in which you are grouping by long lists of columns that are not part of primary keys, you are probably have not structured your query correctly. Here's a classic example that returns total sales per customer, in addition to returning the customer's name and address:

SELECT
C.CustomerID, C.CustomerName,
C.CustomerType, C.Address1, C.City,
C.State, SUM(S.Sales) as TotalSales
FROM
Customers C
INNER JOIN Sales S
ON C.CustomerID = S.CustomerID
GROUP BY
C.CustomerID, C.CustomerName,
C.CustomerType, C.Address1, C.City, C.State

If you observe in detail, SELECT's written this way is simply wrong. You should only be grouping on CustomerID, and not on all those other columns. Push the grouping down a level, into a derived table:

SELECT
C.CustomerID, C.CustomerName,
C.CustomerType, C.Address1, C.City,
C.State, S.TotalSales
FROM
Customers C
INNER JOIN
(SELECT
CustomerID, SUM(Sales) as TotalSales
FROM
Sales
GROUP BY
CustomerID) S
ON
C.CustomerID = S.CustomerID

Now this is a much cleaner SELECT statement now, it is more efficient and it logically makes more sense when you look at it.

One more common mistake is that people just mimic the expressions in their SELECT list in the GROUP BY clause, without thinking logically about what grouping is really necessary. For example:

SELECT LastName + ', ' + FirstName, ... etc ...
FROM Names
GROUP BY LastName + ', ' + FirstName

Again, that is logically wrong and also less efficient. You should not be grouping by the expression itself; you should be grouping by what is needed to evaluate that expression. The correct grouping is:

GROUP BY LastName, FirstName

Too many people just keep stuffing column names and expressions into the GROUP BY clause until the errors go away without stepping back and thinking logically about how grouping works. Take a minute to really consider what you need to return and how it should be grouped, and try using derived tables more frequently when writing aggregate queries to help keep them structured and efficient.
Courtesy: http://weblogs.sqlteam.com/jeffs/archive/2005/12/14/8546.aspx

Monday, May 21, 2012

How to send email in PHP

No comments :
index.html


<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<center>
<table border="1" bgcolor="red">
<tr>
<td>
<form name="form" method="post" action="mail.php">
<center>To: <input type="text" name="to"><br></center>
<center>From: <input type="text name="from"><br></center>
<center>Subject: <input type="text" name="subject"><br></center>
<center>Message:<br><textarea name="message" rows=4 cols=25></textarea></center><br>
<center><input type="submit" value="send"></center>
</td>
</tr>
</body>
</html>


mail.php


<?php
$to = $_POST['to'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$from = $_POST ['from'];
$headers = "From: $from";
// Please specify your Mail Server - Example: mail.yourdomain.com.
ini_set("SMTP","emailserver.sample.data.com");
// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","25");
// Please specify the return address to use
ini_set('anuradha@xyz.com', 'anuradha@xyz.com');

$message = '<html><body>';
$message .= '<img src="http://css-tricks.com/examples/WebsiteChangeRequestForm/images/wcrf-header.png" alt="Website Change Request" />';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['req-name']) . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['from']) . "</td></tr>";
$message .= "<tr><td><strong>Comments:</strong> </td><td>" . strip_tags($_POST['message']) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";


$mail_sent = @mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
?>




Thursday, May 17, 2012

Add a Drop Down List into Excel File using C# .NET

No comments :
Here is sample code to add a drop down list into an Excel File using C# .NET.
Before you adding this codes, make sure you have add the Microsoft Excel Object Library from COM as reference into your project.

Here are the codes:

using Microsoft.Office.Interop.Excel ;
protected void Button1_Click(object sender, EventArgs e)
{
string Filename = "samp.xls";
Application xlsApp = new Application();
Workbook xlsWorkbook;
Worksheet xlsWorksheet;
object oMissing = System.Reflection.Missing.Value;

//Create new workbook
xlsWorkbook = xlsApp.Workbooks.Add(true);

//Get the first worksheet
xlsWorksheet = (Worksheet)(xlsWorkbook.Worksheets[1]);

string[] ddl_item = { "Answers", "Autos", "Finance", "Games", "Groups", "HotJobs",
"Maps", "Mobile Web", "Movies", "Music", "Personals", "Real Estate", "Shopping", "Sports",
"Tech", "Travel", "TV", "Yellow Pages" };

Range xlsRange;
xlsRange = xlsWorksheet.get_Range("A1", "A1");

DropDowns xlDropDowns;
DropDown xlDropDown;
xlDropDowns = ((DropDowns)(xlsWorksheet.DropDowns(oMissing)));
xlDropDown = xlDropDowns.Add((double)xlsRange.Left, (double)xlsRange.Top, (double)xlsRange.Width, (double)xlsRange.Height, true);

//Add item into drop down list
for (int i = 0; i < ddl_item.Length; i++)
{
xlDropDown.AddItem(ddl_item[i], i + 1);
}

xlsApp.DisplayAlerts = false;
xlsWorkbook.Close(true, Filename, null);
xlsApp.Quit();

xlsWorksheet = null;
xlsWorkbook = null;
xlsApp = null;

}

Current file is saved in My Documents [C:\Users\\Documents]

Username Password in WAMPServer MYSQL

No comments :
If you have wamp installed , and if you would like to know how to create username and password in mysql.
Go to http://localhost/phpmyadmin [if port changes for WAMP server use http://localhost:8080/phpmyadmin]
and click on the Privileges tab. There is a "Add a new user" link.

alt text

You can also refer to MySQL documentation on creating new user accounts.

In short, you create a user by running a CREATE USER statement:

CREATE USER "" IDENTIFIED BY "";
Once the user is created, you give him access to do things by using the GRANT statement.

Could not execute menu item (internal error) :The service has not been started

No comments :
When working with WampServer the icon always stays yellow/orange and never turns green.
I found the solution!
under Apache open the httpd.conf and change the lines

#Listen 12.34.56.78:80
Listen 80
to
#Listen 12.34.56.78:80
Listen 8080

Save the file and select “restart all services”
it works!
That just means that something has captured port 80 before apache can get hold of it.

If you would like to know how to find the offending process.
Open a command window "Run As Administrator".
Then run
>netstat -aon
Look at the output under the "Local Address" column for something using :80

Wednesday, May 16, 2012

Free eBooks from Microsoft

No comments :
Here is list of Microsoft Press Ebooks in three formats - PDF, Mobi (Kindle) and epub. http://blogs.msdn.com/b/microsoft_press/archive/2012/05/04/free-ebooks-great-content-from-microsoft-press-that-won-t-cost-you-a-penny.aspx

Unable to open .chm HTML Help files

No comments :
Couple of times we find it difficult to open HTML help file and when we open topics in the .chm file cannot be viewed and it is because of getting blocked and all you have to do is to unblock the file and this time you can see the contents :-)

Steps to Unblock is:
1. Right-click the CHM file, and then click Properties.
2.Click Unblock.
3.Double-click the .chm file to open the file.
More information is available in the KB article - http://support.microsoft.com/kb/902225/EN-US/

WCF Vs Web Services

No comments :

WCF/ASP.Net Web Services are used for developing web services. Here is a list of differentiation between these two.

Feature

ASP.NET Web Service

WCF

Data Transformation

To and from Data Transition is done through XML Serializer

DataContractSerializer is used for data transition

File Extension

asmx

.svc

Webmethods vs DataContract Attributes

ASP.NET WebService uses Webmethods to translate .NET FW types in to XML.

WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types in to XML.

Limitations

Only Public fields or Properties of .NET types can be translated into XML.Only the classes which implement IEnumerable interface. ICollection interface can be serializable

Public/Private fields or properties of .NET types can be translated.

IDictionary Interface class

Classes that implement the IDictionary interface, such as Hash table can not be serialized.

The DataContractSerializer can translate the Hash Table into XML. Hence using WCF we can even translate HashTable into XML

Security

WCF is more secured than WebService

It is based on WS Standards. capable to run in any .NET executable, so it needs independent security capabilities.

Transfer security=Responsible for providing message confidentiality, data integrity, and authentication of communicating parties.
Authorization Responsible for providing a framework for making authorizationdecisions.
Auditing Responsible for logging security-related events to the audit log

Binding

Web service supports only HTTP.

WCF supports multiple bindings HTTP,TCP,MSMQ,WS-HTTP etc

Messaging

ASP.Net web service uses only SOAP for sending and receiving data. It uses Xml Schema  to  defines structure of message.

WCF can send message in any format. It uses SOAP for communication by default. It can use any other transport protocol for message transport .

Performance

Slower compared to WCF

The main advantage of the design of the DataContractSerializer is better performance over XML serialization

Fields / Properties

XMLSerialization does not indicate the which fields or properties of the type are serialized into XML

DataContratSerializer Explicitly shows the which fields or properties are serialized into XML

Exception handling

In ASP.NET Web services, Unhandled exceptions are returned to the client as SOAP faults.

In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

Example

[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Demo(string strDemog)
{
return strDemo;
}
}

[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strDemo);
}
public class Service : ITest
{
public string Demo(string strDemo)
{
return strDemo;
}
}

After you know the importance of the WCF on WebServices, We can create our Sample WCF application in next blog post.

How to Create Split function in SQL Server

No comments :
For using IN statement in SQL Server and search multiple values from string you can use
CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)

select @idx = 1
if len(@String)<1 or @String is null return

while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String

if(len(@slice)>0)
insert into @temptable(Items) values(@slice)

set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end


Just lets see a simpel example of how to use the created split function.

DECLARE @INSTRING AS varchar(300)
SET @INSTRING = '1,2,5'
Select * from Split(@INSTRING,',')
SELECT *
FROM TableA
Where id IN (Select * from Split(@INSTRING,','))

Repeating Characters & Strings in C#

No comments :
//Instead of you write something like this:  
Console.WriteLine("**************************************************");
//You can create a new string and write that string:
//This will repeat '*' fifty times.
Console.WriteLine(new string('*', 50));

Box Selection and Multi-Line Editing with VS 2010

No comments :
Box Selection
Box selection is a feature that has been in Visual Studio for awhile (although not many people knew about it). It allows you to select a rectangular region of text within the code editor by holding down the Alt key while selecting the text region with the mouse. With VS 2008 you could then copy or delete the selected text.
VS 2010 now enables several more capabilities with box selection including:
Text Insertion: Typing with box selection now allows you to insert new text into every selected line
Paste/Replace: You can now paste the contents of one box selection into another and have the content flow correctly
Zero-Length Boxes: You can now make a vertical selection zero characters wide to create a multi-line insert point for new or copied text
These capabilities can be very useful in a variety of scenarios. Some example scenarios: change access modifiers (private->public), adding comments to multiple lines, setting fields, or grouping multiple statements together.

Monday, May 14, 2012

Understanding WCF

No comments :
WCF brings all the formerly distinct and separate Microsoft connectivity technologies together under a single umbrella within the System.ServiceModel namespace.
Web services (ASMX), the Web service Extensions (WS*), Microsoft Message Queuing (MSMQ), COM+, and .NET Remoting are included in WCF.
With WCF you won't have to choose between implementations in a variety of different namespaces and coding types to create a connected application.
Whether your application connects via loosely coupled Web services, or tightly coupled Enterprise Services, the coding model will be consistent and the transition between different communication types will be much smoother—because they will all be using the same programming namespace.
WCF follows the "software as a service" model, where all units of functionality are defined as services.
A WCF Service is exposed using End point.
WCF Service can be deployed, discovered and consumed as Endpoint
All communications with the WCF service will happen via the endpoints.
The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint;
each endpoint may expose a different set of methods.
The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.
WCF provides Windows Activation Services which can be used to host the WCF service.
Otherwise the WCF service can also be hosted in IIS or in any process by using the Service Host class, which is provided by WCF.
Services can also be self-hosted.
An End point is based on ABC.

Address → Where Service is located.
The address specifies the location of the service which will be exposed for clients that will use it to communicate with the service.
The address's protocol that WCF can provided: HTTP , TCP ,NamedPipe , Peer2Peer ,MSMQ.
[transport]://[machine][:optional port]
http://localhost
http://localhost:8081
http://localhost:8081/Service
net.tcp://localhost:8082/Service
net.pipe://localhost/Pipe

Binding → How Service can be consumed/ used
In other words: how the two parties will communicate in terms of transport (HTTP , TCP ,NamedPipe , Peer2Peer ,MSMQ) ,encoding (text, binary etc.) and protocols (like transactional support or reliable messaging).
BasicHttpBinding
NetTcpBinding
WSHttpBinding
NetMsqmqBinding Etc..
Class Name Element Name Transport Encoding WS-* Protocols
BasicHttpBinding basicHttpBinding HTTP XML 1.0 WS-I Basic Profile 1.1
WSHttpBinding wsHttpBinding HTTP XML 1.0 Message security, reliable sessions, and transactions
WSDualHttpBinding wsDualHttpBinding HTTP XML 1.0 Message security, reliable sessions, and transactions
NetTcpBinding netTcpBinding TCP Binary Transport security, reliable sessions, and transactions
NetNamedPipeBinding netNamedPipeBinding Named Pipes Binary Transport security, reliable sessions, and transactions
NetMsmqBinding netMsmqBinding MSMQ Binary Transport security and queue transactions


Contract → What is Available (Interfaces..)
contracts available in WCF are:
Service Contract – Exposes the service.
Operation Contract- Exposes the service members.
Data Contract – Describes service parameters.
Fault Contracts – Defines error handling semantics

Hosting
WCF services must be hosted by a Windows Process (host process).
Hosting options include:
IIS 5 & 6.
IIS 7 & Windows Activation Service (WAS).
Console or Windows Forms applications (also called “Self-Hosting”)

Review of Web services

No comments :
Before we proceed further into WCF in future posts just let’s get a basic understanding on Web services.
Web Service is a web application which expose list of methods (business logic) over Network.
Web service uses 2 protocols.
HTTP: For transportation.
SOAP: For Messaging.
Using a Web service, different applications developed in different technologies can communicate, called as interoperability.
Sample Webservice:
Let’s create a sample web service in ASP.Net
Open Visual studio 2010 » File » New » Website » Select Visual C# Language » Select .Net Framework versions <4.0 » so we select 3.5 » select optional path required »
This creates a sample Helloworld service » Execute the website
» It displays the Service.asmx page with the hello world method » If you open that method » which further displays SOAP Messages with Envelope and Body in XML format.
See the diagram for reference

image

Limitations of Web service:
Web service can be hosted only on IIS.
Web services uses only HTTP Protocol.
Web service doesn’t provide compression of SOAP Messages.
Message Level Security is not provided by web services.
No reliable Transaction Management.

Microsoft and IBM has come up with Web service extensions like WS-Security, WS-Transactions etc.. which is different programming model.
So WCF is introduced which is unification of all these technologies with a similar programming model.
WCF is Framework introduced in .Net3.0 in year 2006.
We shall discuss detailed Architecture and implementation of WCF in future posts.

How to format datetime & date in Sql Server 2005

No comments :

SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM[/PM]-- Oct 2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd -- 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM[/PM]-- Oct 2 2008 11:02:44:013AM
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm -- 02 Oct 2008 11:02:07:577
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm -- 2008-10-02T10:52:47.513
--Craeting date styles with t-sql string functions in SQL Server
SELECT replace(convert(varchar, getdate(), 111), '/', '') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126) -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8) -- mon yyyy

Friday, May 11, 2012

New Language Enhancements in C# 4.0

No comments :
• Auto-implemented properties
For accessing Private variable outside class in .Net , property is needed.
By using Auto implemented properties,there is no need to create private variables.
There is no need to write lengthy code for get, set methods.
• Object Initializer
Object initializers let you assign values to properties of an object at creation time without having to explicitly invoke a constructor.
Ex: Employee emp = new Employee{
EmpId = 111,
Ename = “aaradha”,
Salary=12000
};
• Collection Initializer
Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable.
Ex: List emplist = new List {
new Employee{ EmpId = 111, Ename = “aaradha”, Salary=12000 },
new Employee{ EmpId = 112, Ename = “Conor”, Salary=13000 },
new Employee{ EmpId = 113, Ename = “Higgins”, Salary=10000 }
};
• Implicitly typed local variables
When type of data to be stored is not Known ,then declare it as var.
Once value is assigned , cannot implicitly convert the data type.
Var in javascript is loosely typed whereas in .NET is strongly typed.
• Nullable Types and Variables
NULL is understandeable by character,string,objects but not by INT.
Suppose if database retrieves data as NULL in integer value it needs to be checked for null.
So introduced Question mark after datatype to check for null.
Ex: Int? num = null;
• Anonymous Methods
Delegates is similar to function pointer,used to store address of method / function.
Anonymous method is a method without name.
If method signature matches with delegate,then it is implemented.
Anonymous method is declared using delegate keyword.
Anonymous method is nested inside other method (main)
They get address of method at runtime.
• Lambda expressions
These are Anonymous methods with reduced syntax.
There are two types of Lambda expressions.
Expression Lambda: (params) =>
Statement Lambda: (params) => { }
Only assignment, call, increment, decrement and new object expressions can be used as statements.
• Anonymous types
Used to create properties at Run time.
Ex: var student = { Sid=1, Sname=”Declan”, Marks=200};
• Extension methods
Way of adding behaviour to the class without modifying.
Suppose we have string class which has methods for length, substring, split..etc.. If we want to find number of words in string without making any changes to existing class functionality,we go for extension methods.
Extension method should always be static and should be in static class.
And parameter in Extension method should have this keyword so that compiler understands it as extension method.
• Partial methods
Partial methods is a mechanism of declaring the methods in one place and defining the methods in some other place.
Should be inside partial class.
Partial methods are by default private.
Should always have void as data type, means it do not return any value
Ex: Partial void Add(int x, int y );
• Named Parameters and optional Parameters
Existed earlier in C++ is mplemented now in .NET 4.0
Assigns default values to parameter.
Ex: public int (int x , int y=10)
Here in this example x is mandatory where as y is optional

The specified service has been marked for deletion error message when removing a service

No comments :
If you receive this message while trying to delete a windows service
check if the Services.msc application is open, if so try closing and then try deleting it PRIOR uninstalling the service (using installutil /u service_exe_name).
Hope this helps.

Thursday, May 10, 2012

Insert Image into HTML using C#

No comments :
StringBuilder strBldr = new StringBuilder();
StringWriter strWriter = new StringWriter(strBldr);
HtmlTextWriter writer = new HtmlTextWriter(strWriter);

writer.RenderBeginTag(HtmlTextWriterTag.Html);

writer.RenderBeginTag(HtmlTextWriterTag.Head);
writer.RenderEndTag();

writer.AddStyleAttribute(HtmlTextWriterStyle.FontFamily, "Arial");
writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "13");

writer.RenderBeginTag(HtmlTextWriterTag.Body);
writer.Write("Insert image into HTML.");
writer.WriteBreak();
writer.WriteBreak();

writer.Write("Your Image / Logo");
var img = new Image();
var hw = new HtmlTextWriter(Console.Out);
img.ImageUrl = "data.png";
img.RenderControl(writer);

writer.RenderEndTag();
writer.RenderEndTag();
string str = writer.InnerWriter.ToString();