Creating MleaderStyle Autocad using C# - c#

I have created MleaderStyle in C#.There was no error,but while i run it i get following error.Here is part of my code use for this purpose and error that is displayed by autocad.
MLeaderStyle dst =
(MLeaderStyle)acTrans.GetObject(
acCurDb.DimStyleTableId,
OpenMode.ForWrite);
MText mt = new MText();
mt.Contents = text;
dst.Name = " My LeaderStyle";
dst.ArrowSymbolId = ObjectId.Null;
dst.ArrowSize = 0.18 * scale;
dst.ContentType = 0;
dst.DefaultMText = mt;
dst.LandingGap = gap;
dst.EnableBlockRotation = true;
dst.MaxLeaderSegmentsPoints = 2;
//dst1.Add(dst);
acTrans.AddNewlyCreatedDBObject(dst, true);
MLeader lead = new MLeader();
int i= lead.AddLeader();
lead.AddLeaderLine(i);
lead.AddFirstVertex(i, start);
lead.AddLastVertex(i, end);
lead.MLeaderStyle = dst.ObjectId;
Error;
Unable to cast object of type
'Autodesk.Autocad.DataBaseServices.DimStyleTable'to 'Autodesk.AutoCad.DataBaseServices.MleaderStyle'

MLeaderStyle dst = (MLeaderStyle)acTrans.GetObject(
acCurDb.DimStyleTableId, OpenMode.ForWrite);
You cannot cast the DimStyleTable into a MLeaderStyle, you have to use one of the MLeaderStyle constructors to create a new one.
using (var tr = db.TransactionManager.StartTransaction())
{
// the newly created MText have to be disposed after using
using (MText mt = new MText())
{
mt.Contents = text;
// check if the MLeaderStyle dictionary does not already contains a style named "MyLeaderStyle"
DBDictionary mlStyles = (DBDictionary)tr.GetObject(db.MLeaderStyleDictionaryId, OpenMode.ForWrite);
if (!mlStyles.Contains("MyLeaderStyle"))
{
// create a new instance of MLeaderStyle (you can use the overloaded ctor to copy an existing style)
MLeaderStyle dst = new MLeaderStyle();
dst.ArrowSymbolId = ObjectId.Null;
dst.ArrowSize = 0.18 * scale;
dst.ContentType = 0;
dst.DefaultMText = mt;
dst.LandingGap = gap;
dst.EnableBlockRotation = true;
dst.MaxLeaderSegmentsPoints = 2;
// add the new MLeaderStyle to the database
dst.PostMLeaderStyleToDb(db, "MyLeaderStyle");
tr.AddNewlyCreatedDBObject(dst, true);
}
}
tr.Commit();
}

Related

Passing multiple line items with GP webservice

Below is the code I'm working with to pass multiple line items to create sales order through GP Web service. I can pass single Line Item without any problem , but when I pass multiple Items it is only taking the last one. The array has around 5 Item ID and I'm passing fixed Quantity as 15, Need to make both dynamic. But for the testing purpose I'm trying like this. I know the problem with the creation/initialization of some web service objects. As novice to the entire set of things I couldn't find the exact problem.
C# Code
CompanyKey companyKey;
Context context;
SalesOrder salesOrder;
SalesDocumentTypeKey salesOrderType;
CustomerKey customerKey;
BatchKey batchKey;
// SalesOrderLine salesOrderLine;
ItemKey orderedItem;
Quantity orderedAmount;
Policy salesOrderCreatePolicy;
DynamicsGPClient wsDynamicsGP = new DynamicsGPClient();
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.UserName = "Admin";
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.Password = "pass";
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.Domain = "Gp";
System.ServiceModel.WSHttpBinding binding;
binding = new System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None);
context = new Context();
companyKey = new CompanyKey();
companyKey.Id = (1);
context.OrganizationKey = (OrganizationKey)companyKey;
salesOrder = new SalesOrder();
salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
salesOrder.DocumentTypeKey = salesOrderType;
customerKey = new CustomerKey();
customerKey.Id = "121001";
salesOrder.CustomerKey = customerKey;
batchKey = new BatchKey();
batchKey.Id = "RMS";
salesOrder.BatchKey = batchKey;
// SalesOrderLine[] orders = new SalesOrderLine[6];
SalesOrderLine[] lines = { };
for (int i = 1; i < 5; i++)
{
SalesOrderLine salesOrderLine = new SalesOrderLine();
orderedItem = new ItemKey();
orderedItem.Id = Arr[i].ToString();
salesOrderLine.ItemKey = orderedItem;
orderedAmount = new Quantity();
orderedAmount.Value = 15;
salesOrderLine.Quantity = orderedAmount;
lines = new SalesOrderLine[] { salesOrderLine };
MessageBox.Show(lines.Count().ToString());
}
salesOrder.Lines = lines;
//salesOrder.Lines = orders;
salesOrderCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
wsDynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
if (wsDynamicsGP.State != CommunicationState.Faulted)
{
wsDynamicsGP.Close();
}
MessageBox.Show("Success");
lines = new SalesOrderLine[] { salesOrderLine }; will recreate the lines array object each time meaning you loose any previously added objects. Effectively only the final object in the loop is actually added.
Try using a List<T> like so:
SalesOrderLine[] lines = { }; Becomes List<SalesOrderLine> lines = new List<SalesOrderLine>();
lines = new SalesOrderLine[] { salesOrderLine }; Becomes: lines.Add(salesOrderLine);
If its important you end up with an array as the input:
salesOrder.Lines = lines; Becomes: salesOrder.Lines = lines.ToArray();

How to determine the coordinatesystem of a shapefile set with ShapefileDataReader

I have the following code to read a shapefile set (.dbf, .prj, .shp, .shx) with the NetTopologySuite.IO.ShapefileDataReader:
public FeatureCollection ReadShapeFile(string localShapeFile)
{
var collection = new FeatureCollection();
var factory = new GeometryFactory();
using (var reader = new ShapefileDataReader(localShapeFile, factory))
{
var header = reader.DbaseHeader;
while (reader.Read())
{
var f = new Feature {Geometry = reader.Geometry};
var attrs = new AttributesTable();
for (var i = 0; i < header.NumFields; i++)
{
attrs.AddAttribute(header.Fields[i].Name, reader.GetValue(i));
}
f.Attributes = attrs;
collection.Add(f);
}
}
return collection;
}
This works, but the geometry objects don't have a property to tell which reference system the coordinates are in.
How can I find out which coordinate system / reference system the shape file or individual shapes are in?
The projection is not available in the .shp file, but in the .prj file, and can be loaded separately:
var projectionFile = Path.Combine(Path.GetDirectoryName(localShapeFile), Path.GetFileNameWithoutExtension(localShapeFile) + ".prj");
var projectionInfo = ProjectionInfo.Open(projectionFile);

Open XML Table Generation Using Generic List

I have written a method to insert a table in a word document using Open XML. The method accepts a generic list and a few parameters to control number of columns, column headings etc.
That all works fine.
However when populating the cells in the table I want to pull out the values for each row and place them in their corresponding columns. Given the names of the properties are going to change depending on the contents of the generic list, I am not sure how to accomplish this.
Anyone that can point me in the right direction it would be appreciated.
void InsertTable<T>(List<T> tableData, int[] tableHeadingCount, string[] columnHeadings, string locationInDocument)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(_newDocument, true))
{
var docPart = myDoc.MainDocumentPart;
var doc = docPart.Document;
var table = new Table();
var tableBorderTop = new TopBorder();
var tableBorderBottom = new BottomBorder();
var tableBorderLeft = new LeftBorder();
var tableBorderRight = new RightBorder();
var tableBorderHorizontal = new InsideHorizontalBorder();
var tableBorderVertical = new InsideVerticalBorder();
var tableProperties = new TableProperties();
var borders = new TableBorders();
// Set Border Styles for Table
tableBorderTop.Val = BorderValues.Single;
tableBorderTop.Size = 6;
tableBorderBottom.Val = BorderValues.Single;
tableBorderBottom.Size = 6;
tableBorderLeft.Val = BorderValues.Single;
tableBorderLeft.Size = 6;
tableBorderRight.Val = BorderValues.Single;
tableBorderRight.Size = 6;
tableBorderHorizontal.Val = BorderValues.Single;
tableBorderHorizontal.Size = 6;
tableBorderVertical.Val = BorderValues.Single;
tableBorderVertical.Size = 6;
// Assign Border Styles to Table Borders
borders.TopBorder = tableBorderTop;
borders.BottomBorder = tableBorderBottom;
borders.LeftBorder = tableBorderLeft;
borders.RightBorder = tableBorderRight;
borders.InsideHorizontalBorder = tableBorderHorizontal;
borders.InsideVerticalBorder = tableBorderVertical;
// Append Border Styles to Table Properties
tableProperties.Append(borders);
// Assign Table Properties to Table
table.Append(tableProperties);
var tableRowHeader = new TableRow();
tableRowHeader.Append(new TableRowHeight() { Val = 2000 });
for (int i = 0; i < tableHeadingCount.Length; i++)
{
var tableCellHeader = new TableCell();
//Assign Font Properties to Run
var runPropHeader = new RunProperties();
runPropHeader.Append(new Bold());
runPropHeader.Append(new Color() { Val = "000000" });
//Create New Run
var runHeader = new Run();
//Assign Font Properties to Run
runHeader.Append(runPropHeader);
var columnHeader = new Text();
//Assign the Pay Rule Name to the Run
columnHeader = new Text(columnHeadings[i]);
runHeader.Append(columnHeader);
//Create Properties for Paragraph
var justificationHeader = new Justification();
justificationHeader.Val = JustificationValues.Left;
var paraPropsHeader = new ParagraphProperties(justificationHeader);
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
paraPropsHeader.Append(spacing);
var paragraphHeader = new Paragraph();
paragraphHeader.Append(paraPropsHeader);
paragraphHeader.Append(runHeader);
tableCellHeader.Append(paragraphHeader);
var tableCellPropertiesHeader = new TableCellProperties();
var tableCellWidthHeader = new TableCellWidth();
tableCellPropertiesHeader.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "#C0C0C0" });
var textDirectionHeader = new TextDirection();
textDirectionHeader.Val = TextDirectionValues.BottomToTopLeftToRight;
tableCellPropertiesHeader.Append(textDirectionHeader);
tableCellWidthHeader.Type = TableWidthUnitValues.Dxa;
tableCellWidthHeader.Width = "2000";
tableCellPropertiesHeader.Append(tableCellWidthHeader);
tableCellHeader.Append(tableCellPropertiesHeader);
tableRowHeader.Append(tableCellHeader);
}
tableRowHeader.AppendChild(new TableHeader());
table.Append(tableRowHeader);
//Create New Row in Table for Each Record
foreach (var record in tableData)
{
var tableRow = new TableRow();
for (int i = 0; i < tableHeadingCount.Length; i++)
{
//**** This is where I dynamically want to iterate through selected properties and output the value ****
var propertyText = "Test";
var tableCell = new TableCell();
//Assign Font Properties to Run
var runProp = new RunProperties();
runProp.Append(new Bold());
runProp.Append(new Color() { Val = "000000" });
//Create New Run
var run = new Run();
//Assign Font Properties to Run
run.Append(runProp);
//Assign the text to the Run
var text = new Text(propertyText);
run.Append(text);
//Create Properties for Paragraph
var justification = new Justification();
justification.Val = JustificationValues.Left;
var paraProps = new ParagraphProperties(justification);
var paragraph = new Paragraph();
paragraph.Append(paraProps);
paragraph.Append(run);
tableCell.Append(paragraph);
var tableCellProperties = new TableCellProperties();
var tableCellWidth = new TableCellWidth();
tableCellWidth.Type = TableWidthUnitValues.Dxa;
tableCellWidth.Width = "2000";
tableCellProperties.Append(tableCellWidth);
tableCell.Append(tableCellProperties);
tableRow.Append(tableCell);
}
table.Append(tableRow);
}
var res = from bm in docPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == locationInDocument
select bm;
var bookmark = res.SingleOrDefault();
var parent = bookmark.Parent; // bookmark's parent element
Paragraph newParagraph = new Paragraph();
parent.InsertAfterSelf(newParagraph);
if (bookmark != null)
{
newParagraph.InsertBeforeSelf(table);
}
}
}
I resolved this issue by tackling the problem another way. Essentially rather than passing a List to the Insert Table Method. I decided to Pass a Multi-Dimensional Array with all the data need for the table including the table headings. This essentially meant that the Insert Table method would be more generic and any customization i.e. Generating Data, Specifying Column Headings etc would be done in the Method calling Insert Table.

Insert an image into a .docx file

I am developing a program that has the feature to dynamically create DocX files. As the title suggests, I am having a problem inserting images into a DocX file. One of the issues, as I see it, is that I am using C# 2.0. (When answering this question, I would like to stress that I do not wish to switch to C# 3.0, so please do not try to persuade me.)
I have taken a look at the MSDN article at http://msdn.microsoft.com/en-us/library/office/bb497430.aspx, but when I converted the C# 3.0 code that MSDN uses to C# 2.0, I get a document that does not open, and it gives me the error: "The file Testing.docx cannot be opened because there are problems with the contents," and "No error detail available."
Here is my code:
ImagePart ip_Part;
WordprocessingDocument wpd_Doc = WordprocessingDocument.Create("C:\\Convert\\Testing.docx", WordprocessingDocumentType.Document);
public Testing()
{
wpd_Doc.AddMainDocumentPart();
wpd_Doc.MainDocumentPart.Document = new Document();
wpd_Doc.MainDocumentPart.Document.Body = new Body();
ip_Part = wpd_Doc.MainDocumentPart.AddImagePart(ImagePartType.Png);
System.IO.FileStream fs_Stream = new System.IO.FileStream("image.png", System.IO.FileMode.Open);
ip_Part.FeedData(fs_Stream);
AddImageToBody("image.png", wpd_Doc.MainDocumentPart.GetIdOfPart(ip_Part));
AppendText("Here is a test bulleted list:");
wpd_Doc.MainDocumentPart.Document.Save();
//Close the document.
wpd_Doc.Close();
}
private void AddImageToBody(string s_ImagePath, string s_RelationshipId)
{
//OpenXmlElement oxe_Element = new Numbering();
Drawing d_Drawing = new Drawing();
DrawWord.Inline i_Inline = new DrawWord.Inline();
DrawWord.Extent e_Extent = new DrawWord.Extent();
e_Extent.Cx = 600075; //63px / 96dpi * 914400
e_Extent.Cy = 600075; //63px / 96dpi * 914400
i_Inline.Extent = e_Extent;
DrawWord.DocProperties dp_Prop = new DrawWord.DocProperties();
//dp_Prop.Id = uint.Parse(System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
dp_Prop.Id = 1;
dp_Prop.Name = "Picture 1";
dp_Prop.Description = "An automated image.";
i_Inline.DocProperties = dp_Prop;
DrawWord.NonVisualGraphicFrameDrawingProperties nvgfdp_Prop = new DrawWord.NonVisualGraphicFrameDrawingProperties();
Draw.GraphicFrameLocks gfl_Locks = new Draw.GraphicFrameLocks();
gfl_Locks.NoChangeAspect = true;
nvgfdp_Prop.GraphicFrameLocks = gfl_Locks;
i_Inline.NonVisualGraphicFrameDrawingProperties = nvgfdp_Prop;
Draw.Graphic g_Graphic = new Draw.Graphic();
Draw.GraphicData gd_Data = new DocumentFormat.OpenXml.Drawing.GraphicData();
gd_Data.Uri = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
DrawPic.Picture p_Pic = new DrawPic.Picture();
DrawPic.NonVisualPictureProperties nvpp_Prop = new DrawPic.NonVisualPictureProperties();
DrawPic.NonVisualDrawingProperties nvdp_Prop = new DrawPic.NonVisualDrawingProperties();
nvdp_Prop.Id = uint.Parse(System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
//nvdp_Prop.Name = s_ImagePath;
nvdp_Prop.Name = "New_Image.png";
nvpp_Prop.NonVisualDrawingProperties = nvdp_Prop;
DrawPic.NonVisualPictureDrawingProperties nvpdp_Prop = new DrawPic.NonVisualPictureDrawingProperties();
nvpp_Prop.NonVisualPictureDrawingProperties = nvpdp_Prop;
p_Pic.NonVisualPictureProperties = nvpp_Prop;
DrawPic.BlipFill bf_Fill = new DrawPic.BlipFill();
Draw.Blip b_Blip = new Draw.Blip();
Draw.ExtensionList el_List = new Draw.ExtensionList();
Draw.BlipExtension be_Extension = new Draw.BlipExtension();
be_Extension.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}";
el_List.Append(be_Extension);
b_Blip.Append(el_List);
b_Blip.Embed = s_RelationshipId;
b_Blip.CompressionState = Draw.BlipCompressionValues.Print;
bf_Fill.Blip = b_Blip;
Draw.Stretch s_Stretch = new Draw.Stretch();
Draw.FillRectangle fr_Rect = new Draw.FillRectangle();
s_Stretch.FillRectangle = fr_Rect;
bf_Fill.Append(s_Stretch);
p_Pic.BlipFill = bf_Fill;
DrawPic.ShapeProperties sp_Prop = new DrawPic.ShapeProperties();
Draw.Transform2D t2d_Transform = new Draw.Transform2D();
Draw.Offset o_Offset = new Draw.Offset();
o_Offset.X = 0;
o_Offset.Y = 0;
t2d_Transform.Offset = o_Offset;
Draw.Extents e_Extents = new Draw.Extents();
e_Extents.Cx = 600075; //63px / 96dpi * 914400
e_Extents.Cy = 600075; //63px / 96dpi * 914400
t2d_Transform.Extents = e_Extents;
sp_Prop.Transform2D = t2d_Transform;
Draw.PresetGeometry pg_Geom = new Draw.PresetGeometry();
Draw.AdjustValueList avl_List = new Draw.AdjustValueList();
pg_Geom.AdjustValueList = avl_List;
pg_Geom.Preset = Draw.ShapeTypeValues.Rectangle;
sp_Prop.Append(pg_Geom);
p_Pic.ShapeProperties = sp_Prop;
gd_Data.Append(p_Pic);
g_Graphic.GraphicData = gd_Data;
i_Inline.Graphic = g_Graphic;
d_Drawing.Inline = i_Inline;
//oxe_Element.Append(d_Drawing);
//Run r_Run = new Run(d_Drawing);
wpd_Doc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(d_Drawing)));
}
(The variable names are bad, but this was just a test program, so I did not spend too much time. Also, I have the lines spaced to mimic the Xml format that MSDN had in its example. If I could use the C# 3.0 syntax, I would, but I am using Visual Studio 2005.)
I have found the answer. Surprisingly, I did not find this webpage--because it was some Google pages down with some odd keyword searching--that completely worked: http://blog.stuartwhiteford.com/?p=33. Though it is written with Collection Initializations, I was able to change them to fit C# 2.0 standards.

Using eBay SDK API: internationalShippingOptions.ShipToLocation.Add("Worldwide"); causes:"Object reference not set to an instance of an object"

My goal here so to make the listing say "Free International Shipping". Trying to set up international options and it said I need to set ShipToLocation I tried the line below:
internationalShippingOptions.ShipToLocation.Add("Worldwide");
But when the program hits it I get this error:
"Object reference not set to an instance of an object"
If you would like to see the full method it is:
static ShippingDetailsType BuildShippingDetails()
{
ShippingDetailsType sd = new ShippingDetailsType();
sd.ApplyShippingDiscount = false;
sd.ShippingType = ShippingTypeCodeType.Flat;
AmountType amount = new AmountType();
amount.Value = 0;
amount.currencyID = CurrencyCodeType.USD;
ShippingServiceOptionsTypeCollection shippingOptions = new ShippingServiceOptionsTypeCollection();
ShippingServiceOptionsType domesticShippingOptions = new ShippingServiceOptionsType();
domesticShippingOptions.ShippingService = ShippingServiceCodeType.EconomyShippingFromOutsideUS.ToString();
domesticShippingOptions.FreeShipping = true;
domesticShippingOptions.ShippingServiceCost = amount;
domesticShippingOptions.ShippingServicePriority = 1;
shippingOptions.Add(domesticShippingOptions);
ShippingServiceOptionsType internationalShippingOptions = new ShippingServiceOptionsType();
InternationalShippingServiceOptionsType internationalShippingOptions = new InternationalShippingServiceOptionsType();
internationalShippingOptions.ShippingService = ShippingServiceCodeType.StandardInternational.ToString();
internationalShippingOptions.ShipToLocation.Add("Worldwide");
internationalShippingOptions.FreeShipping = true;
sd.InternationalShippingServiceOption = new InternationalShippingServiceOptionsTypeCollection(new InternationalShippingServiceOptionsType[] { internationalShippingOptions });
sd.ShippingServiceOptions = shippingOptions;
return sd;
}
Here is the code to make it say "Free Standard Intl Shipping". At first in the sandbox it says "Free Standard Shipping" but if you change the shipping destination in the sandbox it will say "Free Standard Intl Shipping".
static ShippingDetailsType BuildShippingDetails()
{
// Shipping details
ShippingDetailsType sd = new ShippingDetailsType();
sd.ApplyShippingDiscount = true;
sd.PaymentInstructions = "eBay .Net SDK test instruction.";
sd.ShippingRateType = ShippingRateTypeCodeType.StandardList;
// Shipping type and shipping service options
//adding international shipping
InternationalShippingServiceOptionsType internationalShipping1 = new InternationalShippingServiceOptionsType();
internationalShipping1.ShippingService = ShippingServiceCodeType.StandardInternational.ToString();
internationalShipping1.ShippingServiceCost = new AmountType { Value = 0, currencyID = CurrencyCodeType.USD };
internationalShipping1.ShippingServicePriority = 1;
internationalShipping1.ShipToLocation = new StringCollection(new[] { "Worldwide" });
sd.ShippingServiceUsed = ShippingServiceCodeType.StandardInternational.ToString();
sd.InternationalShippingServiceOption = new InternationalShippingServiceOptionsTypeCollection(new[] { internationalShipping1 });
//adding domestic shipping
ShippingServiceOptionsType domesticShipping1 = new ShippingServiceOptionsType();
domesticShipping1.ShippingService = ShippingServiceCodeType.ShippingMethodStandard.ToString();
domesticShipping1.ShippingServiceCost = new AmountType { Value = 0, currencyID = CurrencyCodeType.USD };
domesticShipping1.ShippingInsuranceCost = new AmountType { Value = 0, currencyID = CurrencyCodeType.USD };
domesticShipping1.ShippingServicePriority = 4;
domesticShipping1.LocalPickup = true;
domesticShipping1.FreeShipping = true;
sd.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection(new[] { domesticShipping1 });
sd.ShippingType = ShippingTypeCodeType.Flat;
return sd;
To call the method:
item.ShippingDetails = BuildShippingDetails();

Categories

Resources