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.
How do you setup a linked server to an Oracle database on SQL
|
|
comments (0)
|
setup a linked server to a remote Oracle database, which ended up being a multi-step process:
Install Oracle ODBC drivers on SQL Server.
Create System DSN to Oracle database on SQL Server.
Create linked server on SQL server using System DSN.
Step 1: Install Oracle ODBC drivers on server
a. Download the necessary Oracle Instant Client packages: Basic, ODBC, and SQL*Plus (optional)
b. Unzip the packages to a local directory on the SQL server, typically C:\Oracle. This should result in a [directory] like *C:\Oracle\instantclient_10_2*, which will be the value of [directory] referenced in the rest of this answer.
c. Create a text file named tnsnames.ora within the instant client [directory] that contains the following:
OracleTnsName =
(
DESCRIPTION=
(
ADDRESS = (PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521)
)
(
CONNECT_DATA = (SERVICE_NAME=acc)
)
)
Note: Actual HOST, PORT, and SERVICE_NAME will vary based on Oracle server you are establishing a connection to. This information can often be found using the Oracle network client tools under the listeners.
The OracleTnsName can be any name you want to assign to the Oracle data source, and will be used when setting up the system DSN. You can also use the syntax above to define multiple TNS names in the same tnsnames.ora file if desired.
d. Add the [directory] to the system PATH environment variable.
e. Create a new system environment variable named TNS_Admin that has a value of [directory]
f. Execute the [directory]**odbc_install.exe** utility to install the Oracle ODBC drivers.
g. It is recommended that you reboot the SQL server, but may not be necessary. Also, you may want to grant security permissions to this directory for the SQL server and SQL agent user identities.
Step 2: Create a System DNS that uses the Oracle ODBC driver
a. Open the ODBC Data Source Administrator tool. [ Administrative Tools --> Data Sources (ODBC) ]
b. Select the System DSN tab and then select the Add button.
c. In the drivers list, select Oracle in instantclient {version}. (e.g. 'Oracle in instantclient 10_2') and then select Finish button.
d. Specify the following:
Data Source Name: {System DSN Name}
Description: {leave blank/empty}
TNS Service Name: should have the OracleTnsName you defined in the tnsnames.ora file listed, select it as the value.
User ID: {Oracle user name}
e. Select Test Connection button. You should be prompted to provide the {Oracle user password}. If all goes well the test will succeed.
Step 3: Create linked server in SQL to the Oracle database
Open a query window in SQL server and execute the following:
EXEC sp_addlinkedserver
@server = '{Linked Server Name}'
,@srvproduct = '{System DSN Name}'
,@provider = 'MSDASQL'
,@datasrc = '{System DSN Name}'
EXEC sp_addlinkedsrvlogin
@rmtsrvname = '{Linked Server Name}'
,@useself = 'False'
,@locallogin = NULL
,@rmtuser = '{Oracle User Name}'
,@rmtpassword = '{Oracle User Password}'
Note: The {Linked Server Name} can be anything you want to use when referencing the Oracle server, but the {System DNS Name} must match the name of the system DSN you created previously.
The {Oracle User Name} should be the same as the User ID used by the system DSN, and the {Oracle User Password} should be the same as you used to sucessfully test the ODBC connection. See KB 280106 for information on troubleshooting Oracle linked server issues.
Querying the Oracle linked server
You may use OPENQUERY to execute pass-through queries on the Oracle linked server, but be aware that for very large recordsets you may recieve a ORA-01652 error message if you specify a ORDER BY clause in the pass-through query. Moving the ORDER BY clause from the pass-through query to the outer select statement solved this issue for me.
২৯তম বিসিএসের ১৪৮০ জন নিয়োগ পেলেন(Download List)
|
|
comments (0)
|
নিয়োগ পাওয়াদের তালিকা [Dowmload List]
২৯তম বিসিএস পরীক্ষায় চূড়ান্তভাবে উত্তীর্ণ ১ হাজার ৪৮০ জনকে নিয়োগ দিয়েছে সরকার।
জনপ্রশাসন মন্ত্রণালয়ের জ্যেষ্ঠ সহকারী সচিব মো. জাকির হোসেন রোববার স্বাক্ষরিত এক প্রজ্ঞাপনে নিয়োগের এ আদেশ দেওয়া হয়। সোমবার তা প্রকাশ হয়েছে।
নিয়োগ পাওয়াদের আগামী ১ অগাস্ট মন্ত্রণালয় নির্দেশিত কার্যালয়ে যোগ দিতে বলা হয়েছে।
এবার সবচেয়ে বেশি নিয়োগ দেওয়া হয়েছে শিক্ষা ক্যাডারে। এ ক্যাডারে নিয়োগ পেয়েছেন ৬৫৩ জন। শিক্ষার পরই রয়েছে কৃষিতে, এ ক্যাডারে ২০৪ জনকে নিয়োগ দেওয়া হয়েছে। স্বাস্থ্যে নিয়োগ পেয়েছেন ১৯৭ জন। প্রশাসন ক্যাডারে নিয়োগ দেওয়া হয়েছে ১৭৭ জনকে। পুলিশে নিয়োগ পেয়েছেন ৩৩ জন।
এছাড়া নীরিক্ষা ও হিসাবে দুই জন, আনসারে ১২ জন, শুল্ক ও আবগারীতে ৬৪ জন, সমবায়ে ছয় জন, খাদ্যে চার জন, পররাষ্ট্রে ১৩ জন, পরিবার পরিকল্পনায় চার জন, তথ্যে ১০ জন, ডাকবিভাগে তিন জন, রেলওয়ে পরিবহন ও বাণিজ্যিকে তিন জন, কর প্রশাসনে ২৫ জন, বাণিজ্যে দুই জন, অর্থনীতিতে ৩২ জন, মৎস্যে ১১, স্বাস্থ্যে ১৯৭, সড়ক ও জনপথে ১৮, রেলওয়ে প্রকৌশলে ছয় জন এবং জনস্বাস্থ্য প্রকৌশলে এক জন নিয়োগ পেয়েছেন।
২০০৯ সালের ৪ অগাস্ট ২৯তম বিসিএসের প্রিলিমিনারি পরীক্ষায় অংশ নিয়েছিলো ১ লাখ ২৩ হাজার ৭৪৫ জন। তার মধ্যে উত্তীর্ণ হয়েছিলো ১৩ হাজার ৫৩৬ জন।
প্রিলিমিনারিতে উত্তীর্ণদের লিখিত ও মৌখিক পরীক্ষার পর চূড়ান্ত উত্তীর্ণের তালিকায় মনোনীত হন ৫০৬২ জন। এদের মধ্যে থেকেই ১ হাজার ৪৮০ জনকে নিয়োগ দেওয়া হলো।
Creating Message in JSON with JavaScript("toJSONString()" )
|
|
comments (0)
|
Creating Message in JSON with JavaScript
In previous section you have studied about the JSONin JavaScript's some basic concepts of creating a simple object and creating anarray of objects. Now we are going to discuss how to create a message with JSONin JavaScript.
In this example of creating message in JSON withJavaScript we have included "json2.js" file first. After thiswe have created an object variable students which contains two array objects .Again we have created an array object and pushed one array data into it. Messageis then created by converting array object to string by using the function "toJSONString()". Here is the example code of CreatingMessage.htm :
CreatingMessage.htm
<html>
<head>
<title>
Creating Message using JSON in JavaScript
</title>
<script language="javascript" src="json2.js"></script>
<script language="javascript" >
var students = { "Maths" : [
{ "Name" : "Amit", // First element
"Marks" : 67,
"age" : 23 },
{
"Name" : "Sandeep", // Second element
"Marks" : 65,
"age" : 21 }
],
"Science" : [
{ "Name" : "Shaili", // First Element
"Marks" : 56,
"age" : 27 },
{ "Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41 }
]
}
// Printing array elements values
var i=0
var arrayObject = new Array();
for(i=0;i<students.Maths.length;i++)
{
arrayObject.push(students.Maths[i].Name);
arrayObject.push(students.Maths[i].Marks);
arrayObject.push(students.Maths[i].age);
}
alert("Welcome to JSON Message Example ");
alert(arrayObject.toJSONString());
</script>
</head>
<body>
Message creation using JSON in JavaScript
</body>
</html>
To run this example you need to include the JavaScriptfile "json2.js" so that the functions defined for convertingobjects to string and parse them can be done. This can be downloaded from http://www.json.org/json2.js
Here is the "json2.js" file code:
/*
json.js
2008-05-25
Public Domain
No warranty expressed or implied. Use at your own risk.
This file has been superceded by http://www.JSON.org/json2.js
See http://www.JSON.org/js.html
This file adds these methods to JavaScript:
array.toJSONString(whitelist)
boolean.toJSONString()
date.toJSONString()
number.toJSONString()
object.toJSONString(whitelist)
string.toJSONString()
These methods produce a JSON text from a JavaScript value.
It must not contain any cyclical references. Illegal values
will be excluded.
The default conversion for dates is to an ISO string. You can
add a toJSONString method to any date object to get a different
representation.
The object and array methods can take an optional whitelist
argument. A whitelist is an array of strings. If it is provided,
keys in objects not found in the whitelist are excluded.
string.parseJSON(filter)
This method parses a JSON text to produce an object or
array. It can throw a SyntaxError exception.
The optional filter parameter is a function which can filter and
transform the results. It receives each of the keys and values, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted.
Example:
// Parse the text. If a key contains the string 'date' then
// convert the value to a date.
myData = text.parseJSON(function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});
This file will break programs with improper for..in loops. See
http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects without a toJSON
method. It can be a function or an array.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the object holding the key.
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array, then it will be used to
select the members to be serialized. It filters the results such
that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
It is expected that these methods will formally become part of the
JavaScript Programming Language in the Fourth Edition of the
ECMAScript standard in 2008.
This is a reference implementation. You are free to copy, modify, or
redistribute.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU
DO NOT CONTROL.
*/
/*jslint evil: true */
/*global JSON */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,
charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
parse, parseJSON, propertyIsEnumerable, prototype, push, replace, slice,
stringify, test, toJSON, toJSONString, toString
*/
if (!this.JSON) {
// Create a JSON object only if one does not already exist. We create the
// object in a closure to avoid global variables.
JSON = function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
Date.prototype.toJSON = function (key) {
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5
\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5
\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapeable.lastIndex = 0;
return escapeable.test(string) ?
'"' + string.replace(escapeable, function (a) {
var c = meta[a];
if (typeof c === 'string') {
return c;
}
return '\\u' + ('0000' +
(+(a.charCodeAt(0))).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// If the object has a dontEnum length property, we'll treat it as an array.
if (typeof value.length === 'number' &&
!(value.propertyIsEnumerable('length'))) {
// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value, rep);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value, rep);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// Return the JSON object containing the stringify and parse methods.
return {
stringify: function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
},
parse: function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' + ('0000' +
(+(a.charCodeAt(0))).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
}
};
}();
}
// Augment the basic prototypes if they have not already been augmented.
// These forms are obsolete. It is recommended that JSON.stringify and
// JSON.parse be used instead.
if (!Object.prototype.toJSONString) {
Object.prototype.toJSONString = function (filter) {
return JSON.stringify(this, filter);
};
Object.prototype.parseJSON = function (filter) {
return JSON.parse(this, filter);
};
} To run this example open the CreateMessage.htm onthe browser and the output on the browser will look like this:
Creating Array Objects in JavaScript with JSON
|
|
comments (0)
|
Creating Array Objects in JavaScript with JSON
In the previous section of JavaScript-JSON tutorial youhave known that how to create an object and now in this tutorial we haveprovided you the way array of objects are declared in JavaScript-JSON.
In our example file we have created an object "students"which contains two array objects "Maths" and "Science"containing name, marks and age of two students. Now we can access theseobjects value in the following way:
"students.Maths" for accessing Mathsarray and "students.Science" for accessing Science arrayobject. Now to access first element of the Maths array we can write it as"students.Maths[1]" and then we can access elements of thisarray as "students.Maths[1].Name" for name and "students.Maths[1].Marks"for marks of the first student in Maths and so on.
Here is the full example code for JavaScript-JSONArray.htmfile.
JavaScript-JSONArray.htm
<html>
<head>
<title>
Array JSON-JavaScript Example
</title>
<script language="javascript" >
var students = { "Maths" : [ {"Name" : "Amit", // First element
"Marks" : 67,
"age" : 23 },
{"Name" : "Sandeep", // Second element
"Marks" : 65,
"age" : 21 }
],
"Science" : [
{"Name" : "Shaili", // First Element
"Marks" : 56,
"age" : 27 },
"Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41 }
]
}
// Printing all array values
var i=0
document.writeln("<table border='1'><tr>");
for(i=0;i<students.Maths.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='0' width=100 >");
document.writeln("<tr><td><B>Name</B></td><td width=50>"
+students.Maths[i].Name+"</td></tr>");
document.writeln("<tr><td><B>Marks</B></td><td width=50>"
+students.Maths[i].Marks +"</td></tr>");
document.writeln("<tr><td><B>Age</B></td><td width=50>"
+students.Maths[i].age +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i=0;i<students.Science.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='0' width=100 >");
document.writeln("<tr><td><B>Name</B></td><td width=50>"
+students.Science[i].Name+"</td></tr>");
document.writeln("<tr><td><B>Marks</B></td><td width=50>"
+students.Science[i].Marks +"</td></tr>");
document.writeln("<tr><td><B>Age</B></td><td width=50>"
+students.Science[i].age +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
Using Array of objects via JSON in JavaScript
</body>
</html>
JSON in JavaScript
|
|
comments (0)
|
JSON stands for JavaScript Object Notation that is a language independent text format which is fast and easy to understand.
JSON in JavaScript
JSON stands for JavaScriptObject Notationthat is a language independent text format which is fast and easy to understand.That means it is really very simple and easy to learn without sparing much time.In another words we can say that JavaScriptObject Notation is a lightweight data-interchangeformat that iscompletely language independent but with some conventions.
So in thissection of JSON tutorial we are going to discuss JSON with JavaScript.
Creating Object in JavaScript using JSON
We can create objects in JSON with JavaScript in manyways :
1. "var JSONObjectName ={};" willcreate an empty object.
2. "var JSONObjectName= new Object();"will create a new Object.
3. "var JSONObjectName = { "name":"amit", "age":23}; will create an Object withattribute name which contains value in String and age with numericvalue.
Now by creating this object we can access attributes byonly "." operator.
Here is the full example code for creating an Object inJavaScript using JSON:
ObjectJavaScript-JSON.htm
<html>
<head>
<title>
Object creation in JSON in JavaScript
</title>
<script language="javascript" >
var JSONObject = { "name" : "Amit",
"address" : "B-123 Bangalow",
"age" : 23,
"phone" : "011-4565763",
"MobileNo" : 0981100092
};
document.write("<h2><font color='blue'>Name</font>::"
+JSONObject.name+"</h2>");
document.write("<h2><font color='blue'>Address</font>::"
+JSONObject.address+"</h2>");
document.write("<h2><font color='blue'>Age</font>::"
+JSONObject.age+"</h2>");
document.write("<h2><font color='blue'>Phone No.</font>::"
+JSONObject.phone+"</h2>");
document.write("<h2><font color='blue'>Mobile No.</font>::"
+JSONObject.MobileNo+"</h2>");
</script>
</head>
<body>
<h3>Example of object creation in JSON in JavaScript</h3>
</body>
</html>
Introduction to JSON
|
|
comments (0)
|
Introduction to JSON Introduction
As we know Ajax is a web development technology that makes the server responses faster by enabling the client-side scripts to retrieve only the required data from the server without retrieving a complete web page on each request, which will minimize the data transferred from the server.
These requests usually retrieve xml formatted response, the xml responses are then parsed in the JavaScript code to render the results. Which complicate the JavaScript code
The idea of JSON (JavaScript Object Notation) is to make the response a specific data structure that can be easily parsed by the JavaScript code.
Advantages
1- lightweight data-interchange format
2- Easy for humans to read and write
3- Easy for machines to parse and generate
4- JSON can be parsed trivially using the eval() procedure in JavaScript
5- JSON Supports: ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.
.
Syntax
The JSON Syntax is the convention which you will use it to generate data, it’s near to the C family language, so it can be parsed easily in the C family languages.
For objects start the object with “{“ and end it with “}”
object
{}
{ members }
· For members (properties), use pairs of string : value and separate them by commas
members
string : value
members , string : value
· For arrays put the arrays between []
array
[]
[ elements ]
· For elements put the values directly separated by commas
elements
value
elements , value
· Values can be string, number, object, array, true, false, null
EXAMPLESJSON
{"menu": {
"id": "file",
"value": "File:",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"} ]
}
}}
XML<menu id="file" value="File" > <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup></menu>
Server side codeThe following code will be generated in the server side to retrieve the server time, and in one step in the client side it will be rendered to JavaScript
Java <%@ page language="java" import="java.util.*" %>
<%Date date = new Date(); %>alert("The server time is: <%Úte%>");
<SPAN style="mso-tab-count: 1" mce_style="mso-tab-count: 1"> ASP.NET<%@ page language="C#" %> alert("The server time is: <%=System.Date.Now.ToString()%>");
PHPalert("The server time is: <?=time()?>");
Client Side JavaScript//XMLHttpRequest completion function
var myOnComplete = function(responseText, responseXML){eval(responseText);}
Introduction to JSON
|
|
comments (0)
|
Introduction
As we know Ajax is a web development technology that makes the server responses faster by enabling the client-side scripts to retrieve only the required data from the server without retrieving a complete web page on each request, which will minimize the data transferred from the server.
These requests usually retrieve xml formatted response, the xml responses are then parsed in the JavaScript code to render the results. Which complicate the JavaScript code
The idea of JSON (JavaScript Object Notation) is to make the response a specific data structure that can be easily parsed by the JavaScript code.
Advantages
1- lightweight data-interchange format
2- Easy for humans to read and write
3- Easy for machines to parse and generate
4- JSON can be parsed trivially using the eval() procedure in JavaScript
5- JSON Supports: ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.
.
Syntax
The JSON Syntax is the convention which you will use it to generate data, it’s near to the C family language, so it can be parsed easily in the C family languages.
For objects start the object with “{“ and end it with “}”
object
{}
{ members }
· For members (properties), use pairs of string : value and separate them by commas
members
string : value
members , string : value
· For arrays put the arrays between []
array
[]
[ elements ]
· For elements put the values directly separated by commas
elements
value
elements , value
· Values can be string, number, object, array, true, false, null
EXAMPLESJSON
{"menu": {
"id": "file",
"value": "File:",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"} ]
}
}}
XML<menu id="file" value="File" > <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup></menu>
Server side codeThe following code will be generated in the server side to retrieve the server time, and in one step in the client side it will be rendered to JavaScript
Java <%@ page language="java" import="java.util.*" %>
<%Date date = new Date(); %>alert("The server time is: <%Úte%>");
<SPAN style="mso-tab-count: 1"> ASP.NET<%@ page language="C#" %> alert("The server time is: <%=System.Date.Now.ToString()%>");
PHPalert("The server time is: <?=time()?>");
Client Side JavaScript//XMLHttpRequest completion function
var myOnComplete = function(responseText, responseXML){eval(responseText);}
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=11
Tutorial on NHibernate and FluentNhibernate
|
|
comments (0)
|
This tutorial will be well-understood with a project , that can be downloaded from here
Background :In the past we all have spent a considerable amount of time writing a data access layer for our application. The overall time spent developing data access code could easily be 30% of the overall time used to implement the solution. There is one problem with this fact. Data access code is nothing special, nothing that adds business value to your application. (Nearly) every business application needs some kind of data access. So why would we continue to spend such a huge amount of time writing boring data access code?
NHibernate can and will take away the burden of our shoulders. Never again you will have to write and maintain stored procedures. Never again you will deal with ADO.NET and the like. When using a modern ORM tool you can concentrate on the core elements of an application, the ones that provide real business value. You can concentrate on the model of the business domain and the business rules there in. But this is enough for now. Let’s start to introduce NHibernate and its sister Fluent NHibernate. To make this introduction a little bit more realistic let’s first find an interesting domain. The domain should be well known to most of you people. What else could be a better fit that an order entry system? At the same time – to not make things too complicated – I have to define a rather simplistic order entry system. So let’s start.
Object Model first approach :One important change to consider when you develop a so called green-field application (a new application) is that you normally start with the object model of the domain for which you want to develop the application. In the past most of the time the data model was developed first. So you started with the entity relationship diagram (ERD). On top of that the application was then built. But in this article we want to first concentrate on the object model and let the database schema be generated automatically by NHibernate based on the object model. Don’t misunderstand me; I am not saying that one cannot use NHibernate to develop applications the other way around. NHibernate is also able to deal with the situation where there already is an existing data model and one has to build an application on top of this.
Mapping the domain model :Once we have our domain model in place we want to be able to store the state (of this model) in some place. Very often this is done by using a relational database management system (RDBMS) like SQL Server, Oracle, IBM DB2 or MySql to name just a few. When you are using NHibernate it doesn’t really matter which database product you’re going to use since NHibernate supports most of the well known database products. Your application will not be tied to a specific database.
NHibernate in a Nutshell :
NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform,it provides an easy way to use framework for mapping an object-oriented domain model to a traditional relational database. NHibernate is a .NET based object persistence library which helps to persist our .NET objects to and from an underlying relational database. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
“If we use an RDBMS to store our data (or state) then the data is stored in tables. Thus we have to map our object model to corresponding tables in the database. This mapping doesn’t necessarily have to be one to one (and most often it is not). That is we do not always have mapping where one object maps to one table. Very often the content of one table maps to different object.”
FluentNHibernate in a Nutshell :
To be formal – “Fluent NHibernate provides a way for you no longer need to write the standard NHibernate mapping file (. Hbm.xml), but you can use the C # mapping file to write. Doing so, facilitate the reconstruction of our code to provide the code readability, and streamlining the project code.”
The greatest advantage of FluentNHibernate is – the mapping is type-safe since it is not based on strings.
In the past the mapping between the object model and the underlying database has been mainly done by defining XML documents.
Fluent NHibernate canceled the xml file.
Why needs to replace the XML file?
a. XML is not real-time compiled. When your XML configuration file has errors, you can see only in the run-time what went wrong.
b. XML is very cumbersome. Indeed, in the NHibernate configuration file, xml node is very simple, but still can not cover up the cumbersome nature of XML file itself.
c. Repeat mapping file attributes set. For example, in xml, we need to set for each string type fields are not allowed to be empty, the length is greater than 1000, int type had to have a default value is -1, the end of the xml configuration file so you will find a lot of repetition work.
one can define the mappings in C# which is a full blown programming language and not only a data description language as XML is. This fact opens the door for many – previously unthinkable – possibilities since the mapping can now contain logic.
Step By Step Approach:
Now we will build a very simple web application which will store, update, read and delete Car data using NHibernate and FluentNhibernate.
Step 1:
From the VS editor we will create a new web application. We will add reference of NHibernate and FluentNhibernate from here……
Step 2:
We will create a new class file by giving a name “Tables.cs”. In this class file we will add all the classes that we planned to map to the Database. At first we will create a very simple class named “Car” with properties (all class should contain property)
public class Core
{
public virtual int Id { get; set; }
}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}
Step 3:
Ok, so now we have to tell NHibernate how to map our entities to the database. We’re going to use the FluentNHibernate interface to do this, so all configuration is in code. We will create another class such as CarMap that inherits ClassMap<Car>. This is what lets FluentNHibernate know to use these mappings with the Car class we’ve just defined. If we look at the configuration, it’s saying what’s the Id field. Handily called Id in this example. NHibernate has the ability to generate auto Ids and there are many options which are beyond our scope here. Lets have look to the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{
public CarMap()
{
LazyLoad();
Id(x => x.Id);
Map(x => x.Title).Not.Nullable().Length(100);
Map(x => x.Description);
Table(“Car”);
}
}
}
With this statement we define the mapping of the property Title which is mandatory and thus cannot be null. We also tell the system that its maximal length is 100 characters. If we do not explicitly define the name of the column in the corresponding table on the database will be the same as the name of the mapped property. In our case this is Title. Of course this can be changed anytime by using the appropriate syntax.
You might wonder what the LazyLoad() means. A Lazy Load interrupts this loading process for the moment, leaving a marker in the object structure so that if the data is needed it can be loaded only when it is used. I recommend you to read this Article1 & Article2 to know more about lazy loading.
LazyLoad() is an optional field.
Step 4:
Now the challenge appears- we need to tell NHibernate how to connect to the database.
At First We have to choose the Database. Here I have used SQLEXPRESS 2008 which is provided with VS 2010. Here I have created a database named ”nhub”. We will access this database through Server Explorer of the VS Editor.
Here is the place where we will apply our business logic and reduce the number and necessity of writing cumbersome stored procedures.
When we impose CRUD on RDBMS through NHibernate, all the operations is held by the NHibernate Session (Nhibernate session is different from ASP.NET session and they are totally different). It may be easier to think of a session as a cache or collection of loaded objects relating to a single unit of work. NHibernate can detect changes to the objects in this unit of work..To handle these sessions we will use some interfaces that comes form NHibernate.These interfaces are the main point of dependency of application business/control logic on NHibernate.
Five basic Interfaces used as shown in the figure below; where IQuery and ICriteria performs the same operation.
ISession interface
1. The ISession interface is the primary interface used by NHibernate applications, it exposes NHibernates methods for finding, saving, updating and deleting objects.
2. An instance of ISession is lightweight and is inexpensive to create and destroy. This is important because your application will need to create and destroy sessions all the time, perhaps on every ASP.NET page request. NHibernate sessions are not thread safe and should by design be used by only one thread at a time. The NHibernate notion of a session is something between connection and transaction.
3. We sometimes call the ISession a persistence manager because it’s also the interface for persistence-related operations such as storing and retrieving objects. Note that a NHibernate session has nothing to do with an ASP.NET session.
ISessionFactory interface
1. The application obtains ISession instances from an ISessionFactory. Compared to the ISession interface, this object is much less exciting.
2. The ISessionFactory is certainly not lightweight! It’s intended to be shared among many application threads. There is typically a single instance of ISessionFactory for the whole application-created during application initialization, for example. However, if your application accesses multiple databases using NHibernate, you’ll need a SessionFactory for each database.
3. The SessionFactory caches generated SQL statements and other mapping metadata that NHibernate uses at runtime.
4. It can also hold cached data that has been read in one unit of work, and which may be reused in a future unit of work or session. This is possible if you configure class and collection mappings to use the second-level cache.
ITranscation interface
1. The ITransaction interface, next to the ISession interface. The ITransaction interface is an optional API. NHibernate applications may choose not to use this interface, instead managing transactions in their own infrastructure code.
2. A NHibernate ITransaction abstracts application code from the underlying transaction implementation-which might be an ADO.NET transaction or any kind of manual transaction-allowing the application to control transaction boundaries via a consistent API. This helps to keep NHibernate applications portable between different kinds of execution environments and containers.
IQuery and ICriteria interfaces
1. The IQuery interface gives you powerful ways of performing queries against the database, whilst also controlling how the query is executed.
2. It is the basic interface used for fetching data using NHibernate. Queries are written in HQL or in the native SQL dialect of your database. An IQuery instance is lightweight and can’t be used outside the ISession that created it. It is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
3. The ICriteria interface is very similar; it allows you to create and execute object-oriented criteria queries.
Now, I will discuss some points from my written code for configuring the FluentNibernate . We have create a class called ModelClass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
namespace ModelClass
{
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
InitializeSessionFactory();
return _sessionFactory;
}
}
private static void InitializeSessionFactory()
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(
@”Server=fire-3\sqlexpress;Database=nhub;Trusted_Connection=True;”)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<Car>())
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(true, true))
.BuildSessionFactory();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
There’s quite a bit going on here. .Database(MsSqlConfiguration.MsSql2008 is where we tell NHibernate to use the SQL Server driver, there are numerous others, including MySql and SQLLite which are the popular one’s I’m aware of. The .ConnectionString is obvious we’re connecting to the database we defined above.
The next bit is optional .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true,true)) tells NHibernate to actually create the tables in the database if they’re not there. We don’t really want to leave this on otherwise eachtime we run our app it’ll drop the tables with all our Cars in them and recreate them. the Create(true,true) also refers to whether to show the SQL generated to drop the tables, which we’ve turned on so we can see it work its magic.
Finally we BuildSessionFactory() which will build the session factory and we assign it to a static variable so as to only use one Session for the lifetime of our application
Step 5:
All configuration is completed so far, now we will create a very simple webpage that prompt a user to create a table name “Car” for the first time if the table does not exist and then insert data into “Car” table.
We create a page just like below
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Add Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:TextBox ID=”txtTitle” runat=”server”></asp:TextBox>
</td>
<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
<asp:Label ID=”lblsatat” runat=”server” Text=”" ForeColor=”#FF5050″></asp:Label>
</asp:Content>
Step 6:
Now in the “ModelClass.cs” we will add this piece of code to add Car to the “Car” table.
public static void Add<T>(T entity)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
We will add an event in the Page Class which will fire when the Save button is clicked
protected void btnSave_Click(object sender, EventArgs e)
{
Create(txtTitle.Text.ToString(), txtDesc.Text.ToString());
}
}
Notice we’re using the Session we just new up a Car class simply give it a name and then session.Save(entity) but note that it doesn’t actually get added to the database until you Commit the Transaction.
There’s a simple order here:
Open SessionBegin TransactionDo SomethingCommit the TransactionClose the transactionClose the SessionNow because we have a using statement we’re automatically calling Dispose on the Transaction and the session. The session.save(entity) figures out the appropriate SQL to generate for us.
Step 7:
This time we will recreate the “Car” class and create another class “Manufacturer”. We will assume that A Car has a Manufacturer and it is a One to Many relation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Linq;
namespace NHibernateTutorial
{
public class Core
{
public virtual int Id { get; set; }
}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual Manufaturer ManuFacturedBy { get; set; }
}
public class Manufaturer : Core
{
public virtual string Name { get; set; }
}
}
Step 9:
We have to Map the classes again like below -
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Id(x => x.Id);
Map(x => x.Title).Not.Nullable().Length(100);
Map(x => x.Description);
References(x => x.ManuFacturedBy).Column(“ManufacturerID”).Not.LazyLoad();
Table(“Car”);
}
}
public class ManufaturerMap : ClassMap<Manufaturer>
{
public ManufaturerMap()
{
Id(x => x.Id);
Map(x => x.Name);
Table(“Manufacturer”);
}
}
}
Step 10:
We will write the following code to save data now-
public void Create(string carTitle, string carDesc)
{
Car cr = new Car();
cr.Title = carTitle;
cr.Description = carDesc;
cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() };
ModelCode.Add<Manufaturer>(cr.ManuFacturedBy);
ModelCode.Add<Car>(cr);
}
Here, “cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() }” is initaing the “Car” object with “Manufacturer” object. While saving data we have to save the manufacturere object first then Car object.
Step 11:
Now we will retrieve data from the database. to show the data we first add a GridView named “gdvShowCar” to a newly created Webform “ShowCar.aspx”.
Now we will add a method named “Get” in out ModelCode class.
public static IList<T> Get<T>()
{
IList<T> centers;
using (ISession session = OpenSession())
{
centers = session.CreateCriteria(typeof(T))
.List<T>();
}
return centers;
}
This method will return a list to us. the CreateCriteria() take a class which will be queried as a parameter and return an ICriteria Object.
Now in “ShowCar.aspx.cs” we will write -
public partial class ShowCar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
}
public void LoadData()
{
IList<Car> Icar = ModelCode.Get<Car>();
var cars = from car in Icar select new { car.Title, car.Description };
gdvShowCar.DataSource = cars;
gdvShowCar.DataBind();
}
}
This code will fill the griedview with data.
Step 12:
Now we will update data . we will first create a page named ”UpdateCar”. there we will create a drop down list of Car’s name. We will select a name from the list and update data according to this particular Car name.
<%@ Page Title=”" Language=”C#” MasterPageFile=”~/Site.Master” AutoEventWireup=”true” CodeBehind=”UpdateCar.aspx.cs” Inherits=”NHibernateTutorial.UpdateCar” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” runat=”server”>
</asp:Content>
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Update Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:DropDownList ID=”ddlCarTitle” runat=”server” AutoPostBack=”True”></asp:DropDownList>
</td>
<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Manufacturer Name:
</td>
<td>
<asp:TextBox ID=”txtMan” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
</asp:Content>
we did not bind data to the dropdownlist yet. To do that we will simply call the “Get” method fromModelCode class.
we can write -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
initData();
}
}
public void initData()
{
IList<Car> cars = ModelCode.Get<Car>();
ddlCarTitle.DataSource = cars.ToList();
ddlCarTitle.DataTextField = “Title”;
ddlCarTitle.DataValueField = “Id”;
ddlCarTitle.DataBind();
}
The DropDownList is filled with data now. Next, we have to Load our text boxes with appropriate data. For this we will create an overloaded method of “Get” inside the “DataModel” class. this method may looks like below -
public static IList<T> Get<T>(string property, object value)
{
IList<T> centers;
using (ISession session = OpenEngineSession())
{
centers = session.CreateCriteria(typeof(T))
.Add(Restrictions.Eq(property, Convert.ToInt32(value)))
.List<T>();
}
return centers;
}
the eq() searches a match for the (property,value) pair and return a List. It works like traditional WHERE clause with a SELECT statement.
Now we will create an method in the page class named “LoadCarInfo” this method will load data on form when the DropDownList of Name is being populated.
public void LoadCarInfo()
{
var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString());
if (inv.Count > 0)
{
txtDesc.Text = inv[0].Description;
txtMan.Text = inv[0].ManuFacturedBy.Name;
}
}
Now , time to UpDate data. This very similar to “Add” in the ModelCode class.
We will add another method to “ModelCode”. It is very easy and understandable.
public static void Update<T>(T entity)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
So now we can call this “Update” from our Page Class as before-
protected void btnSave_Click(object sender, EventArgs e)
{
var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString())[0];
inv.Description = txtDesc.Text;
inv.ManuFacturedBy.Name = txtMan.Text;
ModelCode.Update<Manufaturer>(inv.ManuFacturedBy);
ModelCode.Update<Car>(inv);
}
Step 13:
Now we will Delete data. We will add another method in “ModelCode”.
public static void Remove<T>(T entity)
{
using (ISession session = OpenEngineSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
Conclusion:
Here I have tried to given some basic CRUD operation using NHibernate and FluentNHibernate. Many thing is left and overlooked intentionally because the limitation of my scope. Actually It takes time to be expert and skilled with these technology.
DownLoad FullCode.
৩০তম বিসিএস লিখিত পরীক্ষার ফল প্রকাশ
|
|
comments (1)
|
ঢাকা : ৩০তম বিসিএস লিখিত পরীক্ষার ফল প্রকাশ করা হয়েছে। বৃহস্পতিবার বিকেলে এই ফল প্রকাশ করা হয়।
সাধারণ ক্যাডারে উত্তীর্ণ হয়েছেন ৪ হাজার ১৯ জন, জেনারেল ও কারিগরি ক্যাডারে ৩ হাজার ৬৩১ জন এবং শুধু কারিগরি ক্যাডারে ১ হাজার ৪০০ জন।
৩০তম বিসিএসের মাধ্যমে ২ হাজার ৫৭২ জনকে নিয়োগের সুপারিশ করবে পিএসসি। এদের মধ্যে সাধারণ ক্যাডারে ৮৩১ জন এবং কারিগরি ক্যাডারে ১ হাজার ৭৪১ জন।
পাবলিক সার্ভিস কমিশনের (পিএসসি) পরীক্ষা নিয়ন্ত্রক (ক্যাডার) আ ই ম নেছার উদ্দিন বাংলানিউজকে এ তথ্য জানান।আগামী ২০ জুন থেকে উত্তীর্ণদের মৌখিক পরীক্ষা গ্রহণ শুরু করবে পিএসসি। মৌখিক পরীক্ষার সময়সূচি পরে জানানো হবে।
এবার প্রার্থীদের ২০০ নম্বরের মৌখিক পরীক্ষা নেওয়া হবে। এর আগে ১০০ নম্বরের মৌখিক পরীক্ষা হয়।জানুয়ারি মাসে এ লিখিত পরীক্ষা অনুষ্ঠিত হয়। এর আগে গত বছরের ৩০ জুলাই প্রিলিমিনারি পরীক্ষা অনুষ্ঠিত হয়।
তথ্যবিভ্রাট ও প্রশাসনিক কারণে ৩৪ জন প্রার্থীর ফল প্রকাশ স্থগিত রেখেছে পিএসসি।
স্থগিত থাকা প্রার্থীদের রেজিস্ট্রেশন নম্বর- ০০৩৩৬২, ০৩০২৮৬, ০৩১৭৭০, ০৩২১০৪, ০৩২১৩৩, ০৩২১৩৫, ০৩৩২৩৪, ০৪১৬৩০, ০৪৮৮০৯, ০৫৪০৫৭, ০৭০৭৩১, ০৭৫২১৪, ০৭৮১৮০, ০৭৮২২০, ০৭৮২২২, ০৭৮৪৫৩, ০৭৮৬৮১, ০৮১৪৫৭, ০৮৬০৯৩, ০৮৮৯০৭, ০৮৯৬৭৬, ০৮৯৬৭৮, ০৯৯০২০, ০৯৯৫৪৬, ০৯৯৬২০, ১০০০১৫, ১০০৪১৯, ১০০৪২১, ১০১৯১৯, ২০৫৩৮০, ২১১৬১০, ৩১০০৫২, ৩১২৯৬৮ ও ৪০০৩৭১।
এ ফলাফলকে সাময়িক ফল উল্লেখ করে পিএসসি জানায়, ‘কোনও ক্ষেত্রে চাহিদাকৃত কাগজপত্রাদির ঘাটতি থাকিলে বা পরবর্তীকালে কোনও সময় কোনও প্রার্থীর যোগ্যতার ঘাটতি ধরা পড়িলে, দুর্নীতি, অসত্য তথ্য প্রদান বা আবেদনপত্রে গুরুতর ত্রুটি বা ঘাটতি দেখা গেলে বা প্রদত্ত তথ্য মিথ্যা হইলে মৌখিক পরীক্ষার পূর্বে বা পরে যে কোনও পর্যায়ে উক্ত প্রার্থীর প্রার্থিতা বাতিল হইবে।’