This may be a stupid question, but how is it possible to add an extra Link header to a response in Nancy?
I can't do that
context.Response.Headers.Add("Link", "value");
because that fails if there is already a header set. I also cannot use the extension
context.Response.WithHeader("Link", "value");
because it replaces any preexisting headers.
So isn't there a convenient way to work with multiple headers?
This is what I do with an extension method. Notice the check to see if the Link header already exists
public static Response AsCreatedResourceWithLinks(this IResponseFormatter formatter, Resource resource)
{
return CreateResponse(formatter, resource.Id.ToString(), resource.Links);
}
private static Response CreateResponse(IResponseFormatter formatter, string id, IEnumerable<ResourceLink> links = null)
{
string url = formatter.Context.Request.Url.ToString();
var response = new Response { StatusCode = HttpStatusCode.Created, Headers = { { "Location", url + "/" + id } } };
if (links != null && links.Any())
{
foreach (var resourceLink in links)
{
var link = "<" + url + "/" + resourceLink.Link + ">; anchor=\"" + url + "/" + resourceLink.Anchor + "\"; rel=\"" + resourceLink.Rel + "\"";
if (response.Headers.ContainsKey("Link"))
{
response.Headers["Link"] += "," + link;
}
else
{
response.Headers.Add("Link", link);
}
}
}
return response;
}
The Resource & ResourceLink classes look like so:
public class Resource
{
public int Id { get; set; }
public List<ResourceLink> Links { get; set; }
}
public class ResourceLink
{
public string Link { get; set; }
public string Anchor { get; set; }
public string Rel { get; set; }
}
The usage is then like so:
Post["/"] = _ =>
{
//Returns Id and Links for Location/Links headers
var resource = something.SaveResource();
return Response.AsCreatedResourceWithLinks(resource);`
}
According to the RFC the Link Header admits multiple values separated by comma(",").
Link: </TheBook/chapter2>; rel="previous"; title*=UTF-8'de'letztes%20Kapitel,
</TheBook/chapter4>; rel="next"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel
So maybe you should add your multiple links manually and then create the header.
String link1 = #"</TheBook/chapter2>; rel="previous"; title*=UTF-8'de'letztes%20Kapitel";
String link2 = #"</TheBook/chapter4>; rel="next"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel";
String linkHeader = link1+","+link2;
context.Response.Headers.Add("Link", linkHeader);
Related
I created a Apex Class like
Public class test_Controller
{
Public test_Controller() { }
Public void send(set<id> oppIds)
{
List<Oppurtunity> OppLst =[Select Name from Opportunity where id IN: oppIds];
Private static string integration_key = 'abcd';
Private static string account_id = 'efgh';
Public string signer_email { get; set; }
Public string signer_name { get; set; }
Public string email_message { get; set; }
Public string output { get; set; }
Public string envelope_id { get; set; }
Public string error_code { get; set; }
Public string error_message { get; set; }
Private static string ds_server = 'callout:DocuSign_Legacy_Demo/api/3.0/dsapi.asmx';
Private static string trace_value = 'SFDC_004_SOAP_email_send'; // Used for tracing API calls
Private static string trace_key = 'X-ray';
Private DocuSignTK.APIServiceSoap api_sender = new DocuSignTK.APIServiceSoap();
configure_sender();
do_send(OppLst);
}
Private void configure_sender()
{
api_sender.endpoint_x = ds_server;
api_sender.inputHttpHeaders_x = new Map<String, String>();
String auth = '<DocuSignCredentials><Username>{!$Credential.Username}</Username>'
+ '<Password>{!$Credential.Password}</Password>'
+ '<IntegratorKey>' + integration_key + '</IntegratorKey></DocuSignCredentials>';
api_sender.inputHttpHeaders_x.put('X-DocuSign-Authentication', auth);
}
Private void do_send(List<Oppurtunity> OppurLst)
{
if (integration_key == 'xxx-xxxx-xxxx' ||
account_id == 'xxxx-xxxx-xxxx')
{
error_message = 'Please configure the Apex class DS_Recipe_Send_Env_Email_Controller with your integration key and account id.';
error_code = 'CONFIGURATION_PROBLEM';
return;
}
String file_contents = '<html><h1>Quote Document</h1>' + get_lorem(OppurLst)
+ '<p> </p>'
+ '<p>Signature: <span style="color:white;">signer1sig</span></p>'
+ '<p>Date: <span style="color:white;">signer1date</span></p></html>';
DocuSignTK.Document document = new DocuSignTK.Document();
document.ID = 1;
document.Name = 'Quote Document';
document.FileExtension = 'html';
document.pdfBytes = EncodingUtil.base64Encode(Blob.valueOf(file_contents));
DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
recipient.Email = '';
recipient.UserName = '';
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
DocuSignTK.Tab signHereTab = new DocuSignTK.Tab();
signHereTab.Type_x = 'SignHere';
signHereTab.AnchorTabItem = new DocuSignTK.AnchorTab();
signHereTab.AnchorTabItem.AnchorTabString = 'signer1sig'; // Anchored for doc 1
signHereTab.AnchorTabItem.XOffset = 8;
signHereTab.RecipientID = 1;
signHereTab.Name = 'Please sign here';
signHereTab.ScaleValue = 1;
signHereTab.TabLabel = 'signer1sig';
DocuSignTK.Tab dateSignedTab = new DocuSignTK.Tab();
dateSignedTab.Type_x = 'DateSigned';
dateSignedTab.AnchorTabItem = new DocuSignTK.AnchorTab();
dateSignedTab.AnchorTabItem.AnchorTabString = 'signer1date'; // Anchored for doc 1
dateSignedTab.AnchorTabItem.YOffset = -6;
dateSignedTab.RecipientID = 1;
dateSignedTab.Name = 'Date Signed';
dateSignedTab.TabLabel = 'date_signed';
DocuSignTK.Envelope envelope = new DocuSignTK.Envelope();
envelope.Subject = 'Please sign the Quote Document';
envelope.AccountId = account_id;
envelope.Tabs = new DocuSignTK.ArrayOfTab();
envelope.Tabs.Tab = new DocuSignTK.Tab[2];
envelope.Tabs.Tab.add(signHereTab);
envelope.Tabs.Tab.add(dateSignedTab);
envelope.Recipients = new DocuSignTK.ArrayOfRecipient();
envelope.Recipients.Recipient = new DocuSignTK.Recipient[1];
envelope.Recipients.Recipient.add(recipient);
envelope.Documents = new DocuSignTK.ArrayOfDocument();
envelope.Documents.Document = new DocuSignTK.Document[1];
envelope.Documents.Document.add(document);
if (String.isNotBlank(email_message))
{
envelope.EmailBlurb = email_message;
}
try
{
DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
envelope_id = result.EnvelopeID;
System.debug('Returned successfully, envelope_id = ' + envelope_id);
}
catch (CalloutException e)
{
System.debug('Exception - ' + e);
error_code = 'Problem: ' + e;
error_message = error_code;
}
}
Private Boolean no_error()
{
return (String.isEmpty(error_code));
}
Private static String get_lorem(List<Oppurtunity> OLst)
{
String lorem = 'Hello World';
return lorem;
}
}
And I am trying to call the send Method from the Apex from the Custom Button like
{!REQUIRESCRIPT("/soap/ajax/41.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/41.0/apex.js")}
sforce.apex.execute("test_Controller","send",{oppIds:"{!Opportunity.Id}"});
When I try to execute the button I get the following error message:
A Problem with the OnClick JavaScript for this button or link was
encountered: {faultcode:''soapenv:Client', faultstring:'No operation
available for request
{http://soap.sforce.com/schemas/package/test_Controller}send, please
check the WSDL for the service.'}'
I am new to Salesforce and Apex scripting. Any help is greatly appreciated.
Your method is expecting a list of Ids.
Public void send(set<id> oppIds)
So I am guessing that maybe you need to send it as an array?
sforce.apex.execute("test_Controller","send",{oppIds:["{!Opportunity.Id}"]});
You need to expose this method as a webservice and it needs to be static
webservice static void send(List<Id> oppIds) {
}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_and_ajax.htm
I created a personal info page to display all the data according to specific username entered. Unfortunately, the edit text didn't display all the data from the SQL Server. It only shows 2/8 data. I'm using a WEB API to retrieve the data and the data is stored in SQL Server. Can you help me to fix this problem please!!
I obtained this code from a website and i follow step by step according to the website. I've tried using Web services, it didn't work ass well.
VehicleRecord.cs
public class VehicleRecord
{
public string clFullName{ get; set; }
public string clGender{ get; set; }
public string clICNo { get; set; }
public string clAddress { get; set; }
public string clPhoneNo { get; set; }
public string clEmail { get; set; }
public string clUsername { get; set; }
public string clPwd { get; set; }
public string clVehicPlateNo { get; set; }
public string clVehicModel { get; set; }
public string clVehicCol { get; set; }
public string clPaymentMethod { get; set; }
public VehicleRecord()
{
this.clFullName = "";
this.clGender = "";
this.clICNo = "";
this.clAddress = "";
this.clPhoneNo = "";
this.clEmail = "";
this.clUsername = "";
this.clPwd = "";
this.clVehicPlateNo = "";
this.clVehicModel = "";
this.clVehicCol = "";
this.clPaymentMethod = "";
}
}
Service.cs
public class Service
{
public static async Task<dynamic> getServiceData(string queryString)
{
dynamic acc = null;
HttpClient client = new HttpClient();
var response = await client.GetAsync(queryString);
if(response != null)
{
string json = response.Content.ReadAsStringAsync().Result;
acc = JsonConvert.DeserializeObject(json);
}
return acc;
}
}
Acc.cs
public class Acc
{
public static async Task<VehicleRecord> GetAcc(string username)
{
string queryString = "http://xxx.xxx.x.xxx/PMSAPI1/api/users/" + username;
dynamic results = await Service.getServiceData(queryString).ConfigureAwait(false);
if(results != null)
{
VehicleRecord vehicleRecord = new VehicleRecord();
vehicleRecord.clFullName = (string)results["clFullName"];
vehicleRecord.clGender = (string)results["clGender"];
vehicleRecord.clICNo = (string)results["clICNo"];
vehicleRecord.clAddress = (string)results["clAddress"];
vehicleRecord.clPhoneNo = (string)results["clPhoneNo"];
vehicleRecord.clEmail = (string)results["clEmail"];
vehicleRecord.clPwd = (string)results["clPwd"];
vehicleRecord.clVehicPlateNo = (string)results["clVehicPlateNo"];
vehicleRecord.clVehicModel = (string)results["clVehicModel"];
vehicleRecord.clVehicCol = (string)results["clVehicCol"];
vehicleRecord.clPaymentMethod = (string)results["clPaymentMethod"];
return vehicleRecord;
}
else
{
return null;
}
}
}
PersonalInfoActivity.cs
private async void BtnGetAcc_Click(object sender, EventArgs e)
{
EditText username = FindViewById<EditText>(Resource.Id.txtUsername);
if (!String.IsNullOrEmpty(username.Text))
{
VehicleRecord vehicleRecord = await Acc.GetAcc(username.Text);
FindViewById<EditText>(Resource.Id.txtFullName).Text = vehicleRecord.clFullName;
FindViewById<EditText>(Resource.Id.txtGender).Text = vehicleRecord.clGender;
FindViewById<EditText>(Resource.Id.txtIC).Text = vehicleRecord.clICNo;
FindViewById<EditText>(Resource.Id.txtAddress).Text = vehicleRecord.clAddress;
FindViewById<EditText>(Resource.Id.txtPhoneNo).Text = vehicleRecord.clPhoneNo;
FindViewById<EditText>(Resource.Id.txtEmail).Text = vehicleRecord.clEmail;
FindViewById<EditText>(Resource.Id.txtPwd).Text = vehicleRecord.clPwd;
FindViewById<EditText>(Resource.Id.txtPayMethod).Text = vehicleRecord.clPaymentMethod;
}
}
The expected output should display all the data according to the username entered, but the actual output only displayed 2/8 data.
The error that i get is System.NullReferenceException:Object reference not set to an instance of an object.
The output displayed on screen
It seems to me that the issue starts at this line
vehicleRecord.clICNo = (string)results["clICNo"];
IMO results does not contains "clICNo". Check this by surrounding this line in try - catch block.
I'm trying to download an file what can be pdf, cvs, word, jpg or png. To do this, I'm using angularjs + filesaver.js. don't know why but, my downloads are always corrupted.
Someone can help me ?
Note:
midia.Nome - Name of my file.
midia.Tipo - The type of the file.
midia.Path - Physical path on project.
midia.MidiaBytesString - Bytes
on Base64 to convert to blob.
Download <br />
My File download method:
$scope.Download = function(bytes,nome,tipo){
var file = new File([bytes], nome , {type: "application/octet-stream"});
saveAs(file);
};
My View Model
public class MidiaViewModel
{
public int MidiaId { get; set; }
public string MidiaDescricao { get; set; }
//public string MidiaPath { get; set; }
public byte[] MidiaBytes { get; set; }
public string MidiaBytesString { get; set; }
public int OsId { get; set; }
public virtual OsViewModel Os { get; set; }
public string MidiaNome { get; set; }
public string MidiaType { get; set; }
public string MidiaPath { get; set; }
public long MidiaSize { get; set; }
}
My register Midia:
[HttpPost]
public JsonResult AtualizarMidias(IEnumerable<HttpPostedFileBase> arquivos, IEnumerable<string> descricoes, int osId)
{
var ordermDeServico = _osService.ObterPorIdLazyLoad(osId);
foreach (var file in arquivos)
{
string targetFolder = HttpContext.Server.MapPath("~/Content/uploads/");
string targetPath = Path.Combine(targetFolder, file.FileName);
if (file != null && file.ContentLength > 0)
{
var itens = arquivos.ToList();
var des = descricoes.ToList();
var index = itens.FindIndex(c => c.FileName == file.FileName);
var midiaViewModel = new MidiaViewModel
{
MidiaType = file.ContentType,
MidiaNome = file.FileName,
MidiaPath = targetPath,
MidiaSize = file.ContentLength,
MidiaDescricao = des[index].ToString(),
MidiaBytes = converterArquivo(file)
};
var midia = Mapper.Map<MidiaViewModel, Midia>(midiaViewModel);
midia.OsId = ordermDeServico.OSId;
file.SaveAs(targetPath);
_midiaService.Salvar(midia);
}
}
return Json(new { resultado = true }, JsonRequestBehavior.AllowGet);
}
And where i make the call to my angular $scope:
[HttpPost]
public string getMidiasOS(int idOS)
{
var getMidias = _midiaService.ObterMidiaPorIdOs(idOS);
List<MidiaAngularViewModel> midiaNova = new List<MidiaAngularViewModel>();
foreach (var midia in getMidias)
{
midiaNova.Add(new MidiaAngularViewModel
{
Id = midia.MidiaId,
Path = midia.MidiaPath,
Tipo = midia.MidiaType,
Descricao = midia.MidiaDescricao,
MidiaBytesString = Convert.ToBase64String(midia.MidiaBytes),
Nome = midia.MidiaNome
});
}
return JsonConvert.SerializeObject(midiaNova);
}
EDIT
Guys, I solved my problem using the Ameni topic in the follow link: download file using angularJS and asp.net mvc
All I need to do was create like the Post method on the Ameni topic and the download by path function.
Simply add/use the download attribute and you will be fine. More about download attribute can be found at w3c download documentation.
Download
I'm trying to uplode File along with some columns.File Uploading sucessfully but why Remaining column taking [object object] type
Table
public partial class CreateUserIdentity
{
public int Id { get; set; }
public string Email { get; set; }
public string Image { get; set; }
public string password { get; set; }
}
AngularJs
var description = {
Passwoed: $scope.FileDescription,
Email : $scope.Email
}
FileUploadService.UploadFile($scope.SelectedFileForUpload, description
).then(function (d) {
});
Mvc Controller
[HttpPost]
public JsonResult SaveFiles(string description)
{
if (Request.Files != null)
{
CreateUserIdentity f = new CreateUserIdentity
{
Image = actualFileName,
Email = description,
};
using (ProjectsEntities dc = new ProjectsEntities())
{
dc.CreateUserIdentities.Add(f);
dc.SaveChanges();
Message = "File uploaded successfully";
flag = true;
}
}
return new JsonResult { Data = new { Message = Message, Status = flag } };
The description you are sending is not a string - it is an object consisting of Email and Passwoed - type that correctly in your rest-controller and use Email = description.Email
Alertatively you can just send $scope.Email from the angular-side instead of wrapping it in a description-Object, that should work as well (if you don't need the attribute Passwoed).
I have a WPF application. I am making REST calls from that.
I would like to alter the response XML/JSON of the rest service.
I am using FiddlerCore to intercept the call.
I need to listen to ALL the ports in my local machine.
List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();
FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
oFCSF = (oFCSF & ~FiddlerCoreStartupFlags.DecryptSSL);
//Fiddler.FiddlerApplication.Startup(8080, true, true);
FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
{
};
FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS)
{
}
};
Fiddler.FiddlerApplication.Startup(0, true, false);
This issue is resolved - Look at the below link
https://gist.githubusercontent.com/timiles/4079321/raw/268f71249f381649a06f4b48ebfb54cbaa8ee282/MockWebProxyHelper.cs
using System;
using System.Net;
// http://www.fiddler2.com/fiddler/Core/
using Fiddler;
public static class MockWebProxyHelper
{
public enum HttpMethods
{
GET, POST, PUT, Unknown
}
public class Response
{
public Response(string header = "HTTP/1.1 200 OK", string body = "", string contentType = "application/json")
{
Header = header;
Body = body;
ContentType = contentType;
}
public string Header { get; private set; }
public string Body { get; private set; }
public string ContentType { get; private set; }
}
public static Func<HttpMethods, string, Response> GetMockResponse = delegate { return new Response(); };
public static Func<HttpMethods, string, bool> InterceptRequest = delegate { return true; };
public static void SetUp(bool registerAsSystemProxy = false)
{
const int port = 18833;
FiddlerApplication.Startup(port, FiddlerCoreStartupFlags.DecryptSSL
| (registerAsSystemProxy ? FiddlerCoreStartupFlags.RegisterAsSystemProxy : FiddlerCoreStartupFlags.None));
WebRequest.DefaultWebProxy = new WebProxy("localhost", port);
FiddlerApplication.BeforeRequest += BeforeRequest;
}
private static void BeforeRequest(Session session)
{
var httpMethod = GetHttpMethod(session);
var url = session.url;
if (InterceptRequest(httpMethod, url))
{
session.utilCreateResponseAndBypassServer();
var response = GetMockResponse(httpMethod, url);
session.oResponse.headers = Parser.ParseResponse(response.Header);
session.oResponse.headers.Add("Content-Type", response.ContentType);
session.utilSetResponseBody(response.Body);
}
}
private static HttpMethods GetHttpMethod(Session session)
{
return session.HTTPMethodIs("GET") ? HttpMethods.GET
: session.HTTPMethodIs("POST") ? HttpMethods.POST
: session.HTTPMethodIs("PUT") ? HttpMethods.PUT : HttpMethods.Unknown;
}
public static void TearDown()
{
FiddlerApplication.BeforeRequest -= BeforeRequest;
FiddlerApplication.oProxy.Detach();
FiddlerApplication.Shutdown();
}
}