Sunday, December 13, 2009

3. Architecture

.Net 3.0 runtime
Contains the core pillars (WPF, WWF etc) and runtime components. If we wish only to run any .net 3.0 application, installing .net 3.0 runtime is enough.

While the .NET Framework 2.0 class library is partially superseded by the new components (WF, WCF, and WPF) added in version 3.0, many portions of the original class library are still crucial to developers. The technologies of version 2.0 (ASP.NET, WinForms, ADO.NET, XML etc.) largely remain the elementary part of the new release; however, .NET framework 3.0 developers may now prefer using WPF over Windows Forms for writing a native Windows GUI.



Windows Workflow Foundation (WF)
WF broadly comprises of the following assorted components:

Activity: A unit of work ranging from very simple to quite complex.
Workflow: A group of activities that partially or completely implements a business process.
WF Designers: The graphical tools to create and modify workflows and activities.
WF Base Activity Library: A fundamental group of activities (IfElse, While, Listen etc. design constructs) used to create workflows. These are quite similar to the BizTalk Orchestration shapes.
WF Runtime Engine: A library that executes workflows. It also provides other services, such as communicating with software outside the workflow.
Host process: A Windows application that hosts the Windows Workflow Foundation runtime engine, workflows, and runtime services for persisting a workflow's state, handling transactions, etc.

WF provides the Workflow Designer, a Visual Studio-hosted graphical tool for creating workflows. The activities in a workflow can be drawn using the Base Activity Library (BAL) provided with WF.

Windows Communication Foundation (WCF)
However applications are built (using workflow or otherwise), most of them need to communicate with each other. This inter-application communication has taken a big leap forward in the last few years. After a perpetual era of disagreement, all of the major vendors agreed to support SOAP based Web services which makes interoperability between applications built on different technology platforms, such as J2EE and the .NET Framework, significantly simpler. So, this also makes the idea of service-oriented architecture much more plausible for most organizations.

A lot of communication approaches exist in the .NET Framework 2.0 such as ASP.NET Web Services, .NET Remoting, System.Messaging supporting queued messaging through MSMQ, Web Services Enhancements (WSE) - an extension to ASP.NET Web Services that supports WS-Security etc. However, instead of requiring developers to use a different technology with a different application programming interface for each kind of communication, WCF provides a common approach and API. "WCF is actually an old wine in new bottle", and was previously called as Indigo. In the .NET Framework 3.0 environment, most applications that might have used one of the communication technologies listed above will instead use WCF.

WCF provides strong support for interoperable communication through SOAP. This includes support for several specifications, including WS-Security, WS-ReliableMessaging, and WS-AtomicTransaction. WCF doesn't itself require SOAP, so other approaches can also be used, including optimized binary protocol and queued messaging using MSMQ. WCF also takes an explicit service-oriented approach to communication, and loosens some of the tight couplings that can exist in distributed object systems, making interaction less error-prone and easier to change. Thus, WCF addresses a range of communication problems for applications. Three of its most important aspects that clearly stand out are:

Unification of Microsoft�s communication technologies.
Support for cross-vendor interoperability, including reliability, security, and transactions.
Rich support for service orientation development.
To sum up, communication between applications, whether within an organization or across, is a fundamental part of any modern software. The .NET Framework 3.0 attempts to address enduring communication challenges by using the service-oriented approach of WCF.

Windows CardSpace (WCS) Digital identities are the way how people electronically represent themselves today on the Internet. In the majority of cases, a person's digital identity is expressed as a simple username, and when its combined with a password, it is used to access web sites, email servers, e-merchants, online banks etc. Yet, despite their simplicity and popularity, usernames and passwords haunt people. Many of us have a hard time remembering all of the usernames and passwords of different sites. Thus, some people use the same values for different sites, easing the memory problem but increasing the security risk.

Usernames, passwords, and other personal information can be stolen by phishers. By sending delusory emails, phishers entice their victims to log in to their Web site that looks just like, say, the site of the victim's bank. So once the victim enters his username and password, the phisher can use this information to masquerade as the user on the real site.

Reducing occurrences and severity of these problems requires an entirely new approach to managing digital identities. WCS (originally called InfoCard) provides this. It helps people keep track of their digital identities as distinct information cards. If a Web site accepts WCS logins, users attempting to log in to that site will see a WCS selection. By choosing a card, users also choose a digital identity that will be used to access this site. Rather than remembering a plethora of usernames and passwords, users need only recognize the card they wish to use.

The identities represented by these cards are created by one or more identity providers. These identities will typically use stronger cryptographic mechanisms to allow users to prove their identity. WCS itself also includes a self-issued identity provider that runs on client machines. With this provider, users can create their own identities that don't rely on passwords for authentication.

So if passwords aren't used to log in to a site, phishers can inflict no harm either. Well, not really! Phishers, if somehow, can trick a user to log into a bogus site, might be still able to acquire personal information of the user, such as sensitive medical information etc. Preventing this requires that users be able to distinguish real sites from the look-alike fakes created by phishers. To allow this, the organization that owns a Web site can get a high-assurance certificate. Unlike today's simple SSL certificates, acquiring this new kind of certificate involves a much more rigorous process, including stronger proof that the organization applying for it actually is who it claims to be. A high-assurance certificate can also carry a company's logo and other information to help the user correctly determine whether a site using this certificate is legitimate. When a user accesses a new site, WCS always displays the information in that site's certificate using a standard screen. Based on the strength of the certificate received, this screen will indicate different levels of assurance of the site's identity.

Windows Presentation Foundation (WPF)

User interfaces are an important part of most Windows applications. No matter how much software evolves, traditional menu-driven GUIs are here to stay for some more time. Similarly, the need to display video, run animations, use 2/3D graphics, and work with different document formats also cannot be superseded. And all of this must be possible whether the application is a stand-alone desktop client or is accessed through a Web browser.

So far, all of these aspects of the user interface have been provided in different ways on Windows. For example, a developer needs to use Windows Forms to build a Windows GUI, or HTML/ASPX/Applets/JavaScript etc. to build a web interface, Windows Media Player or software such as Adobe's Flash Player for displaying video etc. The challenge for developers is certainly clear: building a coherent user interface for different kinds of clients using diverse technologies isn't a simple job.

A primary goal of WPF (originally called Avalon) is to address this challenge! By offering a consistent platform for these entire user interface aspects, WPF makes life simpler for developers. By taking a more modern approach, including support for video, animation, 2/3D graphics, and various kinds of documents, WPF can let users work with information in new ways. And by providing a common foundation for desktop clients and browser clients, WPF makes it easier to build applications that address both.

Another challenge that has long faced the creators of user interfaces stems from the different roles required for building effective interfaces. Software developers are needed to create the logic behind the interface, and Designers are required to define the interface's look and feel. Yet older technologies such as Windows Forms are focused entirely on the developer. There's no truly effective way for developers and designers to collaborate. To address this issue, WPF relies on the eXtensible Application Markup Language (XAML). An XML-based language, XAML allows specifying a user interface declaratively rather than in code. This makes it much easier for user interface design tools like MS Expression Blend (originally branded as MS Expression Interactive Designer and code named as Sparkle) to generate and work with an interface specification based on the visual representation created by a designer. Designers will be able to use such tools to create the look of an interface and then have a XAML definition of that interface generated for them. The developer imports this definition into Visual Studio, then creates the logic the interface requires.

Developers can also build a XAML browser application (XBAP) to create a remote client that runs inside a Web browser. Built on the same foundation as a stand-alone WPF application, an XBAP allows presenting the same style of user interface within a downloadable browser application. The best part is that the same code can potentially be used for both kinds of applications, which means that developers no longer need different skill sets for desktop and browser clients. The downloaded XBAP from the Internet runs in a secure sandbox (like Java applets), and thus it limits what the downloaded application can do.

Burp, GUI is a complex but an important part of the modern applications. Through WPF, the .NET Framework 3.0 presents a more complete and consistent solution to the challenges these interfaces present. The goal is to let people who create user interfaces (both developers and designers) effectively collaborate and do their jobs more expeditiously. So beware, because when your boss hears all this, she/he will certainly start expecting more from you.. : ( But I guess, that is the flip side of adopting any new technology.

Cocktails
�As an ideal meal cannot conclude without cocktails, so cannot a technology review without addressing criticism�.

Of late, I have came across some criticism of .NET 3.0 release and its branding on grounds that the new release doesn't accommodate .Net 2.0 bugs or language enhancements (like LINQ). It is also said that it does not add up anything substantial (other than WinFx lib) and that there shall be no performance gains too. Some even envisage the .Net 3.0 release as an improvised marketing ploy to hype up the forthcoming Vista release.

On the contrary, the re-branding from WinFx to .NET Framework and regrouping of the various technologies, "now", under a unified .NET Framework 3.0 banner, is a far better measure than it can be any later. This will not only avert another round of marketing confusion in future but also prevent the ever expanding branding namespace from getting further convoluted. After all, haven't we long forgotten the Longhorn for Vista (even though there was so much of brick-batting initially over it)? Plausibly, forgetting demands lesser efforts or time than remembering does.

The fact that .Net framework 3.0 is not introducing anything sour at this stage that will require redesigning or recoding the existing applications, is ostensibly welcome. It, otherwise, could have stirred the development community and their trust. Now that our lives are simplified (or at least are less complicated); bug fixes and fancy enhancements can shortly arrive (as patches/SPs). Similarly, major performance gains can be targeted with every new CPU/architecture release.

The aforesaid concerns and the resultant inertia, to a certain extent, were predictable at the time of announcement of the .Net release 3.0!! So, the ensuing confusion is obvious and is owing to the fact that from the very first release, till thus far; the .Net Framework has primarily grown vertically upwards and its now (with the new 3.0 release) attempting to expand horizontally outwards. This, however, indicates the overall maturity of the platform and is by far a healthy sign. So, instead of remaining dubious anymore, lets wisely step forward to accept the new version as an "additive" release (or more simply put the "production" release of WPF, WCF, WF, and WCS technologies), which is veritably colossal enough to be understated.

Saturday, December 12, 2009

Basic Query

SQL SELECT statement has the widest variety of query options, which are used to control the way data is returned.

ORDER BY—A clause that returns the result set in a sorted order based on specified columns.
example:
SELECT * FROM Contacts ORDER BY first_name;
You are free to use ORDER BY with any select statement that might return multiple rows. You can also use it in conjunction with other clauses:

SELECT first_name, last_name FROM Contacts WHERE first_name BETWEEN ‘a’ AND ‘k’ ORDER BY last_name;

When you use DISTINCT, it applies to all requested columns. If you want a list of all the salespeople in your table and the companies they represent but not every sales entry, you can use the following statement. Note that this may return several entries from the same company, etc. DISTINCT applies to the entire requested result set.

DISTINCT—A keyword that returns only unique rows within a result set

SELECT DISTINCT company, last_name, first_name FROM Sales;

COUNT—A function that returns a numeric value which equals the number of rows matching your query

The COUNT function tells you how many rows are in a result set. As with all functions, it accepts one parameter. This basic example will tell you how many rows are in your table:
SELECT COUNT(*) FROM Sales;

You can also use it to count the number of rows in any result set.
SELECT COUNT(*) FROM Sales WHERE net_amount > 100;

AVG—A function that returns the numeric value that equals the average of the numbers in a specified column

AVG returns the average of all the fields in a column with a numeric data type. It accepts one column name as its parameter, and it will return “0” if it's used on a non-numeric column.

SELECT AVG(net_amount) FROM Sales;
SELECT AVG(net_amount) FROM Sales WHERE company LIKE ‘%ABCD Co%’;

SUM—A function that adds the numbers in a specified column
SUM works just like AVG, except it returns the sum of values in all fields in the result set.
SELECT SUM(net_amount) FROM Sales WHERE net_amount > 100;

MIN—A function that returns the lowest non-null value in a column
MIN returns the lowest, non-null value in the specified column. If the column is a numeric data type, the result will be the lowest number. If it's a string data type, it will return the value that comes first alphabetically.
SELECT MIN(net_amount) FROM Sales WHERE last_name = “Smith”;
SELECT MIN(last_name) FROM Sales;

MAX—A function that returns the largest value in a column
MAX works just like MIN, only it returns the highest non-null value. It too can be used on strings or numbers.
SELECT MAX(net_amount) FROM Sales;
SELECT MAX(company) FROM Sales WHERE net_amount > 100;
The MAX function is sometimes used on columns containing an auto-incremented key field to determine what the next entry’s key ID will be. Unless you’re running a nonpublic database, be wary of using this information to insert the next entry, in case another user beats you to the punch.

GROUP BY— Group by keyword is used to give records in same column rows in grouped manner. Group by can be used on one column name and more than one column name in SQL query

Example using the SUM function
For example, you could also use the SUM function to return the name of the department and the total sales (in the associated department). The HAVING clause will filter the results so that only departments with sales greater than $1000 will be returned.

SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;
Example using the COUNT function

For example, you could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year. The HAVING clause will filter the results so that only departments with more than 10 employees will be returned.

SELECT department, COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department
HAVING COUNT(*) > 10;

Example using the MIN function
For example, you could also use the MIN function to return the name of each department and the minimum salary in the department. The HAVING clause will return only those departments where the starting salary is $35,000.

SELECT department, MIN(salary) as "Lowest salary"
FROM employees
GROUP BY department
HAVING MIN(salary) = 35000;

Example using the MAX function
For example, you could also use the MAX function to return the name of each department and the maximum salary in the department. The HAVING clause will return only those departments whose maximum salary is less than $50,000.

SELECT department, MAX(salary) as "Highest salary"
FROM employees
GROUP BY department
HAVING MAX(salary) < 50000;
Joins
A join in SQL is a clause that allows` merging of records from one or more than one tables in database. The records from the tables are fetched based on some values that are common to each.

SELECT * from Employees e JOIN Salary s ON e.employeeid=s.employeeid;
Inner JoinTwo tables getting join result set display which is matched records only
Explicit type
SELECT *from shooters s INNER JOIN guntypes g ON s.guntype = g.guntype ;
Implicit type
SELECT *from shooters s , guntypes g WHERE s.guntype = g.guntype ;
Cross join
Is also called Cartesian join. Result of joining each row of the table with each row of the other table
Left outer join - unmatched left table records and matched right table records.
SELECT *from shooters s LEFT OUTER JOIN guntypes g ON s.guntype = g.guntype ;
Right outer join – unmatched right table and matched left table
SELECT *from shooters s RIGHT OUTER JOIN guntypes g ON s.guntype = g.guntype ;
Full outer join merged the result fetched from left and right
SELECT *from shooters s FULL OUTER JOIN guntypes g ON s.guntype = g.guntype ;

It is a simple sql join condition which uses the equal sign as the comparison operator.
Equi joins are SQL Outer join and SQL Inner join.
SQL Non Equi Join:
A Non Equi Join is a SQL Join whose condition is established using all comparison operators except the equal (=) operator. Like >=, <=, <, >
SELECT first_name, last_name, subject
FROM student_details
WHERE subject != 'Maths

Friday, December 11, 2009

Keys, Cosntraints, index

A constraint is a property assigned to a column or the set of columns in a table that prevents certain types of inconsistent data values from being placed in the column(s). Constraints are used to enforce the data integrity. This ensures the accuracy and reliability of the data in the database. The following categories of the data integrity exist
Entity Integrity ensures that there are no duplicate rows in a table.
Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of possible values.
Referential integrity ensures that rows cannot be deleted, which are used by other records (for example, corresponding data values between tables will be vital).
User-Defined Integrity enforces some specific business rules that do not fall into entity, domain, or referential integrity categories.

A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity

CREATE TABLE employee(
EmployeeId INT NOT NULL CONSTRAINT pk_employee PRIMARY KEY (EmployeeId)
,
LName VARCHAR(30) NOT NULL,
FName VARCHAR(30) NOT NULL,
Address VARCHAR(100) NOT NULL,
HireDate DATETIME NOT NULL,
Salary MONEY NOT NULL CONSTRAINT check_sale CHECK (salary > 0)
)
Constraints Enhancements

When you attempt to update or delete a key to which existing foreign keys point. You can control it by using the new ON DELETE and ON UPDATE clauses in the REFERENCES clause of the CREATE TABLE and ALTER TABLE statements. For example, in the previous versions of SQL Server if you wanted to do a cascade delete from the referenced table when the appropriate record in the parent table is deleted, you had to create a trigger which executed on delete of the parent table, but now you can simply specify the ON DELETE clause in the REFERENCES clause.
CREATE TABLE Books (
BookID INT NOT NULL PRIMARY KEY,
AuthorID INT NOT NULL,
BookName VARCHAR(100) NOT NULL,
Price MONEY NOT NULL
)
GO

CREATE TABLE Authors (
AuthorID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100) NOT NULL
)
GO

ALTER TABLE Books
ADD CONSTRAINT fk_author
FOREIGN KEY (AuthorID)
REFERENCES Authors (AuthorID) ON DELETE CASCADE
GO

Constraints are the built-in mechanism for enforcing data integrity. Using constraints is preferred to using triggers, rules, and defaults because built-in integrity features use much less overhead and perform faster than the ones you can create. When you write your own code to realize the same actions the constraints can make you can make some errors, so the constraints are not only faster, but also are more consistent and reliable. So, you should use triggers and rules only when the constraints do not provide all the needed functionality.

Candidate Key - A Candidate Key can be any column or a combination of columns that can qualify as unique key in database. There can be multiple Candidate Keys in one table. Each Candidate Key can qualify as Primary Key.
Primary Key - A Primary Key is a column or a combination of columns that uniquely identify a record. Only one Candidate Key can be Primary Key.



Select a key that does not contain NULL
It may be possible that there are Candidate Keys that presently do not contain value (not null) but technically they can contain null. In this case, they will not qualify for Primary Key. In the following table structure, we can see that even though column [name] does not have any NULL value it does not qualify as it has the potential to contain NULL value in future
A table can have multiple Candidate Keys that are unique as single column or combined multiple columns to the table. They are all candidates for Primary Key. Candidate keys that follow all the three rules - 1) Not Null, 2) Unique Value in Table and 3) Static - are the best candidates for Primary Key. If there are multiple candidate keys that are satisfying the criteria for Primary Key

When you use the multiple-column constraint format, you can create a composite key. A composite key specifies multiple columns for a primary-key or foreign-key constraint.
The next example creates two tables. The first table has a composite key that acts as a primary key, and the second table has a composite key that acts as a foreign key.
CREATE TABLE accounts (
acc_num INTEGER,
acc_type INTEGER,
acc_descr CHAR(20),
PRIMARY KEY (acc_num, acc_type))

CREATE TABLE sub_accounts (
sub_acc INTEGER PRIMARY KEY,
ref_num INTEGER NOT NULL,
ref_type INTEGER NOT NULL,
sub_descr CHAR(20),
FOREIGN KEY (ref_num, ref_type) REFERENCES accounts
(acc_num, acc_type))
Cluster index & Non cluster index
Primary_Key column is a monotonically increasing integer and that the last three columns are VARCHAR columns. Let's also assume that there is a clustered index on the Primary_Key column, and that there are no nonclustered indexes on the table.

Now, let's assume we run the following query:

SELECT Customer_No, Customer_Name, Customer_Address
FROM Table_Name
WHERE Primary_Key = 1001

When the query optimizer analyzes this query, it will know that the Primary_Key column is the key to a clustered index. So the clustered index will (most likely) be used to locate the Primary_Key of 1001 very quickly using a clustered index lookup. In addition, since the other three columns are part of the clustered index, the values for these three columns are immediately available and can be immediately displayed after the query finishes executing. Keep in mind that all the columns in a clustered index are stored at the leaf level of the clustered index, so SQL Server, in this example, does not have to look elsewhere to find the data to be returned.

Non cluster
Now, let's take a look at the following query:

SELECT Customer_No, Customer_Name, Customer_Address
FROM Table_Name
WHERE Customer_No = 'ABC123'

In this case, when this query is analyzed by the query optimizer, there is no index on the column Customer_No. Because of this, SQL Server will perform a clustered index scan to look for the designated record to return. Since this column is not indexed or unique, every row in the table will have to be scanned until the record is found. Once it is found, the rest of the record (because it is a clustered index and each row's data is part of the leaf index), is immediately available and the data is returned.

If we need to perform the above query often, it would be to our advantage to add a nonclustered index to the Customer_No column. This way, when we run a query like the one above, instead of performing a time-consuming clustered index scan, it can use the nonclustered index on Customer_No to perform an index lookup, which is much faster than a clustered table scan. But is this all we need to do to optimize the above query? Actually, we have forgotten something. If we run the query, let's look at it again below, something else has to happen before our data is returned.

SELECT Customer_No, Customer_Name, Customer_Address
FROM Table_Name
WHERE Customer_No = 'ABC123'

When this query runs, it will use the nonclustered index on the Customer_No column to quickly identify the record using an index lookup. But unlike a clustered index, a nonclustered index only contains the data stored in the index, which is, in this case, only the Customer_No column. On the other hand, our query wants to return three columns: Customer_No, Customer_Name, and Customer_Address, not just key Customer_No. Because of this, SQL Server will now have to perform another step before it can return our data. Once it has located the correct row in the nonclustered index, then SQL Server must then look up the values of the other two columns from the clustered index, where this data is stored
Covering indexes, if used judiciously, can be used to speed up many types of commonly run queries. But covering indexes have some limitations. For example, they are limited to a maximum of 16 columns; they have a 900-character maximum width; certain datatypes cannot be included in them; and adding additional columns to an index makes the index wider, which in turn requires more disk I/O to read and write the rows, potentially hurting performance, especially if the table is subject to many INSERTs, UPDATEs, and DELETEs.

"nonkey column nonclustered indexes." This new feature is a variation of the standard covering index we have been talking about up to this point, but with some advantages over covering indexes.

Let's go back to our example query.

SELECT Customer_No, Customer_Name, Customer_Address
FROM Table_Name
WHERE Customer_No = 'ABC123'

Let's assume, as before, that there is a clustered index on Primary_Key. Now, instead of creating a covering index as described above, what we can do is create a nonclustered index on Customer_No, but instead of adding Customer_Name and Customer_Address as additional key columns to the index, we instead add Customer_Name and Customer_Address as nonkey columns to the nonclustered index.

nonkey column nonclustered index over using a covering index. The benefits include:

All data types are supported, except text, ntext, and image. So you have more datatype options than a covering index.
The maximum number of columns is 1,023, not 16 as with covering indexes.
Because the actual index is narrower, the key is more efficient and can offer better performance over a covering index where all of the columns are part of the key.
Yes, these are small differences, but lots of small differences add up and can help boost the performance of your SQL Server. In fact, you may want to review all of your currently existing covering indexes and change them to nonkey column nonclustered indexes to see if your query performance increases. Depending on the circumstances, performance could indeed increase.

Nonkey columns are created using the INCLUDE clause of the CREATE INDEX statement. For example:

CREATE INDEX IX_Table ON Table (Key_Index_Column) INCLUDE (Column1, Column2, Column3)

More space is required to store indexes with nonkey columns. Nonkey column data is stored at both the leaf level of the index and in the table itself.
Larger indexes mean fewer rows can fit on a page, potentially increasing disk I/O.
Index maintenance is increased for data modifications, potentially hurting performance if nonkey columns are large and the database experiences a high level of data modifications.

Thursday, November 12, 2009

WebPart Creation & Deployment

Custom Web Part Creation and Deployment

Creating Web User Control in VS2005 or VS2008.
Step 1: Create new project (Web application Project)
Note: Do not use new Web Site when creating project.
Step 2: Name the Project with good name. Since this becomes our DLL.
Step 3: Create Web User Control, with complete UI and Logic.
Step 4: Build the project. Which will create a DLL.

Create Web Part Project Library:
This project is our Web part Library. Usually we will create only one Library project for all the web parts we develop.
Step 1: Open new dev VS2005. Create New Library Project.
Step 2: Name the project with Good name. (This becomes Dll)
Step 3: Add a reference system.web to the project. This contains all the related name space for web part to work in share point.
Step 4: Add a Class. Name it. This becomes the WebPart.
Step 5: Import below name space.
using System.Web.UI.WebControls.WebParts;
Step 6: Inherit WebPart Class.

namespace BasicWebParts
{
public class HelloWorld:WebPart
{

}
}
Step 6: Override Create control method .And modify the code to reflect the user control file name.



Example class code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;

namespace BasicWebParts
{
public class UserControlWebPart:WebPart
{
Control cntrl;
protected override void CreateChildControls()
{
this.cntrl = this.Page.LoadControl(@"~/usercontrols/ucDisplay.ascx");
this.Controls.Add(this.cntrl);
}
}
}

Change only the ucDisplay.ascx only to your user control.

Step 7: (Important)
Add the below line to AssemblyInfo file located under Properties folder .
[assembly: System.Security.AllowPartiallyTrustedCallers]
Better Add it at the end.

Information: This related to security issue while inporting the Webpart by sharepoint.

Step 8: Creating snk file.
1.Open Application Properties as shown below Image.



2. Click on signing  Choose Strong name key  as shown in below.



3. Enter Project Name as snk file name and uncheck the Protect my key file with password.
4. Click ok. And save the changes. snk file got created.

Step 9: Build the Project. Get the Dll.
Step 10: Extract public Key token.
Open visual studio 2005 command prompt.
Enter sn –T “Path of the dll”
Example: sn -T “C:\Project1\bin\debug\Test.dll”
Note the Public Key Token: it will be like example “fa29fd297c3b296b”
Step 11:
Add Safe Control Tag in Web.config of the site. To find web.config go to IIS server virtual directory and explore the same.
By Default Location is like : C:\inetpub\wwwroot\wss\virtualdirectories\siteport
Open Web.config . Copy paste one safe control tag from their and modify the Assembly PublicKey token, Namespace.
Example:


Step 12: Deploy dlls and supporting files.
1. Deploying User Control s
2. Create a folder “usercontrol s” in the site root .
Assume 1001 is the site port we created. Create the directory like below
C:\inetpub\wwwroot\wss\virtualdirectories\1001\usercontrols.
Step 13: Place ASCX controls to this folder.
Step 14: Place WebpartDlls, WebUserControl dlls created from above steps into bin folder.

Adding web part to the site:

Step 1: Open site - Click Site Actions - Site Settings - Webparts  Webpart gallery will open
Step 2: Click New . New ly created webpart are displayed. Check the web part to add into current site.
Step 3: Add web part from web part pane to any webpart page.

Note:
rest of the activities whatever functionality/design we can change as it Usercontrols update to reference folder.

SharePoint Architecture

Server Architecture:


1. The SPFarm object is the highest object within the Windows SharePoint Services object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.
2. Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
3. Each SPService object represents a logical service or application installed in the server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, Microsoft SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the Microsoft Office system.
4. An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.
5. An SPDatabaseServiceInstance object represents a single instance of a database service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
6. Each SPWebApplication object represents a load-balanced Web application based in Internet Information Services (IIS). The SPWebApplication object provides access to credentials and other server farm wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; that is, a set of one or more physical servers that appear as a single server to users.
7. An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
8. An SPSiteCollection object represents the collection of site collections within the Web application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection.
Site Architecture



1. Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
2. Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
3. Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
4. Each SPField object has members that contain settings for the field.
5. Each SPListItem object represents a single row in the list.

Wednesday, November 11, 2009

Culture Specifcation, Activate PageworkFlow

1) To enable the culture, activate pageworkFlow





2).cs file
using System;
using System.Web.UI.WebControls;
using Telerik.Workflow;
using System.Collections.Generic;
using Telerik.Workflow.WebControls;
using Telerik.Cms.Engine;
using System.Net.Mail;
using Telerik.Cms;
using Telerik.Security;



public partial class Sitefinity_Admin_ControlTemplates_Pages_PageViewer : System.Web.UI.UserControl
{


protected void Page_Load(object sender, EventArgs e)
{
if (this.workflow.Controls.Count > 0)
notificationArea.Visible = true;

workflow.Command += new CommandEventHandler(PageWorkflowMenu_Command);

}

void PageWorkflowMenu_Command(object sender, CommandEventArgs e)
{


WorkflowInstance workflow = ((WorkflowMenu)sender).GetWorkflow();

if (workflow != null)
{

List commands = new List();

this.LoadCommands(commands, workflow.Activity.Activities);

int idx = int.Parse((string)e.CommandArgument);


string strRole = string.Empty;


Telerik.Cms.CmsManager manager = new Telerik.Cms.CmsManager();

Telerik.Cms.ICmsPage page = manager.Provider.GetPageByWorkflow(workflow.ID);

System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();


mailMsg.IsBodyHtml = true;

switch (idx)
{


case 0:
mailMsg.Subject = "page pending approval";
strRole = "administrators";
string relativeurl = page.DefaultUrl.Url;
mailMsg.Body += String.Format("The '{0}' page has been sent for approval. Comments:" + hiddenTextArea.Value + " To approve the page, please go to URL: http://{1}{2}?cmspagemode=edit", page.Name, System.Web.HttpContext.Current.Request.Url.Host, relativeurl.Substring(1));
break;

case 1:

mailMsg.Subject = "page approved";
strRole = "Content Editor";
mailMsg.Body += String.Format("The '{0}' page has been approved. Comments:" + hiddenTextArea.Value + " To approve the page, please go to URL: http://{1}/Sitefinity/Admin/Pages.aspx", page.Name, System.Web.HttpContext.Current.Request.Url.Host);

break;

case 2:

mailMsg.Subject = "page declined";
strRole = "Content Editor";
mailMsg.Body += String.Format("The '{0}' page has been declined. Comments:" + hiddenTextArea.Value + " ", page.Name, System.Web.HttpContext.Current.Request.Url.Host);

break;


}


if (!mailMsg.Subject.Equals(string.Empty))
{

string[] usernames = Telerik.Security.UserManager.Default.GetUsersInRole(strRole);
//For every user, send him or her an e-mail
foreach (string username in usernames)
{
System.Web.Security.MembershipUser user = Telerik.Security.UserManager.Default.GetUser(username);
mailMsg.To.Add(user.Email);
}

// Init SmtpClient and send
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
if (mailMsg.To.Count <= 0)
mailMsg.To.Add(mailMsg.From);

smtpClient.Send(mailMsg);
}




}

}



private void LoadCommands(List commands, IList activities)
{

foreach (Activity act in activities)
{

if (act is EventActivity)

commands.Add((EventActivity)act);

this.LoadCommands(commands, act.Activities);

}

}

}

Adding Control to Module & Data Fetch

If you would like to add the key value. in any inbuilt sitefinity module
say for example. active check box on the module. while fetching a value based on the check pull the data.

1)


2) while fetching the data to your userControl

Namespace
using Telerik.Cms;
using Telerik.Newsletters;
using Telerik.Notifications.Newsletters;
using System.Collections;
using Telerik.Cms.Engine;
using Telerik.Cms.Web;



3).cs

void GetAllNews()
{

NewsManager objnewsManager = new NewsManager("News");
IMetaSearchInfo[] filters = new IMetaSearchInfo[4];
filters[0] = new MetaSearchInfo(MetaValueTypes.DateTime, "Expiration_Date", DateTime.Now, SearchCondition.GreaterOrEqual);
filters[1] = new MetaSearchInfo(MetaValueTypes.ShortText, "Category", ConfigurationManager.AppSettings["NewsandPressrelease"].ToString());
filters[2] = new MetaSearchInfo(MetaValueTypes.Boolean, "Active",true);
filters[3] = new MetaSearchInfo(MetaValueTypes.Boolean, "English", false);
IList lstListOfNewsItems = objnewsManager.Content.GetContent("Publication_Date DESC", filters);
DataTable dtNewsValue = new DataTable();
dtNewsValue.Columns.Add("MoreURL");
dtNewsValue.Columns.Add("Publication_Date");
dtNewsValue.Columns.Add("Title");
dtNewsValue.Columns.Add("Thumbnail");
int icnt = 0;
QFCLib objQFCLib = new QFCLib();

try
{

if (lstListOfNewsItems.Count > 0)
{
foreach (IContent ICntNews in lstListOfNewsItems)
{
string strImageURL = "";

if (ICntNews.GetMetaData("Thumbnail").ToString() != "" && ICntNews.GetMetaData("Thumbnail").ToString() != null)
{
strImageURL = objQFCLib.GetThumbnailURL(ICntNews.GetMetaData("Thumbnail").ToString()) + "?width=87&height=79&proportional=false&decreaseOnly=true";
}
DateTime strPDate = Convert.ToDateTime(ICntNews.GetMetaData("Publication_Date"));
if (strPDate < DateTime.Now)
{
icnt = icnt + 1;
dtNewsValue.Rows.Add(ConfigurationManager.AppSettings["NewsDetails"].ToString() + "?sNewsID=" + ICntNews.ID, strPDate.ToString("MM.dd.yyyy"), ICntNews.GetMetaData("Title"), strImageURL);

}
if (icnt == 5) break;
}
}

if (dtNewsValue.Rows.Count > 0)
{
repeater.DataSource = dtNewsValue;
repeater.DataBind();
dtNewsValue.Dispose();

}
else
{
lblMsg.Text = Resources.ARCommonResource.NoDataFound;
}
}
catch (Exception ex)
{
AppLogger.LogError("GetAllNews Mediacenter() " + ex.Message, AppLogger.Severity.Error);
}

}

4) protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlGenericControl newsThumbnailImgContainer = (HtmlGenericControl)e.Item.FindControl("newsThumbnailImgContainer");

if (((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[3].ToString() != "")
{
newsThumbnailImgContainer.Visible = true;
}
}
}
catch (Exception ex)
{
AppLogger.LogError("DataBound MediaArchive() " + ex.Message, AppLogger.Severity.Error);
}

}
5)if the content level if any images to get the image
Add to the cs file
#region " Sitefinity Method GetItemUrl "
public string GetItemUrl(string provider, Guid id, bool resolveAsAbsoluteUrl)
{
if (ContentManager.Providers.ContainsKey(provider))
{
IContent cnt = ContentManager.Providers[provider].GetContent(id);
if (cnt != null)
return VirtualPathUtility.ToAbsolute(cnt.UrlWithExtension, HttpContext.Current.Request.ApplicationPath);
}
else
{
ICmsUrlContext urlContext = UrlHelper.GetUrl(id);
if (urlContext != null)
{
SiteMapNode node = urlContext.GetSiteMapNode();
if (node != null)
return VirtualPathUtility.ToAbsolute(node.Url,HttpContext.Current.Request.ApplicationPath);
}
}
return String.Concat("Item not found: [", provider, "]", id);
}
#endregion

#region " Get Thumbnail URL "
public string GetThumbnailURL(string pstrThumbnail)
{

string[] strImage = pstrThumbnail.Split(']');
string strImageURL=string.Empty;
if (strImage.Length == 2)
{
Guid idImage = new Guid(strImage[1]);
strImageURL = GetItemUrl(strImage[0].Substring(1).ToString(), idImage, true);
}
else
{
return pstrThumbnail.Replace("~","");
}
return strImageURL;
}
#endregion
strImageURL = objQFCLib.GetThumbnailURL(ICntNews.GetMetaData("Thumbnail").ToString()) + "?width=87&height=79&proportional=false&decreaseOnly=true";


6) Upload the above ascx on the page leve add controls via and drag.

Sitefinity Admin Tools

Telerik Sitefinity is an ASP.NET 2.0-based Content Management System (CMS) that enables the construction of dynamic, fully editable Web sites.
Sitefinity's out-of-the-box functionality, creating custom modules, and incorporating any ASP.NET 2.0 component in the site could be achieved by using Sitefinity APIs in the Visual Studio development environment.

Default Modules provided by them we can edit add our own controls in the tools.

Adding a Tools(Nothing but an customized module): our own control
1) Create a table in the DB access the link via.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[QFC_Module](
[ModuleID] [int] IDENTITY(1,1) NOT NULL,
[ModuleName] [nvarchar](255) NULL, -- UserMangement
[ModulePath] [nvarchar](500) NULL, -- /ApplicationPath/Folder/UserList.aspx
[Priority] [int] NULL, -- sequence
CONSTRAINT [PK_QFC_Module] PRIMARY KEY CLUSTERED
(
[ModuleID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

2) Add a Values manually
ex; 1, UserMangement, /ApplicationPath/Folder/UserList.aspx, Order
customized all modules admin would like to get in a CMS when login.

3)Write sp to get the Modules.



4).cs back based on the role also we can hide the link position. should control in DB level

if (!IsPostBack)
{
QFCLib objQFCLib = new QFCLib();
DataTable dtModules = objQFCLib.GetModules();
string strhtml = "";
try
{
if (dtModules.Rows.Count > 0)
{
foreach (DataRow dr in dtModules.Rows)
{
string strModuleName = dr["ModuleName"].ToString();
Telerik.WebControls.RadWindow rw = new Telerik.WebControls.RadWindow();
rw.Title = strModuleName;
rw.ID = "RW" + dr["ModuleID"].ToString();
rw.Height = Unit.Pixel(600);
rw.Width = Unit.Pixel(800);
rw.VisibleStatusbar = false;
RadWindowManager1.Windows.Add(rw);
strhtml += "

  • " + strModuleName + "
  • ";

    }
    }
    }
    catch (Exception ex)
    {
    AppLogger.LogError("PageLoad ModuleBinding() " + ex.Message, AppLogger.Severity.Error);
    }
    dtModules.Dispose();
    ul_container.InnerHtml = strhtml;

    }
    5)Drag and drop the Usercontrol on sitefinity tools.aspx page. just deactivate all controls placed on the Page.

    Friday, October 23, 2009

    Common Methods Arrange as a Tools

    Write the common Methods instead refering every time on the class file just drag and drop/ click on the method any .cs file it refers later can make as object (scenario for many parameters)







    Monday, October 19, 2009

    DropdownList Apply Colors for Category

    if(!ispostback)
    {
    BindDll()
    }


    void BindDll()
    {
    SqlConnection mycn;
    SqlDataAdapter myda;
    DataTable dt;
    String strConn;
    strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
    mycn = new SqlConnection(strConn);
    myda = new SqlDataAdapter ("Select * FROM Category", mycn);
    dt = new DataTable();
    myda.Fill(dt);
    DropDownList1.DataSource = dt;
    DropDownList1.DataTextField = "CategoryName";
    DropDownList1.DataValueField ="CategoryId";
    DropDownList1.DataBind () ;
    for (int i =0;i < DropDownList1.Items.Count ;i++ )
    {
    DropDownList1.Items[i].Attributes.Add("style", "color:" + dt.Rows[i]["Color"].ToString());
    }
    }

    If the ddl is available in a grid set the property on grid onRowDatabound.

    Tuesday, October 13, 2009

    .Csv File Reader

    Read .csv File add to dataTable

    Create a CSVReader.cs

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.IO;
    using System.Text;
    using System.Collections;

    public class CSVReader

    {
    private Stream objStream;
    private StreamReader objReader;

    #region CSVFileReader
    // CSV File Read
    public CSVReader(Stream filestream) : this(filestream, null) { }

    public CSVReader(Stream filestream, Encoding enc)
    {
    try
    {

    this.objStream = filestream;
    if (!filestream.CanRead)
    {
    return;
    }
    objReader = (enc != null) ? new StreamReader(filestream, enc) : new StreamReader(filestream);
    }
    catch(Exception ex)
    {
    AppLogger.LogError("CSVReader" + ex.Message, AppLogger.Severity.Error);
    }
    }

    public string[] GetCSVLine()
    {
    string data = objReader.ReadLine();
    data = data.Replace("\t", "\",\"");
    if (!data.StartsWith("\""))
    {
    data = "\"" + data + "\"";
    }

    if (data == null) return null;
    if (data.Length == 0) return new string[0];
    ArrayList result = new ArrayList();
    ParseCSVData(result, data);
    return (string[])result.ToArray(typeof(string));
    }

    private void ParseCSVData(ArrayList result, string data)
    {
    try
    {
    int position = -1;
    while (position < data.Length)
    result.Add(ParseCSVField(ref data, ref position));
    }
    catch(Exception ex)
    {
    AppLogger.LogError("ParseCSVData" + ex.Message, AppLogger.Severity.Error);
    }
    }

    private string ParseCSVField(ref string data, ref int StartSeperatorPos)
    {
    if (StartSeperatorPos == data.Length - 1)
    {
    StartSeperatorPos++;
    return "";
    }
    int fromPos = StartSeperatorPos + 1;
    if (data[fromPos] == '"')
    {
    int nextSingleQuote = GetSingleQuote(data, fromPos + 1);
    int lines = 1;
    while (nextSingleQuote == -1)
    {
    data = data + "\n" + objReader.ReadLine();
    nextSingleQuote = GetSingleQuote(data, fromPos + 1);
    lines++;
    if (lines > 20)

    throw new Exception("lines overflow: " + data);
    }

    StartSeperatorPos = nextSingleQuote + 1;
    string tempString = data.Substring(fromPos + 1, nextSingleQuote - fromPos - 1);
    tempString = tempString.Replace("'", "''");
    return tempString.Replace("\"\"", "\"");
    }

    int nextComma = data.IndexOf(',', fromPos);
    if (nextComma == -1)
    {
    StartSeperatorPos = data.Length;
    return data.Substring(fromPos);
    }
    else
    {
    StartSeperatorPos = nextComma;
    return data.Substring(fromPos, nextComma - fromPos);
    }
    }

    private int GetSingleQuote(string data, int SFrom)
    {
    try
    {
    int i = SFrom - 1;
    while (++i < data.Length)
    if (data[i] == '"')
    {
    if (i < data.Length - 1 && data[i + 1] == '"')
    {
    i++;
    continue;
    }
    else
    {
    return i;
    }
    }
    }
    catch(Exception ex)
    {
    AppLogger.LogError("GetSingleQuote" + ex.Message, AppLogger.Severity.Error);
    }

    return -1;

    }

    #endregion

    #region destructor
    ~CSVReader()
    {}
    #endregion
    }

    DataTable dtUser = new DataTable();

    int[] iColumns = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int iUpdate = 0;
    try
    {
    //fexport.PostedFile.InputStream --> Directly reading .csv file from .net file uploader.
    CSVReader objreader = new CSVReader(fexport.PostedFile.InputStream);
    string[] strheaders = objreader.GetCSVLine();

    foreach (string strHeader in strheaders)
    {
    dtUser.Columns.Add(strHeader);
    }
    string[] struserData;
    while ((struserData = objreader.GetCSVLine()) != null)
    dtUser.Rows.Add(struserData);
    }
    catch (Exception exe)
    {
    lblMsg.Text = "Check the CSV Data Sheet Format.";
    AppLogger.LogError("csv sheet DataRead()QNews " + exe.Message, AppLogger.Severity.Error);
    }

    Friday, September 11, 2009

    SQL Paging

    Using Stored Procedure Managing Pagination
    CREATE PROCEDURE SPName
    @PageNum int,
    @PageSize int
    AS
    BEGIN
    SET NOCOUNT ON;
    WITH OrdersRN
    AS
    (
    SELECT ROW_NUMBER() OVER(ORDER BY createdatetime desc) AS RowNum ,NewsId,Title,createdatetime
    FROM bdl_news
    )

    SELECT * FROM OrdersRN WHERE RowNum BETWEEN ((@PageNum - 1) * @PageSize + 1 ) AND (@PageNum * @PageSize ) ORDER BY createdatetime desc

    end

    Wednesday, August 26, 2009

    Remoting

    http://www.devx.com/dotnet/Article/7002
    Introduction:

    Remoting is a means by which one operating system process, or program, can communicate with another process. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. Communicating between two programs may seem like a big "so what," but it's a rather involved process.

    In any operating system, two paramount goals are security and stability. One way to achieve these goals is to load each executing program into its own process. By design, processes are isolated from each other—the code in one process cannot access the code or data of another process. That design enhances security by preventing one program from snooping around where it does not have access rights, and it enhances stability by ensuring that problems in one program cannot inadvertently corrupt the memory space of another program or of the operating system itself. The .NET Framework provides an additional level of isolation with application domains, which permit two or more programs to run within the same process, maintaining the same level of isolation as if they were in separate processes while minimizing the overhead of multiple processes.

    Web services are probably the best known type of remoting, but they are not your only option.


    While the need for isolation between processes is clear, the fact remains that separate programs sometimes do need to communicate. The emphasis on distributed computing and scalability makes this need even more prevalent today. The .NET Framework provides several method for cross-process communication, collectively called remoting. Web services are probably the best known type of remoting, but they are not your only option. In this article you'll see an overview of .NET remoting technologies that may help you choose between the various remoting options

    Marshal by Value or by Reference :

    Marshal by value: the server creates a copy of the object passes the copy to the client.
    Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object.

    When a client makes a call to an object marshaled by value (MBV), the server creates an exact copy and sends that copy to the client. The client can then use the object's data and executable functionality directly within its own process or application domain without making additional calls to the server. To implement MBV you must either implement the ISerializable interface in your classes, or mark them with the attribute.

    In contrast, when a client makes a call to an object marshaled by reference (MBR), the .NET framework creates a proxy in the client's application domain and the client uses that proxy to access the original object on the server. To implement MBR a class must, at minimum, extend the System.MarshalByRefObject class. Figure 1 illustrates the differences between MBV and MBR.


    Given the differences between MBV and MBR, how do you decide which to use when you're programming a remotable class? In some situations you have no choice—you must use MBR, such as when the remote component must run in its own original app domain, in order to access local files or use operating system handles. These operations could not be carried out by a copy of the object running in the client's app domain. You would also need to use MBR when the client must be made aware of changes in the object. When using MBV the copy of the object that is sent to the client is static, and does not reflect subsequent changes to the state of the object on the server.



    In many situations, however, either MBV or MBR will work, and the question is which is better? The concern here is that old bugaboo—bandwidth. Ask yourself which technique places fewer demands on the transport between server and client? With MBV you need move the object copy from the server to the client one time. While that can be a significant task with large objects, after the copy is at the client, calls to it are all within the client's app domain and do not involve the transport mechanism at all.

    In contrast, MBR does not require a copy of the entire object to be transported to the client—but each and every time the client accesses the remote object it requires either a one-way or round-trip transport of information. Individually these calls may not place a heavy demand on communication, but hundreds or thousands of calls can add up.

    Channels:

    HttpChannel: Implements a channel that uses the HTTP protocol.
    TcpChannel: Implements a channel that uses the TCP protocol (Transmission Control Protocol).
    Both of these classes are dual-purpose in that they implement both a client channel, used on the client side to communicate with remote objects, and a server channel, used on the server side to communicate with clients. The HttpChannel class formats messages using the SOAP protocol, which encodes communications as XML. In contrast the TcpChannel class uses a binary format for messages. While binary formatting is more efficient (formatted messages are smaller), the plain text format of SOAP is much less likely to have problems with firewalls and other network security measures.

    When you create a server—that is, a remotable class—you also define and register one or more channels for the class and associate each channel with a specific port. By registering a channel/port combination you tell the .NET infrastructure to listen on that port for messages intended for that channel. When a message arrives, the framework routes it to the correct server object. Figure 2 illustrates how the client and server communicate. Note that when you're using remoting on a single system, the port numbers used by the client and server cannot be the same, because you can use a given port only once.

    Demonstration:

    This demonstration program presents a simple remoting example. It illustrates the basic tasks involved in creating a remotable class, a server, and a client. To help keep things easy to understand, the demo makes use of .NET command line applications and the command-line compiler, but the same principles apply when you use remoting with other application types. To work with the demo, open a Visual Studio .NET (VS.NET) command prompt from the Start menu by selecting Microsoft Visual Studio .NET, then selecting Visual Studio .NET Tools, and finally Visual Studio .NET Command Prompt. The Command Prompt window opened by this command is like any other Windows command prompt but has the necessary environment and path variables set to let you use the VS.net command line compilers. Create a folder for the project, and make that folder current.

    The remotable class (called RemoteClass) contains a single method that returns a "secret" word to the caller. The class constructor displays a console message when a client activates the class. I've included the console message for demonstration purposes only; it's not required for the class to function. Listing 1 shows the source code for the RemoteClass. Note that the only aspect of the class related to remoting is that it inherits from MarshalByRefObject. You can create the demo code using any text editor and then save it in the project folder under the name RemoteClass.cs. Then, from the command prompt, compile the class using the following command (enter the command on a single line):


    csc /t:library /debug /r:System.Runtime.Remoting.dll
    RemoteClass.cs
    The class compiles to the file RemoteClass.dll.

    Creates a new TcpChannel on port 8085. Note that this is the same channel on which the client will look for the remotable class.
    Registers the channel with the .NET infrastructure.
    Registers the remotable class using a call to the RemotingConfiguration.RegisterWellKnownServiceType() method. The arguments to this call are:
    The first argument identifies the class being registered.
    The second argument specifies the URI for the class. A client will use this URI when looking for the class.
    The third argument specifies that if there are multiple calls to the class (from more than one client), they will all be services by the same instance of the class.
    Display a message to the user and then pause until the user presses Enter.

    Step 4 is required because the server must be executing to do its job. In other words, only while the server program is running will it "listen" for client requests for the remotable class.

    To complete the server, save the code from Listing 3 as Server.cs and compile it with the following command line (enter the command on a single line):


    csc /debug /r:remoteclass.dll
    /r:System.Runtime.Remoting.dll Server.cs
    Assuming all three parts of the project compiled successfully, you can test the program as follows.


    Open a second Command Prompt window and change to the project folder. You will now have two Command Prompt windows open (the need for this will become clear in a moment).
    In one of the windows enter "Server" to execute the server program. It will display the message "Hit to exit...". The server is now waiting, listening for client requests for the remotable class.
    In the other Command prompt window enter "Client" to execute the client program. You'll see two things happen:
    The client window displays the message "The secret word is REMOTING", and the client program terminates.
    The server window displays the message "MyRemoteClass activated", signaling that a client activated the remote class.
    To terminate the server, switch to the server window and press Enter.
    You've seen a simple example introducing you to the .NET Framework's remoting capabilities. Given the power of remoting, the relative ease with which you can accomplished it comes as a welcome surprise to many developers. While few real-world scenarios are as simple as the demonstration program presented here, the principles remain the same.

    Monday, July 27, 2009

    Return XML File

    Get the data from datatable/list, write it in a xml format.

    using System.Data.SqlClient;
    using System.IO;
    using System.Xml;
    using System.Text;

    protected void Page_Load(object sender, EventArgs e)
    {
    ReturnProductDetailsCollections();
    }
    void ReturnProductDetailsCollections()
    {
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(-60));
    PGILib objPGLib = new PGILib();
    try
    {
    int CollectionID;
    StringWriter sw = new StringWriter();
    XmlTextWriter writer = new XmlTextWriter(sw);
    if (Request.QueryString["ProductID"] != null && Request.QueryString["LanguageID"] != null)
    {
    CollectionID = Convert.ToInt32(Request.QueryString["ProductID"]);
    int iLanguageID = Convert.ToInt32(Request.QueryString["LanguageID"]);

    string Currentlang = "";
    DataTable dtCurrentlang = new DataTable();
    dtCurrentlang = objPGLib.Script_GetLanguageName(iLanguageID);
    if (dtCurrentlang.Rows.Count > 0)
    {
    foreach (DataRow dr in dtCurrentlang.Rows)
    {
    Currentlang = dr["LanguageShortName"].ToString();
    }
    }

    int CategoryID = objPGLib.getCollectionCategoryIDByMarket(iLanguageID);

    writer.WriteStartElement("designgallery");
    writer.WriteAttributeString("Result", "Success");
    DataTable dtProductCollection = new DataTable();

    dtProductCollection = objPGLib.Script_GetDesignerCollections(CollectionID,CategoryID);
    if (dtProductCollection.Rows.Count > 0)
    {
    foreach (DataRow dr1 in dtProductCollection.Rows)
    {
    string strpPath = ConfigurationManager.AppSettings["UploadLocation"].ToString() + dr1["SmallThumbnailPath"].ToString();
    writer.WriteStartElement("product");
    writer.WriteAttributeString("productid", dr1["ProductID"].ToString());
    writer.WriteAttributeString("smallthumbnail", strpPath);
    writer.WriteAttributeString("name", dr1["ProductName"].ToString());
    writer.WriteAttributeString("designer", dr1["FirstName"].ToString());
    writer.WriteEndElement();
    }
    }
    }
    else
    {
    writer.WriteStartElement("designgallery");
    writer.WriteAttributeString("Result", "Failure");

    }



    writer.WriteEndElement();
    Response.ContentType = "text/xml";
    Response.ContentEncoding = Encoding.UTF8;
    Response.Write(sw);
    }
    catch (Exception ex)
    {
    AppLogger.LogError("Designer Gallery Product ReturnProductDetailsCollections(based on designerid) " + ex.Message, AppLogger.Severity.Error);
    }


    }

    Rss Feeds in asp.net

    To write the Rss Contents from list/datatable.

    steps to follow:

    Get the all the item (ex: news in a list/datatable loop through the items bind in the rss feeds format)

    refer the attached image.

    image 1



    image 2



    C#Code:

    protected void Page_Load(object sender, EventArgs e)
    {
    this.Context.Response.ContentType = "text/xml";
    this.Context.Response.ContentEncoding = Encoding.UTF8;
    ShowHeader(this.Context);
    NewsManager newsManager = new Telerik.News.NewsManager("News");
    IList listOfNewsItems = newsManager.Content.GetContent();
    if (listOfNewsItems.Count > 0)
    {
    foreach (IContent ICntNews in listOfNewsItems)
    {
    DateTime strPDate = Convert.ToDateTime(ICntNews.GetMetaData("Publication_Date"));
    if (strPDate < DateTime.Now)
    {
    ShowItem(this.Context, ICntNews);
    }
    }
    }

    ShowFooter(this.Context);
    }

    private void ShowItem(HttpContext context, Telerik.Cms.Engine.IContent content)
    {
    context.Response.Write("");
    context.Response.Write(string.Format("{0}", content.GetMetaData("Title")));
    DateTime dtPubdate = Convert.ToDateTime(content.GetMetaData("Publication_Date"));
    context.Response.Write(string.Format("{0}", dtPubdate.ToString("ddd, dd MMM yyyy hh:mm:ss GMT")));
    context.Response.Write(string.Format("{0}", content.GetMetaData("Summary")));
    context.Response.Write(string.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, ConfigurationManager.AppSettings["NewsDetails"].ToString() + "?sNewsID=" + content.ID));
    context.Response.Write(string.Format("{0}", content.ID));
    context.Response.Write("
    ");
    }

    private void ShowHeader(HttpContext context)
    {
    context.Response.Write("");
    context.Response.Write("");
    context.Response.Write("");
    context.Response.Write("QFC Authority news ");
    context.Response.Write("News headlines ");
    context.Response.Write("http://www.qfc.com.qa/ ");
    context.Response.Write("http://backend.userland.com/rss ");
    context.Response.Write(Environment.NewLine);
    }

    private void ShowFooter(HttpContext context)
    {
    context.Response.Write("
    ");
    context.Response.Write("
    ");
    }

    Friday, July 10, 2009

    Open outlook and add reciepient emailid

    To send mail call the below method in .Net.
    1)
    using System.Web.Mail;
    public Boolean SendMail(string pstrFrom, string pstrTo, string pstrSubject, string pstrBody)
    {
    Boolean Result = false;
    try
    {
    MailMessage omsg = new MailMessage();
    omsg.From = pstrFrom;
    omsg.To = pstrTo;
    omsg.Subject = pstrSubject;
    omsg.Body = pstrBody;
    omsg.Priority = MailPriority.High;
    omsg.BodyFormat = MailFormat.Html;
    SmtpMail.SmtpServer = "";
    SmtpMail.Send(omsg);
    Result = true;
    }
    catch (Exception ex)
    {
    Result = false;
    AppLogger.LogError("SendMail(4 parameters): " + ex.Message, AppLogger.Severity.Error);

    }
    return Result;

    }

    2)To open a outlook.

    Wednesday, July 8, 2009

    DateFormat

    Standard Formats:
    The following table lists the standard format characters for internationally accepted standard patterns. The format characters are case-sensitive; for example, 'g' and 'G' represent slightly different patterns. Note that on the whole the format handling of the DateTimePicker is almost identical to that of the associated Culture.DateTimeFormatInfo instance, the main exception being that day names "dddd" are not used anywhere.

    Custom Formats:

    Friday, July 3, 2009

    Passing Data/Parameter/Value/ from one page to another page (.aspx/.ascx)

    Passing Data/Parameter/Value/ from one page to another page (.aspx/.ascx)
    Passing parameters from one page to another page is a very common task in Web development. Especially when you develop a project & redirects or navigates from one ASP.NET Web page to another, you will frequently want to pass information from the source page to the target page . In this post, I will show you some ways of transferring data/parameters/values between one page to another page which is also termed as State Management. The pages I created to show you the example is really simple which consists of a text field and a button in the first page named as page1 and a blank second page named as page2.

    According to the characteristics of aspx page lifecycle web form do not retain their value after a page is displayed. To solve this problem, ASP.NET provides the following ways to retain variables between pages:
    Query Strings
    Cookies
    Session variables
    Server.Transfer
    Post Back URL


    Using Query String:

    The most common & easiest way of passing data is query string. Usually we pass value(s) through query string of the page and then this value is pulled from Request object in another page. One thing keep in mind that user can view query string value any time(from brwser address, View source, even on mouse over of a link etc.). So never pass information which is secure like password through query string. Drawback of Query string appear after a question mark of a URL.

    Example:
    Suppose you want to pass the txtName TextBox value from page1 to page2 on button click event:

    protected void btn_Click(object sender, EventArgs e)
    {
    Response.Redirect("page2.aspx?name=" + txtName.Text);
    }

    Now the question is how we can read/retrieve my name from page2.aspx page? The way is:

    string name = Request.QueryString["name"];

    Now more advance is if you want to transfer special charaters or a line with spaces then you must have to use Server.UrlEncode method before transfer & Server.UrlDecode method to read data from page2.aspx:

    protected void btn_Click(object sender, EventArgs e)
    {
    Response.Redirect("page2.aspx?name=" + Server.UrlEncode(txtName.Text));
    }

    and to read from page2:

    string name = Server.UrlDecode(Request.QueryString["name"]);

    Now i want to show you how you can transfer more data:

    protected void cmdTransfer_Click(object sender, EventArgs e)
    {
    Response.Redirect("page2.aspx?name="+Server.UrlEncode(txtName.Text)+"&age="+txtAge.Text);
    }

    Now read both name & age from page2 in the same way:

    string name = Request.QueryString["name"];
    string age = Request.QueryString["age"];

    now you can check the both parameter (with null value then write it).

    Cookies:
    Developers use cookies to store small amounts of information on the client. Drawback if user set the browser status cookie not supported won’t help. It’s stored only client machine. From the server we can check the page load event.
    Example:
    Now we create a cookie from page1 & read from page2:
    for page1 button click event:

    protected void cmdTransfer_Click(object sender, EventArgs e)
    {
    if(Request.Browser.Cookies) // To check that the browser support cookies
    {
    HttpCookie cookie = new HttpCookie("myname");
    cookie.Value = txtName.Text;
    cookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(cookie);
    Response.Redirect("page2.aspx");
    }
    else
    {
    // You have to follow other option.
    }
    }

    Now read from page2:
    if(Request.Cookies["myname"] != null)
    Response.Write(Request.Cookies["myname"].Value);

    Using Session Variables:
    By default, session variables are stored in the web server memory. Session variables are unique per each user. If you open same url in two browser then server will create two independent sessions for you. Keep in mind that each session has a expire time. You can configure session time from IIS. Also one another thing is, you can receive session value form any pages after assigning. Write the below code under page1 button:

    protected void btn_Click(object sender, EventArgs e)
    {
    Session["name"] = txtName.Text;
    Response.Redirect("page2.aspx");
    }

    Now read session variable value from page2:

    string name ="";
    if(Session["name"]!=null)
    name=Session["name"].ToString();


    Using Server.Transfer:
    We will use Server. Transfer to send the control to a new page. Note that Server.Transfer only transfers the control to the new page and does not redirect the browser to it, which means you will see the address of the old page in your URL. If the user clicks Refresh on his browser, the browser prompt a message warning that the page can not be refreshed without resending information. Write the below code under page1 button click event:

    protected void btn_Click(object sender, EventArgs e)
    {
    Server.Transfer("page2.aspx", true);
    }

    And write the below code in page2 load event:

    if (Request.Form["txtEmail"])
    Response.Write(Request.Form["txtNamel"]);

    Now run the page1, enter your name & click. You will see your name in page2. Merits of using the above it won’t give any blank page or any warnings.

    Using Post Back URL:
    ASP.NET 2.0 has been introduced Cross page posting. By PreviousPage object you can search controls value from which page you are redirected here. To implement Cross page posting you have to define the PostBackUrl property of page1 button to page2. Like:

    aspx/ascx design page btn propery called PostBackUrl="page2.aspx"

    Now write the below code in page2 load event:

    TextBox txtName = (TextBox)(PreviousPage.FindControl("txtName"));
    string myname =txtName.Text;
    Or
    If you use usercontrol the previouspage// prpery won’t support.
    TextBox txtName = (TextBox)Page.PreviousPage.FindControl("txtName"));
    string myname =txtName.Text;

    Copyright © 2009 Angel