Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

Thursday, October 18, 2012

OpenXml Reset Numbering Level


I want to create Word Document using OpenXml and create numbering level. I faced a problem when I want to start numbering Level.
To Solve this problem you need to create new instance from abstract number using function as below:

   
      static Numbering AddAbstractNumbering(Numbering numbering1, int numberId,
             int abstractNumber)
      {
          NumberingInstance numberingInstance6 = new NumberingInstance ()
          {NumberID = numberId};          
          AbstractNumId abstractNumId6 = new AbstractNumId() { Val = 1 };
          numberingInstance6.Append(abstractNumId6,
             new LevelOverride() {
                    StartOverrideNumberingValue = new StartOverrideNumberingValue() { Val = 1 }
             } );
          numbering1.Append(numberingInstance6);
          return numbering1;
      }


and use this instance to add numbering level to your paragraph:

   
      Paragraph paragraph2 = new Paragraph();
      ParagraphProperties paragraphProperties1 = new ParagraphProperties();
      ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
      NumberingProperties numberingProperties1 = new NumberingProperties();
      NumberingLevelReference numberingLevelReference1 =  
                                            new NumberingLevelReference() { Val = 0 };
      NumberingId numberingId1 = null;
      if (isNumberingStart)
      {
             numberId++;
             numbering1 = AddAbstractNumbering(numbering1, numberId);
             isNumberingStart = false;
       }
       numberingId1 = new NumberingId() { Val = numberId };
       numberingProperties1.Append(numberingLevelReference1);
       numberingProperties1.Append(numberingId1);

       paragraphProperties1.Append(paragraphStyleId1);
       paragraphProperties1.Append(numberingProperties1);

        paragraph2.Append(paragraphProperties1);

Monday, May 7, 2012

Convert to Base64

Base64 encoding used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with textual data. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.

Below way of conversion to Base64 using csharp or javascript:
Conversion from/to base64 using csharp:
    static public string EncodeTo64(string toEncode)
    {
      byte[] toEncodeAsBytes
            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
      string returnValue
            = System.Convert.ToBase64String(toEncodeAsBytes);
      return returnValue;
    }

    static public string DecodeFrom64(string encodedData)
    {
      byte[] encodedDataAsBytes
          = System.Convert.FromBase64String(encodedData);
      string returnValue =
         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
      return returnValue;
    }


Conversion from/to base64 using javascript:
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
        Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = Base64._keyStr.indexOf(input.charAt(i++));
        enc2 = Base64._keyStr.indexOf(input.charAt(i++));
        enc3 = Base64._keyStr.indexOf(input.charAt(i++));
        enc4 = Base64._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }
    return string;
}
}

Also there is jquery library for base64:
https://github.com/carlo/jquery-base64

Thursday, April 28, 2011

Regular expressions

Sometimes I required to do some tasks using regular expression. In this post I decided to collect my regular expressions:

First regular expression is to find images in the html and replace its src url:







static string ReplaceTag(string HTMLBody, string srcPath, string newPath)
{
Regex reImg = new Regex(@"]*>", RegexOptions.IgnoreCase);
Regex reHeight = new Regex(@"height=(?:(['""])(?(?:(?!\1).)*)\1(?[^\s>]+))", RegexOptions.IgnoreCase RegexOptions.Singleline);
Regex reWidth = new Regex(@"width=(?:(['""])(?(?:(?!\1).)*)\1(?[^\s>]+))", RegexOptions.IgnoreCase RegexOptions.Singleline);
Regex reSrc = new Regex(@"src=(?:(['""])(?(?:(?!\1).)*)\1(?[^\s>]+))", RegexOptions.IgnoreCase RegexOptions.Singleline);
string tmpHTMLBody = HTMLBody;
MatchCollection mc = reImg.Matches(HTMLBody);
foreach (Match mImg in mc)
{
Console.WriteLine(" img tag: {0}", mImg.Groups[0].Value);
string tmpImgTag = string.Empty;
string tmpOldImgSrc = string.Empty;
string tmpNewImgSrc = string.Empty;
tmpImgTag = mImg.Groups[0].Value;

if (reHeight.IsMatch(mImg.Groups[0].Value))
{
Match mHeight = reHeight.Match(mImg.Groups[0].Value);
Console.WriteLine(" height is: {0}", mHeight.Groups["height"].Value);
}
if (reWidth.IsMatch(mImg.Groups[0].Value))
{
Match mWidth = reWidth.Match(mImg.Groups[0].Value);
Console.WriteLine(" width is: {0}", mWidth.Groups["width"].Value);
}
if (reHeight.IsMatch(mImg.Groups[0].Value))
{
Match mSrc = reSrc.Match(mImg.Groups[0].Value);
tmpOldImgSrc = mSrc.Groups["src"].Value;
tmpNewImgSrc = tmpOldImgSrc.ToLower().Replace(srcPath.ToLower(), newPath.ToLower());
tmpHTMLBody = tmpHTMLBody.ToLower().Replace(tmpOldImgSrc.ToLower(), tmpNewImgSrc.ToLower());
Console.WriteLine(" src is: {0}", mSrc.Groups["src"].Value);
}
}
return tmpHTMLBody;
}

This Regular Expression to Clean Word to Html remove word classes and attributes:







static internal string CleanWordHtml(string html)
{
// start by completely removing all unwanted tags
html = Regex.Replace(html, @"<[/]?(fonth1h2h3h4h5h6bspanxmldelins[ovwxp]:\w+)[^>]*?>", "", RegexOptions.IgnoreCase);
// then run another pass over the html (twice), removing unwanted attributes
html = Regex.Replace(html, @"<([^>]*)(?:classlangstylesizeface[ovwxp]:\w+)=(?:'[^']*'""[^""]*""[^\s>]+)([^>]*)>", "<$1$2>", RegexOptions.IgnoreCase);
html = Regex.Replace(html, @"<([^>]*)(?:classlangstylesizeface[ovwxp]:\w+)=(?:'[^']*'""[^""]*""[^\s>]+)([^>]*)>", "<$1$2>", RegexOptions.IgnoreCase);
return html;
}

This Regular Expression to remove tags from Html:







static internal string StripHtml(string html, bool allowHarmlessTags)
{
if (html == null html == string.Empty)
return string.Empty;

if (allowHarmlessTags)
return System.Text.RegularExpressions.Regex.Replace(html, "", string.Empty);

string strippedHtml = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty);
strippedHtml = HttpUtility.HtmlDecode(strippedHtml);
return strippedHtml;
}


Check that a string contains Arabic Characters using C#:





static internal bool hasArabic(string text)
{
Regex regex = new Regex(
"\\p{IsArabic}");
return regex.IsMatch(text);
}

Saturday, January 22, 2011

Convert Html to Image

I searched for free open source csharp to convert html to image. I found solution using:

WebBrowser (namespace System.Windows.Forms) code below is sample of conversion:


static byte[] CaptureWebPageBytesP(string body, int? width, int? height)
{
byte[] data;
// create a hidden web browser, which will navigate to the page
using (WebBrowser web = new WebBrowser())
{
web.ScrollBarsEnabled = false; // we don't want scrollbars on our image
web.ScriptErrorsSuppressed = true; // don't let any errors shine through
web.Navigate("about:blank");
// wait until the page is fully loaded
while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
web.Document.Body.InnerHtml = body;

// set the size of our web browser to be the same size as the page
if (width == null)
width = web.Document.Body.ScrollRectangle.Width;
if (height == null)
height = web.Document.Body.ScrollRectangle.Height;
web.Width = width.Value;
web.Height = height.Value;
// a bitmap that we will draw to
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width.Value, height.Value))
{
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, new Rectangle(web.Location.X, web.Location.Y, web.Width, web.Height));
// draw the web browser to the bitmap
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
EncoderParameter qualityParam = null;
EncoderParameters encoderParams = null;
try
{
ImageCodecInfo imageCodec = null;
//imageCodec = getEncoderInfo("image/jpeg");
imageCodec = getEncoderInfo("image/bmp");

// Encoder parameter for image quality
qualityParam = new EncoderParameter(Encoder.Quality, 100L);

encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
bmp.Save(stream, imageCodec, encoderParams);
}
catch (Exception)
{
throw new Exception();
}
finally
{
if (encoderParams != null)
encoderParams.Dispose();
if (qualityParam != null)
qualityParam.Dispose();
}
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
}
}
}
return data;
}

But I faced problem when I try to use it without Window Forms (console application, aspnet, or windows service) It gave me error cannot be instantiated because the current thread is not in a single-threaded. To solve this error created STAThread like code below:

public static byte[] CaptureWebPageBytes(string body, int? width, int? height)
{
bool bDone = false;
byte[] data = null;
DateTime startDate = DateTime.Now;
DateTime endDate = DateTime.Now;

//sta thread to allow intiate WebBrowser
var staThread = new Thread(delegate()
{
data = CaptureWebPageBytesP(body, width, height);
bDone = true;
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
while (!bDone)
{
endDate = DateTime.Now;
TimeSpan tsp = endDate.Subtract(startDate);

Application.DoEvents();
if (tsp.Seconds > 50)
{
break;
}
}
staThread.Abort();
return data;
}