Generate c/c++ code from Swagger JSON by using gSoap - web-services
I need to connect to Web API described below with c++ by using gSOAP library. I could use wsdl2h tool for this purpose, but I have only Json generated from Swagger:
{"swagger":"2.0","info":{"version":"v1","title":"WebAPIDemo"},"host":"webapidemo20220427161453.azurewebsites.net","schemes":["https"],"paths":{"/api/Values":{"get":{"tags":["Values"],"operationId":"Values_Get","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"OK","schema":{"type":"array","items":{"type":"string"}}}}},"post":{"tags":["Values"],"operationId":"Values_Post","consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"produces":[],"parameters":[{"name":"value","in":"body","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"No Content"}}}},"/api/Values/{id}":{"get":{"tags":["Values"],"operationId":"Values_Get","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}}}},"put":{"tags":["Values"],"operationId":"Values_Put","consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"value","in":"body","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"No Content"}}},"delete":{"tags":["Values"],"operationId":"Values_Delete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"No Content"}}}}},"definitions":{}}
How to generate C/C++ files for Web Service?
RESTful Web API with automatic documentation from Swagger on Azure by using C# :
namespace WebAPIDemo.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody] string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
It is possible to call function from Swagger.
Related
Call RESTful from gsoap
I have created simple RESTful API with automatic documentation from Swagger on Azure by using C# : namespace WebAPIDemo.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody] string value) { } // PUT api/values/5 public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 public void Delete(int id) { } } } It is possible to call function from Swagger. I would like to connect to this from C/C++ by using gSOAP. In case SOAP server with WSDL I could use wsdl2h.exe to generate header file. But how to deal with REST server that has no WSDL?
CXF In interceptor get reference to service object
I am extending AbstractPhaseInterceptor, and I want to get hold of the JAXWS web service object, in INVOKE or PRE_INVOKE phase. How do I do this? To be clear, I need to get a reference to the object that implements the web service methods, so: #WebService(...) public class ExampleWebService { #WebMethod(...) public void doSomething(...) { } } public class MyInterceptor extends AbstractPhaseInterceptor<Message> { public MyInterceptor() { super(Phase.INVOKE); } #Override public void handleMessage(Message message) throws Fault { ExampleWebService serviceObject = getServiceObject(message); } private static ExampleWebService getServiceObject(Message messsage) { // how do I implement this? } }
I do not test the code but something like that probably works. import org.apache.cxf.endpoint.Server; import org.apache.cxf.frontend.ServerFactoryBean; ... Server server = serverFactoryBean.create(); MyInterceptor myInterceptor = new MyInterceptor(server.getEndpoint()); server.getEndpoint().getInInterceptor().add(myInterceptor);
Best practices of implementing unit of work and repository pattern using ServiceStack.ORMLite
Supposing that there are two repository interface : interface IFooRepository { void Delete(int id); } interface IBarRepository { void Delete(int id); } And an IUnitOfWork interface like : interface IUnitOfWork : IDisposable { void Commit(); void Rollback(); } what is the best practices of implementing those interface using ServiceStack.ORMLite so that user can use them like MyFooRepository.Delete(4); // if an Exception throws here, Bar won't be deleted MyBarRepository.Delete(7); Or using (var uow = CreateUnitOfWork()) { MyFooRepository.Delete(4); MyBarRepository.Delete(7); uow.Commit(); //now they are in an transaction }
Not sure of your need for Repository + UnitOfWork patterns but I think there are some alternative solutions in ServiceStack + OrmLite that keep your code 'DRY' before you need to introduce any patterns (especially if you're mainly seeking Transaction/Rollback support). Something like below is where I would start. public class Foo //POCO for data access { //Add Attributes for Ormlite public int Id { get; set; } } public class Bar //POCO for data access { //Add Attributes for Ormlite public int Id { get; set; } } //your request class which is passed to your service public class DeleteById { public int Id { get; set; } } public class FooBarService : MyServiceBase //MyServiceBase has resusable method for handling transactions. { public object Post(DeleteById request) { DbExec(dbConn => { dbConn.DeleteById<Foo>(request.Id); dbConn.DeleteById<Bar>(request.Id); }); return null; } } public class MyServiceBase : Service { public IDbConnectionFactory DbFactory { get; set; } protected void DbExec(Action<IDbConnection> actions) { using (var dbConn = DbFactory.OpenDbConnection()) { using (var trans = dbConn.OpenTransaction()) { try { actions(dbConn); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw ex; } } } } } Some references... https://github.com/ServiceStack/ServiceStack.RedisWebServices - The above code is modified from this example https://groups.google.com/forum/#!msg/servicestack/1pA41E33QII/R-trWwzYgjEJ - discussion about layers in ServiceStack http://ayende.com/blog/3955/repository-is-the-new-singleton - Ayende Rahien (NHibernate core contributor) on Repository pattern
Cannot seem to moq EF CodeFirst 4.1.Help anyone?
I have been given the task to evaluate codeFirst and possible to use for all our future projects. The evaluation is based on using codeFirst with an existing database. Wondering if it's possible to mock the repository using codeFirst 4.1.(no fakes) The idea is to inject a repository into a service and moq the repository. I have been looking on the net but I have only found an example using fakes.I dont want to use fakes I want to use moq. I think my problem is in the architecture of the DAL.(I would like to use unitOfWork etc.. by I need to show a working moq example) Below is my attempt(Failed miserably) due to lack of knowledge on Code first 4.1. I have also uploaded a solution just in case somebody is in good mood and would like to change it. http://cid-9db5ae91a2948485.office.live.com/browse.aspx/Public%20Folder?uc=1 I am open to suggestions and total modification to my Dal.Ideally using Unity etc.. but I will worry about later. Most importantly I need to be able to mock it. Without ability to use MOQ we will bin the project using EF 4.1 Failed attempt //CodeFirst.Tests Project [TestClass] public class StudentTests { [TestMethod] public void Should_be_able_to_verify_that_get_all_has_been_called() { //todo redo test once i can make a simple one work //Arrange var repository = new Mock<IStudentRepository>(); var expectedStudents = new List<Student>(); repository.Setup(x => x.GetAll()).Returns(expectedStudents); //act var studentService = new StudentService(repository.Object); studentService.GetAll(); //assert repository.Verify(x => x.GetAll(), Times.AtLeastOnce()); } } //CodeFirst.Common Project public class Student { public int StudentId { get; set; } public string Name { get; set; } public string Surname { get; set; } } public interface IStudentService { IEnumerable<Student> GetAll(); } //CodeFirst.Service Project public class StudentService:IStudentService { private IStudentRepository _studentRepository; public StudentService() { } public StudentService(IStudentRepository studentRepository) { _studentRepository = studentRepository; } public IEnumerable<Student> GetAll() { //TODO when mocking using moq this will actually call the db as we need a separate class. using (var ctx = new SchoolContext("SchoolDB")) { _studentRepository = new StudentRepository(ctx); var students = _studentRepository.GetAll().ToList(); return students; } } } //CodeFirst.Dal Project public interface IRepository<T> where T : class { T GetOne(Expression<Func<T, bool>> predicate); IEnumerable<T> GetAll(); IEnumerable<T> Find(Expression<Func<T, bool>> predicate); void Add(T entity); void Delete(T entity); T Single(Func<T, bool> predicate); T First(Func<T, bool> predicate); } public class RepositoryBase<T> : IRepository<T> where T : class { private readonly IDbSet<T> _dbSet; public RepositoryBase(DbContext dbContext) { _dbSet = dbContext.Set<T>(); if (_dbSet == null) throw new InvalidOperationException("Cannot create dbSet "); } protected virtual IDbSet<T> Query { get { return _dbSet; } } public T GetOne(Expression<Func<T, bool>> predicate) { return Query.Where(predicate).FirstOrDefault(); } public IEnumerable<T> GetAll() { return Query.ToArray(); } public IEnumerable<T> Find(Expression<Func<T, bool>> predicate) { return Query.Where(predicate).ToArray(); } public void Add(T entity) { _dbSet.Add(entity); } public void Delete(T entity) { _dbSet.Remove(entity); } public T Single(Func<T, bool> predicate) { return Query.Where(predicate).SingleOrDefault(); } public T First(Func<T, bool> predicate) { return Query.Where(predicate).FirstOrDefault(); } } public class SchoolContext:DbContext { public SchoolContext(string connectionString):base(connectionString) { Database.SetInitializer<SchoolContext>(null); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //Not sure why I have to do this.Without this when using integration testing //as opposed to UnitTests it does not work. modelBuilder.Entity<Student>().ToTable("Student"); } public DbSet<Student> Students { get; set; } } public interface IStudentRepository:IRepository<Student> { } public class StudentRepository : RepositoryBase<Student>, IStudentRepository { public StudentRepository(DbContext dbContext) : base(dbContext) { } public IEnumerable<Student> GetStudents() { return GetAll(); } } Again feel free to modify or whatever is needed to help me to get something together. Thanks a lot for your help
When I started with repository and unit of work patterns I used the implementation similar to this (it is for ObjectContext API but converting it to DbContext API is simple). We used that implementation with MOQ and Unity without any problems. By the time implementations of repository and unit of work have evolve as well as the approach of injecting. Later on we found that whole this approach has serious pitfalls but that was alredy discussed in other questions I referenced here (I highly recommend you to go through these links). It is very surprising that you are evaluating the EFv4.1 with high emphasis on mocking and unit testing and in the same time you defined service method which is not unit-testable (with mocking) at all. The main problem of you service method is that you are not passing repository/context as dependency and because of that you can't mock it. The only way to test your service and don't use the real repository is using some very advanced approach = replacing mocking and MOQ with detouring (for example Moles framework). First what you must do is replacing your service code with: public class StudentService : IStudentService { private readonly IStudentRepository _studentRepository; public StudentService(IStudentRepository studentRepository) { _studentRepository = studentRepository; } public IEnumerable<Student> GetAll() { return _studentRepository.GetAll().ToList(); } } Btw. this is absolutely useless code and example of silly layering which doesn't offer any useful functionality. Just wrapping the call to repository only shows that service is not needed at all as well as unit testing this method is not needed. The main point here is integration test for GetAll method. Anyway if you want to unit thest such method with MOQ you will do: [TestClass] public class StudentsServiveTest { private Mock<IRespository<Student>> _repo; [TestInitialize] public void Init() { _repo = new Mock<IRepository<Student>>(); _repo.Setup(r => r.GetAll()).Returns(() => new Student[] { new Student { StudentId = 1, Name = "A", Surname = "B" }, new Student { StudentId = 2, Name = "B", Surname = "C" } }); } [TestMethod] public void ShouldReturnAllStudents() { var service = new StudentsService(_repo.Object); var data = service.GetAll(); _repo.Verify(r => r.GetAll(), Times.Once()); Assert.IsNotNull(data); Assert.AreEqual(2, data.Count); } }
The issue from what I can see is that you are throwing away the mock object and newing up a new instance _studentRepository = new StudentRepository(ctx); Perhaps add a method on the interface to add the context object and reuse the same instance that was injected in the constructor. using (var ctx = new SchoolContext("SchoolDB")) { _studentRepository.Context = ctx; var students = _studentRepository.GetAll().ToList(); return students; } }
How to write a Mock Repository to test WCF RIA Domain Service build on top of Entity Framework Context
I need to write a test layer to Test my WCF RIA Domain Service layer which is build on top of Entity Framework context. I have come across some patterns which suggest to use a repository and then use the Domain Service factory to intilize the domain service with a repository instance to use. One of the sample which fits the requirement is explained here on Vijay's blog(http://blogs.msdn.com/vijayu/archive/2009/06/08/unit-testing-business-logic-in-net-ria-services.aspx). The problem with this implementation is that it initilize the repository only for a specific Domain Object e.g. Customer/Product but it provides no way to create a repository which can return any object which i would like to return. Please suggest what is the right way of doing this and whether it is possible or not. Thanks in advance, Manoj
I got around this issue by extending the sample with a RepositoryCollection object, which automatically instantiates LinqToSqlRepositories as needed, and also allows the insertion of mock/stub repositories manually for unit testing. public class RepositoryCollection : IDisposable { private Dictionary<Type, object> _repositories = new Dictionary<Type, object>(); private DataContext _context; public RepositoryCollection() { } public RepositoryCollection(DataContext context) { _context = context; } public IRepository<T> Get<T>() where T : class { if(!_repositories.ContainsKey(typeof(T))) _repositories.Add(typeof(T), new LinqToSqlRepository<T>(_context)); return _repositories[typeof(T)] as IRepository<T>; } public RepositoryCollection Insert<T>(IRepository<T> repository) where T : class { _repositories[typeof(T)] = repository; return this; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void SubmitChanges() { if (_context != null) _context.SubmitChanges(); } protected virtual void Dispose(bool disposing) { if (disposing) { if(_context != null) _context.Dispose(); } } } Then, in your domain service, you use it like so: private RepositoryCollection _repositoryCollection; public MyDomainService(RepositoryCollection repositoryCollection = null) { _repositoryCollection = repositoryCollection ?? new RepositoryCollection(new MyDataContext()); } public IQueryable<Customer> GetCustomers() { return _repositoryCollection.Get<Customer>().Query(); } public IQueryable<Product> GetProducts() { return _repositoryCollection.Get<Product>().Query(); } .. other methods go here ...