Saturday, July 14, 2012

Different ways to refresh or reload page using jQuery

different ways using which you can reload or refresh the webpage using jQuery. The first method is nothing to do with jQuery. It is a HTML tag which you need to put in the head section of your page and your page will get refreshed automatically after specified interval.

1<meta http-equiv="refresh" content="10">
The meta tag with "http-equiv" is used to refresh the page. This attribute tells the browser that this meta tag is sending an HTTP command rather than a standard meta tag. Refresh is an actual HTTP header used by the web server.The content attribute in the tag is having value in seconds. As per the above code, it is set to 10, which means after 10 seconds your page will get refreshed or reloaded.

You can also use jQuery to refresh/reload the page automatically. See below jQuery code.
1function ReloadPage() {
2   location.reload();
3};


5$(document).ready(function() {
6  setTimeout("ReloadPage()", 10000); .
7});
location.reload() will reload the page again. The advantage of location.reload() is that it works with all the major browsers.

If you want to reload the page on click of button, then you can call location.reload() on button click event. See below jQuery code.
1$(document).ready(function() {
2     $('#btnReload').click(function() {
3             location.reload();
4       });
5});

Monday, July 2, 2012

Cloud computing

Cloud computing is the delivery of computing and storage capacity   as a service   to a heterogeneous community of end-recipients. The name comes from the use of a cloud-shaped symbol  as an abstraction for the complex infrastructure it contains in system diagrams  Cloud computing entrusts services with a user's data, software and computation over a network.
There are three types of cloud computing: 
  • Infrastructure as a Service (IaaS),
  • Platform as a Service (PaaS), and
  • Software as a Service (SaaS).
Using Infrastructure as a Service, users rent use of servers (as many as needed during the rental period) provided by one or more cloud providers. Using Platform as a Service, users rent use of servers and the system software to use in them. Using Software as a Service, users also rent application software and databases. The cloud providers manage the infrastructure and platforms on which the applications run.

End users access cloud-based applications through a web browser or a light-weight desktop or mobile app while the business software and user's data are stored on servers at a remote location. Proponents claim that cloud computing allows enterprises to get their applications up and running faster, with improved manageability and less maintenance, and enables IT to more rapidly adjust resources to meet fluctuating and unpredictable business demand. 
Cloud computing relies on sharing of resources to achieve coherence and economies of scale similar to a utility (like the electricity grid) over a network (typically the Internet).  At the foundation of cloud computing is the broader concept of converged infrastructure and shared services.



Characteristics

Cloud computing exhibits the following key characteristics:
  • Agility improves with users' ability to re-provision technological infrastructure resources.
  • Application programming interface (API) accessibility to software that enables machines to interact with cloud software in the same way the user interface facilitates interaction between humans and computers. Cloud computing systems typically use REST-based APIs.
  • Cost is claimed to be reduced and in a public cloud delivery model capital expenditure is converted to operational expenditure  This is purported to lower barriers to entry, as infrastructure is typically provided by a third-party and does not need to be purchased for one-time or infrequent intensive computing tasks. Pricing on a utility computing basis is fine-grained with usage-based options and fewer IT skills are required for implementation (in-house).  The e-FISCAL project's state of the art repository  contains several articles looking into cost aspects in more detail, most of them concluding that costs savings depend on the type of activities supported and the type of infrastructure available in-house.
  • Device and location independence  enable users to access systems using a web browser regardless of their location or what device they are using (e.g., PC, mobile phone). As infrastructure is off-site (typically provided by a third-party) and accessed via the Internet, users can connect from anywhere.
  • Virtualization technology allows servers and storage devices to be shared and utilization be increased. Applications can be easily migrated from one physical server to another.
  • Multitenancy enables sharing of resources and costs across a large pool of users thus allowing for:
    • Centralization of infrastructure in locations with lower costs (such as real estate, electricity, etc.)
    • Peak-load capacity increases (users need not engineer for highest possible load-levels)
    • Utilisation and efficiency improvements for systems that are often only 10–20% utilised.
  • Reliability is improved if multiple redundant sites are used, which makes well-designed cloud computing suitable for business continuity and disaster recovery.
  • Scalability and Elasticity via dynamic ("on-demand") provisioning of resources on a fine-grained, self-service basis near real-time, without users having to engineer for peak loads. 
  • Performance is monitored, and consistent and loosely coupled architectures are constructed using web services as the system interface.
  • Security could improve due to centralization of data, increased security-focused resources, etc., but concerns can persist about loss of control over certain sensitive data, and the lack of security for stored kernels.  Security is often as good as or better than other traditional systems, in part because providers are able to devote resources to solving security issues that many customers cannot afford.  However, the complexity of security is greatly increased when data is distributed over a wider area or greater number of devices and in multi-tenant systems that are being shared by unrelated users. In addition, user access to security audit logs may be difficult or impossible. Private cloud installations are in part motivated by users' desire to retain control over the infrastructure and avoid losing control of information security.
  • Maintenance of cloud computing applications is easier, because they do not need to be installed on each user's computer and can be accessed from different places.

Service Models

Cloud computing providers offer their services according to three fundamental models:   Infrastructure as a service (IaaS), platform as a service (PaaS), and software as a service (SaaS) where IaaS is the most basic and each higher model abstracts from the details of the lower models.
Cloud computing layers.png

Infrastructure as a service (IaaS)

In this most basic cloud service model, cloud providers offer computers – as physical or more often as virtual machines –, raw (block) storage, firewalls, load balancers, and networks. IaaS providers supply these resources on demand from their large pools installed in data centers. Local area networks including IP addresses are part of the offer. For wide area connectivity, the Internet can be used or -- in carrier clouds -- dedicated virtual private networks can be configured.
To deploy their applications, cloud users then install operating system images on the machines as well as their application software. In this model, it is the cloud user who is responsible for patching and maintaining the operating systems and application software. Cloud providers typically bill IaaS services on a utility computing basis, that is, cost will reflect the amount of resources allocated and consumed.
IaaS refers not to a machine that does all the work, but simply to a facility given to businesses that offers users the leverage of extra storage space in servers and data centers.
Examples of IaaS include: Amazon CloudFormation (and underlying services such as EC2), Rackspace Cloud, Google Compute Engine, and RightScale.

Platform as a service (PaaS)

In the PaaS model, cloud providers deliver a computing platform typically including operating system, programming language execution environment, database, and web server. Application developers can develop and run their software solutions on a cloud platform without the cost and complexity of buying and managing the underlying hardware and software layers. With some PaaS offers, the underlying compute and storage resources scale automatically to match application demand such that cloud user does not have to allocate resources manually.

Software as a service (SaaS)

In this model, cloud providers install and operate application software in the cloud and cloud users access the software from cloud clients. The cloud users do not manage the cloud infrastructure and platform on which the application is running. This eliminates the need to install and run the application on the cloud user's own computers simplifying maintenance and support. What makes a cloud application different from other applications is its elasticity. This can be achieved by cloning tasks onto multiple virtual machines at run-time to meet the changing work demand.  Load balancers distribute the work over the set of virtual machines. This process is inconspicuous to the cloud user who sees only a single access point. To accommodate a large number of cloud users, cloud applications can be multitenant, that is, any machine serves more than one cloud user organization. It is common to refer to special types of cloud based application software with a similar naming convention: desktop as a service, business process as a service, Test Environment as a Service, communication as a service.
The pricing model for SaaS applications is typically a monthly or yearly flat fee per user.
Examples of SaaS include: Google Apps, Quickbooks Online and Salesforce.com.

Cloud clients


Users access cloud computing using networked client devices, such as desktop computers, laptops, tablets and smartphones. Some of these devices - cloud clients - rely on cloud computing for all or a majority of their applications so as to be essentially useless without it. Examples are thin clients and the browser-based Chromebook. Many cloud applications do not require specific software on the client and instead use a web browser to interact with the cloud application. With Ajax and HTML5 these Web user interfaces can achieve a similar or even better look and feel as native applications. Some cloud applications, however, support specific client software dedicated to these applications (e.g., virtual desktop clients and most email clients). Some legacy applications (line of business applications that until now have been prevalent in thin client Windows computing) are delivered via a screen-sharing technology.


Friday, June 29, 2012

Create MVC Website

Before you can do anything with ASP.NET MVC, you have to create a website to work with. Fortunately, it is easy to do.

Step 1: Find the Project Type in Visual Studio

Open up Visual Studio 2008. Go to File > New > Project in the menu. You will get a dialog much like the following image. Pick the "Web" category.
Picture of the add project dialog.
You can, of course call the project whatever you want and put it wherever you want. Next step.

Step 2: Create a Test Project

This is not necessary but is highly recommended. After all, automating tests is a useful activity.
Picture of the add test project dialog.

As you can see, there is a dropdown for selecting test frameworks other than that which comes with Visual Studio. If you have another test framework that you use, feel free to use it.

Take a Look at What You Get

You now have an MVC project. So now let's take a look at what you have.
Picture of solution explorer for a newly created project.
A few things here. The content folder is the place to put images and css. Putting such things there is not necessary. That is simply the default recommendation. The controllers folder is where you put your controller classes. If you are wondering what that is, well, that will be defined soon enough. This is actually one of the two core pieces of what ASP.NET MVC really is. The models folder is potentially a place to put any "business logic" classes you want to use but it can, frankly, just be deleted. Unless you want to put code there, do not feel constrained to do so. The scripts folder is for javascript files. The views folder is the other super-important core pieces of the ASP.NET MVC framework, and contains your Html files.
In the next section we will discuss the pattern around which ASP.NET MVC is built, the Model-View-Controller pattern. After that we will come back to solution explorer and see how that pattern is applied to the project file, and how they expect code to be written using this framework.

Monday, June 25, 2012

Consumerism and its antisocial effects can be turned on—or off



khg   
Money doesn't buy happiness. Neither does  materialism: Research shows that people who  place a high value on wealth, status, and stuff are more depressed and anxious and less sociable than those who do not. Now new research shows that materialism is not just a personal problem. It's also environmental.
"We found that irrespective of personality, in situations that activate a consumer mindset, people show the same sorts of problematic patterns in wellbeing, including negative affect and social disengagement," says Northwestern University psychologist Galen V. Bodenhausen. The study, conducted with colleagues Monika A. Bauer, James E. B. Wilkie, and Jung K. Kim, appears in Psychological Science, a journal of the Association for Psychological Science.
In two of four experiments, university students were put in a materialistic frame of mind by tasks that exposed them to images of luxury goods or words mobilizing consumerist values (versus neutral scenes devoid of consumer products or words without such connotations). Completing questionnaires afterwards, those who looked at the pictures of cars, electronics, and jewelry rated themselves higher in depression and anxiety, less interested in social activities like parties, and more in solitary pursuits than the others. Those primed to materialism by exposure to certain words evinced more competitiveness and less desire to invest their time in pro-social activities like working for a good cause.
In two other experiments, participants completed tasks that were framed as surveys—one of consumer responses, another of citizens.' The first experiment involved moving words toward or away from the participant's name on a computer screen—positive and negative emotion words and "neutral" ones that actually suggested materialism (wealth, power), self-restraint (humble, discipline), transcendence of self, or self-indulgence. The people who answered the "consumer response survey" more quickly "approached" the words that reflected materialistic values than those in the "citizen" survey. The last experiment presented participants with a hypothetical water shortage in a well shared by four people, including themselves. The water users were identified either as consumers or individuals. Might the collective identity as consumers—as opposed to the individual role—supersede the selfishness ordinarily stimulated by the consumer identity? No: The "consumers" rated themselves as less trusting of others to conserve water, less personally responsible and less in partnership with the others in dealing with the crisis. The consumer status, the authors concluded "did not unite; it divided."
The findings have both social and personal implications, says Bodenhausen. "It's become commonplace to use consumer as a generic term for people," in the news or discussions of taxes, politics, or health care. If we use term such as Americans or citizens instead, he says, "that subtle difference activates different psychological concerns." We can also take personal initiative to reduce the depressive, isolating effects of a materialist mindset by avoiding its stimulants—most obviously, advertising. One method: "Watch less TV."

Creative Activism


Creative activists can be described as: 'These are the changemakers. People who turn their ideas into action. A Creative Activist is any individual or organization who uses media, the arts, and technology to create awareness of important issues in the world and affect positive change.'
I would disagree with the description above, simply because creative activists don’t limit their creativity to using arts, media and technology to create awareness. They also use ingenuity and originality to convey their message, to a sometimes unwilling and skeptical audience.
Nick Darken wrote, commenting on the video above: '‘The Return of Dictator Ben Ali’ saw one huge, imposing portrait of the former dictator reinstated in a square in newly freed Tunisia. The response was emotional. As the crowd tore down the poster in anger, the message underneath reminded people to use their vote at the upcoming elections as only half the population were expected to turn out.”
Some creative volunteers found another way to raise awareness about Israel's apartheid policies, on the streets of New York City. The BDS movement provides a prime example of creativity and spontaneity. Attendees of the Israel Jazz Festival in NYC at the Guggenheim were treated to free water bottles labeled "Israel" on one side and the words "Apartheid since 1948" on the other.
Syrian Activist Ammar Allani is quoted as saying:
“And while they (governments/authorities) can claim supremacy in force, finance and media ownership, the one thing they definitely cannot offer is creativity, freedom and innovation. That is why the young generation is using these specific tools to alter the rules of the game, leaving the regimes unable to keep pace, at least in terms of winning the audience.
In one instance, hundreds of young protestors took to the streets raising blank signs, dozens of white boards with absolutely nothing written on them, yet the security forces were exasperated by that and started shooting and beating people. For everyone watching, including some supporters of the regime, it was really silly and stupid; it was a classic example of creativity winning over force.
Take Kafranbel for instance, this is a very small village in Syria, unknown even to the average Syrian and located in a province ironically called “the forgotten cities”, these people grow olives, and recently ideas!
Every week, a few dozens of the Kafranbel inhabitants brainstorm and create the most incredibly creative and powerful punch lines, they write them on paper panels, go to the grove, photograph themselves with a phone and upload the images to Facebook, as simple as this may seem, it is literarily revolutionizing the nation.
Just to share with you some of these punch lines:
- We demand that school uniforms include a helmet, body armor and gas mask.
- Forgive me my love; I mentioned your name in the interrogation.
- Only in Syria, to get to heaven… just cross the street.”
Marianne Torres, an inspiring American activist, told me of her own small victory:
"We learned that Madeline Albright was coming to Eastern Washington University in Cheney. I was still mightily outraged about Albright's words and continued "service" in the American government so I just decided that if no one else could do anything to expose her crimes, I would.
I had a t-shirt made with her infamous quote on the back "500,000 Iraqi children killed by U.S. sanctions. Madeleine Albright says, '...The price — we think the price is worth it.', wrote up the quote and other ugliness from her on a handout and passed them out at her speaking engagement and then did a double sided sheet with William Blum's piece on her on one side and the absurd list of embargoed items on the other side, and passed them out both outside, and inside the auditorium. Most people didn't read my shirt, but assumed the flyer was something from the University, so a whole lot of people sat and read the awful truth before she spoke.
Imagine my surprise when people who were excited to see this woman asked me if they could buy a t-shirt like mine! They obviously had not actually read it but assumed I was there in support of her. I'm sure they changed their mind after they read the paper I handed to them - and several hundred others."

View In Sql Server 2005 & 2008

Introduction:
In this article we are going to discuss about the Views in the sql server 2005 version. It is one of the important elements in the sql server; it eliminates the difficulties in the business process. There are lots of significant improvements in the view especially in the sql server 2005 version. They have introduced the indexed views and INSTEAD of Trigger on the permanent view. Let us discuss about the views with more practical way.

Views:

The view is a virtual table, which can have the multiple columns from the one or more table. It can be used like the normal table. Normally view cannot store the data permanently in the table. When we create the view it stores the view definition schema as object under the concern database.

Let us see the syntax of the create view

CREATE VIEW View Name [Alias name1, name2,]

WITH ENCRYPTION

WITH SCHEMA BINDING

AS

SELECT statement [WITH CHECK OPTION]

The create view can be created with the view name and the alias can be given in the view name parameter parenthesis. The view schema can be stored in the encrypted format. Here is an option like SCHEMA BINDING; this is an important mile stone in the view to allow the developers to create the permanent view.

When to use VIEW?

When you have complex queries, that use many places in the stored procedures or functions, etc..,

It will be used as security mechanism in the web applications. When we use the original table in the web applications the hackers may drop the table. That time the original data will be persist in the table.

When you want to hide the particular columns to the specific people then we can create the specialized view.

Encrypted View:

The definition of schema will be encrypted and stored as object in the database. This can be done using the ENCRYPTION option in the view creation.

IF
OBJECT_ID('[DBO].Vw_SqlObjects_Encrypted') IS NOT NULLBEGIN   DROP VIEW [DBO].Vw_SqlObjects_Encrypted
   PRINT '<< [DBO].Vw_SqlObjects_Encrypted View dropped >>'
ENDGOCREATE VIEW [DBO].Vw_SqlObjects_EncryptedWITH ENCRYPTIONAS   SELECT       O.Object_ID      ,O.Name
      ,'Type' = CASE O.type WHEN 'S' THEN 'Scalar Functions'                          WHEN 'F' THEN 'Functions'                          WHEN 'V' THEN 'Views'                          WHEN 'PK' THEN 'Primary keys'                          WHEN 'TR' THEN 'Triggers'                          WHEN 'P' THEN 'Procedures'                          WHEN 'U' THEN 'User Defined Functions'                          WHEN 'TF' THEN 'Table Valued Functions'                          WHEN 'IF' THEN 'Inline Functions' END      ,O.create_date
      ,O.modify_date
      ,CASE WHEN SC.encrypted = 0 THEN 'No' ELSE 'Yes' END AS [IsEncrypted]
      ,SC.text
  FROM      SYS.OBJECTS O
  INNER JOIN      SYSCOMMENTS SC ON SC.id = O.object_id
 GO
IF OBJECT_ID('[DBO].Vw_SqlObjects_Encrypted') IS NOT NULLBEGIN   PRINT '<< [DBO].Vw_SqlObjects_Encrypted View created >>'ENDGO
Now if you want to see the view schema definition for the above view is not possible. We have stored in the encrypted format. This is a significant option to hide the important calculations inside the view from the others.

In case of any alter in the view must be stored externally somewhere else.

SELECT
text FROM SYSCOMMENTS WHERE id = OBJECT_ID('[DBO].Vw_SqlObjects_Encrypted')
SELECT definition FROM SYS.sql_modules WHERE object_id = OBJECT_ID('[DBO].Vw_SqlObjects_Encrypted')
sp_helptext Vw_SqlObjects_Encrypted
If you execute the above queries then it will say like view is encrypted.

There are three types of views in the sql server 2005.

They are 
  1. Normal or Standard view
  2. Indexed or permanent view
  3. Partitioned view
Normal or Standard view:
This view is most frequently used by the developers. When create the view the schema will be stored an object in the database. When we retrieve the content from this virtual table, it will be executed the schema and stored the data from the parent table.

Here if you have the result from the same table then it can be updated and inserted. The deleted row will be reflected in the original table.

USE
[Northwind]
GO
IF OBJECT_ID('[DBO].vw_ViewProducts','V') IS NOT NULLBEGIN  DROP VIEW [DBO].vw_ViewProducts
  PRINT '<< [DBO].vw_ViewProducts view dropped.. >>'
ENDGOCREATE VIEW [DBO].vw_ViewProductsAS SELECT
    ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,
UnitsOnOrder,ReorderLevel,Discontinued
 FROM Products
GO
IF OBJECT_ID('[DBO].vw_ViewProducts','V') IS NOT NULLBEGIN  PRINT '<< [DBO].vw_ViewProducts view created.. >>'ENDGO--O/PSELECT * FROM [DBO].vw_ViewProducts--INSERTINSERT INTO [DBO].vw_ViewProducts(ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued)VALUES('Test View',1,2,'100 per bag',25.45,89,57,15,0)--DELETEDELETE FROM [DBO].vw_ViewProducts WHERE ProductID = 81
Here you can do the DML operations in the view when you have only one table.

Indexed views:

The indexed or permanent view is one of the new features introduced in the sql server 2005 version. We have seen that the view only store the schema definition and it will get execute and load the data into the virtual table at the time of view used. But this view creates the permanent view and we can create the indexes on the table. It allows us to create the instead of trigger.

The indexed view can be created with the WITH SCHEMA BINDING option while creating the view.

The indexed view has some restrictions like cannot use the TOP, DISTINCT, UNION, ORDER BY and aggregate functions.

It allows us to use the GROUP BY statement but we cannot use COUNT statement. Instead of that COUNT_BIG statement can be used.

IF
EXISTS(SELECT OBJECT_ID FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].Vw_Product_Sales_Report',N'V'))BEGIN  DROP VIEW [DBO].Vw_Product_Sales_Report
  PRINT '<< [DBO].Vw_Product_Sales_Report view dropped >>'
ENDGOCREATE VIEW [DBO].Vw_Product_Sales_ReportWITH SCHEMABINDINGAS  SELECT
      O.OrderID
     ,C.CustomerID
     ,C.CompanyName
     ,C.Address+', '+C.City AS [Customer Address]
     ,OD.ProductID
     ,P.ProductName
     ,OD.UnitPrice
     ,OD.Quantity
     ,(OD.UnitPrice * OD.Quantity) AS [Total]
     ,(OD.UnitPrice * OD.Quantity) * OD.Discount/100 AS [Discount]
   FROM     [DBO].Orders O (NOLOCK)   INNER JOIN [DBO]."Order Details" OD (NOLOCK) ON OD.OrderID = O.OrderID
   INNER JOIN [DBO].Customers C (NOLOCK) ON C.CustomerID = O.CustomerID
   INNER JOIN [DBO].Products P (NOLOCK) ON P.ProductID = OD.ProductID
GO
IF EXISTS(SELECT OBJECT_ID FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].Vw_Product_Sales_Report',N'V'))BEGIN  PRINT '<< [DBO].Vw_Product_Sales_Report view created >>'ENDGO
Here the  indexed view has created. When you retrieve the data from this table, it will execute like normal table.

There are some retrictions while creating this indexed view like the name of the view must be two part name and we cannot use select * in the view schema defintion.

Normally view cannot have the triggers but from the sql server 2005 onwards We can create the Instead of trigger on the instead of trigger.

Partitioned Views:

The partitioned view and its execution is like normal view. It will work across the database and across the server.

There are two types of Partitioned views. They are 
  1. Local Partitioned View
  2. Global Partitioned View

1. Local Partitioned View:
The local partitioned view can be created within same server but different database.

The view schema definition will be stored in the executed database. But when we try to retrieve the data from the table, it has to execute the schema definition internally and load the data.

Let us see an example.

USE
[Northwind]
GO
CREATE TABLE EmployeeList(  iEmployeeID INT IDENTITY(1,1),  vFirstName VARCHAR(25) NOT NULL,  vLastName VARCHAR(25) NOT NULL,  iDeptID INT,  vAddress VARCHAR(25) NOT NULL,  vCity VARCHAR(25) NOT NULL,  vState VARCHAR(25) NOT NULL,  vCountry VARCHAR(25) NOT NULL,)GOUSE [Master]
GO
CREATE TABLE Department(  iDeptID INT IDENTITY(1,1) PRIMARY KEY,  vDeptName VARCHAR(50),  vDeptDesc VARCHAR(25),  vDeptAddedBy VARCHAR(50),  vPostedDate DATETIME DEFAULT GETDATE())GO--SELECT * FROM DepartmentUSE [Northwind]
GO
IF OBJECT_ID('[DBO].vw_LocalPartion_View','V') IS NOT NULLBEGIN  DROP VIEW [DBO].vw_LocalPartion_View
  PRINT '[DBO].vw_LocalPartion_View view dropped...'
ENDGOCREATE VIEW [DBO].vw_LocalPartion_ViewAS
SELECT
E.iEmployeeID,E.vFirstName+SPACE(1)+E.vLastName AS [Name],       D.vDeptName,E.vAddress,E.vCity,E.vStateFROM EmployeeList E--INNER JOIN Master..Department D ON D.iDeptID = E.iDeptID --Either one of the way will be used.INNER JOIN Master.dbo.Department D ON D.iDeptID = E.iDeptID
GO
IF OBJECT_ID('[DBO].vw_LocalPartion_View','V') IS NOT NULLBEGIN  PRINT '[DBO].vw_LocalPartion_View view created...'ENDGO--O/pSELECT * FROM [DBO].vw_LocalPartion_View 

2. Global Partitioned View

The global Partitioned view will work across the server. The view can be created to join the table across the server.

The accessing format will be like this.

[Server Name].  Database Name. Table Name

When we execute the view if it is not linked with the current server then it will ask us to link the external server.

The following system stored procedure will be used to link the server.

sp_addlinkedserver
'Server name'
The following system catalog table is used to see the list of linked servers.

SELECT
* FROM SYS.SERVERS
INSTEAD OF Triggers on the Indexed View

Normally the triggers cannot be created on the view. But sql server 2005 onwards we can create the INSTEAD OF trigger on the indexed views.

USE
[Northwind]
GO
IF OBJECT_ID('[DBO].[VW_Trigger_Example') IS NOT NULLBEGIN   DROP VIEW [DBO].[VW_Trigger_Example]
   PRINT '[DBO].[VW_Trigger_Example view dropped..'
ENDGOCREATE VIEW [DBO].[VW_Trigger_Example]WITH SCHEMABINDINGAS  SELECT P.ProductID,P.ProductName,P.SupplierID,         OD.OrderID,OD.UnitPrice,OD.Quantity
  FROM [DBO].Products P
  INNER JOIN [DBO].[Order Details] OD ON OD.ProductID = P.ProductID
GO
IF OBJECT_ID('[DBO].[VW_Trigger_Example') IS NOT NULLBEGIN   PRINT '[DBO].[VW_Trigger_Example view created..'ENDGO--SELECT * FROM VW_Trigger_ExampleIF OBJECT_ID('[DBO].Tr_Delete_TriggerExample','TR') IS NOT NULLBEGIN  DROP TRIGGER [DBO].Tr_Delete_TriggerExample
  PRINT '[DBO].Tr_Delete_TriggerExample trigger dropped..'
ENDGOCREATE TRIGGER [DBO].Tr_Delete_TriggerExampleON [DBO].VW_Trigger_ExampleINSTEAD OF DELETEAS
BEGIN
   PRINT '----------------------------------------'   PRINT 'This is an example of INSTEAD OF Trigger'   PRINT '----------------------------------------'   SELECT TOP 1 * FROM DELETEDENDGOIF OBJECT_ID('[DBO].Tr_Delete_TriggerExample','TR') IS NOT NULLBEGIN  PRINT '[DBO].Tr_Delete_TriggerExample trigger created..'ENDGO--O/P
--SELECT * FROM [DBO].[VW_Trigger_Example] WHERE ProductID = 11
DELETE FROM [DBO].[VW_Trigger_Example] WHERE ProductID=11
How to view the Created Views?

There are few ways to view the scehema definition of the created views.

SP_HELPTEXT
vw_LocalPartion_ViewSELECT id,text FROM SYSCOMMENTS WHERE id = OBJECT_ID('[DBO].vw_LocalPartion_View')SELECT object_id,definition FROM SYS.SQL_MODULES WHERE OBJECT_ID = OBJECT_ID('[DBO].vw_LocalPartion_View')
How to drop the View?

If you want to drop the view then you can use the following statement. When you drop the table underlying view will not be deleted. But if you run that view it will thrown an error.

DROP VIEW VIEW_NAME

How to alter the view?

If you want to do changes in the created views then you can alter the view whatever you want to view the same view name.

ALTER VIEW VIEW_NAME
AS
SELECT [Columns List]....

Sunday, June 24, 2012

C++ Get CPU and Memory Utilisation

Write and compile the application

  1. While you can get Memory status fairly easlily with GlobalMemoryStatusEx, there is no equivalent function for CPU. Therefore you have to use PDH Performance Counter Interface to get CPU utilisation. Write the application and save is as check.cpp.

    Also note that CPU is a difference between two PdhCollectQueryData calls, so if you call this once and try to get PdhGetFormattedCounterValue you will get an error.

WPF Controls Progrrammatically

Let’s create a sample app, and add a new window. I named mine AddControls. Here’s the XAML:


<Window x:Class=WPFSample001.AddControls
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    Title=AddControls Height=114 Width=212
    >
  <StackPanel Name=splMain>
    <Button Name=btnAddMore Click=btnAddMore_Click>Add Another</Button>
  </StackPanel>
</Window>


And here’s what it looks like:
wpf029
A few things I’d like to point out. I’ve given a name to the StackPanel, so it can be manipulated in our C# code. I also added a handler for the Click event for the button, btnAddMore_Click. I also named the button, although it really wasn’t necessary for this sample.
OK, make sure to build the app so intellisense will work, then let’s jump to the C# code behind. (You may get an error about the click handler for the button not being found, that’s fine just ignore it.)
First, we’ll create an event handler for the button, passing in the sender and routed event args, like I discussed yesterday (http://arcanecode.wordpress.com/2007/09/05/the-wpf-button/) . Then, all we have to do is create a button control and add it to the children collection of the StackPanel, like so:

    public void btnAddMore_Click(object sender, RoutedEventArgs e)
    {
      System.Windows.Controls.Button newBtn = new Button();
      newBtn.Content = “A New Button”;
      splMain.Children.Add(newBtn);
    } 

Note in this example I used the fully qualified System.Windows.Controls, I did that just to be explicit where the Button came from. After a new button is created, I set it’s Content property, which in this case will be the text on the button.
In the final line, I add it to the children collection of the StackPanel. When you run it, and press the “Add Another” Button, you will see:
wpf030
Now we have a new problem. We’ve added a button to the StackPanel, but clicking on it does no good as we haven’t tied it to an event handler. Turns out that’s pretty easy too.


    public void btnAddMore_Click(object sender, RoutedEventArgs e)
    {
      System.Windows.Controls.Button newBtn = new Button();
      newBtn.Content = “A New Button”;
      newBtn.Click += new RoutedEventHandler(newBtn_Click);
      splMain.Children.Add(newBtn);
    }



What I did was use a delegate. I added a new RoutedEventHandler and tied it to the click event. The code for the event is in a method named newBtn_Click:

    private void newBtn_Click(object sender, RoutedEventArgs e)
    {
      MessageBox.Show(“New Button Clicked!”, “I got pressed.”);
    }

The signature for the event handler has to match the signature for a Click event, since that’s what we’re routing to. Here, all I do is display a message box just so you can see something got done. Run it again and press the Add Another button, and the “A New Button” should appear. Press the new button and you should see a message box.
wpf031
Finally, I want to be clear you can use this technique to add any sort of control. Here I’ve added a Label as well as a button:

    public void btnAddMore_Click(object sender, RoutedEventArgs e)
    {
      System.Windows.Controls.Button newBtn = new Button();
      newBtn.Content = “A New Button”;
      newBtn.Click += new RoutedEventHandler(newBtn_Click);
      splMain.Children.Add(newBtn);

      System.Windows.Controls.Label newLbl = new Label();
      newLbl.Content = “Hi Mom!”;
      splMain.Children.Add(newLbl);
    }

wpf032

I could have created the entire form in C# (or VB.Net) code, adding the StackPanel directly to the “this” object. However, that gets a bit laborious, and I wouldn’t recommend it as a general practice.