Stream PDF Byte array from WebAPI to browser - pdf

I'm working in C#.net in a WebAPI...
I have...
WebAPI Controller...
public class GetSMBController : ApiController
{
public HttpResponseMessage GET(int AgencyID, string UserName)
{
var Pdfs = new HttpResponseMessage();
Pdfs = Utilities.Reporting.CreateStandardMapBooklet(AgencyID,UserName);
return Pdfs;
}
}
That calls a method...
public static HttpResponseMessage CreateStandardMapBooklet(int AgencyID, string userName)
{
string baseDataPath = #"\\dvfmweb4\\arcgisserver\basedata\";
string tempDataPath = #"\\dvfmweb4\arcgisserver\tempGrowerData\";
string unitTestSession = "UnitTestSession";
int ShadeType = 1;
bool isInImagery = false;
double MaxSceneSize = 1.5;
bool ScaleBar = true;
int MapSettingID = 0;
bool OverallPage = false;
bool OverallImagery = false;
bool IsRecordKeepingSheet = false;
int RecordKeepingSheetID = 0;
int TemplateID = 1480;
RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport _Pdfs = new RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport(
baseDataPath,
tempDataPath,
unitTestSession,
AgencyID,
ShadeType,
isInImagery,
MaxSceneSize,
ScaleBar,
MapSettingID,
TemplateID,
OverallPage,
OverallImagery,
false,
RecordKeepingSheetID,
userName,
true);
PDF testPDF = new PDF();
byte[] test = null;
try
{
List<RCIS.Mapping.MapDomain.Layout.CreatePdfResponse> pdf = _Pdfs.CreateReports();
foreach (var item in pdf)
{
//PDFInfo info = new PDFInfo();
//info.PdfBytes = item.PdfBytes;
testPDF.Report = item.PdfBytes;
test = item.PdfBytes;
}
}
catch(Exception e)
{
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(test)
};
response.Content = new ByteArrayContent(test);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = String.Format(AgencyID + userName + DateTime.Now.ToString("MMMddyyyy_HHmmss"))
};
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, 60) // Cache for 30s so IE8 can open the PDF
};
return response;
}
Sorry for some of the commented out stuff and goofy variable names...I'm just trying to see if this is a viable thing.
the test object and HttpResponse message Content ARE populated but
I'm receiving this error when I call this from a browser...
This XML file does not appear to have any style information associated with it. The document tree is shown below.
An error has occurred.
Value cannot be null. Parameter name: content
System.ArgumentNullException
at System.Net.Http.ByteArrayContent..ctor(Byte[] content) at MappingServicesWebAPI.Utilities.Reporting.CreateStandardMapBooklet(Int32 AgencyID, String userName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Utilities\Reporting.cs:line 92 at MappingServicesWebAPI.Controllers.GetSMBController.GET(Int32 AgencyID, String UserName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Controllers\MappingController.cs:line 143 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.b__4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)

Related

input :Specified cast is not valid

I tried to execute my application Rest api. Using a breakpoint, I found a problm in this line:
expenses.AmountTTC = Convert.ToDecimal(ttc.Text);
The error is "Specified cast is not valid".
AmountTTC has the type decimal? in the model , same for my service(i have two projects, one for the services and anthor for my mobile application).
private void Button_Clicked(object sender, EventArgs e)
{
ajoutD.Clicked += async delegate
{
try
{
LoginViews expenses = new LoginViews();
expenses.Name = nameLib.Text;
expenses.StartDate = dataDe.Date;
expenses.EndDate = dateAu.Date;
datenow.Date = DateTime.Now;
expenses.Description = description.Text;
expenses.CurrencyId = Convert.ToInt32(devises.Id);
expenses.AmountTTC = Convert.ToDecimal(ttc.Text);
remb.Text = expenses.AmountReimbursed.ToString();
expenses.Remboursable = Convert.ToBoolean(isremboursable);
expenses.Provider = marchand.Text;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(expenses);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await httpClient.PostAsync(url, content);
AuthResponse responseData = JsonConvert.DeserializeObject<AuthResponse>(response?.Content?.ReadAsStringAsync()?.Result);
if (responseData.data.Success)
{
await DisplayAlert("heey", "connexion done", "ok");
}
else
{
await DisplayAlert("wake up !", responseData.data.ErrorMessage, "attention");
}
}catch(Exception eee)
{
string msg = eee.ToString();
}
};
}

Object reference not set to an instance of an object while connecting Microsoft Dynamics GP 2018 with eConnect 18 using .net Framework 4.6.1

I have tried many solutions for this simple error but I couldn't find bug what actually cause it.
Here is some code for reference.
GPController
[HttpPost("testConnection")]
public bool TestConnection()
{
try
{
var data = eConn.GetEntity();
if (data)
{
return true;
}
return false;
}
catch(Exception ex)
{
throw ex;
}
}
eConn.cs
public static bool GetEntity()
{
try
{
string connString = DataAccess.ConnectionString;
eConnectOut myRequest = new eConnectOut();
myRequest.DOCTYPE = "Customer";
myRequest.OUTPUTTYPE = 1;
myRequest.INDEX1FROM = "Customer001";
myRequest.INDEX1TO = "Customer001";
myRequest.FORLIST = 1;
// Create the eConnect requester XML document object
RQeConnectOutType[] eConnectOutType =
new RQeConnectOutType[1] { new RQeConnectOutType()};
eConnectOutType[0].eConnectOut = myRequest;
eConnectType eConnectDoc = new eConnectType();
eConnectDoc.RQeConnectOutType = eConnectOutType;
// Serialize the object to produce an XML document
MemoryStream memStream = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
serializer.Serialize(memStream, eConnectDoc);
memStream.Position = 0;
XmlDocument myDoc = new XmlDocument();
myDoc.Load(memStream);
eConnectMethods eConnCall = new eConnectMethods();
eConnCall.RequireProxyService = false;
// Retrieve the specified customer document
string myCustomer = eConnCall.GetEntity(connString, myDoc.OuterXml);
return true;
}
catch(Exception ex)
{
throw ex;
}
}
In eConn.cs calling GetEntity method I am getting this error.
{System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Dynamics.GP.eConnect.EventLogHelper.AddExceptionHeader(String action, Object[] inputParameters, StringBuilder errorString)
at Microsoft.Dynamics.GP.eConnect.EventLogHelper.CreateEventLogEntry(Exception exception, String action, Object[] inputParameters)
at Microsoft.Dynamics.GP.eConnect.eConnectMethods.GetEntity(String connectionString, String sXML)
at AP.GPServices.Helper.eConn.GetEntity() in D:\projects\APSystem SM\Source Code\AP.GPServices\Helper\eConn.cs:line 46}
I am referring this Programmer guide.
http://www.mypurelogic.com/files/purelogic/files/manuals/econnectprogrammersguide.pdf

How to add screenshot into RallyDev using RAlly API

how to upload the screenshots into rally dev using the rally rest api. I am able to log defects. I need to log screenshots
Here is an example using Rally REST Api Tookit for Java that creates a defect and then creates an attachment on the defect:
public class CreateDefectAddAttachment{
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String projectRef = "/project/12352608219";
String applicationName = "RestExample_createDefectAttachScreenshot";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
//Read User
QueryRequest userRequest = new QueryRequest("User");
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "user#company.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
try {
for (int i=0; i<1; i++) {
//Create a defect
JsonObject newDefect = new JsonObject();
newDefect.addProperty("Name", "bug1234");
newDefect.addProperty("Project", projectRef);
CreateRequest createRequest = new CreateRequest("defect", newDefect);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read defect
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading Defect %s...", ref));
String imageFilePath = "C:/";
String imageFileName = "pic.png";
String fullImageFile = imageFilePath + imageFileName;
String imageBase64String;
long attachmentSize;
// Open file
RandomAccessFile myImageFileHandle = new RandomAccessFile(fullImageFile, "r");
try {
long longLength = myImageFileHandle.length();
long maxLength = 5000000;
if (longLength >= maxLength) throw new IOException("File size >= 5 MB Upper limit for Rally.");
int fileLength = (int) longLength;
// Read file and return data
byte[] fileBytes = new byte[fileLength];
myImageFileHandle.readFully(fileBytes);
imageBase64String = Base64.encodeBase64String(fileBytes);
attachmentSize = fileLength;
// First create AttachmentContent from image string
JsonObject myAttachmentContent = new JsonObject();
myAttachmentContent.addProperty("Content", imageBase64String);
CreateRequest attachmentContentCreateRequest = new CreateRequest("AttachmentContent", myAttachmentContent);
CreateResponse attachmentContentResponse = restApi.create(attachmentContentCreateRequest);
String myAttachmentContentRef = attachmentContentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment Content created: " + myAttachmentContentRef);
//Create the Attachment
JsonObject myAttachment = new JsonObject();
myAttachment.addProperty("Artifact", ref);
myAttachment.addProperty("Content", myAttachmentContentRef);
myAttachment.addProperty("Name", "AttachmentFromREST.png");
myAttachment.addProperty("Description", "Attachment From REST");
myAttachment.addProperty("ContentType","image/png");
myAttachment.addProperty("Size", attachmentSize);
myAttachment.addProperty("User", userRef);
CreateRequest attachmentCreateRequest = new CreateRequest("Attachment", myAttachment);
CreateResponse attachmentResponse = restApi.create(attachmentCreateRequest);
String myAttachmentRef = attachmentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment created: " + myAttachmentRef);
if (attachmentResponse.wasSuccessful()) {
System.out.println("Successfully created Attachment");
} else {
String[] attachmentContentErrors;
attachmentContentErrors = attachmentResponse.getErrors();
System.out.println("Error occurred creating Attachment: ");
for (int j=0; j<attachmentContentErrors.length;j++) {
System.out.println(attachmentContentErrors[j]);
}
}
}catch (Exception e) {
System.out.println("Exception occurred while attempting to create Content and/or Attachment: ");
e.printStackTrace();
}
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating a defect: ");
for (int j=0; i<createErrors.length;j++) {
System.out.println(createErrors[j]);
}
}
}
} finally {
//Release all resources
restApi.close();
}
}
}

Object reference not set to an instance of an object , youtube API

class Program
{
static void Main(string[] args)
{
string Appname;
string developerKey;
string username;
string password;
Appname = "a";
developerKey = "b";
username = "c";
password = "d";
YouTubeRequestSettings settings = new
YouTubeRequestSettings(Appname, developerKey, username, password);
YouTubeRequest request = new YouTubeRequest(settings);
Uri videoEntryUrl = new
Uri("http://www.youtube.com/watch?v=dOShGP0FM1U");
Video video = request.Retrieve<Video>(videoEntryUrl);
Comment MyComment = new Comment();
MyComment.Content = "random tango";
if (video != null)
{
request.AddComment(video, MyComment);
}
else
{
Console.Write("Video was null for some reason!");
Console.ReadKey();
}
}
}
For some reason the video keeps returning null and i can't figure out , i have tried everything i really need help with this project.

Create Registrant using GoToWebinar

I want to create a registrant for a webinar using GoToWebinar API's. I came across the code at gotowebinar api php
I provided my username and password to get the oAuth object. This worked perfectly fine as described.
Now I want to do something like this:
I have a Registration page. When user fills in the required details, selects the 'register to webinar' option and clicks on 'Submit', I want to enrol him for that webinar using CreateRegistrant API. The problem is, I am not able to get the oAuth object without providing username and password. Is there a way to pass this programatically and create oAuth object?
I store my API key, UserID and password in my WebConfig then read them into a Login Object for use when I do authorization. Here's how I do it in C#:
public class Login
{
public string UserId
{ get { return System.Configuration.ConfigurationManager.AppSettings["GTWUserId"]; } }
public string Password
{ get { return System.Configuration.ConfigurationManager.AppSettings["GTWPassword"]; } }
public string APIKey
{ get { return System.Configuration.ConfigurationManager.AppSettings["GTWAPIKey"]; } }
}
public string DoAuthorize()
{
Login lg = new Login();
string sError = "";
// first we need to create the uri for the web request
string uri = String.Format("https://api.citrixonline.com/oauth/access_token?grant_type=password&user_id={0}&password={1}&client_id={2}",
lg.UserId, lg.Password, lg.APIKey);
// then the request to login is created and sent. From the response
// we need to store at least the access token and the organizer key
// to use for further calls
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Accept = "application/json";
request.ContentType = "application/json";
try
{
var response = request.GetResponse();
//the following lines duplicate the response stream so we can read it for
//deserialization and also re-read it and write it out.
using (MemoryStream ms = new MemoryStream())
{
var stream = response.GetResponseStream();
stream.CopyTo(ms);
ms.Position = 0;
stream.Close();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ResponseDirectLogin));
var deserialized = (ResponseDirectLogin)ser.ReadObject(ms);
auth.OauthToken = deserialized.AccessToken;
auth.OrganizerKey = deserialized.OrganizerKey;
}
}
catch (WebException e)
{
using (var sr = new StreamReader(e.Response.GetResponseStream()))
sError = sr.ReadToEnd();
sError = String.Concat(sError, "/n", uri);
}
return sError;
}
public class Auth {
public string OauthToken { get; set; }
public string OrganizerKey { get; set; }
}
public static Auth auth = new Auth(); // This is actually in a BaseControlelr inherited by our MVC Home Controller.
public string DoRegister(string WebinarKey)
{
// Here we authorize if we haven't alerady
if (auth.OauthToken == null)
{
sMessage = DoAuthorize();
}
// first we need to create the uri for the web request
// OrganizerKey is your authorization key for the webinar organizer
string uri = String.Format(#"https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants",
OrganizerKey, WebinarKey);
//then create and serialize the registrant object
// This is for when you have questions on your webinar, you can omit them if you don't have any
List<questions> q = GetQuestionKeys(Key, OrganizerKey);
List<response> responses_ = new List<response>();
foreach (var question in q)
{
response res1 = new response();
res1.questionKey = question.questionKey;
// determine which question and set the response
if (question.question == "question")
{
res1.responseText = "response";
responses_.Add(res1);
}
}
var registrant = new Registrant
{
firstName = FirstName,
lastName = LastName,
email = EmailAddress,
responses = responses_.ToArray()
};
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(registrant);
// then the request to create a registrant is created and sent
// N.B. we need to include the access token to the headers to access
// the user's account and data
try {
WebClient client = new WebClient();
client.Headers = new WebHeaderCollection();
client.Headers.Add("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
client.Headers.Add("Content-type", "application/json");
client.Headers.Add("Authorization", string.Format("OAuth oauth_token={0}", OAuthToken));
try
{
string resp = client.UploadString(uri, "POST", json);
var ok = ser.Deserialize<ResponseCreateRegistrantOk>(resp);
}
catch (WebException e)
{
//if there is an error, e.g. the registrant exists already
// we need an alternative deserialization
Stream s = new MemoryStream();
using (Stream response = e.Response.GetResponseStream())
{
byte[] buffer = new byte[1024];
int byteCount;
do
{
byteCount = response.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
s.Seek(0, SeekOrigin.Begin);
string content = new StreamReader(s, Encoding.UTF8).ReadToEnd();
s.Seek(0, SeekOrigin.Begin);
using (var err = new StreamReader(s))
{
var sb = new StringBuilder("Registration Error\n");
if (content.IndexOf("int_err_code") > -1)
{
var dupe = ser.Deserialize<ResponseCreateRegistrantDuplicate>(err.ReadToEnd());
sb.AppendFormat(String.Format("Error Code: {0}<br />", dupe.ErrorCode));
sb.AppendFormat(String.Format("Message: {0}<br />", dupe.Message));
}
else
{
var dupe = ser.Deserialize<ResponseCreateRegistrantDuplicate>(err.ReadToEnd());
sb.AppendFormat(String.Format("Description: {0}<br />", dupe.Description));
//sb.AppendFormat(String.Format("Incident: {0}<br />", dupe.Incident));
//sb.AppendFormat(String.Format("Registrant key: {0}<br />", dupe.RegistrantKey));
sb.AppendFormat(String.Format("Join Url: {0}<br />", dupe.JoinUrl));
}
sMessage = sb.ToString();
}
}
} catch (Exception exc) {
exc.Data.Add("stringInfo", "inside");
return "";
}
return sMessage;
}