06 December 2011

Ottiene la versione del FILE dell'assembly

        Shared Function GetFileVersion() As String

            Dim res As String = ""

            'Dim asm As Reflection.Assembly = Reflection.Assembly.GetExecutingAssembly()
            Dim asm As Reflection.Assembly = Reflection.Assembly.GetCallingAssembly

            Dim fvi As FileVersionInfo = FileVersionInfo.GetVersionInfo(asm.Location)

            res = fvi.FileVersion

            fvi = Nothing
            asm = Nothing

            Return res

        End Function

24 November 2011

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record

SELECT @@IDENTITY

It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY()

It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT('tablename')

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.

Trovato qui.

Nota:

se si usa con un ADODB.Recordset, con un'istruzione del genere:
INSERT INTO DataSheet(databaseUserID, currentTimestamp)
VALUES (1, CURRENT_TIMESTAMP);
SELECT SCOPE_IDENTITY()
bisogna aprire il recordset con
Set rs = rs.NextRecordset
perché
You are executing two statements so you will get two results back. the recordset object can only hold one result at a time - to get the other result you need to use the NextRecordset method.

Trovato qui.

16 November 2011

Eliminare tutti gli oggetti di un database / Delete all database objects

Script che genera lo script per eliminare tutti gli oggetti di un database:
This script removes all database objects:
SET NOCOUNT ON

SELECT '-- SCRIPT PER ELIMINARE TUTTI GLI OGGETTI DI UN DB --' = ''

-- procedures
union SELECT '/*A*/ DROP PROCEDURE [' + name + ']'
from sys.procedures

UNION

-- check constraints
SELECT '/*B*/ ALTER TABLE [' + object_name( parent_object_id ) + '] DROP CONSTRAINT [' + name + ']'
from sys.check_constraints

UNION

-- functions
SELECT '/*C*/ DROP FUNCTION [' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )

UNION

-- views
SELECT '/*D*/ DROP VIEW [' + name + ']'
from sys.views

UNION

-- foreign keys
SELECT '/*E*/ ALTER TABLE [' + object_name( parent_object_id ) + '] DROP CONSTRAINT [' + name + ']'
from sys.foreign_keys

UNION

-- tables
SELECT '/*F*/ DROP TABLE [' + name + ']'
from sys.tables

UNION

-- user defined types
SELECT '/*G*/ DROP TYPE [' + name + ']'
from sys.types
where is_user_defined = 1
Testato su SQL 2008.

07 November 2011

Ottenere la versione del file in esecuzione

Un po' pedestre:
Dim fullPath As String = ""
fullPath &= My.Application.Info.DirectoryPath & "\" &
fullPath &= My.Application.Info.AssemblyName & ".exe"

Return FileVersionInfo.GetVersionInfo(fullPath).FileVersion
Migliorabile la parte per recuperare il fullPath dell'assembly corrente.

03 November 2011

VB.NET and C# Comparison

Scarica il PDF! =)

Trovato qui.

21 October 2011

Use asp:Menu and asp:MultiView to create tab control

/*
ASP.NET 2.0 Unleashed (Unleashed) (Hardcover)
by Stephen Walther 

# Publisher: Sams; Bk&CD-Rom edition (June 6, 2006)
# Language: English
# ISBN: 0672328232
*/

<%@ Page Language="C#" %>




    
    MultiView Tabs


    

This is the first view
This is the first view
This is the first view
This is the first view

This is the second view
This is the second view
This is the second view
This is the second view

This is the third view
This is the third view
This is the third view
This is the third view

Trovato qui.

Why you should not shrink your data files

One of my biggest hot-buttons is around shrinking data files. Although I used to own the shrink code while I was at Microsoft, I never had a chance to rewrite it so that data file shrink is a more palatable operation. I really don't like shrink.

Now, don't confuse shrinking the transaction log with shrinking data files. Shrinking the log is necessary if your log has grown out of control, or as part of a process to remove excessive VLF fragmentation. However, shrinking the log should be a rare operation and should not be part of any regular maintenance you perform.

Shrinking of data files should be performed even more rarely, if at all. Here's why - data file shrink causes *massive* index fragmentation. Let me demonstrate with a simple script you can run. The script below will create a data file, create a 10MB 'filler' table at the start of the data file, create a 10MB 'production' clustered index, drop the 'filler' table and then run a shrink to reclaim the space.
USE MASTER;
GO

IF DATABASEPROPERTYEX ('DBMaint2008', 'Version') > 0
 DROP DATABASE DBMaint2008;

CREATE DATABASE DBMaint2008;
GO
USE DBMaint2008;
GO

SET NOCOUNT ON;
GO

-- Create the 10MB filler table at the 'front' of the data file
CREATE TABLE FillerTable (c1 INT IDENTITY,  c2 CHAR (8000) DEFAULT 'filler');
GO

-- Fill up the filler table
INSERT INTO FillerTable DEFAULT VALUES;
GO 1280

-- Create the production table, which will be 'after' the filler table in the data file
CREATE TABLE ProdTable (c1 INT IDENTITY,  c2 CHAR (8000) DEFAULT 'production');
CREATE CLUSTERED INDEX prod_cl ON ProdTable (c1);
GO

INSERT INTO ProdTable DEFAULT VALUES;
GO 1280

-- check the fragmentation of the production table
SELECT [avg_fragmentation_in_percent] FROM sys.dm_db_index_physical_stats (
    DB_ID ('DBMaint2008'), OBJECT_ID ('ProdTable'), 1, NULL, 'LIMITED');
GO

-- drop the filler table, creating 10MB of free space at the 'front' of the data file
DROP TABLE FillerTable;
GO

-- shrink the database
DBCC SHRINKDATABASE (DBMaint2008);
GO

-- check the index fragmentation again
SELECT [avg_fragmentation_in_percent] FROM sys.dm_db_index_physical_stats (
    DB_ID ('DBMaint2008'), OBJECT_ID ('ProdTable'), 1, NULL, 'LIMITED');
GO

avg_fragmentation_in_percent
----------------------------
0.390625

DbId   FileId      CurrentSize MinimumSize UsedPages   EstimatedPages
------ ----------- ----------- ----------- ----------- --------------
6      1           1456        152         1448        1440
6      2           63          63          56          56

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

avg_fragmentation_in_percent
----------------------------
99.296875
Look at the output from the script! The logical fragmentation of the clustered index before the shrink is a near-perfect 0.4%. After the shrink, it's almost 100%. The shrink operation *completely* fragmented the index, removing any chance of efficient range scans on it by ensuring the all range-scan readahead I/Os will be single-page I/Os.

Why does this happen? A data file shrink operation works on a single file at a time, and uses the GAM bitmaps (see Inside The Storage Engine: GAM, SGAM, PFS and other allocation maps) to find the highest page allocated in the file. It then moves it as far towards the front of the file as it can, and so on, and so on. In the case above, it completely reversed the order of the clustered index, taking it from perfectly defragmented to perfectly fragmented.

The same code is used for DBCC SHRINKFILE, DBCC SHRINKDATABASE, and auto-shrink - they're equally as bad. As well as introducing index fragmentation, data file shrink also generates a lot of I/O, uses a lot of CPU, and generates *loads* of transaction log - as everything it does is fully logged.

Data file shrink should never be part of regular maintenance, and you should NEVER, NEVER have auto-shrink enabled. I tried to have it removed from the product for SQL 2005 and SQL 2008 when I was in a position to do so - the only reason it's still there is for backwards compatibility. Don't fall into the trap of having a maintenance plan that rebuilds all indexes and then tries to reclaim the space required to rebuild the indexes by running a shrink - that's a zero-sum game where all you do is generate a log of transaction log for no actual gain in performance.

So what if you *do* need to run a shrink? For instance, if you've deleted a large proportion of a very large database and the database isn't likely to grow, or you need to empty a file before removing it?

The method I like to recommend is as follows:

Create a new filegroup
Move all affected tables and indexes into the new filegroup using the CREATE INDEX ... WITH (DROP_EXISTING) ON filegroup syntax, to move the tables and remove fragmentation from them at the same time
Drop the old filegroup that you were going to shrink anyway (or shrink it way down if its the primary filegroup)
Basically you need to provision some more space before you can shrink the old files, but it's a much cleaner mechanism.

If you absolutely have no choice and have to run a data file shrink operation, be aware that you're going to cause index fragmentation and you should take steps to remove it afterwards if it's going to cause performance problems. The only way to remove index fragmentation without causing data file growth again is to use DBCC INDEXDEFRAG or ALTER INDEX ... REORGANIZE. These commands only require a single 8KB page of extra space, instead of needing to build a whole new index in the case of an index rebuild operation.

Bottom line - try to avoid running data file shrink at all costs!


Trovato qui.
Altre info su SqlAuthority.

07 October 2011

SQL SERVER – The Self Join – Inner Join and Outer Join

July 8, 2010 by pinaldave

Self Join has always been an note-worthy case. It is interesting to ask questions on self join in a room full of developers. I often ask – if there are three kind of joins, i.e.- Inner Join, Outer Join and Cross Join; what type of join is Self Join? The usual answer is that it is an Inner Join. In fact, it can be classified under any type of join. I have previously written about this in my interview questions and answers series. I have also mentioned this subject when I explained the joins in detail over SQL SERVER – Introduction to JOINs – Basic of JOINs.
When I mention that Self Join can be the outer join, I often get a request for an example for the same. I have created example using AdventureWorks Database of Self Join earlier, but that was meant for inner join as well. Let us create a new example today, where we will see how Self Join can be implemented as an Inner Join as well as Outer Join.
Let us first create the same table for an employee. One of the columns in the same table contains the ID of manger, who is also an employee for the same company. This way, all the employees and their managers are present in the same table. If we want to find the manager of a particular employee, we need use self join.

USE TempDb
GO
-- Create a Table
CREATE TABLE Employee(
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(50),
ManagerID INT
)
GO
-- Insert Sample Data
INSERT INTO Employee
SELECT 1, 'Mike', 3
UNION ALL
SELECT 2, 'David', 3
UNION ALL
SELECT 3, 'Roger', NULL
UNION ALL
SELECT 4, 'Marry',2
UNION ALL
SELECT 5, 'Joseph',2
UNION ALL
SELECT 7, 'Ben',2
GO
-- Check the data
SELECT *
FROM Employee
GO
We will now use inner join to find the employees and their managers’ details.

-- Inner Join
SELECT e1.Name EmployeeName, e2.name AS ManagerName
FROM Employee e1
INNER JOIN Employee e2
ON e1.ManagerID = e2.EmployeeID
GO
From the result set, we can see that all the employees who have a manager are visible. However we are unable to find out the top manager of the company as he is not visible in our resultset. The reason for the same is that due to inner join, his name is filtered out. Inner join does not bring any result which does not have manager id. Let us convert Inner Join to Outer Join and then see the resultset.

-- Outer Join
SELECT e1.Name EmployeeName, ISNULL(e2.name, 'Top Manager') AS ManagerName
FROM Employee e1
LEFT JOIN Employee e2
ON e1.ManagerID = e2.EmployeeID
GO

Once we convert Inner Join to Outer Join, we can see the Top Manager as well. Here we have seen how Self Join can behave as an inner join as well as an outer join.
As I said earlier, many of you know these details, but there are many who are still confused about this concept. I hope that this concept is clear from this post.


Trovato qui.

05 October 2011

Personalizzare confirm OnClientClick


Protected Sub gridDocs_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridDocs.RowDataBound

  With e.Row
    If .RowType = DataControlRowType.DataRow Then

      Dim s As String = "return confirm('Eliminare il documento \'"
      s &= DataBinder.Eval(.DataItem, f1.Descrizione.ToString).ToString & "\'?');"

      Dim btn As Button = CType(.FindControl("cmdDelete"), Button)
      btn.OnClientClick = s

    End If
  End With

End Sub

21 September 2011

Login via software

Shared Function LoginUser(ByVal userName As String, ByVal password As String) As Boolean

        Dim res As Boolean = Membership.ValidateUser(userName, password)

        If res Then
            Response.Cookies.Remove(FormsAuthentication.FormsCookieName)
            FormsAuthentication.SetAuthCookie(userName, False)
        End If

        Return res

    End Function

31 August 2011

Cambiare lo schema di tutte le tabelle

1) Lanciare questo script:
DECLARE @schemaFROM AS nvarchar(200); SET @schemaFROM = 'MSSql49479'
DECLARE @schemaTO AS nvarchar(200); SET @schemaTO = 'dbo'
 
DECLARE tabcurs CURSOR FOR
SELECT @schemaFROM + '.' + '[' +  [name] + ']'
FROM sysobjects
WHERE xtype IN ('u', 'p', 'fn', 'fs', 'ft', 'tf', 'v', 'if')
 
OPEN tabcurs
DECLARE @tname NVARCHAR(517)
FETCH NEXT FROM tabcurs INTO @tname
 
WHILE @@fetch_status = 0
    BEGIN
        PRINT ''
        PRINT 'Changing ' + @tname
        EXEC sp_changeobjectowner @tname, @schemaTO

        FETCH NEXT FROM tabcurs INTO @tname
    END
 
CLOSE tabcurs
DEALLOCATE tabcurs
 
PRINT '
Done.'

2) Rifare gli script per View, Stored Procedure, Funzioni, ecc: al loro interno potrebbe essere presente il vecchio schema!!

Utile per i db ripristinati da aruba...


Testato su Sql2005, Sql2008 Express, Sql2008R2
Trovato qui.

19 July 2011

Configurazione tastiera SQL Management Studio e ut_VisDipendenze_sq

Ctrl+3SELECT TOP 9 * FROM
Ctrl+4EXEC sp_help
Ctrl+5SELECT * FROM
Ctrl+6EXEC sp_helptext
Ctrl+7EXEC ut_VisDipendenze_sq
Ctrl+8SELECT TOP 20 * FROM sys.objects X ORDER BY X.modify_date DESC
Ctrl+0SELECT FORMAT(COUNT(*), 'N0') AS [Conta Record] FROM


CREATE PROCEDURE ut_VisDipendenze_sq
(
 @objectName AS nvarchar(1000)
)
AS
BEGIN
 --##2019-09-17 - Boso -           OBJECT_DEFINITION
 SET NOCOUNT ON
 
 IF CHARINDEX('.', @objectName) = 0
  SET @objectName = 'dbo.' + @objectName


 DECLARE @objectId int = OBJECT_ID(@objectName)


 SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name, 
  o.type_desc AS referencing_desciption, 
  COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id, 
  referencing_class_desc,
  referenced_server_name, referenced_database_name, referenced_schema_name,
  referenced_entity_name
  , OBJECT_DEFINITION(OBJECT_ID(referenced_entity_name)) AS referenced_Definition
  , COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name,
  is_caller_dependent, is_ambiguous
 FROM sys.sql_expression_dependencies AS sed
 INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id
 WHERE referencing_id = @objectId
 ORDER BY referencing_entity_name, referencing_desciption



 SELECT OBJECT_SCHEMA_NAME ( referencing_id ) AS referencing_schema_name,
  OBJECT_NAME(referencing_id) AS referencing_entity_name, 
  o.type_desc AS referencing_desciption
  , OBJECT_DEFINITION(o.object_id) AS referencing_Definition
  , COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id, 
  referencing_class_desc, referenced_class_desc,
  referenced_server_name, referenced_database_name, referenced_schema_name,
  referenced_entity_name, 
  COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name,
  is_caller_dependent, is_ambiguous
 FROM sys.sql_expression_dependencies AS sed
   INNER JOIN sys.objects AS o 
    ON sed.referencing_id = o.object_id
 WHERE referenced_id = @objectId
 ORDER BY referencing_entity_name, referencing_desciption



 -- HACK: Returning cross-database dependencies
 -- https://msdn.microsoft.com/en-us/library/bb677315.aspx?f=255&MSPPError=-2147217396

END
GO

15 July 2011

Rinumerare le righe ad ogni cambio della chiave di testata

Nel caso di una tabella di righe, voglio rinumerare il prog ad ogni cambio di id:

-- CREO TABELLA DELLE RIGHE
declare @tmp table 
(
	  id int
	, prog int 
	, primary key (id,prog)
)


-- RIEMPIO CON VALORI 
insert @tmp select 1, 11
insert @tmp select 2, 22
insert @tmp select 2, 33
insert @tmp select 3, 44


--select * from @tmp


-- RINUMERO A PARTIRE DA 1 (ALTRIMENTI NON FUNZIONA!!)
declare @p int;set @p = 0
	
UPDATE	@tmp
SET		@p = prog = @p + 1



--select * from @tmp



-- TABELLA CON I NUOVI prog
declare @num as table
(
	  id int
	, prog int
	, oldProg int
	, primary key (id,prog)
)



-- MAGIA!!!!
insert @num
select
    T.id,
    T.prog - n,
    T.prog 
from
    @tmp T left join 
    (
        select 
            T.id, 
            count(distinct  T2.prog ) as n
        from 
            @tmp T left join 
            @tmp T2 on 
                T2.id < T.id
        group by
            T.id
    ) as P    on
        T.id=P.id


select * from @num


-- AGGIORNA NUOVI prog
update	t
set		t.prog = n.prog
from	@tmp t inner join 
		@num n on
			t.id = n.id
		and t.prog = n.oldProg
		


select * from @tmp

Trovato nel cervello del Faro.

11 July 2011

Get SQL Server version / Leggi la versione di SQL Server

SELECT SERVERPROPERTY('Edition') AS Edition,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('ProductVersion') AS ProductVersion

24 June 2011

Metodo rapido per creare una Primary Key con più campi

DECLARE @tab TABLE 
(
	  IDArgomento int NOT NULL
	, TipoPagina nvarchar(20) NOT NULL
	, Sezione nvarchar(10) NOT NULL
	, MaxBanner smallint NULL
	, Larghezza int NULL
	, Altezza int NULL
	, PosLeft int NULL
	, PosTop int NULL
	, PosRight int NULL
	, PosBottom int NULL
	, PRIMARY KEY (IDArgomento, TipoPagina, Sezione)
)
Questa sintassi è valida anche con:
  • variabili di tipo TABLE (quindi anche in funzioni che ritornano tabelle!)
  • tabelle temporanee

30 May 2011

Method Overloading in Web Services

By default Web Services do not support ‘Method Overloading’.

Reason: when data is passed to an XML Web service it is sent in a request and when it is returned it is sent in a response. Therefore, if an XML Web service contains two or more XML Web service methods with the same name, no uniquely identification will be there. Hence it will produce error.

Solution: To resolve this, MessageName property is required to be attached to Web Method - To uniquely identify polymorphic methods.
public class Calculator : WebService
{
    [WebMethod]
    public int Add(int i, int j) {
       return i + j;
    } 

    [WebMethod(MessageName="Add2")]
    public int Add(int i, int j, int k) {
       return i + j + k;
    }
}


This works perfectly well in .Net 1.x. But in .Net 2.0 this solution solves only one problem. The other problem is related to the ‘Conformity to WS-I Basic Profile v1.1’.

Reason: in .Net 2.0, by default below two attributes are added to the Web Service Class.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    // blah
}

This line indicates that your webservice conforms to the Web Services Interopability Organization's (WS-I) Baisc Profile 1.1. The Basic Profile defines a set of rules to which your webservice must conform.

One of its rules is that the webservice May Not Include Method Overloading. If you run a webservice that uses method overloading, you will receive an errormessage telling that your service is not conform to WS-I Basic Profile v1.1:

This produces below error once you have equiped the ‘Web Method’ with ‘MessageName’ property.

Solution: to resolve this error, modify the attribute as:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]

Complete code:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
public class Service : System.Web.Services.WebService
{
    public Service () {
    }

    [WebMethod]
    public string HelloWorld()
    {     
        return "hello";
    }

    [WebMethod(MessageName = "HelloWorld2")]
    public string HelloWorld(int i)
    {
        return "Overloading";
    }  
}

Trovato qui.

04 May 2011

Convertire una List(Of String) in List(Of Integer)

Dim tmp As List(Of String)(New String() {"1", "2"",3"})

Dim conv As New Converter(Of String, Integer)(AddressOf Convert.ToInt32)

Dim id As List(Of Integer) = tmp.ConvertAll(conv)

Trovato qui.

28 April 2011

How to Rebuild the Icon Cache in Windows Vista and Windows 7

My earlier post Incorrect icon shown for a file type in Vista (March 31, 2008) tells you how to refresh the shell icons in Vista. In case the solution posted in that link does not help, you may want to clear the icon cache database. The icon cache can be cleared by deleting the hidden file named IconCache.db in the following location:

%userprofile%\AppData\Local

Note: %userprofile% represents the path to user profile folder.

Rebuilding the Icon Cache Database

1. Close all folder windows that are currently open.

2. Launch Task Manager using the CTRL+SHIFT+ESC key sequence, or by running taskmgr.exe.

3. In the Process tab, right-click on the Explorer.exe process and select End Process.

4. Click the End process button when asked for confirmation.

5. From the File menu of Task Manager, select New Task (Run…)

6. Type CMD.EXE, and click OK

7. In the Command Prompt window, type the commands one by one and press ENTER after each command:

CD /d %userprofile%\AppData\Local
DEL IconCache.db /a
EXIT

8. In Task Manager, click File, select New Task (Run…)

9. Type EXPLORER.EXE, and click OK.

 


 

An even easier way:

cmd /c taskkill /f /im explorer.exe && del %LocalAppData%\IconCache.db /a && explorer.exe

 

Trovato qui.

26 April 2011

Adding Facebook Share functionality to an ASP.NET web site with a Master Page

This article assumes the reader has experience developing web sites using ASP.NET, specifically using Master Pages. It also assumes a familiarity with Facebook. All sample code is in C#. After reading this article, you should be able to integrate Facebook Share with an ASP.NET web site, whether or not it contains a Master Page. I’ve chosen to illustrate this using a Master Page because it’s a little more involved, and once you can do it with a Master Page, you should be able to do it without one as well.

What is Facebook Share, and how does it work?

First, let’s review what Facebook Share actually is. Adding a Share widget to a web page allows a user to click on an icon which launches a Facebook Share dialog. If the user has a Facebook account, they can then share the web page on their Facebook “wall” with their friends on Facebook, adding comments if they so choose. Their friends will have the opportunity to share with their friends, and so on. In this way, a web page’s exposure can increase dramatically in a very short time.

According to the Facebook web site’s documentation there are five steps you need to take in order to integrate Share with a web page:

Step 1: Add a link to the Facebook Share application hosted by Facebook:
<a name="fb_share" type="button" 
href="http://www.facebook.com/sharer.php">Share</a>

Step 2: Add a script tag that points to a Javascript component hosted by Facebook:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" 
type="text/javascript"></script>

Step 3: Add a meta tag containing the title of the page:
<meta name="title" content="This is the Title" />

Step 4: Add a meta tag containing a description of the page:
<meta name="description"
content="This is a short summary of the page." />

Step 5: Add a link tag pointing to an image to be used as a logo:
<link rel="image_src" 
href="http://www.murrayhilltech.com/images/LogoColorNoText.jpg" />

The problem

All well and good, but we were talking about doing this while using a Master Page. See the problem yet? Well, if all the pages in our site use a common Master Page, which presumably contains the head tag, which in turn contains all the meta tags and link tags, how do we specify different tag values for different pages? Therein lies the problem. The solution lies in the code-behind file.

The solution

I’ve chosen to place the code for Steps 1 and 2 in the actual web page as opposed to the Master Page, since that will allow us the flexibility to place the Share widget in varying locations on each page should we care to do so. However, I’m going to accomplish this by inserting an empty asp:Label component in the desired location in the aspx file, and assigning the appropriate value to it in the Page_Load event in the code-behind file. I’m going to use the same asp:Label component to hold the code for both Steps 1 and 2:
// This code for the asp:Label component goes in the aspx file

<asp:Label ID="labelSteps_1_2" runat="server" Text=""></asp:Label>

// The code to populate the asp:Label component with the html and script code
// for Steps 1 and 2 should go in the code-behind file

labelSteps_1_2.Text = "<a name=\"fb_share\" type=\"button\"></a>" +
    "<script src=\"http://static.ak.fbcdn.net/connect.php/js/FB.Share\" " +
    "type=\"text/javascript\"></script>";
Next, we’ll instantiate a couple of HtmlMeta objects to handle the meta tags in Steps 3 and 4, also in the Page_Load event:
HtmlMeta tag = new HtmlMeta();
            tag.Name = "title";
            tag.Content = “This is the Title”;
            Page.Header.Controls.Add(tag);

            HtmlMeta tag = new HtmlMeta();
            tag.Name = "description";
            tag.Content = “This is a short summary of the page.”;
            Page.Header.Controls.Add(tag);
Finally, we’ll add the logo in Step 5 in the same Page_Load event using an HtmlLink object:
HtmlLink link = new HtmlLink();
            link.Href = “http://www.murrayhilltech.com/images/LogoColorNoText.jpg”;
            link.Attributes["rel"] = "image_src";
            Page.Header.Controls.Add(link);
Creating these elements dynamically in the code-behind file allows us to add them to the head element of the Master Page without ever actually modifying the Master Page. You can use this same method for pages and/or sites that don’t make use of Master Pages.

Putting it all together

The complete listing for the code-behind file is shown below. The only other change we made was to add that asp:Label control to the aspx file. Here’s the code behind file:
using System;
using System.Web.UI; using System.Web.UI.HtmlControls; using System.Net.Mail; namespace MHT_Web_Site { public partial class MyPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { labelSteps_1_2.Text = "<a name=\"fb_share\" type=\"button\"></a>" + "<script " + "src=\"http://static.ak.fbcdn.net/connect.php/js/FB.Share\" " + "type=\"text/javascript\"></script>"; HtmlMeta tag = new HtmlMeta(); tag.Name = "title"; tag.Content = “This is the Title”; Page.Header.Controls.Add(tag); HtmlMeta tag = new HtmlMeta(); tag.Name = "description"; tag.Content = “This is a short summary of the page.”; Page.Header.Controls.Add(tag); HtmlLink link = new HtmlLink(); link.Href = “http://www.murrayhilltech.com/images/LogoColorNoText.jpg”; link.Attributes["rel"] = "image_src"; Page.Header.Controls.Add(link); } catch (Exception ex) { // Handle the exception } } } }
I hope that this article helps you get started integrating Facebook with ASP.NET web sites. For more information, check Facebook’s web site. The documentation there is not organized very well, but it’s there if you dig for it.
 
Trovato qui.

21 April 2011

Disabling the button while the user wait

WebForm1.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebService1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button runat="server" ID="cmd1" Text="test..." Height="40px" Width="246px" />
        <p>
            <asp:Label runat="server" ID="lbl1" />
        </p>
    </div>
    </form>
</body>
</html>
WebForm1.aspx.vb (il trucco è la Me.cmd1.Attributes.Add alla riga 6):
Public Partial Class WebForm1
    Inherits System.Web.UI.Page

    Private Sub WebForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.cmd1.Attributes.Add("onclick", "this.value='Please wait...';this.disabled = true;" + ClientScript.GetPostBackEventReference(Me.cmd1, ""))

    End Sub

    Protected Sub cmd1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmd1.Click

        System.Threading.Thread.Sleep(1000 * 10)
        Me.lbl1.Text = Date.Now.ToString

    End Sub

End Class

Trovato qui.

19 April 2011

web.config: abilitare solo un utente

<!--<location path="AreaRiservata">-->
<location>
    <system.web>
        <authorization>
            <allow users="webmaster"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
Nota: i permessi sono letti in sequenza (nell’esempio: prima allow e poi deny).

30 March 2011

Funzioni che ritornano una TABLE (tabella)

Pare che non sia indispensabile specificare lo schema! :)
CREATE FUNCTION _boso_sf()
RETURNS TABLE 
AS
RETURN 
	(
		SELECT	TOP 2 *
		FROM	Pagine_tb
	)
GO


-- ESEMPIO 1
SELECT * FROM _boso_sf()


-- ESEMPIO 2
SELECT	*
FROM	Pagine_tb a INNER JOIN 
		_boso_sf() b ON 
			a.idpagina = b.idpagina


-- ESEMPIO 3
SELECT	*
FROM	pagine_tb a 
WHERE	a.idpagina in 
			(
				SELECT idpagina FROM _boso_sf()
			)


DROP FUNCTION _boso_sf

23 February 2011

Ottenere l’Url della pagina chiamante

Public Shared Function GetPaginaChiamante() As String

    Dim res As String = ""

    With System.Web.HttpContext.Current.Request
        If .UrlReferrer IsNot Nothing Then
            res = .UrlReferrer.ToString
        End If
    End With

    Return res

End Function

 

Esempio di utilizzo:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

    Me.btnAnnulla.PostBackUrl = GetPaginaChiamante

End Sub


Nota: La funzione GetPaginaChiamante() è nella ITovaglieri.Web.UI.Domain! :)

11 February 2011

Backup di tutti i db

EXEC sp_MSForEachDB  
'IF ''?'' NOT IN (''tempdb'') 
BEGIN
 PRINT ''''
 PRINT ''''
 DBCC checkdb (''?'')
 PRINT ''''
 PRINT ''''
 BACKUP DATABASE [?] TO  DISK = N''c:\Programmi\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\?.bak'' 
  WITH RETAINDAYS = 3, NOFORMAT, NOINIT,  NAME = N''? - Completo Database Backup'', SKIP, 
  NOREWIND, NOUNLOAD,  STATS = 10
END'

Su SQL2000 non funziona :(

SQL Server Hidden Stored Procedures

Introduction

sp_msforeachdb and sp_msforeachtable are very powerful stored procedures. They allow you to loop through the databases and tables in your instance and run commands against them. I have used these extensively in my day to day work as a DBA. Both of the stored procedures use a question mark as a variable subsitution character. When using sp_msforeachdb, the "?" returns the databasename, and when using sp_msforeachtable the "?" returns the tablename.

Using sp_msforeachdb


Example #1 - to do a check db on every database in your instance you could issue the following command:
sp_msforeachdb 'dbcc checkdb( ''?'' )'
Example #2 - to change the owner of each database in the instance to sa.
sp_msforeachdb 'IF ''?'' NOT IN (''master'', ''model'', ''msdb'', ''tempdb'') 
BEGIN
  print ''?''
  exec [?].dbo.sp_changedbowner ''sa''
END'
**Notice how I used an if statement to filter out the system databases

Example #3 - to do a check db on every table in the database you could issue the following command:
sp_msforeachdb 'dbcc checktable( ''?'' )'
Example #4 - to shrink every database on the instance. Be careful with this one. Not something you want to run on a production server during business hours.
sp_msforeachdb 'dbcc ShrinkDatabase( ?, 10 )'
Example #5 - to make a user db_owner on each user database in the instance. This is commonly done for apps like SharePoint that require db_owner in order to apply service packs.
sp_msforeachdb 'IF ''?'' NOT IN (''master'', ''model'', ''msdb'', ''tempdb'')
BEGIN
   print ''?''

   exec [?].dbo.sp_adduser ''<YOUR DOMAIN NAME HERE>\<YOUR USER ACCOUNT HERE>''
   exec [?].dbo.sp_addrolemember ''db_owner'',''<YOUR DOMAIN NAME HERE>\
        <YOUR USER ACCOUNT HERE''
END'

Using sp_msforeachtable


The counterpart to sp_msforeachdb. Once again, the procedure uses the "?" character to signify the name of the table that the command is currently being executed on.
Example #1 - to get a list of each index and when the statistics were last updated on each index.
CREATE table #stats(
   table_name nvarchar(255) null,
   index_name nvarchar(255) null,
      statistics_update_date datetime null
)
GO
          
exec sp_msforeachtable
'insert into #stats
 SELECT
    ''?'',
        name AS index_name,
    STATS_DATE(object_id, index_id) AS statistics_update_date
 FROM
    sys.indexes
 WHERE
    object_id = OBJECT_ID(''?'');'
      
select * from #stats where index_name is not null
      
drop table #stats
There are a million different uses for these stored procedures. The possibilities are endless. You can even nest a sp_msforeachtable inside of a sp_msforeachdb! Have fun and use them with caution!
 
trovato qui.

Undocumented Stored Procedures sp_MSForEachDB and sp_MSForEachTable

The literal ? is used as a token which is replace with database name or table name according to the executed stored procedure "sp_MSForEachDB" or "sp_MSForEachTable".
If you want to select the database name or the table name as a literal in the t-sql expression you should use double single quotes around the ? literal.
Also the sp_MSForEachDB syntax enables the SQL Server developers or administrators to use [?] instead of ?.
Using token ? in the format "[?]" will rescue in case the database names in the Microsoft SQL Server instance have space characters.
But the same point is just the opposite for the undocumented sp_MSForEachTable proc syntax.

For example, if a database name is "Test Database" then executing the below t-sql command will cause the following error :

EXEC sp_MSForEachDB 'Use ?; SELECT DB_NAME()'
/*
Could not locate entry in sysdatabases for database 'Test'. No entry found with that name. Make sure that the name is entered correctly.
*/

So we can say that the correct syntax for the sp_MSForEachDB and sp_MSForEachTable un-documented procedures is using [?] instead of ? which is pointing to databases in the MSSQL Server

EXEC sp_MSForEachDB 'Use [?]; SELECT DB_NAME()'

You can get an idea on how the sp_MSForEachTable syntax works with ? which is representing the table name in the format schema-name.table-name.

EXEC sp_MSForEachTable 'SELECT ''?'', COUNT(*) FROM ?' -- SUCCESSFULL EXEC sp_MSForEachTable 'SELECT ''?'', COUNT(*) FROM [?]' -- FAIL

T-SQL Sample Queries using sp_MSForEachDB

The below t-sql example codes will count database objects and user procedures for each database and will list these count values with the database name beside for the MS SQL Server instance.


EXEC sp_MSForEachDB 'SELECT ''?'' AS DatabaseName, COUNT(*) AS ObjectCount FROM [?].sys.objects'
EXEC sp_MSForEachDB 'SELECT ''?'' AS DatabaseName, COUNT(*) AS ObjectCount FROM [?].sys.procedures'

The following sql code sp_MSForEachDB example will list system files for each database in the current MS SQL Server instance.

EXEC sp_MSForEachDB 'SELECT ''?'', * FROM [?]..sysfiles'

And similar to the above sql example listing database files detail, the following t-sql code will run thesp_helpfile for every SQL Server database in the installed SQL Server instance.

EXEC sp_MSForEachDB 'Use [?]; EXEC sp_helpfile'

You can use the "USE" command in order to change the database scope of the query.
This will execute the following query on the related database which is changing everytime with the sp_MSForEachDB.

EXEC sp_MSForEachDB 'USE [?]; SELECT ''?'' AS DatabaseName, COUNT(*) AS ProcedureCount FROM sys.procedures'

Of course, you can remove the EXEC command and make call to the sp_MSForEachDB or sp_MSForEachTable MS SQL Server stored procedures directly.

SHRINKDATABASE For Every Database in the SQL Server Instance using sp_MSForEachDB

The following t-sql sp_MSForEachDB command will shrink every database in the related SQL Server instance.

EXEC sp_MSForEachDB 'DBCC SHRINKDATABASE (''?'' , 0)'

T-SQL Sample Queries using sp_MSForEachTable

The following t-sql query is a statement which displays rows count for each table in a database.

EXEC sp_MSForEachTable 'SELECT ''?'', COUNT(*) FROM ?'

You should realize that the above select will return the table names in the format [schema name].[table name]
To remove the brackets [ and ] , you can execute the following altered t-sql query.

EXEC sp_MSForEachTable 'SELECT SUBSTRING(''?'', 8, Len(''?'')-8), COUNT(*) FROM ?'

The below t-sql sp_MSForEachTable example will execute the sp_SpaceUsed for everytable in the current MS SQL Server database and will store the results or the outcome of the sp_SpaceUsedsystem stored procedure in the spSpaceUsed table.

CREATE TABLE spSpaceUsed (
  TableName sysname,
  Rows int,
  Reserved varchar(255),
  Data varchar(255),
  Index_Size varchar(255),
  Unused varchar(255)
)
INSERT INTO spSpaceUsed
EXEC sp_MSForEachTable 'EXEC sp_SpaceUsed ''?'''
SELECT * FROM spSpaceUsed

This t-sql query will diplay column names with type and size for every table in a database.

EXEC sp_MSForEachTable '
SELECT
  SUBSTRING(''?'', 8, Len(''?'')-8) AS TableName,
  syscolumns.name ColumnName,
  CASE systypes.name
    WHEN ''sysname'' THEN ''nvarchar''
    ELSE systypes.name
  END AS Type,
  syscolumns.length,
  syscolumns.prec
FROM syscolumns (NoLock)
INNER JOIN systypes (NoLock) ON systypes.xtype = syscolumns.xtype
WHERE
  syscolumns.id = (
    SELECT id FROM sysobjects (NoLock)
    WHERE name = SUBSTRING(''?'', 8, Len(''?'')-8)
  )
'

Actually the above t-sql query command will execute just as shown below for let's say the table name is [dbo].[Logs].

SELECT
  SUBSTRING('[dbo].[Logs]', 8, Len('[dbo].[Logs]')-8) AS TableName,
  syscolumns.name ColumnName,
  CASE systypes.name
    WHEN 'sysname' THEN 'nvarchar'
    ELSE systypes.name
  END AS Type,
  syscolumns.length,
  syscolumns.prec
FROM syscolumns (NoLock)
INNER JOIN systypes (NoLock) ON systypes.xtype = syscolumns.xtype
WHERE
  syscolumns.id = (
    SELECT id FROM sysobjects (NoLock)
    WHERE name = SUBSTRING('[dbo].[Logs]', 8, Len('[dbo].[Logs]')-8)
  )

UPDATE STATISTICS For Every Table in the Database using sp_MSForEachTable

The following sql command will update statistics for each table in a database.

EXEC sp_MSForEachTable 'UPDATE STATISTICS ?'

More Tutorials on T-SQL sp_MSForEachTable Examples

sp_MSForEachTable Example T-SQL Code to Count all Rows in all Tables in MS SQL Server Database
sp_Msforeachdb Example : List All Database Files using sp_Msforeachdb Undocumented Stored Procedure
Create Same Stored Procedure on All Databases using sp_MSForEachDB T-SQL Example
MS SQL Server Execute Undocumented Stored Procedures sp_MSForEachDB and sp_MSForEachTable with Example T-SQL Codes
Listing All MS SQL Server Databases Using T-SQL
SQL Server Last Database Access using Last Batch Date of sysprocesses or using SQL Server Audit Files and Database Audit Specifications

 

 

trovato qui.

18 January 2011

Quickest Way to Identify Blocking Query and Resolution – Dirty Solution

Here is the script we used to identify the blocking query.
SELECT		db.name DBName,
			tl.request_session_id,
			wt.blocking_session_id,
			OBJECT_NAME(p.OBJECT_ID) BlockedObjectName,
			tl.resource_type,
			h1.TEXT AS RequestingText,
			h2.TEXT AS BlockingTest,
			tl.request_mode
FROM		sys.dm_tran_locks AS tl
INNER JOIN	sys.databases db ON db.database_id = tl.resource_database_id
INNER JOIN	sys.dm_os_waiting_tasks AS wt ON tl.lock_owner_address = wt.resource_address
INNER JOIN	sys.partitions AS p ON p.hobt_id = tl.resource_associated_entity_id
INNER JOIN	sys.dm_exec_connections ec1 ON ec1.session_id = tl.request_session_id
INNER JOIN	sys.dm_exec_connections ec2 ON ec2.session_id = wt.blocking_session_id
CROSS APPLY	sys.dm_exec_sql_text(ec1.most_recent_sql_handle) AS h1
CROSS APPLY	sys.dm_exec_sql_text(ec2.most_recent_sql_handle) AS h2
The query above returned us the following results:
 block
In our case, we killed the blocking_session_id after carefully looking at the BlockingText; it was found to be not necessary at all. We killed the session using the following command:
KILL 52
As mentioned earlier, if you kill something important on your production server, there’s a great possibility that you’ll face some serious integrity issues, so I there’s no way I advise use this method. As the title goes, this is a dirty solution so you must utilize this only if you are confident.

Trovato qui.

07 January 2011

Validatore per indirizzo mail

Con le regex! :)
 <asp:RegularExpressionValidator ID="valEmail" runat="server" ControlToValidate="txtEmail"
                    CssClass="errore" ErrorMessage="Formato dell'indirizzo non valido"
                    ForeColor="" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    Enabled="True"></asp:RegularExpressionValidator>