Calling an Oracle GlInterface SOAP service in .net Core - oracle

Error : System.ServiceModel.FaultException`1[Service.ServiceErrorMessage]: JBO-GL:::GL_INVALID_LEDGER: GL-781535You have entered an invalid ledger value. (Fault Detail is equal to Service.ServiceErrorMessage).
only result when I search
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
EndpointAddress endpointAddress = new EndpointAddress(new Uri("https://fa-eosd-dev1-saasfaprod1.fa.ocs.oraclecloud.com:443/fscmService/JournalImportService?WSDL"));
ChannelFactory<JournalImportService> factory = new ChannelFactory<JournalImportService>(basicHttpBinding, endpointAddress);
factory.Credentials.UserName.UserName = "user";
factory.Credentials.UserName.Password = "pass";
JournalImportService serviceProxy = factory.CreateChannel();
((ICommunicationObject)serviceProxy).Open();
var opContext = new OperationContext((IClientChannel)serviceProxy);
var prevOpContext = OperationContext.Current; // Optional if there's no way this might already be set
OperationContext.Current = opContext;
importJournalsRequest importJournalsRequest = new importJournalsRequest();
GlInterfaceTransHeader glInterfaceTransHeader = new GlInterfaceTransHeader();
glInterfaceTransHeader.LedgerId = 300000001958365;
List<GlInterface> glInterface = new List<GlInterface>();
glInterface.Add(glInter);
glInterfaceTransHeader.GlInterface = glInterface.ToArray();
importJournalsRequest.interfaceRows = glInterfaceTransHeader;
try
{
var result = await serviceProxy.importJournalsAsync(importJournalsRequest);
//cleanup
factory.Close();
((ICommunicationObject)serviceProxy).Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// *** ENSURE CLEANUP *** \\
CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
OperationContext.Current = prevOpContext; // Or set to null if you didn't capture the previous context
}
}

glInterfaceTransHeader.AccountingDateSpecified = true;

Related

Digital Signature issue. [Itext]

I'm using itext7 for digitally signing the PDF document. below is my scenario:
when a sender send's a PDF document for review (or) signing. we're digitally signing the certificate from our end for security purpose.
when the document from (1) is sent to another sender for signing, the first signer signature is becoming invalid and second signer signature is becoming valid.
we're not showing the digitally signed image.
Code we've written:
public static ConversionJob AddDigitalSignature(string messageId, string keyFilename, string keyFilePassword, string pdfUserPassword, string pdfOwnerPassword, string signatureCreator, string pdfFilename, string outputFilename, bool restrictPdf = false)
{
var encrypt = !string.IsNullOrEmpty(pdfUserPassword) || !string.IsNullOrEmpty(pdfOwnerPassword) || restrictPdf;
outputFilename = !string.IsNullOrEmpty(outputFilename) ? outputFilename : pdfFilename;
var convertJob = new ConversionJob(messageId, "DigitalSignManager.AddDigitalSignature", pdfFilename, outputFilename);
var flattenFile = pdfFilename + ".flatten.pdf";
var encryptedFile = pdfFilename + ".encrypt.pdf";
try
{
_Log.Info("Adding digital signature to file {0} :: [id={1}]", pdfFilename, messageId);
// Remove existing signatures
if (File.Exists(flattenFile))
File.Delete(flattenFile);
ReaderProperties readerOptions = new ReaderProperties();
if (!string.IsNullOrEmpty(pdfOwnerPassword) || restrictPdf)
{
readerOptions.SetPassword(Encoding.ASCII.GetBytes(pdfOwnerPassword));
if (File.Exists(encryptedFile))
File.Delete(encryptedFile);
}
PdfReader reader = new PdfReader(pdfFilename, readerOptions);
PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(flattenFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
bool hasSignature = form.GetSignatureFlags() > 0;
if (hasSignature)
{
List<string> sigFields = new List<string>();
var fields = form.GetFormFields();
foreach (var field in fields)
{
var formType = field.Value.GetFormType();
if (formType.Equals(PdfName.Sig)) // here's a sig item
{
form.PartialFormFlattening(field.Key);
}
}
form.FlattenFields();
}
//var signFields = form.GetFormFields();
//if (signFields.Keys.Count > 1)
//{
// foreach (var field in signFields)
// {
// var formType = field.Value.GetFormType();
// if (formType.Equals(PdfName.Sig)) // here's a sig item
// {
// form.PartialFormFlattening(field.Key);
// }
// }
// form.FlattenFields();
//}
SignatureUtil signUtil = new SignatureUtil(pdfDoc);
IList<String> names = signUtil.GetSignatureNames();
if (names.Count >= 1)
{
foreach (String name in names)
{
PdfPKCS7 pkcs7 = signUtil.ReadSignatureData(name);
var validity = pkcs7.VerifySignatureIntegrityAndAuthenticity();
var test = signUtil.SignatureCoversWholeDocument(name);
form.PartialFormFlattening(name);
//form.RemoveField(name);
}
form.FlattenFields();
}
if (!pdfDoc.IsClosed())
pdfDoc.Close();
reader.Close();
// reapply password if encrypted
// Sprint S11-119 S11-166 PDF Encryption Start
if (encrypt)
{
var encrypted = Encrypt(messageId, pdfUserPassword, pdfOwnerPassword, flattenFile, encryptedFile, restrictPdf);
convertJob.Encrypted = encrypted.ConvertResult == ConvertResult.Success;
}
// Sprint S11-119 S11-166 PDF Encryption End
// digitally sign the file with certificate
string reason = _Configuration.DigitalSignatureReason; //"Test Electronic Signature";
string location = _Configuration.DigitalSignatureLocation; //"US North America West";
var digitalCert = new DigitalCert(keyFilename, keyFilePassword, true);
var presignPdf = encrypt ? encryptedFile : flattenFile;
PdfReader finalReader = new PdfReader(presignPdf, readerOptions);
StampingProperties sp = new StampingProperties();
sp.UseAppendMode();
PdfSigner signer = new PdfSigner(finalReader, new FileStream(outputFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite), sp);
// Creating the appearance
Rectangle rect = new Rectangle(0, 0, 0, 0);
PdfSignatureAppearance appearance = signer.GetSignatureAppearance()
//.SetCertificate()
.SetSignatureCreator(signatureCreator)
.SetReason(reason)
.SetLocation(location)
.SetReuseAppearance(false)
.SetPageRect(rect)
.SetPageNumber(1);
//signer.SetFieldName("sig");
signer.SetCertificationLevel(PdfSigner.CERTIFIED_FORM_FILLING);
signer.SetSignDate(DateTime.Now);
// Creating the signature
IExternalSignature pks = new PrivateKeySignature(digitalCert.Akp, digitalCert.DigestAlgorithm);
signer.SignDetached(pks, digitalCert.Chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
finalReader.Close();
// cleanup
if (File.Exists(flattenFile))
File.Delete(flattenFile);
if (File.Exists(encryptedFile))
File.Delete(encryptedFile);
//PdfDocument pdfDoc1 = new PdfDocument(new PdfWriter(outputFilename),sp.UseAppendMode());
//PdfAcroForm form1 = PdfAcroForm.GetAcroForm(pdfDoc1, true);
//SignatureUtil signUtil1 = new SignatureUtil(pdfDoc1);
//IList<String> names1 = signUtil1.GetSignatureNames();
//if (names1.Count >= 1)
//{
// foreach (String name in names1)
// {
// PdfPKCS7 pkcs7 = signUtil1.ReadSignatureData(name);
// var validity = pkcs7.VerifySignatureIntegrityAndAuthenticity();
// var test = signUtil1.SignatureCoversWholeDocument(name);
// if (!validity)
// form1.PartialFormFlattening(name);
// }
// form1.FlattenFields();
// if (!pdfDoc1.IsClosed())
// pdfDoc1.Close();
//}
convertJob.SetComplete(ConvertResult.Success);
}
catch (Exception ex)
{
var errorMessage = string.Format("Error adding digital signature to {0}: {1} :: [id={2}]", pdfFilename, ex.Message, messageId);
_Log.Error(ex, FailureType.Conversion, errorMessage);
convertJob.SetComplete(ConvertResult.Failed, errorMessage, ex);
}
return convertJob;
}
the commented code is for removing the not verified signature and adding only the valid signature. But same issue is coming.

Microsoft grap: GetGroupFromIdS2SRequest. Workload MsGraph_DirectoryServices

I have aproject project in Java. When I run the project I got a error: GetGroupFromIdS2SRequest. Workload MsGraph_DirectoryServices, Someone would said me how to fix it?.
SpringApplication.run(DemoApplication.class, args);
final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder().clientId("xxxx").clientSecret("yyyy").tenantId("zzzz").build();
List<String> scope = new ArrayList<>();
scope.add("https://graph.microsoft.com/.default");
final TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider( scope, clientSecretCredential);
final GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(tokenCredentialAuthProvider).buildClient();
GroupCollectionPage groupCollectionPage = graphClient.groups().buildRequest().get();
Group group = new Group();
group.description = "Group with designated owner and members207";
group.displayName = "Operations group207";
LinkedList<String> groupTypesList = new LinkedList<String>();
groupTypesList.add("Unified");
group.groupTypes = groupTypesList;
group.mailEnabled = false;
group.mailNickname = "operations207";
group.securityEnabled = true;
group.additionalDataManager().put("\"owners#odata.bind\"", new JsonPrimitive("[ \"https://graph.microsoft.com/v1.0/directoryObjects/11111111\"]"));
String sIdGrupo = graphClient.groups().buildRequest().post(group).id;
Team team = new Team();
TeamMemberSettings memberSettings = new TeamMemberSettings();
memberSettings.allowCreateUpdateChannels = true;
team.memberSettings = memberSettings;
TeamMessagingSettings messagingSettings = new TeamMessagingSettings();
messagingSettings.allowUserEditMessages = true;
messagingSettings.allowUserDeleteMessages = true;
team.messagingSettings = messagingSettings;
TeamFunSettings funSettings = new TeamFunSettings();
funSettings.allowGiphy = true;
funSettings.giphyContentRating = GiphyRatingType.STRICT;
team.funSettings = funSettings;
graphClient.groups(sIdGrupo).team().buildRequest().put(team);
Before: Team team = new Team();, I added this line:
try {
sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}

TPL Dataflow , finish a Block , re-create a BLock

I am using TPL Dataflow to display a video while first passing the data via TCP to a board. I am using CancellationTokenSource to cancel the Block activities. But the problem is, when I am re-running the "CreateVideoProcessingNetwork" function I have no response. The .Post() command returns false. How should I re-create or "rerun" a TPL Dataflow? here is the code :
private void TPL_Click(object sender, EventArgs e)
{
CreateVideoProcessingNetwork();
}
public async void CreateVideoProcessingNetwork()
{
string video_path = #"C:\.....\video_640x360_360p.mp4";
_canceller = new CancellationTokenSource();
/****************** METHOD 1 - with yield *************/
/* Video Loading TPL Block */
//var video_loader = new TransformManyBlock<string, Bitmap>(load_video, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 });
var send_recv_block = new TransformBlock<Bitmap, Bitmap>(async recv_bitmap =>
{
Console.WriteLine("Inside send_recv block");
var mem_stream = new MemoryStream();
recv_bitmap.Save(mem_stream, System.Drawing.Imaging.ImageFormat.Jpeg);
var recv_image_array = mem_stream.ToArray();
NetworkStream stream = client.GetStream();
byte[] transmit_buffer = new byte[4];
transmit_buffer[0] = (byte)(recv_image_array.Length & (0xFF));
transmit_buffer[1] = (byte)((recv_image_array.Length >> 8) & (0xFF));
transmit_buffer[2] = (byte)((recv_image_array.Length >> 16) & (0xFF));
transmit_buffer[3] = (byte)((recv_image_array.Length >> 24) & (0xFF));
// Sending first the 32bit length
await stream.WriteAsync(transmit_buffer, 0, 4);
// Sending data
await stream.WriteAsync(recv_image_array, 0, recv_image_array.Length);
// Receiving data
var recv_buffer = await Receive(stream);
Bitmap tx_image_array;
using (var ms = new MemoryStream(recv_image_array))
{
tx_image_array = new Bitmap(ms);
}
return tx_image_array;
},
new ExecutionDataflowBlockOptions
{
//BoundedCapacity = 10,
CancellationToken = cancellationSource.Token
});
/****************** METHOD 2 - with send async ***********/
var video_loader = new ActionBlock<string>(async path =>
{
Console.WriteLine("video_loader");
capture = new VideoCapture(path);
Mat matrix = new Mat();
capture.Read(matrix);
var mem_stream = new MemoryStream();
while (matrix.Rows != 0 && matrix.Width != 0)
{
Console.WriteLine("Inside Loop");
capture.Read(matrix);
if (matrix.Rows == 0 && matrix.Width == 0) break;
Bitmap bitmap = new Bitmap(matrix.Width, matrix.Rows);
bitmap = matrix.ToBitmap();
await send_recv_block.SendAsync(bitmap);
await Task.Delay(20);
if (_canceller.Token.IsCancellationRequested) break;
}
}, new ExecutionDataflowBlockOptions
{
//BoundedCapacity = 10 ,
CancellationToken = cancellationSource.Token
});
/* Video Loading TPL Block */
var display_video = new ActionBlock<Bitmap>(async received_image =>
{
Console.WriteLine("Inside Display Video");
PicturePlot2.Image = received_image;
await Task.Delay(25);
},
new ExecutionDataflowBlockOptions()
{
TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(),
//BoundedCapacity = 10,
CancellationToken = cancellationSource.Token
});
var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
/****************** METHOD 2 - with send async *************/
Console.WriteLine("to Link");
var send_recv_disposable = send_recv_block.LinkTo(display_video, linkOptions);
Console.WriteLine("Video path" + video_path);
//var apotelesma_post = video_loader.Post(video_path);
var apotelesma_post = await video_loader.SendAsync(video_path);
Console.WriteLine("Apotelesma Post "+ apotelesma_post);
video_loader.Complete();
try
{
await display_video.Completion;
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex.CancellationToken.IsCancellationRequested);
video_loader.Complete();
send_recv_block.Complete();
display_video.Complete();
MessageBox.Show("Video Ended");
}
}
private void Stop_Reset_Click(object sender, EventArgs e)
{
cancellationSource.Cancel();
_canceller.Cancel();
}
Thanks in Advance
You've not shown where you declare the variable cancellationSource, which you supply to the ExecutionDataFlowBlockOptions.
When you supply a cancellation token to the ExecutionDataFlowBlockOptions, you are telling the block to enter the Completed state with a task status of Canceled when the token is cancelled. The docs tell us this is final:
Because the CancellationToken property permanently cancels dataflow block execution, the whole pipeline must be recreated after the user cancels the operation and then wants to add more work items to the pipeline.[1]
Because your stop button sets this token to cancelled, when you recreate the blocks they are beginning in the cancelled state.
Above _canceller = new CancellationTokenSource(); you need to add cancellationSource = new CancellationTokenSource();.

Response status code does not indicate success: '400' ('Bad request')

i want to POST data to API in my android xamarin app using refit i've tested the API at Postman and it's working fine but at android app i'm getting exception Bad request.
Here is my android code i added the interface and the model i don't know what is the problem .
public interface RequestAPI
{
[Post("/request")]
Task<create_request> submit([Body] create_request request);
}
requestAPI= RestService.For<RequestAPI>("http://courier-magconsulting.azurewebsites.net/api");
button.Click += async delegate
{
try
{
create_request request = new create_request();
request.PickUpPhone = "7664554";
request.DownPayment = 89;
request.DeliveryFees = 56.8;
request.Note = "i need a help!";
request.RequestID = 88; // replace the value yourself
request.DekiveryLocationLatitude = 2323;
request.DeliveryLocationLongitude = 232;
request.PickUpLocationLatitude = 898;
request.PickUpLocationLongitude = 1123;
BroadcastType type = new BroadcastType();
type.Name = "All";
type.ID = 60; // replace the value yourself
request.BroadcastType = type;
Cargosize size = new Cargosize();
size.Name = "Small";
size.ID = 1; // replace the value yourself
request.Cargosize = size;
Cargoweight weight = new Cargoweight();
weight.Name = "Large";
weight.ID = 2; // replace the value yourself
request.CargoWeight = weight;
Sender sender_ = new Sender();
sender_.Name = "Ahmad";
sender_.SenderID = 1; // replace the value yourself
sender_.Phone = "8788";
sender_.SocialID = "8787";
sender_.RatingAvg = 5;
SenderStatus status = new SenderStatus();
status.ID = 1;
status.Name = "Active";
sender_.Senderstatus = status;
request.Sender = sender_;
create_request result = await requestAPI.submit(request);
Toast.MakeText(this, "Request created", ToastLength.Long).Show();
}
catch(Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
};

Async and Await didn't work on web api

I am trying to use await on my async method but it didn't work. I input 2 array of parameters when calling the post method, only the last one is inserted
to database(I use Elasticsearch as database so when the _id is the same the document will replaced by the new one). and I found out when insert is not done yet the program is already run to query the database and the result is 0 so it's insert again instead of update.
I already add await on my program but it didn't work out. Can anyone help me with this problem? Thanks
here is my code
// POST api/values
[HttpPost]
public async Task<AvatarModel.AvatarResponse> Post(MultiLanguageTemp[] LangTemp)
{
//process param to multilanguage model
AvatarModel.AvatarResponse Resp = new AvatarModel.AvatarResponse();
try
{
for (int i = 0; i < LangTemp.Length; i++)
{
string Type = LangTemp[i].Type;
if ("ErrorCode".Equals(Type))
{
}
else
{
string GetLabelId = LangTemp[i].LabelId;
string GetTranslation = LangTemp[i].Translation;
MultiLanguage Lang = new MultiLanguage();
Lang.Type = LangTemp[i].Type;
Lang.Site = LangTemp[i].Site;
Lang.Language = LangTemp[i].LangId;
Lang.Source = LangTemp[i].Source;
Lang.TranslationList = new Dictionary<string, string>();
Lang.TranslationList.Clear();
Lang.TranslationList.Add(GetLabelId, GetTranslation);
//search elasticsearch first using id TYPE+SITE+LANG_ID+SOURCE
string ESResponse = await GetMultiLangAsync(Lang);
JObject GetResp = JObject.Parse(ESResponse);
//get elasticsearch Hits count
JToken GetHitsTotal = GetResp.SelectToken("hits.total");
int Hits = int.Parse(GetHitsTotal.ToString());
// if id exist then do update else do insert
if (Hits > 0)
{
string ResponseUpdate = await UpdateMultiLangAsync(GetLabelId, GetTranslation,Lang);
if (!ResponseUpdate.ToString().ToUpper().Contains("ERROR"))
{
Resp.Result = "0000000";
Resp.Message = "Update MultiLanguage Info is Success";
}
else
{
Resp.Result = "9000003";
Resp.Message = "Update MultiLanguage Info into ES failed";
}
}
else
{
//tasks.Add(InsertMultiLangAsync(Lang));
//insert new document into elasticsearch
string InsertESResponse = await InsertMultiLangAsync(Lang);
if (!InsertESResponse.ToUpper().Contains("ERROR"))
{
Resp.Result = "0000000";
Resp.Message = "Insert MultiLanguage Info is Success";
}
else
{
Resp.Result = "9000003";
Resp.Message = "Insert MultiLanguage Info into ES failed";
}
}
}
}
}
catch (Exception E)
{
Resp.Result = "9000005";
Resp.Message = E.Message.ToString();
}
return Resp;
}
public async Task<string> GetMultiLangAsync(MultiLanguage Lang)
{
var Client = new HttpClient();
Client.BaseAddress = new Uri("http://localhost:9200/multilanguage/MultiLangInfo/");
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var Query = "{\"query\": {\"match\": {\"_id\":\"" + Lang.Type + Lang.Site + Lang.Language + Lang.Source + "\"}}}";
var StringContent = new StringContent(Query, Encoding.UTF8, "application/json");
var Response = Client.PostAsync("_search", StringContent).Result.Content.ReadAsStringAsync();
//JObject GetResp = JObject.Parse(Response.Result);
return await Response;
}
public async Task<string> InsertMultiLangAsync(MultiLanguage Lang)
{
var Client = new HttpClient();
Client.BaseAddress = new Uri("http://localhost:9200/multilanguage/");
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var JsonTextMultiLang = JsonConvert.SerializeObject(Lang, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var StringContent = new StringContent(JsonTextMultiLang, Encoding.UTF8, "application/json");
var ResponseInsert = Client.PostAsync("MultiLangInfo/" + Lang.Type + Lang.Site + Lang.Language + Lang.Source, StringContent).Result.Content.ReadAsStringAsync();
return await ResponseInsert;
}
public async Task<string> UpdateMultiLangAsync(string GetLabelId,string GetTranslation, MultiLanguage Lang)
{
var UpdateES = "{\"doc\":{\"TranslationList\":{\"" + GetLabelId + "\":\"" + GetTranslation + "\"}},\"detect_noop\":true}";
var Client = new HttpClient();
Client.BaseAddress = new Uri("http://localhost:9200/multilanguage/MultiLangInfo/" + Lang.Type + Lang.Site + Lang.Language + Lang.Source + "/");
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var StringContent = new StringContent(UpdateES, Encoding.UTF8, "application/json");
var ResponseUpdate = Client.PostAsync("_update", StringContent).Result.Content.ReadAsStringAsync();
return await ResponseUpdate;
}
Here is my insight.
Based on the details you provided, you have a long-running task that would eventually create/update a record in your database. Now, the problem you encounter is the second http request you send is not waiting for the first one to finish even though you are using async/await pattern. Well, this is not how it works. Regardless of what you do, whether you block the thread or not, there is thread pooling and distinct http calls will have their own thread. So using async/await would not affect that at all. For the most part, you're using async/await correctly. However, what you're trying to achieve is not done by async/await. You might want to try a messaging system to queue all the requests. In that case, you can't put clients on hold, You'd generate a request id and send it to them immediately and process the request asynchronously in time.

Resources