Showing posts with label service. Show all posts
Showing posts with label service. Show all posts

Monday, March 26, 2012

Intercept Exceptions

I was wanting to trap Exceptions that occur in a Web Service, adjust the message (make sure stack trace does not get sent (I know about CustomErrors in web.config)) and put the message in a log.

I found out about SoapExtensions and created such, but just was not able to reach any breakpoints. I then read that I wouldn't reach it unless through a Soap request. So I used WebServiceStudio.exe and hit those breakpoints.

Well, when using Atlas, the full exception was being sent without running through the SoapExtension. I assume now that xmlhttp uses Post requests. Then in web.config WebServices node, I cleared the protocols and added only the Soap protocols... interesting thing is Atlas still called the web service and got the thrown error returned. That made me think it used Soap, but it still never hit the SoapExtension.

Could somebody clear up this confusion? I assume there must be a way to globally intercept Web Service errors. For Web Applications, I use global.asax Application_Error.

Nathan

Atlas does not use SOAP. It uses REST and the serialization method is JSON. Atlas has a custom HTTP Handler for .asmx files, which you can see in your wen.config file. When an Atlas script requests a web service, a special query string parameter named "mn" is appended to the url. The server side web service checks the presense of this parameter and and if it is present it uses custom processing bu Atlas otherwise it uses the default web service handler.The normal processing, which you expect when you call a web service like soap extension execution etc. no longer happens because of the Atlas custom handler. The Atlas custom handler directly catches the excpetion from the web service method and reports to the client, when the web service is invoked from an Atlas script. There is only one option currently (may change in future) and that is to handle the exceptions in the web service methods themshelves. I do not think that there is any global exception hooking mechanism you can use for Atlas.

Saturday, March 24, 2012

InvalidOperationException : Request format is invalid : application/json charset=utf - 8

Can anybody help me guys with this one,

I'm tryng to invoke a web method in my web service from javascript but i keep on getting javascript response Error stating that my webmethod couldn't execute because of this Error (InvalidOperationException : Request format is invalid : application/json charset=utf - 8 )

here is my logic for my web service

[ScriptService]
[WebService(Namespace = "http://www.wipspace.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class svrCreateReal : System.Web.Services.WebService
{
private clsLibraryFile objF;
private clsWipReel objWipR;


public svrCreateReal ()
{
objF = new clsLibraryFile();
objWipR = new clsWipReel();
}

[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public int createReelfileCollection(string reelID, string menuID, string fileID )
{
try
{
objWipR.reelID = Convert.ToInt32(Server.HtmlEncode(reelID));
objWipR.reelMenuID = Convert.ToInt32(Server.HtmlEncode(menuID));
objF.fileID = Convert.ToInt32(Server.HtmlEncode(fileID));
return objWipR.createReelMovieCollection(objWipR, objF);
}
catch
{
return -1;
}

}

From my aspx page i call a javascript function that invokes the web method like below

<asp:ScriptManager ID="scriptManager"
runat="server" >
<Services>
<asp:ServiceReference InlineScript="true" Path="adminWipService/svrCreateReal.asmx" />
</Services>
</asp:ScriptManager>

<script type="text/javascript">

function createReel( sender, e )
{
var container = e.get_container();
var item = e.get_droppedItem();
var position = e.get_position();
var fileID = parseInt(item.getAttribute("fileID"));
var menuID = parseInt(container.getAttribute("MenuID"));
var row = position;

var created = svrCreateReal.createReelfileCollection(6, menuID, fileID);

alert(created );

}

thnks very much in advance

cheers

Pay attention on Web.config of your application. It have to contain some declarations. Similarly to it:

-----

<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections
<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="false">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web
<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "true|false"/>
--
<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>
</system.web.extensions
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated" />
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
</system.webServer>
</configuration>

Invoke ModalPopupExtenders .Show() method within javascript code

Hi,

A colleague wrote an extender to validate an address (street name & postal code). He uses a web service for that BUT he didn't write the necessary code in the _onMethodFailed method !

In this method I woud like to display a popup containing 'yes' and 'no' buttons (to ask the customer if he wants to keep the wrong values or no).

Currently, I have an asp:panel with a ModalPopupExtender (which ID is 'AddressErrorPopup') linked on it.

So, in the address validation extender I would like to do something like that :

_onMethodFailed: function(err, response, context) { if (this._popupValue) { var popupExtender = $get(this._popupValue); if (popupExtender) popupExtender.Show(); }}


the _popupValue variable contains 'AddressErrorPopup' : the ID of the ModalPopupExtender.

Problem : the $get(this._popupValue) returns null...

Is there a way to invoke the Show() method of a ModalPopupExtender in the javascript code of an other extender on the same form ?

Thx for your answer...

You need to use $find instead of $get to locate ajax controls. $get is for DOM elements.

Also, make sure that the modalpopup has BehaviorID="AddressErrorPopup" as the actual client ID may be different depending on the naming container hierarchy. Store the BehaviorID in the _popupValue property and then you should find the popup OK regardless of the naming container.


Ok !

Thank you for your help, this is exactly what I needed.

I'm not good at javascript/ajax, sorry for thatConfused


No need to be sorry...that's an easy mistake to make. Working with the ajax toolkit, you will become good at javascriptSmile

Invoking a Web Service through JavaScript

Hi,

I keep getting the 'WebService is undefined' error when I try to

access my Web Service through JavaScript. I have made all necessary changes -added handlers to

the web.config file, included the DLL in the bin directory, included referernce through the

<ScriptManager> tag...

<atlas:ScriptManager ID="ScriptManager" runat="server" enablepartialrendering="true">
<Services>
<atlas:ServiceReference Path="/TestAJAXApp/MyWebService.asmx" />
</Services>
</atlas:ScriptManager>

<script type ="text/javascript">
function MyCustomFunction(MyRecordID, event)
{
var result = MyWebService.GetRecordDescription(MyRecordID, GetCallBack);
}
function GetCallBack(result)
{
Popup('Description' , result.value, false);
}
</script>

What could I be missing? Any suggestions appreciated.

Thanks!

The first thing to double check, is whether the request for the webservice proxy succeeded or not, use fiddler or whatever your favorite http traffic monitoring tool is, and verify that there indeed is a request to an url like /TestAJAXApp/MyWebService.asmx/js and that the response of that is the client javascript proxy for your webservice. My guess is that is failing in some way, and hopefully that will lead you to the problem...

Hope that helps,
-Hao

Is a WebService a Place to Put General Support Routines?

Let's assume that I am developing several different projects for different clients. Along the way, I may come up with "service routines" which can be generalized (such as recording some progresss or other info in a database table common to all of the different clients -- separately, of course).

If a WebService a good place to place these? Assuming that everything (database connection, etc.) can be passed in, would there be any reason why such a "service package" shouldn't be deployed in this way?

Hints, suggestions appreciated ... :) KevInKauai

Technically, you can, but unless you have a distributed system what does it gain you?

Why not write a common data layer component to use in all of your projects? This will give you the advantage of re-use without impact on performance.

Web services are very useful, but I doubt if they are necessary in your scenario.


Still not clear about the resusablity issue, Are planning to consume the WebService from all client ajax application?

Wednesday, March 21, 2012

Is AutoCompletes ContextKey property useless....?

.....or is it just me? I tried using this property, and yes, the string does get passed to the web service method. However, when I check HttpContext.Current.Items, any objects which had previously been added to the Items collection no longer exist. Even HttpContext.Current.Session is null. This makes sense because, with each user keypress, a new HttpContext is created to invoke the web method.

There seem to be no events that can be handled before the web method is invoked. So my question is, exactly what functionality, aside from allowing a user to pass an additional string paramter to the web method, does this property provide? If there's a configuration setting I need to change, or if I'm going about this in totally the wrong way, someone please tell me! I'm using build 10618 of the toolkit.

Thanks,

Dan

Hi Danludwig,

Sometimes we want to send back more parameters instead of the TextBox's value only. For example, if one WebMethod services serverl AutoCompleteExtenders, we need more parameters to Distinguish different Controls or useages. We can past more parameters by using ContextKey. For example: "parameter1, parameter2,parameter3...";

To set its ContextKey, we can use $find("AutoCompleteExtenders.BehaviorID").set_contextKey("your parameters"); Here is the sample.

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"></script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title> <style> .AutoExtender { font-family: Verdana, Helvetica, sans-serif; font-size: .8em; font-weight: normal; border:solid 1px #006699; line-height:20px; padding:2px; background-color:White; } .AutoExtenderList { border-bottom:dotted 1px #006699; cursor:pointer; color:Maroon } .AutoExtenderHighlight { color:White; background-color:#006699; cursor:pointer; } </style></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:TextBox ID="TBSearch" runat="server"></asp:TextBox> <asp:Panel runat="server" ID="myPanel" Height="100px" ScrollBars="Vertical"> </asp:Panel> <ajaxToolkit:AutoCompleteExtender runat="server" ID="autoComplete1" BehaviorID="myACEBID" TargetControlID="TBSearch" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionListCssClass="AutoExtender" CompletionListItemCssClass="AutoExtenderList"
 CompletionListHighlightedItemCssClass="AutoExtenderHighlight" CompletionInterval="1" EnableCaching="true" CompletionSetCount="12" CompletionListElementID="myPanel"UseContextKey="true" ContextKey="Jonathan"/> <br/><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <input id="Button1" type="button" value="button" onclick="changeContextKey()"/> <script type="text/javascript" language="javascript"> function changeContextKey(){ $find("myACEBID").set_contextKey('tommy'); } </script> </form></body></html>

<%@. WebService Language="C#" Class="AutoComplete" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

public AutoComplete()
{
}

[WebMethod]
public string[] GetCompletionList(string prefixText, int count, string contextKey)
{
//do something on contextKey to get the parameters.
if (count == 0)
{
count = 10;
}

if (prefixText.Equals("xyz"))
{
return new string[0];
}

Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char)random.Next(65, 90);
char c2 = (char)random.Next(97, 122);
char c3 = (char)random.Next(97, 122);

items.Add(prefixText + c1 + c2 + c3);
}

return items.ToArray();
}

}

I hope this help.

Best regards,

Jonathan

Is it a bug? you can try it.

I found a problem in Web Service when I use Asp.Net Ajax rc1.
runhttp://localhost/Website1/WebService1.asmx, Call SetValue() , then GetValue(). You will find an exception.
That's too strange. why is NHibernate?

using System.Web.Script.Services;
using NHibernate;
using NHibernate.Cfg;

[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public void SetValue(string value)
{
// If I run it here, the Session["SESSION1"] in GetValue() will return null;
NHibernate.Cfg.Configuration _cfg = new NHibernate.Cfg.Configuration();

Session["SESSION1"] = value;
}

[WebMethod(EnableSession = true)]
public string GetValue()
{
return Session["SESSION1"].ToString();
}
}

web.config:
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>

Do you mean to say if you include the NHibernate line, Session["Session1"] returns null? What happens if you remove that line? Also are you sure that you are accessing the session variable after you have set it?
Yes, if I remove that NHibernate line, all the things are working well. I tried it many times.
I can't use NHibernate in Asp.Net Ajax? I am almost crazy these days.
I've found why the session will be lost. I have a global.asa file. And I write:
void Application_Start(object sender, EventArgs e)
{
log4net.Config.DOMConfigurator.Configure();
}
and each time I call web method, the application will restart ( seems in compiling again ). That's why the session will be cleaned.

But I still don't know why the Application will restart each time? And if I delete that line in Application_Start, everything works well.

I am using Visual Web Developer 2005, and the solution will not compile to a dll.

hello.

just a guess: does the configure methodf loads the config fromthe web.config file? if so, try changing it to an external file (i'm thinking that maybe it may be changing the web.config file while it reads it and this will definitly restart your web app).


No, I didn't change web.config file while I call these 2 method.
I am using visual web develop 2005 express. and all the code wouldn't be compiled to a dll, so I don't know when the code will be compiled if I call a web service method.