I have develop web App. I do not have office on server and want to deploy my publish folder over there.
Is Microsoft office is madatory for OWC?
If yes is there any way we can use it without excel installed?
using System.Web;
using System.IO;
using OWC11;
namespace AspNetResources.Owc
{
public partial class _default : System.Web.UI.Page
{
// ------------------------------------------------------------------
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
BuildCharts ();
}
// ------------------------------------------------------------------
private void BuildCharts ()
{
string[] chartCategoriesArr = new string [] {"Accord Coupe", "Accord Sedan", "Civic Coupe", "Civic Sedan", "Civic Si"};
string[] chartValuesArr = new string []{"19400", "15900", "13710", "13010", "19070"};
string chartCategoriesStr = String.Join ("\t", chartCategoriesArr);
string chartValuesStr = String.Join ("\t", chartValuesArr);
OWC11.ChartSpaceClass oChartSpace = new OWC11.ChartSpaceClass ();
OWC11.ChartChartTypeEnum chartType;
/*--------------------------------------------------------------
* Try using different char types just for fun
* -------------------------------------------------------------
chartType = ChartChartTypeEnum.chChartTypeArea;
chartType = ChartChartTypeEnum.chChartTypeArea3D;
chartType = ChartChartTypeEnum.chChartTypeBarClustered;
chartType = ChartChartTypeEnum.chChartTypeBar3D;
chartType = ChartChartTypeEnum.chChartTypeColumnClustered;
chartType = ChartChartTypeEnum.chChartTypeColumn3D;
chartType = ChartChartTypeEnum.chChartTypeDoughnut;
chartType = ChartChartTypeEnum.chChartTypeLineStacked;
chartType = ChartChartTypeEnum.chChartTypeLine3D;
chartType = ChartChartTypeEnum.chChartTypeLineMarkers;
chartType = ChartChartTypeEnum.chChartTypePie;
chartType = ChartChartTypeEnum.chChartTypePie3D;
chartType = ChartChartTypeEnum.chChartTypeRadarSmoothLine;
chartType = ChartChartTypeEnum.chChartTypeSmoothLine;
*/
// ------------------------------------------------------------------------
// Give pie and doughnut charts a legend on the bottom. For the rest of
// them let the control figure it out on its own.
// ------------------------------------------------------------------------
chartType = ChartChartTypeEnum.chChartTypeColumn3D;
if (chartType == ChartChartTypeEnum.chChartTypePie ||
chartType == ChartChartTypeEnum.chChartTypePie3D ||
chartType == ChartChartTypeEnum.chChartTypeDoughnut)
{
oChartSpace.HasChartSpaceLegend = true;
oChartSpace.ChartSpaceLegend.Position = ChartLegendPositionEnum.chLegendPositionBottom;
}
oChartSpace.Border.Color = "white";
oChartSpace.Charts.Add(0);
oChartSpace.Charts[0].HasTitle = true;
oChartSpace.Charts[0].Type = chartType;
oChartSpace.Charts[0].ChartDepth = 125;
oChartSpace.Charts[0].AspectRatio = 80;
oChartSpace.Charts[0].Title.Caption = "Pricing Of 2004 Hondas";
oChartSpace.Charts[0].Title.Font.Bold = true;
oChartSpace.Charts[0].SeriesCollection.Add(0);
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection.Add ();
// ------------------------------------------------------------------------
// If you're charting a pie or a variation thereof percentages make a lot
// more sense than values...
// ------------------------------------------------------------------------
if (chartType == ChartChartTypeEnum.chChartTypePie ||
chartType == ChartChartTypeEnum.chChartTypePie3D ||
chartType == ChartChartTypeEnum.chChartTypeDoughnut)
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage = true;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue = false;
}
// ------------------------------------------------------------------------
// Not so for other chart types where values have more meaning than
// percentages.
// ------------------------------------------------------------------------
else
{
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasPercentage = false;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].HasValue = true;
}
// ------------------------------------------------------------------------
// Plug your own visual bells and whistles here
// ------------------------------------------------------------------------
oChartSpace.Charts[0].SeriesCollection[0].Caption = String.Empty;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Name = "verdana";
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Size = 10;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Bold = true;
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Font.Color = "white";
oChartSpace.Charts[0].SeriesCollection[0].DataLabelsCollection[0].Position = ChartDataLabelPositionEnum.chLabelPositionCenter;
oChartSpace.Charts[0].SeriesCollection[0].SetData (OWC11.ChartDimensionsEnum.chDimCategories,
Convert.ToInt32(OWC11.ChartSpecialDataSourcesEnum.chDataLiteral), chartCategoriesStr);
oChartSpace.Charts[0].SeriesCollection[0].SetData (OWC11.ChartDimensionsEnum.chDimValues,
Convert.ToInt32(OWC11.ChartSpecialDataSourcesEnum.chDataLiteral), chartValuesStr);
// ------------------------------------------------------------------------
// Pick your favorite image format
// ------------------------------------------------------------------------
byte[] byteArr = (byte[]) oChartSpace.GetPicture ("png", 500, 500);
// ------------------------------------------------------------------------
// Store the chart image in Session to be picked up by an HttpHandler later
// ------------------------------------------------------------------------
HttpContext ctx = HttpContext.Current;
string chartID = Guid.NewGuid ().ToString ();
ctx.Session [chartID] = byteArr;
imgHondaLineup.ImageUrl = string.Concat ("chart.ashx?", chartID);
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
}
}
It gives error that
Server Error in '/owc' Application.
Could not load file or assembly 'owc' or one of its dependencies. An attempt was made to load a program with an incorrect format.
The error message means that the file owc.dll or one of it's references is missing.
Check whether the file is either:
in the bin folder of your web project (after publishing);
in the GAC (C:\windows\assembly).
If it does exist there, you can use Reflector, or similar products to see what the references of owc.dll are and you have to check those references too.
Related
I'm trying to edit a paragraph in pptx through changing its text, font size, font style and alignment.
This is what i have done so far:
**this is the method im using to call the update paragraph**
public static void Main(string[] args)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open("ppturl", true))
{
// Get the presentation part of the presentation document.
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation part and presentation exist.
if (presentationPart != null && presentationPart.Presentation != null)
{
// Get the Presentation object from the presentation part.
Presentation presentation = presentationPart.Presentation;
// Verify that the slide ID list exists.
if (presentation.SlideIdList != null)
{
SlideId sourceSlide = presentation.SlideIdList.ChildElements[0] as SlideId;
SlidePart slidePart = presentationPart.GetPartById(sourceSlide.RelationshipId) as SlidePart;
updateParagraph(slidePart);
}
}
}
Console.ReadLine();
CreateHostBuilder(args).Build().Run();
}
**Here im extracting the title in the slide because this is what i need.**
public static void updateParagraph(SlidePart slidePart)
{
if (slidePart == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slidePart.Slide != null)
{
// Find all the title shapes.
var shapes = from shape in slidePart.Slide.Descendants<Shape>()
where IsTitleShape(shape)
select shape;
foreach (P.Shape shape in shapes)
{
D.Paragraph paragraph = shape.TextBody.Elements<D.Paragraph>().FirstOrDefault();
shape.TextBody.RemoveAllChildren<D.Paragraph>();
AddNewParagraph(shape, "This is a new Slide");
}
}
}
**This is where i am trying to add a new paragraph with specific style**
public static void AddNewParagraph(this P.Shape shape, string NewText)
{
D.Paragraph p = new D.Paragraph();
P.TextBody docBody = shape.TextBody;
Justification justification1 = new Justification() { Val = JustificationValues.Center };
p.ParagraphProperties=new D.ParagraphProperties(justification1);
D.Run run = new D.Run(new D.Text(NewText));
D.RunProperties runProp = new D.RunProperties() { Language = "en-US", FontSize = 9, Dirty = false };
run.AppendChild(runProp);
D.Text newText = new D.Text(NewText);
run.AppendChild(newText);
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine(runProp.FontSize.ToString());
Console.WriteLine("--------------------------------------------------------------");
p.Append(run);
docBody.Append(p);
}
This is giving me an error whenever im trying to open the pptx "repair pptx error".
Can someone please provide a clear solution specific to pptx and not doc.?
Thankful..
You can try using Aspose.Slides for .NET. The following code example shows you how to change some paragraph properties with this library:
using (var presentation = new Presentation("example.pptx"))
{
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
var firstPortion = firstParagraph.Portions[0];
firstPortion.Text = "New text.";
firstPortion.PortionFormat.FontHeight = 24;
firstPortion.PortionFormat.FontBold = NullableBool.True;
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
presentation.Save("example.pptx", SaveFormat.Pptx);
}
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to change the paragraph settings using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var fileName = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var portionIndex = 1;
var firstPortion = slidesApi.GetPortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex);
firstPortion.Text = "New text.";
firstPortion.FontHeight = 24;
firstPortion.FontBold = Portion.FontBoldEnum.True;
slidesApi.UpdatePortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex, firstPortion);
var firstParagraph = slidesApi.GetParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex);
firstParagraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex, firstParagraph);
I work as a Support Developer at Aspose.
When I check in my website using Paypal it gives me this message: "Checkout Error - Amount total mismatch" I used Microsoft tutorial to implement PayPal:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal
I did exactly what it said I even did twice but somehow keep getting this error Appreciate your help Thanks
public partial class CheckoutReview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
NVPAPICaller payPalCaller = new NVPAPICaller();
string retMsg = "";
string token = "";
string PayerID = "";
NVPCodec decoder = new NVPCodec();
token = Session["token"].ToString();
bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
if (ret)
{
Session["payerId"] = PayerID;
var myOrder = new Order();
myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
myOrder.Username = User.Identity.Name;
myOrder.FirstName = decoder["FIRSTNAME"].ToString();
myOrder.LastName = decoder["LASTNAME"].ToString();
myOrder.Address = decoder["SHIPTOSTREET"].ToString();
myOrder.City = decoder["SHIPTOCITY"].ToString();
myOrder.State = decoder["SHIPTOSTATE"].ToString();
myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
myOrder.Country = decoder["SHIPTOCOUNTRYCODE"].ToString();
myOrder.Email = decoder["EMAIL"].ToString();
myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());
// Verify total payment amount as set on CheckoutStart.aspx.
try
{
decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
{
Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
}
}
catch (Exception)
{
Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
}
// Get DB context.
ProductContext _db = new ProductContext();
// Add order to DB.
_db.Orders.Add(myOrder);
_db.SaveChanges();
// Get the shopping cart items and process them.
using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
{
List<CartItem> myOrderList = usersShoppingCart.GetCartItems();
// Add OrderDetail information to the DB for each product purchased.
for (int i = 0; i < myOrderList.Count; i++)
{
// Create a new OrderDetail object.
var myOrderDetail = new OrderDetail();
myOrderDetail.OrderId = myOrder.OrderId;
myOrderDetail.Username = User.Identity.Name;
myOrderDetail.ProductId = myOrderList[i].ProductId;
myOrderDetail.Quantity = myOrderList[i].Quantity;
myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;
// Add OrderDetail to DB.
_db.OrderDetails.Add(myOrderDetail);
_db.SaveChanges();
}
// Set OrderId.
Session["currentOrderId"] = myOrder.OrderId;
// Display Order information.
List<Order> orderList = new List<Order>();
orderList.Add(myOrder);
ShipInfo.DataSource = orderList;
ShipInfo.DataBind();
// Display OrderDetails.
OrderItemList.DataSource = myOrderList;
OrderItemList.DataBind();
}
}
else
{
Response.Redirect("CheckoutError.aspx?" + retMsg);
}
}
}
protected void CheckoutConfirm_Click(object sender, EventArgs e)
{
Session["userCheckoutCompleted"] = "true";
Response.Redirect("~/Checkout/CheckoutComplete.aspx");
}
}
I encountered the same problem while doing the tutorial, so here is my solution in case someone encounters it as well.
The main problem here is that Asp.NET displays the string versions of the amounts as XX,XX instead of XX.XX. This is because the .ToString()-function displays decimals as they are written in the current region.
To solve this problem, every .ToString() and Convert.ToDecimal() should be called with an extra parameter called CultureInfo.InvariantCulture, which ensures that the string amounts are stored in memory in the XX.XX-format.
I hope this helps someone in the future.
According to this post, you can make Visual Studio find.
I update the code of Asif Iqbal K from the article a bit to eliminate build error.
public const string vsWindowKindFindResults1 = "{0F887920-C2B6-11D2-9375-0080C747D9A0}";
public string FindInFiles(string searchText)
{
EnvDTE80.DTE2 dte;
dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
dte.MainWindow.Activate();
EnvDTE.Find find = dte.Find;
find.Action = EnvDTE.vsFindAction.vsFindActionFindAll;
find.FindWhat = searchText;
find.MatchWholeWord = false;
find.ResultsLocation = EnvDTE.vsFindResultsLocation.vsFindResults1;
find.Target = EnvDTE.vsFindTarget.vsFindTargetSolution;
find.PatternSyntax = EnvDTE.vsFindPatternSyntax.vsFindPatternSyntaxRegExpr;
find.SearchSubfolders = true;
var x = dte.Find.FindWhat;
EnvDTE.vsFindResult result = find.Execute();
var findWindow = dte.Windows.Item(vsWindowKindFindResults1);
string data = "";
System.Threading.Thread.Sleep(5000);//Comment out this code to see the problem, this line of code is not the solution though.
if (result == EnvDTE.vsFindResult.vsFindResultFound)
{
var selection = findWindow.Selection as EnvDTE.TextSelection;
selection.SelectAll();
data = selection.Text;
}
return data;
}
I see that the problem is the function return the string (string data) too early, so it can't get all the text from the result window.
So the code comes so close to get the find text. One remaining puzzle is to check if the find process complete, then get the text.
So the question is: replace what code with the code
System.Threading.Thread.Sleep(5000);
So that the function FindInFiles() can get all the text of 'FindResult 1" window.
Thanks for reading.
Here is the solution
EnvDTE80.DTE2 s_dte;
EnvDTE.FindEvents s_findEvents;
public const string vsWindowKindFindResults1 = "{0F887920-C2B6-11D2-9375-0080C747D9A0}";
public frmFindHelper()
{
InitializeComponent();
s_dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
s_dte.MainWindow.Activate();
s_findEvents = s_dte.Events.FindEvents;
s_findEvents.FindDone += new EnvDTE._dispFindEvents_FindDoneEventHandler(OnFindDone);
}
private void OnFindDone(EnvDTE.vsFindResult result, bool cancelled)
{
if (result == EnvDTE.vsFindResult.vsFindResultFound)
{
var findWindow = s_dte.Windows.Item(vsWindowKindFindResults1);
string data = "";
var selection = findWindow.Selection as EnvDTE.TextSelection;
selection.SelectAll();
data = selection.Text;
MessageBox.Show("Done!");
}
}
private void btnFind_Click(object sender, EventArgs e)
{
EnvDTE.Find find = s_dte.Find;
find.Action = EnvDTE.vsFindAction.vsFindActionFindAll;
find.FindWhat = txtSearch.Text;
find.MatchWholeWord = false;
find.ResultsLocation = EnvDTE.vsFindResultsLocation.vsFindResults1;
find.Target = EnvDTE.vsFindTarget.vsFindTargetSolution;
find.PatternSyntax = EnvDTE.vsFindPatternSyntax.vsFindPatternSyntaxRegExpr;
find.SearchSubfolders = true;
var x = s_dte.Find.FindWhat;
EnvDTE.vsFindResult result = find.Execute();
}
Thanks to Ed Dore from this post
My Requirement: Apply fillers via c# coding(Not Design) ie, filterer salaries greater than 7000.
I have a class library and a web form in my project.
I am creating the report on class library and display report by using web form.
When I run my application it shows always the unfiltered data.
What i do to get Filtered data in Viewer.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Telerik.Reporting.Filter f1 = new Telerik.Reporting.Filter();
f1.Expression = "= Fields.Salary";
f1.Operator = Telerik.Reporting.FilterOperator.GreaterOrEqual;
f1.Value = "=7000";
EmpReport objEmpReport = new EmpReport(); objEmpReport.Filters.Add(f1);
TypeReportSource rptSource = new TypeReportSource(); rptSource.TypeName = typeof(EmpReport).AssemblyQualifiedName; this.ReportViewer1.ReportSource = rptSource;
}
}
working code:
// ...
using Telerik.Reporting;
using Telerik.Reporting.Processing;
// ...
void ExportToPDF(string reportToExport)
{
// all my reports are in trdx format - detect file type and use unpackage below for trdp files.
string currPath = HttpRuntime.AppDomainAppPath; // get the full path so deserialise works
reportToExport = currPath + #"Reports\" + reportToExport; // add folder and report name to path
UriReportSource uriReportSource = new UriReportSource { Uri = reportToExport }; // compressed to 1 line for brevity
Telerik.Reporting.Report myReport = DeserializeReport(uriReportSource); // extract report from xml format (trdx)
// Filters are client side (use params for server side) Here we work with the report object.
// set meaningful field name and values for your code, maybe even pass in as params to this function...
myReport.Filters.Add("UserId", FilterOperator.Equal , "1231");
var instanceReportSource = new Telerik.Reporting.InstanceReportSource(); // report source
instanceReportSource.ReportDocument = myReport; // Assigning Report object to the InstanceReportSource
// kinda optional, lots of examples just used null instead for deviceInfo
System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); // set any deviceInfo settings if necessary
ReportProcessor reportProcessor = new ReportProcessor(); // will do work
RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); // GO!
if (!result.HasErrors)
{
this.Response.Clear();
this.Response.ContentType = result.MimeType;
this.Response.Cache.SetCacheability(HttpCacheability.Private);
this.Response.Expires = -1;
this.Response.Buffer = true;
this.Response.BinaryWrite(result.DocumentBytes);
this.Response.End();
}
else
{
Exception[] ex = result.Errors;
throw new Exception(ex[0].Message);
}
}
Telerik.Reporting.Report DeserializeReport(UriReportSource uriReportSource)
{
var settings = new System.Xml.XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (var xmlReader = System.Xml.XmlReader.Create(uriReportSource.Uri, settings))
{
var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
var report = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
return report;
}
}
Telerik.Reporting.Report UnpackageReport(UriReportSource uriReportSource)
{
var reportPackager = new ReportPackager();
using (var sourceStream = System.IO.File.OpenRead(uriReportSource.Uri))
{
var report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream);
return report;
}
}
Situation:
I have 3 web references (xMap, xLocation, xRoute)
xMap is dedicated to generating maps.
xLocation is dedicated to locating places.
xRoute is dedicated to generating routes.
I am using a simple GUI to display the map and inputting locations for the start and destination routes.
These are my errors.
Error 1 Cannot implicitly convert type 'Plantool.xRoute.LineString[]'
to 'Plantool.xMap.LineString[]'
Error 2 The best overloaded method match for
'Plantool.xMap.XMapWSService.renderMapBoundingBox(Plantool.xMap.BoundingBox,
Plantool.xMap.MapParams, Plantool.xMap.ImageInfo,
Plantool.xMap.Layer[], bool, Plantool.xMap.CallerContext)' has some
invalid arguments
Error 3 Argument '1': cannot convert from
'Plantool.xRoute.BoundingBox' to 'Plantool.xMap.BoundingBox'
I am guessing that PTV xServer's duplicate methods/features/etc are the same as xMap, xLocate, xRoute are optional modules. It is probably a simple answer is there a solution to this?
I am looking a head for a long trip home and spend an additional addicted half an hour of overtime on this code. And hi, I'm new.
Below his my class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Plantool.xMap;
using Plantool.xLocate;
using Plantool.xRoute;
namespace Plantool
{
class ClassMap
{
/*
* xServer clients
*/
private static XMapWSService xMapClient = new XMapWSService();
private static XRouteWSService xRouteClient = new XRouteWSService();
private static XLocateWSService xLocateClient = new XLocateWSService();
/* getLocation()
* Input: Address string
* Output: WKT (Well-Known-Text) Location
* Edited 20/12/12 - Davide Nguyen
*/
public string getLocation(string input)
{
// create the adress object
string[] address = input.Split(',');
Address addr = new Address();
addr.country = address[0];
addr.city = address[1];
addr.postCode = address[2];
// call findAddress on the xLocate server
// only the first argument of findAddress is mandatory,
// all others are nullable (see xLocate API documentation)
AddressResponse response = xLocateClient.findAddress(addr, null, null, null, null);
string result = "";
foreach (ResultAddress ra in response.wrappedResultList)
{
result += String.Format("POINT( {0} {1}) ", ra.coordinates.point.x, ra.coordinates.point.y);
}
string result2 = result.Replace(",", ".");
return result2;
}
/* route()
* Input: Start address, Destination address
* Output: string[] [0] DISTANCE [1] TIME [2] MAP
* Edited 20/12/12 - Davide Nguyen
*/
public string[] route(string startlocation, string destination)
{
#region WaypointDesc[]
// create the WayPoint for the Start
// ATTENTION: Here at the object WaypointDesc the parameters are not named
// "coords" as described within the documentation but
// "wrappedCoords"
WaypointDesc wpdStart = new WaypointDesc();
// please note that this has to be an array of Point...
wpdStart.wrappedCoords = new xRoute.Point[] { new xRoute.Point() };
wpdStart.wrappedCoords[0].wkt = getLocation(startlocation);
// Waypoint for the Destination...
WaypointDesc wpdDestination = new WaypointDesc();
wpdDestination.wrappedCoords = new xRoute.Point[] { new xRoute.Point() };
wpdDestination.wrappedCoords[0].wkt = getLocation(destination);
// create a new array of WayPointDescriptions and fill it with Start and Destination
WaypointDesc[] waypointDesc = new WaypointDesc[] { wpdStart, wpdDestination };
#endregion
try
{
// Route
Route route = calculateRoute(waypointDesc);
// Map
string DisplayMapURL = createMap(waypointDesc, route);
// get route info
string[] routeinfo = getRouteInfo(waypointDesc);
// Create the result
string[] result = new string[3];
result[0] = routeinfo[0]; // Distance
result[1] = routeinfo[1]; // Time
result[2] = DisplayMapURL;// Map URL
// Return the result
return result;
}
catch
{
throw new NotImplementedException();
}
}
/* getRouteInfo()
* Input: WaypointDesc[]
* Output: string mapURL
* Edited 20/12/12 - Davide Nguyen
*/
private static string createMap(WaypointDesc[] waypointDesc, Route route)
{
#region boundingBox
// Set boundingBox fand use corners from the calculated route
xRoute.BoundingBox boundingBox = new xRoute.BoundingBox();
boundingBox.leftTop = route.totalRectangle.rightTop;
boundingBox.rightBottom = route.totalRectangle.leftBottom;
#endregion
#region mapParams
// Build mapParams
MapParams mapParams = new MapParams();
mapParams.showScale = true;
mapParams.useMiles = false;
#endregion
#region imageInfo
// Create imageInfo and set the frame size and image format. NOTE: 1052; 863
ImageInfo imageInfo = new ImageInfo();
imageInfo.format = ImageFileFormat.PNG;
imageInfo.height = 1052;
imageInfo.width = 863;
imageInfo.imageParameter = "";
#endregion
#region layers
// Create a line from the calculated route
xRoute.LineString[] lineStrings = new xRoute.LineString[] { route.polygon };
Lines[] lines = new Lines[1];
LineOptions options = new LineOptions();
LinePartOptions partoptions = new LinePartOptions();
partoptions.color = new Color();
partoptions.visible = true;
partoptions.width = -10;
options.mainLine = partoptions;
lines[0] = new Lines();
lines[0].wrappedLines = lineStrings; //NEED HELP
lines[0].options = options;
// Define customLayer that contains the object lines and set layers.
CustomLayer customLayer = new CustomLayer();
customLayer.visible = true;
customLayer.drawPriority = 100;
customLayer.wrappedLines = lines;
customLayer.objectInfos = ObjectInfoType.NONE;
customLayer.centerObjects = true;
Layer[] layers = new Layer[] { customLayer };
#endregion
#region includeImageInResponse
// Set argument includeImageInResponse to false (default).
Boolean includeImageInResponse = false;
#endregion
// Return object map using the following method.
Map map = xMapClient.renderMapBoundingBox(boundingBox, mapParams, imageInfo, layers, includeImageInResponse, null); // NEED HELP
// Retrieve the image
string result = "http://" + map.image.url;
// Return the drawn map
return result;
}
/* getRouteInfo()
* Input: WaypointDesc[]
* Output: string[] [0] Distance in M [1] Time in H:M:S:MS
* Edited 20/12/12 - Davide Nguyen
*/
private string[] getRouteInfo(WaypointDesc[] waypointDesc)
{
// Call the service
RouteInfo routeInfo = xRouteClient.calculateRouteInfo(waypointDesc, null, null, null);
// Create the result
TimeSpan t = TimeSpan.FromSeconds(routeInfo.time);
string[] result = new string[2];
result[0] = string.Format("{0} KM", routeInfo.distance);
result[1] = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
// Return the result
return result;
}
/* getRouteLines()
* Input: WaypointDesc[]
* Output: Route object
* Edited 20/12/12 - Davide Nguyen
*/
private static Route calculateRoute(WaypointDesc[] waypointDesc)
{
#region ResultListOptions
// Instantiate a new object resultListOPtions
ResultListOptions resultListOptions = new ResultListOptions();
resultListOptions.polygon = true;
resultListOptions.totalRectangle = true;
resultListOptions.detailLevel = DetailLevel.STANDARD;
#endregion
#region CallerContext/CallerContextPropery
// Create a new CallerContextProperty object property
xRoute.CallerContextProperty property = new xRoute.CallerContextProperty();
property.key = "ResponseGeometry";
property.value = "WKT";
xRoute.CallerContext callerContext = new xRoute.CallerContext();
callerContext.wrappedProperties = new xRoute.CallerContextProperty[] { property };
#endregion
// Call the service
Route route = xRouteClient.calculateRoute(waypointDesc, null, null, resultListOptions, callerContext);
return route;
}
}
}
There seems to be some reference confusion between these two.
using Plantool.xMap;
using Plantool.xRoute;
You could delete these:
using Plantool.xMap;
using Plantool.xLocate;
using Plantool.xRoute;
And just add this:
using Plantool;
And then explicitly reference the correct types, ensuring you are referencing the one that is required. This should solve all three error messages.
Ideally, you should avoid having name-clashes where only the namespace is different. In the .NET framework you'll notice that they take care to avoid this, for example...
System.Data.Odbc.OdbcConnection
System.Data.SqlClient.SqlConnection
They could have both been called Connection, given that one is in the Odbc namespace and one is in the SqlClient namespace - but this could lead to the problem you have.
By renaming LineString to RouteLineString and MapLineString you can avoid the confusion in your application.
From what I remember from xServer, this was a major issue: common types from xMap, xRoute and xLocate are not the same (just like you said, because those are optional modules). xMap.LineString is actually a different type from xRoute.LineString, even if they have identical properties. There's nothing you can do about it, except:
if both types share a common base type or interface, use this common type instead
write extension methods to map from xRoute.LineString to xLocate.LineString...etc.
For instance:
public static xLocate.LineString ToXLocateLineString(this xRoute.LineString lineString)
{
return new xLocate.LineString
{
// Map type by copying properties
....
};
}
So you can write
xRoute.LineString[] input = ....
xMap.LineString[] output = input.Select(z => z.ToXLocateLineString()).ToArray();
Or even
public static xLocate.LineString[] ToXLocateLineStringArray(this xRoute.LineString[] lineString)
{
return lineString.Select(z => z.ToXLocateLineString()).ToArray();
}
then
xMap.LineString[] output = input.ToXLocateLineStringArray();
Maybe they improved their API since I used it for the last time, not sure about that.
Cheers, in my eyes the redundance can be resolved by a proper creation of client classes. Instead of adding three WSDL's one by one (through the Visual Studio Wizzards) you could merge the WSDLs in a single step by using the WSDL.EXE of Visual Studio. This worked with PTV xServer 1 (which was referenced in this thread) and even better with xServer2
What I usually do is a CMD statement such as
WSDL /namespace:"XServer" /sharetypes /out:"XServer.cs" "https://xserver2-europe-eu-test.cloud.ptvgroup.com/services/ws/XLocate?wsdl" "https://xserver2-europe-eu-test.cloud.ptvgroup.com/services/ws/XRoute?wsdl" "https://xserver2-europe-eu-test.cloud.ptvgroup.com/services/ws/XTour?wsdl"
See this as a generic advice. Mapping interfaces are completely different nowadays.