How to ignore URL param with "&var=" - asp.net

I have in controller as optional param:
GetPostalCodeLocation(string postalCode, string postalCodeExt, string place = "", string district = "")
if in URL i dont put the var district it works, but in application is generate this url:
Url:"http://localhost:62814/Api/Address/PostalCodeLocation?postalCode=2415&postalCodeExt=021&place=&district=Leiria"
I cannot control the URL (is defined by platform)
Is possible in Routing set &place= to ignore?
Thanks
UPDATE
I Have this action filter
Dictionary<string, string> logParameters = new Dictionary<string, string>();
logParameters = new Dictionary<string, string>();
actionContext.Request.Properties.Add(new KeyValuePair<string, object>("watch", watch));
actionContext.Request.Properties.Add(new KeyValuePair<string, object>("action", actionName));
//// Create integer parameter.
foreach (var param in actionContext.ActionArguments)
{
if (param.Value == null)
{
throw new Exception("Parameter " + param.Key + " cannot be null");
}
{
logParameters.Add(param.Key, param.Value.ToString());
}
}
actionContext.Request.Properties.Add(new KeyValuePair<string, object>("logParameters", logParameters));
base.OnActionExecuting(actionContext);

Related

uri is too long when I try to send a base64 using xamarin forms

I am working with xamarin.forms and System.Net.Http;
I am sending a photo using a post function which is this:
public static async Task<String> PostImagemAsync(User user)
{
using (var client = new HttpClient())
{
try
{
var values = new List<KeyValuePair<string, string>>(0);
values.Add(new KeyValuePair<string, string>("email", user.usua_login));
values.Add(new KeyValuePair<string, string>("senha", user.usua_senha));
values.Add(new KeyValuePair<string, string>("foto", user.cont_imagem));
values.Add(new KeyValuePair<string, string>("json", "1"));
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("http://ws.neosuite.com.br/login.asmx/foto", content);
var json = response.Content.ReadAsStringAsync().Result;
json = json.Substring(json.IndexOf('['));
json = json.Substring(0, json.LastIndexOf(']') + 1);
var userImage = JsonConvert.DeserializeObject<List<User>>(json);
return userImage[0].cont_imagem;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}
My image (foto) is a base64 And it does I get this error when I try to send it:
Invalid URI: The Uri string is too long.
How to solve that?
Without adding your POST content into url, add that to body using following code
var uri = new Uri (string.Format ("http://ws.neosuite.com.br/login.asmx/foto", string.Empty));
var json = JsonConvert.SerializeObject (user);//user object or you can create your own jason here
var content = new StringContent (json, Encoding.UTF8, "application/json");
var response = await client.PostAsync (uri, content);

How to Create and Delete edge properties (Titan 1.0) using c# in .net mvc?

I was using Titan 1.0 with gremlin server to create and delete vertex. I want to implement this logic in my .net project. I wonder if there is any pre build plugin for titan and gremlin server in asp.net?
Currently i'm directly using command prompt to create and delete the required vertices and edges. how can I implement it in my .net MVC project?
I've created one class in my project for interacting with Gremlin server using REST API. you can make small changes to make it work for you.
Source: https://askgif.com/blog/145/how-to-create-and-delete-edge-properties-titan-1-0-using-c-in-net-mvc/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using RestSharp;
using urNotice.Common.Infrastructure.Common.Config;
using urNotice.Common.Infrastructure.Common.Constants;
using urNotice.Common.Infrastructure.Common.Enum;
using urNotice.Common.Infrastructure.commonMethods;
using urNotice.Common.Infrastructure.Model.urNoticeModel.DynamoDb;
using urNotice.Services.NoSqlDb.DynamoDb;
namespace urNotice.Services.GraphDb
{
public class GremlinServerGraphEdgeDb : IGraphEdgeDb
{
private delegate Dictionary<string, string> AddEdgeAsyncDelegate(string userName, string graphName, Dictionary<string, string> properties);
public Dictionary<string, string> AddEdge(string userName, string graphName, Dictionary<string, string> properties)
{
string url = TitanGraphConfig.Server;
var response = CreateEdge(graphName, properties, url);
// add edge to dynamodb.
var edgeDetail = new OrbitPageEdgeDetail
{
url = url,
edgeId = response[TitanGraphConstants.Id],
graphName = graphName,
properties = properties
};
IDynamoDb dynamoDbModel = new DynamoDb();
dynamoDbModel.UpsertOrbitPageEdgeDetail(edgeDetail, userName, properties[EdgePropertyEnum._inV.ToString()], properties[EdgePropertyEnum._outV.ToString()]);
//Adding edgeDetail for faster query.
//dynamoDbModel.UpsertOrbitPageEdgeForQueryDetail(edgeDetail, userName, properties[EdgePropertyEnum._inV.ToString()], properties[EdgePropertyEnum._outV.ToString()]);
return response;
}
public Dictionary<string, string> DeleteEdge(string inV, string outV, string label)
{
string url = TitanGraphConfig.Server;
IDynamoDb dynamoDbModel = new DynamoDb();
string uniqueKey = OrbitPageUtil.GenerateUniqueKeyForEdgeQuery(inV, label, outV);
var edgeInfo = dynamoDbModel.GetOrbitPageCompanyUserWorkgraphyTable(
DynamoDbHashKeyDataType.EdgeDetail.ToString(),
uniqueKey,
null);
if (edgeInfo == null)
return null;
var response = DeleteEdgeNative(TitanGraphConfig.Graph, edgeInfo.CompareId, url);
dynamoDbModel.DeleteOrbitPageCompanyUserWorkgraphyTable(edgeInfo);
//Deleting Edge detail creating for only query purpose.
//string uniqueKey = OrbitPageUtil.GenerateUniqueKeyForEdgeQuery(inV, label, outV);
//edgeInfo = dynamoDbModel.GetOrbitPageCompanyUserWorkgraphyTable(
// DynamoDbHashKeyDataType.EdgeDetail.ToString(),
// uniqueKey,
// null);
//if(edgeInfo!=null)
// dynamoDbModel.DeleteOrbitPageCompanyUserWorkgraphyTable(edgeInfo);
return response;
}
public Dictionary<string, string> AddEdgeAsync(string userName, string graphName, Dictionary<string, string> properties)
{
var addEdgeAsyncDelegate = new GremlinServerGraphEdgeDb.AddEdgeAsyncDelegate(AddEdge);
addEdgeAsyncDelegate.BeginInvoke(userName, graphName, properties, null, null);
return null;
}
private Dictionary<String, String> CreateEdge(string graphName, Dictionary<string, string> properties, string url)
{
var uri = new StringBuilder(url + "/?gremlin=");
//http://localhost:8182/?gremlin=g.V(8320).next().addEdge("Using",g.V(12416).next(),"Desc","Item used by Person","time",12345)
string graphProperties = string.Empty;
//_outV must be the first parameter
graphProperties += "'" + properties[EdgePropertyEnum._label.ToString()] + "', g.V(" + properties[EdgePropertyEnum._inV.ToString()] + ").next() ,";
foreach (KeyValuePair<string, string> property in properties)
{
if (property.Key == EdgePropertyEnum._inV.ToString() || property.Key == EdgePropertyEnum._outV.ToString() || property.Key == EdgePropertyEnum._label.ToString())
{
//do nothing.. May be in future we will write logic here.
}
else
{
if (property.Key == EdgePropertyEnum.PostedDateLong.ToString() || property.Key == EdgePropertyEnum.SalaryAmount.ToString())
graphProperties += "'" + property.Key + "', " + property.Value + " ,";
else
graphProperties += "'" + property.Key + "', '" + property.Value + "' ,";
}
}
if (!string.IsNullOrEmpty(graphProperties))
{
graphProperties = graphProperties.Substring(0, graphProperties.Length - 2);
}
uri.Append("g.V(" + properties[EdgePropertyEnum._outV.ToString()] + ").next().addEdge(" + graphProperties + ");");
var client = new RestClient(uri.ToString());
var request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", "", ParameterType.RequestBody);
var res = client.Execute(request);
var content = res.Content; // raw content as string
dynamic jsonResponse = JsonConvert.DeserializeObject(content);
var response = new Dictionary<String, String>();
response["status"] = "200";
response["CreateEdgeStatus"] = "200";
response[TitanGraphConstants.Id] = jsonResponse.result.data[0].id;
response[TitanGraphConstants.RexsterUri] = url;
return response;
}
private Dictionary<String, String> DeleteEdgeNative(string graphName, string edgeId, string url)
{
var uri = new StringBuilder(url + "/?gremlin=");
//var uri = new StringBuilder(url + "/graphs/" + graphName + "/edges/" + edgeId);
//http://localhost:8182/?gremlin=g.E('odxqo-6f4-2hat-9kw').drop()
uri.Append("g.E('" + edgeId + "').drop();");
var client = new RestClient(uri.ToString());
var request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", "", ParameterType.RequestBody);
var res = client.Execute(request);
var content = res.Content; // raw content as string
dynamic jsonResponse = JsonConvert.DeserializeObject(content);
var response = new Dictionary<String, String>();
response["status"] = "200";
response["DeleteEdgeStatus"] = "200";
//response[TitanGraphConstants.Id] = jsonResponse.result.data[0].id;
//response[TitanGraphConstants.RexsterUri] = url;
return response;
}
}
}
comment if you face any issue in the class.

POST data to XML service aspx vb

Dim doc As New XmlDocument
doc.Load("http://www.example.com/?paramx=1&paramy=2")
is great for GET queries in the querystring. But say I wanted to POST the paramx=1&paramy=2 to http://www.example.com and get the response in XML. How would I do that?
Below is a helper class I use for POSTing data to a website which then returns XML - hope it helps.
Usage:
var resultXmlDoc = new HttpHelper().PostXml("http://www.test.com", new { paramName = "value", paramName2="value2" });
Helper class:
internal class HttpHelper
{
public XDocument PostXml(string baseUrl, IDictionary<string, string> cgiParams)
{
return XDocument.Load(Post(baseUrl, cgiParams).GetResponseStream());
}
public XDocument PostXml(string baseUrl, params object[] items)
{
return XDocument.Load(Post(baseUrl, items).GetResponseStream());
}
public XDocument PostXml(string url, string topost)
{
return XDocument.Load(Post(url, topost).GetResponseStream());
}
protected virtual HttpWebResponse Post(string url, string postString)
{
if (url == null)
throw new ArgumentNullException("baseUrl");
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
throw new ArgumentException("url is not a valid Uri");
var req = (HttpWebRequest)WebRequest.Create(url);
// if the target site issues a session cookie, you need to store it and append it here
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
var bytes = System.Text.Encoding.ASCII.GetBytes(postString);
req.ContentLength = bytes.Length;
using(var str = req.GetRequestStream())
str.Write(bytes, 0, bytes.Length);
return (HttpWebResponse)req.GetResponse();
}
protected virtual HttpWebResponse Post(string url, params object[] items)
{
var x = items.SelectMany(i =>
{
return i.GetType().GetProperties().Select(p => new Tuple<string, string>(p.Name, p.GetValue(i, null) != null ? p.GetValue(i, null).ToString() : ""));
});
var d = new Dictionary<string, string>();
foreach (var p in x)
d[p.Item1] = p.Item2;
return Post(url, d);
}
protected virtual HttpWebResponse Post(string baseUrl, IDictionary<string, string> cgiParams)
{
if (baseUrl == null)
throw new ArgumentNullException("baseUrl");
Uri uri;
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out uri))
throw new ArgumentException("baseUrl is not a valid Uri");
string postString = string.Empty;
if (cgiParams != null && cgiParams.Count > 0)
{
foreach (var k in cgiParams.Keys)
postString += HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(cgiParams[k]) + "&";
postString = postString.Substring(0, postString.Length - 1);
}
return Post(baseUrl, postString);
}
}

Pdf's fields should remain editable using itextsharp in asp.net

I have a fillable pdf. In which i have few textboxes.
I fill these fields by using following code(itextsharp).
DataTable dt = new DataTable();
String pdfPath1 = Server.MapPath("pdfs\\transmittal2.pdf");
if (File.Exists(pdfPath1))
{
dt = objClsTransmittal.GetTransmittal(jobid, cid);
String comment = "Correspondence generated for " + dt.Rows[0]["Recipient"].ToString();
var formfield = PDFHelper.GetFormFieldNames(pdfPath1);
formfield["DocDate"] = DateTime.Now.ToLongDateString();
formfield["Address1"] = dt.Rows[0]["Company"].ToString();
formfield["Address2"] = dt.Rows[0]["Address1"].ToString();
formfield["PropertyAddress"] = dt.Rows[0]["PropertyAddress"].ToString();
formfield["Job"] = dt.Rows[0]["JobID"].ToString();
formfield["Name"] = dt.Rows[0]["Recipient"].ToString();
formfield["CityStateZip"] = dt.Rows[0]["address2"].ToString();
formfield["E-mail"] = dt.Rows[0]["Email"].ToString();
var pdfcontent = PDFHelper.GeneratePDF(pdfPath1, formfield);
PDFHelper.ReturnPDF(pdfcontent, "Transmittal.pdf");
}
Currently its downloded as read only pdf.
when this pdf gets downloaded, i want that all fields still remain fillable, with the text i have filled in pdf. So that i can edit the text.
I'm looking forward for your replies.
Thanks.
EDIT
PdfHelper is my custom class. In which i have used following code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
Your code line
stamper.FormFlattening = true;
instructs iTextSharp to flatten the form fields, i.e. to integrate them into the page content and remove the form field annotations.
As you want to keep the form fields as editable fields, don't flatten the form.
Error: Cannot convert type in PDFHelper.cs
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields) //ERROR: 'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'
{
fields.Add(entry.Key.ToString(), string.Empty);
}
reader.Close();
return fields;
}
'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'

Parameter has all propertys after webrequest

I have a really simple ASP.NET Api Controller with one method.
public HttpResponseMessage<User> Post(User user)
{
return new HttpResponseMessage<User>(new User() { Name = "New User at Server" });
}
My debugger says that the method is called but the problem is that the parameter "user" has all its content set to null; I am using Fiddler to look at request and response.. and all looks good.
This is my service code in the client.
public void AddUser(Models.User user, Action<Models.User> ShowResult)
{
var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
string url = "http://localhost:4921/User";
Uri uri = new Uri(url, UriKind.Absolute);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var sendWebPost = Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)
.ContinueWith(task =>
{
Tuple<string, string>[] stringToSend = { Tuple.Create<string, string>("user", ObjectToJson<Models.User>(user)) };
var bytesToSend = GetRequestBytes(stringToSend);
using (var stream = task.Result)
stream.Write(bytesToSend, 0, bytesToSend.Length);
}
).ContinueWith(task =>
{
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith<WebResponse>(task2 => { ValidateResponse(task2); return task2.Result; })
.ContinueWith<Models.User>(task3 => {return JsonToObject<Models.User>(task3);})
.ContinueWith(task4 => { TryClearWorking(); ShowResult(task4.Result); }, uiThreadScheduler);
});;
}
public static string ObjectToJson<T>(T obj) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
StreamReader sr = new StreamReader(stream);
serializer.WriteObject(stream, obj);
sr.BaseStream.Position = 0;
string jsonString = sr.ReadToEnd();
return jsonString;
}
protected static byte[] GetRequestBytes(Tuple<string, string>[] postParameters)
{
if (postParameters == null || postParameters.Length == 0)
return new byte[0];
var sb = new StringBuilder();
foreach (var key in postParameters)
sb.Append(key.Item1 + "=" + key.Item2 + "&");
sb.Length = sb.Length - 1;
return Encoding.UTF8.GetBytes(sb.ToString());
}
Anyone who can give me some ideas where to start to look for errors.....
You need to set the Content-Length header.

Resources