I'm integrating with BigBlueButton API with Asp Net MVC. But I can't read the response xml file back from api .
It's a force module project.
My code:
public ActionResult GetMeetings()
{
List<AllMeetings> allMeetings = new List<AllMeetings>();
XmlSerializer serializer = new XmlSerializer(typeof(List<AllMeetings>), "response");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://bbb.hsu.ac.ir/bigbluebutton/api/getMeetings?checksum=aca692f682f06312cb43f14564ddf96cb76925ed");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader sr = new StreamReader(dataStream);
List<AllMeetings> allMeeting =(List<AllMeetings>)serializer.Deserialize(sr);
return View(allMeeting);
}
I coded a class so that I could define attributes as xml element and I use them as an enumerable model
namespace BBBJavaScriptTest
{
[Serializable]
[XmlType("response")]
public class AllMeetings
{
[XmlElement(ElementName = "meetingName")]
public string meetingName { get; set; }
[XmlElement(ElementName = "meetingID")]
public string meetingID { get; set; }
[XmlElement(ElementName = "createDate")]
public string createDate { get; set; }
[XmlElement(ElementName = "voiceBridge")]
public string voiceBridge { get; set; }
[XmlElement(ElementName = "moderatorPW")]
public string moderatorPW { get; set; }
public AllMeetings()
{
}
}
and the view part is Razor View:
#model IEnumerable<AllMeetings>
#{
ViewBag.Title = "GetMeetings";
Layout = null;
}
<h2>GetMeetings</h2>
<table class="table table-bordered">
<tr>
<td>meetingID</td>
<td>meetingName</td>
<td>createDate</td>
<td>voiceBridge</td>
<td>moderatorPW</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.meetingID</td>
<td>#item.meetingName</td>
<td>#item.createDate</td>
<td>#item.voiceBridge</td>
<td>#item.moderatorPW</td>
</tr>
}
</table>
Response sample:
<response>
<returncode>SUCCESS</returncode>
<meetings>
<meeting>
<meetingName>****</meetingName>
<meetingID>****</meetingID>
<internalMeetingID>
****
</internalMeetingID>
<createTime>1603543982183</createTime>
<createDate>Sat Oct 24 16:23:02 IRST 2020</createDate>
<voiceBridge>78409</voiceBridge>
<dialNumber>****</dialNumber>
<attendeePW>ap</attendeePW>
<moderatorPW>mp</moderatorPW>
<running>true</running>
<duration>400</duration>
<hasUserJoined>true</hasUserJoined>
<recording>false</recording>
<hasBeenForciblyEnded>false</hasBeenForciblyEnded>
<startTime>1603543982435</startTime>
<endTime>0</endTime>
<participantCount>1</participantCount>
<listenerCount>1</listenerCount>
<voiceParticipantCount>0</voiceParticipantCount>
<videoCount>0</videoCount>
<maxUsers>0</maxUsers>
<moderatorCount>1</moderatorCount>
<attendees>
<attendee>
<userID>****</userID>
<fullName>****</fullName>
<role>MODERATOR</role>
<isPresenter>true</isPresenter>
<isListeningOnly>true</isListeningOnly>
<hasJoinedVoice>false</hasJoinedVoice>
<hasVideo>false</hasVideo>
<clientType>HTML5</clientType>
</attendee>
</attendees>
<metadata> </metadata>
<isBreakout>false</isBreakout>
</meeting>
</meetings>
</response>
I solved the problem , And here is the solution :
XDocument doc = XDocument.Load(sr);
List<AllMeetings> meetings = new List<AllMeetings>();
foreach (XElement element in doc.Element("response").Elements("meetings").Elements("meeting"))
{
AllMeetings newMeeting = new AllMeetings();
newMeeting.meetingName = (string)element.Element("meetingName");
meetings.Add(newMeeting);
}
return View(meetings);
Related
This is my code in ASP.NET CORE 3.0, when I save the image using type as IFormFile in View Model and as Byte in model. Now I want to retrieve this image in Edit Method. I am Unable to display image. Here is my code
var formData = new Student()
{
AppUserID = userId,
FirstName = model.FirstName,
MatricMarks = model.MatricMarks,
CollegeName = model.CollegeName,
HSSCMarks = model.HSSCMarks,
};
if (model.Profile != null && model.Profile.FileName != "" && model.Profile.FileName != null)
{
IFormFile file = model.Profile;
if (file.Length > 0)
//Convert Image to byte and save to database
{
using (var stream = new MemoryStream())
{
await file.OpenReadStream().CopyToAsync(stream);
formData.Profile = stream.ToArray();
}
}
}
ViewModel
public class StudentSignUpViewModel
{
public string Username { get; set; }
public string CollegeName { get; set; }
public string HSSCMarks { get; set; }
public IFormFile Profile { get; set; }
}
here is Model class
public string MatricMarks { get; set; }
public string CollegeName { get; set; }
public string HSSCMarks { get; set; }
[Required]
public byte[] Profile { get; set; }
And here is Edit[GET] Method where Im trying to display image, please guide what went wrong
public IActionResult Edit(int? id)
{
StudentSignUpViewModel model = new StudentSignUpViewModel();
if (id == null)
{
return NotFound();
}
var student = _context.Students.Where(x => x.StudentId == id.Value).Include(x=>x.AppUser).FirstOrDefault();
model.MatricMarks = student.MatricMarks;
model.CollegeName = student.CollegeName;
model.HSSCMarks = student.HSSCMarks;
model.CoursesArray = student.Courses;
var base64 = Convert.ToBase64String(student.Profile);
ViewBag.imgSrc = string.Format("data:image/jpg;base64,{0}",model.Profile, base64);
}
View Method where I'm Trying to display image
<div class="form-group">
<img src="#ViewBag.imgSrc" class="profile-user-img img-responsive img-circle" alt="User profile picture" />
<label asp-for="Username" class="control-label"></label>
<input asp-for="Username" class="form-control" />
Note: Irrelevant Code is cut out.
To display binary image using base64 string, please modify your code as below.
var base64 = Convert.ToBase64String(student.Profile);
ViewBag.imgSrc = string.Format("data:image/jpg;base64,{0}", base64);
Besides, you can also save these image file(s) on your web server rather than storing them in database, so that your app can serve these images directly to clients.
For more information about serving static files, please check: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1
I have POST query with Form data with files and I need to send the same data to another POST request.
I'm going to use for this HttpClient class.
Is there a way to copy all Request.Form data and insert them to new request? Or I need to add every param?
I mean something like this:
var httpClient = new HttpClient();
var httpResponseMessage = await httpClient.PostAsync("some_url", Request.Form);
Is there a way to copy all Request.Form data and insert them to new request? Or I need to add every param?
You need to add every param like below:
Model in ProjectA:
public class FormData
{
public int Id { get; set; }
public IFormFile File { get; set; }
public string Name { get; set; }
}
View in ProjectA:
#model FormData
<form asp-action="Post" enctype="multipart/form-data">
<div>
Id:<input asp-for="Id"/>
</div>
<div>
Name:<input asp-for="Name"/>
</div>
<div>
FIle:<input asp-for="File" />
</div>
<div>
<input type="submit" value="create" />
</div>
</form>
Controller in ProjectA:
[HttpPost]
public async Task<IActionResult> Post(FormData formData)
{
HttpClient client = new HttpClient();
// var formData = HttpContext.Request.Form;
client.BaseAddress = new Uri("http://localhost:63331");//your applicationUrl
client.DefaultRequestHeaders.Accept.Clear();
var multiContent = new MultipartFormDataContent();
var file = formData.File;
if (file != null)
{
var fileStreamContent = new StreamContent(file.OpenReadStream());
multiContent.Add(fileStreamContent, "File", file.FileName);
}
multiContent.Add(new StringContent(formData.Id.ToString()), "id");
multiContent.Add(new StringContent(formData.Name.ToString()), "name");
var response = await client.PostAsync("/api/values", multiContent);
//do your stuff...
return Ok();
}
Model in ProjectB:
public class FormDataModel
{
public int Id { get; set; }
public IFormFile File { get; set; }
public string Name { get; set; }
}
Controller in ProjectB:
[HttpPost]
public void Post([FromForm]FormDataModel model)
{
//...
}
Result:
I'm trying to create an RSS feed for a ServiceStack Service. I've followed various examples as closely as I can. My problem is that I get no output and I am not sure how to troubleshoot the issue. I suspect I have done something wrong on the serialisation. Here is (a simplified version of) what I have
My DTO's are
using System.Collections.Generic;
using ServiceStack;
using Library;
[Route("/MyCollection/Tomorrow/{ID}", "GET, POST")]
[Api("MyCollections Delivery")]
public class MyCollectionTomorrow
: IReturn<MyCollectionTomorrowResponse>
{
public long ID { get; set; }
}
public class MyCollectionTomorrowResponse : IHasResponseStatus
{
public long ID { get; set; }
public List<MyCollection> Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class MyCollection
{
public string Description { get; set; }
public string MyCollectionDayOfWeek { get; set; }
public DateTime MyCollectionDate { get; set; }
public bool Assisted { get; set; }
public string RoundType { get; set; }
public string Description { get; set; }
}
My service is
using System;
using Library;
using ServiceStack;
using ServiceStack.Configuration;
using System;
using Library;
using ServiceStack;
using ServiceStack.Configuration;
using MyCollection.Tomorrow;
using MyCollections.Tomorrow;
public class MyCollectionTomorrowService : Service
{
public object Any(WasteCollectionTomorrow request)
{
int id;
var param = new CollectionTomorrow();
param.ID = ID;
var response = client.Get<CollectionTomorrowResponse>(param);
return response;
}
catch (Exception ex)
{
var response = new CollectionTomorrowResponse();
response.Result = null
var status = new ResponseStatus { Message = ex.Message, StackTrace = ex.StackTrace };
response.ResponseStatus = status;
return response;
}
}
}
and my media type is
namespace DataFeedServices
{
using System;
using System.IO;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using ServiceStack;
using ServiceStack.Data;
using ServiceStack.Web;
using MyCollections.Tomorrow;
public class RssFormat
{
private const string RssContentType = "application/rss+xml";
public static void Register(IAppHost appHost)
{
appHost.ContentTypes.Register(RssContentType, SerializeToStream, DeserializeFromStream);
}
public static void SerializeToStream(IRequest req, object response, Stream stream)
{
StreamWriter sw = null;
try
{
var syndicationFeedResponse = response as MyCollectionResponse;
sw = new StreamWriter(stream);
if (response != null)
{
WriteRssCollectionFeed(sw, syndicationFeedResponse);
}
}
finally
{
if (sw != null)
{
sw.Dispose();
}
}
}
public static void WriteRssCollectionFeed(StreamWriter sw, MyCollectionResponse Mycollections)
{
const string Baseuri = "example.com";
try
{
var uri = new Uri(Baseuri);
var syndicationFeed = new SyndicationFeed(
"MyCollection Service",
"Mycollections " ,
uri);
syndicationFeed.Authors.Add(new SyndicationPerson("email#mysite.com"));
if (Mycollections.Result != null)
{
foreach (var cats in Mycollections.Result)
{
syndicationFeed.Categories.Add(new SyndicationCategory(cats.RoundID));
}
}
syndicationFeed.Generator = "MyApp";
syndicationFeed.Copyright = new TextSyndicationContent("Copyright 2015");
syndicationFeed.LastUpdatedTime = DateTime.Now;
if (Mycollections.Result != null)
{
// set items
foreach (var coll in Mycollections.Result)
{
var item = new SyndicationItem { Title = new TextSyndicationContent(coll.CollectionDate) };
item.Links.Add(new SyndicationLink(uri));
item.Authors.Add(new SyndicationPerson("email#mysite.com"));
var itemContent = new StringBuilder();
itemContent.Append("My Item content");
item.Content = new TextSyndicationContent(
itemContent.ToString(),
TextSyndicationContentKind.Plaintext);
}
}
Rss20FeedFormatter rssFeed = syndicationFeed.GetRss20Formatter();
var xwriter = XmlWriter.Create(sw);
rssFeed.WriteTo(xwriter);
}
catch (Exception)
{
throw new Exception("Something bad happened");
}
}
public static object DeserializeFromStream(Type type, Stream stream)
{
throw new NotImplementedException();
}
}
}
Since your ContentType is not reusable and coupled to a specific MyCollectionResponse, it's easier to just return a raw string with the RSS XML:
[AddHeader(ContentType = "application/rss+xml")]
public object Any(WasteCollectionTomorrow request)
{
//..
return rssXml;
}
You can also write it directly to the Response Output Stream with something like:
public object Any(WasteCollectionTomorrow request)
{
//..
base.Response.ContentType = "application/rss+xml";
RssFormat.SerializeToStream(response, Response.OutputStream);
base.Response.EndRequest();
return null;
}
I am trying to pass data from controller to view. I have searched the web but could not find a solution.
if I do this it works:
Controller:
var yyy = (from a in Connection.Db.Authorities select a) ;
ViewBag.data = yyy;
View:
#foreach(var item in ViewBag.data)
{
#item.Value
}
But the following code does not work:
Controller:
var yyy = (from a in Connection.Db.Authorities select new {Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)}) ;
ViewBag.data = yyy;
View:
#foreach(var item in ViewBag.data)
{
#item.Value
}
It gives "item does not contain a definition for Value" for the view file.
Any help would be great.
Thank you.
-edited: updated the second controller linq query. and corrected the first controller linq query.
It's because You already select Value and Value has no such property as Value. You should change in controller:
var yyy = (from a in Connection.Db.Authorities select a.Value); to
var yyy = (from a in Connection.Db.Authorities select a);
OR change the view to
#foreach(var item in ViewBag.data)
{
#item
}
//////////////////////////////////////////////// EDITS ////////////////////////////////////////////////
Than You should not use anonymous object. You should create ViewModelClass. For Example:
public class AuthoritiesViewModel
{
public string Value { get; set; }
public string TypeCode { get; set; }
public string Return { get; set; }
}
And change your controller:
var yyy = (from a in Connection.Db.Authorities select new AuthoritiesViewModel{ Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)});
ViewBag.data = yyy;
and in your view you will be able to use:
<table>
<tr>
<th>Value</th>
<th>TypeCode</th>
<th>Return</th>
</tr>
#foreach(AuthoritiesViewModel item in ViewBag.data)
{
<tr>
<td>#item.Value<td>
<td>#item.TypeCode<td>
<td>#item.Return<td>
</tr>
}
</table>
Also, I have a question to You. Why do You use ViewBag to pass data from controller to view? Why don't You use Model to pass these data to view according to MVC pattern?
//////////////////////////////////////////////// MORE EDITS ////////////////////////////////////////////////
To send more than one query result You can create more complex model. For example:
public class AuthoritiesViewModel
{
public string Value { get; set; }
public string TypeCode { get; set; }
public string Return { get; set; }
}
public class AnotherQueryViewModel
{
public string AnotherQueryValue { get; set; }
public string AnotherQueryTypeCode { get; set; }
public string AnotherQueryReturn { get; set; }
}
public class ModelClass
{
IEnumerable<AuthoritiesViewModel> Authorities { get; set; }
IEnumerable<AnotherQueryViewModel> AnotherQueryResults { get; set; }
}
And change the controller:
var yyy = (from a in Connection.Db.Authorities select new AuthoritiesViewModel{ Value = a.Value, TypeCode = a.TypeCode, Return = Calculate(a.Return)});
// do your another select
var zzz = (from smthing select new AnotherQueryViewModel ...)
// create model instance
ModelClass model = new ModelClass()
{
Authorities = yyy.AsEnumerable(),
AnotherQueryResults = zzz..AsEnumerable()
}
// return view with model
return View("view", model);
and in view you can use:
#model ModelClass
#*display first query result*#
<table>
<tr>
<th>Value</th>
<th>TypeCode</th>
<th>Return</th>
</tr>
#foreach(AuthoritiesViewModel item in Model.Authorities)
{
<tr>
<td>#item.Value<td>
<td>#item.TypeCode<td>
<td>#item.Return<td>
</tr>
}
</table>
#*display second query result*#
<table>
<tr>
<th>Another Query Value</th>
<th>Another Query TypeCode</th>
<th>Another Query Return</th>
</tr>
#foreach(AnotherQueryViewModel item in Model.AnotherQueryResults)
{
<tr>
<td>#item.AnotherQueryValue<td>
<td>#item.AnotherQueryTypeCode<td>
<td>#item.AnotherQueryReturn<td>
</tr>
}
</table>
use sth like this
ViewBag.qualification = new SelectList(db.Lookups.Where(x => x.lookup_type == "Qualification"), "lookup_content", "lookup_content");
I am trying to implement a payment gateway(INTUIT payment gateway). I would like to serialize an xml to an model class and save into my database. I am using Desktop Model for intuit payment gateway, as the hosted model is a pain to get working with especially ssl certificates, so i dont want to try that.
I must mention i am able to get the response using the below mentioned code, where i am stuck at the moment is serialize the xml and save the response into the database. This xml is pulled from a folder in my xmlfiles folder located in my project.
For sample xml format, check out this one. https://ipp.developer.intuit.com/0085_QuickBooks_Windows_SDK/qbms/0060_Documentation/Sending_Requests
this is an xml file i am trying to post to url (https://merchantaccount.ptc.quickbooks.com/j/AppGateway)
<?xml version="1.0"?>
<?qbmsxml version="4.5"?>
<QBMSXML>
<SignonMsgsRq>
<SignonDesktopRq>
<ClientDateTime>2012-07-25T17:13:45</ClientDateTime>
<ApplicationLogin>abc.abc.us</ApplicationLogin>
<ConnectionTicket>TGT-1-g42FGaMfOTQ82GcWFBpsuQ</ConnectionTicket>
</SignonDesktopRq>
</SignonMsgsRq>
<QBMSXMLMsgsRq>
<CustomerCreditCardChargeRq>
<TransRequestID>4540453787200</TransRequestID>
<CreditCardNumber>4111111111111111</CreditCardNumber>
<ExpirationMonth>12</ExpirationMonth>
<ExpirationYear>2016</ExpirationYear>
<IsCardPresent>false</IsCardPresent>
<Amount>10.00</Amount>
</CustomerCreditCardChargeRq>
</QBMSXMLMsgsRq>
</QBMSXML>
The Controller i use to make a post to the url
public ActionResult Index()
{
WebRequest req = null;
WebResponse rsp = null;
string fileName = Server.MapPath("~/XMLData/XMLFile1.xml");
string uri = "https://merchantaccount.ptc.quickbooks.com/j/AppGateway";
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "application/x-qbmsxml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
// var resp = (Object)rsp.GetResponseStream();
if (rsp != null)
{
StreamReader inStream = new StreamReader(rsp.GetResponseStream());
var data = inStream.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(data);
string path = Server.MapPath("~/XMLData/SampleXmlE2E.xml");
xmlDoc.Save(path);//regenerates the xml file in different system.
}
return View();
//XElement root = new XElement("root");
//root.Add(new XElement("element1"));
//root.Add(new XElement("element2"));
//root.Add(new XAttribute("attribute1", "a value"));
//return new XmlResult(root);
}
private string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
private string SendRequest(Uri UriObj, string data)
{
string _result;
var request = (HttpWebRequest)WebRequest.Create(UriObj);
request.Method = "POST";
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
var streamResponse = response.GetResponseStream();
var streamRead = new StreamReader(streamResponse);
_result = streamRead.ReadToEnd().Trim();
streamRead.Close();
streamResponse.Close();
response.Close();
return _result;
}
Any help would be appreciated. Thanks
Varun,
[Edit -update]
Based on this XML:
<?qbmsxml version="4.5"?>
<QBMSXML>
<SignonMsgsRq>
<SignonDesktopRq>
<ClientDateTime>2012-07-25T17:13:45</ClientDateTime>
<ApplicationLogin>app.app.login.url</ApplicationLogin>
<ConnectionTicket>TGT-1-g42FGaMfOTQ82GcWFBpsuQ</ConnectionTicket>
</SignonDesktopRq>
</SignonMsgsRq>
<QBMSXMLMsgsRq>
<CustomerCreditCardChargeRq>
<TransRequestID>4540453787200</TransRequestID>
<CreditCardNumber>4111111111111111</CreditCardNumber>
<ExpirationMonth>12</ExpirationMonth>
<ExpirationYear>2016</ExpirationYear>
<IsCardPresent>false</IsCardPresent>
<Amount>10.00</Amount>
</CustomerCreditCardChargeRq>
</QBMSXMLMsgsRq>
</QBMSXML>
Here's the class structure that you'd need to deserialize into as per the example above:
[XmlRoot("QBMSXML")]
public class QbmsXml
{
[XmlElement("SignonMsgsRq")]
public SignonMsgsRq SignonMsgsRq { get; set; }
[XmlElement("QBMSXMLMsgsRq")]
public QbmsXmlMsgsRq QbmsXmlMsgsRq { get; set; }
}
public class SignonMsgsRq
{
[XmlElement("SignonDesktopRq")]
public SignonDesktopRq SignonDesktopRq { get; set; }
}
public class SignonDesktopRq
{
[XmlElement("ClientDateTime")]
public DateTime ClientDateTime { get; set; }
[XmlElement("ApplicationLogin")]
public string ApplicationLogin { get; set; }
[XmlElement("ConnectionTicket")]
public string ConnectionTicket { get; set; }
}
public class QbmsXmlMsgsRq
{
[XmlElement("CustomerCreditCardChargeRq")]
public CustomerCreditCardChargeRq CustomerCreditCardChargeRq { get; set; }
}
public class CustomerCreditCardChargeRq
{
[XmlElement("TransRequestID")]
public Int64 TransRequestID { get; set; }
[XmlElement("CreditCardNumber")]
public string CreditCardNumber { get; set; }
[XmlElement("ExpirationMonth")]
public int ExpirationMonth { get; set; }
[XmlElement("ExpirationYear")]
public int ExpirationYear { get; set; }
[XmlElement("IsCardPresent")]
public bool IsCardPresent { get; set; }
[XmlElement("Amount")]
public double Amount { get; set; }
}
Just use the xmlSerialiser along the lines of:
class Program
{
private static T DeSerialize<T>(string fromXmlFile) where T: class
{
if (!File.Exists(fromXmlFile))
{
return default(T);
}
T deserializedClass;
var serializer = new XmlSerializer(typeof(T));
// ToDo: add error catching etc
using (var reader = new StreamReader(fromXmlFile))
{
deserializedClass = (T)serializer.Deserialize(reader);
}
return deserializedClass;
}
static void Main(string[] args)
{
var yourXmlFilePath = #"d:\temp\xmltest.xml";
var deserializedClass = DeSerialize<QbmsXml>(yourXmlFilePath);
Console.WriteLine(deserializedClass
.QbmsXmlMsgsRq
.CustomerCreditCardChargeRq.Amount);
Console.Read();
}
}
hope this helps.