Visual C#

Quite often when dealing with an API or some other external service, you will find that you get Unix timestamps returned to you or alternatively have to provide a timestamp in Unix form when sending a request back. Since you are going to be running your .NET code on a windows machine, you don’t have a built in way to get the time in Unix format. It is pretty simple to obtain a Unix timestamp though. Here is what you need to do to convert C# DateTime object to a Unix timestamp.

The following helper method can be used to convert a standard datetime object into a Unix timestamp value. The value is quite large and will get bigger as time goes on, so make sure to use an appropriate variable type. Long will work fine for this scenario.

It’s a pretty simple method with little to explain. Its worth noting that you need to keep this as a long. Int is not going to be big enough to hold the time value.

If you want to do things in reverse. I.e. Convert a Unix timestamp back to a C# DateTime object, you can use the following helper method.

 

PHP Logo

There are various reasons that you might want to force a website to use SSL. In general, if you have an SSL cert setup for your website, you should probably force all users to https even if the page doesn’t contain sensitive data. In an ideal world, you would do this on the server side of things. Write some rules with the conf file that will force all traffic over https. If you are in a position where you can’t use the server then it is also easy to force SSL with PHP. It is also very easy to do it with pretty much any programming language, but for this example I will use PHP.

And there you have it. It is that simple. If you are using something like Cloudflare it can get a little tricky sometimes depending on how you have cloudflare configured to handle the SSL. For a standard site, this will be a simple way to force the use of SSL.

It is also worth mentioning that you must have an SSL cert configured on your server in order to make this work. If you do not have a site that supports HTTPS then you cannot make this work.

asp.net logo

You are looking to create some sort of HTML element on your site that when clicked will trigger a file download. Seems like a pretty simple request, but there is a little more to it then first appears. By default web browsers will have a set way to handle certain file formats. For example, if you wanted a user to be able to download an image file, simply putting the path of the image in the href, would just open the image in a new tab/window rather than actually download the file. Here is what you need to download a file using ASP MVC.

In order to do this you will need to setup an “ActionResult” on one of your controllers. This means you will be setting the href or source of the link to the URL of the controller. For this example i created a controller called “Services” a method in the controller called “DownloadFile” and this method accepted a value that represented the file. For this you could use some kind of ID that lets you know where to find the file or simple URL encode the file path. This method is probably the easiest, but is not secure. If you are using a public site, you are going to have to setup a DB table to manage the files so that each row has a unique ID that you can use to identify the file. This is what i have done for this example.

I have created a custom document object that works with the DB table. Passing the ID of the row in the constructor (i know its bad practice..but its much quicker). This will pull all of the file information from the database including the path of the file on the disk.

The file path returns a value like “C:/myfiles/somefile.pdf”.

In order to gain access to this file using a download link you will setup a link like the following.

And there you have it, this will trigger the file download in your browser. This can be used to download any file from a windows machine. So long as your server has access to the drive, the file can be downloaded. This means you can download files that are outside of the root of your web servers home directory.

Microsoft-SQL-Server

Classic ASP might seem like a language that is dead and gone, but it is still alive…somehow. With a language that has become outdated, it can be difficult to fight against modern security risks. Knowing how to prevent SQL injection with classic ASP is a valuable bit of code to have at your disposal. With bots capable of hacking sites, you don’t to make things easy for them. Thankfully, there is a way to setup prepared statements using Classic ASP.

If you are familiar with prepared statements, this shouldn’t be too much trouble. I will admint, this is a pretty ugly implementation, but ASP isn’t exactly bleeding edge, so this is the best we have. The first and most awkward thing about prepared statements with classic ASP, is that you need to declare the data type. For example, if a field in a DB is of type int, you need to declare this when creating the statement. It seems odd, but this is how it goes. the following code will show you a quick and easy way to pull a row from a database by using an ID that is passed in the querystring.

The only thing that needs to change are the parameters that you pass into the CreateParameter function. As I mentioned previously, you need to declare the data type when adding a command parameter. A full list of all of the data type codes can be found here http://www.w3schools.com/asp/met_comm_createparameter.asp

This is a pretty solid way to prevent sql injection with classic ASP. Nothing is ever bulletproof, so always be on the lookout for ways to further improve the security by validating data even further to prevent any bad data making its way into a query string.

 

Email

When you have obtained a list of emails from a location that required little to no validation on whether it was a real email, you will be stuck trying to determine if the email address is real or not. You don’t want to risk sending out an email to these users without checking as a regular high bounce rate is a quick way to get your email server blacklisted. There is a 2 step method that you can use to validate if an email address is valid or not. This assumes that you have first filtered out values that are missing an @ symbol and a domain. This guide will show you how to check if an email is valid. For example, how can you tell if john@somesite.com is real or fake?

Step 1

The first thing you will need to do is check if the domain name is valid and has an active mail server/ MX record associated with it. Sometimes an email may have been valid at one stage, but the website has now been shut down. Sending an email to this address wont do anything. By checking to see if the domain name is real you will be able to filter out people who provide stupid domain names that never existed and also filter out emails from valid websites that are not capable of receiving emails.

For the example I am going to use PHP to write the script for this. Many other languages have similar methods that do the same thing, so this should be fairly easy to do with other programming languages. PHP has a function called “getmxrr()”. This function will obtain the MX record for a domain. For those who do not know what this is, a MX record is used in the DNS settings to point to the IP of a domains email server. If one is missing then the domain is not capable of receiving an email and is therefore invalid.

Just because a domain has an MX record, does not mean that the email address is valid. In fact, this makes sending bad emails to this server even more likely to cause you to get blacklisted.

Step 2

This is the most difficult to test while also being the most important. If someone provides an email like asdasd@gmail.com, step 1 will return this as being a valid email address. gmail.com is a valid email domain, but asdasd is likely a non existent user. This step will allow you to determine whether this is a valid inbox or not. Keep in mind that this step requires you to directly contact the email server to essentially ask if the inbox exists. I would suggest you run this from a test machine so you do not run the risk of blacklisting the IP. This many requests in a short period might be considered suspicious.

If you have worked with mail servers in the past, you may be familiar with HELO. This can be used to easily check if a mailbox exists or not. If you send the command and get a positive response you know that this inbox exists. If not you know its fake. I have combined step 1 with step 2 to generate a complete script below that will allow you to check if an email is valid and filter out bad mailboxes.

 

Visual C#

 

I recently hit an issue where i needed to change the name of an XML node. It ended up being a lot more complicated than I had expected it to be. node.Name is a read only field, so you can’t take the simple route and rename it this way. Since you cannot rename the node, I had to create a new node and delete the old one. Not overly complex, but it is a little messy with the limitations of the XmlDocument that require references to the old document. I also wanted to make this solution reusable. Here is the solution I came up with to rename an xml node using C# XmlDocument.

I will start with the method and explain why it seems overcomplicated for a simple task. The first parameter is the doc that oldRoot belongs to. The reason this needs to be passed is because you cant create an XmlNode without an XmlDocument and if you want to add a node to a document, it needs to be created with that document. This is why doc needs to be passed over. The for loop will take all of the elements from the old node and add them to the new node. This will mean that there are now 2 nodes that have the exact same content, but one has the new name that you wanted to rename the node to.

Once the new node has all the data of the old node, you can append this new node to the document and then remove the old one. This is all that you need to do. There is no real need for a return type here. You have passed doc as a parameter, any changes made to this doc will be made on a global level. When the method completes the change will have been made to the doc that you passed to this method.

Here is a simple scenario where you could call this method.

 

TinyMCE File Manager

This tutorial will show you how to take the media manager from WordPress and use it on an external page with a stock version of TinyMCE. I saw some posts about this and people were calling the WordPress editor to achieve this. Its an option, but it is not what this guide is for. If you have downloaded a standard version of TinyMCE and want the be able to browse and upload images using the WordPress media manager then this guide will show you how to do it. There are several file managers for TinyMCE, all which work perfectly fine. I have always found the WordPress media manager to be very powerful and easy to use. Unfortunately its part of WordPress and cant be downloaded on its own. Thankfully I have been able to find a way to use the media uploader within TinyMCE a lot more easy than i though. Here is how to use WordPress media manager with TinyMCE.

The first thing you will need to do is be able to load up the WordPress media manager on the page you are using. This means you need to either load the core of WordPress or just call the media method from WP. The following code will load the WordPress core and que all of the files you need to be able to call the media manager.

The next thing to do is create a javascript function that will load up the WordPress media manager. The following function will do this and will then return the selected image to the instance of TinyMCE that triggered it. The reason for this, is you may have more than one instance of TinyMCE on the page and you want to make sure you return data to the correct one.

You can test if the function works by calling it using a href. The final step to do is to link this function in with the init of TinyMCE. The following code is all you need

This variable in the TinyMCE init will tell the app that you are using a file manager and to call a function called “wpmediabrowser” when the browse button is clicked. When you select the image from the WordPress file manager it will return the image url back into the box.

When pulling comments from a database table, it can be very costly when you are performing a query that will automatically sort all of the comments into the parent child hierarchy. Every extra ms your SQL server spends performing calculations is time that is wasted. If you can easily move this logic to the programming language that you are using it will free up your DB server to serve more data. If you have a blog post that has comments, obtaining the comments from the DB for this post is a simple process, but the problem is that the order of the comments will not be right. If someone replies to the first comment days after lots of other comments have been made, this comment will show up at the end of the list returned from the DB. There are ways in which you can construct your query so that it will return an array of child comments for each comment, but this is way too wasteful. Using a simple recursive method you can sort out the comments using a programming language so as not to lock up your DB server any longer.

A simple SQL query like this is going to pull some comments from a database table that is storing comments for a blog post.

This query now leaves you with a list of comments that are a mix of parent and child comments are not in order. This seems a bit messy and can be a daunting problem to solve, but look at how simple that SQL query is. It is worth the effort when your DB server has very little to do to sort the comments. We are going to start this by creating the recursive function. A recursive function is a function that calls itself many times. The following function is written in PHP, but can be easily translated to any other programming languages.

This function accepts 2 parameters. The parent ID which is the Id of the comment that we want to get the child comments for, and then it contains the full list of all comments that were returned from the database query. When you want to see if a comment has children, you will loop through all of the comments checking to see if any of the comments have a parent ID that is equal to the current comment. Once we find a match we first need to check and make sure that this child comment doesn’t also have child comments,. This is why we use a recursive method. We cant tell how many comments have replies and how deep they go. This way we can do it without needing to know. Once we have checked for more child comments we can add this child comment to an array of child comments for the current comment we are checking.

The only thing left to do now is to determine how to set it off. We need a way to call this method and restart the recursive loop. Here is a completed method that will show you how to pull them from the database and then how to trigger the calling of the recursive loop.

 

Sharepoint Logo

This tutorial will show you how to programmatically create a subsite in Sharepoint. This can be done a few different ways and if you have server access you may prefer to do this on the server side, but you can just as easily create one using the Client-Side Object Model.

You can do this using a standard C# console application. For this example I used Visual Studio 2013 with .NET 4.0. You will need to include 2 assemblies in order for the code to work.

If this code throws an error then you will need to add the reference to your project. For me, I was not able to find Microsoft.Sharepoint but when I added the .client assembly it worked.

Thats it! The code above is all you need to create a new subsite. If you make a mistake and want to change it, you can also do this quite easy using similar code. You can modify pretty much everything on a subsite, but the URL becomes read only so you cannot change this once it has been set.

This is all you need to be able to add a subsite and to be able to edit it.

asp.net logo

File downloads can be a bit of a nuance sometimes as web browsers often support a lot of document types. Simply adding the file path to the href of a html element, wont be enough for you to be able to download the file. There are dozens of work arounds to make this work, but using an ASP.NET ashx handler is definitely one of the cleanest methods to do it using code.

I will paste the contents of the entire ashx file below as the script is very simple. This solution will only work if you are using the non razor MVC models that are part of the ASP.NET framework. First you will need to create a new “Generic Handler” this will create a file with a .ashx extension. Once this is done you can point all of your links to this page when you want to download a file. There are many ways you can direct the downloads to this page. To keep things very simple, I have setup the script to accept the file path in the URL of the request.

In order to make the request work you will need to urlencode the value that is being passed into the url. The following code will be all you need to setup the url.

You could alternatively use javascript or pretty much anything that is capable of generating a request to your download script. This method has massive security risks, so please take this into consideration. This code will be enough to get a working prototype for you to built upon. This should never be used in any public facing code without some security measures being implemented to stop people tampering with the URL.