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
Powered By Blogger · Designed By Seo Blogger Templates