Tag Archives: C#

C# getting correct user IP even if HTTP_X_FORWARDED_FOR contains multiple IP Addresses

HTTP_X_FORWARDED_FOR can return multiple IP Addresses, for example 32.122.54.21, 32.122.54.25, 32.122.65.23 following the general format of the field

X-Forwarded-For: client, proxy1, proxy2

Source: Wikipedia / X-Forwarded-For

My approach

public static string GetClientIp()
{
	string ip = string.Empty;

	ip = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] : System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
	if (ip.Contains(","))
	{
		ip = ip.Split(',').First().Trim();
	}

	if (string.IsNullOrWhiteSpace(ip))
	{
		ip = "0.0.0.0";
	}
	
	return ip;
}
	

C# Dapper – return single result

public static string GetImage(int restaurantId)
{
	using (SqlConnection conn = new SqlConnection(Common.ConnectionString))
	{
		conn.Open();
		const string query = "SELECT ImageURL FROM [Restaurant_Featured] WHERE RestaurantId = @RestaurantId";
		LEORestaurant_Featured featured = conn.Query<Restaurant_Featured>(query, new { RestaurantId = restaurantId }).SingleOrDefault();
		conn.Close();

		return featured != null && !string.IsNullOrWhiteSpace(featured.ImageURL) ? featured.ImageURL : string.Empty;
	}
}

ASP.NET CustomValidator AJAX call using jQuery and Webservice (page method)

Markup

<asp:TextBox ID="txtEmail" runat="server" />
<asp:CustomValidator id="CustomValidator3" runat="server" ErrorMessage="- The email address you provided has already been used." Display="None" ControlToValidate="txtEmail" ClientValidationFunction="validateEmail"></asp:CustomValidator>

JavaScript

function validateEmail(oSrc, args) {
	var isValid;
	if (args.Value == '' || args.Value == undefined || $('#<%= txtEmailConfirm.ClientID %>').val() == '') {
		// prevent from calling webservice when unnecessary
		isValid = true;
		args.IsValid = true;
	}
	else {
		$.ajax({
			type: "POST",
			url: "Default.aspx/ValidateEmail",
			contentType: "application/json; charset=utf-8",
			data: "{ 'email':  '" + args.Value + "'}",
			dataType: "json",
			async: false,
			success: function (msg) {
				isValid = msg.d;
			}
			//, error: function () { }
		});
	}
	args.IsValid = isValid;
//        console.log('args.IsValid: ' + args.IsValid);
//        console.log('isValid: ' + isValid);
}

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using TCUV_contest;

public partial class Default : System.Web.UI.Page
{
    [WebMethod]
    public static bool ValidateEmail(string email)
    {
        return Utilities.EmailAlreadyUsed(email);
    }
}

Sometimes args.IsValid remains unchaged. Useful steps:

  • setting args.IsValid at the end of the code
  • setting $.ajax async property to false (async: false)

Helpful reading: Brian Dobberteen blog

C# Delete files older than a date

static class Helpers
{
    public static void DeleteOldFiles(string folderPath, uint maximumAgeInDays, params string[] filesToExclude)
    {
        DateTime minimumDate = DateTime.Now.AddDays(-maximumAgeInDays);
        foreach (var path in Directory.EnumerateFiles(folderPath))
        {
            if (IsExcluded(path, filesToExclude))
                continue;

            DeleteFileIfOlderThan(path, minimumDate);
        }
    }

    private const int RetriesOnError = 3;
    private const int DelayOnRetry = 1000;

    private static bool IsExcluded(string item, string[] exclusions)
    {
        foreach (string exclusion in exclusions)
        {
            if (item.Equals(exclusion, StringComparison.CurrentCultureIgnoreCase))
                return true;
        }

        return false;
    }

    private static bool DeleteFileIfOlderThan(string path, DateTime date)
    {
        for (int i = 0; i < RetriesOnError; ++i)
        {
            try
            {
                FileInfo file = new FileInfo(path);
                if (file.CreationTime < date)
                    file.Delete();

                return true;
            }
            catch (IOException)
            {
                System.Threading.Thread.Sleep(DelayOnRetry);
            }
            catch (UnauthorizedAccessException)
            {
                System.Threading.Thread.Sleep(DelayOnRetry);
            }
        }

        return false;
    }
}

source: Stack Overflow

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

C# console prompt example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsolePromptExample
{
    class Program
    {
        bool exit = false;

        static void Main(string[] args)
        {
            Program program = new Program();
            program.Start();
        }

        public void Start()
        {
            // do some stuff
            // SomeObject someObjet = new SomeObject();
            // someObjet.Initialize();

            while (exit == false)
            {
                RunCommand(Prompt());
            }
        }

        public void RunCommand(string command)
        {
            switch (command.Contains(" ")
                   ? command.Split(' ')[0].ToLower()
                   : command.ToLower())
            {
                case "x":
                case "q":
                case "quit":
                case "exit":
                    exit = true;
                    return;

                case "scan":

                    Console.WriteLine("scan done");
                    break;

                case "?":
                case "help":
                    PrintHelp();
                    break;

                default:
                    Console.WriteLine("I didn't get that ...");
                    break;
            }
        }

        public void PrintHelp()
        {
            string helpFile = "help.txt";
            string WorkingDirectory = Directory.GetCurrentDirectory().Replace("bin\\Debug", string.Empty);
            string file = string.Format("{0}\\{1}", WorkingDirectory, helpFile);

            using (StreamReader r = new StreamReader(File.OpenRead(file)))
            {
                while (r.Peek() > -1)
                {
                    Console.WriteLine(r.ReadLine());
                }
                Console.WriteLine();
            }
        }

        public string Prompt()
        {
            Console.Write("what's next >");
            return Console.ReadLine();
        }
    }
}

DOWNLOAD example

C# console application – file location

public void PrintFile()
{
	string helpFile = "test.txt"; // located in root 
	string WorkingDirectory = System.IO.Directory.GetCurrentDirectory().Replace("bin\\Debug", string.Empty); // replace string.Empty with subdirectory name if needed

	string file = string.Format("{0}\\{1}", WorkingDirectory, helpFile);
	using (System.IO.StreamReader r = new System.IO.StreamReader(System.IO.File.OpenRead(file)))
	{
		while (r.Peek() > -1)
		{
			Console.WriteLine(r.ReadLine());
		}
		Console.WriteLine();
	}
}

C# Close Console Application on key press

class Program{    static void Main(string[] args)    {        CloseApp();    }    private static void CloseApp()    {        Console.WriteLine("Press 'ESC' or 'X' to Exit");                ConsoleKeyInfo keys;        while (true)        {            keys = Console.ReadKey();            if (keys.Key == ConsoleKey.Escape || keys.Key == ConsoleKey.X) break;            Console.WriteLine();        }    }}

File Content and Directory Search using Directory.GetFiles and PLINQ

Array of File Names

Starting .NET 4, you can use PLINQ queries to parallelize operations on file directories. The following code snippet shows how you can write a query by using the GetFiles method to populate an array of file names in a directory and all subdirectories. This method does not return until the entire array is populated, and therefore it can introduce latency at the beginning of the operation. However, after the array is populated, PLINQ can be used to search inside all the files with the specific extension located in a particular directory for a specific word very quickly. For measuring the performance, you can create a folder called CLOBS and create 8 large text files (1GB each).