Monthly Archives: May 2012

ASP.NET (MVC) AspNetSqlMembershipProvider and aspnetdb.mdf – use SQL instead

After creating a project, running it I was not able to access to aspnetdb.mdf data. Simply couldn’t open it because of it had incorrect server name set in its connection string setting (web.config was set properly).

Initial connection string:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

So, instead I set up database and updated Web.config. Database requires all tables and stored procedures to run membership. How to do that without having access to MDF file?

Use aspnet_regsql.exe as
If you are confused with paramters, just run exe without any and you will get access to wizard.

My command:

C:> cd C:WindowsMicrosoft.NETFramework64v4.0.30319
C:> WindowsMicrosoft.NETFramework64v4.0.30319> aspnet_regsql.exe

PDF Initial View Settings – itextSharp : wskidmore.com

The documentation on iTextSharp is a bit sparse, translating the Java docs to C# without any particular definitions or examples.

This little exe is a console app that takes a PDF and flags for initial view settings and sets them in that PDF. On my end I’ve made a watcher script that listens for PDFs in a particular folder, runs the exe, then moves them to a completed folder — but how you want to use it is up to you. 

You can download the exe and the itextsharp.dll here. Unzip them into the same directory and follow the post below for the flags. The Visual Studio 2008 solution and complete source is here, feel free to adapt as needed.

Let’s go over some of the coding ideas:

iTextSharp needs a Reader and a Writer. The Writer will open a new blank PDF stream and the Reader will open the existing PDF. We then copy over all the Reader contents to the Writer, set our settings, and overwrite the existing PDF. So here is the basic psuedo-code:

Writer = new Writer
Reader = new Reader(existingPDF)
Writer.settings = ourViewSettings
foreach (Page page in Reader.Pages) {
     Writer.Add (page)
}
Reader.Close
Writer.Save (existingPDF)

Start by setting up your environment, download and add the itextsharp.dll to your References. Then add the using statements for iTextSharp and File Handling.

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

Now let us add the basic Writer and Reader for opening an existing PDF, cloning the pages, and overwriting itself.

string filePath = @"C:pdfStoremyPdf.pdf";
Document doc = new Document();
PdfReader reader = new PdfReader(filePath);
using (MemoryStream memoryStream = new MemoryStream())
{
          PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
          doc.Open();
          PdfContentByte cb = writer.DirectContent;
          doc.AddDocListener(writer);
          for (int p = 1; p
          {
               doc.SetPageSize(reader.GetPageSize(p));
               doc.NewPage();
               PdfImportedPage page = writer.GetImportedPage(reader, p);
               int rot = reader.GetPageRotation(p);
               if (rot == 90 || rot == 270)
                    cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
               else
                    cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
          }
          reader.Close();
          doc.Close();
          File.WriteAllBytes(filePath, memoryStream.ToArray());
}

All the above does is open the existing PDF, make a new blank PDF and import all the pages using the same page size and rotation, then saves over itself.

Before we start adding the initial view settings, let us go over what they are. There are three types of settings that this program has control over:

The first controls what Panels are open when a user first opens a PDF, I call these Panel Options. A common setting is to have the Bookmark Panel open, or the Page Thumbs. The exact names vary between PDF Readers.

The next type is the Page Display, which controls if you see 1 or 2 pages at a time and if it is a continuous scroll or if it jumps between pages. I call these Layout Options.

The last type is actions that happen on opening, this program only sets the Magnification (zoom) percentage and the Open To Page settings, but you can apply other actions if needed. These I label Action Options.

As in the psuedo-code, all these settings are applied to the Writer instance, before importing pages. The Panel and Layout options are actually set to the same int value. This is common practice for settings (notably in Microsofts IE registry settings), in which there is no combination of setting values that mean the same.

Example:

settingA = 1, 2 or 3
settingB = 10, 15, 20
options = settingA settingB
Possible Combinations:
A = 1, B = 10 :: final option = 11
A = 2, B = 10 :: final option = 12
A = 3, B = 10 :: final option = 13
A = 1, B = 15 :: final option = 16
A = 2, B = 15 :: final option = 17
A = 3, B = 15 :: final option = 18
A = 1, B = 20 :: final option = 21
A = 2, B = 20 :: final option = 22
A = 3, B = 20 :: final option = 23

As you can see even though Panel and Layout options are set to the variable, adding them together will never result in the wrong combination. Anyways, let us call the final option PageMode:

int PageMode = 0;
// Bookmarks Panel
PageMode = PdfWriter.PageModeUseOutlines;
// No Panels
PageMode = PdfWriter.PageModeUseNone;
// Page View Thumbs Panel
PageMode = PdfWriter.PageModeUseThumbs;
// Attachments Panel
PageMode = PdfWriter.PageModeUseAttachments;
// Layers Panel
PageMode = PdfWriter.PageModeUseOC;

Then we add to PageMode the value for the Layout Option:

// single page, jumps between pages
PageMode = PdfWriter.PageLayoutSinglePage;
// single page, continuous scroll
PageMode = PdfWriter.PageLayoutOneColumn;
// two pages, jumps between pages
PageMode = PdfWriter.PageLayoutTwoPageLeft;
// two pages, continuous scroll
PageMode = PdfWriter.PageLayoutTwoColumnLeft;
// two pages, jumps between pages, Show Cover is on
PageMode = PdfWriter.PageLayoutTwoPageRight;
// two pages, continuous scroll, Show Cover is on
PageMode = PdfWriter.PageLayoutTwoColumnRight;

For the Actions (Zoom) setting it is a little bit more complicated. Basically, when a PDF is opened you can add an Action to be executed. The PDF Action we want to use is GotoLocalPage which takes a Page Number to go to, a PDFDestination, and the Writer instance. When defining the PDFDestination instance you can set the Magnification/Zoom, which gives us all the parts to the Initial View settings!

So first, we define the PDFDestination:

PdfDestination magnify = null;
// equivalent to Default
magnify = new PdfDestination(PdfDestination.FITB);
// Fit Page
magnify = new PdfDestination(PdfDestination.FIT);
// Fit Width
magnify = new PdfDestination(PdfDestination.FITV, 0);
// Fit Height
magnify = new PdfDestination(PdfDestination.FITH, reader.GetPageSize(1).Top);
// Set to %
float magnifyOpt = 100.0;
magnify = new PdfDestination(PdfDestination.XYZ, -1, -1, magnifyOpt/100 );

Just a note, that the Magnification/Zoom is a Float and that it is based on 0-1, 1 being 100%. So my code above divides by 100 so it will correctly set it to 0-1 based. If you want to skip that you can directly send a float like 2.5 for 250% and so on.

Now that we have the PDFDestination, we have to define the PDF Action:

int pageNumberToOpenTo = 1;
PdfAction zoom = PdfAction.GotoLocalPage(pageNumberToOpenTo, magnify, writer);

Note that PDF Numbering starts at 1 (not zero!) so be careful in your for loops or when setting page numbers.

Now that we have all the variables set we can apply them. Going back to the empty PDF open/clone/save code we add these lines after the Writer is instanced (inside the using MemoryStream):

writer.ViewerPreferences = PageMode;
writer.SetOpenAction(zoom);

That is all! You can download the full solution file at the top of this article, or just the exe itself. Below is the full code portion of the executable. Note that there is no error or exception handling – that is left up to you.

 

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

namespace pdfInitView
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 10 || args[0] == "help")
            {
                Console.Error.WriteLine("All flags are required:");
                Console.Error.WriteLine("-f");
                Console.Error.WriteLine("filename = path to file, surround with quotes, include extension");
                Console.Error.WriteLine("-n");
                Console.Error.WriteLine("   p   = Page Only");
                Console.Error.WriteLine("   bp  = Bookmarks Panel and Page");
                Console.Error.WriteLine("   pp  = Page Panel and Page");
                Console.Error.WriteLine("   ap  = Attachment Panel and Page");
                Console.Error.WriteLine("   lp  = Layers Panel and Page");
                Console.Error.WriteLine("-l");
                Console.Error.WriteLine("   d   = Default");
                Console.Error.WriteLine("   sp  = Single Page");
                Console.Error.WriteLine("   sc  = Single Page Continuous");
                Console.Error.WriteLine("   tf  = Two-Up Facing");
                Console.Error.WriteLine("   tfc = Two-Up Continuous Facing");
                Console.Error.WriteLine("   tc  = Two-Up Cover Page");
                Console.Error.WriteLine("   tcc = Two-Up Continuous Cover Page");
                Console.Error.WriteLine("-m");
                Console.Error.WriteLine("   d   = Default");
                Console.Error.WriteLine("   fp  = Fit Page");
                Console.Error.WriteLine("   fw  = Fit Width");
                Console.Error.WriteLine("   fh  = Fit Height");
                Console.Error.WriteLine("   x   = Percentage (do NOT include % sign)");
                Console.Error.WriteLine("-p");
                Console.Error.WriteLine("   x   = Page Number for initial view");
                Console.ReadLine();
            }
            string filePath = string.Empty;
            string navOpt = string.Empty;
            string layoutOpt = string.Empty;
            string magnifyOpt = string.Empty;
            string pageNumInit = string.Empty;
            for (int i = 0; i
            {
                if (args[i] == "-f") { filePath = args[i 1]; }
                if (args[i] == "-n") { navOpt = args[i 1]; }
                if (args[i] == "-l") { layoutOpt = args[i 1]; }
                if (args[i] == "-m") { magnifyOpt = args[i 1]; }
                if (args[i] == "-p") { pageNumInit = args[i 1]; }
            }
            Document doc = new Document();
            PdfReader reader = new PdfReader(filePath);
            int PageMode = 0;
            switch (navOpt)
            {
                case "p": PageMode = PdfWriter.PageModeUseOutlines; break;
                case "bp": PageMode = PdfWriter.PageModeUseNone; break;
                case "pp": PageMode = PdfWriter.PageModeUseThumbs; break;
                case "ap": PageMode = PdfWriter.PageModeUseAttachments; break;
                case "lp": PageMode = PdfWriter.PageModeUseOC; break;
            }
            switch (layoutOpt)
            {
                case "d": PageMode = PdfWriter.PageLayoutSinglePage; break;
                case "sp": PageMode = PdfWriter.PageLayoutSinglePage; break;
                case "sc": PageMode = PdfWriter.PageLayoutOneColumn; break;
                case "tf": PageMode = PdfWriter.PageLayoutTwoPageLeft; break;
                case "tfc": PageMode = PdfWriter.PageLayoutTwoColumnLeft; break;
                case "tc": PageMode = PdfWriter.PageLayoutTwoPageRight; break;
                case "tcc": PageMode = PdfWriter.PageLayoutTwoColumnRight; break;
            }
            PdfDestination magnify = null;
            switch (magnifyOpt)
            {
                case "d": magnify = new PdfDestination(PdfDestination.FITB); break;
                case "fp": magnify = new PdfDestination(PdfDestination.FIT); break;
                case "fw": magnify = new PdfDestination(PdfDestination.FITV, 0); break;
                case "fh": magnify = new PdfDestination(PdfDestination.FITH, reader.GetPageSize(1).Top); break;
                default: magnify = new PdfDestination(PdfDestination.XYZ, -1, -1, (float)Int32.Parse(magnifyOpt)/100 ); break;
            }
            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
                doc.Open();
                PdfContentByte cb = writer.DirectContent;
                writer.ViewerPreferences = PageMode;
                PdfAction zoom = PdfAction.GotoLocalPage(Int32.Parse(pageNumInit), magnify, writer);
                writer.SetOpenAction(zoom);
                doc.AddDocListener(writer);
                for (int p = 1; p
                {
                    doc.SetPageSize(reader.GetPageSize(p));
                    doc.NewPage();
                    PdfImportedPage page = writer.GetImportedPage(reader, p);
                    int rot = reader.GetPageRotation(p);
                    if (rot == 90 || rot == 270)
                        cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
                    else
                        cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
                }
                reader.Close();
                doc.Close();
                File.WriteAllBytes(filePath, memoryStream.ToArray());
            }
        }
    }
}

 

 

 

 

via wskidmore.com
Download source code