Monday, February 24, 2014

“The linked image cannot be displayed, the file may have been moved, renamed or deleted. Verify that the link points to the correct file or location” – Microsoft Word 2010.


“The linked image cannot be displayed, the file may have been moved, renamed or deleted. Verify that the link points to the correct file or location” – Microsoft Word 2010.

Problem Statement:-

Recently I have migrated our word document automation from Word 2007 to Word 2010. I have found that image below error message in place of image.












In our automation I just insert the html file into Word Document by using the below code.

this.wordDocument.Application.Selection.InsertFile(strpath, ref this.missingValue, 
                        ref this.objFalse, ref this.objFalse, ref this.objFalse);

Which works fine in Word 2007, but not in Word 2010. In the html file we have absolute path to image and after html file inserted into Word document, I delete the original file. Means word remove the links to external file and saves the image in document file itself as it does for insert of normal image file(like *.bmp, *.JPEG,…etc) below.

InlineShape picture = this.wordDocument.Application.Selection.InlineShapes.AddPicture(
                path, ref this.objTrue, ref this.objTrue, ref this.missingValue);

Here is the change in Word 2010, which retains the links to external image instead of saving them into document as it does for adding of inline normal image. (One of the reason by guess why Word 2010 does retain the original image file link could be Word not able to confirm as image file of extension because our  file doesn’t have proper image extension like *.bmp, *.JPEG…etc). Because have deleted the original image file after insertion into Word document…it couldn’t able to find the file. So above message will be displayed.


Solution:-
After spend almost two to three days goggling and doing the trial and error, finally contacted the Microsoft support. Support team really very good with technical knowledge about the product.
After careful examination in the macro editor about how many external links the document holds currently and found that it has all the external file as inserted.


Same can be viewed in File->Info->Related documents ->Edit links to file in the  lower right corner in below.














Click the Edit links to file will open up below dialog, which will have all the external file links and type of file and options for document links…etc.












we have found that still it’s pointing to links which got deleted it. So we decided to delete the links yourself automatically in our automation before deleting the original file and works perfectly in both Word 2007 and Word 2010.

Below is the code which remove the external file links automatically in c#

if (this.wordDocument.Application.Selection != null)
            {
                if (this.wordDocument.Application.ActiveDocument.InlineShapes.Count > 0)
                {
                    foreach (InlineShape inlineShape in this.wordDocument.Application.ActiveDocument.InlineShapes)
                    {
                        if (inlineShape.LinkFormat != null && !inlineShape.LinkFormat.SavePictureWithDocument)
                        {
                            inlineShape.LinkFormat.SavePictureWithDocument = true;
                            inlineShape.LinkFormat.BreakLink();
                        }
                    }
                }
            }

Before finally saving the document just remove the links which are “SavePictureWithDocument” flag false. Means which just image file inside the html document not as just inline image, anyway which is working fine and Word intelligently add them as “SavePictureWithDocument” flag set in the “options for documents links” options.

Microsoft support team really helped us their timely response to release the product on time without any delay.

I thought of share the knowledge as it would save someone two days of effort as have spend it already.

Please post the comments if anyone required any more information.








Wednesday, September 4, 2013

Clean up the databses of SQL Server Instance

Hi All,

I had requirement to clean up the SQL Server instance's database of old installation before the new installation. which I have spent almost of 2 hours for exploring the internet to find out there is any script which I can run in setup before attach of new db into the SQL instance. Finally I have found the very good post

http://rdineshkumar.wordpress.com/2011/12/17/t-sql-how-to-drop-all-databases-in-sql-server/

which clean the SQL instance of user database but it had problem which i have corrected and works fine.

Below is the SQL script.

DECLARE @sql NVARCHAR (max)
DECLARE @DBname VARCHAR (50)
DECLARE DBS CURSOR FOR
SELECT name
FROM   sys.databases
WHERE  name NOT IN ( 'model', 'tempdb', 'master', 'model',
'reportserver', 'ReportServerDB', 'msdb', 'mssecurity')
OPEN DBS
FETCH next FROM DBS INTO @DBname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'DROP DATABASE ' + '"' + @DBname + '"'
PRINT @sql
EXECUTE sp_executesql @sql
FETCH next FROM DBS INTO @DBname
END
CLOSE DBS
DEALLOCATE DBS


Feel free to contact me for any problem with the script.

Digest of Design Patterns

I have started learning design pattern in real scenario of use. which will helps to realize how the design pattern works and solves our very complex problems in object oriented way.

There are three categories of design patterns
1) Creational
2) Structural
3) Behavioral

I have started with AbstractFactory pattern of creational categories.

Wednesday, March 28, 2012

Behind Factory Pattern

Hi All,

I just realized that below are advantage and principal behind the Factory Pattern.

1) OCP principal will be satisfied for business object for extension without modifying the client code.
2) Client no need to aware of complex construction of business object
3) Make decision on run time based on user input or environment value.
4) Minimal code is change is applicable in future need some change in construction process as creation is done on central location.

Please add comments for missing advantages/principals

Monday, February 13, 2012

Custom cursor in WPF

I want to show one of my toolbar icon image as cursor when user clicks on the toolbar icon...as we can achieve same in winforms very easier but in WPF cursor object is defined in System.Windows.Input.Cursor instead of System.Windows.Forms.Cursor with restricted the constructor parameters to avoid old GDI objects.

 I have spent almost 2 to 3 hours searching in internet and finally got an way to achieve the same. so i want share with so that it will save some of you valuable hours.

Below is the exact code

 IntPtr curPtr = Properties.Resources.moveMode.GetHicon();
            Microsoft.Win32.SafeHandles.SafeFileHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(curPtr, true);           
DrawingSurface.Cursor = System.Windows.Interop.CursorInteropHelper.Create(handle);

Properties.Resources.moveMode - Bitmap icon from my project resource file which i have used in toolbar icon so want to use the same icon for cursor also.

Rest of the code can be easily understandable we have to use the SafeFileHandle which is used to represents a wrapper class for a file handle and Interop CursorInteropHelper class to convery the bitmap handle into cursor...it's definition defined in MSDN below.

"Provides a static helper class for WPF/Win32 interoperation with one method, which is used to obtain a Windows Presentation Foundation (WPF) Cursor object based on a provided Win32 cursor handle."











Sunday, December 11, 2011

Difference Between SQL Functions and Stored Procedure


StoredProcedure Functions


StoredProcedure has out parameter Functions doesn't have any out parameter
It will return value datatype must be integer It will return value as any datatype
including the user defined datatype
except BLOB, cursor and time stamps
Return value is used as indication whether
execution was success or failure
Unlike stored procedure return value
is to serve a meaningful piece of data
Return value can't used directly in query,
 it has to be stored somewhere before
it's used in query
Return value can be used directly in
query as result.
Stored Procedure will return scalar value Storedprocedure will return scalar value as table



Thursday, October 13, 2011

Difference between ASP.NET Web Service and WCF

"width: 284pt;" width="378">

WCF 

ASP.Net Web Service
Data Representation

DataContractSerialier

XMLSerializer

very precise control over how a type is represented in XML

very little control over how a type is represented in XML

Not much control over the type serialization process becomes highly predictable for the DataContractSerializer, and, thereby, easier to optimize A practical benefit of the design of the DataContractSerializer
 is better performance, approximately ten percent better
performance.

DataMemberAttribute for use with the DataContractSerializer shows explicitly which fields or properties are serialized

We can't specify which fields or properties of the type are  serialized into XML

the DataContractSerializer can translate the members of
objects into XML regardless of the access modifiers of those members.

The XmlSerializer can only translate the public members
of a .NET object into XML

the DataContractSerializer has fewer restrictions on the
variety of .NET types that it can serialize into XML.
In particular, it can translate into XML types
like
Hashtable that implement the IDictionary interface

Classes that implement the IDictionary interface, such as
Hashtable, cannot be serialized into XML.
Hosting

the service file have .svc extension

#@ServiceHost

IIS, WAS, .NET application

the service file have .ASMX extension

#@WebService

IIS


Client development

servicemodel metadata utility tool (svcutil.exe)

Web service definition language (WSDL.exe)


Message Representation

SOAP message can be customized by MessageHeader,
MessageContract, MessageBodyMember

SOAP message can be customized by SoapHeader,
SOAPheaderAttribute


Service Description

WSDL generation of WCF can be customized not generate
instead use existing static WSDL itself

WSDL generation of ASP.NET can't be customized not generate 


Exception Handling

In WCF services, unhandled exceptions are not returned
to clients as SOAP faults to prevent sensitive information being inadvertently exposed through the exceptions.

In ASP.NET Web services, unhandled exceptions are
returned to clients as SOAP fault


State Management

The WCF provides extensible objects for state management.
 Extensible objects are objects that implement
IExtensibleObject. The most important extensible objects
are ServiceHostBase and InstanceContext. ServiceHostBase
 allows you to maintain state that all of the instances of all
 of the service types on the same host can access, while
InstanceContext allows you to maintain state that can
be accessed by any code running within the same
instance of a service type.

ASP.NET provides considerable control over where the
session state information accessed by using the Session
property of the HttpContext is actually stored.
It may be stored in cookies, in a database, in the memory
of the current server, or in the memory of a designated
server. The choice is made in the service’s configuration file.


Globalization

The WCF does not support that configuration setting
except in ASP.NET compatibility mode.
To localize a WCF service that does not use ASP.NET compatibility mode, compile the service type into culture-specific assemblies, and have separate culture-specific endpoints for each culture-specific assembly. 

The ASP.NET configuration language allows you to specify
the culture for individual services









Saturday, August 27, 2011

LINQ to SQL


LINQ – Language integrated query
It’s allows the programmer to express query behavior in their programming language of choice. It provide type safety and compile time valuation of expression.
LINQ supports three data source objects, XML and databases.
LINQ to SQL allows to represent the database objects in .Net classes, you can query the database as well as update/delete/insert the data.
It supports views, stored procedure and transactions, allows the integration validation logic into data model.
DataContext Class
For each LINQ to SQL class, there will be custom datacontext class will be generated. Properties will be added for each table and stored procedure we added into LINQ to SQL design surface.Datacontext is main conduit from which we query our entities from database.

            //Connnection to database.
            AdventureWorksDataContext db = new AdventureWorksDataContext();

            //Query the datamodel through query.
            var query = from p in db.Products
                        select p;

            //Result of query
            this.grid.datasource = query;

            //Update/insert/delete change into database.
            db.SubmitChanges();

Summary

LINQ to SQL provides a nice, clean way to model the data layer of your application.Once you've defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it. 

Wednesday, July 6, 2011

LINQ-Language INtegrated Query

LINQ-Language integrated Query, new language library which can be used to Query the Implementation of interface's IEnumerable, List, T[], HashSet.

Normally LINQ methods are supplied with Lambas expression, Anonymous methods and normal methods.

LINQ methods are classified into Different category.

  • Chiaining – (Where, Select)
  • Combine and Reduce – (Concat, Distinct, Union)
  • First and Match – (First , FirstOrDefault)
  • Other and Match – (Last, ElementAt, Single)
  • Set – (Except, Intersect, Union)
  • Membership and Count – (Contains, Count)
  • Aggregate – (Sum, Avarage, Min, Max, Aggregate)
  • Grouping – (GroupBy)
  • Ordering – (OrderBy, OrderByDescending, ThenBy, ThenBydescending)
  • Export – (ToArray, ToList, ToDictionary, ToLookup)
For more information on MSDN - http://msdn.microsoft.com/en-us/netframework/aa904594

Sunday, March 6, 2011

SQL Server 2008 Joins

Joining is basic functionality of SQL Server to get the results combine of more than one table. There are three types of joinings
1) CROSS JOIN
CROSS JOIN is Cartesian product of both table records.
i) SELF JOIN
SELF JOIN is Cartesian product of same table records.
2) INNER JOIN
INNER JOIN is Cartesian product + Filter predicate on ON
i) COMPOSITE JOIN
COMPOSITE JOIN is Cartesian product + Filter predicate on more than on attribute on joins tables
ii) NON-EQU JOIN
NON-EQU JOIN is Cartesian product + Filter predicate on ON with not equal operator
iii) MULTI TABLE JOIN
MULTI TABLE JOIN is Cartesian product + Filter predicate on ON with more than one table and joining applies from left to right direction.
3) OUTER JOIN
OUTER JOIN is Cartesian product + Filter predicate on ON + Add outer rows(Rows from preserved table)
i) LEFT OUTER JOIN
LEFT OUTER JOIN is Cartesian product + Filter predicate on ON + Add outer rows(Rows from LEFT preserved table)
ii) RIGHT OUTER JOIN
RIGHT OUTER JOIN is Cartesian product + Filter predicate on ON + Add outer rows(Rows from RIGHT preserved table)
iii) FULL OUTER JOIN
FULL OUTER JOIN is Cartesian product + Filter predicate on ON + Add outer rows(Rows from BOTH preserved table)

Write what you want to say about this article.

Monday, December 22, 2008

Read AssemblyInfo file in runtime

Sometime we need to read the information which is there in the assemblyinfo.cs file for about formbox. I googled in internet, finally found an answer.

Assembly currentAssembly = Assembly.GetExecutingAssembly();

AssemblyName assemblyName = currentAssembly.GetName();

//If only need version information then use.
assemblyName.Version.ToString();

//Copyright information
AssemblyCopyrightAttribute copyright =
AssemblyCopyrightAttribute.GetCustomAttribute(currentAssembly,
typeof(AssemblyCopyrightAttribute)) as AssemblyCopyrightAttribute;

like this you can get all the attribute information from assemblyinfo.cs file.

AssemblyVersionAttribute
AssemblyProductAttribute
AssemblyDescriptionAttribute
AssemblyCompanyAttribute
AssemblyTitleAttribute

If you need any more information feel free contact me at any time.

Sunday, December 21, 2008

Checkable group box

Some days ago, i have requirement to design the UI in such way that it should contains group box and chack box on top it. so i thought it's very simple somebody might have done it. i searched on internet, i couldn't find a control. so i decided to create a control which will contains check box on the top corner of group box. It has features like ordinary checkbox if click on checkbox then automatically disable/enable the controls within the group box. if you want some action should be performed while clicking on groupbox then subscribe of for checkbox click event also.

Because of blog file upload constrains i am not able upload file here. but i am telling the steps which needs to be done and code.

1) Implement a Groupbox control
2)Override paint event for drawing of checkbox
3)Override mouse down event for changing the status of check box.

Here my control code.
------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Windows.Forms.VisualStyles;
namespace WindowsApplication
{
public class CheckableGroupBox : GroupBox
{
#region Fields
private bool checkedStatus = false;
private string text = "CheckGroupBox";
private Color textColor = Color.Blue;
#endregion
#region Constructor
public CheckableGroupBox()
{
this.SetStyle(ControlStyles.UserPaint ControlStyles.AllPaintingInWmPaint, true);
}
#endregion
#region Properties
public bool Checked
{
get { return this.checkedStatus; }
set
{
this.checkedStatus = value;
foreach (Control ctrl in this.Controls)
{
ctrl.Enabled = value;
}
}
}
public new string Text
{
get { return this.text; }
set { this.text = value; }
}
public Color TextColor
{
get { return this.textColor; }
set { this.textColor = value; }
}
#endregion
#region Events
public event EventHandler CheckStateChanged;
#endregion
#region Protected Methods
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
float totalLength = e.ClipRectangle.Right - e.ClipRectangle.Left;
float quaterLength = ((totalLength / 2) / 4);
int startPoint = (int)(e.ClipRectangle.Left + quaterLength);
Rectangle rectAngle = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y - 1,
e.ClipRectangle.Width, e.ClipRectangle.Height);
rectAngle.X = startPoint + CheckBoxRenderer.GetGlyphSize(e.Graphics,
CheckBoxState.UncheckedNormal).Width;
SizeF sizeF = e.Graphics.MeasureString(Text, this.Font);
rectAngle.Width = (int)sizeF.Width + 2;
rectAngle.Height = this.Font.Height;
CheckBoxRenderer.RenderMatchingApplicationState = true;
Rectangle rectAngleBack = new Rectangle(startPoint - 3, rectAngle.Y,
(rectAngle.X - (startPoint - 3)) + rectAngle.Width, rectAngle.Height);
CheckBoxRenderer.DrawParentBackground(e.Graphics, rectAngleBack, this);
Font font = Font;
CheckBoxRenderer.DrawCheckBox(e.Graphics, new System.Drawing.Point(startPoint, e.ClipRectangle.Y),
rectAngle, Text, this.Font, TextFormatFlags.VerticalCenter, false,
checkedStatus ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
using (Graphics g = this.CreateGraphics())
{
Rectangle rectAngle = ClientRectangle;
rectAngle.X = ClientRectangle.Left + (((ClientRectangle.Right - ClientRectangle.Left) / 2) / 4);
rectAngle.Y -= 1;
rectAngle.Width = CheckBoxRenderer.GetGlyphSize(g, checkedStatus ?
CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal).Width;
rectAngle.Height = CheckBoxRenderer.GetGlyphSize(g, checkedStatus ?
CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal).Height;
if (rectAngle.Contains(e.Location))
{
Checked = !Checked;
if (CheckStateChanged != null)
{
CheckStateChanged(this, new EventArgs());
}
}
}
Invalidate();
}
}
#endregion
}
}
------------------------------------------------------------------------------------------------
Just create c# file and copy paste above code, compile and use it in your application.

Feel free contact me if you need any more information and also i am very glad accept your suggestion.