Joseph Michael Pesch
VP Programming

Extract PDF File(s) from Adobe PDF Portfolio File Using iTextSharp Open Source PDF Library

by 30. August 2016 07:23

Using iTextSharp open source PDF library, the below console application illustrates opening one or more PDF files (based on file path and file mask inputs) and extracting a desired single PDF file from each.

using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;

namespace PdfPortfolioSample
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.Write("Enter source path: ");
      string sourcePath = Console.ReadLine();
      Console.Write("Enter file mask (e.g. *.pdf): ");
      string fileMask = Console.ReadLine();
      Console.Write("Recursive (y/n): ");
      bool recursive = Console.ReadLine().ToUpper() == "Y";
      Console.Write("Enter target path: ");
      string targetPath = Console.ReadLine();
      Console.Write("Enter document name to extract (e.g. MLPA.PDF): ");
      string docName = Console.ReadLine();
      List<string> files = GetFiles(sourcePath, fileMask, recursive);
      foreach (string file in files)
      {
        GetPdfFromPortfolio(file, targetPath, docName);
      }
    }
    private static void GetPdfFromPortfolio(string filePath, string targetPath, string docName)
    {
      PdfReader reader = new PdfReader(filePath);
      PdfDictionary root = reader.Catalog;
      PdfDictionary documentnames = root.GetAsDict(PdfName.NAMES);
      PdfDictionary embeddedfiles =
          documentnames.GetAsDict(PdfName.EMBEDDEDFILES);
      PdfArray filespecs = embeddedfiles.GetAsArray(PdfName.NAMES);
      for (int i = 0; i < filespecs.Size;)
      {
        filespecs.GetAsString(i++);
        PdfDictionary filespec = filespecs.GetAsDict(i++);
        PdfDictionary refs = filespec.GetAsDict(PdfName.EF);
        foreach (PdfName key in refs.Keys)
        {
          PRStream stream = (PRStream)PdfReader.GetPdfObject(
            refs.GetAsIndirectObject(key)
          );

          if (filespec.GetAsString(key).ToString().ToUpper() == docName.ToUpper())
            using (FileStream fs = new FileStream(
              targetPath + @"\" + Path.GetFileName(filePath).Substring(0, 10) + filespec.GetAsString(key).ToString(), FileMode.OpenOrCreate
            ))
            {
              byte[] attachment = PdfReader.GetStreamBytes(stream);
              fs.Write(attachment, 0, attachment.Length);
            }
        }
      }

    }
    private static List<string> GetFiles(string path, string fileMask = "", bool recursive = false, List<string> files = null)
    {
      if (files == null) files = new List<string>();
      try
      {
        foreach (var file in Directory.GetFiles(path, fileMask))
        {
          files.Add(file);
        }
        if (recursive)
          foreach (string dir in Directory.GetDirectories(path))
          {
            GetFiles(dir, fileMask, recursive, files);
          }
      }
      catch (System.Exception e)
      {
        Console.WriteLine(e.ToString());
      }
      return files;
    }
  }
}

Tags:

C# | iTextSharp | PDF

Configuring and Running Azure Powershell (for Azure Classic and Azure Resource Manager) on Windows Using Nuget

by 24. August 2016 07:57

Run Windows Powershell ISE as Administrator:
PS > Set-ExecutionPolicy RemoteSigned
PS > Import-Module PowerShellGet
PS > Install-Module Azure (Classic)
PS > Install-Module AzureRM (Resource Manager)

# To make sure the Azure PowerShell module is available after you install
Get-Module –ListAvailable 

# To login to Azure Resource Manager
Login-AzureRmAccount

# You can also use a specific Tenant if you would like a faster login experience
# Login-AzureRmAccount -TenantId xxxx

# To view all subscriptions for your account
Get-AzureRmSubscription

# To select a default subscription for your current session
Get-AzureRmSubscription –SubscriptionName “your sub” | Select-AzureRmSubscription

# View your current Azure PowerShell session context
# This session state is only applicable to the current session and will not affect other sessions
Get-AzureRmContext

# To select the default storage context for your current session
Set-AzureRmCurrentStorageAccount –ResourceGroupName “your resource group” –StorageAccountName “your storage account name”

# View your current Azure PowerShell session context
# Note: the CurrentStorageAccount is now set in your session context
Get-AzureRmContext

# To list all of the blobs in all of your containers in all of your accounts
Get-AzureRmStorageAccount | Get-AzureStorageContainer | Get-AzureStorageBlob

Tags:

Azure

Restart IIS Web Site from C# Code

by 24. April 2016 04:58

In some cases I have setup caching on the website for items such as menus, header, footer, etc.  However, when there is a CMS in place on the site and a user changes any of that relevant content there needs to be a way to reset the web cache.  One easy way is to force the IIS web site to restart by making a benign change in the web.config file, which will automatically force the restart.  Below is a sample version of code to do this, where I update an otherwise unused entry in the web.config that just indicates the last date/time of restart request by the user.  In the case of an MVC application I put this into a controller with some specific route provided to the CMS users so they can navigate to that route after making CMS changes that need to be updated in the cache.  As a side note, using this method will require granting write access to the web.config file for the IIS application pool user (by default "IIS AppPool\WebSiteName" user).

    public static void RestartWeb()
    {
      var configuration = WebConfigurationManager.OpenWebConfiguration("~");
      var section = (AppSettingsSection)configuration.GetSection("appSettings");
      section.Settings["LastRestart"].Value = 
        DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString();
      configuration.Save();
    }

Tags:

ASP.Net | C#

Change the "SharePoint" Text in the Ttop Left Corner of SharePoint 2013 Site

by 20. April 2016 11:04

To change the text you can use PowerShell with the sample code snippet shown below.  NOTE: To use PowerShell for SharePoint make sure add the snapin (Add-PSSnapIn Microsoft.SharePoint.Powershell).

PowerShell Script Sample:

$webApp = Get-SPWebApplication http://MySiteUrlHere; $webApp.SuiteBarBrandingElementHtml = "<a href='/'>My Site Title Here</>"; $webApp.Update(); 

Tags:

Sharepoint

BlogEngine.Net Using TinyMCE Allow User to Paste Image Directly Onto Page

by 7. April 2016 09:18

By default the TinyMCE configuration in a standard BlogEngine.Net implementation may not be setup to allow users to paste images directly from their clipboard onto the page.  To make sure this feature is enabled, go to the "admin/editors/tinymce/editor.js" and add the two lines listed below into the tinymce.init method (sample of a full view of the method also shown below):

browser_spellcheck: true,
paste_data_images: true,

For any editor customization, check TinyMce website for plugins: https://www.tinymce.com/docs/plugins/paste/

tinymce.init({
    selector: '#txtContent',
    plugins: [
        "advlist autolink lists link image charmap print preview anchor",
        "searchreplace visualblocks code fullscreen textcolor imagetools",
        "insertdatetime media table contextmenu paste sh4tinymce filemanager"
    ],
    toolbar: "styleselect | bold underline italic | alignleft aligncenter alignright | bullist numlist | forecolor backcolor | link media sh4tinymce | fullscreen code | filemanager",
    autosave_ask_before_unload: false,
    max_height: 1000,
    min_height: 300,
    height: 500,
	browser_spellcheck: true,
	paste_data_images: true,
    menubar: false,
    relative_urls: false,
    browser_spellcheck: true,
    setup: function (editor) {
        editor.on('init', function (e) {
            if (htmlContent) {
                editor.setContent(htmlContent);
            }
        });
    }
});

Tags:

BlogEngine.NET

Setup Git Repo on Digital Ocean Droplet

by 2. April 2016 06:38

This tutorial will show you how to set up a fully fledged Git server using SSH keys for authentication. It will not have a web interface, this will just cover getting Git installed and your access to it set up. We'll use the host "git.droplet.com" in place of the domain you will use for your VPS.

This can be a great option if you want to keep your code private while you work. While open-souce tends to be the status quo, there are some times when you don't want to have your code freely available. An example would be if you are developing a mobile app, especially a paid one. Keep in mind this code can be read by anyone if they know the URL address to use for a clone, but that is only if they know it.

There is one major concern for many and that is a web interface to your repositories. GitHub accomplishes this amazingly well. There are applications that you can install such as Gitosis (https://wiki.archlinux.org/index.php/Gitosis), GitList (http://gofedora.com/insanely-awesome-web-interface-git-repos/), and Goblet (http://git.kaarsemaker.net/). We don't go over those in this tutorial, but if you rely heavily on a graphic interface then you may want to look over those and think about installing one of them as soon as you done installing your Git server.

Next, the VPS will need a user specifically for Git. Most people will simply create a user called "Git", and that is what we'll do for this tutorial but feel free to name this user whatever you'd like.

 

Setup a Git User and Install Git on your VPS

Log into your VPS, and gain root*:

 

su -

*Some people feel uncomfortable using root in this manner. If your VPS is set up to use sudo, then do so.

 

Add the Unix user (not necessarily Git user names) to handle the repositories:

 

useradd git

Then give your Git user a password:

 

passwd git

Now it's as easy as:

 

CentOS/Fedora: yum install git

Ubuntu/Debian: apt-get install git

Add your SSH Key to the Access List

At this point, you'll want to be logged in as the Git user. If you haven't already logged in to that user, use this command to switch to it:

 

su git

Now you need to upload your id_rsa.pub file to your Git user's home directory. Once you have done that, we need let the SSH daemon know what SSH keys to accept. This is done using the authorized keys file, and it resides in the dot folder "ssh". To create this, input:

 

mkdir ~/.ssh && touch ~/.ssh/authorized_keys

Note: Using the double '&' in your command chains them, so it tells the system to execute the first command and then the second. Using the 'tilde' at the beginning of the path will tell the system to use your home directory, so '~' becomes /home/git/ to your VPS.

 

We are going to use the 'cat' command, which will take the contents of a file and return them to the command line. We then use the '>>' modifier to do something with that output rather than just print it in your console. Be careful with this, as a single '>' will overwrite all the contents of the second file you specify. A double '>' will append it, so make sure you know what you want to do and in most cases it will be easier to just use ">>" so that you can always delete what you append rather than looking to restore what you mashed over.

 

Each line in this file is an entry for a key that you wish to have access to this account. To add the key that you just uploaded, type the following, replacing :

 

cat .ssh/id_rsa.pub | ssh user@123.45.56.78 "cat >> ~/.ssh/authorized_keys"

Now you can see the key there if you use cat on the authorized key file:

 

cat ~/.ssh/authorized_keys

If you want to add others to your access list, they simply need to give you their id_rsa.pub key and you append it to the authorized keys file.

 

Setup a Local Repository

This is a pretty simple process, you just call the Git command and initialize a bare repository in whichever directory you'd like. Let's say I want to use "My Project" as the project title. When creating the folder, I'd use all lower case, replace any spaces with hyphens, and append ".git" to the name. So "My Project" becomes "my-project.git".

 

To create that folder as an empty Git repository:

 

git init --bare my-project.git

Thats it! You now have a Git repository set up on your VPS. Let's move on to how to use it with your local computer.

 

Using your Git Server from your Local Computer

On Linux or Mac OS, you need to change the remote origin to your newly created server. If you already have a local repo that you want to push to the server, change the remote using this command:

 

git remote set-url origin git@git.droplet.com:my-project.git

If this is a new repository you are setting up, use this:

 

git init && git remote add origin git@git.droplet.com:my-project.git

Now you may add, push, pull, and even clone away knowing that your code is only accessible to yourself.

 

But what if you want a few trusted people to have access to this server and you want to keep things simple by sorting them by the names of your users? A simple and effective way to do that is to create a folder named after each person, so in the home folder for your Git user list, input:

 

mkdir user1 user2

Now when you specify the remote repository, it would look like this:

 

git remote add origin git@git.droplet.com:user1/user-project.git 

Step 1: Create SSH Public/Private Key Using PuTTY 

1. Download and start the puttygen.exe generator (download location: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html).

2. In the "Parameters" section choose SSH2 DSA and press Generate.

3. Move your mouse randomly in the small screen in order to generate the key pairs.

4. Enter a key comment, which will identify the key (useful when you use several SSH keys).

5. Type in the passphrase and confirm it. The passphrase is used to protect your key. You will be asked for it when you connect via SSH.

6. Click "Save private key" and then "Save public key" to save both keys to your disk.

 

Tags:

Windows Task Scheduler Create Web Request (Web Site Keep Alive)

by 25. March 2016 18:09

Add Windows Schedule and from the "Actions" tab, select "Start a program" dropdown and enter "powershell" (without the quotes) in the "Program/script:" text box then enter a command like the one below in the "arguments" text box:

-Command "Get-Date > c:\pathToLogFile.txt; $req = [System.Net.WebRequest]::Create(\"http://url\"); $res = $req.GetResponse(); $str = $res.GetResponseStream(); $rdr = new-object System.IO.StreamReader $str; $dat = $rdr.ReadToEnd(); $dat >> c:\pathToLogFile.txt; Get-Date >> c:\pathToLogFile.txt;"

Powershell HTTP Request

$r = [System.Net.WebRequest]::Create("http://url/")
$resp = $r.GetResponse()
$reqstream = $resp.GetResponseStream()
$sr = new-object System.IO.StreamReader $reqstream
$result = $sr.ReadToEnd()
write-host $result

Username and passwords
$creds = new-object System.Net.NetworkCredential "username", "password"
$uri = mew-object System.Uri "http://url/"
$credcache = new-object System.Net.CredentialCache
$credcache.Add($uri, "Basic", $creds)
$webrequestobject.Credentials = $credcache

One Liner Version
Powershell -Command "$r = [System.Net.WebRequest]::Create('http://url/'); $resp = $r.GetResponse(); $respstream = $resp.GetResponseStream(); $sr =
new-object System.IO.StreamReader $respstream; $result = $sr.ReadToEnd(); write
-host $result"

Tags:

PowerShell

SQL Backup All User Databases via Windows Task Scheduler

by 22. March 2016 18:14

Create command file with the following contents and add the command to Windows Task Scheduler:

sqlcmd -S localhost -E -Q "exec master.dbo.prc_BackupUserDatabases"

Create the corresponding SQL stored procedure:

create procedure prc_BackupUserDatabases as
begin
  declare @DatabaseName varchar(50)
, @BackupFolder sysname = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\'; declare cur cursor for select name from sys.databases where len(owner_sid) > 1 open cur while 1=1 begin fetch next from cur into @DatabaseName if @@FETCH_STATUS <> 0 break declare @BackupFilePath sysname = @BackupFolder
+ @DatabaseName + N'_' + CONVERT(char(8), GETDATE(), 112); backup database @DatabaseName to disk = @BackupFilePath with init, STATS=10; end close cur deallocate cur end

Tags:

SQL Server

Enable Remote IIS Web Administration with IIS Management Console or Power Shell

by 24. February 2016 05:00

https://technet.microsoft.com/en-us/magazine/dn198619.aspx

Tags:

MP4 File Format Specification Details

by 14. February 2016 14:59

 

 

Tags:

Tools for Apache Cordova for Visual Studio 2013 - Blocking Update and Cannot Uninstall

by 24. January 2016 07:07

I was trying to update Visual Studio 2013 and could not as it was complaining that I needed to remove an older version of "Tools for Apache Cordova for Visual Studio 2013".  I went into my Control Panel and found "Tools for Apache Cordova for Visual Studio 2013 - CTP3.1" as an installed program and tried to uninstall; however, that would immediately say it completed and would not actually remove it.  To force the removal I had to search in my "%ProgramData%\Package Cache" folder for the "MultiDeviceHybridApps_VS.msi" file.  Then run the following command from an administration command prompt using the full path to the MSI.

misexec /x FULL_PATH_TO_MSI_HERE

Tags:

Visual Studio

C# Generic Class Wrapper

by 23. January 2016 07:57

 

public class Wrapper<T>
{
    public Wrapper(T wrapped)
    {
        Wrapped = wrapped;
    }

    public T Wrapped { get; set; }
}

public class WrapperFactory
{
    public static Wrapper<T> Create<T>(T wrapped)
    {
        return new Wrapper<T>(wrapped);
    }
}

var wrappedInt = WrapperFactory.Create(42);

Tags:

C#

Morris.js Charting Issue with Unresponsive JavaScript in Firefox Browser

by 8. January 2016 11:09

After implementing Morris.js for charting I would periodically receive this error message in Firefox:

Warning: Unresponsive script

A script on this page may be busy, 
or it may have stopped responding.  
You can stop the script now, 
open the script in the debugger, 
or let the script continue.

Script: http://.../plugins/morris/raphael.min.js


To resolve this I added the parseTime: false setting to the chart object. It seems that Mozilla tries to parse the "xLabels" attribute as a datetime and goes into a loop.

 

Tags:

JavaScript

SQL Function to Convert Delimited String to Table

by 24. December 2015 07:58

This is a SQL function to convert a delimited string into a table.

create function [dbo].[DelimToTable] 
(@StringInput varchar(max), @Delimiter nvarchar(1))
returns @OutputTable table([String] varchar(255)) as begin
declare @String varchar(255)
while len(@StringInput) > 0 begin
set @String = left(@StringInput
, isnull(nullif(charindex(@Delimiter, @StringInput) - 1, -1)
, len(@StringInput)))
set @StringInput = substring(@StringInput
, isnull(nullif(charindex(@Delimiter, @StringInput), 0)
, len(@StringInput)) + 1, len(@StringInput))
insert into @OutputTable ([String]) values(@String)
end
return
end

Tags:

SQL Server

Visual Studio 2013 Setup/Installer Add In

by 21. October 2015 05:03

https://visualstudiogallery.msdn.microsoft.com/9abe329c-9bba-44a1-be59-0fbf6151054d

NOTE: To create a windows service setup make sure to open the service.cs file and right-click on the screen to "Add Installer" (as shown in screen shot below).

 

Tags:

Migrate Azure Virtual Machine (VM) Between Storage Accounts

by 20. October 2015 04:39

https://azure.microsoft.com/en-us/blog/migrate-azure-virtual-machines-between-storage-accounts/

Tags:

Azure

Sending Email Through SMTP Using TELNET

by 16. September 2015 05:17

1) Open a cmd prompt.

2) Enter telnet <the FQDN of your SMTP server> <the port number>

image

3) Enter EHLO <the DNS domain name where the SMTP server is at>

image

If you get a successful connection you will see this:

image

4) Enter MAIL FROM: <the email address of the Workflow Run As Account>

image

5) Enter RCPT TO: <some email address you want to send to>

image

6) Enter DATA

image

7) Enter SUBJECT: <some subject you want to have> and hit Enter TWO times:

image

8) Enter a message body followed by Enter, then a period, then Enter again.

image

9: Enter QUIT

Tags:

Windows

SQL Server Drop Extended Properties (e.g. MS_Description)

by 8. September 2015 04:38

This script will generate a set of drop statements:

--tables
 select 'EXEC sp_dropextendedproperty
 @name = '''+name+'''
 ,@level0type = ''schema''
 ,@level0name = ' + object_schema_name(extended_properties.major_id) + '
 ,@level1type = ''table''
 ,@level1name = ' + object_name(extended_properties.major_id)
 from sys.extended_properties
 where extended_properties.class_desc = 'OBJECT_OR_COLUMN'
 and extended_properties.minor_id = 0
 union
 --columns
 select 'EXEC sp_dropextendedproperty
 @name = '''+sys.extended_properties.name+'''
 ,@level0type = ''schema''
 ,@level0name = ' + object_schema_name(extended_properties.major_id) + '
 ,@level1type = ''table''
 ,@level1name = ' + object_name(extended_properties.major_id) + '
 ,@level2type = ''column''
 ,@level2name = ' + columns.name
 from sys.extended_properties
 join sys.columns
 on columns.object_id = extended_properties.major_id
 and columns.column_id = extended_properties.minor_id
 where extended_properties.class_desc = 'OBJECT_OR_COLUMN'
 and extended_properties.minor_id > 0

Tags:

SQL Server

BundleConfig EnableOptimizations Breaks Font Awesome

by 30. August 2015 15:13

When using Font Awesome with bundling and optimization you need to add the CssRewriteUrlTransform() to the font awesome bundle (as shown below).

BundleTable.EnableOptimizations = true;

bundles.Add(new StyleBundle("~/bundles/css/font-awesome").Include(
  "~/css/font-awesome.min.css", new CssRewriteUrlTransform()
));

Tags:

CSS

Bootstrap Image Slider Center Image

by 30. August 2015 12:03

div.carousel-wrapper{
    width: 80%; /* for example */
    margin: auto;
}

.carousel-inner > .item > img,
.carousel-inner > .item > a > img{
width: 100%; /* use this, or not */
margin: auto;
}

Tags:

CSS