I have a problem, need to display the contents of a query in the database with webservice, serializing with Json.
My Billing List
using BiDAL.Entity.Graficos;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BiDAL.Persistence
{
public class FaturamentoIvelDAL : Conexao
{
public List<FaturamentoIvel> FindAllFaturamentoIvel()
{
try
{
OpenConnection();
Cmd = new SqlCommand("SELECT Operacao, AnoMes, TradeMarketing, SUM(ValorNF) AS ValorTotal FROM dbo.FatoFaturamentoIVEL WHERE TradeMarketing = 0 GROUP BY Operacao, AnoMes, TradeMarketing ORDER BY SUM(ValorNF) DESC", Con);
Dr = Cmd.ExecuteReader();
List<FaturamentoIvel> lista = new List<FaturamentoIvel>();
while (Dr.Read())
{
FaturamentoIvel ft = new FaturamentoIvel();
ft.Operacao = Convert.ToString(Dr["Operacao"]);
ft.AnoMes = Convert.ToString(Dr["AnoMes"]);
ft.ValorNF = Convert.ToSingle(Dr["ValorNF"]);
lista.Add(ft);
}
return lista;
}
catch (Exception ex)
{
throw new Exception("Erro ao listar Faturamento: " + ex.Message);
}
}
}
}
My WebService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using BiDAL.Persistence;
using BiDAL.Entity;
using BiDAL.Util;
using BiFrontEnd.Controllers;
namespace BiFrontEnd
{
/// <summary>
/// Summary description for WebService
/// </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 WebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet= true, ResponseFormat = ResponseFormat.Json)]
public void GerarGraficoFaturamentoIvel(Conexao Con)
{
try
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Con.OpenConnection();
Context.Response.Write(Serializer.Serializador(FindAllFaturamentoIvel));
}
catch (Exception)
{
throw;
}
}
}
}
In the code line "Context.Response.Write(Serializer.Serializador(FindAllFaturamentoIvel));" is giving error in FindAllFaturamentoIvel
Related
Hi i have a Api that i want to use to collect data from a backend that spits out json i need to get this via C# Application and it's http functionalities. My question is should i use a rest api and setup an async thread that downloads the data and then use the data as i want to from there or should i somehow use something close to a Web Api i have an authentication that is required to exist in a header. This has given me some hedaches because i keep on being split by what to use for what. I mean i need to do a Httprequest with a header. this i later on need to use for posting to another database. but the user of the program should not have to see the data itself. i have two examples that i have done but i don't know with what i should continue? this is my two examples in code...
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace Plugin
{
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class Api
{
private HttpVerb HttpMethod { get; set; }
public Api()
{}
public string startDownload()
{
return (Download("sending token"));
}
private string Download(string token)
{
string strResponseValue = string.Empty;
string finnishedOutput = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Url");
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = HttpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
strResponseValue = reader.ReadToEnd();
}
return strResponseValue;
}
catch (WebException e)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if ((int)httpResponse.StatusCode == 401)
{}
int errorCodeInt;
string errorCode;
errorCodeInt = (int)httpResponse.StatusCode;
errorCode = errorCodeInt.ToString();
return errorCode;
}
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestAPi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Api.InitializeClient("");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestAPi
{
public class Api
{
private static HttpClient ApiClient { get; set;}
private string url { get; set;}
public static void InitializeClient(string token)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("your url");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Bearer Authentication"));
}
public async Task<Data> LoadData()
{
url = ApiClient.BaseAddress.ToString();
using (HttpResponseMessage response = await ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
Data data = await response.Content.ReadAsAsync<data>();
return data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
I've been working on a small MVC-project which since I converted to more of an MVC-approach has stopped working.
The program consuming the web-service is a simple console-application with its own controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication.ServiceReference1;
namespace ConsoleApplication
{
class ConsoleController
{
ServiceReference1.WebService2SoapClient webservice = new ServiceReference1.WebService2SoapClient();
public List<Employee> GetEmployees()
{
return webservice.GetEmployees().ToList();
}
}
}
The web-service consists of a Employee-class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webservice
{
public class Employee
{
public string _socialSN { get; set; }
public string _lastName { get; set; }
public string _firstName { get; set; }
public Employee(string socialSN, string firstName, string lastName)
{
this._firstName = firstName;
this._lastName = lastName;
this._socialSN = socialSN;
}
}
}
A data access layer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace webservice
{
public class DAL
{
private SqlConnection con;
private SqlCommand cmd;
public void GetConnection()
{
con = new SqlConnection("Data Source=****;Initial Catalog=DB2015;Persist Security Info=True;User ID=****;Password=***********");
}
public List<Employee> GetEmployees()
{
GetConnection();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "SELECT SocialSN, Name, Surname FROM Employee";
SqlDataReader reader = cmd.ExecuteReader();
List<Employee> employeeList = new List<Employee>();
if (reader.HasRows)
{
while (reader.Read())
{
employeeList.Add(new Employee(reader.GetString(0), reader.GetString(1), reader.GetString(2)));
}
}
else
{
employeeList = null;
}
reader.Close();
con.Close();
reader.Dispose();
con.Dispose();
return employeeList;
}
}
}
A BackController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webservice
{
class BackController
{
DAL dal = new DAL();
public List<Employee> GetEmployees()
{
return dal.GetEmployees();
}
}
}
And finally the webservice-code itself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace webservice
{
/// <summary>
/// Summary description for WebService2
/// </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 WebService2 : System.Web.Services.WebService
{
BackController bcontroller = new BackController();
[WebMethod]
public List<Employee> GetEmployees()
{
return bcontroller.GetEmployees();
}
}
}
Whenever I try to add a new service-reference to my console-application I get this error:
Error part 1 http://i.imgur.com/UVw1cAO.png
Error part 2 http://i.imgur.com/N0dF159.png
I cannot figure out what is wrong. It worked fine before I changed to MVC. I've tried to clean the projects, rebuild them and create them all from scratch again and just simply won't work.
Please let me know if you've got any ideas what could be wrong or if you need additional information.
Thanks!
It sounds like you've upgraded some components but the code is still trying to latch onto the old version. Essentially something in your code is looking for say version 1.1.0.1 and you've got version 2.1.0.1. or something like that. You'll need to either redirect to the correct assembly in your web config or find another way to get your application to accept the newer version.
Here are some links you can check out for some tips but these can be elusive bugs to sort out.
From stackoverflow:
The located assembly's manifest definition does not match the assembly reference.
that link has this one inside it:
http://blogs.msdn.com/b/junfeng/archive/2004/03/25/95826.aspx
And here is an independent blogger's take on it:
http://www.codingdefined.com/2014/10/error-located-assemblys-manifest.html
I have created one web service to save error log
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Configuration;
using System.Data.Common;
using System.Data;
using System.Net.Mail;
using System.IO;
namespace TestErrorHandling
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
public int SaveErrorLog(CompositeType objCom)
{
int messageId = 0;
try
{
SqlDatabase _errDBConnection = null;
_errDBConnection = new SqlDatabase(ConfigurationManager.ConnectionStrings["ErrorLogConnStr"].ToString());
DbCommand dbCommand = _errDBConnection.GetStoredProcCommand("usp_SaveErrorLog");
_errDBConnection.AddInParameter(dbCommand, "#i_ApplicationId", DbType.Int32, objCom.AppId);
_errDBConnection.AddInParameter(dbCommand, "#i_ExceptionType", DbType.String, objCom.ExceptionType);
_errDBConnection.AddOutParameter(dbCommand, "#O_MESSAGEID", DbType.Int32, 4);
_errDBConnection.ExecuteReader(dbCommand);
messageId = Convert.ToInt32(_errDBConnection.GetParameterValue(dbCommand, "#O_MESSAGEID"));
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
return messageId;
}
}
}
Now I am calling this service in my web application
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections.Specialized;
using Test.ServiceReference1;
namespace Test
{
public partial class _Default : BasePage
{
ServiceReference1.Service1Client obj1 = new ServiceReference1.Service1Client;
obj1.
}
But after typing obj1. its not showing SaveErrorLog method of Service.
Please help on this where I am doing wrong.
added like
change
ServiceReference1.Service1Client obj1 = new ServiceReference1.Service1Client;
to
ServiceReference1.Service1Client obj1 = new ServiceReference1.Service1Client();
and then use
obj1.<method name>
also add reference using add service references
like this..
I have created a web service in Visual Studio 2010 using the wsdl provided by our vendor. I have created an interface using their wsdl and implemented that interface for our implementation. They also need a SSL certificate so we have provided them certificate open ssl of windows. Web service also implements authentication using soap header.
But they are unable to connect and getting the following error
<soap:Body>
<soap:Fault>
<faultcode>soap:MustUnderstand</faultcode>
<faultstring>SOAP header Security was not understood.</faultstring>
</soap:Fault>
</soap:Body>
My web service code is as follows for your reference
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.IO;
using Microsoft.Web.Services3;
namespace MyWebService1
{
/// <summary>
/// Summary description for PSWebService
/// </summary>
///
[WebService(Namespace = "http://tempuri.org")]
[WebServiceBinding(Name = "PSWebService", ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[SoapDocumentService(RoutingStyle = SoapServiceRoutingStyle.RequestElement)]
// 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 PSWebService : Microsoft.Web.Services3.WebServicesClientProtocol, IPartStoreRequiredServiceSOAP11Binding
{
public UserCredentials consumer;
Functions objFunctions = new Functions ();
String SqlConnStr = "Data Source=test\\test;uid=sa;pwd=abc123;database=testdb";
public AeslPSWebService()
{
}
[WebMethod]
[SoapDocumentMethod(Binding = "PSWebService")]
[SoapHeader("consumer", Direction = SoapHeaderDirection.In, Required = true)]
public CustomerInformationOutput getCustomerInformation(CustomerInformationInput custLookUpInput)
{
CustomerInformationOutput cio = new CustomerInformationOutput();
try
{
if (checkUser())
{
// My business logic goes here
}
}
catch (Exception ex)
{
}
}
private bool checkUser()
{
// In this method you can check the username and password
// with your database or something
// You could also encrypt the password for more security
if (consumer != null)
{
if (consumer.Username == "sa" && consumer.Password == "abc123")
return true;
else
return false;
}
else
return false;
}
}
# region "SOAP Headers"
public class UserCredentials : System.Web.Services.Protocols.SoapHeader
{
public string Username;
public string Password;
}
# endregion
}
Please help as i am unable to resolve it.
I am getting the following error "Invalid authorization specification, Invalid connection string attribute"
//namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Data.OleDb;
namespace Database1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public bool IsValidConnectionForPrinting()
{
//string declaration
string str = #" Provider = SQLOLEDB; Data Source = sekhar; Database = DMS; UserId = sa; Password = 123";
//Oledbconnection to database
OleDbConnection oleDbcon = new OleDbConnection(str);
try
{
oleDbcon.Open();
MessageBox.Show("hai");
oleDbcon.Close();
}
//Exception
catch (Exception ex)
{
if (ex.Message.StartsWith("Invalid object name"))
{
MessageBox.Show(ex.Message.Replace("Invalid object name", "Table or view not found"), "Connection Test");
}
//Connection
private void btnConnTest_Click(object sender, EventArgs e)
{
if (IsValidConnectionForPrinting())
{
MessageBox.Show("Connection succeeded", "Connection Test");
}
}
}
}
I would recommend using a connection string that does not include Database or Initial Catalog, and then calling something like:
oleDbcon.ChangeDatabase("DMS");
This is because, as you have already experienced, different database drivers use different syntax for referring to the database in the connection string.
I had this error and it turned out the code path had not connected to the database.
Worth checking.