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..
Related
I have the following:
public class StripeController : Controller
{
private readonly UserService _userService;
public StripeController(UserService userService)
{
_userService = userService;
}
[HttpPost]
public ActionResult StripeWebook()
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
[HttpPost]
[Route("api/stripewebhook")]
public async Task<ActionResult> Index(CancellationToken ct)
{
var json = new StreamReader(Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
And requests from stripe generate an error:
The controller for path '/api/stripewebhook' was not found or does not implement IController
Any idea why this is happening when I test from the stripe portal?
Using WebApi 2 it works with no problem.
Here is the smallest WebApi controller to begin with:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
return Ok();
}
}
}
if you execute this from VS you can access it from http://localhost:(port)/api/stripewebhook
Now you only need to extend this to include the stripe code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return Ok();
}
}
}
I have been working on ASP.NET MVC project Visual Studio 2012 Ultimate with Entity Framework. I have to include a Unit Test project into my solution. My problem is in that the test method (called Index()) can't recognize the application connection string in app.config. My Unit test method is:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ELSORegistry;
using ELSORegistry.DataAccess;
using ELSORegistry.Controllers;
namespace ELSORegistryUnitTests
{
[TestClass]
public class FirstControllerTest
{
[TestMethod]
public void Index()
{
//Arange
HomeController controller = new HomeController();
//Act
Guid? myGuid = new Guid("941b1615-f21b-4e2c-8fa8-0ed0d3f2de53");
ViewResult result = controller.Index(myGuid) as ViewResult;
//Assert
Assert.IsNotNull(result);
}
}
}
My Index() action in the Home Controller is:
using System;
using System.Diagnostics.Contracts;
using System.Web.Mvc;
using ELSORegistry.DataAccess;
using ELSORegistry.Models;
using Kendo.Mvc.UI;
using WebGrease.Css.Extensions;
using ELSORegistry.Extensions;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using Kendo.Mvc.Extensions;
using System.Diagnostics;
using ELSORegistry.Helpers;
using Newtonsoft.Json;
namespace ELSORegistry.Controllers
{
[Authorize]
public class HomeController : Controller
{
[Authorize(Roles = "ECLS Center Data Manager, ECLS Center Administrator,ECLS Center Data Viewer, ECLS Center Data Entry")]
//[RequireHttps] // Enable for production
public ActionResult Index(Guid? CenterId)
{
//----------------------------------------
// Remove references to previous patients
//----------------------------------------
Session.Remove("Patient");
Session.Remove("PatientSummary");
Session.Remove("Run");
Session.Remove("RunDetail");
Session.Remove("Addendum");
// if user have this session then he will get edit forms. // Yes if Add new
Session.Remove("AddNewMode");
Session.Remove("AddNewRunId");
Center center;
if (CenterId == null)
{
center = Session["Center"] as Center;
Contract.Assert(center != null);
}
else
{ // set center by selected centerId from dropdownlist
center = new Repository().GetCenter(new Guid(CenterId.ToString()));
Session["Center"] = center;
center = Session["Center"] as Center;
Contract.Assert(center != null);
}
ViewBag.RunCounts = Session["RunCounts"];
ViewBag.ChartSummaries = Session["ChartSummaries"];
return View(new QuickAdd());
}
The bug is in the line:
center = new Repository().GetCenter(new Guid(CenterId.ToString()));
of the controller. The method GetCenter is:
public Center GetCenter(Guid centerId)
{
try
{
using (var context = new ELSORegistryEntities())
{
var center = context.Centers.FirstOrDefault(c => c.CenterId == centerId);
return center;
}
}
catch (InvalidOperationException ex)
{
throw new DataException(string.Format("Error retrieving center for CenterId {0}", centerId), ex);
}
}
and app.config is in the ELSORegistry.DataAccess project which is included in the test. The class ELSORegistryEntities() is:
namespace ELSORegistry.DataAccess
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
public partial class ELSORegistryEntities : DbContext
{
public ELSORegistryEntities()
: base("name=ELSORegistryEntities")
{
}
The connection string is:
<connectionStrings>
<add name="ELSORegistryEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=NELAPC\NELA2014;initial catalog=ELSORegistry2;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
The bug is : "Test method ELSORegistryUnitTests.FirstControllerTest.Index throw exception:System.Data.DataException:Error retrieving center for CenterId 941b1615-f21b-4e2c-8fa8-0ed0d3f2de53->System.InvalidOperationException: No connection string named'ELSORegistryEntities' could be found in the application config file". How can I solve this? Thank you in advance for any help.
You need to include an app.config file inside you unit test project. Only the running project's (in this case the unit test project) app.config is respected/used.
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
Error
Invalid token 'using' in class, struct, or interface member declaration
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
String Connectionstring = ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString;
using(SqlConnection con = new SqlConnection()){
}
}
}
You're attempting to use the using statement at the class scope, which is invalid. Try the following:
public void YourMethod() {
string connStr = ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString.ToString();
using(SqlConnection connection = new SqlConnection()) {
//do something
}
}
I am trying to write a little console app to display a list of running Service Applications on a SharePoint 2010 site. I have employed Microsoft.SharePoint as well as Microsoft.SharePoint.Administration, but so far I am not having much luck. Below is what I have been fiddling around with. Can anyone give me some pointers on how to properly use SPServiceApplicationCollection?
Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceProcess;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SPServiceApplicationCollection services = new SPServiceApplicationCollection(String, SPFarm.Local.Services);
foreach (SPServiceApplication service in services)
{
Console.WriteLine(service.Name);
if (service is SPWebService)
{
SPWebService webService = (SPWebService)service;
foreach (SPWebApplication webApp in webService.WebApplications)
{
Console.WriteLine(webApp.Name);
Console.ReadLine();
}
}
}
}
}
}
EDIT
After some digging/asking around I came up with a rough solution of what I wanted.
For future reference/anyone else that wishes to do this sort of thing, I was able to get a list of deployed servers as well as the application name by doing the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceProcess;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Health;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var solution = SPFarm.Local.Solutions["Your Service Application Name.wsp"];
string serverName = string.Empty;
foreach (SPServer server in solution.DeployedServers)
{
serverName += server.Name;
Console.WriteLine(server.Name);
}
if (solution != null)
{
if (solution.Deployed)
{
Console.WriteLine("{0} is currently deployed on: {1}", solution.Name, serverName);
Console.ReadLine();
}
else
{
Console.WriteLine("Error! Solution not deployed!");
Console.ReadLine();
}
}
}
}
}
After some digging/asking around I came up with a rough solution of what I wanted. For future reference/anyone else that wishes to do this sort of thing, I was able to get a list of deployed servers as well as the application name by doing the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceProcess;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Health;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var solution = SPFarm.Local.Solutions["Your Service Application Name.wsp"];
string serverName = string.Empty;
foreach (SPServer server in solution.DeployedServers)
{
serverName += server.Name;
Console.WriteLine(server.Name);
}
if (solution != null)
{
if (solution.Deployed)
{
Console.WriteLine("{0} is currently deployed on: {1}", solution.Name, serverName);
Console.ReadLine();
}
else
{
Console.WriteLine("Error! Solution not deployed!");
Console.ReadLine();
}
}
}
}
}