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;
}
Wednesday, September 29, 2010
call function in javascript before window close
Thursday, September 23, 2010
Load XML using javascript [works with all browser]
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
Sunday, September 19, 2010
Timer in javascript
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
Friday, September 17, 2010
How to: add 'Tweet This' button to Asp.net Webpage/website
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
Determine which columns have been modified as a result of an UPDATE operation
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
error: Execution of user code in the .NET Framework is disabled. Enable clr enabled configuration option
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
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.
Thursday, September 16, 2010
Convert String to Date
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
}
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.
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
Free Download IP latitude longitude database
the best one :http://ipinfodb.com/ip_database.php
this is also good:http://www.maxmind.com/app/geolitecity
Solutions by:
Rajesh Rolen
Sunday, September 12, 2010
What is difference between Abstract and virtual keywords
Solution by:
Rajesh Rolen
Friday, September 10, 2010
Get list of variables names in class
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
delegate(FieldInfo field) { return field.Name; });
Solution by:Rajesh Rolen
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!
What is difference between interface and abstract class
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
What is difference between Singleton pattern and static class
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
What are the benefits of MVC architecture over N-Tier architecture
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
Can we use virtual keyword with functions in interface
What is difference between Custom Controls and User Controls
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
What is XHTML? what is its advantages
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
What is procedure to host WCF webservices
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
| IIS host runs automatically when a client makes a call to the
|
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 | HTTP,net.tcp,net.pipe,net.msmq |
Windows | 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
How many type of Styles in SilverLight
Every Style Element requires a Key, so that we can refer it anywhere using their Key. It supports only named types. It requires TargetType, which is the type of an element on which you r applying a style.
There are three ways to use Styles:
1. You can apply styles to particular page.
2. You can apply styles to particular Control.
3. You can apply styles globally.
Let us see all the steps one by one.
1. Applying Styles to a particular page:
Defining:
First we need to define the style in UserControl.Resource section like,
1.gif
A Setter element is a definition of one property to set on the target object. A Setter has a two Property one is Property naming the property to set on the target and another one is Value property defining the value to set on the property.
Here is your Page.xaml code:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
Applying:
Then you can apply the style which you have created using the Style property of a Button as shown in the below code.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
2. Applying Styles to a particular Control:
To use Style for a particular Control, place the style directly in the control. Here, no need to mention the x:Key attribute.
For Example,
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
3. Applying Styles Globally:
To use the Styles globally, i.e., you can use the Styles in any xaml pages throughout your application, for that you need to define the Style in Application.Resource in App.xaml file.
x:Class="styling.App">
Here is your xaml file.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
Solution by:
Rajesh Rolen
When "VAR" becomes of type
Var i = 10;
so when i will become an integer at run-time or at compile time?
Thursday, September 9, 2010
Structure are Reference type or value type
Structs are value types, while classes are reference types, and the runtime deals with the two in different ways
When a value-type instance is created, a single space in memory is allocated to store the value. Primitive types such as int, float, bool and char are also value types, and work in the same way. When the runtime deals with a value type, it's dealing directly with its underlying data and this can be very efficient, particularly with primitive types.
With reference types, however, an object is created in memory, and then handled through a separate reference—rather like a pointer.
Primitives are reference type or value type
Overriding in Interface is possible or Not
Wednesday, September 8, 2010
Convert HTML to Doc in asp.net
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
Finally, paste the following code in the button click event
Listing 2
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset ="";
HttpContext.Current.Response.ContentType ="application/msword";
string strFileName = "GenerateDocument"+ ".doc";
HttpContext.Current.Response.AddHeader("Content-Disposition",
"inline;filename=" + strFileName);
StringBuilder strHTMLContent = newStringBuilder();
strHTMLContent.Append(
" < h1 title='Heading' align='Center'style='font-family: verdana; font -size: 80 % ;
color: black' >< u >Document Heading< /u > < / h1 > ".ToString());
strHTMLContent.Append("< br >".ToString()); strHTMLContent.Append(
"< table align='Center' >".ToString());
// Row with Column headers
strHTMLContent.Append("< tr >".ToString()); strHTMLContent.Append(
"< td style='width:100px; background:
# 99CC00' >< b >Column
1 < / b > < / td >".ToString());
strHTMLContent.Append("< td style='width:100px;background:
# 99CC00' >< b >Column
2 < / b > < / td >".ToString());
strHTMLContent.Append("< tdstyle='width:100px; background:
# 99CC00' >< b >Column 3< /b >
< / td >".ToString());strHTMLContent.Append(" < / tr > ".ToString());
// First Row Data
strHTMLContent.Append("< tr >".ToString()); strHTMLContent.Append(
"< td style='width:100px' >a< /td >" .ToString()); strHTMLContent.Append(
"< td style='width:100px' >b< /td >" .ToString()); strHTMLContent.Append(
"< td style='width:100px' >c< /td >" .ToString());strHTMLContent.Append("< /tr >"
.ToString());
// Second Row Data
strHTMLContent.Append("< tr >".ToString()); strHTMLContent.Append(
"< td style='width:100px' >d< /td >" .ToString()); strHTMLContent.Append(
"< td style='width:100px' >e< /td >" .ToString()); strHTMLContent.Append(
"< td style='width:100px' >f< /td >" .ToString()); strHTMLContent.Append("< /tr >"
.ToString());
strHTMLContent.Append("< /table >".ToString());
strHTMLContent.Append("< br >< br >".ToString()); strHTMLContent.Append(
"< p align='Center' > Note : This is adynamically generated word document < / p > ".ToString());
HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();