Call rest web service from SQL Server 2008 using stored procedure - web-services

I have an xml created from a SQL query through a stored procedure. I need to call a REST web service with that xml and get a response. I am using SQL Server 2008. Is there a way to do it from the stored procedure?
I keep seeing links to use SQL CLR to access the web service. In those links, I need to create a SQL Server project / .NET framework. I do not see those templates / options in my Visual Studio 2008 or SQL Server Management Studio.
Is there a way to call this https rest web service directly from the stored procedure?
===============
I am using the SQL CLR to do this. But somehow the xml is not getting passed right. I get a 500 error. Could you please see if there is anything wrong with this code.
public static void SampleWSPost(SqlString weburl, out SqlString returnval)
{
string url = Convert.ToString(weburl);
string feedData = string.Empty;
ASCIIEncoding encoding = new ASCIIEncoding();
try
{
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream stream = null;
StreamReader streamReader = null;
XmlTextReader reader = new XmlTextReader("D:\\CXmls\\crmXml.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
reader.Close();
request = (HttpWebRequest)WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
request.Credentials = mycache;
request.Method = "POST";
request.ContentType = "text/xml";
string data = xmlDoc.InnerXml;
byte[] bytedata = Encoding.UTF8.GetBytes(data);
Stream newStream = request.GetRequestStream();
newStream.Write(bytedata, 0, bytedata.Length);
newStream.Close();
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
streamReader = new StreamReader(stream);
feedData = streamReader.ReadToEnd();
response.Close();
stream.Dispose();
streamReader.Dispose();
}
catch (Exception ex)
{
SqlContext.Pipe.Send(ex.Message.ToString());
}
returnval = feedData;
}

Related

Power BI API - How can I get reports from app.powerbi.com?

I have some client that uses the Power BI App.
And with this API I want to get all the reports (.pbix) to my folder.
How can I get them?
You can simply open the report in your browser and save it as .pbix file:
If you want to do this using an API, you will need Export Report In Group REST API. To use it, you need to acquire an access token and add it to your request header. You can acquire it by calling some of the AcuireToken methods from ADAL.
You can use code like this (please note there is no error checking in the example):
string clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Obtain at https://dev.powerbi.com/apps
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
string resourceUri = "https://analysis.windows.net/powerbi/api";
string authorityUri = "https://login.windows.net/common/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authorityUri, new TokenCache()); // PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
var authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Auto));
var accessToken = authenticationResult.AccessToken);
string powerBIApiUrl = "https://api.powerbi.com/v1.0/myorg/groups/{groupId}/reports/{reportKey}/Export"; // Replace groupId and reportKey with actual values
var request = WebRequest.Create(powerBIApiUrl) as HttpWebRequest;
request.KeepAlive = true;
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "application/json";
request.Headers.Add("Authorization", $"Bearer {accessToken}");
using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
{
//Read httpResponse.GetResponseStream() to get the .pbix file
}

Why am I not recieving facebook graph entity_id value from http get request?

if I do a simple HTTP GET request with e.g. POSTMAN then in the response there's an element called 'entity_id'.
e.g. https://www.facebook.com/yourFacebookName
If however, I do the request from a simple C# app then the following code doesnt return the 'entity_id' element in the response and I cant figure out why?
Code from app:
string html = string.Empty;
string url = string.Format("https://www.facebook.com/{0}", "yourFBName");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
if (html.Contains("entity_id"))
{
//do some stuff
}
Anyone know why its dropping the 'entity_id' element, but returning it when hitting that url from POSTMAN etc?

call a classic asp page from a console application

I need to call my .NET (C#) web service from a classic asp page. I want to test it by creating a console application that calls the asp page.
This is my asp page:
Dim strUserID
Dim strUserName
Dim strUserEmail
strUserID = Request.Form("UserID")
strUserName = Request.Form("UserName")
strUserEmail = Request.Form("UserEMail")
SET objSoapClient = Server.CreateObject("MSSOAP.SoapClient")
objSoapClient.ClientProperty("ServerHTTPRequest") = True
Call objSoapClient.mssoapinit("http://localhost:/MyWebService/Service1/" & _
"MyWebService.asmx?WSDL", "MyWebService")
strReturnValue = objSoapClient.SendData(strUserID, strUserName, strUserEmail)
response.Write("Returned from service with return value: " & strReturnValue)
Now my console application has to call the .asp page.
How do I construct the URL?
If the asp page is located in this folder: C:\Folder1\OldPage.asp, how do I construct the URL?
This is what I have so far:
static void Main(string[] args)
{
WebClient client = new WebClient();
Uri aspPagingServiceUri = new Uri("http://localhost/Folder1/OldPage.asp?UserID=g39s24&UserName=Gloria Test$UserEmail=gtest#hvhs.org");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(aspPagingServiceUri);
httpWebRequest.Method = "GET";
var response = httpWebRequest.GetResponse();
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string strResponse = reader.ReadToEnd();
Console.WriteLine(strResponse);
reader.Close();
}
I get the error: 'The remote server returned an error: (503) Server Unavailable. ' when it gets to the GetResponse function.
I believe my problem is with the creation of the URL.
Thanks.
UPDATE
I have trying to connect to the ASP file that on the web server. I am getting a (500) error: "The remote server returned an error: (500) Internal Server Error."
The file is folder: C:\inetpub/wwwroot/Apps/Services/ServiceNew.asp
This is my console application:
static void Main(string[] args)
{
try
{
WebClient client = new WebClient();
Uri aspPagingServiceUri = new Uri("http://myserverName/Apps/Services/ServiceNew.asp?UserID=g39r345&UserName=John Smith&UserEmail=jsmith#mydomain.com&Subject=Test&MSG=Testing&ContactList=Sam Smith;");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(aspPagingServiceUri);
httpWebRequest.Method = "GET";
var response = httpWebRequest.GetResponse();
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string strResponse = reader.ReadToEnd();
Console.WriteLine(strResponse);
reader.Close();
}
catch (WebException wex)
{
Console.WriteLine("Web Exception: " + wex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
}
The error is occurring var response = httpWebRequest.GetResponse();
Am I creating the URL correctly?
I am just following the file path.
You can not execute ASP code directly. What you need is to setup a web server that can execute classic ASP, i.e. Internet Information Services (IIS) on your machine, on another computer in a local network or externally.
IIS is part of some Windows distributions, you may just have to activate it. Make sure to install the classic ASP module, as this is not installed by default nowadays.
A warning: classic ASP often depends on additional COM components. So you may have to install more to get your code working.

connection.getConnetion() returns 404 code on WebSphere7

I have implemented a REST service using Spring Integration.
When I try to access the service manually using main function, It is working fine.
I also tested the service using REST Client in Google Chrome and that worked. But the service is coming back with responseCode 404 on WebSphere server. So I am facing the issue when I deploy the code on higher environment.
URL u = new URL("http://localhost:8080/MyApplication/testRestService");
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String input = jsonInput;
wout.write(input.getBytes());
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
Is is dependent on server, so its coming back with response code 404 ? Do we need any server side configuration ?
Any suggestion will be appreciated.
Why do you use different ContentType for URLConnection and for httpClient?
Show, please, your REST service config: 404 means Not found. Therefore you use (or don't) some options in request which makes it non-matching for the server's RequestMapping.
I tried with Apache HTTP Client and the code is working on WebSphere now. Still I am not able to find the reason why java.net.HttpURLConnection was not working on WebSphere.
Please find my updated code below :
DefaultHttpClient httpClient = null;
HttpPost postRequest = null;
StringEntity inputEntity = null;
HttpResponse response = null;
try{
//RETREIVE WEB SERVICE URL FROM DB
String callbackURL = "http://localhost:8080/MyApplication/testRestService";
httpClient = new DefaultHttpClient();
postRequest = new HttpPost(callbackURL);
String inputData = request.toString();
inputEntity = new StringEntity(inputData);
inputEntity.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(inputEntity);
response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());
}
//System.out.println("HTTP Response Code :"+response.getStatusLine().getStatusCode());
LOGGER.debug("HTTP Response Code :"+response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
}catch(IOException ex){
ex.printStackTrace();
throw ex;
}finally{
httpClient.getConnectionManager().shutdown();
httpClient = null;
postRequest = null;
inputEntity = null;
response = null;
}

JBoss EAP 5.1 Server not using Windows Network Setting

I'm trying to call a web service from my application. My system is protected with a Firewall and I'm using a Proxy to access any external URL/internet access. The application is running on JBoss EAP 5.1 server. The application fails to write to the service URL with IO Exception: 'Could not transmit message'.
However, when I'm trying to access the service URL with IE/Firefox, it's opening. Although the XML response I'm receiving from Browser states a generic error - 'invalid request parameters...', which is quite obvious. Because I'm not sending a proper request XML from Browser.
I'm really confused with this disparity. I used to believe that JBoss will pick up standard windows network settings, but in my case it is not.
My code is as follows:
String strUrl = "http://theurlgoeshere";
String requestXml = "<request></request>";
String wsResponse="";
SOAPConnection conn = null;
try {
MessageFactory msgFac = MessageFactory.newInstance();
MimeHeaders mh = new MimeHeaders();
mh.setHeader("Content-Type", "text/xml; charset=UTF-8");
log.info("Request Xml:" + requestXml );
InputStream is = new ByteArrayInputStream(requestXml.getBytes("UTF-8"));
SOAPMessage reqMsg = msgFac.createMessage(mh, is);
SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
conn = conFac.createConnection();
SOAPMessage repMsg = conn.call(reqMsg, strUrl);
ByteArrayOutputStream out = new ByteArrayOutputStream();
repMsg.writeTo(out);
wsResponse = new String(out.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
}
Got it sorted few days back. Basically I am using HttpURLConnection now to add proxy setting in the java code itself while making the Webservice call. Just closing this question, since my query is solved.
Will update the new code, if anyone needs.