I'm developing a plugin were i have done something like this code
[ChildActionOnly]
[HttpPost,ActionName("Configure")]
[FormValueRequired("test")]
public ActionResult TestSms(SmsRobiModel model)
{
bd.com.robi.bmpws.CMPWebService objCmpService = new bd.com.robi.bmpws.CMPWebService();
bd.com.robi.bmpws.ServiceClass sc = objCmpService.SendTextMessage("username", "password", "sendernumber", "receivernumber", "test msg");
}
but I get an error on this line and here is the error:
bd.com.robi.bmpws.ServiceClass sc = objCmpService.SendTextMessage("username", "password", "sendernumber", "receivernumber", "test msg");
Getting an error when try to consume soap service from nopCommerce.
I am trying to develop a SMS plugin in nopCommerce. I did everything for
a plugin but the sms send method is not functioning.
A SMS provider give me a soap service URL. I added it into my class library project, build it and install it in nopCommerce.
I am getting this error:
System.Net.WebException: The request failed with an empty response. at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at Nop.Plugin.SMS.Robi.bd.com.robi.bmpws.CMPWebService.SendTextMessage(String Username, String Password, String From, String To, String Message) at Nop.Plugin.SMS.Robi.SmsRobiProvider.SendSms(String text, Int32 orderId, SmsRobiSettings settings) at Nop.Plugin.SMS.Robi.OrderPlacedEventConsumer.HandleEvent(OrderPlacedEvent eventMessage) at Nop.Services.Events.EventPublisher.PublishToConsumer[T](IConsumer`1 x, T eventMessage) in d:\MahadyLiveProjects\eshoptest\Libraries\Nop.Services\Events\EventPublisher.cs:line 40
Related
When the token is expired or tampered token is passed to call an api in postman, I get exception as mentioned below. Now how to return this as proper response is my concern in asp.net core.
Token expired:
Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: 'System.DateTime', Current time: 'System.DateTime'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
Token tampered and passed:
System.ArgumentException: IDX12729: Unable to decode the header 'System.String' as Base64Url encoded string. jwtEncodedString: 'System.String'.
---> System.FormatException: IDX10400: Unable to decode: 'System.String' as Base64url encoded string.
at Microsoft.IdentityModel.Tokens.Base64UrlEncoder.DecodeBytes(String str)
at Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Decode(String arg)
at System.IdentityModel.Tokens.Jwt.JwtHeader.Base64UrlDeserialize(String base64UrlEncodedJsonString)
at System.IdentityModel.Tokens.Jwt.JwtSecurityToken.Decode(String[] tokenParts, String rawData)
--- End of inner exception stack trace ---
at System.IdentityModel.Tokens.Jwt.JwtSecurityToken.Decode(String[] tokenParts, String rawData)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ReadJwtToken(String token)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
The above mentioned problems are handled after adding the following,
image link
Now iam facing with new exceptionimage link
You can re-install the Newtonsoft.Json library via Nuget. Or adding the Newtonsoft.Json dll to your project, it will fix the issue.
The proper response from the API is to always return a 401 Unauthorized status code regardless if the token is expired or invalid/tampered. That is all that the client should care about.
Returning to detailed information about why it failed can actually help the attacker.
I have already connected d365 CRM online with the .net core console app using client id, clients secret, and organization URI. But it is throwing an error on connecting with on-prem.
here is the error.
Microsoft.PowerPlatform.Dataverse.Client.Utils.DataverseConnectionException
HResult=0x80131500
Message=Failed to connect to Dataverse
Source=Microsoft.PowerPlatform.Dataverse.Client
StackTrace:
at Microsoft.PowerPlatform.Dataverse.Client.ServiceClient.CreateServiceConnection(Object externalOrgServiceProxy, AuthenticationType requestedAuthType, String hostName, String port, String orgName, NetworkCredential credential, String userId, SecureString password, String domain, String Geo, String claimsHomeRealm, Boolean useSsl, Boolean useUniqueInstance, OrganizationDetail orgDetail, String clientId, Uri redirectUri, PromptBehavior promptBehavior, OrganizationWebProxyClient externalOrgWebProxyClient, String certificateThumbPrint, StoreName certificateStoreName, X509Certificate2 certificate, Uri instanceUrl, Boolean isCloned, Boolean useDefaultCreds, Version incomingOrgVersion, ILogger externalLogger)
at Microsoft.PowerPlatform.Dataverse.Client.ServiceClient..ctor(Uri instanceUrl, String clientId, String clientSecret, Boolean useUniqueInstance, ILogger logger)
at DOHTestCoreConApp.Program.crmConnection() in C:\DOH PRP\Code\DOHTestCoreConApp\DOHTestCoreConApp\Program.cs:line 23
at DOHTestCoreConApp.Program.Main(String[] args) in C:\DOH PRP\Code\DOHTestCoreConApp\DOHTestCoreConApp\Program.cs:line 11
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
AggregateException: One or more errors occurred. (Need a non-empty authority (Parameter 'Authority'))
Inner Exception 2:
ArgumentNullException: Need a non-empty authority (Parameter 'Authority')
here is the code
string SoapOrgServiceUri = "http://crm/XRMServices/2011/Organization.svc";
Uri serviceUri = new Uri(SoapOrgServiceUri);
string client_id = "****";
string client_sec = "****";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cdsClient = new ServiceClient(serviceUri, client_id, client_sec, true);
On prem doesn't use the azure ad client id / secret.
You will need to use an ad account.
See https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/active-directory-claims-based-authentication
I was able to connect d365 CRM on-prem with my .net core app using Odata Client.
here is the link to it https://learn.microsoft.com/en-us/odata/client/getting-started
In my app,I use springMVC and tomcat,my controller return object,but when something wrong,I only want return some string message with content tye json,so I use response.error, but it not work,the return is a html.
my controller:
#RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody UserBean login(#PathVariable String id,#PathVariable("name") String userName,
#RequestHeader(value = "User-Agent") String user_agen,
#CookieValue(required = false) Cookie userId,
HttpServletRequest request,HttpServletResponse response,#RequestBody UserBean entity
) throws IOException {
System.out.println("dsdsd");
System.out.print(userName);
response.setContentType( MediaType.APPLICATION_JSON_VALUE);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "somethind wrong");
return null;
According to the Javadoc for the HttpServletReponse#sendError method:
Sends an error response to the client using the specified status. The
server defaults to creating the response to look like an
HTML-formatted server error page containing the specified message,
setting the content type to "text/html", leaving cookies and other
headers unmodified...
So sendError will generate an HTML error page using the message that you supplied and will override the content type to text/html.
Since the client end is expecting a JSON response, you may be better to manually set the response code and the message yourself using fields on your UserBean - assuming it can support it. That will then be serialized to a JSON response that your clientside Javascript can evaluate.
#RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody UserBean login(#PathVariable String id,#PathVariable("name") String userName,
#RequestHeader(value = "User-Agent") String user_agen,
#CookieValue(required = false) Cookie userId,
HttpServletRequest request,HttpServletResponse response,#RequestBody UserBean entity
) throws IOException {
System.out.println("dsdsd");
System.out.print(userName);
response.setContentType( MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
UserBean userBean = new UserBean();
userBean.setError("something wrong"); // For the message
return userBean;
There is also the option of using the Tomcat property org.apache.coyote. USE_CUSTOM_STATUS_MSG_IN_HEADER which will place the message into a custom response header. See this post and the Tomcat docs for more info.
I'm using an app_offline.htm file as described here : http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx to take an old asmx web service offline.
All works fine, and the client end gets a HTTP 503 exception like :
Exception : System.Net.WebException
The request failed with HTTP status 503: Service Unavailable.
Source : System.Web.Services
Stack trace :
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
My question : is it possible for the client application to read the contents of the app_offline.htm file which would have been returned ? The basic HTML in that file has helpful text like : "The application is currently undergoing maintenance". I can see the contents of this file being returned in the response using Fiddler.
It would be useful to be able to parse this html response to provide more info to the user. (i.e. so it is possible to distinguish between a 503 error due to system maintenance, and other 503s due to system being overloaded etc).
EDIT : BluesRockAddict's response sounded good, but the stream seems to be unavailable at this time. e.g. :
// wex is the caught System.Net.WebException
System.Net.WebResponse resp = wex.Response;
byte[] buff = new byte[512];
Stream st = resp.GetResponseStream();
int count = st.Read(buff, 0, 512);
The last line above which attempts to read the stream gives :
Exception : System.ObjectDisposedException
Cannot access a closed Stream.
Source : mscorlib
Stack trace :
at System.IO.__Error.StreamIsClosed()
at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
credit goes to BluesRockAddict, adding to his answer, this is how you can read the content of html page.
catch (WebException ex)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.ServiceUnavailable)
{
using (Stream stream = ex.Response.GetResponseStream())
{
using(StreamReader reader = new StreamReader(stream))
{
var message = reader.ReadToEnd();
}
}
}
}
You should use WebException.Response to retrieve the message:
using (WebClient wc = new WebClient())
{
try
{
string content = wc.DownloadString(url);
}
catch (WebException ex)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.ServiceUnavailable)
{
message = ex.Response
}
}
}
I have asked the same question at http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/d5d00302-8f7b-4efc-873b-c54b3e29749d but didn't get an answer. So, I will give another try at stackoverflow.
I was running the example code from the crm 2011 training kit.
var creds = new ClientCredentials();
var dsp = new DiscoveryServiceProxy( dinfo, creds);
dsp.Authenticate();
var orgRequest = new RetrieveOrganizationRequest();
var response = dsp.Execute(orgRequest);
var orgResponse = response as RetrieveOrganizationsResponse;
if (orgResponse != null)
comboOrgs.ItemsSource = orgResponse.Details;
At the line of var response = dsp.Execute(orgRequest), I got the FaltException`1, the detailed message is as follows
System.ServiceModel.FaultException`1 was unhandled
Message=organizationName
Source=mscorlib
Action=http://schemas.microsoft.com/xrm/2011/Contracts/Discovery/IDiscoveryService/ExecuteDiscoveryServiceFaultFault
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
at Microsoft.Xrm.Sdk.Client.DiscoveryServiceProxy.Execute(DiscoveryRequest request)
I was able to access the Discovery.svc file using browser. So the server url should be correct. Is this an authentication problem?
Is this for Microsoft CRM Online or on-premise? For Online, I know you would want to use something along the lines of what is found in the SDK -
// Connect to the Discovery service.
// The using statement assures that the service proxy will be properly disposed.
using (DiscoveryServiceProxy _serviceProxy = new DiscoveryServiceProxy(serverConfig.DiscoveryUri,
serverConfig.HomeRealmUri,
serverConfig.Credentials,
serverConfig.DeviceCredentials))
{
// You can choose to use the interface instead of the proxy.
IDiscoveryService service = _serviceProxy;
#region RetrieveOrganizations Message
// Retrieve details about all organizations discoverable via the
// Discovery service.
RetrieveOrganizationsRequest orgsRequest =
new RetrieveOrganizationsRequest()
{
AccessType = EndpointAccessType.Default,
Release = OrganizationRelease.Current
};
RetrieveOrganizationsResponse organizations =
(RetrieveOrganizationsResponse)service.Execute(orgsRequest);
}
There are overloads for the DiscoveryServiceProxy class but if you provide some more details on what you are trying to connect to, I think it will narrow it down.