Wednesday, December 28, 2011

how to create a proxy from webservice?

There are two ways to create proxy from web Service:

1. Add web reference in your web application and use them.


2. Open the command prompt of visual studio and copy & paste bellow mentioned line:

For VB
=====
wsdl /language:VB /n:"<destination>" http://<source&lgt;?WSDL

For C# 
=====
wsdl /language:CS /n:"<destination>" http://
<source&lgt;?WSDL

Friday, December 2, 2011

how to download a file

        Response.ContentType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=aaa-13.pdf");
        Response.TransmitFile(Server.MapPath("~/Image/UserDetails-13.pdf"));
        Response.End();

Thursday, November 24, 2011

How to Store Viewstate to Persistence Medium



In this article we will discuss about How to store ViewState of a Page/Control on server or a custom data store like sql server or file.
As you all know ViewState is stored as part of html sent to your browser in form of hidden field. This is the default behavior of asp.net framework. Starting asp.net 2.0 you have more control over how & where view state should be stored? First of all let’s understand the reason behind not sending viewstate to client:-
1.)    ViewState can be tempered with on client side with tools like firebug, fiddler etc.
2.)    ViewState makes page bulky and page loading process becomes slow.

Asp.net 2.0 introduced two methods which help us out in this process:-
1.)    LoadPageStateFromPersistenceMedium
2.)    SavePageStateToPersistenceMedium
LoadPageStateFromPersistenceMedium loads viewstate data from your custom storage.
SavePageStateToPersistenceMedium saves viewstate data to persistence medium.
So let’s try to understand this with an example
1.   Create an empty website in visual studio
2.   Add a page say Default.aspx
3.   Write below code in aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
td>
tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
td>
tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
td>
tr>
table>
div>
form>
body>
html>

4. In code behind file write below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("1"));
items.Add(new ListItem("2"));
items.Add(new ListItem("3"));
DropDownList1.DataSource = items;
DropDownList1.DataBind();
}
}
protected override object LoadPageStateFromPersistenceMedium()
{
if (Session["DefaultPageViewState"] != null)
{
       string viewStateString = Session["DefaultPageViewState"] as string;
TextReader reader = new StringReader(viewStateString);
LosFormatter formatter = new LosFormatter();
object state = formatter.Deserialize(reader);
return state;
}
else
return base.LoadPageStateFromPersistenceMedium();
//return null;
}
protected override void SavePageStateToPersistenceMedium(object state)
{
LosFormatter formatter = new LosFormatter();
StringWriter writer = new StringWriter();
formatter.Serialize(writer, state);
Session["DefaultPageViewState"] = writer.ToString();
}
}
Open page in browser and page loads up with values in dropdown list.



Right click page and click View Source. See highlighted portion below..The viewstate field is empty.

Click the button to perform postback. You will see the dropdown still loads with data i.e. ViewState has been persisted and is working fine.
Just to cross check if our code is actually working. Comment out code in LoadPageStateFromPersistenceMedium method and return null instead. Again compile and run the code. Page will open fine first time but now click on postback , you will see dropdown losing data since it was stored in viewstate.

Sunday, October 30, 2011

how to get name of procedure where word like tablename, column name have been used in Oracle

SQL> select distinct name from user_source where upper(type)='PROCEDURE' and upp
er(text) like '%TABLENAME%';

NAME
------------------------------
SP_ABC
SP_BCD
SP_XYZ
SP_LMD
SP_WEEK_ABC
SP_WEEK_XYZ

Friday, October 28, 2011

How to count no of rows in a Textarea in javascript

function rowcount()

var area = document.getElementById("hist");
var text = area.value.replace(/\s+$/g, "");
var split = text.split("\n");
return split.length;
}

Thursday, August 18, 2011

How to get that particular table is being used in any procedure, trigger etc...?

select * from user_source where upper(text) like '%REVENUE_EMP_DTLS_WEEK_REPORT%'

Monday, June 27, 2011

What is the difference between hiding and overriding for casting related matters?

When you use virtual+new, the method definition of base class is hided by the definition provided in child class (called method hiding) . In this case, method of the class, whose object is created, will be called.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  //Will give output Base
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public new void foo()
        {
            Console.WriteLine("Child");
        }
    }


In second case, where you want to use virtual+override, Thats method overriding. In this case child class function will be called when you create object using casting.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  // output will be "Child"
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public override void foo()
        {
            Console.WriteLine("Child");
        }
    }


You can also combine both method overriding and hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }

Why does TextBox retains its value after multiple postbacks even if we set the EnableViewState property of the TextBox to False?

The reason being is ASP.NET uses this primitive to update the control's value. ASP.NET uses IPostBackDataHandler  for the controls that load the data from the form collection.
Actually all the controls which implement IPostbackdatahandler, implement the method LoadPostData and
RaisePostDataChangedEvent. But here the key method is LoadPostData, which returns true if the posted value is changed from earlier value and updates it with posted value, else it returns false.

As from the Page Life Cycle, we can see LoadPostData is called after the LoadViewState, whether viewstate is on or not,  it gets populated from the posted data. That's why the data get persisted even if viewstate is set to off for few controls. Following is the complete list of the controls, those implement IPostBackDataHandler.
  •  CheckBox
  •  CheckBoxList
  •  DropDownList
  •  HtmlInputCheckBox
  •  HtmlInputFile
  •  HtmlInputHidden
  •  HtmlInputImage
  •  HtmlInputRadioButton
  •  HtmlInputText
  •  HtmlSelect
  •  HtmlTextArea
  •  ImageButton
  •  ListBox
  •  RadioButtonList
  •  TextBox

Tuesday, June 21, 2011

Can we overload methods in WCF Service or Web Service?

Yes for a WCF Service use the Name property of OperationContractAttribute class
example:
[ServiceContract]
interface ddd
{
[OperationContract(Name = "one")]
int calc(int a,int b);

[OperationContract(Name = "two")]
double calc(double a,double b);
}

1)For a Web Service use the MessageName property of WebMethodAttribute class
2)Please comment the following line in the .cs file of the Web Service
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebMethod]
public string HelloWorld(string a) {
return "Hello"+" "+a;
}
[WebMethod(MessageName="second")]
public string HelloWorld()
{
return "Hello second";
}

What does a Windows Communication Foundation, or WCF, service application use to present exception information to clients by default?

However, the service cannot return a .NET exception to the client. The WCF service and the client communicate by passing SOAP messages. If an exception occurs, the WCF runtime serializes the exception into XML and passes that to the client.

What is the use of Is Required Property in Data Contracts?

Data Contracts, is used to define Required or NonRequired data members. It can be done with a property named IsRequired on DataMember attribute.


[DataContract]
public class test
{
      [DataMember(IsRequired=true)]
      public string NameIsMust;

      [DataMember(IsRequired=false)]
      public string Phone;          
}

Wednesday, June 15, 2011

Delete Duplicate Recods from a Table in SQL Server 2005

CREATE TABLE dbo.Dupes
(
    PK_Column INT IDENTITY(1,1),
    Dupe_String VARCHAR(32)
)



INSERT dbo.Dupes(Dupe_String)
    SELECT 'foo'
    UNION ALL SELECT 'foo'
    UNION ALL SELECT 'foo'
    UNION ALL SELECT 'bar'
    UNION ALL SELECT 'bar'
    UNION ALL SELECT 'splunge'
    UNION ALL SELECT 'splunge'
    UNION ALL SELECT 'mort'

SELECT * FROM dbo.Dupes


DELETE dbo.Dupes
    FROM dbo.Dupes d
    LEFT OUTER JOIN
    (
        SELECT Dupe_String, pk_column = MIN(PK_Column)
        FROM dbo.Dupes
        GROUP BY Dupe_String
    ) x
    ON d.pk_column = x.pk_column
    WHERE x.pk_column IS NULL

What is Event bubling?

The concept of calling parent event from child event.
For example, Let us take a GridView Control. GridView control consists of several events like row edit,update. We can edit a particular row of a gridview control by raising row edit event. The reslt of that row edit event effects to the gridview control data. Hence this concept is called Event Bubbling

Saturday, May 14, 2011

Difference between Oracle & Sql Server?

  • a better transaction system
  • packages
  • Cursor For Loops
  • anchored declarations (variables declared as table.column%type)
  • initial values for variable declarations
  • %rowtype variables
  • much lower overhead for cursors
  • BEFORE triggers
  • FOR EACH ROW triggers
  • While sequences require either discipline or before each row triggers, they are more flexible than SQL Server identity columns.
SQL Server Strengths:
  • Transact-SQL is just one language, so you don't have to worry about what's SQL, what's SQL*PLUS and what's PL/SQL.
  • Because T-SQL is just one language, the T-SQL collections actually work decently with SQL. You can join T-SQL table variables to real tables. This tends to mean, while PL/SQL is more powerful for procedural programming, you just don't need to do procedural programming in T-SQL.
  • If you perform a select query with no target, the results are automatically returned to the client. For production code, this means you don't need to declare and pass sys_refcursor. For ad-hoc research work, this means you can easily make scripts that perform lookups and display multiple recordsets.
  • SQL Server Management Studio is much better than SQL*Plus or SQL Developer. Because it just displays any returned recordsets, data retrieval procedures are very easy to test.
  • easier client connectivity setup (nothing as bad as tnsnames)
  • less confusion about what drivers to use, apart from JDBC
  • Declare a column "Int Identity Not Null Primary Key" and then you can forget about it.
  • Every variable name starts with an "@" sigil, which looks terrible, but prevents name collisions between variables and columns.
  • The case you declared a table or column with will be remembered, but it's not case sensitive, and you aren't limited to 30 characters.
  • Crystal Reports can call SQL Server stored procedures, where you tend to be forced into a view with Oracle.

Thursday, May 12, 2011

How to Show Flash movie

function createFlashMarkup(width,height,uri,replaceid){

 var embed = document.createElement('embed');
 embed.setAttribute('width',width);
 embed.setAttribute('height',height);
 embed.setAttribute('src',uri);

 var div = document.getElementById(replaceid);
 document.getElementsByTagName('body')[0].replaceChild(embed,div); 
}

window.onload = function(){
 createFlashMarkup('550','400','vuurwerk.swf','replaced-by-flash');
}

Saturday, February 26, 2011

how to get total number of working days in a month?

WITH c AS
     (SELECT     TRUNC (sysdate, 'MM') + ROWNUM - 1 n,rownum
       FROM DUAL
      CONNECT BY ROWNUM <= (TRUNC (sysdate) - TRUNC (sysdate, 'MM'))+1)
SELECT sum(decode(to_char(n,'D'),7,0,6,0,1)) weekdays
  FROM c




How to get total no. of weeks in a month in oracle?

WITH c AS
     (SELECT     TRUNC (sysdate, 'MM') + ROWNUM - 1 n,rownum
       FROM DUAL
      CONNECT BY ROWNUM <= (TRUNC (sysdate) - TRUNC (sysdate, 'MM'))+1)
SELECT sum(decode(to_char(n,'D'),7,1,0)) weekdays
  FROM c


OUTPUT:
                  WeekDays
                         4








Monday, February 21, 2011

Configuration setting for using code with different language

<system.web>
    <compilation>
        <codeSubDirectories>
            <add directoryName="VB"/>
            <add directoryName="CSHARP"/>
        </codeSubDirectories>
    </compilation>
</system.web>

Configuration setting for using different version of an assembly

<configurations>
<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configurations>

Friday, February 11, 2011

Delete Duplicate Rows in Microsoft SQL Server



Microsoft SQL Server tables should never contain duplicate rows, nor non-unique primary keys. For brevity, we will sometimes refer to primary keys as "key" or "PK" in this article, but this will always denote "primary key." Duplicate PKs are a violation of entity integrity, and should be disallowed in a relational system. SQL Server has various mechanisms for enforcing entity integrity, including indexes, UNIQUE constraints, PRIMARY KEY constraints, and triggers.

Despite this, under unusual circumstances duplicate primary keys may occur, and if so they must be eliminated. One way they can occur is if duplicate PKs exist in non-relational data outside SQL Server, and the data is imported while PK uniqueness is not being enforced. Another way they can occur is through a database design error, such as not enforcing entity integrity on each table.

Often duplicate PKs are noticed when you attempt to create a unique index, which will abort if duplicate keys are found. This message is:
Msg 1505, Level 16, State 1 Create unique index aborted on duplicate key.
If you are using SQL Server 2000 or SQL Server 2005, you may receive the following error message:
Msg 1505, Level 16, State 1 CREATE UNIQUE INDEX terminated because a duplicate key was found for object name '%.*ls' and index name '%.*ls'. The duplicate key value is %ls.
This article discusses how to locate and remove duplicate primary keys from a table. However, you should closely examine the process which allowed the duplicates to happen in order to prevent a recurrence.
For this example, we will use the following table with duplicate PK values. In t...
For this example, we will use the following table with duplicate PK values. In this table the primary key is the two columns (col1, col2). We cannot create a unique index or PRIMARY KEY constraint since two rows have duplicate PKs. This procedure illustrates how to identify and remove the duplicates.
create table t1(col1 int, col2 int, col3 char(50))
insert into t1 values (1, 1, 'data value one')
insert into t1 values (1, 1, 'data value one')
insert into t1 values (1, 2, 'data value two')
The first step is to identify which rows have duplicate primary key values:
SELECT col1, col2, count(*)
FROM t1
GROUP BY col1, col2
HAVING count(*) > 1
This will return one row for each set of duplicate PK values in the table. The last column in this result is the number of duplicates for the particular PK value.
Collapse this tableExpand this table
col1
col2

1 1 2


If there are only a few sets of duplicate PK values, the best procedure is to delete these manually on an individual basis. For example:
set rowcount 1
delete from t1
where col1=1 and col2=1
The rowcount value should be n-1 the number of duplicates for a given key value. In this example, there are 2 duplicates so rowcount is set to 1. The col1/col2 values are taken from the above GROUP BY query result. If the GROUP BY query returns multiple rows, the "set rowcount" query will have to be run once for each of these rows. Each time it is run, set rowcount to n-1 the number of duplicates of the particular PK value.

Before deleting the rows, you should verify that the entire row is duplicate. While unlikely, it is possible that the PK values are duplicate, yet the row as a whole is not. An example of this would be a table with Social Security Number as the primary key, and having two different people (or rows) with the same number, each having unique attributes. In such a case whatever malfunction caused the duplicate key may have also caused valid unique data to be placed in the row. This data should copied out and preserved for study and possible reconciliation prior to deleting the data.

If there are many distinct sets of duplicate PK values in the table, it may be too time-consuming to remove them individually. In this case the following procedure can be used:
  1. First, run the above GROUP BY query to determine how many sets of duplicate PK values exist, and the count of duplicates for each set.
  2. Select the duplicate key values into a holding table. For example:
  3. SELECT col1, col2, col3=count(*)
  4. INTO holdkey
  5. FROM t1
  6. GROUP BY col1, col2
  7. HAVING count(*) > 1
  1. Select the duplicate rows into a holding table, eliminating duplicates in the process. For example:
  2. SELECT DISTINCT t1.*
  3. INTO holddups
  4. FROM t1, holdkey
  5. WHERE t1.col1 = holdkey.col1
  6. AND t1.col2 = holdkey.col2
  1. At this point, the holddups table should have unique PKs, however, this will not be the case if t1 had duplicate PKs, yet unique rows (as in the SSN example above). Verify that each key in holddups is unique, and that you do not have duplicate keys, yet unique rows. If so, you must stop here and reconcile which of the rows you wish to keep for a given duplicate key value. For example, the query:
  2. SELECT col1, col2, count(*)
  3. FROM holddups
  4. GROUP BY col1, col2
should return a count of 1 for each row. If yes, proceed to step 5 below. If no, you have duplicate keys, yet unique rows, and need to decide which rows to save. This will usually entail either discarding a row, or creating a new unique key value for this row. Take one of these two steps for each such duplicate PK in the holddups table.
  1. Delete the duplicate rows from the original table. For example:
  2. DELETE t1
  3. FROM t1, holdkey
  4. WHERE t1.col1 = holdkey.col1
  5. AND t1.col2 = holdkey.col2
  1. Put the unique rows back in the original table. For example:
  2. INSERT t1 SELECT * FROM holddups

Tuesday, February 8, 2011

What is Event?

The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." In this model, you have publishers who will do some logic and publish an "event." Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.
In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified. The following figure shows this mechanism.
Conventions
The following important conventions are used with events:
  • Event Handlers in the .NET Framework return void and take two parameters.
  • The first paramter is the source of the event; that is the publishing object.
  • The second parameter is an object derived from EventArgs.
  • Events are properties of the class publishing the event.
  • The keyword event controls how the event property is accessed by the subscribing classes.
Example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace IILButton
{
     public class MyClass
    {
        public delegate void LogHandler(string Message);
        public event LogHandler Log;
        public void Process()
        {
            OnLog("Process() Begin");
            OnLog("Process() End");
        }
        protected void OnLog(string Message)
        {
            if (Log != null)
            {
                Log(Message);
            }
        }
}
public class FileLogger
{
    FileStream fs;
    StreamWriter sw;
    public FileLogger(string FileName)
    {
        fs = new FileStream(FileName, FileMode.OpenOrCreate);
        sw = new StreamWriter(fs);
    }
    public void Logger(string s)
    {
        sw.WriteLine(s);
    }
    public void Close()
    {
        sw.Close();
        fs.Close();
    }
  }
}
on Button Click
FileLogger fl = new FileLogger("C:/Process.log");
MyClass mycls = new MyClass();
mycls.Log += new MyClass.LogHandler(Logger);
mycls.Log += new MyClass.LogHandler(fl.Logger);
mycls.Process();
fl.Close();

On Page
protected void Logger(string s)
{
Response.Write(s);
}

What is Multicast Delegate?


It is a delegate which holds the reference of more than one method. 
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

 delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y)
{
Console.WriteLine("You r in Method 1");
}

static void Method2(int x, int y)
{
Console.WriteLine("You r in Method 2");
}

public static void "on" />Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement: 
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using the -= operator.