how to access Header information in service stack service implementation / Methods - servicestack

I am new to servicestack.net, and I am struggling to access the header information inside my methods. I am attaching the code I am using. It is in vb.net
Service stack Classes
a)Service Stack Request Class
Public Class LeaveManagementDashboardRequest
Public Property ClientID As String
Public Property DateFormatID As String
Public Property UserID As String
Public Property NOOFROWS As String
End Class
b)Service Stack Response Class
Public Class LeaveManagementDashboardResponse
Public Property data As String
End Class
c)Service Stack Service Class(Actual Service implementation)
Public Class LeaveManagementDashboardService
Implements IService(Of LeaveManagementDashboardRequest)
Private sqlCon As New SqlConnection
Public Function Execute(ByVal request As LeaveManagementDashboardRequest) As Object Implements ServiceStack.ServiceHost.IService(Of LeaveManagementDashboardRequest).Execute
Dim ds As New DataSet
If sqlcon.State = ConnectionState.Closed Then
Common.OpenConnection(sqlCon)
End If
Dim ClientID As String = request.ClientID
Dim UserID As String = request.UserID
Dim DataFormatID As String = request.DateFormatID
Dim NOOFROWS As String = request.NOOFROWS
Dim sqlcmd As New SqlCommand("abcdefg", sqlcon)
sqlcmd.CommandType = CommandType.StoredProcedure
sqlcmd.Parameters.Add(New SqlParameter("#UserID", SqlDbType.Int, 0))
sqlcmd.Parameters.Add(New SqlParameter("#DateFormatID", SqlDbType.TinyInt, 0))
sqlcmd.Parameters.Add(New SqlParameter("#Count", SqlDbType.SmallInt, 0))
sqlcmd.Parameters.Add(New SqlParameter("#ClientID", SqlDbType.Int, 0))
sqlcmd.Parameters(0).Value = UserID
sqlcmd.Parameters(1).Value = DataFormatID
sqlcmd.Parameters(2).Value = NOOFROWS
sqlcmd.Parameters(3).Value = ClientID
Dim dsResult As New DataSet
Dim sqlda As New SqlDataAdapter(sqlcmd)
sqlda.Fill(dsResult)
Dim obj As String = Common.GetJson(dsResult.Tables(0))
' obj.countries = lstCountries
sqlcon.Close()
sqlcon.Dispose()
Return New LeaveManagementDashboardResponse With {.data = obj}
Return dsResult
End Function
End Class
Routes are defined in the Global.aspx.cs file as given below
Public Class _Global
Inherits System.Web.HttpApplication
Public Class HelloAppHost
Inherits AppHostBase
Public Sub New()
MyBase.New("Plant Best Services", GetType(HelloAppHost).Assembly)
End Sub
Public Overrides Sub Configure(ByVal container As Container)
Routes.Add(Of LeaveManagementDashboardRequest)("/pml/Dashboard/LeavesRequests")
End Sub
End Class
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim apphost = New HelloAppHost()
apphost.Init()
End Sub

It's hard to decipher what question is being asked here, I'm going to assume you want to know how to access the header information in your services.
You should first look at using ServiceStack's New API for new services. When you inherit from Service you can access the HTTP Headers with:
public class MyService : Service
{
public LeaveManagementDashboardResponse Any(LeaveManagementDashboard request)
{
var httpHeader = base.Request.Headers["headerName"];
}
}
If you want to continue to use the Old API (e.g. IService<T>) then you want to implement the IRequiresRequestContext interface to get ServiceStack to inject the RequestContext into your service. Read the wiki docs for more info on this.

Related

Spring Boot Test - Mockito - Service call return null

I'm testing a post method in my controller that only return a String and using Mockito to mock the service call. My problem is that when the service method is called on controller it return null.
#RunWith(SpringRunner.class)
#WebMvcTest(ProcessGroupController.class)
public class ProcessGroupRestControllerTest {
.............
#Test
public void givenAllNifiArguments_whenImportProcessGroup_thenReturnJsonOk() throws Exception {
NiFiArguments niFiArguments = NiFiArguments.builder()......flowVersion("3").build();
String expected = "1689d61b-624d-4574-823d-f1b4755882e1";
String json = mapper.writeValueAsString(niFiArguments);
//Mock service call
when(nifiService.importProcessGroup(niFiArguments)).thenReturn(expected);
mvc.perform(post("/nifi/pg-import").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isCreated())......);
}
The controller:
#PostMapping("/pg-import")
public ResponseEntity<String> importProcessGroup(#RequestBody NiFiArguments niFiArguments)
throws NiFiClientException {
log.info("Called method importFlow");
String result = nifiService.importProcessGroup(niFiArguments);
return new ResponseEntity<String>(result, HttpStatus.CREATED);
}
String result = null
I have similar tests that return a POJO and it works perfectly
As ekalin said my builder class needed to implement equals and hashcode:
#Builder
#Getter
#EqualsAndHashCode
public class NiFiArguments {
private String bucketIdentifier;
private String flowIdentifier;
private String flowVersion;
private String baseUrl;
}

How to use UserDefinedType(UDT) with Spring Data Cassandra for List<UDT>

I have created a UDT named widgetData in cql for which i have a corresponding POJO class named widgetData. I want to use this in another domain POJO class as List. What kind of annotation should be used to do so?
#Table("dashboardManagement")
public class Dashboard implements Serializable {
#Column("dashboardState")
#CassandraType(type = DataType.Name.UDT, userTypeName = "widgetData")
private List<widgetData> dashboardState;
....
The above code does not work.
Do I have to write a seperate userTypeResolver for this?
I realize this question is a little old, but I have made this work.
Basically, I had a user profile with an address UDT, and that UDT had its own POJOs/entity classes. The UDT address entity class used the #UserDefinedType annotation:
#UserDefinedType("address")
public class AddressEntity implements Serializable {
private static final long serialVersionUID = 1817053316281666003L;
#Column("mailto_name")
private String mailtoName;
private String street;
private String street2;
private String city;
...
The user entity utilized the Address UDT entity:
#Table("user")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 4067531918643498429L;
#PrimaryKey("user_id")
private UUID userId;
#Column("user_email")
private String userEmail;
#Column("first_name")
private String firstName;
#Column("last_name")
private String lastName;
#Column("addresses")
private List<AddressEntity> addresses;
...
Then, it was a simple matter to map a user's address data to a UserEntity object (userE below) and save it with standard repository methods.
// save to DB
userRepo.save(userE);
You can find everything built to support the User services here: https://github.com/datastaxdevs/workshop-ecommerce-app/blob/main/backend/src/main/java/com/datastax/tutorials/service/user/
So I would say to have a look at the class for the widgetData object, make sure it's using the #UserDefinedType annotation, and mark the column using the #Column annotation in the Dashboard class (basically, get rid of the #CassandraType):
#Column("dashboardState")
private List<WidgetData> dashboardState;

Cassandra UDT mapping issue

I am not able to map data which has UDT type.
The table is definition is the following.
CREATE TABLE IF NOT EXISTS members_data.Test(
priority int,
name text,
test_links list<frozen<TestLinks>>,
PRIMARY KEY(name)
);
The model is the following.
#JsonAutoDetect
#JsonSerialize
#Table(keyspace="members_data", caseSensitiveKeyspace=false, caseSensitiveTable=false, name="Test")
public class Test{
#Column(name="name", caseSensitive=false)
private String name;
#Column(name="priority", caseSensitive=false)
private int priority;
#Frozen
#Column(name="test_links", caseSensitive=false)
private List<TestLinks> test_links;
#JsonAutoDetect
#JsonSerialize
#UDT(keyspace = "members_data", name = "Testlinks")
public class TestLinks {
#Field(name = "test_link")
private String test_link;
#Field(name = "link_title")
private String link_title;
The mapper usage.
MappingManager manager = new MappingManager(sessionManager.getSession());
manager.udtCodec(TestLinks.class);
Mapper<Test> mapper = manager.mapper(Test.class);
Result<Test> result = mapper.map(testResultSet);
test = result.one(); //test object would be null here
the cassandra-driver-mapping is 3.1.0.
Mapper is not throwing any error and now even mapping data to model. Could someone tell me what is the problem?

How to use AutoMapper to map a DataRow to an object in a WCF service?

I have a WCF service that calls a stored procedure and returns a DataTable. I would like to transform the DataRows to custom object before sending to the consumer but can't figure out how to do so. Lets say I retrieved a customer from a stored procedure. To keep things short here is the customer via DataRow:
string lastName = dt.Rows[0]["LastName"].ToString();
string firstName = dt.Rows[0]["FirstName"].ToString();
string age = System.Convert.ToInt32(dt.Rows[0]["Age"].ToString());
I can retrieve the customer easily. Now, I created a Customer object like so:
public Customer
{
public string LastName {get;set;}
public string FirstName {get;set;}
public int Age {get;set;}
}
I loaded AutoMapper from the package manager console. I then put a public static method on my customer like so:
public static Customer Get(DataRow dr)
{
Mapper.CreateMap<DataRow, Customer>();
return Mapper.Map<DataRow, Customer>(dr);
}
When I step through my code, every property in the customer returned from Get() is null. What am I missing here? Do I have to add a custom extension to map from a DataRow? Here is a thread that seems related but I thought AutoMapper would support this out of the box especially since the property names are identical to the column names. Thanks in advance.
This works!!
public static Customer GetSingle(DataTable dt)
{
if (dt.Rows.Count > 0) return null;
List<Customer> c = AutoMapper.Mapper.DynamicMap<IDataReader, List<Customer>>(dt.CreateDataReader());
return c[0];
}

How to get a string representation of a property name of a Model in MVC3?

I have the following model:
Public Class MyModel
Public Property MyModelId As Integer
Public Property Description As String
Public Property AnotherProperty As String
End Class
Is there a method to get a property name of the Model as a string representation like the following code?
Dim propertyName as String = GetPropertyNameAsStringMethod(MyModel.Description)
So the propertyName variable has "Description" as value.
Check the Darin Dimitrov' answer on this SO thread - Reflection - get property name.
class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
var result = Get<Foo, string>(x => x.Bar);
Console.WriteLine(result);
}
static string Get<T, TResult>(Expression<Func<T, TResult>> expression)
{
var me = expression.Body as MemberExpression;
if (me != null)
{
return me.Member.Name;
}
return null;
}
}
Hope this help..
Here is a helper extension method you can use for any property:
public static class ReflectionExtensions
{
public static string PropertyName<T>(this T owner,
Expression<Func<T, object>> expression) where T : class
{
if (owner == null) throw new ArgumentNullException("owner");
var memberExpression = (MemberExpression)expression.Body;
return memberExpression.Member.Name;
}
}
However, this will only work on instances of a class. You can write a similar extension method that will operate directly on the type instead.
You need to do it using reflection.
There are already loads of posts on stack overflow like this:
How to get current property name via reflection?
Reflection - get property name
Get string name of property using reflection
Reflection - get property name
I believe that the answer will be along the lines of:
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
Create an extension method and then use it where needed.
Private Shared Function GetPropertyName(Of T)(exp As Expression(Of Func(Of T))) As String
Return (DirectCast(exp.Body, MemberExpression).Member).Name
End Function
have a look at this post as well.
I have solved this issue editing a bit #NiranjanKala's source example,
converting the code in vb.Net like this
<System.Runtime.CompilerServices.Extension()> _
Public Function GetPropertyName(Of T, TResult)(expression As Expression(Of Func(Of T, TResult))) As String
Dim [me] = TryCast(expression.Body, MemberExpression)
If [me] IsNot Nothing Then
Return [me].Member.Name
End If
Return Nothing
End Function
Then I am able to call the extension like this
Dim propertyName as String = GetPropertyName(Of MyModel, String)(Function(x) x.Description)
Then propertyName variable has "Description" as string value.

Resources