how to return list in asp.net to a json post - asp.net

So in my web service i get the data from textboxes search it in database and create letter objects.Then add those objects to a list.my question is how do i return the list to my web page and create divs. for example if service finds 5 letters how i do i return them and create 5 different divs with their data.Thanks in advance
public Letter(string lid, string companyname, string personname, string email, string fax, string phone, string industryname, string teamname, string sender, string statusname, string description, string date)
{
LID = lid;
CompanyName = companyname;
PersonName = personname;
Email = email;
Fax = fax;
Phone = phone;
IndustryName = industryname;
TeamName = teamname;
Sender = sender;
StatusName = statusname;
Description = description;
Date = date;
}

You just need to decorate your web services with ScriptService attribute and it will return response in raw json format. For more info check it out here and you also want to check out this.
Once you get Json response, you can do something like this to render the output as per your requirement. It's not exactly what you're looking for but it will give you an idea how to proceed further.

In .net 3.5 you can create json by using the System.Web.Script.Serialization.JavaScriptSerializer otherwise you have to do it manually or by a 3rd party component.

Related

Microsoft Teams: How to send a Message/Card to a User from an external App without an Bot

we have an external ASP.NET 4.7 App (in Azure App Service), which should send Messages/Cards to one specific User in Teams (without an Bot).
I managed to send Cards to Channels via the Connector/WebHook, but cannot target an specific User.
How can i do this / which Services are needed?
please as simple as possible :-)
thank you
==========================
update: Sample Code:
Private Shared Sub SendToTeams(ChannelPath As AppSettingsKey, Card As TeamsCard)
If String.IsNullOrWhiteSpace(ChannelPath) Then Return
Dim Channel = AppSettings.GetAppSetting(ChannelPath)
If String.IsNullOrWhiteSpace(Channel) Then Return
Dim ChannelWebHook = "https://outlook.office.com"
Dim Client = New RestClient(ChannelWebHook)
Dim Req = New RestRequest(Method.POST) With {
.Resource = Channel,
.RequestFormat = DataFormat.Json
}
Dim JSON = Card.SaveJSON(False)
Req.AddParameter("application/json; charset=utf-8", JSON, ParameterType.RequestBody)
Dim Erg = Client.Execute(Req)
Logger.Info("Teams:", Erg.StatusCode)
End Sub
And some Helpers:
Friend Class TeamsCard
<JsonProperty(PropertyName:="#context")> Public Property context As String = "https://schema.org/extensions"
<JsonProperty(PropertyName:="#type")> Public Property type As String = "MessageCard"
Public Property themeColor As String = "ff6100"
Public Property title As String = "Title"
Public Property summary As String = "Summary"
Public Property text As String = "Text"
Public Property potentialAction As New List(Of TeamsCardAction)
End Class
Friend Class TeamsCardAction
<JsonProperty(PropertyName:="#type")> Public Property type As String = "OpenUri"
Public Property name As String = "ButtonText"
Public Property targets As New List(Of TeamsCardButtonTarget)
Public Sub New(Text As String, URI As String)
name = Text
targets.Add(New TeamsCardButtonTarget With {.uri = URI})
End Sub
End Class
Friend Class TeamsCardButtonTarget
Public Property os As String = "default"
Public Property uri As String = "https://google.com"
End Class
Currently, Office 365 Connectos only support only channels. These can't be user to send message/card to individual users.
Only option to send message to Microsoft Teams individual user would be using Bots.

Can I disable model binding and use the raw request body in an action in dotnet core?

I want to setup an endpoint for testing webhooks from third parties. Their documentation is uniformly poor and there is no way ahead of time to tell exactly what I will be getting. What I've done is setup an ApiController that will just take a request and add a row to a table with what they are sending. This lets me at least verify they are calling the webhook, and to see the data so I can program to it.
// ANY api/webook/*
[Route("{*path}")]
public ActionResult Any(string path)
{
string method = Request.Method;
string name = "path";
string apiUrl = Request.Path;
string apiQuery = Request.QueryString.ToString();
string apiHeaders = JsonConvert.SerializeObject(Request.Headers);
string apiBody = null;
using (StreamReader reader = new StreamReader(Request.Body))
{
apiBody = reader.ReadToEnd();
}
Add(method, name, apiUrl, apiQuery, apiHeaders, apiBody);
return new JsonResult(new { }, JsonSettings.Default);
}
This works great, except for this new webhook I am usign that posts as form data so some middleware is reading the body and it ends up null in my code. Is there any way to disable the model processing so I can get at the request body?
You could actually use model binding to your advantage and skip all that stream reading, using the FromBody attribute. Try this:
[Route("{*path}")]
[HttpPost]
public ActionResult Any(string path, [FromBody] string apiBody)

How can the Identity.GetUserId() be made to return a Guid instead of a string?

I am using ASP.Net Identity 2 but soon hope to change to Identity 3 when it becomes more stable (anyone know when that might be?). Here's a sample of my code:
content.ModifiedBy = User.Identity.GetUserId();
The Content table stores ModifedBy as a UNIQUEIDENTIFIER and the Content object assigns a datatype of Guid to ModifiedBy
When I look at the signature for GetUserId() it returns a string.
So how can I take the users UserId and put it into the ModifiedBy which is a Guid?
A guid can take a string as a constructor
content.ModifiedBy = new Guid( User.Identity.GetUserId());
You can use Guid.Parse() or Guid.TryParse()
content.ModifiedBy = Guid.Parse(User.Identity.GetUserId());
https://msdn.microsoft.com/en-us/library/system.guid.parse%28v=vs.110%29.aspx
As I was using same method over and over I added the following extension:
public static class ExtensionMethods
{
public static Guid ToGuid(this string value)
{
Guid result= Guid.Empty;
Guid.TryParse(value, out result);
return result;
}
}
and then I used this:
User.Identity.GetUserId().ToGuid()

Unit Test .Net on Simple EF Function

I have 3 layers in Asp.Net Web API. The controller layer, service layer and repository layer implemented using EF.
I am new to unit testing and have a simple function that gets a person by their id in the database and nothing else.
Basically the service layer calls
Unit_Work.Person_Repository.GetPersonByID(id);
and the Repository does this:
return context.chapters.Where(p=>p.chapterID==id).SingleOrDefault();
What kind of Unit Test would i write on this.
should i use the database or a mock implementation.
I thought of using Sql Server Compact populating it with a mock person and then trying to get that person by ID is this correct.?
Thanks in advance to all those that answer.
If you are using entity framework you can't unit test your data access layer.
Solution provided by Erik Alsmyr is very wrong!
Look here why - What's the point of in memory IDbSet?.
When you use in memory db sets you are running Linq to Objects. When you use EF's DbContext your Linq is converted to SQL. Those are two different things!
It is very easy to write code that will work with in memory db set (all your unit tests will pass and you will be happy) just to notice runtime error first time you try to hit database.
Let's modify this code a bit. I don't think FULLNAME should have setter if we are using FIRSTNAME, LASTNAME. It should be calculated from FIRSTNAME and LASTNAME.
class User
{
public string FIRSTNAME { get; set; }
public string LASTNAME { get; set; }
public string FULLNAME
{
get { return string.Format("{0}, {1}", LASTNAME, FIRSTNAME }
}
User(string firstName, string lastName)
{
this.FIRSTNAME = firstName;
this.LASTNAME = lastName;
}
}
Now you can write test like this and it will pass (of course after you implement it in controller)
public IMyEntities GetRepoWithUsers(params User[] users)
{
var inMemoryUsers = new InMemoryDbSet<User>();
var mockData = new Mock<IMyEntities>();
mockData.Setup(m => m.Users).Returns(inMemoryUsers);
return mockData.Object;
}
[Test]
public void GetUserByFullname()
{
var ankaArne = new User("Arne", "Anka");
var bjornBertil = new User("Bertil", "Björn");
var repo = GetRepoWithUsers(ankaArne, bjornBertil);
var usersController = new UsersController(repo);
var found = usersController.GetUser("Anka, Arne");
Assert.NotNull(found);
Assert.AreEqual("Anka", found.LASTNAME);
Assert.AreEqual("Arne", found.FIRSTNAME);
}
But when you run it against 'real' DbContext and 'real' DbSet it will throw because you can't do Linq queries on calculated properties. Only on those that are mapped to database columns. So what's the point of that test?
You can use the xml/ .csv file for data. ie, you need to fetch the ID, chapter details from the xml file inside the unit test project. Then you have to pass the id as the parameter then check the return values with the data fetch from xml file. if you dont understand let me know. You cn create unit test project by add-new project options. then on vs2010 ther r options to add xml file for fetching the data to be tested.
your 3rd question is also correct. u cn populate the data from database and check the data with the return value
I recommend mocking and injecting an Entity framework context into your repository.
We do this using something similar to http://nuget.org/packages/FakeDbSet/
Then our unit tests look like this:
[TestFixture]
class UsersControllerTester
{
private Mock<IMyEntities> mockData = null;
[SetUp]
public void Setup()
{
// Create fake data
var inMemoryUsers = new InMemoryDbSet<User>();
inMemoryUsers.Add(new User { ID = 1, FIRSTNAME = "Arne", LASTNAME = "Anka", EMAIL = "arne.anka#email.com", FULLNAME = "Anka, Arne", USERNAME = "arne.anka" });
inMemoryUsers.Add(new User { ID = 2, FIRSTNAME = "Bertil", LASTNAME = "Björn", EMAIL = "bertil.bjorn#email.com", FULLNAME = "Björn, Bertil", USERNAME = "bertil.bjorn" });
inMemoryUsers.Add(new User { ID = 3, FIRSTNAME = "Carl", LASTNAME = "Cool", EMAIL = "carl.cool#email.com", FULLNAME = "Cool, Carl", USERNAME = "carl.cool" });
inMemoryUsers.Add(new User { ID = 4, FIRSTNAME = "David", LASTNAME = "Dûsk", EMAIL = "david.dusk#email.com", FULLNAME = "Dûsk, David", USERNAME = "david.dusk" });
// Create mock unit of work
mockData = new Mock<IMyEntities>();
mockData.Setup(m => m.Users).Returns(inMemoryUsers);
}
[Test]
public void GetUser()
{
// Test
var usersController = new UsersController(mockData.Object);
// Invoke
User user1 = usersController.GetUser("1");
// Assert
Assert.NotNull(user1);
Assert.AreEqual(1, user1.ID);
Assert.AreEqual("Anka", user1.LASTNAME);
}

how we send multiple values to server from android

public boolean setContacts(String name, String number) {
serviceUrl = "http://...../sample.php?method=setcontacts";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("num", number));
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(serviceUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
..................
}
In this code i sending a single row having name and number to server its working fine,
but i want to send a list of name and number like
ArrayList<Strng[]> contactsList =...............;
so how i can implement this
public boolean setContacts(ArrayList<String[]> contactsList) {
}
if you have any alternative way please suggest me thanks in advance.
Serialize the information as a string and send it in the POST body. There are many ways to skin this cat, but the big 3 are:
Form encoding
XML
JSON

Resources