Archive

Archive for the ‘.NET’ Category

C# word automation : Inserting page break

May 30, 2011 Leave a comment

I went through many articles in order to insert a page break in word document with C#. Though they seemed to work for others, they did not for me. But I did find a way to insert breaks.

object oEndOfDoc = "\\endofdoc";
object paramNextPage = WdBreakType.wdSectionBreakNextPage;

wrdDocument.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertBreak(ref paramNextPage);

WHERE
wrdDocument
- Active word document object of type : Microsoft.Office.Interop.Word.Document

Categories: .NET

C# Word Automation: Inserting images with text wrapping around

March 9, 2011 3 comments

As I work, I keep noting about my work here. Earlier, I wrote about inserting images in a word document at a bookmark in this post. Later, arose the need for having text wrapping around an image if it is small for document width. Solution is to use frames to achieve it and here is how I did it.

CImage class definition:

    public class CImage
    {
        public string Path
        {
            get;
            set;
        }

        public decimal Id
        {
            get;
            set;
        }

        public string Title
        {
            get;
            set;
        }

        public Image Bitmap
        {
            get;
            set;
        }

        public bool BusyLoading
        {
            get;
            set;
        }

        public void GetImage()
        {
            try
            {
                BusyLoading = true;
                WebRequest req = WebRequest.Create(Path);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                Bitmap = Image.FromStream(stream);
                
                stream.Close();
            }
            catch
            {
                Bitmap = null;
            }
            finally
            {
                BusyLoading = false;
            }
        }

 
        public override bool Equals(object obj)
        {
            CImage objToCompare = obj as CImage;
            if (objToCompare == null)
                return false;
            return this.Id.Equals(objToCompare.Id);
        }
    }

Adding frame at end of the document (can be any bookmark for that matter)

Frame wrdFrame = wrdDocument.Frames.Add(wrdDocument.Bookmarks.get_Item(ref oEndOfDoc).Range);

WHERE
wrdDocument
- Active word document object of type : Microsoft.Office.Interop.Word.Document

Setting frame properties for textwrap and autosize

wrdFrame.TextWrap = true;
wrdFrame.VerticalDistanceFromText = 7;
wrdFrame.HorizontalDistanceFromText = 10;
wrdFrame.HeightRule = WdFrameSizeRule.wdFrameAuto;
wrdFrame.WidthRule = WdFrameSizeRule.wdFrameAuto;

Inserting image in frame

Clipboard.SetDataObject(objImage.Bitmap);
wrdFrame.Range.Paste();

WHERE
objImage
- Object of type CImage

And you are done !

Important information

You need to add a COM reference to your favorite word object library which should in turn add

Related Posts
Categories: .NET

C# Word Automation : How to add a Shape textbox

March 3, 2011 3 comments

Though I took quite a lot of time to figure it out; when I did – it actually seemed pretty simple !

Shape wrdTextBox = wrdDocument.Shapes.AddTextbox(
Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
0, 2, 500, 30, ref objRange);

WHERE

wrdDocument
- Active word document object of type : Microsoft.Office.Interop.Word.Document

objRange
- Range object in wrdDocument where I want this text box to be inserted of type : Microsoft.Office.Interop.Word.Range

 

In order to assign text and style to this text box:


wrdTextBox.TextFrame.TextRange.Text = "I am sitting right inside a textbox in word";
wrdTextBox.TextFrame.TextRange.set_Style(ref my_style);

 

 

Important information

You need to add a COM reference to your favorite word object library which should in turn add

Related Posts
Categories: .NET

C# Word Automation: Solve “The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)”

December 29, 2010 5 comments

Assignment:
Export data in word 2003 format using COM Interop

Problem:
First time export worked just fine. Second time, I received exception “The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)” for “Microsoft.Office.Interop.Word”

Solution:

  
public class CDocumentExporter
{
        static ApplicationClass _word_application;

        public static ApplicationClass AppClass
        {
            get
            {

                if (_word_application == null)
                {
                    _word_application = new ApplicationClass();
                    _word_application.ApplicationEvents2_Event_Quit += new ApplicationEvents2_QuitEventHandler(_word_application_ApplicationEvents2_Event_Quit);
                }
                return _word_application;
            }
        }

        static void _word_application_ApplicationEvents2_Event_Quit()
        {
            _word_application = null;
        }
}//end of class

And just use the CDocumentExporter.AppClass wherever necessary

Important information

You need to add a COM reference to your favorite word object library which should in turn add

Related Posts
Categories: .NET

C# Word Automation: Inserting Images

December 23, 2010 3 comments

I was looking for a way to insert images at a bookmark in a word document and thought should document these for future reference

CImage class Definition

public class CImage
{
        public string Path
        {
            get;
            set;
        }

        public decimal Id
        {
            get;
            set;
        }

        public string Title
        {
            get;
            set;
        }

        public Image Bitmap
        {
            get;
            set;
        }

        public bool BusyLoading
        {
            get;
            set;
        }

        public void GetImage()
        {
            try
            {
                BusyLoading = true;
                WebRequest req = WebRequest.Create(Path);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                Bitmap = Image.FromStream(stream);
                stream.Close();
            }
            catch
            {
                Bitmap = null;
            }
            finally
            {
                BusyLoading = false;
            }
        }
}

Scenario 1:
You have a path of the image file which is to be inserted

public static void SetBookMark(Document p_objWordDocument, string p_strName,
          CImage p_objImage)
        {
            if (p_objWordDocument.Bookmarks.Exists(p_strName))
            {
                object objBookMark = p_strName;
                p_objWordDocument.Bookmarks.get_Item(ref objBookMark).Range.InlineShapes.AddPicture(p_objImage.Path, ... dozons of object params ...);
            }
        }

Scenario 2:
When you have the bitmap in memory

public static void SetBookMark(Document p_objWordDocument, string p_strName,
           CImage p_objImage)
        {
            if (p_objWordDocument.Bookmarks.Exists(p_strName))
            {
                object objBookMark = p_strName;
                Clipboard.SetDataObject(p_objImage.Bitmap);
                p_objWordDocument.Bookmarks.get_Item(ref objBookMark).Range.Paste();
            }
        }

Important information

You need to add a COM reference to your favorite word object library which should in turn add

Related Posts
Categories: .NET

Sending email through C#.net

December 9, 2008 Leave a comment

Module: CEmailManager
Calling function:

public static bool SendDummyEmail()
{
   return SendEmail(CGlobalParams.AdminEmail, "dummy", "Hi");
}

Worker function:
private static bool SendEmail(string p_strTo, string p_strSubject, string p_strBody)
{
   try
   {
      MailMessage objMessage = new MailMessage();

      string[] lstRecipient = p_strTo.Split(',');
      foreach (string strTo in lstRecipient)
      {
          objMessage.To.Add(strTo);
      }

      objMessage.From = new MailAddress(CGlobalParams.SMTPUser, CGlobalParams.EmailSenderDisplay);
      objMessage.Subject = p_strSubject;
      objMessage.Body = p_strBody;

      SmtpClient objClient = new SmtpClient(CGlobalParams.SMTPServer, CGlobalParams.SMTPPort);
      objClient.UseDefaultCredentials = false;
      objClient.Credentials = new System.Net.NetworkCredential(CGlobalParams.SMTPUser, CGlobalParams.SMTPPassword);
      objClient.DeliveryMethod = SmtpDeliveryMethod.Network;

      if (CGlobalParams.SMTPRequireSSL)
      {
          objClient.EnableSsl = true;
      }

      objClient.Send(objMessage);

      return true;
   }
   catch
   {
     return false;
   }
}

Where

CGlobalParams: A class responsible for reading values for global parameters

Global parameters used here:

SMTPPassword    : somevalue
SMTPPort   : 587
SMTPRequireSSL    : true
SMTPServer    : smtp.gmail.com
SMTPUser    : jyotsnas@philogy.com

With currently set global parameters, the code sends email with gmail/ google apps over SSL. Setting the SMTPRequireSSL to false, will make the code send email with SMTP server which requires authentication but not SSL.

Categories: .NET

To remember: .net web app deployment

December 6, 2008 Leave a comment

Problem:
While creating an installer for a .net web application, we usually follow a practice of adding a web deployment project and then adding the pre-compiled web output to a web setup project. An observation is that the precompiled web output contains project files, version control system files if any and debug symbols as well.

Solution:
Find a way to remove the files from precompiled web output. How: Open the web deployment project file and add following so that ItemGroup section looks like following. This example is considering SVN as a version control system.


								
Categories: .NET
Follow

Get every new post delivered to your Inbox.