Search Results

Search found 9271 results on 371 pages for 'drop handler'.

Page 1/371 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • SQL Server script commands to check if object exists and drop it

    - by deadlydog
    Over the past couple years I’ve been keeping track of common SQL Server script commands that I use so I don’t have to constantly Google them.  Most of them are how to check if a SQL object exists before dropping it.  I thought others might find these useful to have them all in one place, so here you go: 1: --=============================== 2: -- Create a new table and add keys and constraints 3: --=============================== 4: IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableName' AND TABLE_SCHEMA='dbo') 5: BEGIN 6: CREATE TABLE [dbo].[TableName] 7: ( 8: [ColumnName1] INT NOT NULL, -- To have a field auto-increment add IDENTITY(1,1) 9: [ColumnName2] INT NULL, 10: [ColumnName3] VARCHAR(30) NOT NULL DEFAULT('') 11: ) 12: 13: -- Add the table's primary key 14: ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [PK_TableName] PRIMARY KEY NONCLUSTERED 15: ( 16: [ColumnName1], 17: [ColumnName2] 18: ) 19: 20: -- Add a foreign key constraint 21: ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [FK_Name] FOREIGN KEY 22: ( 23: [ColumnName1], 24: [ColumnName2] 25: ) 26: REFERENCES [dbo].[Table2Name] 27: ( 28: [OtherColumnName1], 29: [OtherColumnName2] 30: ) 31: 32: -- Add indexes on columns that are often used for retrieval 33: CREATE INDEX IN_ColumnNames ON [dbo].[TableName] 34: ( 35: [ColumnName2], 36: [ColumnName3] 37: ) 38: 39: -- Add a check constraint 40: ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [CH_Name] CHECK (([ColumnName] >= 0.0000)) 41: END 42: 43: --=============================== 44: -- Add a new column to an existing table 45: --=============================== 46: IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='dbo' 47: AND TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') 48: BEGIN 49: ALTER TABLE [dbo].[TableName] ADD [ColumnName] INT NOT NULL DEFAULT(0) 50: 51: -- Add a description extended property to the column to specify what its purpose is. 52: EXEC sys.sp_addextendedproperty @name=N'MS_Description', 53: @value = N'Add column comments here, describing what this column is for.' , 54: @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE', 55: @level1name = N'TableName', @level2type=N'COLUMN', 56: @level2name = N'ColumnName' 57: END 58: 59: --=============================== 60: -- Drop a table 61: --=============================== 62: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableName' AND TABLE_SCHEMA='dbo') 63: BEGIN 64: DROP TABLE [dbo].[TableName] 65: END 66: 67: --=============================== 68: -- Drop a view 69: --=============================== 70: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'ViewName' AND TABLE_SCHEMA='dbo') 71: BEGIN 72: DROP VIEW [dbo].[ViewName] 73: END 74: 75: --=============================== 76: -- Drop a column 77: --=============================== 78: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='dbo' 79: AND TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') 80: BEGIN 81: 82: -- If the column has an extended property, drop it first. 83: IF EXISTS (SELECT * FROM sys.fn_listExtendedProperty(N'MS_Description', N'SCHEMA', N'dbo', N'Table', 84: N'TableName', N'COLUMN', N'ColumnName') 85: BEGIN 86: EXEC sys.sp_dropextendedproperty @name=N'MS_Description', 87: @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE', 88: @level1name = N'TableName', @level2type=N'COLUMN', 89: @level2name = N'ColumnName' 90: END 91: 92: ALTER TABLE [dbo].[TableName] DROP COLUMN [ColumnName] 93: END 94: 95: --=============================== 96: -- Drop Primary key constraint 97: --=============================== 98: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_SCHEMA='dbo' 99: AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'PK_Name') 100: BEGIN 101: ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [PK_Name] 102: END 103: 104: --=============================== 105: -- Drop Foreign key constraint 106: --=============================== 107: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY' AND TABLE_SCHEMA='dbo' 108: AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'FK_Name') 109: BEGIN 110: ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [FK_Name] 111: END 112: 113: --=============================== 114: -- Drop Unique key constraint 115: --=============================== 116: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='UNIQUE' AND TABLE_SCHEMA='dbo' 117: AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'UNI_Name') 118: BEGIN 119: ALTER TABLE [dbo].[TableNames] DROP CONSTRAINT [UNI_Name] 120: END 121: 122: --=============================== 123: -- Drop Check constraint 124: --=============================== 125: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='CHECK' AND TABLE_SCHEMA='dbo' 126: AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'CH_Name') 127: BEGIN 128: ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [CH_Name] 129: END 130: 131: --=============================== 132: -- Drop a column's Default value constraint 133: --=============================== 134: DECLARE @ConstraintName VARCHAR(100) 135: SET @ConstraintName = (SELECT TOP 1 s.name FROM sys.sysobjects s JOIN sys.syscolumns c ON s.parent_obj=c.id 136: WHERE s.xtype='d' AND c.cdefault=s.id 137: AND parent_obj = OBJECT_ID('TableName') AND c.name ='ColumnName') 138: 139: IF @ConstraintName IS NOT NULL 140: BEGIN 141: EXEC ('ALTER TABLE [dbo].[TableName] DROP CONSTRAINT ' + @ConstraintName) 142: END 143: 144: --=============================== 145: -- Example of how to drop dynamically named Unique constraint 146: --=============================== 147: DECLARE @ConstraintName VARCHAR(100) 148: SET @ConstraintName = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 149: WHERE CONSTRAINT_TYPE='UNIQUE' AND TABLE_SCHEMA='dbo' 150: AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME LIKE 'FirstPartOfConstraintName%') 151: 152: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='UNIQUE' AND TABLE_SCHEMA='dbo' 153: AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = @ConstraintName) 154: BEGIN 155: EXEC ('ALTER TABLE [dbo].[TableName] DROP CONSTRAINT ' + @ConstraintName) 156: END 157: 158: --=============================== 159: -- Check for and drop a temp table 160: --=============================== 161: IF OBJECT_ID('tempdb..#TableName') IS NOT NULL DROP TABLE #TableName 162: 163: --=============================== 164: -- Drop a stored procedure 165: --=============================== 166: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='dbo' AND 167: ROUTINE_NAME = 'StoredProcedureName') 168: BEGIN 169: DROP PROCEDURE [dbo].[StoredProcedureName] 170: END 171: 172: --=============================== 173: -- Drop a UDF 174: --=============================== 175: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA='dbo' AND 176: ROUTINE_NAME = 'UDFName') 177: BEGIN 178: DROP FUNCTION [dbo].[UDFName] 179: END 180: 181: --=============================== 182: -- Drop an Index 183: --=============================== 184: IF EXISTS (SELECT * FROM SYS.INDEXES WHERE name = 'IndexName') 185: BEGIN 186: DROP INDEX TableName.IndexName 187: END 188: 189: --=============================== 190: -- Drop a Schema 191: --=============================== 192: IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'SchemaName') 193: BEGIN 194: EXEC('DROP SCHEMA SchemaName') 195: END And here’s the same code, just not in the little code view window so that you don’t have to scroll it.--=============================== -- Create a new table and add keys and constraints --=============================== IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableName' AND TABLE_SCHEMA='dbo') BEGIN CREATE TABLE [dbo].[TableName]  ( [ColumnName1] INT NOT NULL, -- To have a field auto-increment add IDENTITY(1,1) [ColumnName2] INT NULL, [ColumnName3] VARCHAR(30) NOT NULL DEFAULT('') ) -- Add the table's primary key ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [PK_TableName] PRIMARY KEY NONCLUSTERED ( [ColumnName1],  [ColumnName2] ) -- Add a foreign key constraint ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [FK_Name] FOREIGN KEY ( [ColumnName1],  [ColumnName2] ) REFERENCES [dbo].[Table2Name]  ( [OtherColumnName1],  [OtherColumnName2] ) -- Add indexes on columns that are often used for retrieval CREATE INDEX IN_ColumnNames ON [dbo].[TableName] ( [ColumnName2], [ColumnName3] ) -- Add a check constraint ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [CH_Name] CHECK (([ColumnName] >= 0.0000)) END --=============================== -- Add a new column to an existing table --=============================== IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') BEGIN ALTER TABLE [dbo].[TableName] ADD [ColumnName] INT NOT NULL DEFAULT(0) -- Add a description extended property to the column to specify what its purpose is. EXEC sys.sp_addextendedproperty @name=N'MS_Description',  @value = N'Add column comments here, describing what this column is for.' ,  @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE', @level1name = N'TableName', @level2type=N'COLUMN', @level2name = N'ColumnName' END --=============================== -- Drop a table --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableName' AND TABLE_SCHEMA='dbo') BEGIN DROP TABLE [dbo].[TableName] END --=============================== -- Drop a view --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'ViewName' AND TABLE_SCHEMA='dbo') BEGIN DROP VIEW [dbo].[ViewName] END --=============================== -- Drop a column --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') BEGIN -- If the column has an extended property, drop it first. IF EXISTS (SELECT * FROM sys.fn_listExtendedProperty(N'MS_Description', N'SCHEMA', N'dbo', N'Table', N'TableName', N'COLUMN', N'ColumnName') BEGIN EXEC sys.sp_dropextendedproperty @name=N'MS_Description',  @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE', @level1name = N'TableName', @level2type=N'COLUMN', @level2name = N'ColumnName' END ALTER TABLE [dbo].[TableName] DROP COLUMN [ColumnName] END --=============================== -- Drop Primary key constraint --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'PK_Name') BEGIN ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [PK_Name] END --=============================== -- Drop Foreign key constraint --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY' AND TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'FK_Name') BEGIN ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [FK_Name] END --=============================== -- Drop Unique key constraint --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='UNIQUE' AND TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'UNI_Name') BEGIN ALTER TABLE [dbo].[TableNames] DROP CONSTRAINT [UNI_Name] END --=============================== -- Drop Check constraint --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='CHECK' AND TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = 'CH_Name') BEGIN ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [CH_Name] END --=============================== -- Drop a column's Default value constraint --=============================== DECLARE @ConstraintName VARCHAR(100) SET @ConstraintName = (SELECT TOP 1 s.name FROM sys.sysobjects s JOIN sys.syscolumns c ON s.parent_obj=c.id WHERE s.xtype='d' AND c.cdefault=s.id  AND parent_obj = OBJECT_ID('TableName') AND c.name ='ColumnName') IF @ConstraintName IS NOT NULL BEGIN EXEC ('ALTER TABLE [dbo].[TableName] DROP CONSTRAINT ' + @ConstraintName) END --=============================== -- Example of how to drop dynamically named Unique constraint --=============================== DECLARE @ConstraintName VARCHAR(100) SET @ConstraintName = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS  WHERE CONSTRAINT_TYPE='UNIQUE' AND TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME LIKE 'FirstPartOfConstraintName%') IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='UNIQUE' AND TABLE_SCHEMA='dbo' AND TABLE_NAME = 'TableName' AND CONSTRAINT_NAME = @ConstraintName) BEGIN EXEC ('ALTER TABLE [dbo].[TableName] DROP CONSTRAINT ' + @ConstraintName) END --=============================== -- Check for and drop a temp table --=============================== IF OBJECT_ID('tempdb..#TableName') IS NOT NULL DROP TABLE #TableName --=============================== -- Drop a stored procedure --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='dbo' AND ROUTINE_NAME = 'StoredProcedureName') BEGIN DROP PROCEDURE [dbo].[StoredProcedureName] END --=============================== -- Drop a UDF --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA='dbo' AND  ROUTINE_NAME = 'UDFName') BEGIN DROP FUNCTION [dbo].[UDFName] END --=============================== -- Drop an Index --=============================== IF EXISTS (SELECT * FROM SYS.INDEXES WHERE name = 'IndexName') BEGIN DROP INDEX TableName.IndexName END --=============================== -- Drop a Schema --=============================== IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'SchemaName') BEGIN EXEC('DROP SCHEMA SchemaName') END

    Read the article

  • How to speed up this simple mysql query?

    - by Jim Thio
    The query is simple: SELECT TB.ID, TB.Latitude, TB.Longitude, 111151.29341326*SQRT(pow(-6.185-TB.Latitude,2)+pow(106.773-TB.Longitude,2)*cos(-6.185*0.017453292519943)*cos(TB.Latitude*0.017453292519943)) AS Distance FROM `tablebusiness` AS TB WHERE -6.2767668133836 < TB.Latitude AND TB.Latitude < -6.0932331866164 AND FoursquarePeopleCount >5 AND 106.68123318662 < TB.Longitude AND TB.Longitude <106.86476681338 ORDER BY Distance See, we just look at all business within a rectangle. 1.6 million rows. Within that small rectangle there are only 67,565 businesses. The structure of the table is 1 ID varchar(250) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 2 Email varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 3 InBuildingAddress varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 4 Price int(10) Yes NULL Change Change Drop Drop More Show more actions 5 Street varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 6 Title varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 7 Website varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 8 Zip varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 9 Rating Star double Yes NULL Change Change Drop Drop More Show more actions 10 Rating Weight double Yes NULL Change Change Drop Drop More Show more actions 11 Latitude double Yes NULL Change Change Drop Drop More Show more actions 12 Longitude double Yes NULL Change Change Drop Drop More Show more actions 13 Building varchar(200) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 14 City varchar(100) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 15 OpeningHour varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 16 TimeStamp timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP Change Change Drop Drop More Show more actions 17 CountViews int(11) Yes NULL Change Change Drop Drop More Show more actions The indexes are: Edit Edit Drop Drop PRIMARY BTREE Yes No ID 1965990 A Edit Edit Drop Drop City BTREE No No City 131066 A Edit Edit Drop Drop Building BTREE No No Building 21 A YES Edit Edit Drop Drop OpeningHour BTREE No No OpeningHour (255) 21 A YES Edit Edit Drop Drop Email BTREE No No Email (255) 21 A YES Edit Edit Drop Drop InBuildingAddress BTREE No No InBuildingAddress (255) 21 A YES Edit Edit Drop Drop Price BTREE No No Price 21 A YES Edit Edit Drop Drop Street BTREE No No Street (255) 982995 A YES Edit Edit Drop Drop Title BTREE No No Title (255) 1965990 A YES Edit Edit Drop Drop Website BTREE No No Website (255) 491497 A YES Edit Edit Drop Drop Zip BTREE No No Zip (255) 178726 A YES Edit Edit Drop Drop Rating Star BTREE No No Rating Star 21 A YES Edit Edit Drop Drop Rating Weight BTREE No No Rating Weight 21 A YES Edit Edit Drop Drop Latitude BTREE No No Latitude 1965990 A YES Edit Edit Drop Drop Longitude BTREE No No Longitude 1965990 A YES The query took forever. I think there has to be something wrong there. Showing rows 0 - 29 ( 67,565 total, Query took 12.4767 sec)

    Read the article

  • Fake ISAPI Handler to serve static files with extention that are rewritted by url rewriter

    - by developerit
    Introduction I often map html extention to the asp.net dll in order to use url rewritter with .html extentions. Recently, in the new version of www.nouvelair.ca, we renamed all urls to end with .html. This works great, but failed when we used FCK Editor. Static html files would not get serve because we mapped the html extension to the .NET Framework. We can we do to to use .html extension with our rewritter but still want to use IIS behavior with static html files. Analysis I thought that this could be resolve with a simple HTTP handler. We would map urls of static files in our rewriter to this handler that would read the static file and serve it, just as IIS would do. Implementation This is how I coded the class. Note that this may not be bullet proof. I only tested it once and I am sure that the logic behind IIS is more complicated that this. If you find errors or think of possible improvements, let me know. Imports System.Web Imports System.Web.Services ' Author: Nicolas Brassard ' For: Solutions Nitriques inc. http://www.nitriques.com ' Date Created: April 18, 2009 ' Last Modified: April 18, 2009 ' License: CPOL (http://www.codeproject.com/info/cpol10.aspx) ' Files: ISAPIDotNetHandler.ashx ' ISAPIDotNetHandler.ashx.vb ' Class: ISAPIDotNetHandler ' Description: Fake ISAPI handler to serve static files. ' Usefull when you want to serve static file that has a rewrited extention. ' Example: It often map html extention to the asp.net dll in order to use url rewritter with .html. ' If you want to still serve static html file, add a rewritter rule to redirect html files to this handler Public Class ISAPIDotNetHandler Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest ' Since we are doing the job IIS normally does with html files, ' we set the content type to match html. ' You may want to customize this with your own logic, if you want to serve ' txt or xml or any other text file context.Response.ContentType = "text/html" ' We begin a try here. Any error that occurs will result in a 404 Page Not Found error. ' We replicate the behavior of IIS when it doesn't find the correspoding file. Try ' Declare a local variable containing the value of the query string Dim uri As String = context.Request("fileUri") ' If the value in the query string is null, ' throw an error to generate a 404 If String.IsNullOrEmpty(uri) Then Throw New ApplicationException("No fileUri") End If ' If the value in the query string doesn't end with .html, then block the acces ' This is a HUGE security hole since it could permit full read access to .aspx, .config, etc. If Not uri.ToLower.EndsWith(".html") Then ' throw an error to generate a 404 Throw New ApplicationException("Extention not allowed") End If ' Map the file on the server. ' If the file doesn't exists on the server, it will throw an exception and generate a 404. Dim fullPath As String = context.Server.MapPath(uri) ' Read the actual file Dim stream As IO.StreamReader = FileIO.FileSystem.OpenTextFileReader(fullPath) ' Write the file into the response context.Response.Output.Write(stream.ReadToEnd) ' Close and Dipose the stream stream.Close() stream.Dispose() stream = Nothing Catch ex As Exception ' Set the Status Code of the response context.Response.StatusCode = 404 'Page not found ' For testing and bebugging only ! This may cause a security leak ' context.Response.Output.Write(ex.Message) Finally ' In all cases, flush and end the response context.Response.Flush() context.Response.End() End Try End Sub ' Automaticly generated by Visual Studio ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class Conclusion As you see, with our static files map to this handler using query string (ex.: /ISAPIDotNetHandler.ashx?fileUri=index.html) you will have the same behavior as if you ask for the uri /index.html. Finally, test this only in IIS with the html extension map to aspnet_isapi.dll. Url rewritting will work in Casini (Internal Web Server shipped with Visual Studio) but it’s not the same as with IIS since EVERY request is handle by .NET. Versions First release

    Read the article

  • Issues with signal handling [closed]

    - by user34790
    I am trying to actually study the signal handling behavior in multiprocess system. I have a system where there are three signal generating processes generating signals of type SIGUSR1 and SIGUSR1. I have two handler processes that handle a particular type of signal. I have another monitoring process that also receives the signals and then does its work. I have a certain issue. Whenever my signal handling processes generate a signal of a particular type, it is sent to the process group so it is received by the signal handling processes as well as the monitoring processes. Whenever the signal handlers of monitoring and signal handling processes are called, I have printed to indicate the signal handling. I was expecting a uniform series of calls for the signal handlers of the monitoring and handling processes. However, looking at the output I could see like at the beginning the monitoring and signal handling processes's signal handlers are called uniformly. However, after I could see like signal handler processes handlers being called in a burst followed by the signal handler of monitoring process being called in a burst. Here is my code and output #include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <signal.h> #include <cstdio> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #define NUM_SENDER_PROCESSES 3 #define NUM_HANDLER_PROCESSES 4 #define NUM_SIGNAL_REPORT 10 #define MAX_SIGNAL_COUNT 100000 using namespace std; volatile int *usrsig1_handler_count; volatile int *usrsig2_handler_count; volatile int *usrsig1_sender_count; volatile int *usrsig2_sender_count; volatile int *lock_1; volatile int *lock_2; volatile int *lock_3; volatile int *lock_4; volatile int *lock_5; volatile int *lock_6; //Used only by the monitoring process volatile int monitor_count; volatile int usrsig1_monitor_count; volatile int usrsig2_monitor_count; double time_1[NUM_SIGNAL_REPORT]; double time_2[NUM_SIGNAL_REPORT]; //Used only by the main process int total_signal_count; //For shared memory int shmid; const int shareSize = sizeof(int) * (10); double timestamp() { struct timeval tp; gettimeofday(&tp, NULL); return (double)tp.tv_sec + tp.tv_usec / 1000000.; } pid_t senders[NUM_SENDER_PROCESSES]; pid_t handlers[NUM_HANDLER_PROCESSES]; pid_t reporter; void signal_catcher_1(int); void signal_catcher_2(int); void signal_catcher_int(int); void signal_catcher_monitor(int); void signal_catcher_main(int); void terminate_processes() { //Kill the child processes int status; cout << "Time up terminating the child processes" << endl; for(int i=0; i<NUM_SENDER_PROCESSES; i++) { kill(senders[i],SIGKILL); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { kill(handlers[i],SIGKILL); } kill(reporter,SIGKILL); //Wait for the child processes to finish for(int i=0; i<NUM_SENDER_PROCESSES; i++) { waitpid(senders[i], &status, 0); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { waitpid(handlers[i], &status, 0); } waitpid(reporter, &status, 0); } int main(int argc, char *argv[]) { if(argc != 2) { cout << "Required parameters missing. " << endl; cout << "Option 1 = 1 which means run for 30 seconds" << endl; cout << "Option 2 = 2 which means run until 100000 signals" << endl; exit(0); } int option = atoi(argv[1]); pid_t pid; if(option == 2) { if(signal(SIGUSR1, signal_catcher_main) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, signal_catcher_main) == SIG_ERR) { perror("2"); exit(1); } } else { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } } if(signal(SIGINT, signal_catcher_int) == SIG_ERR) { perror("3"); exit(1); } /////////////////////////////////////////////////////////////////////////////////////// ////////////////////// Initializing the shared memory ///////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// cout << "Initializing the shared memory" << endl; if ((shmid=shmget(IPC_PRIVATE,shareSize,IPC_CREAT|0660))< 0) { perror("shmget fail"); exit(1); } usrsig1_handler_count = (int *) shmat(shmid, NULL, 0); usrsig2_handler_count = usrsig1_handler_count + 1; usrsig1_sender_count = usrsig2_handler_count + 1; usrsig2_sender_count = usrsig1_sender_count + 1; lock_1 = usrsig2_sender_count + 1; lock_2 = lock_1 + 1; lock_3 = lock_2 + 1; lock_4 = lock_3 + 1; lock_5 = lock_4 + 1; lock_6 = lock_5 + 1; //Initialize them to be zero *usrsig1_handler_count = 0; *usrsig2_handler_count = 0; *usrsig1_sender_count = 0; *usrsig2_sender_count = 0; *lock_1 = 0; *lock_2 = 0; *lock_3 = 0; *lock_4 = 0; *lock_5 = 0; *lock_6 = 0; cout << "End of initializing the shared memory" << endl; ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////// End of initializing the shared memory /////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////Registering the signal handlers/////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the signal handlers" << endl; for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { if((pid = fork()) == 0) { if(i%2 == 0) { struct sigaction action; action.sa_handler = signal_catcher_1; sigset_t block_mask; action.sa_flags = 0; sigaction(SIGUSR1,&action,NULL); if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } } else { if(signal(SIGUSR1 ,SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } struct sigaction action; action.sa_handler = signal_catcher_2; action.sa_flags = 0; sigaction(SIGUSR2,&action,NULL); } if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } while(true) { pause(); } exit(0); } else { //cout << "Registerd the handler " << pid << endl; handlers[i] = pid; } } cout << "End of registering the signal handlers" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////End of registering the signal handlers ////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////Registering the monitoring process ////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the monitoring process" << endl; if((pid = fork()) == 0) { struct sigaction action; action.sa_handler = signal_catcher_monitor; sigemptyset(&action.sa_mask); sigset_t block_mask; sigemptyset(&block_mask); sigaddset(&block_mask,SIGUSR1); sigaddset(&block_mask,SIGUSR2); action.sa_flags = 0; action.sa_mask = block_mask; sigaction(SIGUSR1,&action,NULL); sigaction(SIGUSR2,&action,NULL); if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } while(true) { pause(); } exit(0); } else { cout << "Monitor's pid is " << pid << endl; reporter = pid; } cout << "End of registering the monitoring process" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////End of registering the monitoring process//////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Sleep to make sure that the monitor and handler processes are well initialized and ready to handle signals sleep(5); ////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////Registering the signal generators/////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the signal generators" << endl; for(int i=0; i<NUM_SENDER_PROCESSES; i++) { if((pid = fork()) == 0) { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } srand(i); while(true) { int signal_id = rand()%2 + 1; if(signal_id == 1) { killpg(getpgid(getpid()), SIGUSR1); while(__sync_lock_test_and_set(lock_4,1) != 0) { } (*usrsig1_sender_count)++; *lock_4 = 0; } else { killpg(getpgid(getpid()), SIGUSR2); while(__sync_lock_test_and_set(lock_5,1) != 0) { } (*usrsig2_sender_count)++; *lock_5=0; } int r = rand()%10 + 1; double s = (double)r/100; sleep(s); } exit(0); } else { //cout << "Registered the sender " << pid << endl; senders[i] = pid; } } //cout << "End of registering the signal generators" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////End of registering the signal generators/////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Either sleep for 30 seconds and terminate the program or if the number of signals generated reaches 10000, terminate the program if(option = 1) { sleep(90); terminate_processes(); } else { while(true) { if(total_signal_count >= MAX_SIGNAL_COUNT) { terminate_processes(); } else { sleep(0.001); } } } } void signal_catcher_1(int the_sig) { while(__sync_lock_test_and_set(lock_1,1) != 0) { } (*usrsig1_handler_count) = (*usrsig1_handler_count) + 1; cout << "Signal Handler 1 " << *usrsig1_handler_count << endl; __sync_lock_release(lock_1); } void signal_catcher_2(int the_sig) { while(__sync_lock_test_and_set(lock_2,1) != 0) { } (*usrsig2_handler_count) = (*usrsig2_handler_count) + 1; __sync_lock_release(lock_2); } void signal_catcher_main(int the_sig) { while(__sync_lock_test_and_set(lock_6,1) != 0) { } total_signal_count++; *lock_6 = 0; } void signal_catcher_int(int the_sig) { for(int i=0; i<NUM_SENDER_PROCESSES; i++) { kill(senders[i],SIGKILL); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { kill(handlers[i],SIGKILL); } kill(reporter,SIGKILL); exit(3); } void signal_catcher_monitor(int the_sig) { cout << "Monitoring process " << *usrsig1_handler_count << endl; } Here is the initial segment of output Monitoring process 0 Monitoring process 0 Monitoring process 0 Monitoring process 0 Signal Handler 1 1 Monitoring process 2 Signal Handler 1 2 Signal Handler 1 3 Signal Handler 1 4 Monitoring process 4 Monitoring process Signal Handler 1 6 Signal Handler 1 7 Monitoring process 7 Monitoring process 8 Monitoring process 8 Signal Handler 1 9 Monitoring process 9 Monitoring process 9 Monitoring process 10 Signal Handler 1 11 Monitoring process 11 Monitoring process 12 Signal Handler 1 13 Signal Handler 1 14 Signal Handler 1 15 Signal Handler 1 16 Signal Handler 1 17 Signal Handler 1 18 Monitoring process 19 Signal Handler 1 20 Monitoring process 20 Signal Handler 1 21 Monitoring process 21 Monitoring process 21 Monitoring process 22 Monitoring process 22 Monitoring process 23 Signal Handler 1 24 Signal Handler 1 25 Monitoring process 25 Signal Handler 1 27 Signal Handler 1 28 Signal Handler 1 29 Here is the segment when the signal handler processes signal handlers are called in a burst Signal Handler 1 456 Signal Handler 1 457 Signal Handler 1 458 Signal Handler 1 459 Signal Handler 1 460 Signal Handler 1 461 Signal Handler 1 462 Signal Handler 1 463 Signal Handler 1 464 Signal Handler 1 465 Signal Handler 1 466 Signal Handler 1 467 Signal Handler 1 468 Signal Handler 1 469 Signal Handler 1 470 Signal Handler 1 471 Signal Handler 1 472 Signal Handler 1 473 Signal Handler 1 474 Signal Handler 1 475 Signal Handler 1 476 Signal Handler 1 477 Signal Handler 1 478 Signal Handler 1 479 Signal Handler 1 480 Signal Handler 1 481 Signal Handler 1 482 Signal Handler 1 483 Signal Handler 1 484 Signal Handler 1 485 Signal Handler 1 486 Signal Handler 1 487 Signal Handler 1 488 Signal Handler 1 489 Signal Handler 1 490 Signal Handler 1 491 Signal Handler 1 492 Signal Handler 1 493 Signal Handler 1 494 Signal Handler 1 495 Signal Handler 1 496 Signal Handler 1 497 Signal Handler 1 498 Signal Handler 1 499 Signal Handler 1 500 Signal Handler 1 501 Signal Handler 1 502 Signal Handler 1 503 Signal Handler 1 504 Signal Handler 1 505 Signal Handler 1 506 Here is the segment when the monitoring processes signal handlers are called in a burst Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Why isn't it uniform afterwards. Why are they called in a burst?

    Read the article

  • Why can blocked IPs get through my iptables? What's wrong with this configuration?

    - by NeedSomeHelp
    (Why can/How are) blocked IPs (get/getting) through my iptables? Hello and thanks for your consideration... I have configured iptables and included (below) output from the command "iptables --line-numbers -n -L" yet IP addresses (like 31.41.219.180) from IP blocks I have already blocked are getting through. Please take a look and share any input you may have. Thank you. P.S. The initial ACCEPT IP addresses are for CloudFlare. . Chain INPUT (policy DROP 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination 1 32267 14M ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 2 0 0 REJECT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp flags:!0x17/0x02 state NEW reject-with tcp-reset 3 149 8570 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 state INVALID 4 434 25606 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0 5 0 0 ACCEPT udp -- * * 103.21.244.0/22 0.0.0.0/0 6 0 0 ACCEPT udp -- * * 103.22.200.0/22 0.0.0.0/0 7 0 0 ACCEPT udp -- * * 103.31.4.0/22 0.0.0.0/0 8 0 0 ACCEPT udp -- * * 104.16.0.0/12 0.0.0.0/0 9 0 0 ACCEPT udp -- * * 108.162.192.0/18 0.0.0.0/0 10 0 0 ACCEPT udp -- * * 141.101.64.0/18 0.0.0.0/0 11 0 0 ACCEPT udp -- * * 162.158.0.0/15 0.0.0.0/0 12 0 0 ACCEPT udp -- * * 173.245.48.0/20 0.0.0.0/0 13 0 0 ACCEPT udp -- * * 188.114.96.0/20 0.0.0.0/0 14 0 0 ACCEPT udp -- * * 190.93.240.0/20 0.0.0.0/0 15 0 0 ACCEPT udp -- * * 197.234.240.0/22 0.0.0.0/0 16 0 0 ACCEPT udp -- * * 198.41.128.0/17 0.0.0.0/0 17 0 0 ACCEPT udp -- * * 199.27.128.0/21 0.0.0.0/0 18 0 0 ACCEPT tcp -- * * 103.21.244.0/22 0.0.0.0/0 19 9 468 ACCEPT tcp -- * * 103.22.200.0/22 0.0.0.0/0 20 0 0 ACCEPT tcp -- * * 103.31.4.0/22 0.0.0.0/0 21 0 0 ACCEPT tcp -- * * 104.16.0.0/12 0.0.0.0/0 22 858 44616 ACCEPT tcp -- * * 108.162.192.0/18 0.0.0.0/0 23 376 19552 ACCEPT tcp -- * * 141.101.64.0/18 0.0.0.0/0 24 0 0 ACCEPT tcp -- * * 162.158.0.0/15 0.0.0.0/0 25 257 13364 ACCEPT tcp -- * * 173.245.48.0/20 0.0.0.0/0 26 0 0 ACCEPT tcp -- * * 188.114.96.0/20 0.0.0.0/0 27 0 0 ACCEPT tcp -- * * 190.93.240.0/20 0.0.0.0/0 28 0 0 ACCEPT tcp -- * * 197.234.240.0/22 0.0.0.0/0 29 0 0 ACCEPT tcp -- * * 198.41.128.0/17 0.0.0.0/0 30 92 4784 ACCEPT tcp -- * * 199.27.128.0/21 0.0.0.0/0 31 0 0 DROP tcp -- * * 1.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 32 0 0 DROP tcp -- * * 101.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 33 0 0 DROP tcp -- * * 102.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 34 0 0 DROP tcp -- * * 103.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 35 18 1080 DROP tcp -- * * 109.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 36 0 0 DROP tcp -- * * 112.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 37 12 656 DROP tcp -- * * 113.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 38 0 0 DROP tcp -- * * 114.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 39 0 0 DROP tcp -- * * 115.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 40 8 352 DROP tcp -- * * 116.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 41 0 0 DROP tcp -- * * 117.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 42 0 0 DROP tcp -- * * 118.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 43 2 120 DROP tcp -- * * 119.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 44 0 0 DROP tcp -- * * 120.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 45 0 0 DROP tcp -- * * 121.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 46 4 160 DROP tcp -- * * 122.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 47 4 240 DROP tcp -- * * 123.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 48 0 0 DROP tcp -- * * 125.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 49 0 0 DROP tcp -- * * 134.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 50 0 0 DROP tcp -- * * 146.185.0.0/16 0.0.0.0/0 tcp dpts:1:50000 51 6 360 DROP tcp -- * * 148.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 52 0 0 DROP tcp -- * * 151.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 53 0 0 DROP tcp -- * * 175.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 54 0 0 DROP tcp -- * * 176.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 55 0 0 DROP tcp -- * * 177.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 56 46 2696 DROP tcp -- * * 178.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 57 0 0 DROP tcp -- * * 179.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 58 4 224 DROP tcp -- * * 180.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 59 0 0 DROP tcp -- * * 181.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 60 0 0 DROP tcp -- * * 182.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 61 34 2040 DROP tcp -- * * 183.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 62 0 0 DROP tcp -- * * 185.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 63 0 0 DROP tcp -- * * 186.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 64 0 0 DROP tcp -- * * 187.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 65 18 912 DROP tcp -- * * 188.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 66 0 0 DROP tcp -- * * 189.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 67 0 0 DROP tcp -- * * 190.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 68 2 120 DROP tcp -- * * 192.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 69 0 0 DROP tcp -- * * 196.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 70 0 0 DROP tcp -- * * 197.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 71 5 300 DROP tcp -- * * 198.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 72 0 0 DROP tcp -- * * 2.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 73 0 0 DROP tcp -- * * 200.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 74 0 0 DROP tcp -- * * 201.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 75 6 360 DROP tcp -- * * 202.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 76 0 0 DROP tcp -- * * 203.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 77 4 160 DROP tcp -- * * 210.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 78 0 0 DROP tcp -- * * 211.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 79 2 96 DROP tcp -- * * 212.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 80 4 240 DROP tcp -- * * 213.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 81 0 0 DROP tcp -- * * 214.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 82 0 0 DROP tcp -- * * 215.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 83 0 0 DROP tcp -- * * 216.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 84 0 0 DROP tcp -- * * 217.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 85 4 172 DROP tcp -- * * 218.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 86 12 576 DROP tcp -- * * 219.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 87 7 372 DROP tcp -- * * 220.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 88 0 0 DROP tcp -- * * 222.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 89 0 0 DROP tcp -- * * 27.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 90 12 608 DROP tcp -- * * 31.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 91 11 528 DROP tcp -- * * 37.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 92 0 0 DROP tcp -- * * 41.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 93 0 0 DROP tcp -- * * 42.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 94 0 0 DROP tcp -- * * 43.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 95 8 480 DROP tcp -- * * 46.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 96 0 0 DROP tcp -- * * 49.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 97 6 360 DROP tcp -- * * 5.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 98 0 0 DROP tcp -- * * 58.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 99 0 0 DROP tcp -- * * 60.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 100 4 160 DROP tcp -- * * 61.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 101 32 1848 DROP tcp -- * * 62.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 102 0 0 DROP tcp -- * * 63.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 103 20 1200 DROP tcp -- * * 64.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 104 0 0 DROP tcp -- * * 65.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 105 266 15960 DROP tcp -- * * 66.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 106 3 180 DROP tcp -- * * 69.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 107 5 272 DROP tcp -- * * 72.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 108 0 0 DROP tcp -- * * 78.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 109 0 0 DROP tcp -- * * 81.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 110 3 180 DROP tcp -- * * 82.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 111 0 0 DROP tcp -- * * 83.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 112 8 384 DROP tcp -- * * 84.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 113 0 0 DROP tcp -- * * 85.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 114 0 0 DROP tcp -- * * 86.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 115 6 360 DROP tcp -- * * 87.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 116 7 408 DROP tcp -- * * 88.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 117 0 0 DROP tcp -- * * 89.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 118 0 0 DROP tcp -- * * 90.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 119 0 0 DROP tcp -- * * 91.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 120 3 152 DROP tcp -- * * 92.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 121 20 992 DROP tcp -- * * 93.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 122 9 512 DROP tcp -- * * 94.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 123 5 272 DROP tcp -- * * 95.0.0.0/8 0.0.0.0/0 tcp dpts:1:50000 124 0 0 DROP udp -- * * 1.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 125 0 0 DROP udp -- * * 101.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 126 0 0 DROP udp -- * * 102.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 127 0 0 DROP udp -- * * 103.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 128 0 0 DROP udp -- * * 109.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 129 0 0 DROP udp -- * * 112.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 130 0 0 DROP udp -- * * 113.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 131 0 0 DROP udp -- * * 114.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 132 1 112 DROP udp -- * * 115.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 133 0 0 DROP udp -- * * 116.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 134 0 0 DROP udp -- * * 117.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 135 0 0 DROP udp -- * * 118.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 136 0 0 DROP udp -- * * 119.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 137 0 0 DROP udp -- * * 120.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 138 0 0 DROP udp -- * * 121.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 139 0 0 DROP udp -- * * 122.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 140 0 0 DROP udp -- * * 123.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 141 0 0 DROP udp -- * * 125.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 142 0 0 DROP udp -- * * 134.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 143 0 0 DROP udp -- * * 146.185.0.0/16 0.0.0.0/0 udp dpts:1:50000 144 0 0 DROP udp -- * * 148.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 145 0 0 DROP udp -- * * 151.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 146 0 0 DROP udp -- * * 175.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 147 0 0 DROP udp -- * * 176.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 148 1 70 DROP udp -- * * 177.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 149 0 0 DROP udp -- * * 178.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 150 0 0 DROP udp -- * * 179.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 151 0 0 DROP udp -- * * 180.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 152 0 0 DROP udp -- * * 181.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 153 0 0 DROP udp -- * * 182.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 154 0 0 DROP udp -- * * 183.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 155 0 0 DROP udp -- * * 185.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 156 1 74 DROP udp -- * * 186.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 157 0 0 DROP udp -- * * 187.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 158 0 0 DROP udp -- * * 188.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 159 0 0 DROP udp -- * * 189.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 160 0 0 DROP udp -- * * 190.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 161 0 0 DROP udp -- * * 192.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 162 0 0 DROP udp -- * * 196.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 163 0 0 DROP udp -- * * 197.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 164 0 0 DROP udp -- * * 198.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 165 0 0 DROP udp -- * * 2.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 166 0 0 DROP udp -- * * 200.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 167 0 0 DROP udp -- * * 201.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 168 0 0 DROP udp -- * * 202.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 169 0 0 DROP udp -- * * 203.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 170 0 0 DROP udp -- * * 210.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 171 0 0 DROP udp -- * * 211.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 172 0 0 DROP udp -- * * 212.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 173 0 0 DROP udp -- * * 213.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 174 0 0 DROP udp -- * * 214.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 175 0 0 DROP udp -- * * 215.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 176 0 0 DROP udp -- * * 216.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 177 0 0 DROP udp -- * * 217.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 178 1 80 DROP udp -- * * 218.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 179 0 0 DROP udp -- * * 219.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 180 0 0 DROP udp -- * * 220.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 181 0 0 DROP udp -- * * 222.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 182 0 0 DROP udp -- * * 27.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 183 0 0 DROP udp -- * * 31.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 184 0 0 DROP udp -- * * 37.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 185 0 0 DROP udp -- * * 41.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 186 0 0 DROP udp -- * * 42.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 187 0 0 DROP udp -- * * 43.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 188 0 0 DROP udp -- * * 46.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 189 0 0 DROP udp -- * * 49.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 190 0 0 DROP udp -- * * 5.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 191 0 0 DROP udp -- * * 58.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 192 0 0 DROP udp -- * * 60.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 193 0 0 DROP udp -- * * 61.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 194 0 0 DROP udp -- * * 62.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 195 0 0 DROP udp -- * * 63.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 196 0 0 DROP udp -- * * 64.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 197 0 0 DROP udp -- * * 65.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 198 0 0 DROP udp -- * * 66.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 199 0 0 DROP udp -- * * 69.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 200 0 0 DROP udp -- * * 72.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 201 0 0 DROP udp -- * * 78.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 202 0 0 DROP udp -- * * 81.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 203 0 0 DROP udp -- * * 82.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 204 0 0 DROP udp -- * * 83.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 205 0 0 DROP udp -- * * 84.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 206 0 0 DROP udp -- * * 85.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 207 0 0 DROP udp -- * * 86.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 208 0 0 DROP udp -- * * 87.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 209 0 0 DROP udp -- * * 88.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 210 0 0 DROP udp -- * * 89.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 211 0 0 DROP udp -- * * 90.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 212 0 0 DROP udp -- * * 91.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 213 0 0 DROP udp -- * * 92.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 214 2 72 DROP udp -- * * 93.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 215 0 0 DROP udp -- * * 94.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 216 0 0 DROP udp -- * * 95.0.0.0/8 0.0.0.0/0 udp dpts:1:50000 217 0 0 DROP tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:12443 218 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:11443 219 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:11444 220 23 1104 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8447 221 24 1152 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8443 222 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8880 223 207 11096 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 224 19 996 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443 225 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:21 226 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 227 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:587 228 4 216 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:25 229 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:465 230 14 840 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:110 231 2 120 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:995 232 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:143 233 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:993 234 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:106 235 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306 236 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5432 237 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9008 238 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9080 239 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:137 240 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:138 241 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:139 242 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:445 243 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1194 244 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:53 245 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:53 246 73 4488 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0 icmp type 8 code 0 247 77 23598 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 Chain FORWARD (policy DROP 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination 1 0 0 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 2 0 0 REJECT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp flags:!0x17/0x02 state NEW reject-with tcp-reset 3 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 state INVALID 4 0 0 ACCEPT all -- lo lo 0.0.0.0/0 0.0.0.0/0 5 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 Chain OUTPUT (policy DROP 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination 1 31004 25M ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 2 1 333 REJECT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp flags:!0x17/0x02 state NEW reject-with tcp-reset 3 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 state INVALID 4 434 25606 ACCEPT all -- * lo 0.0.0.0/0 0.0.0.0/0 5 328 21324 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0

    Read the article

  • Subterranean IL: Exception handler semantics

    - by Simon Cooper
    In my blog posts on fault and filter exception handlers, I said that the same behaviour could be replicated using normal catch blocks. Well, that isn't entirely true... Changing the handler semantics Consider the following: .try { .try { .try { newobj instance void [mscorlib]System.Exception::.ctor() // IL for: // e.Data.Add("DictKey", true) throw } fault { ldstr "1: Fault handler" call void [mscorlib]System.Console::WriteLine(string) endfault } } filter { ldstr "2a: Filter logic" call void [mscorlib]System.Console::WriteLine(string) // IL for: // (bool)((Exception)e).Data["DictKey"] endfilter }{ ldstr "2b: Filter handler" call void [mscorlib]System.Console::WriteLine(string) leave.s Return } } catch object { ldstr "3: Catch handler" call void [mscorlib]System.Console::WriteLine(string) leave.s Return } Return: // rest of method If the filter handler is engaged (true is inserted into the exception dictionary) then the filter handler gets engaged, and the following gets printed to the console: 2a: Filter logic 1: Fault handler 2b: Filter handler and if the filter handler isn't engaged, then the following is printed: 2a:Filter logic 1: Fault handler 3: Catch handler Filter handler execution The filter handler is executed first. Hmm, ok. Well, what happens if we replaced the fault block with the C# equivalent (with the exception dictionary value set to false)? .try { // throw exception } catch object { ldstr "1: Fault handler" call void [mscorlib]System.Console::WriteLine(string) rethrow } we get this: 1: Fault handler 2a: Filter logic 3: Catch handler The fault handler is executed first, instead of the filter block. Eh? This change in behaviour is due to the way the CLR searches for exception handlers. When an exception is thrown, the CLR stops execution of the thread, and searches up the stack for an exception handler that can handle the exception and stop it propagating further - catch or filter handlers. It checks the type clause of catch clauses, and executes the code in filter blocks to see if the filter can handle the exception. When the CLR finds a valid handler, it saves the handler's location, then goes back to where the exception was thrown and executes fault and finally blocks between there and the handler location, discarding stack frames in the process, until it reaches the handler. So? By replacing a fault with a catch, we have changed the semantics of when the filter code is executed; by using a rethrow instruction, we've split up the exception handler search into two - one search to find the first catch, then a second when the rethrow instruction is encountered. This is only really obvious when mixing C# exception handlers with fault or filter handlers, so this doesn't affect code written only in C#. However it could cause some subtle and hard-to-debug effects with object initialization and ordering when using and calling code written in a language that can compile fault and filter handlers.

    Read the article

  • Using Native Drag and Drop in HTML 5 pages

    - by nikolaosk
    This is going to be the eighth post in a series of posts regarding HTML 5. You can find the other posts here, here , here , here, here , here and here. In this post I will show you how to implement Drag and Drop functionality in an HTML 5 page using JQuery.This is a great functionality and we do not need to resort anymore to plugins like Silverlight and Flash to achieve this great feature. This is also called a native approach on Drag and Drop.I will use some events and I will write code to respond when these events are fired.As I said earlier we need to write Javascript to implement the drag and drop functionality. I will use the very popular JQuery Library. Please download the library (minified version) from http://jquery.com/downloadI will create a simple HTML page.There will be two thumbnails pics on it. There will also be the drag and drop area where the user will drag the thumb pics into it and they will resize to their actual size. The HTML markup for the page follows<!doctype html><html lang="en"><head><title>Liverpool Legends Gallery</title><meta charset="utf-8"><link rel="stylesheet" type="text/css" href="style.css"><script type="text/javascript" charset="utf-8" src="jquery-1.8.1.min.js"></script>  <script language="JavaScript" src="drag.js"></script>   </head><body><header><h1>A page dedicated to Liverpool Legends</h1><h2>Drag and Drop the thumb image in the designated area to see the full image</h2></header><div id="main"><img src="thumbs/steven-gerrard.jpg"  big="large-images/steven-gerrard-large.jpg" alt="John Barnes"><img src="thumbs/robbie-fowler.jpg" big="large-images/robbie-fowler-large.jpg" alt="Ian Rush"><div id="drag"><p>Drop your image here</p> </div></body></html> There is nothing difficult or fancy in the HTML markup above. I have a link to the external JQuery library and another javascript file that I will implement the whole drag and drop functionality.The code for the css file (style.css) follows#main{  float: left;  width: 340px;  margin-right: 30px;}#drag{  float: left;  width: 400px;  height:300px;  background-color: #c0c0c0;}These are simple CSS rules. This post cannot be a tutorial on CSS.For all these posts I assume that you have the basic HTML,CSS,Javascript skills.Now I am going to create a javascript file (drag.js) to implement the drag and drop functionality.I will provide the whole code for the drag.js file and then I will explain what I am doing in each step.$(function() {          var players = $('#main img');          players.attr('draggable', 'true');                    players.bind('dragstart', function(event) {              var data = event.originalEvent.dataTransfer;               var src = $(this).attr("big");              data.setData("Text", src);               return true;          });          var target = $('#drag');          target.bind('drop', function(event) {            var data = event.originalEvent.dataTransfer;            var src = ( data.getData('Text') );                         var img = $("<img></img>").attr("src", src);            $(this).html(img);            if (event.preventDefault) event.preventDefault();            return(false);          });                   target.bind('dragover', function(event) {                if (event.preventDefault) event.preventDefault();            return false;          });           players.bind('dragend', function(event) {             if (event.preventDefault) event.preventDefault();             return false;           });        });   In these lines var players = $('#main img'); players.attr('draggable', 'true');We grab all the images in the #main div and store them in a variable and then make them draggable.Then in following lines I am using the dragstart event.  players.bind('dragstart', function(event) {              var data = event.originalEvent.dataTransfer;               var src = $(this).attr("big");              data.setData("Text", src);               return true;          }); In this event I am associating the custom data attribute value with the item I am dragging.Then I create a variable to get hold of the dropping area var target = $('#drag'); Then in the following lines I implement the drop event and what happens when the user drops the image in the designated area on the page. target.bind('drop', function(event) {            var data = event.originalEvent.dataTransfer;            var src = ( data.getData('Text') );                         var img = $("<img></img>").attr("src", src);            $(this).html(img);            if (event.preventDefault) event.preventDefault();            return(false);          }); The dragend  event is fired when the user has finished the drag operation        players.bind('dragend', function(event) {             if (event.preventDefault) event.preventDefault();             return false;           }); When this method event.preventDefault() is called , the default action of the event will not be triggered.Please have a look a the picture below to see how the page looks before the drag and drop takes place. Then simply I drag and drop a picture in the dropping area.Have a look at the picture below It works!!! Hope it helps!!  

    Read the article

  • IIS7 Handler Mapping Migration from Sites Config to Server Config [migrated]

    - by Danomite
    We have a bunch of sites running with about 8 handler mappings in their web.config files. Unfortunately, they were getting copied site to site every time a new one was added. Now the time has come for me to get these out of all the web.config's and get them into the server's Handler Mappings. If I add the mapping to the the server while it still exists in the web.config, IIS throws an error when you browse to the site. I have a few dozen web.config's to edit here with about 10 mappings in each. Is there a way to add these mappings to the server without having to go in an edit each web.config file manually? Otherwise, every site will be down for a few minutes while I go into each file and remove the handlers. Thanks!

    Read the article

  • Qt drag & drop button; drop not detecting

    - by Thomas Verbeke
    I'm creating a 2D game in QT and i'm trying to implement a drag & drop into my program. For some reason the drop is not registered: qDebug should print a message on dropping but this doesn't happen. #include "dialog.h" #include "ui_dialog.h" #include "world.h" #include <vector> Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); MySquare *item; QGraphicsRectItem *enemyItem; World *myWorld = new World(); std::vector<Tile*> tiles = myWorld->createWorld(":/texture.jpg"); int count = 0; foreach (Tile *tile, tiles){ count++; item = new MySquare(tile->getXPos()*4,tile->getYPos()*4,4,4); item->setBrush(QColor(tile->getValue()*255,tile->getValue()*255,tile->getValue()*255)); item->setAcceptDrops(true); scene->addItem(item); } player = new MySquare(10,20,10,10); player->setAcceptDrops(true); scene->addItem(player); //drag & drop part QPushButton *pushButton = new QPushButton("Click Me",this); connect(pushButton,SIGNAL(pressed()),this,SLOT(makeDrag())); setAcceptDrops(true); } void Dialog::makeDrag() { QDrag *dr = new QDrag(this); // The data to be transferred by the drag and drop operation is contained in a QMimeData object QMimeData *data = new QMimeData; data->setText("This is a test"); // Assign ownership of the QMimeData object to the QDrag object. dr->setMimeData(data); // Start the drag and drop operation dr->start(); } mysquare.cpp #include "mysquare.h" MySquare::MySquare(int _x,int _y, int _w, int _h) { isPlayer=false; Pressed=false; setFlag(ItemIsMovable); setFlag(ItemIsFocusable); setAcceptDrops(true); color=Qt::red; color_pressed = Qt::green; x = _x; y = _y; w = _w; h = _h; } QRectF MySquare::boundingRect() const { return QRectF(x,y,w,h); } void MySquare::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QRectF rec = boundingRect(); QBrush brush(color); if (Pressed){ brush.setColor(color); } else { brush.setColor(color_pressed); } painter->fillRect(rec,brush); painter->drawRect(rec); } void MySquare::mousePressEvent(QGraphicsSceneMouseEvent *event) { Pressed=true; update(); QGraphicsItem::mousePressEvent(event); qDebug() << "mouse Pressed"; } void MySquare::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Pressed=false; update(); QGraphicsItem::mousePressEvent(event); qDebug() << "mouse Released"; } void MySquare::keyPressEvent(QKeyEvent *event){ int x = pos().x(); int y = pos().y(); //key handling QGraphicsItem::keyPressEvent(event); } void MySquare::dropEvent(QDropEvent *event) { qDebug("dropEvent - square"); // Unpack dropped data and handle it the way you want qDebug("Contents: %s", event->mimeData()->text().toLatin1().data()); } void MySquare::dragMoveEvent(QDragMoveEvent *event){ qDebug("dragMoveEvent - square "); event->accept(); } void MySquare::dragEnterEvent(QDragEnterEvent *event){ event->setAccepted(true); qDebug("dragEnterEvent - square"); event->acceptProposedAction(); } void MySquare::setBrush(QColor _color){ color = _color; color_pressed = _color; update(); //repaint } edit; there is no problem with qDebug() i'm just using it to test them i'm inside the drag events..which i'm not

    Read the article

  • Flex - Drag and drop - Drop a subset of multiple items

    - by flanagann
    I'm developing two DataGrid with drag and drop support. Multiple items can be selected from the source data grid, and dropped into the target data grid. I'm using an drag and drop event listener which completes the operation only in certain cases. I'm using event.preventDefault() but it doesn't work, since it stops the drag and drop from all the items. My aim is, for example, finally dropping 2 elements from the total 4 elements that I previously selected. public function onDropPermission(event:DragEvent):void { var sourceGrid:mx.controls.DataGrid = new mx.controls.DataGrid(); sourceGrid = event.dragInitiator as mx.controls.DataGrid; var targetGrid:mx.controls.DataGrid = new mx.controls.DataGrid(); targetGrid = event.target as mx.controls.DataGrid; var i:int; for (i = 0; i < sourceGrid.selectedIndices.length; i++) { var j:int; for (j = 0; j < dataGroupPermissions.length; j++) { var permission:Permission = new Permission; permission = dataGroupPermissions[j] as Permission; if (permission.id == sourceGrid.selectedItems[i].id) { event.preventDefault(); } } } }

    Read the article

  • Drag and drop onto Python script in Windows Explorer

    - by grok
    I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target. Is there some kind of configuration that needs to be done somewhere for this work?

    Read the article

  • Custom ASP.NET Routing to an HttpHandler

    - by Rick Strahl
    As of version 4.0 ASP.NET natively supports routing via the now built-in System.Web.Routing namespace. Routing features are automatically integrated into the HtttpRuntime via a few custom interfaces. New Web Forms Routing Support In ASP.NET 4.0 there are a host of improvements including routing support baked into Web Forms via a RouteData property available on the Page class and RouteCollection.MapPageRoute() route handler that makes it easy to route to Web forms. To map ASP.NET Page routes is as simple as setting up the routes with MapPageRoute:protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("StockQuote", "StockQuote/{symbol}", "StockQuote.aspx"); routes.MapPageRoute("StockQuotes", "StockQuotes/{symbolList}", "StockQuotes.aspx"); } and then accessing the route data in the page you can then use the new Page class RouteData property to retrieve the dynamic route data information:public partial class StockQuote1 : System.Web.UI.Page { protected StockQuote Quote = null; protected void Page_Load(object sender, EventArgs e) { string symbol = RouteData.Values["symbol"] as string; StockServer server = new StockServer(); Quote = server.GetStockQuote(symbol); // display stock data in Page View } } Simple, quick and doesn’t require much explanation. If you’re using WebForms most of your routing needs should be served just fine by this simple mechanism. Kudos to the ASP.NET team for putting this in the box and making it easy! How Routing Works To handle Routing in ASP.NET involves these steps: Registering Routes Creating a custom RouteHandler to retrieve an HttpHandler Attaching RouteData to your HttpHandler Picking up Route Information in your Request code Registering routes makes ASP.NET aware of the Routes you want to handle via the static RouteTable.Routes collection. You basically add routes to this collection to let ASP.NET know which URL patterns it should watch for. You typically hook up routes off a RegisterRoutes method that fires in Application_Start as I did in the example above to ensure routes are added only once when the application first starts up. When you create a route, you pass in a RouteHandler instance which ASP.NET caches and reuses as routes are matched. Once registered ASP.NET monitors the routes and if a match is found just prior to the HttpHandler instantiation, ASP.NET uses the RouteHandler registered for the route and calls GetHandler() on it to retrieve an HttpHandler instance. The RouteHandler.GetHandler() method is responsible for creating an instance of an HttpHandler that is to handle the request and – if necessary – to assign any additional custom data to the handler. At minimum you probably want to pass the RouteData to the handler so the handler can identify the request based on the route data available. To do this you typically add  a RouteData property to your handler and then assign the property from the RouteHandlers request context. This is essentially how Page.RouteData comes into being and this approach should work well for any custom handler implementation that requires RouteData. It’s a shame that ASP.NET doesn’t have a top level intrinsic object that’s accessible off the HttpContext object to provide route data more generically, but since RouteData is directly tied to HttpHandlers and not all handlers support it it might cause some confusion of when it’s actually available. Bottom line is that if you want to hold on to RouteData you have to assign it to a custom property of the handler or else pass it to the handler via Context.Items[] object that can be retrieved on an as needed basis. It’s important to understand that routing is hooked up via RouteHandlers that are responsible for loading HttpHandler instances. RouteHandlers are invoked for every request that matches a route and through this RouteHandler instance the Handler gains access to the current RouteData. Because of this logic it’s important to understand that Routing is really tied to HttpHandlers and not available prior to handler instantiation, which is pretty late in the HttpRuntime’s request pipeline. IOW, Routing works with Handlers but not with earlier in the pipeline within Modules. Specifically ASP.NET calls RouteHandler.GetHandler() from the PostResolveRequestCache HttpRuntime pipeline event. Here’s the call stack at the beginning of the GetHandler() call: which fires just before handler resolution. Non-Page Routing – You need to build custom RouteHandlers If you need to route to a custom Http Handler or other non-Page (and non-MVC) endpoint in the HttpRuntime, there is no generic mapping support available. You need to create a custom RouteHandler that can manage creating an instance of an HttpHandler that is fired in response to a routed request. Depending on what you are doing this process can be simple or fairly involved as your code is responsible based on the route data provided which handler to instantiate, and more importantly how to pass the route data on to the Handler. Luckily creating a RouteHandler is easy by implementing the IRouteHandler interface which has only a single GetHttpHandler(RequestContext context) method. In this method you can pick up the requestContext.RouteData, instantiate the HttpHandler of choice, and assign the RouteData to it. Then pass back the handler and you’re done.Here’s a simple example of GetHttpHandler() method that dynamically creates a handler based on a passed in Handler type./// <summary> /// Retrieves an Http Handler based on the type specified in the constructor /// </summary> /// <param name="requestContext"></param> /// <returns></returns> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; // If we're dealing with a Callback Handler // pass the RouteData for this route to the Handler if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; } Note that this code checks for a specific type of handler and if it matches assigns the RouteData to this handler. This is optional but quite a common scenario if you want to work with RouteData. If the handler you need to instantiate isn’t under your control but you still need to pass RouteData to Handler code, an alternative is to pass the RouteData via the HttpContext.Items collection:IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; requestContext.HttpContext.Items["RouteData"] = requestContext.RouteData; return handler; } The code in the handler implementation can then pick up the RouteData from the context collection as needed:RouteData routeData = HttpContext.Current.Items["RouteData"] as RouteData This isn’t as clean as having an explicit RouteData property, but it does have the advantage that the route data is visible anywhere in the Handler’s code chain. It’s definitely preferable to create a custom property on your handler, but the Context work-around works in a pinch when you don’t’ own the handler code and have dynamic code executing as part of the handler execution. An Example of a Custom RouteHandler: Attribute Based Route Implementation In this post I’m going to discuss a custom routine implementation I built for my CallbackHandler class in the West Wind Web & Ajax Toolkit. CallbackHandler can be very easily used for creating AJAX, REST and POX requests following RPC style method mapping. You can pass parameters via URL query string, POST data or raw data structures, and you can retrieve results as JSON, XML or raw string/binary data. It’s a quick and easy way to build service interfaces with no fuss. As a quick review here’s how CallbackHandler works: You create an Http Handler that derives from CallbackHandler You implement methods that have a [CallbackMethod] Attribute and that’s it. Here’s an example of an CallbackHandler implementation in an ashx.cs based handler:// RestService.ashx.cs public class RestService : CallbackHandler { [CallbackMethod] public StockQuote GetStockQuote(string symbol) { StockServer server = new StockServer(); return server.GetStockQuote(symbol); } [CallbackMethod] public StockQuote[] GetStockQuotes(string symbolList) { StockServer server = new StockServer(); string[] symbols = symbolList.Split(new char[2] { ',',';' },StringSplitOptions.RemoveEmptyEntries); return server.GetStockQuotes(symbols); } } CallbackHandler makes it super easy to create a method on the server, pass data to it via POST, QueryString or raw JSON/XML data, and then retrieve the results easily back in various formats. This works wonderful and I’ve used these tools in many projects for myself and with clients. But one thing missing has been the ability to create clean URLs. Typical URLs looked like this: http://www.west-wind.com/WestwindWebToolkit/samples/Rest/StockService.ashx?Method=GetStockQuote&symbol=msfthttp://www.west-wind.com/WestwindWebToolkit/samples/Rest/StockService.ashx?Method=GetStockQuotes&symbolList=msft,intc,gld,slw,mwe&format=xml which works and is clear enough, but also clearly very ugly. It would be much nicer if URLs could look like this: http://www.west-wind.com//WestwindWebtoolkit/Samples/StockQuote/msfthttp://www.west-wind.com/WestwindWebtoolkit/Samples/StockQuotes/msft,intc,gld,slw?format=xml (the Virtual Root in this sample is WestWindWebToolkit/Samples and StockQuote/{symbol} is the route)(If you use FireFox try using the JSONView plug-in make it easier to view JSON content) So, taking a clue from the WCF REST tools that use RouteUrls I set out to create a way to specify RouteUrls for each of the endpoints. The change made basically allows changing the above to: [CallbackMethod(RouteUrl="RestService/StockQuote/{symbol}")] public StockQuote GetStockQuote(string symbol) { StockServer server = new StockServer(); return server.GetStockQuote(symbol); } [CallbackMethod(RouteUrl = "RestService/StockQuotes/{symbolList}")] public StockQuote[] GetStockQuotes(string symbolList) { StockServer server = new StockServer(); string[] symbols = symbolList.Split(new char[2] { ',',';' },StringSplitOptions.RemoveEmptyEntries); return server.GetStockQuotes(symbols); } where a RouteUrl is specified as part of the Callback attribute. And with the changes made with RouteUrls I can now get URLs like the second set shown earlier. So how does that work? Let’s find out… How to Create Custom Routes As mentioned earlier Routing is made up of several steps: Creating a custom RouteHandler to create HttpHandler instances Mapping the actual Routes to the RouteHandler Retrieving the RouteData and actually doing something useful with it in the HttpHandler In the CallbackHandler routing example above this works out to something like this: Create a custom RouteHandler that includes a property to track the method to call Set up the routes using Reflection against the class Looking for any RouteUrls in the CallbackMethod attribute Add a RouteData property to the CallbackHandler so we can access the RouteData in the code of the handler Creating a Custom Route Handler To make the above work I created a custom RouteHandler class that includes the actual IRouteHandler implementation as well as a generic and static method to automatically register all routes marked with the [CallbackMethod(RouteUrl="…")] attribute. Here’s the code:/// <summary> /// Route handler that can create instances of CallbackHandler derived /// callback classes. The route handler tracks the method name and /// creates an instance of the service in a predictable manner /// </summary> /// <typeparam name="TCallbackHandler">CallbackHandler type</typeparam> public class CallbackHandlerRouteHandler : IRouteHandler { /// <summary> /// Method name that is to be called on this route. /// Set by the automatically generated RegisterRoutes /// invokation. /// </summary> public string MethodName { get; set; } /// <summary> /// The type of the handler we're going to instantiate. /// Needed so we can semi-generically instantiate the /// handler and call the method on it. /// </summary> public Type CallbackHandlerType { get; set; } /// <summary> /// Constructor to pass in the two required components we /// need to create an instance of our handler. /// </summary> /// <param name="methodName"></param> /// <param name="callbackHandlerType"></param> public CallbackHandlerRouteHandler(string methodName, Type callbackHandlerType) { MethodName = methodName; CallbackHandlerType = callbackHandlerType; } /// <summary> /// Retrieves an Http Handler based on the type specified in the constructor /// </summary> /// <param name="requestContext"></param> /// <returns></returns> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; // If we're dealing with a Callback Handler // pass the RouteData for this route to the Handler if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; } /// <summary> /// Generic method to register all routes from a CallbackHandler /// that have RouteUrls defined on the [CallbackMethod] attribute /// </summary> /// <typeparam name="TCallbackHandler">CallbackHandler Type</typeparam> /// <param name="routes"></param> public static void RegisterRoutes<TCallbackHandler>(RouteCollection routes) { // find all methods var methods = typeof(TCallbackHandler).GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (var method in methods) { var attrs = method.GetCustomAttributes(typeof(CallbackMethodAttribute), false); if (attrs.Length < 1) continue; CallbackMethodAttribute attr = attrs[0] as CallbackMethodAttribute; if (string.IsNullOrEmpty(attr.RouteUrl)) continue; // Add the route routes.Add(method.Name, new Route(attr.RouteUrl, new CallbackHandlerRouteHandler(method.Name, typeof(TCallbackHandler)))); } } } The RouteHandler implements IRouteHandler, and its responsibility via the GetHandler method is to create an HttpHandler based on the route data. When ASP.NET calls GetHandler it passes a requestContext parameter which includes a requestContext.RouteData property. This parameter holds the current request’s route data as well as an instance of the current RouteHandler. If you look at GetHttpHandler() you can see that the code creates an instance of the handler we are interested in and then sets the RouteData property on the handler. This is how you can pass the current request’s RouteData to the handler. The RouteData object also has a  RouteData.RouteHandler property that is also available to the Handler later, which is useful in order to get additional information about the current route. In our case here the RouteHandler includes a MethodName property that identifies the method to execute in the handler since that value no longer comes from the URL so we need to figure out the method name some other way. The method name is mapped explicitly when the RouteHandler is created and here the static method that auto-registers all CallbackMethods with RouteUrls sets the method name when it creates the routes while reflecting over the methods (more on this in a minute). The important point here is that you can attach additional properties to the RouteHandler and you can then later access the RouteHandler and its properties later in the Handler to pick up these custom values. This is a crucial feature in that the RouteHandler serves in passing additional context to the handler so it knows what actions to perform. The automatic route registration is handled by the static RegisterRoutes<TCallbackHandler> method. This method is generic and totally reusable for any CallbackHandler type handler. To register a CallbackHandler and any RouteUrls it has defined you simple use code like this in Application_Start (or other application startup code):protected void Application_Start(object sender, EventArgs e) { // Register Routes for RestService CallbackHandlerRouteHandler.RegisterRoutes<RestService>(RouteTable.Routes); } If you have multiple CallbackHandler style services you can make multiple calls to RegisterRoutes for each of the service types. RegisterRoutes internally uses reflection to run through all the methods of the Handler, looking for CallbackMethod attributes and whether a RouteUrl is specified. If it is a new instance of a CallbackHandlerRouteHandler is created and the name of the method and the type are set. routes.Add(method.Name,           new Route(attr.RouteUrl, new CallbackHandlerRouteHandler(method.Name, typeof(TCallbackHandler) )) ); While the routing with CallbackHandlerRouteHandler is set up automatically for all methods that use the RouteUrl attribute, you can also use code to hook up those routes manually and skip using the attribute. The code for this is straightforward and just requires that you manually map each individual route to each method you want a routed: protected void Application_Start(objectsender, EventArgs e){    RegisterRoutes(RouteTable.Routes);}void RegisterRoutes(RouteCollection routes) { routes.Add("StockQuote Route",new Route("StockQuote/{symbol}",                     new CallbackHandlerRouteHandler("GetStockQuote",typeof(RestService) ) ) );     routes.Add("StockQuotes Route",new Route("StockQuotes/{symbolList}",                     new CallbackHandlerRouteHandler("GetStockQuotes",typeof(RestService) ) ) );}I think it’s clearly easier to have CallbackHandlerRouteHandler.RegisterRoutes() do this automatically for you based on RouteUrl attributes, but some people have a real aversion to attaching logic via attributes. Just realize that the option to manually create your routes is available as well. Using the RouteData in the Handler A RouteHandler’s responsibility is to create an HttpHandler and as mentioned earlier, natively IHttpHandler doesn’t have any support for RouteData. In order to utilize RouteData in your handler code you have to pass the RouteData to the handler. In my CallbackHandlerRouteHandler when it creates the HttpHandler instance it creates the instance and then assigns the custom RouteData property on the handler:IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; Again this only works if you actually add a RouteData property to your handler explicitly as I did in my CallbackHandler implementation:/// <summary> /// Optionally store RouteData on this handler /// so we can access it internally /// </summary> public RouteData RouteData {get; set; } and the RouteHandler needs to set it when it creates the handler instance. Once you have the route data in your handler you can access Route Keys and Values and also the RouteHandler. Since my RouteHandler has a custom property for the MethodName to retrieve it from within the handler I can do something like this now to retrieve the MethodName (this example is actually not in the handler but target is an instance pass to the processor): // check for Route Data method name if (target is CallbackHandler) { var routeData = ((CallbackHandler)target).RouteData; if (routeData != null) methodToCall = ((CallbackHandlerRouteHandler)routeData.RouteHandler).MethodName; } When I need to access the dynamic values in the route ( symbol in StockQuote/{symbol}) I can retrieve it easily with the Values collection (RouteData.Values["symbol"]). In my CallbackHandler processing logic I’m basically looking for matching parameter names to Route parameters: // look for parameters in the routeif(routeData != null){    string parmString = routeData.Values[parameter.Name] as string;    adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);} And with that we’ve come full circle. We’ve created a custom RouteHandler() that passes the RouteData to the handler it creates. We’ve registered our routes to use the RouteHandler, and we’ve utilized the route data in our handler. For completeness sake here’s the routine that executes a method call based on the parameters passed in and one of the options is to retrieve the inbound parameters off RouteData (as well as from POST data or QueryString parameters):internal object ExecuteMethod(string method, object target, string[] parameters, CallbackMethodParameterType paramType, ref CallbackMethodAttribute callbackMethodAttribute) { HttpRequest Request = HttpContext.Current.Request; object Result = null; // Stores parsed parameters (from string JSON or QUeryString Values) object[] adjustedParms = null; Type PageType = target.GetType(); MethodInfo MI = PageType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (MI == null) throw new InvalidOperationException("Invalid Server Method."); object[] methods = MI.GetCustomAttributes(typeof(CallbackMethodAttribute), false); if (methods.Length < 1) throw new InvalidOperationException("Server method is not accessible due to missing CallbackMethod attribute"); if (callbackMethodAttribute != null) callbackMethodAttribute = methods[0] as CallbackMethodAttribute; ParameterInfo[] parms = MI.GetParameters(); JSONSerializer serializer = new JSONSerializer(); RouteData routeData = null; if (target is CallbackHandler) routeData = ((CallbackHandler)target).RouteData; int parmCounter = 0; adjustedParms = new object[parms.Length]; foreach (ParameterInfo parameter in parms) { // Retrieve parameters out of QueryString or POST buffer if (parameters == null) { // look for parameters in the route if (routeData != null) { string parmString = routeData.Values[parameter.Name] as string; adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType); } // GET parameter are parsed as plain string values - no JSON encoding else if (HttpContext.Current.Request.HttpMethod == "GET") { // Look up the parameter by name string parmString = Request.QueryString[parameter.Name]; adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType); } // POST parameters are treated as methodParameters that are JSON encoded else if (paramType == CallbackMethodParameterType.Json) //string newVariable = methodParameters.GetValue(parmCounter) as string; adjustedParms[parmCounter] = serializer.Deserialize(Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType); else adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject( Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType); } else if (paramType == CallbackMethodParameterType.Json) adjustedParms[parmCounter] = serializer.Deserialize(parameters[parmCounter], parameter.ParameterType); else adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(parameters[parmCounter], parameter.ParameterType); parmCounter++; } Result = MI.Invoke(target, adjustedParms); return Result; } The code basically uses Reflection to loop through all the parameters available on the method and tries to assign the parameters from RouteData, QueryString or POST variables. The parameters are converted into their appropriate types and then used to eventually make a Reflection based method call. What’s sweet is that the RouteData retrieval is just another option for dealing with the inbound data in this scenario and it adds exactly two lines of code plus the code to retrieve the MethodName I showed previously – a seriously low impact addition that adds a lot of extra value to this endpoint callback processing implementation. Debugging your Routes If you create a lot of routes it’s easy to run into Route conflicts where multiple routes have the same path and overlap with each other. This can be difficult to debug especially if you are using automatically generated routes like the routes created by CallbackHandlerRouteHandler.RegisterRoutes. Luckily there’s a tool that can help you out with this nicely. Phill Haack created a RouteDebugging tool you can download and add to your project. The easiest way to do this is to grab and add this to your project is to use NuGet (Add Library Package from your Project’s Reference Nodes):   which adds a RouteDebug assembly to your project. Once installed you can easily debug your routes with this simple line of code which needs to be installed at application startup:protected void Application_Start(object sender, EventArgs e) { CallbackHandlerRouteHandler.RegisterRoutes<StockService>(RouteTable.Routes); // Debug your routes RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); } Any routed URL then displays something like this: The screen shows you your current route data and all the routes that are mapped along with a flag that displays which route was actually matched. This is useful – if you have any overlap of routes you will be able to see which routes are triggered – the first one in the sequence wins. This tool has saved my ass on a few occasions – and with NuGet now it’s easy to add it to your project in a few seconds and then remove it when you’re done. Routing Around Custom routing seems slightly complicated on first blush due to its disconnected components of RouteHandler, route registration and mapping of custom handlers. But once you understand the relationship between a RouteHandler, the RouteData and how to pass it to a handler, utilizing of Routing becomes a lot easier as you can easily pass context from the registration to the RouteHandler and through to the HttpHandler. The most important thing to understand when building custom routing solutions is to figure out how to map URLs in such a way that the handler can figure out all the pieces it needs to process the request. This can be via URL routing parameters and as I did in my example by passing additional context information as part of the RouteHandler instance that provides the proper execution context. In my case this ‘context’ was the method name, but it could be an actual static value like an enum identifying an operation or category in an application. Basically user supplied data comes in through the url and static application internal data can be passed via RouteHandler property values. Routing can make your application URLs easier to read by non-techie types regardless of whether you’re building Service type or REST applications, or full on Web interfaces. Routing in ASP.NET 4.0 makes it possible to create just about any extensionless URLs you can dream up and custom RouteHanmdler References Sample ProjectIncludes the sample CallbackHandler service discussed here along with compiled versionsof the Westwind.Web and Westwind.Utilities assemblies.  (requires .NET 4.0/VS 2010) West Wind Web Toolkit includes full implementation of CallbackHandler and the Routing Handler West Wind Web Toolkit Source CodeContains the full source code to the Westwind.Web and Westwind.Utilities assemblies usedin these samples. Includes the source described in the post.(Latest build in the Subversion Repository) CallbackHandler Source(Relevant code to this article tree in Westwind.Web assembly) JSONView FireFoxPluginA simple FireFox Plugin to easily view JSON data natively in FireFox.For IE you can use a registry hack to display JSON as raw text.© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  AJAX  HTTP  

    Read the article

  • jQuery: Prevent drop propragation over a draggable dialog

    - by Alban
    I have a page with some droppable <td elements and a dialog over the page with some draggable elements. When I drag an element over the dialog that is over a droppable <td, then elements drops inside it even if it is still being dragged over the dialog. Is there any way to prevent drop while the draggable is still over the dialog? For an example, see here: http://www.albanx.com/drop.jpg

    Read the article

  • Drag and drop fearture for a website

    - by gpuguy
    I have to design a website which will have drag and drop features for creating an e-card. So you select items from a tool box and drag and drop this item on the card area. Once you have completed the design you can publish the e-card on the web by clicking "Save and publish" button. What are the possible technologies for implementing this feature? The requirement is that the application should not degrade the performance of the website, and should not take much time in publishing once the user click "Save and publish" button.

    Read the article

  • 13.04 gnome problem with drag and drop and text selection

    - by Laurent BERNABE
    I have an ubuntu 13.04 gnome 64 bits, but since a few days I am facing serious problem for doing simple drag an drop : in nautilus, in eclipse, in the browser. Also I can't manage to select text areas with the mouse (the only way I found is to double click on the first word, then expand selection with shift and arrows keys). I noticed that often, after having started a drag n drop, it is cancelled though I did not release the left mouse ! It is as if for each simple mouse clic : two was done ! My graphic card is an ati radeon hd 4330, and I had installed the default purposed driver. I don't know if I should give you results from some terminal commands, as I don't know which could be useful. Thanks in advance.

    Read the article

  • Cannot move/drag/drop windows/items in remote VNC session

    - by hansioux
    I find it a little hard to believe that no one here has asked this question, I tried searching for it but it isn't asked, so here goes: I setup a Ubuntu desktop computer with VNC to use as a server. And use another Ubuntu desktop computer to VNC into it. The rest of the VNC works ok, but drag and drop with mouse is gone. Thus I can not move windows, or drag and drop items via VNC. I am using the default remote desktop in System - Preferences to setup my server. And use Remmina as my client. The same happens using MS Windows's VNC clients connecting to my Ubuntu desktop. I did a bit of searching on google, and there are actually a lot of reports regarding this issue. But, oddly there is no solution. There are even bug reports made for this since Ubuntu 9.10, yet here it still is in Ubuntu 11.04. There have been suggestions that the bugs is in gtk, as see in link below: http://ubuntuforums.org/showthread.php?t=1497635&page=2 libgtk2.0-0 stable(lenny) -> DnD works libgtk2.0-0 lenny-backport (libgtk2.0-0_2.18.6-1~bpo50+1_i386) -> DnD still works libgtk2.0-0 testing (libgtk2.0-0_2.20.1-2_i386) -> DnD broken please don't give answers such as "use NX", "use ssh -x" or "use x11vnc". I am aware that some people don't have this problem with x11vnc, and I have setup x11vnc before, but i can't for this setup. I am setting this up so Windows only friends/families can use it.

    Read the article

  • Override an IOCTL Handler in PQOAL

    - by Kate Moss' Big Fan
    When porting or creating a BSP to a new platform, we often need to make change to OEMIoControl or HAL IOCTL handler for more specific. Since Microsoft introduced PQOAL in CE 5.0 and more and more BSP today leverages PQOAL to simplify the OAL, we no longer define the OEMIoControl directly. It is somehow analogous to migrate from pure Windows SDK to MFC; people starts to define those MFC handlers and forgot the WinMain and the big message loop. If you ever take a look at the interface between OAL and Kernel, PUBLIC\COMMON\OAK\INC\oemglobal.h, the pfnOEMIoctl is still there just as the entry point of Windows Program is WinMain since day one. (For those may argue about pfnOEMIoctl is not OEMIoControl, I will encourage you to dig into PRIVATE\WINCEOS\COREOS\NK\OEMMAIN\oemglobal.c which initialized pfnOEMIoctl to OEMIoControl. The interface is just to split OAL and Kernel which no longer linked to one executable file in CE 6, all of the function signature is still identical) So let's trace into PQOAL to realize how it implements OEMIoControl and how can we override an IOCTL handler we interest. First thing to know is the entry point (just as finding the WinMain in MFC), OEMIoControl is defined in PLATFORM\COMMON\SRC\COMMON\IOCTL\ioctl.c. Basically, it does nothing special but scan a pre-defined IOCTL table, g_oalIoCtlTable, and then execute the handler. (The highlight part) Other than that is just for error handling and the use of critical section to serialize the function. BOOL OEMIoControl(     DWORD code, VOID *pInBuffer, DWORD inSize, VOID *pOutBuffer, DWORD outSize,     DWORD *pOutSize ) {     BOOL rc = FALSE;     UINT32 i; ...     // Search the IOCTL table for the requested code.     for (i = 0; g_oalIoCtlTable[i].pfnHandler != NULL; i++) {         if (g_oalIoCtlTable[i].code == code) break;     }     // Indicate unsupported code     if (g_oalIoCtlTable[i].pfnHandler == NULL) {         NKSetLastError(ERROR_NOT_SUPPORTED);         OALMSG(OAL_IOCTL, (             L"OEMIoControl: Unsupported Code 0x%x - device 0x%04x func %d\r\n",             code, code >> 16, (code >> 2)&0x0FFF         ));         goto cleanUp;     }            // Take critical section if required (after postinit & no flag)     if (         g_ioctlState.postInit &&         (g_oalIoCtlTable[i].flags & OAL_IOCTL_FLAG_NOCS) == 0     ) {         // Take critical section                    EnterCriticalSection(&g_ioctlState.cs);     }     // Execute the handler     rc = g_oalIoCtlTable[i].pfnHandler(         code, pInBuffer, inSize, pOutBuffer, outSize, pOutSize     );     // Release critical section if it was taken above     if (         g_ioctlState.postInit &&         (g_oalIoCtlTable[i].flags & OAL_IOCTL_FLAG_NOCS) == 0     ) {         // Release critical section                    LeaveCriticalSection(&g_ioctlState.cs);     } cleanUp:     OALMSG(OAL_IOCTL&&OAL_FUNC, (L"-OEMIoControl(rc = %d)\r\n", rc ));     return rc; }   Where is the g_oalIoCtlTable? It is defined in your BSP. Let's use DeviceEmulator BSP as an example. The PLATFORM\DEVICEEMULATOR\SRC\OAL\OALLIB\ioctl.c defines the table as const OAL_IOCTL_HANDLER g_oalIoCtlTable[] = { #include "ioctl_tab.h" }; And that leads to PLATFORM\DEVICEEMULATOR\SRC\INC\ioctl_tab.h which defined some of IOCTL handler but others are defined in oal_ioctl_tab.h which is under PLATFORM\COMMON\SRC\INC\. Finally, we got the full table body! (Just like tracing MFC, always jumping back and forth). The format of table is very straight forward, IOCTL code, Flags and Handler Function // IOCTL CODE,                          Flags   Handler Function //------------------------------------------------------------------------------ { IOCTL_HAL_INITREGISTRY,                   0,  OALIoCtlHalInitRegistry     }, { IOCTL_HAL_INIT_RTC,                       0,  OALIoCtlHalInitRTC          }, { IOCTL_HAL_REBOOT,                         0,  OALIoCtlHalReboot           }, The PQOAL scans through the table until it find a matched IOCTL code, then invokes the handler function. Since it scans the table from the top which means if we define TWO handler with same IOCTL code, the first one is always invoked with no exception. Now back to the PLATFORM\DEVICEEMULATOR\SRC\INC\ioctl_tab.h, with the following table { IOCTL_HAL_INITREGISTRY,                   0,  OALIoCtlDeviceEmulatorHalInitRegistry     }, ... #include <oal_ioctl_tab.h> Note the IOCTL_HAL_INITREGISTRY handler are defined in both BSP's local ioctl_tab.h and the common oal_ioctl_tab.h, but due to BSP's local handler comes before "#include <oal_ioctl_tab.h>" so we know the OALIoCtlDeviceEmulatorHalInitRegistry always get called. In this example, the DeviceEmulator BSP overrides the IOCTL_HAL_INITREGISTRY handler from OALIoCtlHalInitRegistry to OALIoCtlDeviceEmulatorHalInitRegistry by manipulating the g_oalIoCtlTable table. (In some point of view, it is similar to message map in MFC) Please be aware, when you override an IOCTL handler in PQOAL, you may want to clone the original implementation to your BSP and change to meet your need. It is recommended and save you the redundant works but remember to rename the handler function (Just like the DeviceEmulator it changes the name of OALIoCtlHalInitRegistry to OALIoCtlDeviceEmulatorHalInitRegistry). If you don't change the name, linker may not be happy (due to name conflict) and the more important is by using different handler name, you could always redirect the handler back to original one. (It is like the concept of OOP that calling a function in base class; still not so clear? I am goinf to show you soon!) The OALIoCtlDeviceEmulatorHalInitRegistry setups DeviceEmulator specific registry settings and in the end, if everything goes well, it calls the OALIoCtlHalInitRegistry (PLATFORM\COMMON\SRC\COMMON\IOCTL\reginit.c) to do the rest.     if(fOk) {         fOk = OALIoCtlHalInitRegistry(code, pInpBuffer, inpSize, pOutBuffer,             outSize, pOutSize);     } Now you got the picture, whenever you want to override an IOCTL hadnler that is implemented in PQOAL just Clone the handler function to your BSP as a template. Simple name change for the handler function, and a name change in the IOCTL table header file that maps the IOCTL with the function Implement your IOCTL handler and whenever you need to redirect it back just calling the original handler function. It is the standard way of implementing a custom IOCTL and most Microsoft developers prefer. The mapping of IOCTL routine to IOCTL code is platform specific - you control the header file that does that mapping.

    Read the article

  • jQuery Drag and Drop Checking Question

    - by Kim
    i am new to using jQuery and I just want to know how I can check whether a draggable object has been removed from the droppable object. Example, i have a dog and I dragged it to a doghouse which has a lightbulb that will light up indicating that the dog is there. When i drag the dog out of the doghouse, the lightbulb should go off again indicating the dog's absence. Help me please coz I really don't have any idea how to do this. Thanks in advance. :)

    Read the article

  • Update UI in the main activity through handler in a thread (Android)

    - by Hrk
    Hello, I try to make several connection in a class and update the multiple progressbar in the main screen. But I've got the following error trying to use thread in android : Code: 05-06 13:13:11.092: ERROR/ConnectionManager(22854): ERROR:Can't create handler inside thread that has not called Looper.prepare() Here is a small part of my code in the main Activity public class Act_Main extends ListActivity { private ConnectionManager cm; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up the window layout requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); } public void startConnection() { //open DB connection db = new DBAdapter(getApplicationContext()); db.open(); cm = new ConnectionManager(handler, db); showDialog(DIALOG_PROGRESS_LOGIN); } @Override public void onStart() { super.onStart(); startConnection(); } protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS_LOGIN: progressDialog = new ProgressDialog(Act_Main.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Connecting.\nPlease wait..."); progressThreadLogin = new ProgressThreadLogin(); progressThreadLogin.start(); return progressDialog; case DIALOG_PROGRESS_NETWORK: [b]progressDialog = new ProgressDialog(Act_Main.this);[/b] progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading entire network.\nPlease wait..."); progressThreadNetwork = new ProgressThreadNetwork(); progressThreadNetwork.start(); return progressDialog; default: return null; } } // Define the Handler that receives messages from the thread and update the progress final Handler handler = new Handler() { public void handleMessage(Message msg) { int total = msg.getData().getInt("total"); int step = msg.getData().getInt("step"); Log.d(TAG, "handleMessage:PROCESSBAR:"+total); progressDialog.setProgress(total); if (total >= 100) { switch (step) { case UPDATE_NETWORK: dismissDialog(DIALOG_PROGRESS_LOGIN); showDialog(DIALOG_PROGRESS_NETWORK); cm.getNetwork(); break; .... default: break; } } } }; private class ProgressThreadLogin extends Thread { ProgressThreadLogin() { } public void run() { cm.login(); } } private class ProgressThreadNetwork extends Thread { ProgressThreadNetwork() { } public void run() { cm.getNetwork(); } } } And my connectionManager class: public class ConnectionManager { public ConnectionManager(Handler handler, DBAdapter db) { this.handler = handler; this.db = db; } public void updateProgressBar(int step, int value) { if (value == 0) total = total+1; else total = value ; Message msg = handler.obtainMessage(); Bundle b = new Bundle(); b.putInt("total", total); b.putInt("step", step); msg.setData(b); handler.handleMessage(msg); } public void login() { //DO MY LOGIN TASK updateProgressBar(Act_Main.UPDATE_NETWORK, 100); } } The crash errors occurs on the first line of "case DIALOG_PROGRESS_NETWORK:". My first progressbar is hidden but the second one is not displayed. I think I've done somthing wrong using the threads and handlers but I dont' know why. I was first using handler.sendMessage in place of handler.handleMessage but when I had several task in my connectionManager, the progressbar was updated only at the end of all tasks. Thank you in advance for your help

    Read the article

  • iptables rules keep showing up

    - by Omriko
    I just installed an ubuntu precise server, after a few weird communications issues I checked the iptables list and found: Chain INPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp -- 10.0.0.0/24 anywhere tcp spts:1024:65535 dpt:ssh state NEW ACCEPT icmp -- anywhere anywhere state NEW ACCEPT icmp -- anywhere anywhere state NEW ACCEPT icmp -- anywhere anywhere state NEW ACCEPT icmp -- anywhere anywhere state NEW DROP tcp -- anywhere anywhere tcp dpt:10520 state NEW DROP udp -- anywhere anywhere udp spts:1:65535 dpt:31337 state NEW DROP udp -- anywhere anywhere udp spts:1:65535 dpt:31338 state NEW DROP udp -- anywhere anywhere udp spts:1:65535 dpt:54320 state NEW DROP udp -- anywhere anywhere udp spts:1:65535 dpt:54321 state NEW DROP tcp -- anywhere anywhere tcp dpt:12345 state NEW DROP tcp -- anywhere anywhere tcp dpt:12346 state NEW DROP tcp -- anywhere anywhere tcp dpt:20034 state NEW DROP tcp -- anywhere anywhere tcp dpt:16600 state NEW DROP tcp -- anywhere anywhere tcp dpt:16660 state NEW DROP tcp -- anywhere anywhere tcp dpt:65000 state NEW DROP udp -- anywhere anywhere udp dpt:34555 state NEW DROP udp -- anywhere anywhere udp dpt:35555 state NEW DROP udp -- anywhere anywhere udp spts:netbios-ns:netbios-dgm dpts:netbios-ns:netbios-dgm state NEW DROP tcp -- anywhere anywhere tcp spts:1024:65535 dpt:netbios-ssn state NEW DROP tcp -- anywhere anywhere tcp spts:1024:65535 dpt:microsoft-ds state NEW DROP udp -- anywhere anywhere udp spt:microsoft-ds dpt:microsoft-ds state NEW DROP udp -- anywhere anywhere udp spts:1024:65535 dpt:microsoft-ds state NEW DROP tcp -- anywhere anywhere tcp spts:1024:65535 dpt:loc-srv state NEW DROP tcp -- anywhere anywhere tcp spts:1024:65535 dpt:5000 state NEW DROP tcp -- anywhere anywhere tcp spts:1024:65535 dpts:1025:1029 state NEW DROP udp -- anywhere anywhere udp spts:1:65535 dpt:loc-srv state NEW ACCEPT tcp -- anywhere anywhere tcp spts:1024:65535 dpt:28082 state NEW DROP all -- anywhere anywhere state NEW Chain FORWARD (policy DROP) target prot opt source destination Chain OUTPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp -- anywhere anywhere tcp spts:tcpmux:65535 dpts:tcpmux:65535 state NEW ACCEPT udp -- anywhere anywhere udp dpts:1:65535 state NEW ACCEPT icmp -- anywhere anywhere state NEW ACCEPT tcp -- anywhere anywhere tcp spts:1024:65535 dpt:28082 state NEW DROP all -- anywhere anywhere state NEW I tried to wipe the rules, I disabled UFW, Ive rewritten and saved iptables rules according to this guide, but every minute or so the old rules return.... I checked crontab for scheduled tasks, there is nothing in there but still these rules appear every minute... please help!

    Read the article

  • what is need for a handler in general

    - by nish
    I have been searching for a definition for handler. basics i've understood that "A handler is a piece of code that is called when something happens, and usually takes some action, like generating a response." - (from http://stackoverflow.com/questions/3246200/what-is-an-handler ). But that can be a trigger or a callback. Also in specific an event handler on a low-level , often works by polling a device and waiting for a hardware response. So, what is the specific role of a handler ( that makes it unique from a trigger or a callback or any other such function ). Do all handlers have similar role ( event handler, file handler , exception handler, error handler )...

    Read the article

  • ASP.NET Web Forms Extensibility: Handler Factories

    - by Ricardo Peres
    An handler factory is the class that implements IHttpHandlerFactory and is responsible for instantiating an handler (IHttpHandler) that will process the current request. This is true for all kinds of web requests, whether they are for ASPX pages, ASMX/SVC web services, ASHX/AXD handlers, or any other kind of file. Also used for restricting access for certain file types, such as Config, Csproj, etc. Handler factories are registered on the global Web.config file, normally located at %WINDIR%\Microsoft.NET\Framework<x64>\vXXXX\Config for a given path and request type (GET, POST, HEAD, etc). This goes on section <httpHandlers>. You would create a custom handler factory for a number of reasons, let me list just two: A centralized place for using dependency injection; Also a centralized place for invoking custom methods or performing some kind of validation on all pages. Let’s see an example using Unity for injecting dependencies into a page, suppose we have this on Global.asax.cs: 1: public class Global : HttpApplication 2: { 3: internal static readonly IUnityContainer Unity = new UnityContainer(); 4: 5: void Application_Start(Object sender, EventArgs e) 6: { 7: Unity.RegisterType<IFunctionality, ConcreteFunctionality>(); 8: } 9: } We instantiate Unity and register a concrete implementation for an interface, this could/should probably go in the Web.config file. Forget about its actual definition, it’s not important. Then, we create a custom handler factory: 1: public class UnityPageHandlerFactory : PageHandlerFactory 2: { 3: public override IHttpHandler GetHandler(HttpContext context, String requestType, String virtualPath, String path) 4: { 5: IHttpHandler handler = base.GetHandler(context, requestType, virtualPath, path); 6: 7: //one scenario: inject dependencies 8: Global.Unity.BuildUp(handler.GetType(), handler, String.Empty); 9:  10: return (handler); 11: } 12: } It inherits from PageHandlerFactory, which is .NET’s included factory for building regular ASPX pages. We override the GetHandler method and issue a call to the BuildUp method, which will inject required dependencies, if any exist. An example page with dependencies might be: 1: public class SomePage : Page 2: { 3: [Dependency] 4: public IFunctionality Functionality 5: { 6: get; 7: set; 8: } 9: } Notice the DependencyAttribute, it is used by Unity to identify properties that require dependency injection. When BuildUp is called, the Functionality property (or any other properties with the DependencyAttribute attribute) will receive the concrete implementation associated with it’s type, as registered on Unity. Another example, checking a page for authorization. Let’s define an interface first: 1: public interface IRestricted 2: { 3: Boolean Check(HttpContext ctx); 4: } An a page implementing that interface: 1: public class RestrictedPage : Page, IRestricted 2: { 3: public Boolean Check(HttpContext ctx) 4: { 5: //check the context and return a value 6: return ...; 7: } 8: } For this, we would use an handler factory such as this: 1: public class RestrictedPageHandlerFactory : PageHandlerFactory 2: { 3: private static readonly IHttpHandler forbidden = new UnauthorizedHandler(); 4:  5: public override IHttpHandler GetHandler(HttpContext context, String requestType, String virtualPath, String path) 6: { 7: IHttpHandler handler = base.GetHandler(context, requestType, virtualPath, path); 8: 9: if (handler is IRestricted) 10: { 11: if ((handler as IRestricted).Check(context) == false) 12: { 13: return (forbidden); 14: } 15: } 16:  17: return (handler); 18: } 19: } 20:  21: public class UnauthorizedHandler : IHttpHandler 22: { 23: #region IHttpHandler Members 24:  25: public Boolean IsReusable 26: { 27: get { return (true); } 28: } 29:  30: public void ProcessRequest(HttpContext context) 31: { 32: context.Response.StatusCode = (Int32) HttpStatusCode.Unauthorized; 33: context.Response.ContentType = "text/plain"; 34: context.Response.Write(context.Response.Status); 35: context.Response.Flush(); 36: context.Response.Close(); 37: context.ApplicationInstance.CompleteRequest(); 38: } 39:  40: #endregion 41: } The UnauthorizedHandler is an example of an IHttpHandler that merely returns an error code to the client, but does not cause redirection to the login page, it is included merely as an example. One thing we must keep in mind is, there can be only one handler factory registered for a given path/request type (verb) tuple. A typical registration would be: 1: <httpHandlers> 2: <remove path="*.aspx" verb="*"/> 3: <add path="*.aspx" verb="*" type="MyNamespace.MyHandlerFactory, MyAssembly"/> 4: </httpHandlers> First we remove the previous registration for ASPX files, and then we register our own. And that’s it. A very useful mechanism which I use lots of times.

    Read the article

  • Drag and Drop File into Application under run as administrator

    - by Chris Dwyer
    Whenever I have an application running (Visual Studio 2008, Notepad, etc.) under "Run as Administrator", I cannot drag and drop files from Windows Explorer into the application. I've tried running Windows Explorer as administrator, but to no avail. Is there a way to get drag and drop to work when my applications are under "Run as Administrator"?

    Read the article

  • Python Tkinter - Edit external object within event handler?

    - by M3RPHY
    Hey all, As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location, however I cannot for the life of me figure out how to edit the label's text field (or any external object for that matter) within the event handler. From what I understand, event is the only argument passed to the handler, which means I can't pass the label object. How do I access objects outside of the handler? Apologize for the noobish question as I'm a C programmer new to Python. Thanks!

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >