Thank You for Visit Me
Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)
|
|
comments (1)
|
Introduction to ASP.NET Web Programming Using the Razor Syntax (C#) OverviewTutorialsVideosSamplesForumBooksOpen Source
Introducing ASP.NET Web Pages 2 - Getting StartedIntroducing ASP.NET Web Pages 2 - Programming BasicsIntroducing ASP.NET Web Pages 2 - Displaying DataIntroducing ASP.NET Web Pages 2 - HTML Form BasicsIntroducing ASP.NET Web Pages 2 - Entering Database Data by Using FormsIntroducing ASP.NET Web Pages 2 - Updating Database DataIntroducing ASP.NET Web Pages 2 - Deleting Database DataIntroducing ASP.NET Web Pages 2 - Creating a Consistent LayoutIntroducing ASP.NET Web Pages 2 - Publishing a Site by Using WebMatrixIntro to ASP.NET Web Programming Razor SyntaxASP.NET Web Pages Visual BasicIntro to DebuggingWorking with FormsValidating User Input in ASP.NET Web Pages SitesCreating a Consistent LookCustomizing Site-Wide BehaviorCreating and Using a Helper in an ASP.NET Web Pages SiteRendering ASP.NET Web Pages Sites for Mobile DevicesCreating Readable URLs in ASP.NET Web Pages SitesWorking with DataDisplaying Data in a ChartMigrating a Database to SQL ServerWorking with FilesWorking with ImagesWorking with VideoDisplaying Maps in an ASP.NET Web Pages SiteAdding Security and MembershipAdding Security to Any SiteEnabling Login from External Sites in an ASP.NET Web Pages SiteUsing a CAPTCHA to Prevent Automated Programs (Bots) from Using Your ASP.NET Web SiteSending Email from Your SiteAdding Search to Your Web SiteAdding Social Networking to Your WebsiteCaching to Improve the Performance of Your WebsiteAnalyzing Traffic
This article gives you an overview of programming with ASP.NET Web Pages using the Razor syntax. ASP.NET is Microsoft's technology for running dynamic web pages on web servers. This articles focuses on using the C# programming language.
What you'll learn:
- The top 8 programming tips for getting started with programming ASP.NET Web Pages using Razor syntax.
- Basic programming concepts you'll need.
- What ASP.NET server code and the Razor syntax is all about.
The Top 8 Programming Tips
This section lists a few tips that you absolutely need to know as you start writing ASP.NET server code using the Razor syntax.
Note The Razor syntax is based on the C# programming language, and that's the language that's used most often with ASP.NET Web Pages. However, the Razor syntax also supports the Visual Basic language, and everything you see you can also do in Visual Basic. For details, see the appendix Visual Basic Language and Syntax.
You can find more details about most of these programming techniques later in the article.
1. You add code to a page using the @ character
The @ character starts inline expressions, single statement blocks,
and multi-statement blocks:
<!-- Single statement blocks -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }
<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
This is what these statements look like when the page runs in a browser:

2. You enclose code blocks in braces
A code block includes one or more code statements and is enclosed in braces.
<!-- Single statement block. -->
@{ var theMonth = DateTime.Now.Month; }
<p>The numeric value of the current month: @theMonth</p>
<!-- Multi-statement block. -->
@{
var outsideTemp = 79;
var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<p>Today's weather: @weatherMessage</p>
The result displayed in a browser:

3. Inside a block, you end each code statement with a semicolon
Inside a code block, each complete code statement must end with a semicolon. Inline expressions don't end with a semicolon.
<!-- Single-statement block -->
@{ var theMonth = DateTime.Now.Month; }
<!-- Multi-statement block -->
@{
var outsideTemp = 79;
var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<!-- Inline expression, so no semicolon -->
<p>Today's weather: @weatherMessage</p>
4. You use variables to store values
You can store values in a variable,
including strings, numbers, and dates, etc. You create a new variable using the
var keyword. You can insert variable values directly in a page using @.
<!-- Storing a string -->
@{ var welcomeMessage = "Welcome, new members!"; }
<p>@welcomeMessage</p>
<!-- Storing a date -->
@{ var year = DateTime.Now.Year; }
<!-- Displaying a variable -->
<p>Welcome to our new members who joined in @year!</p>
The result displayed in a browser:

5. You enclose literal string values in double quotation marks
A string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:
@{ var myString = "This is a string literal"; }
If the string that you want to display contains a backslash character (\) or double quotation marks
( " ;), use
a verbatim string literal
that's prefixed with the @ operator. (In C#, the \ character has special
meaning unless you use a verbatim string literal.)
<!-- Embedding a backslash in a string -->
@{ var myFilePath = @"C:\MyFolder\"; }
<p>The path is: @myFilePath</p>
To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:
<!-- Embedding double quotation marks in a string -->
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
<p>@myQuote</p>
Here's the result of using both of these examples in a page:

Note Notice that the @ character is used both to
mark verbatim string literals in C# and to mark code in ASP.NET pages.
6. Code is case sensitive
In C#, keywords (like var, true, and if) and variable names are case sensitive.
The following lines of code create two different variables, lastName
and LastName.
@{
var lastName = "Smith";
var LastName = "Jones";
}
If you declare a variable as var lastName = "Smith"; and if you
try to reference that variable in your page as @LastName, an error
results because LastName won't be recognized.
Note In Visual Basic, keywords and variables are not case sensitive.
7. Much of your coding involves objects
An object represents a thing that you can program with — a page, a text box, a
file, an image, a web request, an email message, a customer record (database row),
etc. Objects have properties that describe their characteristics and that you
can read or change — a text box object
has a Text property (among others), a request object has a Url property, an email
message has a From property, and a customer object has a FirstName property. Objects
also have methods that are the "verbs" they can perform. Examples include a file
object's Save method, an image object's Rotate method, and an email object's
Send
method.
You'll often work with the Request object, which gives you information like the
values of text boxes (form fields) on the page, what type of browser made
the request, the URL of the page, the user identity, etc. The following example shows how
to access properties of the Request object and how to call the
MapPath method of
the Request object, which gives you the absolute path of the page on the server:
<table border="1">
<tr>
<td>Requested URL</td>
<td>Relative Path</td>
<td>Full Path</td>
<td>HTTP Request Type</td>
</tr>
<tr>
<td>@Request.Url</td>
<td>@Request.FilePath</td>
<td>@Request.MapPath(Request.FilePath)</td>
<td>@Request.RequestType</td>
</tr>
</table>
The result displayed in a browser:

8. You can write code that makes decisions
A key feature of dynamic web pages is that you can determine what to do based
on conditions. The most common way to do this is with the if statement
(and optional else statement).
@{
var result = "";
if(IsPost)
{
result = "This page was posted using the Submit button.";
}
else
{
result = "This was the first request for this page.";
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Submit"/>
<p>@result</p>
</form>
</body>
</html>
</body>
</html>
The statement if(IsPost) is a shorthand way of writing if(IsPost == true).
Along with if statements, there are a variety of ways to test conditions,
repeat blocks of code, and so on, which are described later in this article.
The result displayed in a browser (after clicking Submit):

A Simple Code Example
This procedure shows you how to create a page that illustrates basic programming techniques. In the example, you create a page that lets users enter two numbers, then it adds them and displays the result.
- In your editor, create a new file and name it AddNumbers.cshtml.
- Copy the following code and markup into the page, replacing anything already
in the page.
@{
var total = 0;
var totalMessage = "";
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Numbers</title>
<meta charset="utf-8" />
<style type="text/css">
body {background-color: beige; font-family: Verdana, Arial;
margin: 50px; }
form {padding: 10px; border-style: solid; width: 250px;}
</style>
</head>
<body>
<p>Enter two whole numbers and then click <strong>Add</strong>.</p>
<form action="" method="post">
<p><label for="text1">First Number:</label>
<input type="text" name="text1" />
</p>
<p><label for="text2">Second Number:</label>
<input type="text" name="text2" />
</p>
<p><input type="submit" value="Add" /></p>
</form>
<p>@totalMessage</p>
</body>
</html>Here are some things for you to note:
The
@character starts the first block of code in the page, and it precedes thetotalMessagevariable that's embedded near the bottom of the page.The block at the top of the page is enclosed in braces.
In the block at the top, all lines end with a semicolon.
The variables
total,num1,num2, andtotalMessagestore several numbers and a string.The literal string value assigned to the
totalMessagevariable is in double quotation marks.Because the code is case-sensitive, when the
totalMessagevariable is used near the bottom of the page, its name must match the variable at the top exactly.The expression
num1.AsInt() + num2.AsInt()shows how to work with objects and methods. TheAsIntmethod on each variable converts the string entered by a user to a number (an integer) so that you can perform arithmetic on it.The
<form>tag includes amethod="post"attribute. This specifies that when the user clicks Add, the page will be sent to the server using the HTTP POST method. When the page is submitted, theif(IsPost)test evaluates to true and the conditional code runs, displaying the result of adding the numbers.
- Save the page and run it in a browser. (Make sure the page is selected
in the Files workspace before you run it.) Enter two whole numbers and then
click the Add button.
Basic Programming Concepts
This article provides you with an overview of ASP.NET web programming. It isn't an exhaustive examination, just a quick tour through the programming concepts you'll use most often. Even so, it covers almost everything you'll need to get started with ASP.NET Web Pages.
But first, a little technical background.
The Razor Syntax, Server Code, and ASP.NET
Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code. Client content is the stuff you're used to in web pages: HTML markup (elements), style information such as CSS, maybe some client script such as JavaScript, and plain text.
Razor syntax lets you add server code to this client content. If there's server code in the page, the server runs that code first, before it sends the page to the browser. By running on the server, the code can perform tasks that can be a lot more complex to do using client content alone, like accessing server-based databases. Most importantly, server code can dynamically create client content — it can generate HTML markup or other content on the fly and then send it to the browser along with any static HTML that the page might contain. From the browser's perspective, client content that's generated by your server code is no different than any other client content. As you've already seen, the server code that's required is quite simple.
ASP.NET web pages that include the Razor syntax have a special file extension (.cshtml or .vbhtml). The server recognizes these extensions, runs the code that's marked with Razor syntax, and then sends the page to the browser.
Where does ASP.NET fit in?
Razor syntax is based on a technology from Microsoft called ASP.NET, which in turn is based on the Microsoft .NET Framework. The.NET Framework is a big, comprehensive programming framework from Microsoft for developing virtually any type of computer application. ASP.NET is the part of the .NET Framework that's specifically designed for creating web applications. Developers have used ASP.NET to create many of the largest and highest-traffic websites in the world. (Any time you see the file-name extension .aspx as part of the URL in a site, you'll know that the site was written using ASP.NET.)
The Razor syntax gives you all the power of ASP.NET, but using a simplified syntax that's easier to learn if you're a beginner and that makes you more productive if you're an expert. Even though this syntax is simple to use, its family relationship to ASP.NET and the .NET Framework means that as your websites become more sophisticated, you have the power of the larger frameworks available to you.

Basic Syntax
Earlier you saw a basic example of how to create an ASP.NET Web Pages page, and how you can add server code to HTML markup. Here you'll learn the basics of writing ASP.NET server code using the Razor syntax — that is, the programming language rules.
If you're experienced with programming (especially if you've used C, C++, C#, Visual Basic, or JavaScript), much of what you read here will be familiar. You'll probably need to familiarize yourself only with how server code is added to markup in .cshtml files.
Combining Text, Markup, and Code in Code Blocks
In server code blocks, you often want to output text or markup (or both) to the page. If a server code block contains text that's not code and that instead should be rendered as is, ASP.NET needs to be able to distinguish that text from code. There are several ways to do this.
- Enclose the text in an HTML element like
<p></p>or<em></em>:
@if(IsPost) {
// This line has all content between matched <p> tags.
<p>Hello, the time is @DateTime.Now and this page is a postback!</p>
} else {
// All content between matched tags, followed by server code.
<p>Hello <em>stranger</em>, today is: <br /> </p> @DateTime.Now
}The HTML element can include text, additional HTML elements, and server-code expressions. When ASP.NET sees the opening HTML tag (for example,
<p>), it renders everything including the element and its content as is to the browser, resolving server-code expressions as it goes. - Use the
@:operator or the<text>element. The@:outputs a single line of content containing plain text or unmatched HTML tags; the<text>element encloses multiple lines to output. These options are useful when you don't want to render an HTML element as part of the output.
@if(IsPost) {
// Plain text followed by an unmatched HTML tag and server code.
@: The time is: <br /> @DateTime.Now
<br/>
// Server code and then plain text, matched tags, and more text.
@DateTime.Now @:is the <em>current</em> time.
}If you want to output multiple lines of text or unmatched HTML tags, you can precede each line with
@:, or you can enclose the line in a<text>element. Like the@:operator,<text>tags are used by ASP.NET to identify text content and are never rendered in the page output.@if(IsPost) {
// Repeat the previous example, but use <text> tags.
<text>
The time is: <br /> @DateTime.Now
<br/>
@DateTime.Now is the <em>current</em> time.
</text>
}
@{
var minTemp = 75;
<text>It is the month of @DateTime.Now.ToString("MMMM"), and
it's a <em>great</em> day! <br /><p>You can go swimming if it's at
least @minTemp degrees. </p></text>
}The first example repeats the previous example but uses a single pair of
<text>tags to enclose the text to render. In the second example, the<text>and</text>tags enclose three lines, all of which have some uncontained text and unmatched HTML tags (<br />), along with server code and matched HTML tags. Again, you could also precede each line individually with the@:operator; either way works.Note When you output text as shown in this section — using an HTML element, the
@:operator, or the<text>element — ASP.NET doesn't HTML-encode the output. (As noted earlier, ASP.NET does encode the output of server code expressions and server code blocks that are preceded by@, except in the special cases noted in this section.)
Whitespace
Extra spaces in a statement (and outside of a string literal) don't affect the statement:
@{ var lastName = "Smith"; }
A line break in a statement has no effect on the statement, and you can wrap statements for readability. The following statements are the same:
@{ var theName =
"Smith"; }
@{
var
personName
=
"Smith"
;
}
However, you can't wrap a line in the middle of a string literal. The following example doesn't work:
@{ var test = "This is a long
string"; } // Does not work!
To combine a long string that wraps to multiple lines like the above code, there
are two options. You can use the concatenation operator (+), which you'll see later
in this article. You can also use the @ character to create a verbatim string literal,
as you saw earlier in this article. You can break verbatim string literals across
lines:
@{ var longString = @"This is a
long
string";
}
Code (and Markup) Comments
Comments let you leave notes for yourself or others. They also allow you to disable (comment out) a section of code or markup that you don't want to run but want to keep in your page for the time being.
There's different commenting syntax for Razor code and for HTML markup. As with all Razor code, Razor comments are processed (and then removed) on the server before the page is sent to the browser. Therefore, the Razor commenting syntax lets you put comments into the code (or even into the markup) that you can see when you edit the file, but that users don't see, even in the page source.
For ASP.NET Razor comments, you start the comment with @* and
end it with *@. The comment can be
on one line or multiple lines:
@* A one-line code comment. *@
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
Here is a comment within a code block:
@{
@* This is a comment. *@
var theVar = 17;
}
Here is the same block of code, with the line of code commented out so that it won't run:
@{
@* This is a comment. *@
@* var theVar = 17; *@
}
Inside a code block, as an alternative to using Razor comment syntax, you can use the commenting syntax of the programming language you're using, such as C#:
@{
// This is a comment.
var myVar = 17;
/* This is a multi-line comment
that uses C# commenting syntax. */
}
In C#, single-line comments are preceded by the // characters,
and multi-line comments begin with /*
and end with */. (As with Razor comments, C# comments are not
rendered to the browser.)
For markup, as you probably know, you can create an HTML comment:
<!-- This is a comment. -->
HTML comments start with <!-- characters and
end with -->. You can use HTML comments to surround not only
text, but also any HTML markup that you may want to keep in the page
but don't want to render. This HTML comment will hide the entire content of the tags and the text they
contain:
<!-- <p>This is my paragraph.</p> -->
Unlike Razor comments, HTML comments are rendered to the page and the user can see them by viewing the page source.
Variables
A variable is a named object that you use to store data. You can name variables anything, but the name must begin with an alphabetic character and it cannot contain whitespace or reserved characters.
Variables and Data Types
A variable can have a specific data type, which indicates what kind of data is stored in the variable. You can have string variables that store string values (like "Hello world"), integer variables that store whole-number values (like 3 or 79), and date variables that store date values in a variety of formats (like 4/12/2012 or March 2009). And there are many other data types you can use.
However, you generally don't have to specify a type for a variable. Most of the time, ASP.NET can figure out the type based on how the data in the variable is being used. (Occasionally you must specify a type; you'll see examples where this is true.)
You declare a variable using the var keyword (if you don't want to specify a
type) or by using the name of the type:
@{
// Assigning a string to a variable.
var greeting = "Welcome!";
// Assigning a number to a variable.
var theCount = 3;
// Assigning an expression to a variable.
var monthlyTotal = theCount + 5;
// Assigning a date value to a variable.
var today = DateTime.Today;
// Assigning the current page's URL to a variable.
var myPath = this.Request.Url;
// Declaring variables using explicit data types.
string name = "Joe";
int count = 5;
DateTime tomorrow = DateTime.Now.AddDays(1);
}
The following example shows some typical uses of variables in a web page:
@{
// Embedding the value of a variable into HTML markup.
<p>@greeting, friends!</p>
// Using variables as part of an inline expression.
<p>The predicted annual total is: @( monthlyTotal * 12)</p>
// Displaying the page URL with a variable.
<p>The URL to this page is: @myPath</p>
}
If you combine the previous examples in a page, you see this displayed in a browser:

Converting and Testing Data Types
Although ASP.NET can usually determine a data type automatically, sometimes it can't. Therefore, you might need to help ASP.NET out by performing an explicit conversion. Even if you don't have to convert types, sometimes it's helpful to test to see what type of data you might be working with.
The most common case is that you have to convert a string to another type, such as to an integer or date. The following example shows a typical case where you must convert a string to a number.
@{
var total = 0;
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
}
}
As a rule, user input comes to you as strings. Even if you've prompted users to enter a number, and even if they've entered a digit, when user input is submitted and you read it in code, the data is in string format. Therefore, you must convert the string to a number. In the example, if you try to perform arithmetic on the values without converting them, the following error results, because ASP.NET cannot add two strings:
Cannot implicitly convert type 'string' to 'int'.
To convert the values to integers, you call the AsInt method. If the conversion
is successful, you can then add the numbers.
The following table lists some common conversion and test methods for variables.
|
Method |
Description |
Example |
|
|
Converts a string that represents a whole number (like "593") to an integer. |
var myIntNumber = 0; |
|
|
Converts a string like "true" or "false" to a Boolean type. |
var myStringBool = "True"; |
|
|
Converts a string that has a decimal value like "1.3" or "7.439" to a floating-point number. |
var myStringFloat = "41.432895"; |
|
|
Converts a string that has a decimal value like "1.3" or "7.439" to a decimal number. (In ASP.NET, a decimal number is more precise than a floating-point number.) |
var myStringDec = "10317.425"; |
|
|
Converts a string that represents a date and time value to the ASP.NET
|
var myDateString = "12/27/2012"; |
|
|
Converts any other data type to a string. |
int num1 = 17; |
Operators
An operator is a keyword or character that tells ASP.NET what kind of command to perform in an expression. The C# language (and the Razor syntax that's based on it) supports many operators, but you only need to recognize a few to get started. The following table summarizes the most common operators.
|
Operator |
Description |
Examples |
|
|
Math operators used in numerical expressions. |
@(5 + 13)
|
|
|
Assignment. Assigns the value on the right side of a statement to the object on the left side. |
var age = 17; |
|
|
Equality. Returns |
var myNum = 15; |
|
|
Inequality. Returns |
var theNum = 13; |
|
|
Less-than, |
if (2 < 3) { |
|
|
Concatenation, which is used to join strings. ASP.NET knows the difference between this operator and the addition operator based on the data type of the expression. |
// The displayed result is "abcdef". |
|
|
The increment and decrement operators, which add and subtract 1 (respectively) from a variable. |
int theCount = 0; |
|
|
Dot. Used to distinguish objects and their properties and methods. |
var myUrl = Request.Url; |
|
|
Parentheses. Used to group expressions and to pass parameters to methods. |
@(3 + 7)
|
|
|
Brackets. Used for accessing values in arrays or collections. |
var income = Request["AnnualIncome"]; |
|
|
Not. Reverses a |
bool taskCompleted = false; |
|
|
Logical AND and OR, which are used to link conditions together. |
bool myTaskCompleted = false; |
How can a formcollection be enumerated in ASP.NET MVC?
|
|
comments (1)
|
Here are 3 ways to do it specifically with a FormCollection object.
public ActionResult SomeActionMethod(FormCollection formCollection)
{
foreach (var key in formCollection.AllKeys)
{
var value = formCollection[key];
}
foreach (var key in formCollection.Keys)
{
var value = formCollection[key.ToString()];
}
// Using the ValueProvider
var valueProvider = formCollection.ToValueProvider();
foreach (var key in valueProvider.Keys)
{
var value = valueProvider[key];
}
}
ASP.Net Chart Control On Shared Hosting Environment
|
|
comments (0)
|
Chart Control of ASP.Net 3.5 is very handy way to get statictical data as charts. There are variety of ways to display data with Chart Control. Also it is extramely simple to adapt it to your project. But as I hear from so many ASP.Net user nowadays, there might be some problems when it comes to publish it on your web server, especially on shared hosting servers !
After you install the Chart Control, in order to run ASP.Net chart control on your project, you need to configure your web.config file on your root directory which you have already done (I guess !). If you do that properly, you are able to run it on your local server perfectly. But it is not enough for you to be good to go on your web server.
You need to have Chart Control installed on your web server in order to run it on web !
It is easy to do that if you have your own server but for those who have their website files on a shared hosting service, it is a bit hard. But you do not need to beg your hosting provider to make it be installed on server. Only you need to do is to make proper changes on your web.config file and believe me those changes are much more simple than you think ! Of Course, some references is needed to be added to the Bin Folder on your root directory !
Solution :
Follow this directory on windows explorer:
C:\Program Files\Microsoft Chart Controls\Assemblies
You will see 4 DLL files inside the folder. Two of those files are for Windows Applications and two of them for Web Applications. We need web application dll files so copy the dll files which are named 'System.Web.DataVisualization.Design' and 'System.Web.DataVisualization'
Paste those dll files into the Bin folder on the root directory of your Web Application.
Secondly, open the Web.Config file on the root directory of your web application.Find the <appSettings> node. You have a key add inside this just like below;
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
Replace this tag with the new one as below;
<add key="ChartImageHandler" value="storage=file;timeout=20;"/>
Save the changes on your Web.Config file and close it. Now copy the two dll inside the bin folder and replace the Web.Config file on your server with your new Web.Config file.
That's it !
Now you should be able to run the Chart Control on your Web Server without begging your hosting provider
If you have any problem with this, I recommend you to check the following codes if they exist on your Web.Config file or not;
how to create and consume webservice using asp.net
|
|
comments (0)
|
What is Web Service?
Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as
HTTP
XML
SOAP
Advantages of Web Service
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Examples for Web Service
Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
News Headline: You can display latest news update by using News Headline Web Service in your website.
In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.
Frequently used word with web services
What is SOAP?
SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
What is WSDL?
WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.
What is UDDI?
UDDI allows you to find web services by connecting to a directory.
What is Discovery or .Disco Files?
Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.
Before start creating web service first create one table in your database and give name UserInformation in my code I am using same name and enter some dummy data for our testing purpose
Now we will see how to create new web service application in asp.net
Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service

Now our new web service ready our webservice website like this

Now open your Service.cs file in web service website to write the code to get the user details from database
Before writing the WebMethod in Service.cs first add following namespaces
using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page
Learn Objective-C: Day 1
|
|
comments (1)
|
What is Objective-C?
Objective-C is an object oriented language which lies on top of the C language (but I bet you guessed that part!). Itʼs primary use in modern computing is on Mac OS X as a desktop language and also on iPhone OS (or as it is now called: iOS). It was originally the main language for NeXTSTEP OS, also known as the operating system Apple bought and descended Mac OS X from, which explains why its primary home today lies on Appleʼs operating systems.
Because Objective-C is a strict superset of C, we are free to use C in an Objective-C file and it will compile fine. Because any compiler of Objective-C will also compile any straight C code passed into it, we have all the power of C along with the power of objects provided by Objective-C.
If youʼre a little confused at this point, think of it this way: everything C can do, Objective-C can do too, but not the other way around.
What will I need?
Throughout this series, we will not focus on building applications for the iPhone. Instead, we will concentrate more on the language itself and for this reason all you will need is a Mac with a compiler such as GCC. If youʼve installed the developer tools from Apple (Xcode, Interface Builder, etc), then GCC should already be installed. If not, then head to Appleʼs developer website and get yourself a free copy.
As far as prerequisites go, while I donʼt expect you to have a full background in computer science, some knowledge of programming in general or of C in particular would definitely be a bonus. If you donʼt have much prior programming experience, donʼt worry -youʼll pick it up in no time!
If youʼre running Windows (which is unlikely as this tutorial is aimed at iPhone developers) you can still compile Objective-C on your system using a compiler such as CygWin or MinGW. This tutorial series is catered to Mac users, but if you are using Windows and encounter any problems then be sure to leave a comment and Iʼll see if I can help.
Compiling your code
Before you can see your code in action, you need to be able to compile it into something executable. Hopefully you now have your copy of GCC ready. Compiling is really easy, a simple one line command.
NOTE:
Compiling is the process of “translating” a high-level computer language, like Objective-C or PHP, into a low-level machine code that can be processed by a computer when the program is executed.
All the programs that we see running in our fancy Mac OS operating system consist of a series of instructions that are visually displayed to us in a GUI, or Graphical User Interface. In contrast to the GUI program interaction with a mouse that most of us are familiar with, it is possible to issue commands directly to the operating system through a text-based interface known as a “terminal” or “command line.”
The command line application in Mac OS is called Terminal and can be found in Applications -> Utilities. Go ahead and open Terminal now (you can also search for it in Spotlight). Terminal has several basic commands you should be aware of in order to properly utilize it. One of the most important commands to know is cd, which stands for “change directory.” This command allows us to change where in the filesystem Terminal is reading from. We canʼt just tell Terminal to compile our file if we donʼt show it where the file is first! To switch to a desired directory, you can use a full path such as:
cd /Users/MyName/Desktop/Test You can also use relative paths, allowing you to only type a single folder name in some cases. For example, if youʼre already in your Desktop folder, you could simply type:
cd Test to get to the Test folder.
What if you want to see where you currently are? The immediate folder name is displayed before the prompt (the bit where you type). For example, if your prompt says Dan- Walkers-MacBook: Desktop iDemonix$ I can assume Iʼm in the Desktop folder. If you aren’t sure, you can also type pwd to display the absolute filepath of the current location.
If you want to list what files and folders are in the current folder, use the list command: ls. Finally, if you wish to go up a directory to a parent folder, type “cd .. “. So, if we were in the Test folder, which is inside the Desktop folder, but we wanted to go to the Desktop folder instead, we could type cd .. to go up to the parent directory, Desktop. If we wanted to get to the home directory we would type cd ../.. to go up two levels. Alternatively, to get to the home directory you can just type cd ~ from anywhere.
When using the Terminal application, compiling looks like this:
gcc inputfile.m -o outputfile Youʼve probably already guessed how it works: inputfile.m contains our code (.m is the extension used for Objective-C files) and -o tells gcc we want our executable to be called whatever we specify next, which in the example above is outputfile. To run our creation after compiling, we simply type:
./outputfile Simple.
When you compile, the compiler will generate any errors, notifications or warnings related to the syntax of your code. Errors generated when compiling are understandably referred to as “compile-time” errors, and this is often the most stressful part of writing an application (especially when your code isnʼt compiling because you put a single character in the wrong place or forgot to end a line with a semi-colon). Compiling can also take time when youʼre writing large applications consisting of multiple files, which is also another reason why compiling can be a tedious experience. This fact has led to a ubiquitous programmer joke often seen on the t-shirts of men with unkempt beards: “I’m not slacking off. My code is compiling.”
The Basics
Objective-C itself isnʼt that hard to learn. Once you get to grips with the basic principles, you can pick the rest up as you go along pretty easily. You do need to have an understanding of the fundamentals of C programming though, and that is what the rest of this tutorial will cover.
Letʼs look at a basic application in C:
#include <stdio.h> int main(){
printf("Hello World\n"); return 0;
}
All this application will do when you run it is display the string “Hello World” in Terminal and exit.
NOTE:
Curious about the “return 0″ statement? Because we told the compiler that the function main() will return an integer, we return the constant integer value ’0′ at the end of the function. By convention, returning ’0′ signals to the calling program that our program finished execution without any errors.
To try this for yourself, fire up Xcode and make a new Objective-C class. Delete all the code Xcode gives you by default and stick the above code in. Once youʼve done that, you can compile it using Terminal. Open Terminal and change to the location where your file is, if you saved to the desktop then simply type cd desktop so that Terminal is now reading from your Desktop. Then type this command:
gcc program1.m -o program1 Your program should compile with no errors. To run it, simply type:
./program1 Then hit return.
Awesome, so what actually happened there? Well, first we imported a library called stdio which manages the standard i/o (input output) functions, like printf(). We then create a function called main which should return an int or integer which is basically a number with no decimal point. We then use the printf() function to output ʻHello Worldʼ in to terminal. The \n we use tells Terminal to put a newline after the text. Finally, we return 0 (remember we said main should return an integer) which tells the operating system everything went fine. We use the name main because this is triggered automatically when the program is executed.
So far everything should be pretty simple: we wanted to write some text to Terminal, so we imported a library with a function for writing text, then we used a function from that library to write the text. Imagine that what you import is a physical library and printf() is one of the books available.
Variables
int – for storing integers (numbers with no decimal point)
char – for storing a character
float – for storing numbers with decimal points
double – same as a float but double the accuracy
When weʼre not using variables, weʼre often using constants. A constant will never change: we always know what the value will be. If we combine constants we get a constant expression, which we will always know the result of. For example:
123 + 2 = 125
This is a constant expression, 123 + 2 will always equal 125, no matter what. If we substituted a constant for a variable, the new expression would look like this:
view plaincopy to clipboardprint?123 + i = ? Because i is a dynamic variable, we do not definitely know the result of this equation. We can change i to whatever we want and get a different result. This should give you an idea of how variables work.
One thing we still need to know is how do we display variables like we displayed “Hello World” above? We still use the printf() function, except it changes a little this time:
#include <stdio.h> int main(){
int someNumber = 123;
printf("My number is %i \n", someNumber);
return 0; }
What weʼve done here is told the function printf() where we want our integer to appear, then where it can be found. This is different to a lot of languages such as PHP where you could just place the variable in the text.
We are not just limited to just one variable in printf(). The function can accept multiple parameters separated by commas, so we can pass in as many as we have formatting signs for in the text. Above we use %i as a formatting sign because we were including an integer. Other variables have their own format specifiers:
%i – integer
%f – float
%e – double
%c – charOne
thing I want to touch on before we move on is the char type. A variable of type char can only handle single characters, when thatʼs all we need this is great, but if we need a string of text itʼs pretty useless. To get round this, we use something called a character array.
Imagine you have a sentence that is 11 characters long (like ʻHello Worldʼ – donʼt forget to include the space), a character array is like having 11 charʼs but all glued together. This means that the value of the character array overall is ʻHello Worldʼ but char[0] is ʻHʼ. In brackets is the char youʼre after, because we put 0 we get the first character. Donʼt forget that counting in arrays usually starts from 0, not 1.
Conditionals
When an application needs to make a decision, we use a conditional. Without conditionals, every time you ran your application it would be exactly the same, like watching a movie. By making decisions based on variables, input or anything else, we can make the application change – this could be as simple as a user entering a serial number or pressing a button more than 10 times.
There are a few different types of conditionals, but for now weʼre just going to look at the most common and basic: the if statement. An if statement does what it sounds like, it checks to see if something is true, then acts either way. For example:
#include <stdio.h>
int main()
{
if(1 == 1) { // This is always true
// Do some stuff here
}
return 0;
}
If 1 is equal to 1, then whatever is between the brackets is executed. You might also be wondering why we used two equals signs instead of one. Using two equal signs is an equality operator, which checks to see if the two are equal to each other. If we use a single equal sign then weʼre trying to assign the first value to the second value.
Above, since 1 will always be the same as 1, whatever is in the brackets would be executed. What if we wanted to do something if this wasnʼt true though? Thatʼs where else comes in. By using else we can run code when the if conditional returns false, like so:
int main(){
if(1==1){
// Do some stuff here.
}
else{
// The universe is broken!
}
return 0;
}
Of course, in real life, we wouldn’t be checking to make sure 1 is the same as 1, but the point is made. Consider an application that closes if you press the close button three times (annoying but relevant). You could check in the brackets to see how many times it has been pushed. If it is lower than 3, then your else block could execute code to tell the user how many more times the button must be pushed to exit.
Weʼll look at conditionals more when we come to use them in our applications further along in the series.
Loops
Now let’s investigate a programming loop. Loops, as the name suggests, let us loop through a piece of code and execute it multiple times. This can come in very handy in situations such as populating a list or repeating a piece of code until a conditional returns true.
There are three types of loops, in order of most common: for, while, and do. Each one is used to repeat execution of a block of code, but they function differently. Here are examples of each:
// if loop
int main () {
int i = 9;
int x = 0;
for (x = 0; x < i; x++){
printf("Count is: %i\n", x);
}
return 0;
}
This may look a little complex at first, but it really isnʼt. In the parentheses after for is the initiator, a conditional, and the action. When the for loop starts it executes the initiator, which in our case above sets x to 0. Each time the loop runs (including the very first time) it checks the conditional, which is "is x smaller than i?" Finally, after each loop through the code, the loop runs the action - which above increments x by one. Simple. Since x is increasing by one each time, x will soon no longer be less than i and the loop will finish and the program will carry on running.
// while loop
int main () {
int x = 0;
while (x < 10){
printf("Count is: %i\n", x); //Watch OUT! Something is missing.
}
return 0;
}
Similar to the for loop, the while loop will execute the code between the brackets until the conditional is false. Since x is 0 and we don't change it in the code block, the above would run forever, creating an "infinite loop." If you wish to increment x, then in the case of our while loop you would do this between the brackets:
// while loop
int main () {
int x = 0;
while (x < 10){
x++;
printf("Count is: %i\n", x);
}
return 0;
}
The do loop is essentially the while loop, except the conditional runs after the block of code. What this means is when using a do loop, the code is guaranteed to run at least once:
// do loop
int main () {
int x = 0;
do {
x++;
printf("Count is: %i\n", x);
} while(x < 10);
return 0;
}
Pointers
Pointers can cause a lot of confusion with newcomers to programming or just newcomers to C. It is also not immediately clear to some people how they are useful, but youʼll gradually learn this over time. So, what is a pointer?
As the name implies, pointers point to a location. Specifically, locations in computer memory. Think of it like this, when we create a variable (let's say it's an integer called ʻfooʼ as is so popular with programming theory) and give it a value of, for example 123, we have just that - a variable with a value of 123. Now, if we setup a pointer to foo, then we have a way of indirectly accessing it. That is, we have a pointer of type int that points to foo which holds the value '123.' This would be done in code like so:
int foo = 123; // This is an integer variable
int *ptr = &foo; // This is a pointer to an integer variable
Clear as mud? Donʼt sweat it. Pointers are hard - often considered the hardest thing to learn when picking up the C language. Pointers will eventually become second nature to you though, and there will be more on pointers within Objective-C further in this series.
JQgrid Tutorial
|
|
comments (0)
|
ASP.NEt Interview Question
|
|
comments (1)
|
1. Explain the life cycle of an ASP .NET page.?
Following are the events occur during ASP.NET Page Life Cycle:
1)Page_PreInit
2)Page_Init
3)Page_InitComplete
4)Page_PreLoad
5)Page_Load
6)Control Events
7)Page_LoadComplete
8)Page_PreRender
9)SaveViewState
10)Page_Render
11)Page_Unload
Among above events Page_Render is the only event which is raised by page. So we can't write code for this event.
2. how does the cookies work in asp.net?
we know Http is an state-less protocol which is required for interaction between clinet and server .
so there is an need to remeber state of request raised by an web browser so that
web server can recognize you have already previously visited or not.
There are two types of state management techniques:
a) Client side state management
b) Server - side statemanagement
Using cookies comes under clinet side statemanagement .In HttpResponse we write
Cookie containing sessionId and other information within it.
when a browser made a request to the web server the same cookie is sent to the server where server recognize the session id and get other information stored to it previously.
3. What is Ispostback method in ASP.Net? Why do we use that??
Basically Post back is an action performed by a interactive Webpage. When it goes to the server side for a non-client Operation Server again posts it back to the client and hence the name.
Ex:
if(!IsPostBack)
will not allow the page to post back again n again bcoz it reduces the performance.
5. what is the difference between application state and caching?
Application Object and Cached Object both falls under Server side State Management.
Application object resides in InProc i.e. on the same server where we hosted our application.
Cache Object resides on server side/ DownStream/Client Side.
Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.
Only one user can access Application Object at a time hence we have to lock it every time we modify it.
6. what is boxing and unboxing?
Boxing is what happens when a value-type object is assigned to a reference-type variable.
Unboxing is what happens when a reference-type variable is assigned to a value-type variable.
7. What are the uses of Reflection??
Reflection is a concept using which we can
1) Load assemblies dynamically
2) Invoke methods at runtime
3) Retriving type information at runtime.
8. What is the use of AutoWireup in asp.net?
AutoEventWireup attribute is used to set whether the events needs to be automatically generated or not.
In the case where AutoEventWireup attribute is set to false (by default) event handlers are automatically required for Page_Load or Page_Init. However when we set the value of the AutoEventWireup attribute to true the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.
9. what events will occur when a page is loaded?
Below are the events occures during page load.
1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
10. Where is the View state Data stored?
ViewState data is stored in the hidden field. When the page is submitted to the server the data is sent to the server in the form of hidden fields for each control. If th viewstate of the control is enable true the value is retained on the post back to the client when the page is post backed.
12. Where do the Cookie State and Session State information be stored?
Cookie Information will be stored in a txt file on client system under a
folder named Cookies. Search for it in your system you will find it. Coming to Session State
As we know for every process some default space will be allocated by OS.
In case of InProc Session Info will be stored inside the process where our
application is running.
In case of StateServer Session Info will be stored using ASP.NET State Service.
In case of SQLServer Session info will be stored inside Database. Default DB
which will be created after running InstallSQLState Script is ASPState.
14. What are the different types of sessions in ASP.Net? Name them.?
Session Management can be achieved in two ways
1)InProc
2)OutProc
OutProc is again two types
1)State Server
2)SQL Server
InProc
Adv.:
1) Faster as session resides in the same process as the application
2) No need to serialize the data DisAdv.:
1) Will degrade the performance of the application if large chunk of data is stored
2) On restart of IIS all the Session info will be lost
State Server
Adv.:
1) Faster then SQL Server session management
2) Safer then InProc. As IIS restart
won't effect the session data
DisAdv.:
1) Data need to be serialized
2) On restart of ASP.NET State Service session info will be lost
3)Slower as compared to InProc
SQL Server
Adv.:
1) Reliable and Durable
2) IIS and ASP.NET State Service
restart won't effect the session data
3) Good place for storing large chunk of data
DisAdv.:
1) Data need to be serialized
2) Slower as compare to InProc and State Server
3)Need to purchase Licensed
version of SQL Serve
16. What is caching? What are different ways of caching in ASP.NET?
Caching is a technique of persisting the data in memory for immediate access to requesting program calls. This is considered as the best way to enhance the performance of the application.
Caching is of 3 types:
Output Caching - Caches the whole page.
Fragment Caching - Caches a part of the page
Data Caching - Caches the data
17. What is meant by 3-tier architecture.
We generally split our application into 3-Layers
1)Presentation Layer ( Where we keep all web forms Master Pages and User Controls).
2)Business Layer (Where we keep business logic). e.g Code related to manipulating data Custom Exception classes Custom Control classes Login related code if any etc. etc.
3)Data Access Layer (Where we keep code used to interact with DB). e.g. We can have the methods which are using SQL Helper (Application Block).
19. What is the difference between mechine.config and web.config?
machine.config is a system level configuration i.e it is applied on all application in o/s that the configuration is set where as in web.config it is applicable to only one application i.e each asp.net webapplication will contain atleast on web.config file.
21. What is the difference between Response.Redirect and Server.Transfer.
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server.Server.Transfer does not update the clients url history list or current url.
Response.Redirect is used toredirect the user's browser to another page or site. This performs a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.
25. What is the exact purpose of http handlers?
ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP URLs or groups of URL extensions within an application. HttpHandlers have the same functionality as ISAPI extensions with a much simpler programming model
Ex
1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)
2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler (*.asmx)
An HttpHandler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler usually launches a process that can be lengthy and returns before that process finishes
After writing and compiling the code to implement an HttpHandler you must register the handler using your application's Web.config file.
Interview Question of .NET
|
|
comments (0)
|
Cookies
Definition: – A cookie is information that a Website puts on your hard disk so that it can remember something about you at a later time. (More technically, it is information for future use that is stored by the server on the client side of a client/server communication.)
In short, Cookie is client’s information for particular site stored on client’s PC.
Typically, a cookie records your preferences when using a particular site. Using the Web’s Hypertext Transfer Protocol (HTTP), each request for a Web page is independent of all other requests. For this reason, the Web page server has no memory of what pages it has sent to a user previously or anything about your previous visits. A cookie is a mechanism that allows the server to store its own information about a user on the user’s own computer.
Procedure:- following are steps show how cookies works
When you visit some site, server for that site stores information (user name or simply physical address of user’s pc) in 1 text file. For that, that site may ask you to fill details about yourself or it can simple fetch physical address of your computer.Server sends this file to client with web page and that file is saved in client’s pc.Now when user visits that website again, that cookie file is also sent to server with the web page request. From that file, website’s sever can identify that particular user and do further procedures (Ex. Prepare customized webpage for that user) using that information.
Session
Definition: – A session is information of user that a Website puts on its temporary memory so that it can remember something about you when you are visiting that site. (More technically, it is information for future use that is stored by the server on the server side of a client/server communication.)
In short, Session is client’s information for particular site stored on Server’s temporary memory. The period of time a user interfaces with an application. The user session begins when the user accesses the application and ends when the user quits the application The number of user sessions on a site is used in measuring the amount of traffic a website gets. The site administrator determines what the time frame of a user session will be (e.g., 30 minutes). If the visitor comes back to the site within that time period, it is still considered one user session because any number of visits within those 30 minutes will only count as one session. If the visitor returns to the site after the allotted time period has expired, say an hour from the initial visit, then it is counted as a separate user session. Contrast with unique visitor, hit, click-through and page view, which are all other ways that site administrators measure the amount of traffic a Web site gets. Example:- When you visit www.gmail.com , you have to enter your account ID and password first. That information is verified on server and stored on server in session until that user is logged on.
What is the difference between session and cookie?
If you set the variable to “cookies”, then your users will not have to log in each time they enter your community. The cookie will stay in place within the user’s browser until the user deletes it.
But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
If you set the variable to “sessions”, then user activity will be tracked using browser sessions, and your users will have to log in each time they re-open their browser. Additionally, if you are using the “sessions” variable, you need to secure the “sessions” directory, either by placing it above the web root or by requesting that your web host make it a non-browsable directory.
The Key difference would be cookies are stored in your hard disk whereas a session aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects
Explain the access specifiers Public, Private, Protected, Friend, Internal, Default?
The main purpose of using access specifiers is to provide security to the applications. The availability (scope)of the member objects of a class may be controlled using access specifiers.
1. PUBLIC
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.
2. PRIVATE
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.
3. FRIEND/INTERNAL
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#.Friends can be accessed by all classes within an assembly but not from outside the assembly.
4. PROTECTED
Protected variables can be used within the class as well as the classes that inherites this class.
5. PROTECTED FRIEND/PROTECTED INTERNAL
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.
6. DEFAULT
A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.
Whats the difference between Classic ASP and ASP.NET?
Major difference: Classic ASP is Interpreted. ASP.NET is Compiled. If code is changed, ASP.NET recompiles, otherwise does'nt.
Other differences: ASP works with VB as the language. ASP.NET works with VB.NET & C# as the languages (Also supported by other languages that run on the .NET Framework).
ASP.NET is the web technology that comes with the Microsoft .NET Framework. Themain process in ASP.NET is called aspnet_wp.exe that accesses system resources. ASP.NET was launchedin 2002 with version 1.0. Subsequent versions are 1.1 and version 2.0. ASP.NET is built upusing thousands of objects, ordered in the System namespace. When an ASP.NET class is compiled, itscalled an assembly.
In Classic ASP, complex functionalities are achieved using COM components, that are nothingbut component objects created using VB 6, C++ etc, and are usually in a DLL format. Thesecomponents provide an exposed interface to methods in them, to the objects that reference thesecomponents. Last version of classic ASP is version 3.0. ASP has 7 main objects - Application, ASPError, ObjectContext, Request, Response, Server, Session.
Dynamically setting the "editoption" 'value' field for a select box in jqgrid with AJAX call
|
|
comments (1)
|
<script type="text/javascript">
$(function() {
var data1 = '';
var tmp = 'Select:Select Course;';
$.ajax({
type: "POST",
url: "AddAEP.aspx/GetCourses",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
data1 = msg.d.split(";");
for (var i = 0; i <= data1.length - 1; i++) {
tmp = tmp + data1[i] + ";";
}
tmp = tmp.substring(0, tmp.length - 1);
}
});
$("#InstructorGrid").jqGrid({
url: '../Handler/InstructorHandler.ashx',
datatype: 'json',
height: 300,
width: 1000,
colNames: ['InstructorID', 'Date', 'CourseName', 'CourseNumber', 'Instructor', 'Comments', 'Actions'],
colModel: [
{ name: 'InstructorID', index: 'InstructorID', width: 100, sortable: false, hidden: true },
{ name: 'Date', width: 100, sortable: false, editable: true, editrules: { required: true, date: true, datefmt: 'd-M-Y'} },
{ name: 'CourseName', width: 150, editable: true, editrules: { required: false }, edittype: "select", formatter: "select", editoptions: { value: tmp} },
{ name: 'CourseNumber', width: 100, editable: true, editrules: { required: false }, edittype: "select", editoptions: { dataUrl: "../Handler/Select.txt"} },
{ name: 'Instructor', width: 100, editable: true, editrules: { required: false }, edittype: "select", editoptions: { value: "UserHandler.ashx/GetAllUserName1"} },
{ name: 'Comments', width: 250, editable: true, edittype: "textarea", editoptions: { rows: "5", cols: "30"} },
{ name: 'Actions', width: 100 }
],
rowNum: 25,
rowList: [25, 35, 45],
pager: '#InstructorGridPager',
//sortname: 'StudentID',
viewrecords: true,
mtype: "GET",
editurl: '../Handler/InstructorHandler.ashx',
gridview: true,
sortorder: 'asc',
caption: 'Instructor',
//loadComplete: function(data) {
// alert("safdewrfe");
//$("#InstructorGrid").setColProp('CourseName', { editoptions: { value: "A:A"} });
//},
col: {
caption: "Show/Hide Columns",
bSubmit: "Submit",
bCancel: "Cancel"
}
});
$("#InstructorGrid").jqGrid('navGrid', '#InstructorGridPager', { edit: true, add: true, del: true });
options = { autosearch: true };
$("#InstructorGrid").filterToolbar(options);
});
</script>
WebMethod:
[WebMethod ]
public static string GetCourses()
{
string Users = "";
string connectionString = SQLHelper.getConnetionString();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
//command.CommandText = "User_GETAllUser";
command.CommandText = "SELECT CourseTitle FROM CourseCatalog";
//command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
string user;
while (dataReader.Read())
{
user = Convert.ToString(dataReader["CourseTitle"]);
Users += user + ":" + user + ";";
}
Users = Users.Substring(0, Users.Length - 1);
}
}
return Users;
}
Dynamically setting the "editoption" 'value' field for a select box in jqgrid
|
|
comments (0)
|
1) call $.get() before constructing the grid
2) put its result into a variable
3) set that variable in value:name pair of the select box editoptions
in colModel.
This didn't work because of $.get() executing an AJAX call asynchronously
so that the abovementioned variable is assigned before the AJAX call is
finished and gets 'undefined' value accordingly.
The only way I found to make the stuff work is to use $.ajax() with async
set to 'false' ( instead of calling $.get() ) :
===========================
jQuery(document).ready(function(){
var selectValue = $.ajax({
url: "get_some_params_url",
async: false
}).responseText;
………….
colModel : [
..........
{
edittype: "select",
editoptions: {value: selectValue}
},
.........
],
}
========================
Which is obviously not performance "friendly". It would be great to get
an option just to put a function making an AJAX call into 'editoptions', so
that the call will be fired off only when you click on a select box to pick the
value.
We have here a lot of possible solutions.
1. Setting the values direct via script – here is PHP example:
When you call the page with a grid – call it as php page and not as html
colModel [{....
{name:"mayname"...editable:true,edittype:"select",
editoptions:{'<?=$myeditoptions?>'}...},
...
]
where the variable $myeditoptions holds the values from the db
This is the recommendet solution. If this is not possible
2. We can use the method from previous post. We can cal this after the grid is constructed.It is not too late – why?
$.get("myurl",data:mydata,function(result,status){
if (status == "success") {
// get the result here, suppose that in myselect are the values
$("#mygrid").setColProp("myname",{editoptions:{myselects}});
…
}
}
3. Another possible solution is to use the userData in jqGrid -
(this is another elegant solution). See userData examples haw to do that.
Then
loadComplete : function() {
// get the userData here and convert it to format supported
// in colModel then the same tehchniquie as from 2
$("#mygrid").setColProp("myname",{editoptions:{myselects}});
…
}
~Enjoy
