Friday, December 10, 2010

How to get list of file and directory names from remote direcotry

Many of times we requires to get list of all name of files and folder which exists on remote server.

To get list of File and Folder names from Remote Directory / Remote Server

public void getDirList()
        {
            FtpWebRequest _lsDirFtp;

            _lsDirFtp = (FtpWebRequest)FtpWebRequest.Create("ftp://myFTPIPorName//MyDirecoty/");
            _lsDirFtp.KeepAlive = false;
            _lsDirFtp.Credentials = new NetworkCredential("username", "password");

            _lsDirFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;



            WebResponse response = _lsDirFtp.GetResponse();
            
            StreamReader reader = new StreamReader(response.GetResponseStream());



            //Get Directory/File names

            FtpWebRequest _lsDirDetailsFtp;
            _lsDirDetailsFtp = (FtpWebRequest)FtpWebRequest.Create("ftp://myFTPIPorName//MyDirecoty/");
            _lsDirDetailsFtp.KeepAlive = false;

            _lsDirDetailsFtp.Credentials = new NetworkCredential("username", "password");

            _lsDirDetailsFtp.Method = WebRequestMethods.Ftp.ListDirectory;



            WebResponse response2 = _lsDirDetailsFtp.GetResponse();

            StreamReader reader2 = new StreamReader(response2.GetResponseStream());



            //read file/directory names into arraylist

            string lsdirectory = reader2.ReadLine();

            ArrayList lsnames = new ArrayList();

            while (lsdirectory != null)
            {

                lsnames.Add(lsdirectory);
                Response.Write("fileName:" + lsdirectory);

                lsdirectory = reader2.ReadLine();

            }



            //read through directory details response

            string line = reader.ReadLine();

            while (line != null)
            {

                //if (line.StartsWith("d") && !line.EndsWith(".")) //"d" = dir don't need "." or ".." dirs
                //{

                    foreach (String chk in lsnames) //compare basic dir output to detail dir output to get dir name
                    {

                        if (line.EndsWith(chk))
                        {

                            //found dir
                          Response.Write ("fileName:" + chk);

                            // Console.WriteLine(chk);

                        }

                    }

               // }

                line = reader.ReadLine();

            }


        }

Solution By:

Rajesh Rolen

Read More

The remote server returned an error: (503) Bad sequence of commands.

While working with FTP some times you gets this error "The remote server returned an error: (503) Bad sequence of commands." to resolve it just do set

_request.KeepAlive = false;

actually by default it keeps your ftp request connection open even your work is done.but when we will set its KeepAlive to false so now it will not give you the error again.

Solution By:

Rajesh Rolen

Read More

Thursday, December 9, 2010

How to upload / download / delete file using FTP in asp.net / vb.net

We can easily upload or download files from FTP using asp.net/vb.net:


To Upload file to FTP/Remote Server using VB.NET

Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter

myFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")

'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True

myStreamWriter = New StreamWriter(myFtpWebRequest.GetRequestStream())
myStreamWriter.Write(New StreamReader(Server.MapPath("filename.ext")).ReadToEnd)
myStreamWriter.Close()

myFtpWebResponse = myFtpWebRequest.GetResponse()

litResponse.Text = myFtpWebResponse.StatusDescription

myFtpWebResponse.Close()
End Sub


To Download file from FTP/Remote Server using VB.NET

Protected Sub btnDownloadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter

myFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")

'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

myFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile
myFtpWebRequest.UseBinary = True

myFtpWebResponse = myFtpWebRequest.GetResponse()

myStreamWriter = New StreamWriter(Server.MapPath("filename.ext"))
myStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)
myStreamWriter.Close()

litResponse.Text = myFtpWebResponse.StatusDescription

myFtpWebResponse.Close()
End Sub

To Delete file from FTP/Remote Server using VB.NET

Protected Sub btnDeleteFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse

myFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")

'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

myFtpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile

myFtpWebResponse = myFtpWebRequest.GetResponse()

litResponse.Text = myFtpWebResponse.StatusDescription

myFtpWebResponse.Close()
End Sub
Read More

Wednesday, December 8, 2010

How to show immediate window.

Some times in visual studio the immediate window gets disappeared.
to get it just press: ctrl+alt+I and its done..

Solution by

Rajesh Rolen

Read More

Friday, December 3, 2010

How to set PopUp Window size of current Page

To change height and width of current window we can use resizeTo function like:
window.resizeTo(iWidth, iHeight) 


Solution By

Rajesh Rolen

Read More

Thursday, December 2, 2010

Send file on FTP using .net

To send a file over FTP using asp.net / c#.net / vb.net :

using System.Net;

public void ftpfile(string ftpfilepath, string inputfilepath)
    {

        string ftphost = "122.22.1.1"; // destination IP address      

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
        ftp.Credentials = new NetworkCredential("userid", "password");
        ftp.KeepAlive = true;
        ftp.UseBinary = true;
        ftp.Method = WebRequestMethods.Ftp.UploadFile;
        FileStream fs = File.OpenRead(inputfilepath);
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        fs.Close();
        Stream ftpstream = ftp.GetRequestStream();
        ftpstream.Write(buffer, 0, buffer.Length);
        ftpstream.Close();

    }  

Solution by: Rajesh Rolen

Read More

Friday, November 26, 2010

Rebuild index of complete database

for maintaining performance of queries we need to rebuild indexes so below is the way we can use to rebuild all indexes of complete database so we need not to rebuild indexes of all tables one by one.


DECLARE @TableName varchar(255)

DECLARE TableCursor CURSOR FOR
SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'

OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
DBCC DBREINDEX(@TableName,' ',90)
FETCH NEXT FROM TableCursor INTO @TableName
END

CLOSE TableCursor

DEALLOCATE TableCursor


Solution By: Rajesh Rolen

Read More

Remove Scripts from database/ Remove Sql Injections


USE [DBFORUMSNEW]
GO
/****** Object: StoredProcedure [dbo].[sp_sqlinjection] Script Date: 11/26/2010 19:46:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[sp_sqlinjection]
@DBName varchar(100)
as
Begin
declare @DB_Name varchar(40), @Table_Name varchar(40),@Column_Name varchar(40)
declare @sql1 varchar(1000), @sql2 varchar(1000)
Set @DB_Name = @DBName
begin
exec ('use ' + @Db_Name)
DECLARE Table_Cursor CURSOR FOR SELECT name from sysobjects where type= 'U'
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor into @Table_Name
WHILE @@FETCH_STATUS = 0
begin
declare Column_Cursor CURSOR for select name from syscolumns where id = object_id(@Table_Name) and xtype in (239,175,231,167) and length > 20
open Column_Cursor
Fetch next from Column_Cursor into @Column_Name
WHILE @@FETCH_STATUS = 0
begin
set @sql1='if exists (SELECT 1 FROM ['+@Table_Name+'] where ['+@Column_Name+'] like ''%< script%'')
begin
update ['+@Table_Name+'] set ['+@Column_Name+'] = replace(['+@Column_Name+'],
substring(['+@Column_Name+'],charindex(''< script'',['+@Column_Name+']),
case when charindex(''< /script'',['+@Column_Name+']) >charindex(''< script'',['+@Column_Name+']) then
charindex(''< /script'',['+@Column_Name+'])-charindex(''< script'',['+@Column_Name+'])+9
else
len (['+@Column_Name+'])
end ),
'''') where ['+@Column_Name+'] like ''%< script%''
end '
exec (@sql1)
set @sql2='if exists (SELECT 1 FROM ['+@Table_Name+'] where ['+@Column_Name+'] like ''%< title%'')
begin
update ['+@Table_Name+'] set ['+@Column_Name+'] = replace(['+@Column_Name+'],
substring(['+@Column_Name+'],charindex(''< title'',['+@Column_Name+']),
case when charindex(''< /title'',['+@Column_Name+']) >charindex(''< title'',['+@Column_Name+']) then
charindex(''< /title'',['+@Column_Name+'])-charindex(''< title'',['+@Column_Name+'])+9
else
len (['+@Column_Name+'])
end ),
'''') where ['+@Column_Name+'] like ''%< title%''
end '
exec (@sql2)
FETCH NEXT FROM Column_Cursor into @Column_Name
end
close Column_Cursor
DEALLOCATE Column_Cursor
FETCH NEXT FROM Table_Cursor into @Table_Name
end
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
--FETCH NEXT FROM DB_Cursor into @DB_Name
end
end







Solution By: Rajesh Rolen

Read More

Friday, November 12, 2010

What is Bookmarklet / what is use of Bookmarklet

Each bookmarklet is a tiny program (a JavaScript application) contained in a bookmark (the URL is a "javascript:" URL) which can be saved and used the same way you use normal bookmarks. The idea was suggested in the Netscape JavaScript Guide.

JavaScript has been used by page authors on millions of webpages; Bookmarklets allow anybody to use JavaScript - on whatever page you choose (not just your own page).

so A bookmarklet is an applet, a small computer application, stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. The term is a portmanteau of the terms bookmark and applet. Whether bookmarklet utilities are stored as bookmarks or hyperlinks, they are designed to add one-click functionality to a browser or web page. When clicked, a bookmarklet performs some function, one of a wide variety such as a search query or data extraction. Usually the applet is a JavaScript program.

Web browsers use URIs for the href attribute of the < a > tag and for bookmarks. The URI scheme, such as http:, file:, or ftp:, specifies the protocol and required form for the rest of the string. Browsers also implement a prefix javascript: that to a parser is just like any other URI. Internally, the browser sees that the protocol is javascript, treats the rest of the string as javascript code which is then executed, and uses the resulting string as the new page.

The executing script has access to the current page, which it may inspect and change. If the script returns an undefined type (rather than, say, a string), the browser will not load a new page, with the result that the script simply runs against the current page content. This permits in-place font size and color changes, for example, without a page reload.

An anonymous function can be used to force the script to return an undefined type:

javascript:(function(){
/* Statements returning a non-undefined type, e.g. assignments */
})();


Bookmarklets are saved and used as normal bookmarks. As such, they are simple "one-click" tools which add functionality to the browser. For example, they can:

- Modify the appearance of a web page within the browser (e.g., change font size, background color, etc.).
- Extract data from a web page (e.g., hyperlinks, images, text, etc.).
- Submit the current page to a blogging service such as Posterous, link-shortening service such as su.pr, or bookmarking service such as Delicious.
- Query a search engine, with search term(s) provided by previously selected text, or by a dialog box.
- Submit the current page to a link validation service, or translation service.
- Set commonly chosen configuration options when the page itself provides no way to do this.

Bookmarklets are safer than traditional software for the following reasons:

- They are extremely simple. With only a few lines of code it's hard to make a programming error that isn't detected immediately.

- You don't install software. Traditional software programs can produce conflicts with other programs on your hard drive. Bookmarklets work entirely within your web browser, so they can't independently interfere with the functioning of other programs.

- Even if something goes wrong (say, you try to use a Netscape-only bookmarklet on Internet Explorer) the worst thing that is likely to happen is that you will get a JavaScript error message. Furthermore, this site has been designed (through server-side scripting) to make it impossible for you to get a bookmarklet that doesn't work on your browser.

- Because you don't install software, you don't have the security risks of traditional software (which can install files all over your hard drive). Your hard drive is protected by JavaScript security restrictions.
Read More

FileUploader in asp.net MVC2

as we all know ASP.NET MVC sits on top of ASP.NET. That means ASP.NET MVC didn't do any special work for File Upload support. It uses whatever stuff is built into ASP.NET itself.

So the core process is still same for file upload:
below is code for view

Code for how to Upload file in ASP.NET MVC2



< %@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" % >

< asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server" >
FileUpload
< /asp:Content >
< asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" >
< h2 >FileUpload< /h2 >

< % using (Html.BeginForm("FileUpload", "FileUpload",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{% >
< input name="uploadFile" type="file" / >
< input type="submit" value="Upload File" / >
< %} % >

< /asp:Content >


//and this is code for controller class:
[HandleError]
public class FileUploadController : Controller
{
public ActionResult FileUpload()
{
return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
}

How to Upload file in ASP.NET MVC2 by Rajesh Rolen

Read More

Wednesday, November 10, 2010

difference between exec and sp_executeSql

both are used for executing dynamic sql in sql server.
both are not preferred because, If we are using dynamic sql in stored procedure, SQL Server may not use the execution plan. It will recreate the execution plan every time with different string of SQL.So, we have to think about the performance while using dynamic sql.

Main Difference:

Exec is non parametrized
sp_executeSql is parametrized

the main difference between above two is difference in performance.
the for Exec the execution plan is created every time it gets executed where as with sp_executeSql the same execution plan (will try) will be used only its value will be changed.

but if both's queries are getting changed on every call than there is no difference between them. but even though the plus point is with sp_executeSql that if their comes same query to it than it use same execution plan with different parameter and perform operation faster with compare to Exec.

Example:


DECLARE @ItemID INT
DECLARE @Query NVARCHAR(200)

SET @Query = 'SELECT * FROM [dbo].[Item] WHERE ID = '

SET @ItemID = 1
EXEC( @Query + @ItemID)

SET @ItemID = 2
EXEC( @Query + @ItemID)

SET @Query = 'SELECT * FROM [dbo].[Item] WHERE ID = @ID'

SET @ItemID = 1
EXEC sp_executesql @Query, N'@ID INT', @ID = @ItemID -- this will be faster because its only value will be changed and will use same execution plan.



Solution By:

Rajesh Rolen

Read More

what is cls compliant code

cls compliant is mostly used when we wants our dll or any other code to be used by other language which are supported by .net.
lets say we wants to create a library in c# which we wants to be use in c# , vb.net , visual c++ or any other such languages. so for that we will have to create it as a cls compliant so that it can be consumed by all other .net supported language.

You can apply the CLSCompliant attribute on a class, an assembly (or a program element) and have the compiler check if your code is CLS (Common Language System) compliant. This means it works properly when consumed by other .NET languages. For example, you can place the following attribute on your .NET AssemblyInfo.cs files:

[assembly: CLSCompliant(true)]

Some of the things the compiler checks:

Class and member names cannot differ only by case. For example, you can't have one property named Counter and another named counter. This is important for cross-language compatibility since VB .NET isn't case sensitive.

Overloaded class methods cannot differ only by out or ref parameter designations.

Publicly exposed members cannot start with an underscore ( _ ).

Operators can't be overloaded

Unsigned types can't be part of the public interface of a class

Unfortunately, although you can apply the CLSCompliant attribute in VB .NET, the VB .NET compiler doesn't check for CLS compliance. In VB.NET 2005, this has apparently been fixed.


basic rules that should be followed when writing a CLS complaint C# code.

1. Unsigned types should not be part of the public interface of the class. What this means is public fields should not have unsigned types like uint or ulong, public methods should not return unsigned types, parameters passed to public function should not have unsigned types. However unsigned types can be part of private members.

2. Unsafe types like pointers should not be used with public members. However they can be used with private members.

3. Class names and member names should not differ only based on their case. For example we cannot have two methods named MyMethod and MYMETHOD.

4. Only properties and methods may be overloaded, Operators should not be overloaded.

The above-mentioned rules should be followed only for the types and member that are publicly exposed by your program. Private classes, private methods and local variables need to follow the rules.

By default the C# complier does not check for CLS compliance of the code. We should explicitly make the C# compiler check for CLS compliance by using the CLSCompliantAttribute class. By specifying the value of true to this attribute we specify that the C# compiler should check for the CLS compliance of the code. The CLSCompliantAttribute can be applied to assemblies, modules, types, and members.

For marking an entire assembly as CLS compliant the following syntax is used

using System;
[assembly:CLSCompliant(true)]

For marking a particular method as CLS compliant the following syntax is used

[CLSCompliant(true)]
public void MyMethod()


Example

using System;
//setting CLSCompliant attribute to true
[assembly:CLSCompliant(true)]
[CLSCompliant(true)]
public class Test
{
public void MyMethod()
{
}
//error because methods differ only in their case
public void MYMETHOD()
{
}
static void Main()
{
}
}
Read More

How to refresh view when table structure got changed

Lets we have got a table named tblstudent which contains following fields

studentRNo, studentName, StudentAddress

now we have create a view on it like:

create view viewName
as
select * from tblstudent

now when we will perform select operation on view then it will show us columns:

select * from viewName

output:
studentRNo, studentName, StudentAddress

now we have added a new column to tblstudent named 'studentFee'

alter table tblstudent add StudentFee int

now when we will run select operation on view again like:

select * from viewName

it will show use only those three columns which was exists while creating view:


select * from viewName

output:
studentRNo, studentName, StudentAddress

so as we are using '*' in query so it should show the newly added column in result but it will not show it. so to get desired result you will have to use a system storedprocedure 'sp_refreshView'

sp_refreshView 'ViewName'

and its done.


select * from viewName

output:
studentRNo, studentName, StudentAddress, studentFee


Solution by

Rajesh Rolen

Read More

Monday, November 1, 2010

Gridview with master-slave data

some times we wants to show gridview with master-child data. so that on click of master the details should be shown in child.
To do so here is a very good article:

http://www.progtalk.com/viewarticle.aspx?articleid=54
Read More

Sunday, October 31, 2010

How to add attributes with controls in MVC2

this is how we can add attributes with HTML controls in MVC2 :


< %: Html.TextBox("txtfind", null, new { @maxlength = "5", @class = "findInput" })% >


in above sample we are setting max length property of textbox to 5 and adding its css class name "findinput".

Solutions By:Rajesh Rolen

Read More

Friday, October 29, 2010

Disable Trigger

To disable the trigger use this syntex:


DISABLE TRIGGER triggerName ON TableName;


To disable all triggers of available server:


DISABLE Trigger ALL ON ALL SERVER


Solutions By:Rajesh Rolen

Read More

Rebuild index while insert/update is also available

Some times we face such a situation that we have data in GB of size and we want to rebuild our index which is applied on that table. but in previous editions from MS-Sql server2005 this was not possible to provide insert/update facility while performing rebuild index operation.

but from sql server2005 we have got this very good facility to make insert/update available (working) while rebuild index is under progress.

to do so the syntax is :

CREATE CLUSTERED INDEX cl_SalesHistory_SaleID ON SalesHistory(SaleID ASC, SaleDate ASC)
WITH(DROP_EXISTING = ON, ONLINE = ON)


in above query we have made our table available/allowing for insert/update while we perform rebuild index operation on it.

ONLINE = { ON | OFF }
Specifies whether underlying tables and associated indexes are available for queries and data modification during the index operation. The default is OFF.

Solutions By:Rajesh Rolen

Read More

Remove interger values from string variable

To remove integer values from string you can use regular expression like this:


string result = Regex.Replace(stringValue, @"\d", "");


Solutions by: Rajesh Rolen

Read More

Thursday, October 28, 2010

Import data from .csv to sql

to import data from .csv file to sql server you can use below query.


BULK INSERT ZIPCodes
FROM 'e:\yourCSVFileName.csv'
WITH
(
FIRSTROW = 2 ,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
Read More

Extract url from string

To extract URL from a string you can use below javascript functions:


function parseUrl1(data) {
var e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;

if (data.match(e)) {
return {url: RegExp['$&'],
protocol: RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
hash:RegExp.$7};
}
else {
return {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}



function parseUrl2(data) { var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w-.]+.[^#?\s]+)(#[\w-]+)?/;

if (data.match(e)) {
return {url: RegExp['$&'],
protocol: RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
hash:RegExp.$7};
}
else {
return {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}




References :http://lawrence.ecorp.net/inet/samples/regexp-parse.php
Read More

Wednesday, October 27, 2010

get All child controls/div using jquery

lets assume i have got a div and i want all its child div.
you can do it using jquery:


$("#ParentDivID > div").each(function(){
//your operation on div
}


Solution by:Rajesh Rolen

Read More

Tuesday, October 26, 2010

Partial Update in MVC2 (like update panel in classic asp.net)

     
function showAjaxMessage(targetDiv, ajaxMessage) {
var ajaxLoader = "";
$(targetDiv).html("

" + ajaxLoader + " " + ajaxMessage + "

");
}
function submitme() {
submitForm("MyFunction", "#dvdamageAreaMid", "Submitting...", "#BodyWork", function () { alert('Submitted!'); });
}
function submitToPartialView(data) {
getPartialView("UCDamage", "#dvdamageAreaMid", "Loading...", function () { },data );
}

function getPartialView(actionUrl, targetDiv, ajaxMessage, callback,data) {
showAjaxMessage(targetDiv, ajaxMessage);

$.get(actionUrl, { searchText: data }, function (result) {
$(targetDiv).html(result);
callback();
});
}
function submitForm(actionUrl, targetDiv, ajaxMessage, form, callback) {

var data = $(form).serialize();
showAjaxMessage(targetDiv, ajaxMessage);
$.post(
actionUrl,
data,
function (data) {
$(targetDiv).html(data);
callback();
}
);
}
Read More

Tuesday, October 12, 2010

Trigger Ordering in Sql Server

Many of times we face such issue that we have two triggers defined on same table which are set to fire on the same table actions (i.e. an INSERT, DELETE, UPDATE transaction). The second trigger that fires is dependent on the first fired trigger. So how can we make sure that they fire in the correct order to enforce my business logic.

By default, multiple triggers on a SQL Server table for the same action are not fired in a guaranteed order. However, it's possible to declare the firing order for 2 AFTER triggers (i.e. triggers that fire after the database action has been completed) using system stored procedure sp_settriggerorder. This feature cannot be used with INSTEAD OF triggers and you will receive a database error if you attempt to define an order on these types of triggers.

The system stored procedure sp_settriggerorder was introduced in SQL Server 2000 and has been modified to accept a new parameter in SQL Server 2005 to support the new DDL trigger feature. It is defined as follows:


exec sp_settriggerorder @triggername = , /* SQL Server 2000 and 2005 */
@order = [FIRST|LAST|NONE], /* SQL Server 2000 and 2005 */
@stmttype = [INSERT|UPDATE|DELETE|], /* SQL Server 2000 and 2005 */
@namespace = [DATABASE|SERVER|NULL] /* SQL Server 2005 only */



- Parameter @triggername is self explanatory; it's the trigger being ordered.

- Parameter @order indicates whether the trigger should fire FIRST or LAST. If NONE is specified, then no order is enforced.

- Parameter @stmttype indicates the trigger type i.e. whether it's an INSERT trigger, for instance.

- Parameter @namespace is SQL Server 2005 specific and indicates whether a DDL trigger was created on the database or on the server. If set to NULL, it indicates that the trigger is a DML trigger

lets say we have 2 insert trigger named:trg1 and trg2 on same table and we want the trg1 to be fired first and than trg2 should be fired.
so to perform this we will have to set its order using sp_settriggerorder. otherwise their default ordering will be not sure as per required.

Create trigger:

trg1:

create trigger dbo.trg1 on dbo.customer
for insert
as
set nocount on
print 'firing original trigger 1'

trg2:

create trigger dbo.trg2 on dbo.customer
for insert
as
set nocount on
print 'firing original trigger 2'


Setting order of trigger:
exec sp_settriggerorder @triggername = 'trg1',
@order = 'first',
@stmttype = 'insert',
@namespace = null

exec sp_settriggerorder @triggername = 'trg2',
@order = 'last',
@stmttype = 'insert',
@namespace = null
go

Solutions By: Rajesh Rolen

Read More

What is Link Server and what are its advantages in SQL Server/ How to write Queries on tables and database which are on seperate sql server instance

Basically it provides us facility of Distributed transactions.

Some times we want to retrieve data from a sever and insert it in table of another server.
or
Some times we want to run sql queries and perform joins on tables of different database whose database are on different computer.

Link server provides us all above facility

Linked Servers allow you to submit a TSQL statement on one SQL Server instance, which retrieves data from a different SQL Server instances. In fact, linked server can be used to join data from multiple SQL Server instances using a single TSQL statement. When you have databases on multiple SQL Server instances, you might find it useful to use linked servers in your application to retrieve data from more than one instance. By using a linked server your application will only need to connect to one SQL Server instance to retrieve data from multiple SQL Server instances. On that single SQL Server instance, you would define linked servers so your application could retrieve data from the databases that reside on a different SQL Server instance. Next time you are considering how to handle retrieving data from multiple instances of SQL Server from a single connection or single TSQL statement you might consider looking into using a linked server.

Eg:

SELECT e.* FROM SERVER2.AdventureWorks.Employee e inner join
Server1.AdventureWorks.Salary s on e.employeeid = s.employeeid



Performance of Distributed Query:


when you run a distributed query using a linked server, the query is processed locally. This may or may not be efficient, depending on how much data must be sent from the remote server to the local server for processing. Sometimes it is more efficient to pass through the query so that it is run on the remote server. This way, if the query must process many rows, it can process them on the remote server, and only return to the local server the results of the query

When running distributed queries on a linked server, if the linked server has the same character set and sort order (collation) as the local SQL Server, then you can reduce overhead and boost performance if you set the SP_SERVEROPTION "collation compatible" option to true. What this setting does is tell SQL Server to assume that all columns and character sets on the remote server are compatible with the local server. This same option can also be turned on for a linked server using Enterprise Manager or Management Studio.


References:http://www.databasejournal.com/features/mssql/article.php/3691721/Setting-up-a-Linked-Server-for-a-Remote-SQL-Server-Instance.htm
Read More

Monday, October 11, 2010

Invoke a Method when method name is in string format or stored in variable

Below is the code that will do the trick, wrapped in the method InvokeStringMethod. As you see, it takes only two lines to call another method given its name as a string, and its class name also as a string. Read the comments in the code to see how it works.

public static string InvokeStringMethod(string typeName, string methodName)
{
// Get the Type for the class
Type calledType = Type.GetType(typeName);

// Invoke the method itself. The string returned by the method winds up in s
String s = (String)calledType.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public |
BindingFlags.Static,
null,
null,
null);

// Return the string that was returned by the called method.
return s;
}

This method assumes that the called method has no parameters and returns a string. Pass the name of the method in parameter methodName, and the name of its class in typeName.

Example:

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

namespace MyNameSpace
{

public class MyClass
{
public int returnvalue(int x)
{
return x;
}
}


class Program
{

static void Main(string[] args)
{
string s ="returnvalue";
Type t = typeof(MyClass);
ConstructorInfo CI = t.GetConstructor(new Type[] {});
object o = CI.Invoke(new object[]{});
MethodInfo MI = t.GetMethod(s);
object[] fnargs = new object[] {4};
Console.WriteLine("Function Returned values: " +MI.Invoke(o, fnargs).ToString());

}
}
}



references:http://www.codeproject.com/KB/cs/CallMethodNameInString.aspx

http://stackoverflow.com/questions/3906650/how-can-i-call-methods-from-a-regex-string/3906839#3906839
Read More

Tuesday, October 5, 2010

Fulltext search in sql server

To set fulltext search in sql server follow below steps:


EXEC sp_fulltext_database 'enable'
go
CREATE FULLTEXT CATALOG mycatalogName
go

CREATE NONCLUSTERED INDEX primaryKeyIndexName
ON FAQ (pkColumnName);

CREATE FULLTEXT INDEX ON dbo.TableName
(
Question
Language 0X0
)

KEY INDEX PK_TableName ON mycatalogName
WITH CHANGE_TRACKING AUTO


Solution By:Rajesh Rolen

Read More

Read config file using XML reader

The best way is to use System.Configuration.ConfigurationManager.AppSettings; to retrive values of webconfig but from xml reader you can also do that:


private void loadConfig()
{

XmlDocument xdoc = new XmlDocument();
xdoc.Load( Server.MapPath("~/") + "web.config");
XmlNode xnodes = xdoc.SelectSingleNode ("/configuration/appSettings");

foreach (XmlNode xnn in xnodes .ChildNodes)
{
ListBox1.Items.Add(xnn.Attributes[0].Value + " = " + xnn.Attributes[1].Value );
}

}
Read More

What is use of “??”.

It's the null-coalescing operator. Essentially it evaluates the left-hand operand, and if the result is null (either a null reference or the null value for a nullable value type) then it evaluates the right operand.

works something like this:

Instead of doing:

int? number = null;
int result = number == null ? 0 : number;

You can now just do:

int result = number ?? 0;

The result of the expression a ?? b is a if that's not null, or b otherwise. b isn't evaluated unless it's needed.

Two nice things:

*

The overall type of the expression is that of the second operand, which is important when you're using nullable value types:

int? maybe = ...;
int definitely = maybe ?? 10;

(Note that you can't use a non-nullable value type as the first operand - it would be pointless.)
*

The associativity rules mean you can chain this really easily. For example:

string address = shippingAddress ?? billingAddress ?? contactAddress;

That will use the first non-null value out of the shipping, billing or contact address.


Note that due to its associativity, you can write:

int? x = E1 ?? E2 ?? E3 ?? E4;

if E1, E2, E3 and E4 are all expressions of type int? - it will start with E1 and progress until it finds a non-null value.

The first operand has to be a nullable type, but e second operand can be non-nullable, in which case the overall expression type is non-nullable. For example, suppose E4 is an expression of type int (but all the rest are still int? then you can make x non-nullable:

int x = E1 ?? E2 ?? E3 ?? E4;
Read More

Monday, October 4, 2010

Do Enum Supports Inharitence

Enums do not supports inheritance since they are value type and therefor are sealed.
Read More

Value type polymorphism

.NET value types are objects descending from Object; but, they cannot inherit from other types. They can implement interfaces. Thus, primitives—such as Int32— can implement the IComparable interface, for example, making them comparable.
Read More

How to detect browser using javascript

we can use navigator.userAgent to detect the type/name of current browser and perform compatibility operations according to it:

below is javascript code so put it in script tag


function DetectBrowser()
{

var val = navigator.userAgent.toLowerCase();



if(val.indexOf("firefox") > -1)

{

isFF = true;

}

else if(val.indexOf("opera") > -1)

{
isOP = true;

}

else if(val.indexOf("msie") > -1)

{

isIE = true;

}

else if(val.indexOf("safari") > -1)

{

isIE = true;

}
}
Read More

How to Detect the browser using asp.net and c#.net

Many of times we need to detect browser type/name and its capability in asp.net
to do so below code can help you:
These properties are exposed by the HttpBrowserCapabilities object indicate inherent capabilities of the browser,
*but do not necessarily reflect current browser settings.

so using Request.Browser.Browser we can find the name of browser and using if-else/switch-case we can perform desired operation for specific browser type or we can use these to find capabilities of current browser and do operations according to supported by browser.


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim s As String = ""
With Request.Browser
s &= "Browser Capabilities" & vbCrLf
s &= "Type = " & .Type & vbCrLf
s &= "Name = " & .Browser & vbCrLf
s &= "Version = " & .Version & vbCrLf
s &= "Major Version = " & .MajorVersion & vbCrLf
s &= "Minor Version = " & .MinorVersion & vbCrLf
s &= "Platform = " & .Platform & vbCrLf
s &= "Is Beta = " & .Beta & vbCrLf
s &= "Is Crawler = " & .Crawler & vbCrLf
s &= "Is AOL = " & .AOL & vbCrLf
s &= "Is Win16 = " & .Win16 & vbCrLf
s &= "Is Win32 = " & .Win32 & vbCrLf
s &= "Supports Frames = " & .Frames & vbCrLf
s &= "Supports Tables = " & .Tables & vbCrLf
s &= "Supports Cookies = " & .Cookies & vbCrLf
s &= "Supports VBScript = " & .VBScript & vbCrLf
s &= "Supports JavaScript = " & _
.EcmaScriptVersion.ToString() & vbCrLf
s &= "Supports Java Applets = " & .JavaApplets & vbCrLf
s &= "Supports ActiveX Controls = " & .ActiveXControls & _
vbCrLf
s &= "Supports JavaScript Version = " & _
Request.Browser("JavaScriptVersion") & vbCrLf
End With
TextBox1.Text = s
End Sub

Reference Link:http://msdn.microsoft.com/en-us/library/3yekbd5b.aspx

Solution by:Rajesh Rolen

Read More

Wednesday, September 29, 2010

call function in javascript before window close

if you want to ask user before closing popup window or you want to perform certain operation before window gets closed, you can use below code for that:


window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}

Solution by:Rajesh Rolen

Read More

Thursday, September 23, 2010

Load XML using javascript [works with all browser]

When ever we wants to load and parse xml using javascript. we face a issue most of time is that the script works with one browser but not works with other.
Below script will work on all browsers including [safari,mizila firefox, crome]:


function loadxml() {
var xmlFeed = "xmldata/wfc20100915.xml";
if (window.ActiveXObject) {
var errorHappendHere = "Check Browser and security settings";
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(xmlFeed);
}
else if (window.XMLHttpRequest) {
var errorHappendHere = "Error handling XMLHttpRequest request";
var d = new XMLHttpRequest();
d.open("GET", xmlFeed, false);
d.send(null);
xmlDoc = d.responseXML;
} else {
var errorHappendHere = "Error.";
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(xmlFeed);
}


var tmp = readXML();

return tmp;
}
//below code is to read xml
function readXML() {

var labels = xmlDoc.getElementsByTagName('node');
arr = new Array();
var counter = 0;
for (i = 0; i < labels.length/ 10; i++) {
{
if (labels[i].childNodes.length >= 9) {
arr[counter] = new Array(5);
arr[counter][0] = parseFloat(labels[i].childNodes[1].textContent);
arr[counter][1] = parseFloat(labels[i].childNodes[3].textContent);
arr[counter][2] = parseFloat(labels[i].childNodes[5].textContent);
arr[counter][3] = parseFloat(labels[i].childNodes[7].textContent);
arr[counter][4] = parseFloat(labels[i].childNodes[9].textContent);
counter++;
}

}

return arr;

}


Solutions by: Rajesh Rolen

Read More

Sunday, September 19, 2010

Timer in javascript

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

* setTimeout() - executes a code some time in the future
* clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
The setTimeout() Method
Syntax
var t=setTimeout("javascript statement",milliseconds);

The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first parameter.

lets say I wanted to start download a file after 5 seconds of loading my web page.
for that i created below function which i using javascript timer:


write it in script tag in .aspx file:
function startdown() {
var url = "<%= siteurl %>";
setTimeout("window.location.href='" + url + "';", 5000);
}

in .cs file write below code:
protected void Page_LoadComplete(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "downloadnewwin", "startdown();", true);

}

you can use this timer for calling various javascript function or for any other activity.

Solutions By:Rajesh Rolen

Read More

Friday, September 17, 2010

How to: add 'Tweet This' button to Asp.net Webpage/website

You can add your own ‘Tweet This’ buttons to you webpage/website so that your visitors can post to twitter (complete with URL shortening using Bit.ly) is really easy.

step 1:go to solution exproler and add a webpage (i have given it name:MyTwitterPage).
step 2:remove all the HTML from the page.

step 3:Add below code in code behind file:

Imports System.Net

Partial Public Class MyTwitterPage

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Request.QueryString("url") <> "" And Request.QueryString("com") <> "" Then

TweetThis(Request.QueryString("url"), Request.QueryString("com"))

End If

End Sub

Private Sub TweetThis(ByVal sIWTFURL As String, ByVal sComment As String)

Dim sShortURL As String

Dim sFullTweet As String

sShortURL = ShortenURL(sIWTFURL)

sFullTweet = sComment & " - " & sShortURL

SentToTwitter(sFullTweet)

End Sub

Private Function ShortenURL(ByVal sURL As String) As String

Dim sJSON As String

Dim oWebClient As New WebClient

Dim sBitlyURL As String

Dim sShortURL As String

sBitlyURL = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" & Server.UrlEncode(sURL) & "&login=bitlyapidemologin&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07"

sJSON = oWebClient.DownloadString(sBitlyURL)

sJSON = Mid$(sJSON, InStr(sJSON, Chr(34) & "shortUrl" & Chr(34)) + 9)

Do While sJSON.ToLower.StartsWith("http://") = False

sJSON = Mid$(sJSON, 2)

Loop

sShortURL = sJSON.Split(Chr(34))(0)

ShortenURL = sShortURL

End Function

Private Sub SentToTwitter(ByVal sComments As String)

Dim sURL As String

sURL = "http://twitter.com/home/?status=" & HttpUtility.UrlEncode(sComments)

Response.Redirect(sURL, False)

End Sub

End Class

Note: I am using the default Bit.ly login in the example, you should sign up for your own bit.ly account so you can track usage of your links.

step 4:Now you just need to add some javascript to your html pages:


< a href="#" onClick='javascript:PostToTwitter()'> Tweet This < /a >

< script >
function PostToTwitter()
{
var sTweet = 'This is the default text that will appear in the tweet';
var ShareURL = window.location.href;

window.open('http://yoursite.com/MyTwitterPage.aspx?url='+encodeURIComponent(ShareURL)+'&com='+encodeURIComponent(sTweet));
return false;
}
< /script >

Solution By:Rajesh Rolen

Read More

Determine which columns have been modified as a result of an UPDATE operation

we can Determine which columns have been modified as a result of an UPDATE operation using CLR Triggers, this is its one of unique capabilities.

Unique Capabilities of CLR Triggers



Triggers written in Transact-SQL have the capability of determining which columns from the firing view or table have been updated by using the UPDATE(column) and COLUMNS_UPDATED() functions.

Triggers written in a CLR language differ from other CLR integration objects in several significant ways. CLR triggers can:

*Reference data in the INSERTED and DELETED tables
*Determine which columns have been modified as a result of an UPDATE operation
*Access information about database objects affected by the execution of DDL statements.

These capabilities are provided inherently in the query language, or by the SqlTriggerContext class.


Determining Updated Columns

You can determine the number of columns that were modified by an UPDATE operation by using the ColumnCount property of the SqlTriggerContext object. You can use the IsUpdatedColumn method, which takes the column ordinal as an input parameter, to determine whether the column was updated. A True value indicates that the column has been updated.

For example, this code snippet (from the EmailAudit trigger later in this topic) lists all of the columns updated:

C#

reader = command.ExecuteReader();
reader.Read();
for (int columnNumber = 0; columnNumber < triggContext.ColumnCount; columnNumber++)
{
pipe.Send("Updated column "
+ reader.GetName(columnNumber) + "? "
+ triggContext.IsUpdatedColumn(columnNumber).ToString());
}

reader.Close();

Visual Basic


reader = command.ExecuteReader()
reader.Read()
Dim columnNumber As Integer

For columnNumber=0 To triggContext.ColumnCount-1

pipe.Send("Updated column " & reader.GetName(columnNumber) & _
"? " & triggContext.IsUpdatedColumn(columnNumber).ToString() )

Next

reader.Close()


Reference:http://msdn.microsoft.com/en-us/library/ms131093.aspx
Read More

error: Execution of user code in the .NET Framework is disabled. Enable clr enabled configuration option

when you creates sql server clr project in visual studio and then when you wants to run stored procedure created using that clr project in sql server then you will get below error because by default sql server's CLR is not enabled:

error: Execution of user code in the .NET Framework is disabled. Enable clr enabled configuration option.

By default .NET Framwork is disabled in SQL2005.

How to fix:

1. Explore "SQL Server 2005/Configuration Tools/Surface Area Configuration" in your Start menu.
2. Select "Surface Area Configuration for Features"
3. You will find "CLR Integration" option, activate it and save


Solution By:Rajesh Rolen

Read More

Crystal Reports .NET Error - "Access to report file denied. Another program may be using it."

Crystal Reports .NET Error - "Access to report file denied. Another program may be using it."

From the been there, done that, beat my head against the wall until I figured it out file:

This is a very misleading error message, and usually has nothing to do with another program. The actual filename will differ based on your configuration, but the entire error message will be the same, similar to what's shown below.

Error in File C:\DOCUME~1\FFUK\ASPNET\LOCALS~1\Temp\temp_9ff883f0-88e3-469c-a942-092ca424001a.rpt: Access to report file denied. Another program may be using it.

In this example (http://www.asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=574159), the code was listed, setting the output file as such:

DiskOpts.DiskFileName = "C:\Output.pdf"

Usually, the ASPNET user does not have write permission granted to it, and especially not on the root directory. The solution in this case was to change the output directory to a subfolder of the web root, and grant ASPNET Modify permissions on that folder. If you're using Windows Server 2003, you need to grant permissions to Network Service, not ASPNET.

If you have configured your application to run as a user other than ASPNET, you need to make sure that user has the permissions described above. On Windows Server 2003, you need to grant permissions to NetworkService user, not ASPNET. The .NET Framework on Win2K3 uses NetworkService, while on Win2K, ASPNET.

provide write permission on c:\windows\temp

Dot forgot to restart IIS after setting permissions on folder:
go to run type iisreset and press enter.
Read More

Thursday, September 16, 2010

Convert String to Date

To convert string to date You either specify a culture that uses that specific format :
like we want to convert string date "dd/MM/yyyy" to Date..

datetime mydate = Convert.ToDateTime(
txtdate.Text, CultureInfo.GetCulture("en-GB")
);

or use the ParseExact method:

datetime mydate = DateTime.ParseExact(
txtdate.Text, "dd/MM/yyyy", CultureInfo.Invariant
);

The ParseExact method only accepts that specific format, while the Convert.ToDateTime method still allows some variations on the format, and also accepts some other date formats.

To catch illegal input, you can use the TryParseExact method:

DateTime d;
if (DateTime.TryParseExact(txtdate.Text, "dd/MM/yyyy", CultureInfo.Invariant, DateTimeStyles.None, out d)) {
datetime mydate = d;
} else {
// communcate the failure to the user
}
Read More

Tuesday, September 14, 2010

how to provide functionality to a Windows user based on the user rights that have been granted to the Windows user account.

You can design the Windows Form to accept the user name and password at runtime by using TextBox controls. Then, you can make the application verify the Windows user's user rights when the Windows user clicks a Button control. To do this, follow these steps:

1. Open form
2. from Toolbox,add two textbox to you form.
3. Add a button on form.
4. add a form2 in application
5. Add a Button control to the Form2 form.
6. add a label control on form2..
7. Right-click the Label1 Label control, and then click Properties.
8. In the Properties window, set the Size property to 200, 56.
9. Double-click the Button1 Button control, and then add the following code to the Button1_Click event handler:

Dim firstnum, secondnum, result As Integer
firstnum = InputBox("Enter the first number")
secondnum = InputBox("Enter the second number")
result = firstnum + secondnum
MessageBox.Show("The sum of the two numbers is:" & result)

Write code to validate the Windows user in your Visual Basic .NET application
You can use the LogonUser Win32 API to verify the user name and password. The LogonUser function is declared in the Advapi32.dll library. You can call the LogonUser function from your Visual Basic .NET application by using the Declare statement.

You must pass the domain name, the user name, and the password to the LogonUser function. The LogonUser function validates the user by using these parameters and then returns a Boolean value. If the function succeeds, you receive a handle to a token that represents the Windows user. The WindowsIdentity object uses this token to represent the Windows user in your Visual Basic .NET or Visual Basic 2005 application. The WindowsPrincipal object uses this WindowsIdentity object to verify the Windows user's user rights.

To write code that implements validation in your Visual Basic .NET or Visual Basic 2005 application, follow these steps:

1. In Solution Explorer, right-click Form1.vb, and then click View Code.
2. Add the following code at the top of the Form1 form:

Imports System.Security.Principal
Imports System.Security.Permissions
Imports System.Runtime.InteropServices
Imports System.Environment

3. Locate the following code:

End Class

4. Add the following code before the code that you located in step 3:


'The LogonUser function tries to log on to the local computer
'by using the specified user name. The function authenticates
'the Windows user with the password provided.
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean

'The FormatMessage function formats a message string that is passed as input.
_
Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
End Function

'The CloseHandle function closes the handle to an open object such as an Access token.
Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

5. Locate the following code:

End Class

6. Add the following code before the code that you located in step 5:

'The GetErrorMessage function formats and then returns an error message
'that corresponds to the input error code.
Public Shared Function GetErrorMessage(ByVal errorCode As Integer) As String
Dim FORMAT_MESSAGE_ALLOCATE_BUFFER As Integer = &H100
Dim FORMAT_MESSAGE_IGNORE_INSERTS As Integer = &H200
Dim FORMAT_MESSAGE_FROM_SYSTEM As Integer = &H1000

Dim msgSize As Integer = 255
Dim lpMsgBuf As String
Dim dwFlags As Integer = FORMAT_MESSAGE_ALLOCATE_BUFFER Or FORMAT_MESSAGE_FROM_SYSTEM Or FORMAT_MESSAGE_IGNORE_INSERTS

Dim lpSource As IntPtr = IntPtr.Zero
Dim lpArguments As IntPtr = IntPtr.Zero
'Call the FormatMessage function to format the message.
Dim returnVal As Integer = FormatMessage(dwFlags, lpSource, errorCode, 0, lpMsgBuf, _
msgSize, lpArguments)
If returnVal = 0 Then
Throw New Exception("Failed to format message for error code " + errorCode.ToString() + ". ")
End If
Return lpMsgBuf
End Function

7. In Solution Explorer, right-click Form1.vb, and then click View Designer.
8. Double-click the Button1 Button control, and then add the following code to the Button1_Click event handler:

Dim tokenHandle As New IntPtr(0)
Try

Dim UserName, MachineName, Pwd As String
'The MachineName property gets the name of your computer.
MachineName = System.Environment.MachineName
UserName = TextBox1.Text
Pwd = TextBox2.Text
Dim frm2 As New Form2
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
tokenHandle = IntPtr.Zero
'Call the LogonUser function to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(UserName, MachineName, Pwd, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)

If returnValue = False Then
'This function returns the error code that the last unmanaged function returned.
Dim ret As Integer = Marshal.GetLastWin32Error()
Dim errmsg As String = GetErrorMessage(ret)
frm2.Show()
frm2.Label1.Text = errmsg
frm2.Button1.Visible = False
Else
'Create the WindowsIdentity object for the Windows user account that is
'represented by the tokenHandle token.
Dim newId As New WindowsIdentity(tokenHandle)
Dim userperm As New WindowsPrincipal(newId)
'Verify whether the Windows user has administrative credentials.
If userperm.IsInRole(WindowsBuiltInRole.Administrator) Then
frm2.Button1.Text = "Add Numbers"
frm2.Label1.Text = "Click this button to add two numbers"
frm2.Show()
Else
frm2.Label1.Text = " You do not have administrative credentials."
frm2.Button1.Visible = False
frm2.Show()
End If
End If

'Free the access token.
If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then
CloseHandle(tokenHandle)
End If
Catch ex As Exception
MessageBox.Show("Exception occurred. " + ex.Message)
End Try

Back to the top
Verify that your Visual Basic .NET application works
To verify that the validation has completed correctly, follow these steps:

1. On the Build menu, click Build Solution.
2. On the Debug menu, click Start.
3. In the TextBox1 box, type a user name.
4. In the TextBox2 box, type a password.
5. Click Validate User.

references:http://support.microsoft.com/kb/841699
Read More

Free Download IP latitude longitude database

For various projects we need database of IP , latitude , longitude to locate city and country... here you can find it.

the best one :http://ipinfodb.com/ip_database.php

this is also good:http://www.maxmind.com/app/geolitecity

Solutions by:

Rajesh Rolen

Read More

Sunday, September 12, 2010

What is difference between Abstract and virtual keywords

Abstract differs from virtual in that a virtual method can have an overridable implementation whereas an abstract method has no implementation at all and, as such, abstract methods must be implemented in any derived classes but with virtual keyword its not essential to override that function in derived class but it allow derived class to override that function.

Solution by:

Rajesh Rolen

Read More

Friday, September 10, 2010

Get list of variables names in class

Sometimes we have lots of fields in a class and we want the field names.. in that situation we can get list of all field names using below code:
in below code "YourType" will be your class name of which fields name list you want.
for vs2008:
var fields = typeof(YourType).GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var names = Array.ConvertAll(fields, field => field.Name);

for vs2005:
FieldInfo[] fields = typeof(YourType).GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
string[] names = Array.ConvertAll(fields,
delegate(FieldInfo field) { return field.Name; });




Solution by:Rajesh Rolen

Read More

Memory Allocation and Disposal

Memory Allocation


The Common Language Runtime allocates memory for objects in two places: the stack and the heap. The stack is a simple first-in last-out memory structure, and is highly efficient. When a method is invoked, the CLR bookmarks the top of the stack. The method then pushes data onto the stack as it executes. When the method completes, the CLR just resets the stack to its previous bookmark—“popping” all the method’s memory allocations is one simple operation!

In contrast, the heap can be pictured as a random jumble of objects. Its advantage is that it allows objects to be allocated or deallocated in a random order. As we’ll see later, the heap requires the overhead of a memory manager and garbage collector to keep things in order.

To illustrate how the stack and heap are used, consider the following method:

void CreateNewTextBox()
{
TextBox myTextBox = new TextBox(); // TextBox is a class
}

In this method, we create a local variable that references an object. The local variable is stored on the stack, while the object itself is stored on the heap:


The stack is always used to store the following two things:

* The reference portion of reference-typed local variables and parameters (such as the myTextBox reference)
* Value-typed local variables and method parameters (structs, as well as integers, bools, chars, DateTimes, etc.)

The following data is stored on the heap:

* The content of reference-type objects.
* Anything structured inside a reference-type object.

Memory Disposal



Once CreateNewTextBox has finished running, its local stack-allocated variable, myTextBox, will disappear from scope and be “popped” off the stack. However, what will happen to the now-orphaned object on the heap to which it was pointing? The answer is that we can ignore it—the Common Language Runtime’s garbage collector will catch up with it some time later and automatically deallocate it from the heap. The garbage collector will know to delete it, because the object has no valid referee (one whose chain of reference originates back to a stack-allocated object).[1] C++ programmers may be a bit uncomfortable with this and may want to delete the object anyway (just to be sure!) but in fact there is no way to delete the object explicitly. We have to rely on the CLR for memory disposal—and indeed, the whole .NET framework does just that!

However there is a caveat on automatic destruction. Objects that have allocated resources other than memory (in particular “handles”, such as Windows handles, file handles and SQL handles) need to be told explicitly to release those resources when the object is no longer required. This includes all Windows controls, since they all own Windows handles! You might ask, why not put the code to release those resources in the object’s finalizer? (A finalizer is a method that the CLR runs just prior to an object’s destruction). The main reason is that the garbage collector is concerned with memory issues and not resource issues. So on a PC with a few gigabytes of free memory, the garbage collector may wait an hour or two before even getting out of bed!

So how do we get our textbox to release that Windows handle and disappear off the screen when we’re done with it? Well, first, our example was pretty artificial. In reality, we would have put the textbox control on a form in order to make it visible it in the first place. Assuming myForm was created earlier on, and is still in scope, this is what we’d typically do:

myForm.Controls.Add (myTextBox);

As well as making the control visible, this would also give it another referee (myForm.Controls). This means that when the local reference variable myTextBox drops out of scope, there’s no danger of the textbox becoming eligible for garbage collection. The other effect of adding it to the Controls collection is that the .NET framework will deterministically call a method called Dispose on all of its members the instant they’re no longer needed. And in this Dispose method, the control can release its Windows handle, as well as dropping the textbox off the screen.

All classes that implement IDisposable (including all Windows Forms controls) have a Dispose method. This method must be called when an object is no longer needed in order to release resources other than memory. There are two ways this happens:
- manually (by calling Dispose explicitly)
- automatically: by adding the object to a .NET container, such as a Form, Panel, TabPage or UserControl. The container will ensure that when it’s disposed, so are all of its members. Of course, the container itself must be disposed (or in turn, be part of another container).
In the case of Windows Forms controls, we nearly always add them to a container – and hence rely on automatic disposal.

The same thing applies to classes such as FileStream—these need to be disposed too. Fortunately, C# provides a shortcut for calling Dispose on such objects, in a robust fashion: the using statement:

using (Stream s = File.Create ("myfile.txt"))

{

...

}

This translates to the following code:

Stream s = File.Create ("myfile.txt");

try

{

...

}

finally

{

if (s != null) s.Dispose();

}

The finally block ensurse that Dispose still gets executed should an exception be thrown within the main code block.

What about in WPF?

Most of the elements in WPF don’t wrap unmanaged handles requiring explicit disposal. So you can mostly ignore the disposal with WPF!
Read More

Where does the value of variables in structure get stored in memory

Read More

What is use of Design Patterns

Read More

How to default initialize (not at declaring time) static variables of static class

Read More

What is difference between interface and abstract class

In C# there is no multiple inheritance. You can only inherit from one base
class, however you can implement multiple interfaces. An abstract base class
can't be directly instantiated, but it can implement code an interface can
only define it. A class that inherits from an abstract base class can choose
to override members or not (unless they are abstract themselves). All
members of an interface must be implemented.

Much of the time a class derived from another class will have a "type of"
relationship with the base class for example:

abstract class Fruit
{
}

class Apple : Fruit
{
}

Often interfaces represent a set of capabilities for example:


interface Eatable
{
public void Chew();
}

class Apple : Fruit, Eatable
{
public void Chew()
{
}
}


Also it depends on how polymorphic your code is. If you have divergent
objects that can be acted on in a similar way with in a system, it makes
sense to define interfaces for example:


class Apple : Fruit, Eatable
{
}

class Cow : Eatable
{
}


It is unlikely that class Cow and class Apple would inherit from the same
base class but it is likely that they would both be acted upon in a similar
way.

The following table compares the features of abstract classes and interfaces.



















Abstract class
Interface
Derived classes exhaust their single base class inheritance option.
Classes can implement multiple interfaces without using up their base class option. But, there are no default implementations.

Cannot be instantiated except as part of subclasses. Only derived classes can call an abstract class constructor.
Cannot be instantiated.
Defines abstract member signatures which derived classes must implement. Otherwise, the derived class itself will be abstract.
Defines abstract member signatures—all of which—implementing classes must implement. Otherwise, a compiler error results.
New non-abstract members may be added that derived classes will inherit without breaking version compatibility.
Extending an interface with new members breaks version compatibility.
Optionally, provide default (virtual) member implementation.
All members are virtual and cannot provide implementations.
Can include data fields.
Cannot include data fields. However, abstract properties may be declared.



So finally:
Interface programming is called the Programming by Contract because the class which is implementing the interface has to implement all the functions of interface. Interfaces is the only way provide multiple inheritence is C#. A class can not be inherited by more than one classes but it can implement more than one interfaces simultaneously. This was a short descritption about the Abstract Classes and Interfaces. Now the real thing comes in to picture. That What to Use When? So following are the points to remeber duirng the usage of Abstract Classes and Interfaces-
1. Interfaces should be used when creating a standalone project which can be changed at anytime, use an interface in preference to an abstract class; because, interfaces offers more design flexibility.
2. Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance.
3. Use an interface to design a polymorphic hierarchy for value types.
4. Use an interface when an immutable contract is really required.
5. Use an abstract class to define a common base class for a family of types.
6. Use an abstract class to provide default behavior to your application.
7. Subclass only a base class in a hierarchy to which the class logically belongs.
8. If you add a new functionality in abstract class then derived class can easily implement without breaking the versioning functionality. But in case of Interfaces addition of new interface member breaks the versioning functionality.

Reference Link:http://stackoverflow.com/questions/1231985/when-to-use-interfaces-or-abstract-classes-when-to-use-both

Solution By:Rajesh Rolen

Read More

In Single Ton design Pattern, the class will be static or Function will be static

Read More

What is difference between Singleton pattern and static class

Both can be invoked without instantiation, both provide only with one "instance" and neither of them is threadsafe.

Usually both should be implemented to be thread-safe.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

Advantages of singletons



Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

Solution by:

Rajesh Rolen

Read More

What is use of Single Tone Pattern

Read More

How to create Single Ton class pattern

Read More

What are the benefits of MVC architecture over N-Tier architecture

15 down vote accepted


N-tier architecture usually has each layer separated by the network. I.E. the presentation layer is on some web servers, then that talks to backend app servers over the network for business logic, then that talks to a database server, again over the network, and maybe the app server also calls out to some remote services (say Authorize.net for payment processing).

MVC is a programming design pattern where different portions of code are responsible for representing the Model, View, and controller in some application. These two things are related because, for instance the Model layer may have an internal implementation that calls a database for storing and retrieving data. The controller may reside on the webserver, and remotely call appservers to retrieve data. MVC abstracts away the details of how the architecture of an app is implemented.

N-tier just refers to the physical structure of an implementation. These two are related because an MVC design is often implemented using an N-tier architecture.


A 3-tier application it's deployed in 3 different processors/processes: such division is, most of all, physical (so watch your frequency of tier-crossing bcs it could affect the application performance, despite its multiple benefits). Usually the tiers are:

* The Front-End environment (typically a browser, a desktop application in a desktop terminal)
* The Middleware (an application server usually accessible thru a web protocol-based process)
* The Back-End, ranging from databases to large mainframe environments

In UML terms, a 3-tier application is better depicted with a Deployment diagram

The MVC architecture pattern establishes a division of responsibilities between components at a use case level, without mentioning physical boundaries (in deployment terms). Here you can find

* The Model, which represents the present status of the domain entities (without specifying where is that status, whether in memory, whether in a database, XML files set or a mainframe system)
* The View, responsible to capture user input and to display outcomes based on the Model status
* The Controller, which reacts to events generated in the View, motivating changes in the domain status (I mean, changes in the Model). Changes subsequently displayed in the View

In UML terms, the MVC architecture pattern is well depicted with a Sequence Diagram



So, as you can see, both models decompose applications from different perspectives and, sure, you can have both models present in a same application.

solution by:

Rajesh Rolen

Read More

Can we use virtual keyword with functions in interface

This is no need to use virtual keyword with functions of interface as it is by default made to override.
Read More

What will the use of Abstract class is preferred and where Interface will be preferred

Read More

What is difference between Custom Controls and User Controls

Difference between user controls and custom controls in .net (vb, c# net with asp.net)
User controls:

It is newly concept in .net it same like as inheritance concept in oops
In asp.net the base class is system.web.ui.page object
When ever creating user control that will be converting as a class, and this class become
Subclasses of System.web.ui.page class at compile time
User control extension with .ascx
Let us see program how build (at end I will mention difference between user control and
Custom control)


Now this save as labeltextbox.ascx (user control)
Now this user control can be used for any page in your web application


Custom control:
Creating user controls, which are essentially reusable small web pages,
You can also create your own compiled custom controls.
There are three ways to create custom controls:
1) Create a derived custom control by deriving from an existing control.
2) Create a composite control by grouping existing controls together into a new compiled control.
3) Create a full custom control by deriving from System.Web.UI.WebControls.WebControl
Composite controls are most similar to user controls. The key difference is that composite
Controls are compiled into a DLL and used as you would any server control.
Let us programmatically that will help how to build:

Let us see differences
User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx
Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll

A very good reference:http://support.microsoft.com/kb/893667

Solution by:Rajesh Rolen

Read More

How to create custom generic collection

Read More

What is difference betwee collections and Generic Collections

Read More

What is DHTML and what are its advantages over general HTML

Read More

What is XHTML? what is its advantages

XHTML Elements Must Be Properly Nested

In HTML, some elements can be improperly nested within each other, like this:
< b >< i >This text is bold and italic< /b >< /i >

In XHTML, all elements must be properly nested within each other, like this:
< b >< i >This text is bold and italic< /i >< /b >

Note: A common mistake with nested lists, is to forget that the inside list must be within < li > and < /li > tags.

This is wrong:
< ul >
< li >Coffee< /li >
< li >Tea
< ul >
< li >Black tea< /li >
< li >Green tea< /li >
< /ul >
< li >Milk< /li >
< /ul >

This is correct:
< ul >
< li >Coffee< /li >
< li >Tea
< ul >
< li >Black tea< /li >
< li >Green tea< /li >
< /ul >
< /li >
< li >Milk< /li >
< /ul >

Notice that we have inserted a < /li > tag after the < /ul > tag in the "correct" code example.
XHTML Elements Must Always Be Closed

Non-empty elements must have a closing tag.

This is wrong:
< p >This is a paragraph
< p >This is another paragraph

This is correct:
< p >This is a paragraph< /p >
< p >This is another paragraph< /p >

Empty Elements Must Also Be Closed

Empty elements must also be closed.

This is wrong:
A break: < br >
A horizontal rule: < hr >
An image: < img src="happy.gif" alt="Happy face" >

This is correct:
A break: < br / >
A horizontal rule: < hr / >
An image: < img src="happy.gif" alt="Happy face" / >

XHTML Elements Must Be In Lower Case

Tag names and attributes must be in lower case.

This is wrong:
< BODY >
< P >This is a paragraph< /P >
< /BODY >

This is correct:
< body >
< p >This is a paragraph< /p >
< /body >

XHTML Documents Must Have One Root Element

All XHTML elements must be nested within the < html > root element. Child elements must be in pairs and correctly nested within their parent element.

The basic document structure is:
< html >
< head > ... < /head >
< body > ... < /body >
< /html >

HTML Vs. XHTML


Both languages come in three flavors: Frameset, Transitional and Strict. The “strict” version is strongly recommended by the W3C for regular documents. Using strict versions removes problematic elements as well as forcing a significant separation between the structure of your document and its presentation. Transitional versions allow deprecated elements to assist those implementers to upgrade smoothly their software or their content.
Using the right tool for the job

Is there any advantage to using HTML 4.01 over XHTML 1.0? There is no simple answer and the benefits you will gain are tied to how you’re using the language in a given situation.

Switching from HTML 4.01 to XHTML 1.0 brings almost no direct benefits for the visitors of your Web site; still, there are several good reasons for Web authors to make the switch:
XHTML is easier to maintain

XML syntax rules are far more rigorous than HTML. As a result, XHTML makes authors work more precisely, having to address issues such as:

* all elements and attribute names must appear in lower case
* all attribute values must be quoted
* non-Empty Elements require a closing tag
* empty elements are terminated using a space and a trailing slash
* no attribute minimization is allowed
* in strict XHTML, all inline elements must be contained in a block element

In HTML, case, quotes, termination of many elements and uncontained elements are allowed and commonplace. The margin for errors in HTML is much broader than in XHTML, where the rules are very clear. As a result, XHTML is easier to author and to maintain, since the structure is more apparent and problem syntax is easier to spot.
XHTML is XSL ready

As you are probably aware by now, XHTML 1.0 is the reformulation of HTML 4.01 in XML. Therefore, XHTML documents are hypertext documents and XML documents. A powerful technology has been developed at W3C to manipulate and transform XML documents: the Extensible Style sheet Language Transformations (XSLT). This technology is tremendously useful to create various new resources automatically from an XHTML document. For example

* You can create a table of contents for a long document
* Get a quick overview of a page by listing its languages and structural outlines! See the Semantics extractor for this page, created by W3C QA Working Group member Dominique Hazaël-Massieux
* You can provide a printable version of your documents by using the XSL-FO features of XSL
* You can produce an RSS feed directly from your page, check out the QA RSS feed to see this in action

XHTML is easier to teach and to learn

The syntax rules defined by XML are far more consistent than those found in HTML and therefore easier to explain than the SGML rules on which HTML is based.
XHTML is ready for the future

When the new version of XHTML becomes a recommendation, XHTML 1.0 documents will be easily upgradable to this new version, to allow to take advantages of its exciting new features. It’s likely that an XSLT style sheet will be available by then to help you move your XHTML 1.0 (strict) documents to XHTML 2.0 documents.

Solution by:

Rajesh Rolen

Read More

Array is value type or reference type

Read More

What is procedure to host WCF webservices

WCF is a flagship product from Microsoft for developing distributed application using SOA. Prior to WCF traditional ASMX Web services were hosted only on Internet Information Services (IIS). The hosting options for WCF services are significantly enhanced from Microsoft .NET Framework 3.0 onwards. In WCF there are three main parts: Service, Endpoints and Hosting Environment. Multiple services can be hosted using a single host process and also the same service type can be hosted in multiple host processes. We can host a WCF service in two ways - Self Hosting and IIS Hosting. Here we will examine Self Hosting along with a comparative discussion of different hosting environments.

elf Hosting Vs IIS Hosting


Let’s look at  the differences between the two hosting types
available for a WCF service.


































Self-Hosting



IIS Hosting



Needs to add code to host the process



Automatic hosting



Host process should be running before client makes a call to the
service.


 




IIS host runs automatically when a client makes a call to the
service.


 




Automatic process recycling not possible



Automatic process recycling not possible




Can   controlled the service lifetime using Open and Close methods



Lifetime cannot be controlled manually.



Easy to deploy



More difficult deployment than  Self-Hosting



 


Protocols Supported































IIS6



http, wshttp



IIS7



HTTP,net.tcp,net.pipe,net.msmq



Windows
console and form application



HTTP,net.tcp,net.pipe,net.msmq



Windows
service



HTTP,net.tcp,net.pipe,net.msmq



WAS



HTTP,net.tcp,net.pipe,net.msmq










Steps to host WCF services



This is the Procedure to host and publish your Website : 1-Change the EndPoints in ServiceReferences.ClientConfig and any where there are Endpoints to
2-Right Click Project.Web and then select (Publish) :
a-Publish method :FTP
b-Target Location :any Folder(X)

3-When you have Images and ect.. you should all put in ClientBin in your (X) Folder

4-Configure your IIS >> Add the MIME types Like this >>>
http://www.longhorncorner.com/UploadFile/nipuntomar/ConfiguringIISSilverlight10022008234540PM/ConfiguringIISSilverlight.aspx

5-Add your Publish Folder to C:\Inetpub\wwwroot

6 >>

1. Open IIS
2. Expand Sites
3. Right click on Default Web Page and select "Add New Virtual Directory" option
4. In the opened pop-up window input "Alias" as Test and populate "Physical path" with C:\Inetpub\wwwroot\TestApp and click "OK"
5. Right click on the created virtual directory (Test) and select "Convert To Application" option from the content menu.
6. In the opened pop-up window make sure you have selected by clicking the "Select..." button Classic .NET AppPool in "Application pool". Click "OK".


7-Copy the clientAccessPolicy.xml and crossDomain.xml to your C:\Inetpub\wwwroot folder.

a-clientAccessPolicy.xml:















b-crossDomain.xml :








8-In your Sql Server , Give IIS Users Permissions to Access your Database.

Solution by:

Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates