I'm trying to display a list of positions (from a xml document:using xml reading) in a Bing map with WP7,using the method below, but it doesn't work.
When i tried to see what my function is reading, i found out that it's not extracting the Longitude.Where's the problem?
void frloc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ListBoxItem areaItem = null;
StringReader wkstream = new StringReader(e.Result);
XmlReader wkreader = XmlReader.Create(wkstream);
string areaName = String.Empty;
string Nom = String.Empty;
string Photo = String.Empty;
string Latitude = String.Empty;
string Longitude = String.Empty;
string Timing = String.Empty;
while (wkreader.Read())
{
if (wkreader.NodeType == XmlNodeType.Element)
{
switch (wkreader.Name)
{
case ("name"):
{
Nom = wkreader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = Nom;
} break;
case ("photo"):
{
Photo = wkreader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = Photo;
} break;
case ("latitude"):
{
Latitude = wkreader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = Latitude;
} break;
case ("longitude"):
{
Longitude = wkreader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = Longitude;
} break;
}
double lat, lon;
double.TryParse(Latitude, NumberStyles.Any, CultureInfo.InvariantCulture, out lat);
double.TryParse(Longitude, NumberStyles.Any, CultureInfo.InvariantCulture, out lon);
GeoCoordinate Loc = new GeoCoordinate(lat, lon);
Pushpin wkpin = new Pushpin();
Image wkpinImage = new Image();
wkpin.Content = Nom;
wkpinImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://weenek.com/markers/" + Photo, UriKind.Absolute));
wkpinImage.Opacity = 0.8;
wkpinImage.Stretch = System.Windows.Media.Stretch.None;
imageLayer.AddChild(wkpinImage, Loc);
map1.Children.Add(wkpin);
The xml:
<resultat>
<ami>
<id>547</id>
<nom>Hakim</nom>
<prenom>Abidi</prenom>
<latitude>37.01406741589469</latitude>
<longitude>11.02375026562504</longitude>
<date>2011-12-02</date>
<time>01:09:35</time>
<image>175.jpg</image>
</ami>
</resultat>
There's nothing wrong with your code except of that you're never setting the coordinates of the Pushpin.
Try adding
wkpin.Location = Loc;
Related
In my xamarin.forms app. I am using Media.plugin to select images from gallery and camera.And also file picker plugin to select files like pdf,jpg etc from file manager.User can select multiple images and files and It will store in an observable collection.In this observable collection I have the path of images as well as files. Where I am stuck is I want to send these data to rest API by using multipart/form data.How can I send these multiple files to the server? Any help is appreciated.
My ObservableCollection
public ObservableCollection<SelectedDocumentModel> DataManager
{
get
{
return _selectedfile ?? (_selectedfile = new ObservableCollection<SelectedDocumentModel>());
}
}
My Data Model
public class SelectedDocumentModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string FileName { get; set; }
public string Path { get; set; }
public ImageSource SelectedImage { get; set; }
public object Tasks { get; internal set; }
private bool isLoadingVisible = false;
public bool IsLoadingVisible
{
get
{
return isLoadingVisible;
}
set
{
if (value != null)
{
isLoadingVisible = value;
NotifyPropertyChanged("IsLoadingVisible");
}
}
}
}
Selecting image using media.plugin and allocating to my observable collection
var Filename = Path.GetFileName(file.Path);
var FilePath = file.Path;
var newList = new SelectedDocumentModel()
{
FileName = Filename,
SelectedImage = imageSource,
IsLoadingVisible = false,
Path = FilePath
};
DataManager.Add(newList);
Selecting file from file manager using filepicker plugin and assign to observablecollection
var FilePath = pickedFile.FilePath;
var newList = new SelectedDocumentModel()
{
FileName = filename,
SelectedImage = imageSource,
IsLoadingVisible = false,
Path= FilePath
};
DataManager.Add(newList);
EDIT
This is what I should do using httpclient.Currently these are written using RestSharp.
var client = new RestClient("{{api_url}}/MYData");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "bearer {{token}}");
request.AddHeader("Content-Type", "application/json");
request.AlwaysMultipartFormData = true;
request.AddParameter("ids", " [{\"id\":1,\"person_id\":5}]");
request.AddParameter("title", " Test");
request.AddParameter("description", " Test");
request.AddParameter("send_text_message", " true");
request.AddParameter("text_message", " Test");
request.AddParameter("notification_type"," global");
request.AddParameter("my_files", "[
{
\"name\": \"abc.jpg\",
\"key\": \"1583307983694\"
}
]");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
What I have done by the way suggested by Lucas Zhang - MSFT.
try {
MultipartFormDataContent multiContent = new MultipartFormDataContent();
foreach (SelectedDocumentModel model in SelectedFileData)
{
byte[] byteArray = Encoding.UTF8.GetBytes(model.Path);
MemoryStream stream = new MemoryStream(byteArray);
HttpContent fileStreamContent1 = new StreamContent(stream);
fileStreamContent1.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = model.FileName,
FileName = model.FileName
};
fileStreamContent1.Headers.ContentType = new
System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
multiContent.Add(fileStreamContent1);
}
multiContent.Add(new StringContent(notificationdetails[0]), "title");
multiContent.Add(new StringContent(notificationdetails[1]), "description");
multiContent.Add(new StringContent(notificationdetails[3]), "type");
multiContent.Add(new StringContent(notificationdetails[7]), "send_text_message");
multiContent.Add(new StringContent(notificationdetails[2]), "text_message");
multiContent.Add(new StringContent(notificationdetails[8]), "send_email");
multiContent.Add(new StringContent(notificationdetails[9]), "notification_type");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer",Settings.AuthToken);
var response = await client.PostAsync(url, multiContent);
var responsestr = response.Content.ReadAsStringAsync().Result;
await DisplayAlert("Result", responsestr.ToString(), "ok");
}
catch (Exception ex)
{
await DisplayAlert("Result", ex.Message.ToString(), "ok");
}
unfortunately it not working.It not sending the data as I intend.
How can I upload each files as multipart/formdata on a button click.?Any help is appriciated.
You could use MultipartFormDataContent to add multiple images,and use ContentDispositionHeaderValue.Parameters to add the values of your Data.
Usage
var fileStream = pickedFile.GetStream();
var newList = new SelectedDocumentModel()
{
FileName = filename,
SelectedImage = imageSource,
IsLoadingVisible = false,
Path= FilePath,
Data = fileStream ,
};
MultipartFormDataContent multiContent = new MultipartFormDataContent();
foreach(var SelectedDocumentModel model in DataManager)
{
HttpContent fileStreamContent1 = new StreamContent(model.Data);
fileStreamContent1.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = "File",
FileName = "xxx.jpg"
};
fileStreamContent1.Headers.ContentType = new
System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
multiContent.Add(fileStreamContent1);
multiContent.Add(new StringContent(model.Title), "model.Title");
multiContent.Add(new StringContent(model.Description), "model.Description");
multiContent.Add(new StringContent(model.Detail), "model.Detail");
}
// Send (url = url of api) ,use httpclient
var response = await client.PostAsync(url, multiContent);
I am developing a Windows Phone app in which I have to post a photo to facebook. And that particular photo is choosen by using PhotoChooserTask or CameraChooserTask.
Normally, I can post a particular photo successfully, but I am facing problem to post the selected photo. I saw some link like
link
So please if anyone know about the issue please help me out.
Thanx in advance.
EDIT
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
//var parameters1 = new Dictionary<>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["ContentType"] = "image/png";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
string imageName = "ic_launcher.png";
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
try
{
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
fbUpload.SetValue(imageData);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Tribute";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1 + "\n" + d + "\n" + memoType + "\n" + message1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
//client.PostTaskAsync("me/photos", parameters1);
}
On clicking on a button I am calling PostClicked class and it will directly go to facebook mainpage and it will ask for login information. Like this I am doing.
Please check it out
Now I can share a photo to facebook successfully by using photochoosertask or cameratask.
I am sharing my experience so that if anyone face the same issue can use it.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageToIsolatedStorage(image, tempJPEG);
this.image.Source = image;
}
public void SaveImageToIsolatedStorage(BitmapImage image, string fileName)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
if (image != null)
{
var wb = new WriteableBitmap(image);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
fileStream.Close();
}
}
With this you can able to save the selected image to IsolatedStorage.
And then at the time of posting the photo to facebook you have to select the image from IsolatedStorage.
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
try
{
byte[] data;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();
}
}
//MemoryStream ms = new MemoryStream(data);
//BitmapImage bi = new BitmapImage();
//// Set bitmap source to memory stream
//bi.SetSource(ms);
//this.imageTribute.Source = bi;
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = tempJPEG,
ContentType = "image/jpg"
};
fbUpload.SetValue(data);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Notice";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
Thanx to all....
you can do that by two methods :
1) by using mediasharetask in which it will show u all sharing account to which your phone is synced like facebook,gmail,linkdin,twitter,etc : it can be used like like this.
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
2) by using facebook sdk. you can get the package from nuget manager and then u can use it to share on facebook.
I hope this might help u.
I need to convert csv to xls/xlsx in my project? How can i do that? Can anyone post me some examples? I want to do it with Apache poi. I also need to create a cell from java side.
You can try following method to create xlsx file using apache-poi.
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}
We can use SXSSF Jar in which we can parse a long file as below:
public static void main( String[] args ) {
try {
// String fName = args[ 0 ];
String csvFileAddress = "C:\\Users\\psingh\\Desktop\\test\\New folder\\GenericDealerReport - version6.txt"; //csv file address
String xlsxFileAddress = "C:\\Users\\psingh\\Desktop\\trial\\test3.xlsx"; //xlsx file address
SXSSFWorkbook workBook = new SXSSFWorkbook( 1000 );
org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet( "sheet1" );
String currentLine = null;
int RowNum = -1;
BufferedReader br = new BufferedReader( new FileReader( csvFileAddress ) );
while ( ( currentLine = br.readLine() ) != null ) {
String str[] = currentLine.split( "\\|" );
RowNum++;
Row currentRow = sheet.createRow( RowNum );
for ( int i = 0; i < str.length; i++ ) {
currentRow.createCell( i )
.setCellValue( str[ i ] );
}
}
DateFormat df = new SimpleDateFormat( "yyyy-mm-dd-HHmmss" );
Date today = Calendar.getInstance()
.getTime();
String reportDate = df.format( today );
FileOutputStream fileOutputStream = new FileOutputStream( xlsxFileAddress );
workBook.write( fileOutputStream );
fileOutputStream.close();
//System.out.println( "Done" );
}
catch ( Exception ex ) {
System.out.println( ex.getMessage() + "Exception in try" );
}
}
public static void convertCsvToXlsx(String xlsLocation, String csvLocation) throws Exception {
SXSSFWorkbook workbook = new SXSSFWorkbook();
SXSSFSheet sheet = workbook.createSheet("Sheet");
AtomicReference<Integer> row = new AtomicReference<>(0);
Files.readAllLines(Paths.get(csvLocation)).forEach(line -> {
Row currentRow = sheet.createRow(row.getAndSet(row.get() + 1));
String[] nextLine = line.split(",");
Stream.iterate(0, i -> i + 1).limit(nextLine.length).forEach(i -> {
currentRow.createCell(i).setCellValue(nextLine[i]);
});
});
FileOutputStream fos = new FileOutputStream(new File(xlsLocation));
workbook.write(fos);
fos.flush();
}
I have found SXSSFWorkbook really faster then XSSFWorkbook. Here is the modified code:
try {
String csvFileInput = "inputFile.csv";
String xlsxFileOutput ="outputFile.xls";
LOGGER.error(csvFileInput);
LOGGER.error( xlsxFileOutput);
SXSSFWorkbook workBook = new SXSSFWorkbook();
Sheet sheet = workBook.createSheet(transformBean.getOutputFileName());
String currentLine = null;
int RowNum = 0;
BufferedReader br = new BufferedReader(new FileReader(csvFileInput));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
Row currentRow = sheet.createRow(RowNum);
for (int i = 0; i < str.length; i++) {
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileOutput);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage() + "Found Exception");
}
if(new File(newFileName).isFile()) return;
#SuppressWarnings("resource")
HSSFWorkbook wb = new HSSFWorkbook();
Row xlsRow;
Cell xlsCell;
HSSFSheet sheet = wb.createSheet("sheet1");
int rowIndex = 0;
for(CSVRecord record : CSVFormat.EXCEL.parse(new FileReader(fileName))) {
xlsRow = sheet.createRow(rowIndex);
for(int i = 0; i < record.size(); i ++){
xlsCell = xlsRow.createCell(i);
xlsCell.setCellValue(record.get(i));
}
rowIndex ++;
}
FileOutputStream out = new FileOutputStream(newFileName);
wb.write(out);
out.close();
Try this one if you have inputstream
public static XSSFWorkbook csvToXLSX(InputStream inputStream) throws IOException {
XSSFWorkbook workBook = new XSSFWorkbook();
try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
Sheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int rowNum=0;
while ((currentLine = br.readLine()) != null) {
String[] str = currentLine.split(",");
rowNum++;
Row currentRow=sheet.createRow(rowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
log.info("CSV file converted to the workbook");
return workBook;
} catch (Exception ex) {
log.error("Exception while converting csv to xls {}",ex);
}finally {
if (Objects.nonNull(workBook)) {
workBook.close();
}
}
return workBook;
}
I have bing map controll in which so many maplayer are there
I want to display popup in my pushpin click event same like this
Bing Maps Gets New Look for Pushpins, Popups, And Transit - See more at: http://wmpoweruser.com/bing-maps-gets-new-look-for-pushpins-popups-and-transit/#sthash.ApL3q6bA.dpuf
How i can do this.
Give me some advice for developing popup in bing map controll and yes i want to show latitude,longlatitude and address in this popup
Mu pushin code
void _ClsGetDeviceMap_WorkFinished(bool success)
{
try
{
if (ClsGetDeviceMap.lstresponsecode.ElementAt<string>(0).Trim() == "1")
{
MessageBox.Show(ClsGetDeviceMap.lstresponsemsg.ElementAt<string>(0));
for (int i = 0; i <= ClsGetDeviceMap.lstLongLatitude.Count - 1; i++)
{
string lat, lon;
lat = ClsGetDeviceMap.lstLatitude.ElementAt<string>(i).Trim();
lon = ClsGetDeviceMap.lstLongLatitude.ElementAt<string>(i).Trim();
Latitude = Convert.ToDouble(lat);
LongLatitude = Convert.ToDouble(lon);
GpsSpeed = 44.21811;
map1.Center = new GeoCoordinate(Latitude, LongLatitude, GpsSpeed);
map1.ZoomLevel = 17;
map1.ZoomBarVisibility = Visibility.Visible;
imglayer[i] = new MapLayer();
Image img = new Image();
img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/ReachMe;component/Images/mappinicn.png", UriKind.Relative));
img.Opacity = 0.8;
img.Stretch = System.Windows.Media.Stretch.None;
GeoCoordinate location = new GeoCoordinate() { Latitude = Latitude, Longitude = LongLatitude };
PositionOrigin position = PositionOrigin.Center;
imglayer[i].AddChild(img, location, position);
Pushpin pin = new Pushpin();
ToolTipService.SetToolTip(pin, "Pushpin 1\r\nThis is the first pushpin infobox.");
imglayer[i].Children.Add(pin);
map1.Children.Add(imglayer[i]);
myCoorditeWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
myCoorditeWatcher.MovementThreshold = 20;
var g1 = GestureService.GetGestureListener(imglayer[i]);
g1.Tap += new EventHandler<GestureEventArgs>(g1_Tap);
}
}
else// if error
{
MessageBox.Show("No Data Between This data");
// NavigationService.Navigate(new Uri("/ReachMeView/Login.xaml", UriKind.RelativeOrAbsolute));
}
}
catch (Exception ex)
{
Error.WriteErrorLog(ex.ToString(), "MainPage.xaml", "Data_WorkFinished");
}
}
void g1_Tap(object sender, GestureEventArgs e)
{
for (int i = 0; i <= ClsGetDeviceMap.lstLongLatitude.Count - 1; i++)
{
if (sender.Equals(imglayer[i]))
{
MessageBox.Show(ClsGetDeviceMap.lstLocationName.ElementAt<string>(i).Trim());
MessageBox.Show(ClsGetDeviceMap.lstLatitude.ElementAt<string>(i).Trim());
MessageBox.Show(ClsGetDeviceMap.lstLongLatitude.ElementAt<string>(i).Trim());
MessageBox.Show(ClsGetDeviceMap.lstDate.ElementAt<string>(i).Trim());
}
}
}
I did appreciate your help for my previous question , and i was wondering how to read data from an URI,using web service(let's assume it's the same data).
Here's the url link:
http://www.google.com/ig/api?weather=paris
I tryied with this code but it didn't work:
public MainPage()
{
InitializeComponent();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(download_string_complete);
wc.DownloadStringAsync(new Uri("http://www.google.com/ig/api?weather=hammamet", UriKind.Absolute));
}
public void download_string_complete(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ListBoxItem areaItem = null;
StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
string day = String.Empty;
string low = String.Empty;
string high = String.Empty;
string condition = String.Empty;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name=="forecast_conditions")
{
WeatherElement welement = new WeatherElement();
switch (reader.Name)
{
case ("day_of_week"):
{
day = reader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = day;
friendsBox.Items.Add(day);
} break;
case ("low"):
{
low = reader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = low;
friendsBox.Items.Add(low);
} break;
case ("high"):
{
high = reader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = high;
friendsBox.Items.Add(high);
} break;
case ("condition"):
{
condition = reader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = condition;
friendsBox.Items.Add(condition);
} break;
}
}
}
}
}
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
string Day = String.Empty;
string Low = String.Empty;
string High = String.Empty;
string ImageUri = String.Empty;
string Condition = String.Empty;
reader.MoveToContent();
while (reader.Read())
{
switch (reader.Name)
{
case ("day_of_week"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
Day = Content.ToString();
} break;
case ("low"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
Low = Content.ToString();
} break;
case ("high"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
High = Content.ToString();
} break;
case ("icon"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
Image wkpinImage = new Image();
wkpinImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://www.google.com" + Content, UriKind.Absolute));
wkpinImage.Opacity = 0.8;
wkpinImage.Stretch = System.Windows.Media.Stretch.None;
} break;
case ("condition"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
Condition = Content.ToString();
} break;
case("weather"):
break;
}
}
reader.Close();
}
}