ImageResizer  3.4.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events
Public Member Functions | Protected Member Functions | Properties | List of all members
ImageResizer.Plugins.SqlReader.SqlReaderPlugin Class Reference

Specialized VirtualPathProvider that allows accessing database images as if they are on disk. More...

Inheritance diagram for ImageResizer.Plugins.SqlReader.SqlReaderPlugin:
Inheritance graph
[legend]
Collaboration diagram for ImageResizer.Plugins.SqlReader.SqlReaderPlugin:
Collaboration graph
[legend]

Public Member Functions

 SqlReaderPlugin (NameValueCollection args)
 
 SqlReaderPlugin (SqlReaderSettings s)
 
IPlugin Install (Configuration.Config c)
 Installes the plugin into the specified configuration. Once installed, it cannot be uninstalled. More...
 
bool Uninstall (Configuration.Config c)
 This plugin cannot be uninstalled as ASP.NET does not provide a 'undo' function for RegisterVirtualPathProvider More...
 
virtual void FireAuthorizeEvent (string id)
 Called before any database op. Fires the BeforeAccess event More...
 
Stream GetStream (string id)
 Returns a stream to the More...
 
SqlParameter CreateIdParameter (string id)
 Creates a SQL paramater of the correct type for the row id More...
 
bool RowExists (string id)
 Executes existsQuery, and returns true if the value is greater than 0 More...
 
DateTime GetDateModifiedUtc (string id)
 Returns DateTime.MinValue if there are no rows, or no values on the row. Executes ModifiedDateQuery, then returns the first non-null datetime value on the first row. More...
 
SqlConnection GetConnectionObj ()
 Creates and returns a SqlConnection object for the database based on the configuration. More...
 
SqlCommand GetCacheDependencyQuery (string id)
 Returns a SqlCommand cache dependency using the modifiedQuery. More...
 
virtual string ParseIdFromVirtualPath (string virtualPath)
 Supports int, string, and GUID IDs. Override this to modify ID parsing if you can't do it with rewrite rules. More...
 
override bool FileExists (string virtualPath)
 VPP method - not for external use More...
 
override VirtualFile GetFile (string virtualPath)
 VPP method, not for external use More...
 
bool FileExists (string virtualPath, NameValueCollection queryString)
 Returns true if the specified virtual file should be provided by this reader and it exists. False if this provider cannot/should not provide it, or it doesn't exist. More...
 
IVirtualFile GetFile (string virtualPath, NameValueCollection queryString)
 Returns an IVirtualFile instance if the file exists in this provider. More...
 
override CacheDependency GetCacheDependency (string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
 VPP method, not for external use More...
 
IEnumerable< IIssueGetIssues ()
 Provides the diagnostics system with a list of configuration issues More...
 
Configuration.Xml.Node RedactFrom (Node resizer)
 
- Public Member Functions inherited from ImageResizer.Plugins.IPlugin
IPlugin Install (Config c)
 Installs the plugin in the specified Config instance. The plugin must handle all the work of loading settings, registering the plugin etc. More...
 
bool Uninstall (Config c)
 Uninstalls the plugin. Should reverse all changes made during Install More...
 

Protected Member Functions

override void Initialize ()
 No initialization needed for this VPP More...
 

Properties

SqlReaderSettings Settings [get]
 Provides all the configuration options for the plugin. More...
 
bool FailedToRegisterVpp [get]
 True if the provider attempted to register itself as a VirtualPathProvider and failed due to limited security clearance. False if it did not attempt, or if it succeeded. More...
 
bool IsStringKey [get]
 Returns true if Settings.ImageIdType is a string type More...
 
bool IsIntKey [get]
 Returns true if Settings.ImageIdType is an integer type More...
 

Detailed Description

Specialized VirtualPathProvider that allows accessing database images as if they are on disk.

Definition at line 21 of file SqlReader.cs.

Member Function Documentation

SqlParameter ImageResizer.Plugins.SqlReader.SqlReaderPlugin.CreateIdParameter ( string  id)
inline

Creates a SQL paramater of the correct type for the row id

Parameters
id
Returns

Definition at line 138 of file SqlReader.cs.

139  {
140  SqlParameter sp = new SqlParameter("id", s.ImageIdType);
141  if (IsIntKey) {
142  sp.Size = 4;
143  sp.Value = long.Parse(id);
144  } else if (s.ImageIdType == System.Data.SqlDbType.UniqueIdentifier)
145  sp.Value = new Guid(id);
146  else if (IsStringKey)
147  sp.Value = id;
148 
149  return sp;
150  }
bool IsIntKey
Returns true if Settings.ImageIdType is an integer type
Definition: SqlReader.cs:162
SqlDbType ImageIdType
Specifies the type of ID used for images. Int, string, and GUID types are the only valid values...
bool IsStringKey
Returns true if Settings.ImageIdType is a string type
Definition: SqlReader.cs:154
override bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.FileExists ( string  virtualPath)
inline

VPP method - not for external use

Parameters
virtualPath
Returns

Definition at line 333 of file SqlReader.cs.

334  {
335  if (IsPathVirtual(virtualPath))
336  {
337  return !s.CheckForModifiedFiles || RowExists(ParseIdFromVirtualPath(virtualPath));
338  }
339  else
340  return Previous.FileExists(virtualPath);
341  }
bool RowExists(string id)
Executes existsQuery, and returns true if the value is greater than 0
Definition: SqlReader.cs:174
virtual string ParseIdFromVirtualPath(string virtualPath)
Supports int, string, and GUID IDs. Override this to modify ID parsing if you can&#39;t do it with rewrit...
Definition: SqlReader.cs:273
bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.FileExists ( string  virtualPath,
NameValueCollection  queryString 
)
inline

Returns true if the specified virtual file should be provided by this reader and it exists. False if this provider cannot/should not provide it, or it doesn't exist.

Parameters
virtualPath
queryString
Returns

Implements ImageResizer.Plugins.IVirtualImageProvider.

Definition at line 362 of file SqlReader.cs.

362  {
363  return IsPathVirtual(virtualPath) && (!s.CheckForModifiedFiles || RowExists(ParseIdFromVirtualPath(virtualPath)));
364  }
bool RowExists(string id)
Executes existsQuery, and returns true if the value is greater than 0
Definition: SqlReader.cs:174
virtual string ParseIdFromVirtualPath(string virtualPath)
Supports int, string, and GUID IDs. Override this to modify ID parsing if you can&#39;t do it with rewrit...
Definition: SqlReader.cs:273
virtual void ImageResizer.Plugins.SqlReader.SqlReaderPlugin.FireAuthorizeEvent ( string  id)
inlinevirtual

Called before any database op. Fires the BeforeAccess event

Parameters
id

Definition at line 105 of file SqlReader.cs.

105  {
106  s.FireBeforeAccess(id);
107  }
override CacheDependency ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetCacheDependency ( string  virtualPath,
System.Collections.IEnumerable  virtualPathDependencies,
DateTime  utcStart 
)
inline

VPP method, not for external use

Parameters
virtualPath
virtualPathDependencies
utcStart
Returns

Definition at line 383 of file SqlReader.cs.

387  {
388  if (IsPathVirtual(virtualPath))
389  return new SqlCacheDependency(GetCacheDependencyQuery(ParseIdFromVirtualPath(virtualPath)));
390  else
391  return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
392  }
virtual string ParseIdFromVirtualPath(string virtualPath)
Supports int, string, and GUID IDs. Override this to modify ID parsing if you can&#39;t do it with rewrit...
Definition: SqlReader.cs:273
SqlCommand GetCacheDependencyQuery(string id)
Returns a SqlCommand cache dependency using the modifiedQuery.
Definition: SqlReader.cs:254
SqlCommand ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetCacheDependencyQuery ( string  id)
inline

Returns a SqlCommand cache dependency using the modifiedQuery.

Parameters
id
Returns

Definition at line 254 of file SqlReader.cs.

254  {
255  SqlCommand sc = new SqlCommand(s.ModifiedDateQuery, GetConnectionObj());
256  sc.CommandType = s.QueriesAreStoredProcedures ? System.Data.CommandType.StoredProcedure : System.Data.CommandType.Text;
257  sc.Parameters.Add(CreateIdParameter(id));
258  return sc;
259  }
SqlParameter CreateIdParameter(string id)
Creates a SQL paramater of the correct type for the row id
Definition: SqlReader.cs:138
string ModifiedDateQuery
The query that returns the modified and created date of the image. Defaults to &quot;Select ModifiedDate...
SqlConnection GetConnectionObj()
Creates and returns a SqlConnection object for the database based on the configuration.
Definition: SqlReader.cs:227
SqlConnection ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetConnectionObj ( )
inline

Creates and returns a SqlConnection object for the database based on the configuration.

Returns

Definition at line 227 of file SqlReader.cs.

227  {
228 
229  //First, try the connection string as a connection string key.
230  if (System.Configuration.ConfigurationManager.ConnectionStrings[s.ConnectionString] != null)
231  return new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[s.ConnectionString].ConnectionString);
232 
233  //Second, try the .NET syntax
234  string prefix = "ConnectionStrings:";
235  //ConnectionStrings:namedString convention
236  if (s.ConnectionString.Trim().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {
237  string key = s.ConnectionString.Trim().Substring(prefix.Length).Trim();
238  if (System.Configuration.ConfigurationManager.ConnectionStrings[key] != null)
239  return new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[key].ConnectionString);
240  else
241  throw new ImageResizer.ImageProcessingException("SqlReader: Failed to locate the named connection string '" + key + "' in web.config");
242 
243  }
244 
245  //Third, try it as an actual connection string
246  return new SqlConnection(s.ConnectionString);
247  }
Represents an non-recoverable exception that occured while processing the image. Possible causes are:...
string ConnectionString
The database connection string. Defaults to null. You can specify an existing web.config connection string using the &quot;ConnectionStrings:namedKey&quot; convention.
DateTime ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetDateModifiedUtc ( string  id)
inline

Returns DateTime.MinValue if there are no rows, or no values on the row. Executes ModifiedDateQuery, then returns the first non-null datetime value on the first row.

Parameters
id
Returns

Definition at line 195 of file SqlReader.cs.

195  {
196  FireAuthorizeEvent(id);
197  SqlConnection conn = GetConnectionObj();
198  conn.Open();
199  using (conn)
200  {
201  SqlCommand sc = new SqlCommand(s.ModifiedDateQuery, conn);
202  sc.Parameters.Add(CreateIdParameter(id));
203  sc.CommandType = s.QueriesAreStoredProcedures ? System.Data.CommandType.StoredProcedure : System.Data.CommandType.Text;
204  SqlDataReader sdr = sc.ExecuteReader();
205  using (sdr)
206  {
207  if (!sdr.Read()) return DateTime.MinValue; //0 rows
208 
209  for (int i = 0; i < sdr.FieldCount; i++)
210  {
211  if (!sdr.IsDBNull(i) && sdr.GetValue(i) is DateTime)
212  {
213  DateTime val = (DateTime)sdr.GetValue(i);
214  if (val.Kind == DateTimeKind.Unspecified) val = DateTime.SpecifyKind(val, DateTimeKind.Utc);
215  return val; //Return the first non-null datetime instance in the row. Regardless of value.
216  }
217  }
218  }
219  }
220  return DateTime.MinValue;
221  }
SqlParameter CreateIdParameter(string id)
Creates a SQL paramater of the correct type for the row id
Definition: SqlReader.cs:138
string ModifiedDateQuery
The query that returns the modified and created date of the image. Defaults to &quot;Select ModifiedDate...
SqlConnection GetConnectionObj()
Creates and returns a SqlConnection object for the database based on the configuration.
Definition: SqlReader.cs:227
virtual void FireAuthorizeEvent(string id)
Called before any database op. Fires the BeforeAccess event
Definition: SqlReader.cs:105
override VirtualFile ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetFile ( string  virtualPath)
inline

VPP method, not for external use

Parameters
virtualPath
Returns

Definition at line 348 of file SqlReader.cs.

349  {
350  if (IsPathVirtual(virtualPath))
351 
352  return new DatabaseFile(virtualPath, this);
353  else
354  return Previous.GetFile(virtualPath);
355  }
IVirtualFile ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetFile ( string  virtualPath,
NameValueCollection  queryString 
)
inline

Returns an IVirtualFile instance if the file exists in this provider.

Parameters
virtualPath
queryString
Returns

Implements ImageResizer.Plugins.IVirtualImageProvider.

Definition at line 372 of file SqlReader.cs.

372  {
373  return IsPathVirtual(virtualPath) ? new DatabaseFile(virtualPath, this) : null;
374  }
IEnumerable<IIssue> ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetIssues ( )
inline

Provides the diagnostics system with a list of configuration issues

Returns

Implements ImageResizer.Configuration.Issues.IIssueProvider.

Definition at line 398 of file SqlReader.cs.

398  {
399  List<IIssue> issues = new List<IIssue>();
400 
401  //1) Verify named connection strings exist
402  string prefix = "ConnectionStrings:";
403  //ConnectionStrings:namedString convention
404  if (s != null && s.ConnectionString != null && s.ConnectionString.Trim().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {
405  string key = s.ConnectionString.Trim().Substring(prefix.Length).Trim();
406  if (System.Configuration.ConfigurationManager.ConnectionStrings[key] == null)
407  issues.Add(new Issue("SqlReader", "Failed to locate the named connection string '" + key + "' in web.config","", IssueSeverity.ConfigurationError));
408 
409  }
410 
412  issues.Add(new Issue("SqlReader", "Failed to register as VirtualPathProvider.",
413  "Only the image resizer will be able to access files located in SQL - other systems will not be able to.", IssueSeverity.Error));
414 
415 
416  return issues;
417  }
string ConnectionString
The database connection string. Defaults to null. You can specify an existing web.config connection string using the &quot;ConnectionStrings:namedKey&quot; convention.
bool FailedToRegisterVpp
True if the provider attempted to register itself as a VirtualPathProvider and failed due to limited ...
Definition: SqlReader.cs:44
Stream ImageResizer.Plugins.SqlReader.SqlReaderPlugin.GetStream ( string  id)
inline

Returns a stream to the

Parameters
id
Returns

Definition at line 113 of file SqlReader.cs.

114  {
115  FireAuthorizeEvent(id);
116  SqlConnection conn = GetConnectionObj();
117  conn.Open();
118  using (conn)
119  {
120  SqlCommand sc = new SqlCommand(s.ImageBlobQuery, conn);
121  sc.CommandType = s.QueriesAreStoredProcedures ? System.Data.CommandType.StoredProcedure : System.Data.CommandType.Text;
122  sc.Parameters.Add(CreateIdParameter(id));
123  SqlDataReader sdr = sc.ExecuteReader();
124  using (sdr)
125  {
126  if (!sdr.Read()) throw new FileNotFoundException("Failed to find the specified image " + id + " in the database"); //0 rows
127 
128  return sdr.GetSqlBytes(0).Stream; //No connection required for the stream, all cloned in memory.
129  }
130  }
131  }
SqlParameter CreateIdParameter(string id)
Creates a SQL paramater of the correct type for the row id
Definition: SqlReader.cs:138
SqlConnection GetConnectionObj()
Creates and returns a SqlConnection object for the database based on the configuration.
Definition: SqlReader.cs:227
string ImageBlobQuery
The query that returns the binary image data based on the ID. Defaults to &quot;SELECT Content FROM Images...
virtual void FireAuthorizeEvent(string id)
Called before any database op. Fires the BeforeAccess event
Definition: SqlReader.cs:105
override void ImageResizer.Plugins.SqlReader.SqlReaderPlugin.Initialize ( )
inlineprotected

No initialization needed for this VPP

Definition at line 264 of file SqlReader.cs.

265  {
266  }
IPlugin ImageResizer.Plugins.SqlReader.SqlReaderPlugin.Install ( Configuration.Config  c)
inline

Installes the plugin into the specified configuration. Once installed, it cannot be uninstalled.

Parameters
c
Returns

Definition at line 53 of file SqlReader.cs.

53  {
54  c.Plugins.add_plugin(this);
55 
56  c.Pipeline.PostAuthorizeRequestStart += delegate(IHttpModule sender2, HttpContext context) {
57  //Only work with database images
58  //This allows us to resize database images without putting ".jpg" after the ID in the path.
59  if ((!s.RequireImageExtension || s.UntrustedData) && c.Pipeline.PreRewritePath.StartsWith(s.VirtualPathPrefix, StringComparison.OrdinalIgnoreCase))
60  c.Pipeline.SkipFileTypeCheck = true; //Skip the file extension check. FakeExtensions will still be stripped.
61  };
62 
63 
64  c.Pipeline.RewriteDefaults += delegate(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e) {
65  //Only work with database images
66  //Non-images will be served as-is
67  //Cache all file types, whether they are processed or not.
68  if (s.CacheUnmodifiedFiles && e.VirtualPath.StartsWith(s.VirtualPathPrefix, StringComparison.OrdinalIgnoreCase))
69  e.QueryString["cache"] = ServerCacheMode.Always.ToString();
70 
71 
72  };
73  c.Pipeline.PostRewrite += delegate(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e) {
74  //Only work with database images
75  //If the data is untrusted, always re-encode each file.
76  if (s.UntrustedData && e.VirtualPath.StartsWith(s.VirtualPathPrefix, StringComparison.OrdinalIgnoreCase))
77  e.QueryString["process"] = ImageResizer.ProcessWhen.Always.ToString();
78 
79  };
81  try {
82  HostingEnvironment.RegisterVirtualPathProvider(this);
83  } catch (SecurityException) {
84  this._failedToRegisterVpp = true;
85  }
86  }
87 
88  return this;
89  }
bool CacheUnmodifiedFiles
(default false). When true, files and unmodified images (i.e, no querystring) will be cached to disk ...
bool RequireImageExtension
(default true) When false, all URLs inside the PathPrefix folder will be assumed to be images...
bool UntrustedData
(default: false) When true, all requests will be re-encoded before being served to the client...
bool RegisterAsVirtualPathProvider
(default: true) When true, the SqlReader will be registered as a VirtualPathProvider with ASP...
ServerCacheMode
When to disk cache the image
Definition: Enumerations.cs:36
string VirtualPathPrefix
Returns PathPrefix, but with the &quot;~&quot; resolved - I.e, a full virtual path. If the string doesn&#39;t sta...
virtual string ImageResizer.Plugins.SqlReader.SqlReaderPlugin.ParseIdFromVirtualPath ( string  virtualPath)
inlinevirtual

Supports int, string, and GUID IDs. Override this to modify ID parsing if you can't do it with rewrite rules.

Parameters
virtualPath
Returns

Definition at line 273 of file SqlReader.cs.

274  {
275  String checkPath = ImageResizer.Util.PathUtils.ResolveAppRelative(virtualPath);
276  //Check for prefix
277  if (!checkPath.StartsWith(s.VirtualPathPrefix, StringComparison.OrdinalIgnoreCase)) return null;
278  string id = checkPath.Substring(s.VirtualPathPrefix.Length); //Strip prefix
279  //Strip slashes at beginning
280  id = id.TrimStart(new char[] { '/', '\\' });
281  //Strip extension if not a string
282  if (!IsStringKey || s.StripFileExtension) {
283  int length = id.LastIndexOf('.');
284  if (length > -1) id = id.Substring(0, length);
285  }
286  //Can't be empty.
287  if (id.Length < 1) return null;
288  //Verify only valid characters present
289  if (IsIntKey)
290  {
291  long val =0;
292  if (!long.TryParse(id, out val)) return null; // not a valid integer
293  }
294  else if (s.ImageIdType == System.Data.SqlDbType.UniqueIdentifier)
295  {
296  try
297  {
298  Guid test = new Guid(id);
299  }
300  catch
301  {
302  return null; //Not a valid guid.
303  }
304 
305  } else if (IsStringKey) {
306  return id;
307  }else {
308  throw new ImageProcessingException("Only Integer, String, and GUID identifiers are suported by SqlReader");
309  }
310 
311  return id;
312  }
bool IsIntKey
Returns true if Settings.ImageIdType is an integer type
Definition: SqlReader.cs:162
SqlDbType ImageIdType
Specifies the type of ID used for images. Int, string, and GUID types are the only valid values...
bool StripFileExtension
When true, the last file extension segment will be removed from the URL before the SQL Id is parsed...
bool IsStringKey
Returns true if Settings.ImageIdType is a string type
Definition: SqlReader.cs:154
string VirtualPathPrefix
Returns PathPrefix, but with the &quot;~&quot; resolved - I.e, a full virtual path. If the string doesn&#39;t sta...
bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.RowExists ( string  id)
inline

Executes existsQuery, and returns true if the value is greater than 0

Parameters
id
Returns

Definition at line 174 of file SqlReader.cs.

174  {
175  FireAuthorizeEvent(id);
176  SqlConnection conn = GetConnectionObj();
177  conn.Open();
178  using (conn)
179  {
180  SqlCommand sc = new SqlCommand(s.ImageExistsQuery, conn);
181  sc.CommandType = s.QueriesAreStoredProcedures ? System.Data.CommandType.StoredProcedure : System.Data.CommandType.Text;
182  sc.Parameters.Add(CreateIdParameter(id));
183  int count = (int)sc.ExecuteScalar();
184  if (count > 0) return true;
185  }
186  return false;
187  }
SqlParameter CreateIdParameter(string id)
Creates a SQL paramater of the correct type for the row id
Definition: SqlReader.cs:138
SqlConnection GetConnectionObj()
Creates and returns a SqlConnection object for the database based on the configuration.
Definition: SqlReader.cs:227
virtual void FireAuthorizeEvent(string id)
Called before any database op. Fires the BeforeAccess event
Definition: SqlReader.cs:105
string ImageExistsQuery
The query that returns whether an image exists or not. Defaults to &quot;Select COUNT(ImageID) From Images...
bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.Uninstall ( Configuration.Config  c)
inline

This plugin cannot be uninstalled as ASP.NET does not provide a 'undo' function for RegisterVirtualPathProvider

Parameters
c
Returns

Definition at line 96 of file SqlReader.cs.

96  {
97  return false;
98  }

Property Documentation

bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.FailedToRegisterVpp
get

True if the provider attempted to register itself as a VirtualPathProvider and failed due to limited security clearance. False if it did not attempt, or if it succeeded.

Definition at line 44 of file SqlReader.cs.

bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.IsIntKey
get

Returns true if Settings.ImageIdType is an integer type

Definition at line 162 of file SqlReader.cs.

bool ImageResizer.Plugins.SqlReader.SqlReaderPlugin.IsStringKey
get

Returns true if Settings.ImageIdType is a string type

Definition at line 154 of file SqlReader.cs.

SqlReaderSettings ImageResizer.Plugins.SqlReader.SqlReaderPlugin.Settings
get

Provides all the configuration options for the plugin.

Definition at line 36 of file SqlReader.cs.


The documentation for this class was generated from the following file: