best way to access database using SOAP - c#

I am currently working to understand SOAP protocol with C#, I find some examples in Google and understand the envelope, header, body.
I authenticate with the webservice but I want to know where can I to implement a class or method to access a database with the user and password provided, I mean, soap header has user="john" pass="odos223kiwi0X" the server received the header, now access to database with the user provided and check the password.
if a right option create a custom method in the soap Class to do it?

you can create a class just as the following :
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.Web.Services;
using System.Net;
[System.Web.Services.WebServiceBindingAttribute(
Name = "FunctionName",
Namespace = "nameSpace")]
public class ClassName:
System.Web.Services.Protocols.SoapHttpClientProtocol
{
public ClassName(string uri) // Constractor
{
this.Url = uri; // the full path for your server we will make later on in the answer
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute(
"nameSpace/ClassName",
RequestNamespace = "nameSpace",
ResponseNamespace = "nameSpace",
Use = System.Web.Services.Description.SoapBindingUse.Literal,
ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public object[] FunctionName(string Parameter1)
{
object[] results = { };
try
{
results = this.Invoke("FunctionName", new object[] { Parameter1});
return ((object[])(results[0]));
}
catch (Exception error)
{
object[] webException = { -1, error.Message };
return (webException);
}
}
}
and now we create the asmx service:
create a web service and add this under the namespace :
[WebService(Namespace = "NameSpace")] //same namespace you wrote in the class
then add your function and Object[] as returning value.
[WebMethod]
public object[] FunctionName(string Parameter1) // function name and parameters should be the same in your class where you called the web service (case sensitive)
{
... // your code
}
** you can download http://www.fiddler2.com/fiddler2/version.asp that will allow you to see and trace the out going requests
please send me back if you need any farther info.

Related

How to return a JSON from WebAPI using http request?

I'm trying to implement a new web API. This API returns a JSON from HTTP-request.
So far I wrote very basic code, but the strange thing is that I get an error using XML template - and I have no idea what to do:
This is the call: http://localhost:55643/api/ShipmentsStatus/getShipmentsStatusJSON
The code is here:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RunCom.WebAPI.Controllers
{
[Route("api/[controller]")]
public class ShipmentsStatusController : ApiController
{
// /api/ShipmentsStatus/getShipmentsStatusJSON
public ShipmentsStatusController()
{
int i = 0;
}
[HttpGet]
[Route("getShipmentsStatusJSON")]
public IEnumerable<String> Get()
{
test check = new test("1");
yield return JsonConvert.SerializeObject(check);
}
}
internal class test
{
string key;
public test(string k)
{
key = k;
}
}
}
The error I got is here:
<Error>
<Message>No HTTP resource was found that matches the request URI
'http://localhost:55643/api/ShipmentsStatus/getShipmentsJSON'.</Message>
<MessageDetail>No action was found on the controller 'ShipmentsStatus' that matches the request.</MessageDetail>
</Error>
What is wrong with my code?
Try to fix the route
[Route("~/api/ShipmentsStatus/GetShipmentsStatusJSON")]
public IEnumerable<string> Get()
{
return new List<string> {"1","2","3"};
}
You should use http://localhost:55643/api/ShipmentsStatus/getShipmentsStatusJSON or change [Route("getShipmentsStatusJSON")] to the appropriate API method name

Microsoft Computer Vision API returning 404 Resource Not Found

I tried to call Azure's Computer Vision API using the C# code below but got the following response:
{"code":"404","message":"Resource not found"}
Any advice to get this work?
using System;
using System.IO;
using System.Threading.Tasks;
using AzureFunctions.Extensions.CognitiveServices.Bindings.Vision.Analysis;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Table;
namespace myCognitiveFunction
{
public static class myCognitiveFunction
{
[FunctionName("myCognitiveFunction")]
public static async Task RunAsync(
[BlobTrigger("images/{name}", Connection = "storageAccount")]Stream myBlob,
[VisionAnalysis(VisionKey = "Key", VisionUrl = "Url")]VisionAnalysisClient visionClient,
[Table("VisionAnalysis", Connection = "storageAccount")]IAsyncCollector<VisionResult> results,
string name, ILogger log)
{
var request = new VisionAnalysisRequest(myBlob);
var result = await visionClient.AnalyzeAsync(request);
var visionResult = new VisionResult(Guid.NewGuid().ToString(), "VisionAnalysis") { ResultJson = result.ToString() };
await results.AddAsync(visionResult);
log.LogInformation($"Results: {result.ToString()}");
}
}
public class VisionResult : TableEntity
{
public VisionResult(string id, string partitionKey)
{
this.RowKey = id;
this.PartitionKey = partitionKey;
}
public string ResultJson { get; set; }
}
}
Url: https://mycognitive1000.cognitiveservices.azure.com/
First, Welcome to SO! It seems you've copied the code from the documentation without replacing the placeholders namely storageAccount,Key,Url... which are required for the service to work. For example, in your case, the URL posted under your question should go in the VisionUrl property as follows:
[VisionAnalysis(VisionKey = "YOUR_KEY", VisionUrl = "mycognitive1000.cognitiveservices.azure.com")]
The storage account is an Azure Blob Storage connection string. As for the Vision Key and Url, you can find a good tutorial and documentation on the Computer Vision API in the official docs. The tutorial explains as well how to have those parameters written within a separate configuration file as a best practice.

Get JSON data out of Umbraco

I am a frontend developer so forgive my lack of ability to explain my issue.
I am trying to create some pages in an Umbraco project that display data using Vue.js. For this, I am trying to set up a custom API controller that will return the data I want, when called.
A simple example would be that I want to return all blog articles. Below is the code I have currently got:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using System.Web.Http;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public string Test()
{
return "qwerty";
}
}
}
I've read numerous articles and just can't seem to grasp what I need to do to query Umbraco for the data I want back?
I've tried adding
var content = Umbraco.TypedContent(1122);
And then returning that but I get errors stating:
(local variable) Umbraco.Core.Models.IPublishedContent content
Cannot implicitly convert type 'Umbraco.Core.Models.IPublishedContent' to 'string'
I have then tried serialising the var content but I get stuck with:
Self referencing loop detected for property 'FooterCtalink' with type
'Umbraco.Web.PublishedContentModels.Blog'. Path
'ContentSet[0].FeaturedProducts[0].Features[0].ContentSet[0]'.
Any help would be fantastic!
EDIT:
I have no edited the controller to be like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
using System.Web.Mvc;
using DTOs.PostDTO;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public PostDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new PostDTO();
// 3. Pupulate your DTO
myDTO.Url = content.Url;
// 4. return it
return myDTO;
}
}
}
And created a DTO like so:
namespace DTOs.PostDTO
{
public class PostDTO
{
public string Url { get; set; }
}
}
However, when console logging my data after the ajax request, I only only getting 1122.
The issue is that you can't return a .NET Object in JSON that has the circular dependency.
To solve your problem, you can simply follow the below steps:
Create your own DTO & add required properties in that.
Fetch content from Umbraco API in C# & populate your custom DTO object.
Return that DTO from JsonResult.
Your code will look like below:
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public MyDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new MyDTO();
// 3. Pupulate your DTO
myDTO.SomeProperty = content.SomeProperty;
// 4. return it
return myDTO;
}
}
You are on the right track.
I think you need to return ActionResult instead of string.
Something like:
[HttpGet]
public ActionResult Test()
{
var content = Umbraco.TypedContent(1122);
return new JsonResult(content);
}
This should return the umbraco object as Json.

Web API call returned 404 from DNN site

First of all sorry If I am wrongly asking this question on SO. I have a third party library ([Link][1]) where the Web API logic has been written. I have a DNN Custom module from where I show the PDF viewer. But when loading the Viewer I get 404 exception for this call http://dnndev.me/dvapi3/docuvieware3api/init/1.
I am not sure from where the problem is happening exactly whether in DNN or in the third party tool. Any help to this problem will be highly appreciated.
UPDATE
WebAPI Controller MetaData
namespace GdPicture14.WEB
{
public class DocuVieware3ApiController : System.Web.Http.ApiController
{
public DocuVieware3ApiController();
[System.Web.Http.ActionNameAttribute("init")]
[System.Web.Http.HttpPostAttribute]
public string init([System.Web.Http.FromBodyAttribute] object jsonString);
}
}
RouteMapper.cs
using DotNetNuke.Web.Api;
using GdPicture14.WEB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace DocumentViewer
{
public class RouterMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute(
"DocumentViewer",
"default",
"{controller}/{action}",
new string[] { "DocumentViewer" });
}
}
}
I've got an example of API calls available in a DNN module in my VehiDataCollector module
You need to provide a route mapper
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute("VehiDataCollector","Default", "{controller}.ashx/{action}",
new[] { "Christoc.Modules.VehiDataCollector.Services" });
//mapRouteManager.MapHttpRoute("MyServices", "default", "{controller}/{action}", new {"MyServices"});
}
Then a controller that inherits from DnnApiController like #Mickers points out in the comments
public class VehiDataCollectorController : DnnApiController
{
//URL to get the list of vehicles
[HttpGet]
//[DnnAuthorize()]
//TODO: make it so we can call without ModuleId to get a list of vehicles
[AllowAnonymous]
public HttpResponseMessage GetVehicles()
{
try
{
var mc = new ModuleController();
var mi = mc.GetModuleByDefinition(0, "VehiDataCollector");
//TODO: assuming PortalId=0 if moduleid =0
return GetVehicles(mi.ModuleID);
}
catch (Exception exc)
{
DnnLog.Error(exc); //todo: obsolete
return Request.CreateResponse(HttpStatusCode.BadRequest, "Module Not On A Page, or No Vehicles Exist"); //todo: probably should localize that?
}
}
}

Asp.Net 4.5 Consume Service Reference with windows authentication and default credentials

I have a web application on my intranet configured to use windows authentication on IIS. We have a windows network and an active dircory server, so when some user try to access the application the browser doesn't ask for login and password because it uses the windows credentials of the current logged user.
I added a webservice in this application and tried to consume it in an windows application. I got an error 401 when I tried. The users are already logged on windows with their own credentials, so I'd like to have my windows application logging into the webservice using current user's credentials.
My Service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace MyWebServices
{
/// <summary>
/// Summary description for TestWS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class TestWS : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
My console Application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWebServiceClient
{
class Program
{
static void Main(string[] args)
{
TWS.TestWSSoapClient svc = new TWS.TestWSSoapClient();
try
{
Console.WriteLine(svc.HelloWorld());
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
finally
{
Console.ReadLine();
}
}
}
}
both are .net framework 4.5
Sorry about my poor English :)
I found it.
I needed to create a basic http binding and set it's client credential type to Windows. It works with ntlm too.
I had to create an endpont address to and pass both http binding and endpoint address to my SoapClient constructor.
static void Main(string[] args)
{
try
{
System.ServiceModel.BasicHttpBinding MyHttpBinding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly);
MyHttpBinding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
//MyHttpBinding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Ntlm; //works too
System.ServiceModel.EndpointAddress MyAuthASMXWebServiceAddress = new System.ServiceModel.EndpointAddress(new Uri("http://localhost/TestWS.asmx"));
TWS.TestWSSoapClient svc = new TWS.TestWSSoapClient(MyHttpBinding, MyAuthASMXWebServiceAddress);
Console.WriteLine(svc.HelloWorld());
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
finally
{
Console.ReadLine();
}
}
I still doesn't know what means BasicHttpSecurityMode.TransportCredentialOnly and what are the another options, how they work. But, for now, it worked.

Categories

Resources