Blog Archives
Custom DAL Class SQL ORM ASP .NET
(common.DataObject may be of your choosing or may simply replace with dynamic)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Web.UI.WebControls; using System.Web.UI; using System.Data.SqlClient; using AIS.Common; //this is a common namespace I use in examples throughout my site using System.Reflection; using System.Dynamic; //TODO: consider returning ienumerable in sp return values for lazy eval vs .tolist immediate eval namespace AIS.DAL.AppName { public static class StoredProcedures { public delegate void ErrorHandler(Exception ex); /// <summary> /// If no custom error handling is bound to this event, exceptions will be thrown back up to the calling function. /// If custom handling is bound to this event, ensure it does not perform a redirect or kill the thread unless you intend to abort the procedural /// steps following the method/function call which threw the error. /// </summary> public static event ErrorHandler HandleError; #region Unique Procedures public static List<Common.DataObject> LoadUserSessions_All(dynamic o) { return ExecuteRead("an_get_db_fn1", o); } public static List<Common.DataObject> LoadUserSessionsDetails_LiveStream(dynamic o) { return ExecuteRead("an_get_db_fn2", o); } public static List<Common.DataObject> LoadUserSessionsDetails_Live(dynamic o) { return ExecuteRead("an_get_db_fn3", o); } public static int LogChat() { return ExecuteScalar("an_get_db_fn4", null); } public static int LogError() { return ExecuteScalar("an_get_db_fn5", null); } #endregion //TODO: consider hiding from external assemblies which would require strong mappings above #region Execution Logic public static List<Common.DataObject> ExecuteRead(string procedurename, dynamic param) { try { SqlDataSource sds = new SqlDataSource(); sds.ConnectionString = ConfigValues.TrainingPortalConnectionString; sds.SelectCommandType = SqlDataSourceCommandType.StoredProcedure; sds.SelectCommand = procedurename; if (param != null) { foreach (PropertyInfo pi in param.GetType().GetProperties()) { object pval = pi.GetValue(param, null); if (pval != null) { sds.SelectParameters.Add(pi.Name, pval.ToString()); } } } List<Common.DataObject> results = new List<Common.DataObject>(); //sds.Select(new DataSourceSelectArguments()).Cast<DataRowView>().ToList().ForEach(o => Load_AddResult<dynamic>(o, ref results)); sds.Select(new DataSourceSelectArguments()).Cast<DataRowView>().ToList().ForEach(o => Load_AddResult<Common.DataObject>(o, ref results)); return results; } catch (Exception ex) { HandleError_Condensed(ex); return null; } } public static void Load_AddResult<t>(Common.DataObject o, ref List<t> results) { try { t r = (t)Activator.CreateInstance(typeof(t)); foreach (PropertyInfo pi in typeof(t).GetProperties()) { object v = o[pi.Name].ToString(); Type pt = Type.GetType(pi.PropertyType.FullName); //try { pi.SetValue(r, Convert.ChangeType(v, pt), null); } //catch (Exception ex) { HandleError_Condensed(ex); } o.Add(pi.Name, Convert.ChangeType(v, pt)); } results.Add(r); } catch (Exception ex) { HandleError_Condensed(ex); } } //public static void Load_AddResult<t>(dynamic o, ref List<t> results) //{ // try // { // t r = (t)Activator.CreateInstance(typeof(t)); // foreach (PropertyInfo pi in typeof(t).GetProperties()) // { // object v = o[pi.Name].ToString(); // Type pt = Type.GetType(pi.PropertyType.FullName); // try { pi.SetValue(r, Convert.ChangeType(v, pt), null); } // catch (Exception ex) { HandleError_Condensed(ex); } // } // results.Add(r); // } // catch (Exception ex) // { // HandleError_Condensed(ex); // } //} public static void ExecuteNonScalar(string procedurename, dynamic param) { try { ExecuteScalar(procedurename, param); } catch (Exception ex) { HandleError_Condensed(ex); } } public static int ExecuteScalar(string procedurename, dynamic param) { try { SqlDataSource sds = new SqlDataSource(); sds.ConnectionString = ConfigValues.TrainingPortalConnectionString; sds.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure; sds.UpdateCommand = procedurename; if (param != null) { foreach (PropertyInfo pi in param.GetType().GetProperties()) { object pval = pi.GetValue(param, null); if (pval != null) { sds.SelectParameters.Add(pi.Name, pval.ToString()); } } } return sds.Update(); } catch (Exception ex) { HandleError_Condensed(ex); return 1; //1 signifies error in tsql } } #endregion private static void HandleError_Condensed(Exception ex) { if (HandleError != null) { HandleError(ex); } else { throw new Exception(ex.Message, ex); } } } }
Custom AWS S3 Helper Class AWSSDK Wrapper
Implements some very commonly used AWS S3 functionality. (need to merge with my other AWS wrapper classes, Route53, EC2, etc)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Collections.Specialized; using System.Configuration; //uses AWSSDK.dll from amazon using Amazon; using Amazon.S3; using Amazon.S3.Model; using System.Xml.Linq; using System.Xml; using System.Data; namespace AIS.Common { public static class AWSHelper { private static List<S3Bucket> LoadS3Buckets() { System.Collections.Specialized.NameValueCollection appConfig = System.Configuration.ConfigurationManager.AppSettings; using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey)) { return s3client.ListBuckets().Buckets; } } private static List<S3Object> LoadS3Objects(string bucketname) { System.Collections.Specialized.NameValueCollection appConfig = System.Configuration.ConfigurationManager.AppSettings; using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey)) { return s3client.ListObjects(new ListObjectsRequest() { BucketName = bucketname }).S3Objects; } } private static void LoadS3File(string bucketname, string keyname, HttpResponse response, string contenttype) { NameValueCollection appConfig = ConfigurationManager.AppSettings; using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey)) { GetObjectRequest s3request = new GetObjectRequest() .WithBucketName(bucketname).WithKey(keyname); using (GetObjectResponse s3response = s3client.GetObject(s3request)) { string title = s3response.Metadata["x-amz-meta-title"]; response.Clear(); //Response.Write(string.Format("The object's title is {0}", title)); //Response.AddHeader //Response.ContentType="application/swf"; ////Response.ContentType="contenttype"; response.ContentType = s3response.ContentType; //s3response.Headers["Content-Length"]; long filesize = s3response.ContentLength; byte[] buffer = new byte[(int)filesize]; response.BinaryWrite(ConvertStreamToBytes(s3response.ResponseStream, filesize)); response.Flush(); response.Close(); } } } public static string GetS3UrlToVideo(string bucketname, string keyname) { System.Collections.Specialized.NameValueCollection appConfig = System.Configuration.ConfigurationManager.AppSettings; string url = ""; using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey)) { Amazon.S3.Model.GetPreSignedUrlRequest request = new Amazon.S3.Model.GetPreSignedUrlRequest() .WithBucketName(bucketname) .WithKey(keyname) .WithProtocol(Amazon.S3.Model.Protocol.HTTP) .WithVerb(HttpVerb.GET) .WithExpires(DateTime.Now.AddMinutes(ConfigValues.VideoURLExpiration)); Amazon.S3.Model.GetPreSignedUrlRequest r = new GetPreSignedUrlRequest(); url = s3client.GetPreSignedURL(request); url= "https://s3.amazonaws.com/" + bucketname + keyname; } //return System.Xml.XmlConvert.EncodeName(url); return url; } public static byte[] ConvertStreamToBytes(Stream input, long filesize) { byte[] buffer = new byte[(int)filesize]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } } }
Custom Web.Config Wrapper Class ASP .NET
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; namespace AIS.Common { public class ConfigValues { #region appSettings public static string SomeStringOne { get { return getval("SomeStringOne "); } } public static string SomeStringTwo { get { return getval("SomeStringTwo "); } } public static string Env { get { return getval("env"); } } //keep in mind case sensitivity public static string LastManualRefresh { get { return getval("date_last_manual_refresh"); } } //useful for manual site refresh/reload public static double SomeDouble { get { return Convert.ToDouble(getval("some_static_double")); } } #endregion #region connectionStrings - update web.config env variable to toggle between dev and prd public static string YourDBOneConnectionString { get { return getcstr("win_web_db"); } } //also read only implementation like above, but illustrates environment variable usage specific in web.config useful if you have many environments public static string YourDBTwoConnectionString { get { if (Env.ToLower().ToString() != "filesystem") { return getcstr("static_string" + Env.ToLower().ToString()); } return ""; } } #endregion /// <summary> /// Retrieve Connection String for specified provided key /// </summary> /// <param name="key"></param> /// <returns></returns> private static string getcstr(string key) { try { return ConfigurationManager.ConnectionStrings[key].ConnectionString; } catch (Exception ex) { Shared.HandleError(ex); //TODO: change to throw error event handle instead of direct call for reusability return "Error retrieving value"; } } /// <summary> /// Retrieve appSettings value for provided specified key /// </summary> /// <param name="key"></param> /// <returns></returns> private static string getval(string key) { try { return ConfigurationManager.AppSettings[key]; } catch (Exception ex) { Shared.HandleError(ex); //TODO: change to throw error event handle instead of direct call for reusability return "Error retrieving value"; } } } }
Custom URLRewriting with XML and Global.asax
utilizes my custom DocParser class here https://ronniediaz.com/2013/08/23/parse-xml-to-dynamic-expandoobject-c-net-4-0/
void Application_BeginRequest(object sender, EventArgs e) { //string path = Request.Url.ToString(); string path = Request.Path; if (Regex.IsMatch(path.ToLower(), ".*[.](jpg|png|gif|css|js|pdf|ico|woff|svg|eot|ttf)$")) { //var h = Regex.Replace(path.ToLower(), ".*/(.*)/(.*)$", "~/$1/$2", RegexOptions.Singleline); //Context.RewritePath(path); return; } //TODO: authorize user/request DocParser dp = new DocParser(Server.MapPath("~/rewrite.xml")); var rules = dp.GetElements("*/rule"); foreach (var r in rules) { if (string.IsNullOrEmpty(r.match_url)) { Shared.HandleError("Global.asax::null or empty match_url encountered"); } if (string.IsNullOrEmpty(r.action_url)) { Shared.HandleError("Global.asax::null or empty action_url encountered"); } if (Regex.IsMatch(path, r.match_url,RegexOptions.IgnoreCase)) { List<object> qsvars = new List<object>(); foreach (Match m in Regex.Matches(path, r.match_url, RegexOptions.IgnoreCase)) { for (int i=1;i<m.Groups.Count;i++) { qsvars.Add(m.Groups[i].Value); } } //Context.RewritePath(string.Format(r.action_url,qsvars.ToArray()) + "&rewrite=1"); Context.RewritePath(string.Format(r.action_url, qsvars.ToArray())); } } }
rewrite.xml examples
<?xml version="1.0" encoding="utf-8" ?> <rules> <rule match_url="^/home" action_url="~/home.aspx" /> <rule match_url="^/login" action_url="~/default.aspx" /> <rule match_url="^/register" action_url="~/welcome/register.aspx" /> <rule match_url="^/logout" action_url="~/logout.aspx" /> <rule match_url="^/default/(.*)" action_url="~/default.aspx?q={0}" /> <rule match_url="^/test/(.*)/(.*)" action_url="~/test.aspx?q={0}&r={1}" /> </rules>
asp .net repeater itemcommand command name common repeater control item operations
This is only one small snippet illustrating some functionality. I will add to this blog from my previous usage with Repeater control over time or per request.
In many deployments, I prefer to use Repeater or ListView rather than Grids. The code pattern is the same, but the output is slightly different as well as some of the inherent features/functionality.
Notice the example below simulates table output similar to a Grid, or it may also be used for non-table type of output. Repeater is therefore IMO more adaptable to different needs, and allows more re-usability code patterns across projects.
page side:
<asp:Repeater ID="rptRobotsInFactories" runat="server" OnItemCommand="rptRobotsInFactories_ItemCommand"> <HeaderTemplate> <table> <tr> <td>factory name</td> <td>robot name</td> <td>factory location</td> <td>manufacture date</td> <td colspan="2">commands</td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%# Eval("factoryname")%> <asp:TextBox ID="tbRobotName" runat="server" Text='<%# Eval("robotname")%>'></asp:TextBox> </td> <td> <%# Eval("factorylocation")%> </td> <td> <%# Eval("manufacturedate")%> </td> <td> <asp:LinkButton ID="lbtnRename" runat="server"> CommandName="rename" CommandArgument='<%# Eval("robotname")%>'>rename</asp:LinkButton> </td> <td> <asp:LinkButton ID="lbtnDeelte" runat="server"> CommandName="delete" CommandArgument="">delete</asp:LinkButton> </td> </tr> </ItemTemplate> </HeaderTemplate> <FooterTemplate> <!-- insert pager here if you like--> </table> </FooterTemplate> </asp:Repeater>
code behind:
//you can also intercept item databind as i've listed in another previous article on nested repeaters protected void rptRobotsInFactories_ItemCommand(object sender, RepeaterCommandEventArgs e) { if (e.CommandName == "rename") { string newname = ((TextBox)rptRobotsInFactories.Items[e.Item.ItemIndex].FindControl("tbFileName")).Text; //string newname = ((TextBox)e.Item.FindControl("tbFileName")).Text; //equal to the above //string index = (string)e.CommandArgument; //useful to pass in index values also. can split the values passed in or pass in class obj //var rif = ((List<robotinfactory>)rptRobotsInFactories.DataSource)[e.Item.ItemIndex]; //var rif = Session_RobotsInFactories().Select(r=>r.id==Convert.ToInt32(e.CommandArgument)); //compare to using viewstate/page repeater above string oldname = (string)e.CommandArgument; if ((newname.ToLower().Trim().Replace(" ","") != "") && (newname!=oldname)) { //dowork_rename(oldname,newname); } } else if (e.CommandName=="delete") { robotinfactory rif = ((List<robotinfactory>)rptRobotsInFactories.DataSource)[e.Item.ItemIndex]; //dowork_delete(rif.id); } } //added below funcs for clarity public class robotinfactory() { public string factoryname {get;set;} public string robotname {get;set;} public string factorylocation {get;set;} public string manufacturedate {get;set;} } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //these would normally load from your LINQ dbml SP, view, select statement, stored procedure etc var rifs = new List<robotinfactory>(); rifs.Add(new rif { factoryname="a", robotname="bob", factorylocation="florida", manufacturedate="7/1/2013" }); rifs.Add(new rif { factoryname="b", robotname="sam", factorylocation="not florida", manufacturedate="7/4/2013" }); rptRobotsInFactories.DataSource = rifs; rptRobotsInFactories.DataBind(); } }
directory info get files show directories C# .Net
There is sometimes a misunderstanding between a “file” and a “folder” in filesystems. In C# .Net the following is often used to list all “files” in a folder.
DirectoryInfo di = new DirectoryInfo("yourpath"); foreach (FileInfo fi in di.GetFiles()) { //do work }
However, even though you can specify to search containing subdirectories, the above function will not inherently list folders. If you are looking for the equivalent to “dir” or “ls”, instead use “GetFileSystemInfos()”.
DirectoryInfo di = new DirectoryInfo("yourpath"); //note the difference here with getfilesysteminfos foreach (dynamic d in di.GetFileSystemInfos()) { }
Note the usage of dynamic in the above example compared to the first example. This avoids any potential issues with inheritance and choosing the right class for your temp iterator variable for unboxing etc.
asp .net could not establish trust relationship for the SSL/TLS secure channel
A quick google search revealed multiple reported resolutions, however, after following the steps in the MSDN blog reference listed below, the issue was still unresolved in my situation.
Additional details in the stack trace will reveal another similar message: “The remote certificate is invalid according to the validation procedure.”
In this specific scenario, the site in question is either not configured with a wildcard certificate for a subdomain of the parent site or the operation system I am working on does not support SNI. In the meantime, a workaround is needed to continue testing and development.
Additional reading on google revealed another solution which was more suitable and utilized a code based approach, as opposed to a server configuration based solution.
To make it more dynamic, I added a key into the app/web config to control if SSL errors should be ignored. Please note that it is also possible to replace the code based approach solely with an app/web config entry listed in the west-wind blog referenced below, but I personally prefer to go with code whenever possible.
<?xml version="1.0"?> <configuration> <configSections> </configSections> <connectionStrings> <add name="ConnectionString" connectionString="Data Source=servername;Initial Catalog=databasename;" providerName="System.Data.SqlClient" /> </connectionStrings> <appSettings> <add key="ignoresslerrors" value="true"/> </appSettings> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
public class ConfigValues { public static string IgnoreSSLErrors { get { return getval("ignoresslerrors"); } } } public function main() { connect("https://sitename.com",ConfigValues.IgnoreSSLErrors); } public function connect(string url, string ignoresslerrors) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); try { if (Convert.ToBoolean(ignoresslerrors)) { System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; //will always accept the cert and ignore errors. this is not good common practice unless you are sure of the destination you are connecting to. needed in this scenario to continue development until issue with cert is resolved. }; } } catch (Exception ex) { Shared.HandleError(ex); } }
References
http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors
Classic ASP VB Filter File Name Extensions From String EndsWith
Came across a classic ASP VB site recently in my adventures. There was a feature request to filter out some file extensions from existing code logic, and I discovered quickly most of my .Net methods were unavailable, so I came up with this little snippet and had a great blast from the past. 🙂
function FilterExtensions(fn) FilterExtensions=true a_ext = Array(".db",".db") 'place additional extensions here for each ext in a_ext i = InStrRev(fn,ext) if i>0 then FilterExtensions=false end if next end function
If FilterExtensions returns true then there were no matches (extension of filename successfully passed all filters).
lastChild is null in FireFox works in IE invalid nodeType javascript c# asp .net
This issue alluded me at first as it works in IE but not in FF. See code below.
//pass in table, last cell number and style to apply to it. call this on hover and blur for cell highlight effects. alternatively you can determine last cell number as well and this function could be rewritten to work solely for the purpose of modifying specific cells rather than last cell function ChangeTableCellStyle(tableid,cellnumber,mystyle) { if (document.getElementById) { var selectedElement = document.getElementById(tableid); selectedElement.className = style; //change style on end cell by drilling into table. this will become deprecated by css3. if (selectedElement.tagName.toLowerCase()=="table") { var tbody = selectedElement.lastChild; if (tbody!=null) { var tr = tbody.lastChild; if (tbody !=null) { var tr = tbody.lastChild; //BUGGED IN FF! //nodetype should be 1 for element type. in FF it is 3. see reference link at bottom for list of types. if (tr.nodeType!=1) { tr.tbody.getElementsByTagName("td"); tr[cellnumber].className+= ' ' + mystyle; } else { tr.lastChild.className+=' ' + mystyle; } } } } } } //example usage ChangeTableCellStyle("table1",3,"cellend"); //will append the class cellend to the last cell in table1 if table1 only has 4 cells per row
In you’re interested in reviewing other approaches to styling your table cells, see my similar article here.