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

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.

Related

What can i do if SSL certificate don`t working in IIS, but working in Local

I have two projects: Web Api(back) and MVC(front). Web Api(back) has a method that uses the SSL certificate. If running the Web Api(back) in local, then the method works, but if running Web Api(back) in IIS and send post in MVC(front) to the method, then it catches an error "One or more errors occurred". (The SSL connection could not be established, see inner exception.).
Web Api(back) code
public decimal GetIdentification(IdentificationModel identification, int key)
{
try
{
var handler = new HttpClientHandler();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cert\\hgg.p12");
handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword));
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), _identityUrl + "iin=" + identification.IIN + "&vendor=" + _vendor))
{
string token = GetToken();
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
request.Headers.TryAddWithoutValidation("x-idempotency-key", "key:" + "hggKey-" + key);
request.Method = new HttpMethod("POST");
//request.Content = new StringContent(identification.Photo);
request.Content = new StreamContent(new MemoryStream(Convert.FromBase64String(identification.Photo)));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
var response = httpClient.SendAsync(request);
string data = response.Result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<dynamic>(data).result;
}
}
}
catch (Exception e)
{
throw new Exception("GetIdentification" + e.Message);
}
}
public string GetToken()
{
var handler = new HttpClientHandler();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cert\\hgg.p12");
handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword));
try
{
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), _tokenUrl))
{
request.Headers.TryAddWithoutValidation("Authorization", "Basic " + _token);
request.Method = new HttpMethod("POST");
request.Content = new StringContent("grant_type=password&username=" + _username + "&password=" + _password + "&scope=identkey");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = httpClient.SendAsync(request);
return JsonConvert.DeserializeObject<dynamic>(response.Result.Content.ReadAsStringAsync().Result).access_token;
}
}
}
catch(Exception e)
{
throw new Exception("GetToken" + e.Message + path + " " +_certPassword);
}
}
}
MVC(front)
public string Identity(RequestClass<IdentificationModel> request)
{
ResponseClass<decimal> response = new ResponseClass<decimal>();
using (var httpClient = new HttpClient())
{
var json = JsonConvert.SerializeObject(request);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse =
httpClient.PostAsync(_apiUrl + $"Identification", data).Result;
string responseContent = httpResponse.Content.ReadAsStringAsync().Result;
return responseContent;
}
}
ApplicationPoolIdentity don't have permission for certmgr.msc

How to ignore URL param with "&var="

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);

jQuery Bootgrid sorting, pagination and search functionality not working

I have a jQuery bootgrid implemented into my ASP.Net application which is filled using a Generic Handler.
I fill the bootgrid using the Generic Handler as follows:
$(function () {
var grid = $("#grid").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
},
url: "/MyHandler.ashx",
rowCount: [10, 50, 75, 100, 200, -1]
});
}
Here's MyHandler.ashx code:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
context.Response.Write(GetData());
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData()
{
var result = string.Empty;
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
var sNumRows = dt.Rows.Count.ToString();
var sDT = JsonConvert.SerializeObject(dt);
result = "{ \"current\": 1, \"rowCount\": 10, \"rows\": " + sDT + ", \"total\": " + sNumRows + " }";
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
THF.Models.SQLConnectionManager.CloseConn(con);
}
return result;
}
}
Basically all the important functionality of my bootgrid that worked before I implemented it the ajax way doesn't work anymore. Specifically the ordering, searching and pagination functionality aren't working at all without any errors.
As far as I know from a bit of research. This is because every time a search phrase is made, or a header is clicked (for ordering) etc. The bootgrid performs an ajax call.
Any idea on how to fix the functionality here?
After much work I ended up getting it working and this is the final code result:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
var current = context.Request.Params["current"];
var rowCount = context.Request.Params["rowCount"];
var orderById = context.Request.Params["sort[Id]"];
var orderByName = context.Request.Params["sort[Name]"];
var searchPhrase = context.Request.Params["searchPhrase"];
var orderBy = "Id";
var orderFrom = "ASC";
if (orderById != null)
{
orderBy = "Id";
orderFrom = orderById;
}
else if (orderByName != null)
{
orderBy = "Name";
orderFrom = orderByName;
}
context.Response.Write(GetData(current, rowCount, orderBy, orderFrom, searchPhrase));
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData(string current, string rowCount, string orderBy, string orderFrom, string searchPhrase)
{
var result = string.Empty;
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if (!"Id".Equals(orderBy, StringComparison.OrdinalIgnoreCase)
&& !"Name".Equals(orderBy, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderBy is not a valid value");
if (!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if (!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase
ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
command.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase + "%"));
command.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
connection.Close();
}
}
var total = string.Empty;
string sSQLTotal = #"SELECT COUNT(*)
FROM dbo.Log
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQLTotal, connection))
{
command.Parameters.Add(new SqlParameter("searchPhrase", "%" + searchPhrase + "%"));
connection.Open();
command.CommandTimeout = 0;
total = command.ExecuteScalar().ToString();
connection.Close();
}
}
var rows = JsonConvert.SerializeObject(dt);
return result = "{ \"current\": " + current + ", \"rowCount\": " + rowCount + ", \"rows\": " + rows + ", \"total\": " + total + " }";
}
}

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