Search and Truncate / Trim Paragraph By Sentence C# (not word or character)

mag-glassI’ve had the need on more than one occasion to preview or trim a paragraph around a search term, but I don’t want to just use a character count and cut words in half, or a word could and cut sentences in half. My simple method below takes a paragraph and a search word and returns a string that is truncated by sentences. With some additional params, you can decide how many sentences to include from around your desired sentence, if you want a “read more” tag or begging tag to indicate more text exists.

In this example, I’m searching for a word in a string object (‘para’).

truncateBySent(para, "redmond", 1, 1, true, " View More...", false, "...", false, "Not Found")

In this example paragraph:

By a board session on the weekend of Dec. 14, some board members were exhausted from the months of work, and were concerned that the process had dragged on, said a person familiar with the matter. They left the meeting, at a hotel less than 8 miles from Microsoft’s Redmond, Wash., headquarters, without a pick. The board had more potential CEO candidates with whom they wanted to meet, and were frustrated that research wasn’t ready on at least one new prospect, said people familiar with the situation.

It would return:

…They left the meeting, at a hotel less than 8 miles from Microsoft’s Redmond, Wash., headquarters, without a pick. The board had more potential CEO candidate s with whom they wanted to meet, and were frustrated that research wasn’t ready on at least one new prospect, said people familiar with the situation.
 

Another variation:

truncateBySent(para, “board”, 1, 1, true, ” View More…”, false, “…”, false, “Not Found”)

Returns:

By a board session on the weekend of Dec. 14, some board members were exhausted from the months of work, and were concerned that the process had dragged on, said a person familiar with the matter. They left the meeting, at a hotel less than 8 miles from Microsoft’s Redmond, Wash., headquarters, without a pick. View More…
 

And here is the function, you’ll need to import:

using System.Linq;
using System.Text.RegularExpressions;
  public static string truncateBySent(string source, string searchWord, int sentPrepend = 1, int sentAppend = 1, bool onlyShowFirst = true, string viewMoreTag = "", bool alwaysShowViewMoreTag = false, string startTruncTag = "", bool returnSourceIfKeywordNotFound = false, string returnNotFound = "")
        {
            //going to be the final string
            string truncated = "";

            //parse source sentences
           string[] sents = Regex.Split(source, @"(?<=[.?!;])\s+(?=\p{Lu})");

            //create some search start & end holders
            int i = 0;
            int ssent = -1;
            int esent = 0;

            //find start / end
            foreach (string sent in sents)
            {
                //search using regex for word boundaries \b
                if (Regex.IsMatch(sent, "\\b" + searchWord + "\\b", RegexOptions.IgnoreCase))
                {
                    if (ssent == -1)
                    {
                        ssent = i;
                    }
                    else
                    {
                        esent = i;
                    }
                }

                i++;
            }

            //make final string:

            if (esent == 0 || onlyShowFirst == true) esent = ssent;

            i = 0;

            foreach (string sent in sents)
            {
                if (i == ssent - sentPrepend || i == ssent || i == esent + sentAppend || (i >= ssent - sentPrepend && i <= esent + sentAppend))
                {
                    truncated = truncated + sent + " ";
                }

                i++;
            }

            //add view more

            if (esent + sentAppend + 1 < sents.Count() || alwaysShowViewMoreTag == true)
            {
                truncated = truncated + viewMoreTag;
            }

            //add beginning tag
            if (ssent - sentPrepend > 0)
            {
                truncated = startTruncTag + truncated;
            }

            //check if anything was even found:

            if (ssent == -1)
            {
                if (returnSourceIfKeywordNotFound)
                { truncated = source; }
                else
                {
                    truncated = returnNotFound;
                }
            }

           //and now return the final string - do a trim and remove double spaces.
            //did i ever mention how much i despise double spaces?
            return truncated.Trim().Replace("  ", " ");
        }

 

Happy Searching!

Search and Truncate / Trim Paragraph By Sentence C# (not word or character)

SQL Server / Renaming Databases With Active Connections

hello-my-name-isI believe there are many methods and opinions that exist on the best practice to rename a SQL Server DB. Below I’ll quickly give you the method I use to rename a database. In the below example, I rename two DB’s – a common scenario if you’re swapping your production database with a different version:

-- #1 change first db name
use master
-- set db to single user
ALTER DATABASE myProdDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
-- do the rename
ALTER DATABASE myProdDB MODIFY NAME = [myOldProdDB]
-- set back to multi user
ALTER DATABASE myOldProdDB SET MULTI_USER

-- #2 change second db name
use master
-- set db to single user
ALTER DATABASE myNewProdDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
-- do the rename
ALTER DATABASE myNewProdDB MODIFY NAME = [myProdDB]
-- set back to multi user
ALTER DATABASE myProdDB SET MULTI_USER

Note: this does not change the database or log file names, just the database name.

SQL Server / Renaming Databases With Active Connections

Installing & starting with PhoneGap on Windows for cross platform mobile development

Build-BotPhoneGap is a great framework for creating cross platform apps (Android, iOS, BB, WM, etc.) using HTML, CSS, and JavaScript and uses Apache Cordova™. Installing and testing on Windows takes little setup, below I’ve tried to cover all of the steps needed to get going. My setup / guide below uses Windows 7, 64 bit, it seems like many steps, but in reality is pretty easy.

  1. Install node.js from nodejs.org (use default settings).
  2. Open a command prompt (cmd) and run:
    1. npm install -g phonegap
    2. npm install -g ant
    3. npm install –g cordova
    4. Now add ‘C:\Users\<yourusername>\AppData\Roaming\npm\node_modules\ant\ant\bin’ to the Path system variable
    5. Download and extract the Android SDK from https://developer.android.com/sdk/index.html
      1. I extracted to c:\mobile\androidsdk (referenced below as <yoursdkpath>)
      2. Add <yoursdkpath> + \sdk\platform-tools to the Path system variable
      3. Add <yoursdkpath> + \sdk\tools to the Path system variable
      4. Now to setup an Android image to emulate and test with:
        1. In the sdk folder, run Eclipse (ie: C:\mobile\androidsdk\eclipse\eclipse.exe
        2. Create or use the default workspace
        3. In Eclipse, under Window choose Android SDK Manager
        4. In the SDK Manager, make sure these are checked:
        5. i.      Tools > SDK Tools, Platform-tools
        6. ii.      Android <you choose the version> SDK Platform, Arm system image & Intel system image (if available)
        7. iii.      Extras > Android Support Library, Google USB Driver, Intel x86 emulator HAXM
  3. Click Install x Packages, accept all licenses
  4. When downloads are finished, close the SDK Manager
  5. If you want to speed up the Android emulator, I suggest installing the Intel HAXM located at: \sdk\extras\intel\Hardware_Accelerated_Execution_Manager
  6. Now back in Eclipse (restart if you’ve installed the HAXM), you can go to Window > Android Virtual Device Manager.
  7. Click “New” to create a new virtual device
  8. Choose a name (anything you want)
  9. Choose a device (something simple like the “4.0” WVGA”)
  10. Choose a target (this is what you downloaded in step 4d).
  11. In CPU, choose Intel if it’s available (it’s not required, but if it’s not available, double check the HAXM install and the download the Intel system image for your target version)
  12. Now you can click “OK”
  13. In the list of virtual devices, choose your new device and click “Start”
  14. Provided you don’t see any errors, after a few minutes (be patient) you’ll have a working Android emulator going. android-emulator
  15. Now, let’s do a quick project and test it! Go back to cmd (your command prompt).
  16. Create your project with, run: cordova create hello com.ex.hello “HelloChris”
  17. Go to the project directory, run: cd hello
  18. Add android to the project, run: cordova platform add android
  19. To make sure your project is ok, run: cordova build
  20. Now if you don’t already have your emulator running, go back into Eclipse into the Android Virtual Device Manager and start your device.
  21. When it’s running, run: cordova emulate android
  22. That’s it; you should see “your” app on the emulator in a few seconds. (It reads “device ready” with a logo or something…).

Continue reading “Installing & starting with PhoneGap on Windows for cross platform mobile development”

Installing & starting with PhoneGap on Windows for cross platform mobile development

Quick guide to installing Django framework on Windows

djangoDjango is a dev framework for building web apps that uses Python. It has many great features (db api, auto admin interface, templates, cache framework, etc.). Installing the framework on Windows take a few steps to get going and has a few prerequisites. The below steps assume you don’t have Python or Django currently installed. This guide was created on Windows 7 (64 bit). Now let’s get to it:

  1. Download Python: http://www.python.org/download/releases/3.3.3/
  2. Install Python (to c:\python)
  3. Go to the pip download area: http://www.pip-installer.org/en/latest/installing.html#using-the-installer
  4. Right click, download / save ez_setup.py to c:\python
  5. In cmd prompt: cd\python
  6. Run: python.exe ez_setup.py
  7. From the same link, download get-pip.py
  8. In the cmd prompt, run python.exe get-pip.py
  9. When finished, in cmd, navigate to: \python\scripts  (where pip lives now)
  10. Now run pip install Django
  11. To see if Django was installed correctly, at a cmd prompt run:
    python -c “import django; print(django.get_version())”
    This should return 1.6.1 (or similar).
  12. Add c:\python\scripts to your windows environment path
  13. Close / reopen a cmd prompt (to reflect the addition to your PATH variable)
  14. Now you can navigate to any folder (ie: c:\projects) and run:
    django-admin.py startproject thenextbigidea
  15. Your project was created! To test:
  16. Navigate to c:\projects\thenextbigidea and run:
    python manage.py runserver
  17. In your browser, visit: http://localhost:8000/

So that’s just the start. Visit https://docs.djangoproject.com to continue your journey!

Quick guide to installing Django framework on Windows

Enabling SMB / Samba Write on Xbian (XBMC for Raspberry Pi)

Raspi_Colour_RIf you’ve got a Raspberry Pi (if you don’t, please go order one right now), and use Xbian (a great version of XBMC for Pi) you may have connected to your Pi via SMB but noticed it’s read only. Fixing this (to read / write) only takes a few seconds.

Provided you already have Xbian installed and your Pi is connected to your network and you know the address (something like 192.168.x.x – or you should be able to simple use “Xbian”), you can:

  1. On a PC, download and run Putty. Putty is a great – free – ssh terminal app.
  2. Enter your Pi’s ip (or “Xbian”) in the host name textbox.
  3. Click Open to connect to the Pi.
  4. Enter the default username: xbian and password: raspberry
  5. At the prompt, enter: sudo nano /etc/usbmount/usbmount.conf
  6. In Nano (a text editor) find the line: SMBSHARE=no
  7. Change SMBSHARE=no to SMBSHARE=yes
  8. Exit Nano and save (Control+X, Y).
  9. Reboot.
  10. You should now be able to connect to you Pi in Windows using SMB with \\XBIAN\ or find your Pi in your Network and have write permission.

Happy downloading AND uploading.

Enabling SMB / Samba Write on Xbian (XBMC for Raspberry Pi)

Checking if a file is locked in C# using Win32

Below is a simple, fast way you can check if a file is locked, using Interop to use a win32 function. I’ve found this method to be pretty fast, but I would caution, you should still have some error logic in your code in case in the window of time between you checking your file for availability and using your file, it should become locked. Below is the c# code:

Using:

using System;
using System.IO;
using System.Runtime.InteropServices;

And in your class:

  [DllImport("kernel32.dll")]
        private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition, System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

        private static readonly uint GENERIC_WRITE = 0x40000000;
        private static readonly uint OPEN_EXISTING = 3;

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(SafeHandle hObject);

        public static bool boolFileLocked(string fPath)
        {
            if (!File.Exists(fPath))
            {
                return false;
            }

            SafeHandle sHandle = null;

            try
            {
                sHandle = CreateFile(fPath, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

                bool inUse = sHandle.IsInvalid;

                return inUse;
            }
            finally
            {
                if (sHandle != null)
                {
                    CloseHandle(sHandle);
                }
            }
        }

To test, toss this into your Main:

long tStart = DateTime.Now.Ticks;
Console.WriteLine("start");
Console.WriteLine(boolFileLocked(@"c:\locked.xlsx"));
Console.WriteLine(string.Format("{0:n0}", DateTime.Now.Ticks - tStart));
tStart = DateTime.Now.Ticks;
Console.WriteLine(boolFileLocked(@"c:\unlocked.xls"));
Console.WriteLine(string.Format("{0:n0}", DateTime.Now.Ticks - tStart));
tStart = DateTime.Now.Ticks;
Console.WriteLine(boolFileLocked(@"c:\missing.xls"));
Console.WriteLine(string.Format("{0:n0}", DateTime.Now.Ticks - tStart));
Console.WriteLine("end");
Console.ReadLine();
Checking if a file is locked in C# using Win32

RavenDB Document Database – Super Quickstart Guide

Raven-info0RavenDB is among the many available document databases on the market today (mongo, redis, etc.). If you’re looking to try this db and see if it’s right for your project, below is a super quick guide to start using using RavenDB on Windows with asp.net. Below are my 10 simple steps to start using. You can skip to the bottom for entire “source” code.  Continue reading “RavenDB Document Database – Super Quickstart Guide”

RavenDB Document Database – Super Quickstart Guide

Overlaying / compositing images using c# – System.Drawing

If you have an image or images you want to apply another image on top of, it’s easy using CompositingMode & DrawImage in .net. Below is simple example showing a .jpg photo overlaying with a transparent .png file. You could use this technique to apply a custom watermark, logo, copyright, etc. to images. In the code are also some options for showing the image and saving the final file. Happy compositing!

            Bitmap baseImage;
            Bitmap overlayImage;

            baseImage = (Bitmap)Image.FromFile(@"C:\temp\base.jpg");

            overlayImage = (Bitmap)Image.FromFile(@"C:\temp\overlay.png");

            var finalImage = new Bitmap(overlayImage.Width, overlayImage.Height, PixelFormat.Format32bppArgb);
            var graphics = Graphics.FromImage(finalImage);
            graphics.CompositingMode = CompositingMode.SourceOver;

            graphics.DrawImage(baseImage, 0, 0);
            graphics.DrawImage(overlayImage, 0, 0);

            //show in a winform picturebox
            pictureBox1.Image = finalImage;

            //save the final composite image to disk
            finalImage.Save(@"C:\temp\final.jpg", ImageFormat.Jpeg);

You’ll probably want to include:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
Overlaying / compositing images using c# – System.Drawing

PowerPoint VBA / Macro Controls On Slides – Return Focus To The Slide

I recently had the need to add some functionality to some PowerPoint presentations. While it was “fun” to use VBA (brought be back to the classic .asp days) I had forgotten a few issues. One main issue, if you have a button on a slide, when the button is clicked, the focus still remains on the button, not the slide. If you press next or use a presentation ‘clicker’ it won’t advance the slide because you’re still focused on the button. The easiest way I’ve found to return focus back to the slide is by hiding and showing the control. See below:

Private Sub cmdYourButton_Click()
'Do something cool here
cmdYourButton.Visible = False
cmdYourButton.Visible = True
'Focus is now back on the slide!
End Sub

One final note: if you’re looking for the “Developer” tab in PowerPoint, go to File > Options > Customize Ribbon and check “Developer” under ‘Main Tabs’.

Happy presenting!

PowerPoint VBA / Macro Controls On Slides – Return Focus To The Slide

Tweet button / link without javascript – HTML only

Twitter buttonIf you’ve ever wanted to include a ‘Tweet’ button or link but didn’t want to use the popular Tweet Button code from Twitter (it uses a remote javascript function), there is an alternate approved method called “Intents”. This function works great for instances when simple HTML is preferred (emails, pages geared toward older or simple browsers, etc.). However it doesn’t provide extras like showing how many have used the button or creating the image automatically. So how does it work?

Using Twitter’s Web Intents, you can create links like below:

<a href="http://twitter.com/intent/tweet?url=http://chrisbitting.com
&text=Checkout this awesome blog.&via=chrisbitting&hashtags=twitter"
 title="Tweet" target="_blank">Tweet</a>

Which looks like: Tweet

No Javascript!

Be sure to check the documentation for more options and details: https://dev.twitter.com/docs/intents

Tweet button / link without javascript – HTML only