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.

Full Text Search In Sql Server 2008

The first query simply returns a list of all of the catalogs in the system.
– Get current list of full text catalogs
select [name] as CatalogName
    , path
    , is_default
  from sys.fulltext_catalogs
 order by [name];

The next query returns a list of all the StopLists. 

 – Get the list of StopLists
 select stoplist_id
      , name
   from sys.fulltext_stoplists;

This query returns a list of StopWords in the database. Note the linking to get the associated StopList name and language. 

 – Get list of StopWords
 select sl.name as StopListName
      , sw.stopword as StopWord
      , lg.alias as LanguageAlias
      , lg.name  as LanguageName
      , lg.lcid  as LanguageLCID
   from sys.fulltext_stopwords sw
   join sys.fulltext_stoplists sl
    on sl.stoplist_id = sw.stoplist_id
   join master.sys.syslanguages lg
    on lg.lcid = sw.language_id;


This next query gets a list of all of the stopwords that ship with SQL Server 2008. This is a nice improvement, you can not do this in SQL Server 2005.


– Get a list of the System provided stopwords  
select ssw.stopword
    , slg.name
  from sys.fulltext_system_stopwords ssw
  join sys.fulltext_languages slg
    on slg.lcid = ssw.language_id;


My next query returns a list of all the Full Text Indexes in the database.


– List full text indexes
select c.name as CatalogName
    , t.name as TableName
    , idx.name as UniqueIndexName
    , case i.is_enabled
        when 1 then ‘Enabled’
        else ‘Not Enabled’
       end as IsEnabled
    , i.change_tracking_state_desc
    , sl.name as StopListName
  from sys.fulltext_indexes i
  join sys.fulltext_catalogs c
    on i.fulltext_catalog_id = c.fulltext_catalog_id
  join sys.tables t
    on i.object_id = t.object_id
  join sys.indexes idx
    on i.unique_index_id = idx.index_id
       and i.object_id = idx.object_id
  left join sys.fulltext_stoplists sl
    on sl.stoplist_id = i.stoplist_id




This query returns a list of all the document types SQL Server 2008 understands when they are placed in a varbinary(max) field.


– List all of the document types SQL Server 2008 will understand in varbinary(max) field
select document_type
    , path
    , [version]
    , manufacturer
  from sys.fulltext_document_types;

If your full text performance begins to suffer over time, you might want to check and see how many fragments exist. If you have multiple closed fragments, you should consider doing a REORGANIZE on the index (using alter fulltext index). This query will tell you how many fragments exist for your full text index.


– See how many fragments exist for each full text index.
– If multiple closed fragments exist for a table do a REORGANIZE to help performance
select t.name as TableName
    , f.data_size
    , f.row_count
    , case f.status
        when 0 then ‘Newly created and not yet used’
        when 1 then ‘Being used for insert’
        when 4 then ‘Closed ready for query’
        when 6 then ‘Being used for merge inpurt and ready for query’
        when 8 then ‘Marked for deletion. Will not be used for query and merge source’
        else ‘Unknown status code’
       end
  from sys.fulltext_index_fragments f
  join sys.tables t on f.table_id = t.object_id;

There you go, a handful of powerful queries to help you query and maintain the state of your full text indexes.

Upload File Form in php

This below code allow user to upload image in web page that made in php program language .. 

html code : 

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html> 


the following about the HTML form above:
  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.


Create The Upload Script

The "upload_file.php" file contains the code for uploading a file:

<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?> 
 
 
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Restrictions on Upload

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>
Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.

Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server.
The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?> 
 
The script above checks if the file already exists, if it does not, it copies the file to the specified folder.

make rss feed in asp.net

Using the XmlTextWrite to output an XML file that serves as an RSS feed.

using System.Data.SqlClient;
using System.Text;
using System.Xml;
...
int copyrightyear = DateTime.Now.Year;
Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
writer.WriteElementString("title", "Mikesdotnetting News Feed");
writer.WriteElementString("link", 
  "http://www.mikesdotnetting.com/rss.aspx");
writer.WriteElementString("description", 
  "Latest additions to the rubbish that appears on Mikesdotnetting.com.");
writer.WriteElementString("copyright", "(c) " + copyrightyear.ToString() +
  ", Mikesdotnetting. All rights reserved.");
string connectionString = Utils.GetConnString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
  using (SqlCommand objCommand = new SqlCommand("GetRss", conn))
  {
    objCommand.CommandType = CommandType.StoredProcedure;
    conn.Open();
    using (SqlDataReader objReader = objCommand.ExecuteReader())
    {
      while (objReader.Read())
      {
        writer.WriteStartElement("item");
        writer.WriteElementString("title", objReader.GetString(1));
        writer.WriteElementString("description", objReader.GetString(2));
        writer.WriteElementString("link", "http://www.mikesdotnetting.com/Article.aspx?ArticleID=
          " + objReader.GetInt32(0).ToString());
        writer.WriteElementString("pubDate", 
          objReader.GetDateTime(3).ToString("R"));
        writer.WriteEndElement();
      } 
      objReader.Close();
      conn.Close();
      writer.WriteEndElement();
      writer.WriteEndElement();
      writer.WriteEndDocument();
      writer.Flush();
      writer.Close();
      Response.End();
    }
  }
}

Rss File Code Project

Having an RSS feed on your website is a great way of sharing your content with the rest of the Internet. It’s not a new technology and it’s probably something that you use on a daily basis. If you have a blog or use any form of CMS, that software will most likely handle the creation of your RSS feed for you.
Sometimes, however, it might be necessary for you to create a RSS feed yourself. Perhaps you have just won a new client who’s current site has a old bespoke CMS which they like and want to keep, but you want to be able to publish their updated content via RSS. Hopefully this tutorial will help you to achieve this.

What is RSS?

RSS, in its current form, stands for Really Simple Syndication and is a family of web formats to publish frequently updated content. The RSS Feed (as it is commonly known) can then be read by the users feed reading software or by another website which wishes to ‘syndicate’ the content of that feed.

The RSS format is based on XML that is built using standardised tags. Here is an example of a basic RSS document, we will be generating something similar using PHP later in this tutorial:



01
02
03
04
05     
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
    <channel>
        <title>My RSS feed</title>
        <link>http://www.mywebsite.com/</link>
        <description>This is an example RSS feed</description>
        <language>en-us</language>
        <copyright>Copyright (C) 2009 mywebsite.com</copyright>
        <item>
            <title>My News Story 3</title>
            <description>This is example news item</description>
            <link>http://www.mywebsite.com/news3.html</link>
            <pubDate>Mon, 23 Feb 2009 09:27:16 +0000</pubDate>
        </item>
        <item>
            <title>My News Story 2</title>
            <description>This is example news item</description>
            <link>http://www.mywebsite.com/news2.html</link>
            <pubDate>Wed, 14 Jan 2009 12:00:00 +0000</pubDate>
        </item>
        <item>
            <title>My News Story 1</title>
            <description>This is example news item</description>
            <link>http://www.mywebsite.com/news1.html</link>
            <pubDate>Wed, 05 Jan 2009 15:57:20 +0000</pubDate>
        </item>
    </channel>
  </rss>




As we know, RSS is made up of standardised XML tags which you would normally find in a flat XML file. What we are going to do is create this standard XML data dynamically using PHP. This means that the URL for our feed will end with the .php extension, but we will tidy this up later in the tutorial.
So, lets start building the PHP script. The first thing we are going to do is tell PHP what type of data we would like to output (I am going to break each section of the script down, but I will include it in full at the end):

1
2
<?php
    header("Content-Type: application/rss+xml; charset=ISO-8859-1");
The header() function that we have called is telling PHP to output our data using the XML MIME type as well as to use the ISO-8859-1 character set. This makes sure that our content is delivered to the users in the correct format.
Now we are going to define our database connection details and create the header XML tags for our RSS feed. I’m going to statically assign the feed information tags just to keep it simple, however, you may wish to expand on this to dynamically set these. That way, you can re-use this code as a function or even go a step further and use it to build your own PHP class. The actual feed data will be kept in a variable called $rssfeed.
 
01
02   
03
04
05
06
07
08
09
10
11
12
13
DEFINE ('DB_USER', 'my_username');
DEFINE ('DB_PASSWORD', 'my_password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'my_database');
 
$rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>My RSS feed</title>';
$rssfeed .= '<link>http://www.mywebsite.com </link>';
$rssfeed .= '<description>This is an example RSS feed</description>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';
Next, we need to extract our data by looping through our MySQL database to create the <item> tags. I’m not going to explain this part in too much details as it’s not point of this tutorial and you may do this differently. We are going to assume that our MySQL table (“mytable”) has columns called title, description, link and date which hold the relevant data:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 <?php  
 $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');
 
    $query = "SELECT * FROM mytable ORDER BY date DESC";
    $result = mysql_query($query) or die ("Could not execute query");
 
    while($row = mysql_fetch_array($result)) {
        extract($row);
 
        $rssfeed .= '<item>';
        $rssfeed .= '<title>' . $title . '</title>';
        $rssfeed .= '<description>' . $description . '</description>';
        $rssfeed .= '<link>' . $link . '</link>';
        $rssfeed .= '<pubDate>' . date("D, d M Y H:i:s O", strtotime($date)) . '</pubDate>';
        $rssfeed .= '</item>';
    }
 
    $rssfeed .= '</channel>';
    $rssfeed .= '</rss>';
 
    echo $rssfeed;
 ?>
The first part of this section connects to the MySQL database using the constants which we defined at the start of the script. Then we perform a basic SQL query to pull out all our data from the database in date order. The final part of the query, DESC, ensures that the newest content will appear first in the users RSS reader.
Next, we look at each row of data from the results of the query using a while loop. In each loop cycle, the first action performed is the extract() function to create a set of variables that take the name of the columns of the database, in my case $title, $description, $link, and $date. We then add the data contained in these variables to our main $rssfeed variable. When it reaches the final row of data, the while loop ends and we apply the closing XML tags.
The final step of the script is to actually output the data we have collected. This is simply done by echoing the $rssfeed variable. Here is the code in full:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
    header("Content-Type: application/rss+xml; charset=ISO-8859-1");
 
    DEFINE ('DB_USER', 'my_username');
    DEFINE ('DB_PASSWORD', 'my_password');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'my_database');
 
    $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
    $rssfeed .= '<rss version="2.0">';
    $rssfeed .= '<channel>';
    $rssfeed .= '<title>My RSS feed</title>';
    $rssfeed .= '<link>http://www.mywebsite.com</link>';
    $rssfeed .= '<description>This is an example RSS feed</description>';
    $rssfeed .= '<language>en-us</language>';
    $rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';
 
    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');
 
    $query = "SELECT * FROM mytable ORDER BY date DESC";
    $result = mysql_query($query) or die ("Could not execute query");
 
    while($row = mysql_fetch_array($result)) {
        extract($row);
 
        $rssfeed .= '<item>';
        $rssfeed .= '<title>' . $title . '</title>';
        $rssfeed .= '<description>' . $description . '</description>';
        $rssfeed .= '<link>' . $link . '</link>';
        $rssfeed .= '<pubDate>' . date("D, d M Y H:i:s O", strtotime($date)) . '</pubDate>';
        $rssfeed .= '</item>';
    }
 
    $rssfeed .= '</channel>';
    $rssfeed .= '</rss>';
 
    echo $rssfeed;
?>


I mentioned earlier that I would tidy up the .php extension of the feed. I don’t know about you, but I find this a little bit ugly. When you see RSS feeds that have been generated by WordPress for example, you don’t see the actual file name, you just get the containing folder. To do this, create a folder in the root directory of the site and call it ‘feed’. Create a file in this new folder called ‘index.php’ and copy the code above into it. This leaves us with a nicer looking feed URL, in the case of this example, http://www.mydomain.com/feed/.