How to call webservice methods in Windows Phone 7? - windows-phone-7

For connecting to webservices i wrote the following code.
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri("http://www.Webservices.asmx"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
void wc_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)
{
Debug.WriteLine("Web service says: " + e.Result);
using (var reader = new StringReader(e.Result))
{
String str = reader.ReadToEnd();
}
}
by using above code Get the string result.But i want get the result in HTMLVisulaizer then i know the what are the methods having that webservice.then i can easily access the particular method.
Please tell me how to call a web service method in Windows phone 7?in webservice i am having 5 webmethods.how to get that and how to call the Particular webmenthod.
Please tell me thanks in advance.

#venkateswara Are you talking about obtaining a list of known WebReference methods so you know which one to call in you code? Do you not see the this of known method calls when you add the WebReference to your WP7 project? Since you will be developing the WP7 app in VS I can't see the reason you would want to do this. Even if you don't own the webservice yourself, you will need to connect to it from VS in order to add the reference to your project.
Below is the screen in VS2010 where a WebReference is added. The Operations are listed on the right.
Once added you can use the ObjectBrowser to understand how the methods should be called.
Please let me know if I have missed something from your question.

#Jason James
The first step:
You must add referent Services ,like Jason James has very detailed instructions .
step 2 :
You can open App.xaml.cs , in Functions Apps
public Apps()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// You can declare objects here that you will use
//Examlpe: NameservicesReferent.(Function that returns services) = new NameservicesReferent.(Function that returns services)();
Ws_Function = new Nameservices.ServiceSoapClient();
}
step 3:
in Mainpage.xaml.cs
GlobalVariables.Ws_advertise.getLinkAdvertiseIndexCompleted += new EventHandler<advertise.getLinkAdvertiseIndexCompletedEventArgs>(Ws_advertise_getLinkAdvertiseIndexCompleted);
GlobalVariables.***NameWedservise***.getLinkAdvertiseIndexAsync("**parameters to be passed**");
step 4:
void Ws_advertise_getLinkAdvertiseIndexCompleted(object sender, advertise.getLinkAdvertiseIndexCompletedEventArgs e)
{
//function returns the results to you, the example here is an array
string[] array = null;
try
{
array = e.result;
if(array != null)
}
cath(exception ex)
{
}
finally
{
array = null;
GlobalVariables.Ws_advertise.getLinkAdvertiseIndexCompleted -= new EventHandler<advertise.getLinkAdvertiseIndexCompletedEventArgs>(Ws_advertise_getLinkAdvertiseIndexCompleted);
}
}

Related

IBM Lotus Notes Domino DLL

The Domino interop API which is included with Lotus Notes causes an out of memory exception in .NET when the NotesDXLExporter class based object fails to export the 390th record, which is a big document, after exporting 389 records (which are smaller documents).
Here is a code snippet:
I initialize the NotesDXLExporter class.
NotesDXLExporter dxl1 = null;
I then configure the NotesDXLExported object as shown below:
dxl1 = notesSession.CreateDXLExporter();
dxl1.ExitOnFirstFatalError = false;
dxl1.ConvertNotesbitmapsToGIF = true;
dxl1.OutputDOCTYPE = false;
I then perform a for a loop shown below in reading documents using the dxl1 class (line on which exception occurs is indicated below).
NotesView vincr = database.GetView(#"(AllIssuesView)"); //view from an NSF file
for (int i = 1; i < vincr.EntryCount; i++)
{
try
{
vincrdoc = vincr.GetNthDocument(i);
System.IO.File.WriteAllText(#"C:\Temp\" + i + #".txt", dxl1.Export(vincrdoc)); //OUT OF MEMORY EXCEPTION HAPPENS HERE WHEN READING A BIG DOCUMENT.
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
I have tried using a different version of the Interop domino dll and had had no success.
As I understand this, I see an API issue but I dont know if I am missing something?
Can you please shed some light on this?
Thanks in advance.
Subbu
You haven't said what version of the Lotus Notes you are working with. Given the history of DXL, I would say that you should try your code on the latest version of Notes that you possibly can.
But also, I don't see any calls to recycle(). Failure to call recycle() for Domino objects causes memory to leak from the Domino back end classes, and since you are running out of memory it could be contributing to your problem. You should also not use a for loop and getNthDocument. You should use getFirstDocument and a while loop with getNextDocument. You'll get much better performance. Putting these two things together leads you to the common pattern of using a temporary document to hold the result of getNextDocument, allowing you to recycle the current document, and then assign the temp document to the current, which would be something like this (not error-checked!)
NotesView vincr = database.GetView(#"(AllIssuesView)"); //view from an NSF file
vincrdoc = vincr.getFirstDocument();
while (vincrdoc != null)
{
try {
System.IO.File.WriteAllText(#"C:\Temp\" + i + #".txt", dxl1.Export(vincrdoc));
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Document nextDoc = vincr.getNextDocument(vincrdoc);
vincrdoc.recycle();
vincrdoc = nextDoc;
}

New Tile with special start of application in WP7

I've got question. I have application which is a phone book. I would like to create Tile (in Windows Phone main screen) which'll call that number after I click Tile on main screen.
Is that possible? What should I do to make something like that? I can create custom Tile or maybe I should create some method after my application start?
Create the live tile with something like the following code:
string number = "000 - 000 000";
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(t => t.NavigationUri.ToString().Contains("phone=" + number));
if (tile == null)
{
StandardTileData tileData = new StandardTileData();
tileData.Title = "Call " + number;
ShellTile.Create(new Uri("/MainPage.xaml?phone=" + number, UriKind.Relative), tileData);
}
And then override the OnNavigatedTo in MainPage.xaml, and add the following code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("phone"))
{
string number = NavigationContext.QueryString["phone"];
PhoneCallTask task = new PhoneCallTask();
task.PhoneNumber = number;
task.Show();
}
base.OnNavigatedTo(e);
}
If you have not done it yet, you also need to add the "ID_CAP_PHONEDIALER" capability in the WMAppManifest.xml file, or you will get an exception when calling task.Show(); above.
Now you got a live tile that when clicked will launch the application and call the number (The user must still confirm it in a dialog though, and that is something you can't disable)
Have you tried a flip tile and the using something like this:
http://blog.ecofic.com/?p=406
Write the number to isolated storage then when they click the tile you read the isolated storage and call the number.
You can also use the Mangopollo library from CodePlex to create a secondary live tile: http://mangopollo.codeplex.com/

C# WIA with Automatic Document Feeder (ADF) retuns only one page on certain scanners

I have a HP Scanjet 7000 (duplex & ADF scanner) and a HP Scanjet 5500c (only ADF) and a scanner program I'm developing which uses WIA 2.0 on Windows 7.
The problem is that the code works perfectly on the older scanner model, but on the newer one the code seems to run just fine through the first page, then fail on the second. If I step through the code around the following line;
image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);
the old scanner stops and waits for another call to be made on the same reference, but the newer one just runs through all it's pages from the feeder in one continuous operation.
I notice if I'm using the default scanning program in Windows 7, the newer one returns a single .tif file which contains all the separate pages. The older one returns separate .jpg files (one for each page).
This indicates to me that the newer scanner is scanning through its whole feeder before it is ready to return a collection of images where the older one returns ONE image between each page scanned.
How can I support this behavior in code? The following is part of the relevant code which works on the older scanner model:
public static List<Image> Scan(string scannerId)
{
List<Image> images = new List<Image>();
List<String> tmp_imageList = new List<String>();
bool hasMorePages = true;
bool useAdf = true;
bool duplex = false;
int pages = 0;
string fileName = null;
string fileName_duplex = null;
WIA.DeviceManager manager = null;
WIA.Device device = null;
WIA.DeviceInfo device_infoHolder = null;
WIA.Item item = null;
WIA.ICommonDialog wiaCommonDialog = null;
manager = new WIA.DeviceManager();
// select the correct scanner using the provided scannerId parameter
foreach (WIA.DeviceInfo info in manager.DeviceInfos)
{
if (info.DeviceID == scannerId)
{
// Find scanner to connect to
device_infoHolder = info;
break;
}
}
while (hasMorePages)
{
wiaCommonDialog = new WIA.CommonDialog();
// Connect to scanner
device = device_infoHolder.Connect();
if (device.Items[1] != null)
{
item = device.Items[1] as WIA.Item;
try
{
if ((useAdf) || (duplex))
SetupADF(device, duplex); //Sets the right properties in WIA
WIA.ImageFile image = null;
WIA.ImageFile image_duplex = null;
// scan image
image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);
if (duplex)
{
image_duplex = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatPNG, false);
}
// save (front) image to temp file
fileName = Path.GetTempFileName();
tmp_imageList.Add(fileName);
File.Delete(fileName);
image.SaveFile(fileName);
image = null;
// add file to images list
images.Add(Image.FromFile(fileName));
if (duplex)
{
fileName_duplex = Path.GetTempFileName();
tmp_imageList.Add(fileName_duplex);
File.Delete(fileName_duplex);
image_duplex.SaveFile(fileName_duplex);
image_duplex = null;
// add file_duplex to images list
images.Add(Image.FromFile(fileName_duplex));
}
if (useAdf || duplex)
{
hasMorePages = HasMorePages(device); //Returns true if the feeder has more pages
pages++;
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
wiaCommonDialog = null;
manager = null;
item = null;
device = null;
}
}
}
device = null;
return images;
}
Any help on this issue would be very much appreciated! I can't seem to find a working solution on the web. Just unanswered forum posts from people with the same problem.
we had a very similar problem and various solutions, e.g. by setting certain properties, did not help. The main problem was that the scanner (ADF) retracted all pages on startup, regardless of what was happening in the program code.
The process repeatedly led to errors, since "too much" was made before the next page was scanned. This applies in particular to the fact that another "Connect" was attempted.
For this reason, we have modified the code so that the individual pages can be read in as quickly as possible:
public List<Image> Scan(string deviceID)
{
List<Image> images = new List<Image>();
WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
WIA.Device device = this.Connect(deviceID);
if (device == null)
return images;
WIA.Item item = device.Items[1] as WIA.Item;
List<WIA.ImageFile> wiaImages = new List<ImageFile>();
try
{
// scan images
do
{
WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
wiaImages.Add(image);
} while (true);
}
catch (System.Runtime.InteropServices.COMException ex)
{
if ((uint)ex.ErrorCode != WIA_PROPERTIES.WIA_ERROR_PAPER_EMPTY)
throw ex;
}
catch (Exception ex)
{
throw ex;
}
foreach (WIA.ImageFile image in wiaImages)
this.DoImage(images, image);
return images;
}
I see you're calling a method called SetupADF, which is not shown, that presumably sets some properties on the device object. Have you tried setting WIA_DPS_PAGES (property 3096) and/or WIA_DPS_SCAN_AHEAD_PAGES (property 3094)?
I have a blog post about scanning from an ADF in Silverlight, and I believe a commenter came up against the same issue you're having. Setting WIA_DPS_PAGES to 1 fixed it for him. I ended up modifying my code's SetDeviceProperties method to set WIA_DPS_PAGES to 1 and WIA_DPS_SCAN_AHEAD_PAGES to 0.
After alot of trial and error I stumbled upon a solution which worked for reasons I'm not quite sure of. It seems like the ShowTransfer() method was unable to convert the page to .png or .tiff WHILE scanning. Setting the format to JPEG or BMP actually solved the issue for me:
image = (ImageFile)scanDialog.ShowTransfer(item, wiaFormatJPEG, false);
I think I saw somewhere on the web that this method actually returns BMP regardless of the format specified. Might be that converting the image to png or tiff is too heavy as opposed to using bmp or jpeg.
On a sidenote, I'm setting the property setting: 3088 to 0x005 (adf AND duplex mode).

How to pull the finalUri property from an async image lookup result?

In windows phone 7 I'm doing a simple async lookup to find an image by uri and set the returned binary as the source for an image control.
public object SetImageFromUri(string uri)
{
var wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(uri), wc);
return null;
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
var image = new BitmapImage();
image.SetSource(e.Result);
//e.Result has a property in the memory stream labeled finalUri
//someImageControl.Source = image;
}
}
My question is- how can I pull out the final uri property from the e.Result so I can see what image control it's associated with
Thank you in advance
Instead of passing the WebClient through as the second parameter, pass the Uri (or some other piece of usefule state information)
wc.OpenReadAsync(new Uri(uri), uri);
You can then access this in your callback
var uri = (string)e.UserState;
Due to specific restrictions implemented in the Reflection mechanism, you cannot access internal content from sandboxed code. Ultimately, you would want to use something like this:
FieldInfo f = e.Result.GetType().GetField("_finalUri", BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);
Uri n = (Uri)f.GetValue(e.Result);
However, this will cause a FieldAccessException. If you are not using a redirect URI, then you can simply reuse the parameter that is initially passed to your method. If not, you need to check HttpWebRequest and follow the idea I outlined a couple of days ago.
You could also just bind directly to the Image, and use the LowProfileImageLoader, to avoid it blocking the UI thread during the load. (Remember to set a FallBack image)

wp7: App failing! Can not figure out where?

I think I've narrowed it down to this code in the Deactivation event:
Here's the thing... When I put a break point in this code everything works fine. The application does NOT fail. However, when I take the break point off it fails. What I don't understand is why the try/catch isn't firing.
I should also note that I commented everything out of this event with no break point and the application worked fine. So it is something in this code...
Could it be that the Save Event is not finished for the unsaved object and when it tries to reactivate the Activation event is actually the one failing???
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//MessageBox.Show("deactivated");
try
{
//if ((Application.Current as App).infoSaved == false)
//{
unsaved unSavedPillInfo = new unsaved();
unSavedPillInfo.RXName = (Application.Current as App).appRXName;
unSavedPillInfo.RXNumber = (Application.Current as App).appRXNumber;
unSavedPillInfo.DosageNotes = (Application.Current as App).appDosageNotes;
unSavedPillInfo.Generic = (Application.Current as App).appGeneric;
unSavedPillInfo.Instructions = (Application.Current as App).appInstructions;
unSavedPillInfo.Reason = (Application.Current as App).appReason;
unSavedPillInfo.Quantity = (Application.Current as App).appQuantity;
unSavedPillInfo.Refills = (Application.Current as App).appRefills;
unSavedPillInfo.Doctor = (Application.Current as App).appDoctor;
unSavedPillInfo.DoctorNumber = (Application.Current as App).appDoctorNumber;
unSavedPillInfo.Pharmacy = (Application.Current as App).appPharmacy;
unSavedPillInfo.PharmacyNumber = (Application.Current as App).appPharmacyNumber;
unSavedPillInfo.OrigDate = (Application.Current as App).appOrigDate;
unSavedPillInfo.ReorderReminder = (Application.Current as App).appReorderReminder;
unSavedPillInfo.ReorderDate = (Application.Current as App).appReorderDate;
unSavedPillInfo.ConsumptionFrequency = (Application.Current as App).appConsumptionFrequency;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).perscriptionUpdated;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).doctorUpdated;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).detailsUpdated;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).pharmacyUpdated;
unSavedPillInfo.Save();
//}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
This is hardly perfect but try putting a Messagebox inside of each of the eventhandlers. That way you can tell when each one is firing and see if one isn't firing.
Also you might want to unistall the application often to clear the IsolatedStorage. This is known to create issues if you keep running on the same installation.
EDIT: Yeah from what I have run into, the application can hang if you aren't properly saving to isolated storage. It can also happen if you aren't properly loading data from isolated storage. You might want to try each one seperately. Use a messagebox to make sure it saves and loads properly because VisualStudio will exit the current debugging session.
UPDATE What you should do is create a global variable called unsavedPrescription. Now when the user selects a prescription assign the global variable "unsaved" the prescription they selected. Note: you should not be assigning properties when the app is deactivating because it is very possible it won't save completely which leads to the app hanging. Instead all you have to do is assign the selected prescription to the global variable and change your code in App.xaml.cs to the following:
public unsaved unsavedPrescription {get; set;}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//Open up IsolatedStorageSettings
IsolatedStorageSettings settings = Isolated StorageSettings.ApplicationSettings;
//Use a model to save prescription
//So create a name/value pair to store the prescription in isolatedstorage
//Notice we used the global variable
settings["UnsavedPrescription"] = unsavedPrescription;
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
//Now you can easily load the prescription you saved
//I'm reassigning the global variable that will contain the savedprescription
if(settings.TryGetValue("UnsavedPrescription", out prescription)
{
unsavedPrescription = prescription;
}
}
This greatly simplifies your code when loading and saving. Also you'll be able to test using the messageboxes like I said earlier, which isn't professional but it works nicely. Also your not running too much stuff when the app is trying to deactivate. THIS WAY WILL WORK AS I TESTED IT. The way you did it above looks like your running to much code while the app is deactivating which is probably why its hanging. Also this explains why when you remove it, everything works.
I had a problem that seems similar to yours that wasn't actually related to the Saving/Loading from IsolatedStorage itself, but rather the property I was setting / getting had inifinite recursion. This caused the application to terminate before getting to Catch statements.
It might be worthwhile for you to turn off the Debugger stepping over Properties:
Tools -> Options -> Debugger -> Step over Properties and Operators (Managed Only)
public Dictionary<string, object> Dictionary
{
get
{
if (_dictionary == null)
_dictionary = new Dictionary<string, object>();
return _dictionary;
}
set
{
Dictionary = value;
}
}
App Never launches successfully again after Tombstoning. No exception thrown

Resources