Inconsistent Result With Bing Map Silverlight Using Basic Key - silverlight

Hi I have used following code but sometime I didnt get the pushpin, I am using Basic key can any one please suggest me.
public MainPage()
{
InitializeComponent();
Geocode("8800 Lyra Avenue, Columbus, OH 43240", 1);
Geocode("2137 Birchwood Dr, Redmond,WA 78214,U.S.", 1);
Geocode("Santa Cruz, Duval Co., TX", 1);
}
private void Geocode(string address, int waypointIndex)
{
PlatformServices.GeocodeServiceClient geocodingService = new PlatformServices.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
geocodingService.GeocodeCompleted += new EventHandler<TestSL.PlatformServices.GeocodeCompletedEventArgs>(geocodingService_GeocodeCompleted);
PlatformServices.GeocodeRequest request = new PlatformServices.GeocodeRequest();
request.Credentials = new TestSL.PlatformServices.Credentials();
request.Credentials.ApplicationId = ((Microsoft.Maps.MapControl.ClientTokenCredentialsProvider)(MyMap.CredentialsProvider)).Token;
request.Query = address;
geocodingService.GeocodeAsync(request, waypointIndex);
}
public void geocodingService_GeocodeCompleted(object sender, TestSL.PlatformServices.GeocodeCompletedEventArgs e)
{
MapLayer myMapLayer = new MapLayer();
MyMap.Children.Add(myMapLayer);
// create a location collection class
LocationCollection myLocationColl = new LocationCollection();
var geoResult = (from r in e.Result.Results
orderby (int)r.Confidence ascending
select r).FirstOrDefault();
if (geoResult != null)
{
Pushpin myPushPin = new Pushpin();
// set it to first found location
myPushPin.Location = new Microsoft.Maps.MapControl.Location(geoResult.Locations[0].Latitude, geoResult.Locations[0].Longitude);
ToolTipService.SetToolTip(myPushPin, geoResult.DisplayName);
// add it to location collection
// which would be used to set the map's bound
myLocationColl.Add(myPushPin.Location);
// Add the drawn point to the route layer.
myMapLayer.Children.Add(myPushPin);
}
}
Sometime i get two pushpin and Sometime I didnt get anything and sometimes i get 1 or 3. can any one please tell me why this is happening.

You should geocode all your data ahead of time and store the coordinates. Trying to geocode a bunch of addresses on the fly like this will drive up the number of transactions generated by your application. When using a basic key it can be rate limited if a bunch of requests are made in a short period of time. When the request is rate limited a flag is added to the header of the response to indicate this. This is documented at the bottom half of this page: http://msdn.microsoft.com/en-us/library/ff701703.aspx

Related

DynamicReport - How to plot too many data points

I am trying to create LineChartReport using more than 1000 data points. Problem is that the X Axis should show the time stamp, and since there are too many data points, the data gets overlapped and no comprehensible data is shown. So I need help on following 2 points:
1. Limit the data points on X-Axis (only) to say 25. The number of data points for the graph/chart still remains at 1000
2. Rotate the Timestamp data by 90 degrees so that the Timestamp data is recorded correctly and not truncated.
Have tried to get the domain axis and manipulate it, like this, but the library does not allow that:
CategoryAxis domainAxis = chart.getCategoryPlot().getDomainAxis();
domainAxis.setMinorTickMarksVisible(false);
domainAxis.clearCategoryLabelToolTips();
chart.getCategoryPlot().getDataset().getColumnKeys()
CategoryDataset ds = chart.getCategoryPlot().getDataset();
List ls = ds.getColumnKeys();
List ls2 = new ArrayList();
int i = 0;
for (Iterator it = ls.iterator(); it.hasNext(); ) {
it.next();
if (i % 2 != 0) {
ls2.add(ls.get(i));
}
i++;
}
chart.getCategoryPlot().setDataset(ds);
Sample image with 10 data points appear here: https://drive.google.com/drive/u/0/folders/0B-m6SCJULOTRdHZ6cUwxX041SHM
Any suggestions ??
The below codes are based on DynamicReport 4.0.2. I didn't test them in other versions.
Regarding your first question, you want 1000 points of data, and just want the few data in line chart. In this case, you need to use the different data source for you data table and line chart.
Firstly, create the subreport for the data table and set up.
SubreportBuilder subreport = cmp.subreport(
report().setTemplate(Templates.reportTemplate)
.addColumn(
col.column("Name", "name", type.stringType()),
col.column("Counts", "value", type.integerType())
)
);
JasperReportBuilder reportContent = report();
subreport.setDataSource(allDatasource);
reportContent.summary(subreport, cmp.verticalGap(20));
Secondly, prepare another data source for line chart and set up.
reportContent.setTemplate(Templates.reportTemplate)
/* add title */
.title(title, subtitle,
/* add chart in the head of title */
cmp.verticalList(LINE_CHART)
/* set style */
.setStyle(stl.style().setBottomPadding(30).setTopPadding(30)))
/* set data source for line chart*/
.setDataSource(dataSource);
About your second question, you need to create customizer at first.
public class DynamicLineCustomizer implements DRIChartCustomizer, Serializable {
private static final long serialVersionUID = -8493880774698206000L;
#Override
public void customize(JFreeChart jFreeChart, ReportParameters reportParameters) {
CategoryPlot plot = jFreeChart.getCategoryPlot();
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions
.createUpRotationLabelPositions(Math.PI / 6.0));
}
}
Then use this customizer in line chard builder.
LineChartBuilder lineChart = cht.lineChart()
.customizers(new DynamicLineCustomizer())
.setCategory(columns[0])
.series(createSeries(columns))
.setCategoryAxisFormat(cht.axisFormat().setLabel("TimeStamp"))
.seriesColors(seriesColors);
The line chart and data table will be like below:
This finally worked for me (hope it helps somebody) :
Ref: http://www.dynamicreports.org/forum/viewtopic.php?f=1&t=1046
private void build(String startDate, String endDate) {
TextColumnBuilder<Integer> i = col.column("I", "I", type.integerType());
TextColumnBuilder<Integer> b = col.column("B", "B", type.integerType());
TextColumnBuilder<Integer> t = col.column("T", "T", type.integerType());
TextColumnBuilder<Date> timeColumn = col.column("TimeStamp", "TimeStamp", type.dateType());
createDataSource(startDate, endDate);
try {
TimeSeriesChartBuilder timeSeriesChartBuilder1 = cht.timeSeriesChart();
timeSeriesChartBuilder1.series(cht.serie(b), cht.serie(t), cht.serie(i));
timeSeriesChartBuilder1.setShowShapes(false);
timeSeriesChartBuilder1.setDataSource(dataSource);
timeSeriesChartBuilder1.setTimePeriod(timeColumn);
timeSeriesChartBuilder1.setTimePeriodType(TimePeriod.SECOND);
timeSeriesChartBuilder1.setTitle("ABC Information");
JasperReportBuilder builder = report()
.summary(cht.multiAxisChart(timeSeriesChartBuilder1))
.setTemplate(Templates.reportTemplate)
.title(Templates.createTitleComponent("ABC Complete Info"))
;
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}

Infragistics UltraGrid (9.2) Band duplication after re-creating the datasource

I'm working my brain off trying to figure out a strange behavior of the UltraGrid Bands mechanism. The below code contains everything you need to re-create the problem.
I'm creating a DataSet and filling it with two DataTables. Then I assign the DataSet as a DataSource of BindingSource object. That BindingSource object is set as an UltraGrid.DataSource.
The below code will be helpful to fully understand what's going on after a single PrepareData() method is launched. The grid displays 3 records with the first one expandable to show the second Band referenced to it by DataRelation. You can check that by commenting out the second call.
public partial class Form1 : Form {
BindingSource bs = new BindingSource();
DataSet ds = new DataSet();
public Form1() {
InitializeComponent();
DoLayout();
Bind();
PrepareData();
PrepareData();
}
private void DoLayout() {
ultraGrid1.DisplayLayout.Override.ExpansionIndicator = Infragistics.Win.UltraWinGrid.ShowExpansionIndicator.CheckOnDisplay;
}
private void Bind() {
bs.DataSource = ds;
ultraGrid1.DataSource = bs;
}
private void PrepareData() {
// you need to keep watching the ultraGrid1.DisplayLayout.Bands.All property
// all the time - normally it contains one entry,
// the default {NewDataSet} entry
bs.SuspendBinding();
ds.Relations.Clear();
ds.Clear();
ds.Tables.Clear();
// when the above code will run for the second time, you can see that
// Bands.All property will claim to have the standard {NewDataSet} entry
// again. Seems like everything is working well
DataTable dt = new DataTable("TABLE1");
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
dt.Rows.Add("1", "1", "1");
dt.Rows.Add("2", "2", "2");
dt.Rows.Add("3", "3", "3");
// after adding the datatable to the dataset, we can see that there was
// a change made to the DisplayLayout.Band.All list of the ultraGrid1
// {NewDataSet} will change to {TABLE1}
//
// now watch the behavior when the method is run for the second time
ds.Tables.Add(dt);
// after the second run, you can see the first problem in the Bands.All entries
dt = new DataTable("TABLE2");
dt.Columns.Add("scol1");
dt.Columns.Add("scol2");
dt.Rows.Add("s1", "1");
dt.Rows.Add("s2", "1");
dt.Rows.Add("s3", "1");
// the Bands.All property still will say there is only one element in it
// but not anymore once the code is executed for the second time
ds.Tables.Add(dt); // for the second code run - here is the second problem
// now the first time we add that relation, you can see that
// a new entry exists in the Bands.All property of the ultraGrid1: {T1T2}
dt.ParentRelations.Add("T1T2", ds.Tables["TABLE1"].Columns["col1"], dt.Columns["scol2"], false);
// after the second run of the code, here you can see the third problem
bs.ResumeBinding();
}
}
Now if you run the PrepareData() method once more, the grid gets messy. I actually found what's causing the problem, thus the heavy comments in the code above, but I can't figure out why is this happening. As a result I simply want the grid to behave exactly the same no matter how many times the method is called.
Does anyone have a clue what could be the reason for this?
I already tried to null the DataSources, and re-assigning them; tired changing the order of the methods called; even tried to invoke non-public methods of the BandsCollection object like "ClearAllButBandZero" and "Clear", but it was all to no avail.
I've found an artible in the KnowledgeBase of the Infragistics DevCenter:
http://devcenter.infragistics.com/Support/KnowledgeBaseArticle.Aspx?ArticleID=1751
but that didn't help in my case. Each time the DataSet is reconstructed, the UltraGrid.DisplayLayout.Bands collection is getting more and more messy.
It is not necessary to use BindingSource to add a dataset as a datasource in UltraGrid. You can assign the dataset directly as grid's datasource. Take a look to the following code:
public partial class Form1 : Form
{
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
DoLayout();
PrepareData();
PrepareData();
}
private void DoLayout()
{
ultraGrid1.DisplayLayout.Override.ExpansionIndicator = Infragistics.Win.UltraWinGrid.ShowExpansionIndicator.CheckOnDisplay;
}
private void Bind()
{
ultraGrid1.DataSource = ds;
}
private void PrepareData()
{
ds = null;
ds = new DataSet();
DataTable dt = new DataTable("TABLE1");
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
dt.Rows.Add("1", "1", "1");
dt.Rows.Add("2", "2", "2");
dt.Rows.Add("3", "3", "3");
ds.Tables.Add(dt);
dt = new DataTable("TABLE2");
dt.Columns.Add("scol1");
dt.Columns.Add("scol2");
dt.Rows.Add("s1", "1");
dt.Rows.Add("s2", "1");
dt.Rows.Add("s3", "1");
ds.Tables.Add(dt);
dt.ParentRelations.Add("T1T2", ds.Tables["TABLE1"].Columns["col1"], dt.Columns["scol2"], false);
Bind();
}
}
I've found what's causing such behaviour. It's a bug in the .NET Framework.
There is a private field on the BindingSource class:
private Dictionary<string, BindingSource> relatedBindingSources;
The problem is that once you assign null to your BindingSource.DataSource, the Dictionary remains untouched. Then you assign new DataSource, add a relation in it, the Dictionary grows. And never stops.
My solution to this problem was creating a simple method, that will assure me that all possible relations are removed:
private void ClearRelatedBindingSources(BindingSource bindingSource) {
System.Reflection.FieldInfo fi = bindingSource.GetType().GetField("relatedBindingSources", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Dictionary<string, BindingSource> relatedBsDict = fi.GetValue(bindingSource) as Dictionary<string, BindingSource>;
if (relatedBsDict != null) {
relatedBsDict.Clear();
}
}
All there is to do is to call that method after nulling the BindingSource.DataSource property. That essentially solved the problem of band replication in my grids.
Many thanks to Thanasis thanks to whom I began to dig in the right place ;)

How To Bind an Array/List's Elements To DataGridViewTextBoxColumn's

In DataGridView, how to bind an array or list (with n elements) to n DataGridViewTextBoxColumn's?
Maybe it's not so clear, for example, I have a class:
public class DynamicNumberFieldsClass
{
public string FullName { get; set; }
public int[] Years { get; set; }
}
The expected form a DataGridView should display:
FullName Year1 Year2 Year3...
Peter 11 12 13
Bryan 21 22 23
If I have to use reflection, it's okay for me.
Any idea?
Thanks!
Peter
P.S.: We can assume the array field will never be null.
we can even assume that the number of elements in the array is fixed once a session is started, but the user can change it in Settings, so in the next session, the number of elements might not be the same.
I am assuming you are working in Windows Forms. I was able to at least display the data in the format you've shown by putting the DataGridView in Virtual Mode. You had best follow the entire walkthrough for a complete solution, but here is what I did in a quick test (hacked up from the samples in the walkthough):
CellValueNeeded handler:
private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
// If this is the row for new records, no values are needed.
if (e.RowIndex == this.dataGridView1.RowCount - 1) return;
DynamicNumberFieldsClass objectInRow = (DynamicNumberFieldsClass)this._people[e.RowIndex];
// Set the cell value to paint using the DynamicNumberFieldsClass object retrieved.
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "FullName":
e.Value = objectInRow.FullName;
break;
default:
e.Value = objectInRow.Years[e.ColumnIndex - 1];
break;
}
}
where _people is a collection of DynamicNumberFieldsClass.
Form Load:
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.VirtualMode = true;
this.dataGridView1.CellValueNeeded += new DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
// Add columns to the DataGridView.
DataGridViewTextBoxColumn fullNameColumn = new
DataGridViewTextBoxColumn();
fullNameColumn.HeaderText = "FullName";
fullNameColumn.Name = "FullName";
this.dataGridView1.Columns.Add(fullNameColumn);
for (int i = 0; i < _numYears; i++)
{
DataGridViewTextBoxColumn yearIColumn = new
DataGridViewTextBoxColumn();
yearIColumn.HeaderText = "Year" + (i+1);
yearIColumn.Name = "Year" + (i+1);
this.dataGridView1.Columns.Add(yearIColumn);
}
this.dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
// Set the row count, including the row for new records.
this.dataGridView1.RowCount = 3; //two objects in _people and the empty row
}
where _numYears is the fixed value you mentioned. If you have at least one instance of the object available, you could use the size of the Years array in that instance as the loop limiter, so that it is completely dynamic.
You would need to expand the switch statement if any other properties are included in the class, and of course add more error checking in general. The walkthrough shows how to support editing in the DataGridView, as well.
(I know you asked how to bind the columns, not force their values, so you probably wanted to be able to decorate the class definition, assign the data source, and go. To that end, I first looked into doing this with Reflection via CustomTypeDescriptor and TypeDescriptionProvider, etc., which is how second-level properties can be bound. Of course, the individual elements of the array are not exposed as properties, so this doesn't work. I can't think of a way to support auto-generation of the columns the way you want, but maybe someone else will find one.)

Is it possible to choose Datagrid grouping order in WPF?

I've just started to learn WPF/C# and I picked a project which would actually be useful to me instead of variations of "Hello, World!" programs.
It's a small app that polls a game server for player information and binds it to a DataGrid. The data is grouped by team, which can be one of four values: Blue, Red, Spectator, or None.
I've got the Linq query working fine, and the DataGrid grouping is almost good, except for one small problem: the order of the four teams groups is different every time. Sometimes Red is first, sometimes None, etc.
Is there any way I can force the groups into the order above?
Here is the Linq query (addr is the server ip):
private void get_server(string addr)
{
var loc = "http://ukcs.gameme.com/api/serverinfo/" + addr + "//players";
XDocument doc = XDocument.Load(#loc);
var server = new ObservableCollection<Player>
(from player in doc.Descendants("player")
orderby player.Element("rank").Value
select new Player
{
name = player.Element("name").Value,
team = player.Element("team").Value,
frags = player.Element("kills").Value + ":" + player.Element("deaths").Value,
rank = int.Parse(player.Element("rank").Value)
});
server.OrderBy(p => p.rank);
ListCollectionView collection = new ListCollectionView(server);
collection.GroupDescriptions.Add(new PropertyGroupDescription("team"));
player_list.ItemsSource = collection;
}
A second problem is that neither of the OrderBys seem to have an effect.
Any help would be appreciated!
To answer your last question first :) The OrderBy's have no meaning here, because after you sort the players, you put the list inside a CollectionView with a grouping which promptly sorts it by Team (since the grouping is on Team).
To get them in the proper order, you can sort them by Team before putting them inside the ListCollectionView. However, this will put them in alphabetical order - and not exactly the order you wanted. You need to implement IComparable and put that in your sort method - i've rewritten your method a bit (I am not so good at that Linq-form - so, bear with me :)):
You made it a bit harder on yourself by introducing a few unnecessary things - I've tried to root them out.
private void get_server(string addr)
{
var loc = "http://ukcs.gameme.com/api/serverinfo/" + addr + "//players";
var doc = XDocument.Load(#loc);
var server = doc.Descendants("player")
.Select(player => new Player
{
name =player.Element("name").Value,
team=player.Element("team").Value,
frags=player.Element("kills").Value +":" +player.Element("deaths").Value,
rank=int.Parse(player.Element("rank").Value)
})
.OrderBy(p => p.team,new CustomSort())
.ThenBy(p => p.rank).ToList();
var collection = new ListCollectionView(server);
collection.GroupDescriptions.Add(new PropertyGroupDescription("team"));
player_list.ItemsSource = collection;
}
public class CustomSort : IComparer<string>
{
public int Compare(string x, string y)
{
if (x.Equals(y))
return 0;
if (y.Equals("None") || x.Equals("Blue"))
return 1;
if (x.Equals("None") || y.Equals("Blue"))
return -1;
if (x.Equals("Red")|| y.Equals("Spectator"))
return -1;
return 1; // y == "Red" and x == "Spectator"
}
}
Hope this helps!

Silverlight specific Image shifting to the right

I am generating a set images to form a human body so that I can use for a physics engine.
The images generated are in a specific user control in where I set the dimentions and co-ordinates of each image. That usercontrol is then loaded in another user control but for some reason when the images are loaded, one specific image which I named (rightBicep) is shifting to the right. Here is a screenshot :
alt text http://img193.imageshack.us/img193/592/imageshift.jpg
I illustrated the positions of the images with dotted lines, the green dotted line is refering to where the image should be located, and the red dotted line is where the image is being shown.
The weird thing is the image beneath it (called rightForearm) take's it's LeftPosition from it, and when during debugging they have the exact same leftProperty value. Here's the syntax :
public void generateRightBicep(string imageUrl)
{
rightBicep = new Image();
rightBicep.Name = CharacterName + "rightbicep";
Uri imageUri = new Uri(imageUrl, UriKind.Relative);
LayoutRoot.Children.Add(rightBicep);
rightBicep.Source = new BitmapImage(imageUri);
rightBicep.ImageOpened += new EventHandler<RoutedEventArgs>(bodyPart_ImageOpened);
}
public void rightBicepLoaded()
{
var bi = waitTillImageLoad(rightBicep.Name);
rightBicep.Height = elbowToArmpit + (2 * palm);
rightBicep.Width = ratio(bi.PixelHeight, bi.PixelHeight, rightBicep.Height); // to be determined
Vector2 topVector;
topVector.X = (float)(Convert.ToDouble(torso.GetValue(Canvas.LeftProperty)) - palm);
topVector.Y = (float)(Convert.ToDouble(neck.GetValue(Canvas.TopProperty)) + neck.Height);
if (!faceRight)
{
perspectiveVectorHeight(ref topVector, ref rightBicep, torso.Width);
rightBicep.Width = ratio(bi.PixelHeight, bi.PixelHeight, rightBicep.Height);
}
rightBicep.SetValue(Canvas.LeftProperty, Convert.ToDouble(topVector.X));
rightBicep.SetValue(Canvas.TopProperty, Convert.ToDouble(topVector.Y));
rightBicep.SetValue(Canvas.ZIndexProperty, rightBicepZindex);
generateRightShoulder();
}
public void generateRightForearm(string imageUrl)
{
rightForearm = new Image();
rightForearm.Name = CharacterName + "rightforearm";
Uri imageUri = new Uri(imageUrl, UriKind.Relative);
LayoutRoot.Children.Add(rightForearm);
rightForearm.Source = new BitmapImage(imageUri);
rightForearm.ImageOpened += new EventHandler<RoutedEventArgs>(bodyPart_ImageOpened);
}
public void rightForearmLoaded()
{
var bi = waitTillImageLoad(rightForearm.Name);
rightForearm.Height = (elbowToHandTip - handLength) + palm;
rightForearm.Width = ratio(bi.PixelHeight, bi.PixelWidth, rightForearm.Height);
Vector2 topVector;
if (faceRight)
{
topVector.X = (float)(Convert.ToDouble(rightBicep.GetValue(Canvas.LeftProperty)));
topVector.Y = (float)(Convert.ToDouble(rightBicep.GetValue(Canvas.TopProperty)) + rightBicep.Height - palm);
}
else
{
topVector.X = (float)(Convert.ToDouble(leftBicep.GetValue(Canvas.LeftProperty)));
topVector.Y = (float)(Convert.ToDouble(leftBicep.GetValue(Canvas.TopProperty)) + leftBicep.Height - palm);
perspectiveVectorHeight(ref topVector, ref rightForearm, torso.Width);
rightForearm.Width = ratio(bi.PixelHeight, bi.PixelWidth, rightForearm.Height);
}
rightForearm.SetValue(Canvas.LeftProperty, Convert.ToDouble(topVector.X));
rightForearm.SetValue(Canvas.TopProperty, Convert.ToDouble(topVector.Y));
rightForearm.SetValue(Canvas.ZIndexProperty, rightForearmZIndex);
generateRightElbow();
}
Now all the values I am adding together are a group of doubles I preset, and the property faceRight is to dertmine if the human body is facing right or left to determine where the positions of the body parts (since if the right hand looks on the left hand side when the human body turns the other way).
If you notice the rightforearm is taking the leftproperty of the rightbicep, so technically it should display direcrly underneath which it isn't. I also debugged the user control and both have the left property of -3.
PS. I call the methods rightbicepLoaded and rightforearmLoaded when an event is called when all the imageOpened events all have been triggered.
Any ideas on why this is happening?
Found out why , in my method ratio it should take hieght and width, and I put and i put 2 hieghts instead

Resources