Create a Excel File and Send by email with Microsoft Graph - c#

I am triying to create an Excel file and then send by email using my microsft email adress using Microsft Graph.
If the only thing that i do is send an email works fine, but if create the excel and then try send email using the same code stops working, no errors, simply stop working.
This is my code:
class Solds
{
public string Empres { get; set; }
public string NClient { get; set; }
public string Name { get; set; }
public string PurchaseNumber { get; set; }
public DateTime Date { get; set; }
public string Codart { get; set; }
public string Description { get; set; }
public string Fampro { get; set; }
public string Serpro { get; set; }
public string Group { get; set; }
public decimal Price { get; set; }
public decimal Cost { get; set; }
public string Seller { get; set; }
public string Quarter { get; set; }
}
static void Main(string[] args)
{
List<String> Destinations = new List<string>() { "myemail#mycompany.com" };
List<string> Cc = new List<string>();
List<System.IO.FileInfo> Filess = new List<System.IO.FileInfo>();
List<Solds> lstSolds = GetData();
SenMailUsingMicrosoftGraph(Destinations, Cc, "", "Text of the Body", "title of the mail", Filess);
// GenerateExcel creates a Excel File (i use ClosedXML) and retuns a FileInfo
Files.Add(GenerateExcel(lstSolds));
SenMailUsingMicrosoftGraph(Destinations, Cc, "", "Text of the Body", "title of the mail", Filess);
}
private static async void SenMailUsingMicrosoftGraph(List<String>Destinations, List<String>Cc, string HidenCopy, string Body, string Title, List<FileInfo>Filess);
{
ClientSecretCredential credential = new ClientSecretCredential("MyTenantID", "MyClientId", "MyClientSecret");
List<Recipient> recipientsDestinatarios = new List<Recipient>();
List<Recipient> recipientsCopias = new List<Recipient>();
foreach (var c in Destinations)
{
recipientsDestinatarios.Add(
new Recipient
{
EmailAddress = new EmailAddress
{
Address = c
}
});
}
foreach (var mail in Cc)
{
recipientsCopias.Add(
new Recipient
{
EmailAddress = new EmailAddress
{
Address = mail
}
});
}
#endregion
var message = new Microsoft.Graph.Message
{
Subject = Title,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = Body
},
ToRecipients = recipientsDestinatarios
,
CcRecipients = recipientsCopias
,
BccRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress=new EmailAddress{Address=Hiden}
}
}
};
GraphServiceClient graphClient = new GraphServiceClient(credential);
#endregion
#region adjuntar ficheros
var msgResult = await graphClient.Users["myemail#mycompany.com"].MailFolders.Drafts.Messages
.Request()
.WithMaxRetry(9)
.AddAsync(message);
foreach (var Archivo in Filess)
{
var attachmentContentSize = Archivo.Length;
var attachmentItem = new AttachmentItem
{
AttachmentType = AttachmentType.File,
Name = Archivo.Name,
Size = attachmentContentSize,
};
//initiate the upload session for large files
var uploadSession = await graphClient.Users["myemail#mycompany.com"].Messages[msgResult.Id].Attachments
.CreateUploadSession(attachmentItem)
.Request()
.PostAsync();
var maxChunkSize = 1024 * 320;
var allBytes = System.IO.File.ReadAllBytes(Archivo.FullName);
using (var stream = new MemoryStream(allBytes))
{
stream.Position = 0;
LargeFileUploadTask<FileAttachment> largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxChunkSize);
await largeFileUploadTask.UploadAsync();
}
}
await graphClient.Users["myemail#mycompany.com"].Messages[msgResult.Id].Send().Request().PostAsync();
}
private static FileInfo GenerateExcel(List<Solds> lstSolds)
{
System.IO.FileInfo file= new System.IO.FileInfo(#"E:\MyFolder\MyFile.xlsx");
if (file.Exists) file.Delete();
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("Example");
ws.Cell(2, 1).InsertTable(lstSolds);
wb.SaveAs(file.FullName);
}
return file;
}
private static List<ventas> ObtenerDatos()
{
List<ventas> lstSolds = new List<Solds>();
string connString = #"Data Source=MyServer\SQLExpress; Initial Catalog=MyDataBAse;User Id=User;Password=password;";
string sentenciaSQL = "QuarterSolds";
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand(sentenciaSQL, conn))
{
DateTime t = DateTime.Now;
conn.Open();
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.CommandTimeout = 240;
using (SqlDataReader reader = comm.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Solds v = new Solds();
decimal d = 0;
v.Empres = reader.GetValue(0).ToString();
v.NClient = reader.GetValue(1).ToString();
v.Name = reader.GetValue(2).ToString();
v.PurchaseNumber = reader.GetValue(3).ToString();
v.Date = DateTime.TryParse(reader.GetValue(4).ToString(), out t) ? t : t;
v.Codart = reader.GetValue(5).ToString();
v.Description = reader.GetValue(6).ToString();
v.Fampro = reader.GetValue(7).ToString();
v.Serpro = reader.GetValue(8).ToString();
v.Group = reader.GetValue(9).ToString();
v.Price = decimal.TryParse(reader.GetValue(10).ToString(), out d) ? d : 0;
v.Cost = decimal.TryParse(reader.GetValue(11).ToString(), out d) ? d : 0;
v.Seller = reader.GetValue(12).ToString();
v.Quarter = reader.GetValue(13).ToString();
lstSolds.Add(v);
}
}
else Console.WriteLine("No lines");
}
}
}
If i execute this first call to my method SenMailUsingMicrosoftGraph works fine and sends an email. But if i call again to SenMailUsingMicrosoftGraph after creating the Excel, the program stops when arrives to:
var msgResult = await graphClient.Users["myemail#mycompany.com"].MailFolders.Drafts.Messages
.Request()
.WithMaxRetry(9)
.AddAsync(message);
Any suggestions?

Make your code really async. Now your program doesn't wait for the response from Graph API and ends immediately after the second call of SenMailUsingMicrosoftGraph.
Use static async Task Main(string[] args), private static async Task SenMailUsingMicrosoftGraph and await before SenMailUsingMicrosoftGraph.
static async Task Main(string[] args)
{
List<String> Destinations = new List<string>() { "myemail#mycompany.com" };
List<string> Cc = new List<string>();
List<System.IO.FileInfo> Filess = new List<System.IO.FileInfo>();
List<Solds> lstSolds = GetData();
await SenMailUsingMicrosoftGraph(Destinations, Cc, "", "Text of the Body", "title of the mail", Filess);
// GenerateExcel creates a Excel File (i use ClosedXML) and retuns a FileInfo
Files.Add(GenerateExcel(lstSolds));
await SenMailUsingMicrosoftGraph(Destinations, Cc, "", "Text of the Body", "title of the mail", Filess);
}
private static async Task SenMailUsingMicrosoftGraph
{
...
}

Whilst debugging, go to 'Exception settings' and click on the box 'Common Language Runtime Exception' so that it turns into a checkmark.
You've probably disabled the specific error being thrown.
After this you'll need to restart debugging.

Related

How Can I Create One xml file with Multiple XML douments inside from a text file

I am a C# beginner programmer. I have a text file, which is my source, with multiple rows of data. I want to create one xml file with multiple xml documents inside the file. The xml documents are generated from the rows of data in the text file. I can only get one xml document to generate in the A0x.xml file that is created. My code only reads the first row of data and generates one xml document instead to multiple xml documents. Below are 8 rows from the M24EX.txt file. Please help!!
A0ASMSS3110004624190 EA00008FB239980940001RAIR A30 0120505 18094133644FT
A0ASMSS5340011122822 HD00001FB239981000001RAIR A6C 0120503 18100124741FT
A0ASMSS5365002870093 EA00003FB239981000002RAIR A6C 0120503 18100125431FT
A0ASMS 5365001671717 EA00005FB239981010001REY2550A6C 0120503133 18101075536SF
A0ASMS 5365001671717 EA00011FB239981010002RGE A6C 0120505129 18101105015FT
A0AFLZ 6625013922071 EA00001FB239981070001RGRN D6C 0120505110 18107150014FT
A0AFLZ 6650013204283 EA00003FB239981070002NGRN D6C 0120504777 18107151015FT
A0ASMSS1650009937278 EA00006FB239981080001RAIR A6C 0120505 18108082906FT
And the code:
Public class Program
{
public static void Main(string[] arg)
{
XDocument A0x = new XDocument();
var IdCode = "511";
var CtrlNbr = "0001";
var PurposeCode = "00";
var TypeCode = "A0";
var EntyIdCode = "OB";
var IdCodeQlfr = "10";
var EntyIdCode1 = "FR";
var DocNbr = "TN";
var AssignNbr = "1";
var NSN = "FS";
var DD = "74";
var AgncyQlfrCode = "DF";
var LstQlfrCode = "0";
DateTime saveUtcNow = DateTime.UtcNow;
DateTime saveNow = DateTime.Now;
var field = new ParseTextFile().Parse();
var tagBuilder = new TagBuilder();
var parent = tagBuilder.BuildParent("File");
var subParent = tagBuilder.BuildParent("T_Requisition_511");
var ParentST = tagBuilder.BuildParent("S_Transaction_Set_Header");
var ST01 = tagBuilder.BuildChild("E_Transaction_Set_Identifier_Code", IdCode);
var ST02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
var ParentBR = tagBuilder.BuildParent("S_Beginning_Segment_for_Material_Management");
var BR01 = tagBuilder.BuildChild("E_Transaction_Set_Purpose_Code", PurposeCode);
var BR02 = tagBuilder.BuildChild("E_Transaction_Type_Code", TypeCode);
var BR03 = tagBuilder.BuildChild("E_Date", saveUtcNow.ToString("yyyyMMdd"));
var BR09 = tagBuilder.BuildChild("E_Time", saveUtcNow.ToString("hhmmss"));
var ParentN1 = tagBuilder.BuildParent("L_Name");
var ParentS = tagBuilder.BuildParent("S_Name");
var N101 = tagBuilder.BuildChild("E_Entity_Identifier_Code", EntyIdCode);
var N103 = tagBuilder.BuildChild("E_Identification_Code_Qualifier", IdCodeQlfr);
var N104 = tagBuilder.BuildChild("E_Identification_Code", field.SRAN);
var N106 = tagBuilder.BuildChild("E_Entity_Identifier_Code_1", EntyIdCode1);
var ParentLX = tagBuilder.BuildParent("L_Assigned_Number");
var ParentAN = tagBuilder.BuildParent("S_Assigned_Number");
var LX01 = tagBuilder.BuildChild("E_Assigned_Number", AssignNbr);
var ParentN9 = tagBuilder.BuildParent("S_Reference_Identification");
var N901 = tagBuilder.BuildChild("E_Reference_Identification_Qualifier", DocNbr);
var N902 = tagBuilder.BuildChild("E_Reference_Identification", field.DocumentNumber);
var ParentPO1 = tagBuilder.BuildParent("S_Baseline_Item_Data");
var PO102 = tagBuilder.BuildChild("E_Quantity_Ordered", Convert.ToString(field.Quantity));
var PO103 = tagBuilder.BuildChild("E_Unit_or_Basis_for_Measurement_Code", field.UnitofIssue);
var PO106 = tagBuilder.BuildChild("E_Product_Service_ID_Qualifier", NSN);
var PO107 = tagBuilder.BuildChild("E_Product_Service_ID", field.StockNumber);
var ParentSE = tagBuilder.BuildParent("S_Transaction_Set_Trailer");
var SE01 = tagBuilder.BuildChild("E_Number_of_Included_Segments", new CountSegmentTags().CountSgmts().ToString());
var SE02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
parent.Add(subParent);
subParent.Add(ParentST);
ParentST.Add(ST01);
ParentST.Add(ST02);
subParent.Add(ParentBR);
ParentBR.Add(BR01);
ParentBR.Add(BR02);
ParentBR.Add(BR03);
ParentBR.Add(BR09);
subParent.Add(ParentN1);
ParentN1.Add(ParentS);
ParentS.Add(N101);
ParentS.Add(N103);
ParentS.Add(N104);
ParentS.Add(N106);
subParent.Add(ParentLX);
ParentLX.Add(ParentAN);
ParentAN.Add(LX01);
ParentLX.Add(ParentN9);
ParentN9.Add(N901);
ParentN9.Add(N902);
ParentLX.Add(ParentPO1);
ParentPO1.Add(PO102);
ParentPO1.Add(PO103);
ParentPO1.Add(PO106);
ParentPO1.Add(PO107);
ParentSE.Add(SE01);
ParentSE.Add(SE02);
A0x.Add(parent);
A0x.Declaration = new XDeclaration("1.0", "utf-8", "true");
A0x.Save("M24EX.xml");
}
public class TagBuilder
{
public XElement BuildParent(string name)
{
return new XElement(name);
}
public XElement BuildChild(string name, string value)
{
var tag = new XElement(name);
tag.Add(value);
return tag;
}
}
public void Read()
{
int counter = 0;
string line;
StreamReader file = new StreamReader("M24EX.txt");
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0")) // only pull "A0x" records
{
counter++;
Console.WriteLine("{0}:{1}", counter, line);
}
file.Close();
}
public class ParseTextFile
{
public TransactionFields Parse()
{
StreamReader file = new StreamReader("M24Ex.txt");
string line;
int counter = 0;
var field = new TransactionFields();
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0"))
{
//Assigns field to the Transaction field names
field.DocumentIdentifier = line.Substring(0, 3).Trim(); // Tric
field.RoutingIdentifier = line.Substring(4, 3).Trim();
field.MediaStatusCode = line.Substring(7, 1).Trim();
field.StockNumber = line.Substring(7, 15).Trim();
field.UnitofIssue = line.Substring(22, 2).Trim();
field.Quantity = Convert.ToInt32(line.Substring(24, 5));
field.DocumentNumber = line.Substring(29, 14).Trim();
field.SRAN = line.Substring(29, 6).Trim();
field.DemandCode = line.Substring(44, 1).Trim();
field.SupplementaryAddress = line.Substring(45, 6).Trim();
field.SignalCode = line.Substring(51, 1).Trim();
field.FundCode = line.Substring(52, 2).Trim();
field.DistributionCode = line.Substring(54, 3).Trim();
field.ProjectCode = line.Substring(57, 3).Trim();
field.Priority = line.Substring(60, 2).Trim();
field.ReqDeliveryDate = line.Substring(62, 3).Trim();
field.AdviceCode = line.Substring(65, 2).Trim();
field.DateReceiptofReq = line.Substring(67, 3).Trim();
field.PurposeCode = line.Substring(70, 1).Trim();
field.ConditionCode = line.Substring(71, 1).Trim();
field.MgmtCode = line.Substring(72, 1).Trim();
}
file.Close();
return field;
}
}
public class ConvertXmlToText
{
public void ConvertXmlDoc()
{
string onlyContent = string.Empty;
XmlDocument xdoc = new XmlDocument();
xdoc.Load("A0x.xml");
var file = xdoc.SelectNodes("File/T_Requisition_511");
for (int i = 0; i < file.Count; i++)
{
onlyContent += string.Format("\n", i);
foreach (XmlNode node in file[i].ChildNodes)
onlyContent += string.Format("{0},", node.InnerText);
}
File.WriteAllText("A0x.txt", onlyContent);
}
}
public class TransactionFields
{
public string DocumentIdentifier { get; set; }
public string RoutingIdentifier { get; set; }
public string MediaStatusCode { get; set; }
public string StockNumber { get; set; }
public string UnitofIssue { get; set; }
public int Quantity { get; set; }
public string DocumentNumber { get; set; }
public string SRAN { get; set; }
public string DemandCode { get; set; }
public string SupplementaryAddress { get; set; }
public string SignalCode { get; set; }
public string FundCode { get; set; }
public string DistributionCode { get; set; }
public string ProjectCode { get; set; }
public string Priority { get; set; }
public double UnitPrice { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}

Autofill with REST API in windows 8.1 phone app

I am implementing a city search so I want a Autofill with the functionality where when I select a city I want the ID to be sent back to the API. to populate some other fields.
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
string text = sender.Text;
if (text.Length >= 3)
{
GetCities(text);
sender.ItemsSource = await Task<string[]>.Run(() => { return this.GetSuggestions(text); });
}
else
{
sender.ItemsSource = new string[] { "No suggestions..." };
}
}
}
My Get response class
private async void GetCities(string city)
{
try
{
string baseAddress = Url.url + "searchCities?q="+city+"&access_token=" + tcm;
HttpClient httpClient = new HttpClient();
string co = "";
var content = await httpClient.GetAsync(new Uri(baseAddress));
if (!content.IsSuccessStatusCode)
{
TokenGenerator tc = new TokenGenerator();
tc.GetToken();
tcm = TokenManager.accessT.access_tocken;
HttpClient client = new HttpClient();
content = await client.GetAsync(new Uri(baseAddress));
}
co = await content.Content.ReadAsStringAsync();
AutofillHelper result = JsonConvert.DeserializeObject<AutofillHelper>(co);
foreach (var item in result.data)
{
suggestions = new string [] {item.city} ;
}
}
catch (Exception ex)
{
dispatcherTimer.Stop();
throw new Exception(ex.ToString());
}
}
private string[] GetSuggestions(string text)
{
string[] result = null;
result = suggestions.Where(x => x.StartsWith(text)).ToArray();
return result;
}
My Get Set
class Autofill
{
public string city_id { get; set; }
public string city { get; set; }
}
class AutofillHelper
{
public List<Autofill> data { get; set; }
}
I want it to display the response from the API for the person to select it. A Run time error is thrown. Can someone please guide me what has gone wrong.
Any kind of help is appreciated...

Parsing JSON data in Windows app

Suppose this is my JSON data received through an API:
[
{
"id": "1",
"title": "Test_rom",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.1.png"
},
{
"id": "2",
"title": "Jewelry",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.2.png"
},
{
"id": "3",
"title": "Jackets",
"subtitle": "All sizes available",
"icon": "http://lpl.info/Admin/upload/cat.3.png"
}
]
I created a class called "RootObject":
public class RootObject {
public string id { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string icon { get; set; }
}
I only want to extract values of "title" keys from the array. How can I achieve that?
I tried the following code, but I am getting error in "Encoding" word:
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
RootObject childlistonly = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(TotalList.GetType());
TotalList = ser.ReadObject(ms) as RootObject;
string category = "";
foreach(var d in TotalList.title) {
category = category + " " + d.ToString() + "\n";
}
ResultsText.Text = category;
I used the following, but it is giving an error:
var titlevariable = myobj.title;
Textblock.Text = titlevariable; // (under a click button method)...
Try this
foreach(var d in TotalList) {
category = category + " " + d.title.ToString() + "\n";
}
#kickaha..
private async void Butoon_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var uri = new Uri("http://www.blabla.com/alliance/App/mobilelogin.php?KG=MA&EM="+Textboxname.Text+"&PA="+password.Password);
var response = await client.GetAsync(uri);
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
RootObject resu = (RootObject)ser.ReadObject(ms);
NavigationContext nav = new NavigationContext()
{
ID = resu.USERID.ToString(),
Name = resu.NAME.ToString(),
Email = resu.EMAIL.ToString()
}
SaveFile();
RestoreFile();
}
private async void SaveFile()
{
StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserDetails", CreationCollisionOption.ReplaceExisting);
IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);
using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
{
// Serialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(NavigationContext));
serializer.WriteObject(outStream.AsStreamForWrite(), nav);
await outStream.FlushAsync();
}
}
private async void RestoreFile()
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("UserDetails");
if (file == null) return;
IRandomAccessStream inStream = await file.OpenReadAsync();
// Deserialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(NavigationContext));
var StatsDetails = (NavigationContext)serializer.ReadObject(inStream.AsStreamForRead());
inStream.Dispose();
string hu = StatsDetails.Name + "\n" + StatsDetails.Email;
// UserName.Text = "Welcome " + StatsDetails.Name;
// UserProfileId = StatsDetails.Id;
resultblock.Text = hu;
}
}
public class RootObject
{
public string USERID { get; set; }
public string EMAIL { get; set; }
public string NAME { get; set; }
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public string CITY { get; set; }
}
public class NavigationContext
{
public string ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Email { get; set; }
}
}
i am getting null value in "instream" property of Restorefile() method...

Time of query very long

i'm new on the world of elasticsearch and i'm trying to code it in c# with the NEST aPI.
I succed to index some doc with content but when i try to search, the research take ~4sec.
I use visual studio 2012
I hope you can help me :)
[ElasticType(Name = "document")]
public class Document
{
public int Id { get; set; }
[ElasticProperty(Store = true)]
public string Titre { get; set; }
[ElasticProperty(Type = FieldType.Attachment, TermVector = TermVectorOption.WithPositionsOffsets, Store = true)]
public Attachment File { get; set; }
}
public class Attachment
{
[ElasticProperty(Name = "_content")]
public string Content { get; set; }
[ElasticProperty(Name = "_content_type")]
public string ContentType { get; set; }
[ElasticProperty(Name = "_name")]
public string Name { get; set; }
}
static int i = 0;
static int j = 0;
This is my class's declarations
static void Main(string[] args)
{
//New connection
//var node = new Uri("http://serv-intra:9200");
var node = new Uri("http://localhost:9200/");
var settings = new ConnectionSettings(
node,
defaultIndex: "document"
);
var client = new ElasticClient(settings);
//Creation of my index with mapping
//client.CreateIndex("document", c => c
// .AddMapping<Document>(m => m.MapFromAttributes())
// );
//function for index
//feignasse(client);
var query = Query<Document>.Term("_all", "chu");
var searchResults = client.Search<Document>(s => s
.From(0)
.Size(200)
.Query(query)
);
}
protected static void feignasse(ElasticClient client)
{
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
Indexation(#"\\serv-intra\Documents", client);
// Stop timing
stopwatch.Stop();
}
//This is my function for index
protected static void Indexation(string path, ElasticClient client)
{
string[] rootDirectories = Directory.GetDirectories(path);
string[] rootFiles = Directory.GetFiles(path);
foreach (string nomfich in rootFiles)
{
if (nomfich.Length < 256)
{
FileInfo file = new FileInfo(nomfich);
var attachement = new Attachment();
attachement.Content = Convert.ToBase64String(File.ReadAllBytes(nomfich));
attachement.Name = file.Name;
attachement.ContentType = GetMimeType(file.Extension);
var document = new Document
{
Id = i,
Titre = file.Name,
File = attachement,
};
var index = client.Index(document);
i++;
}
else
{
j++;
}
}
foreach (string newPath in rootDirectories)
{
Indexation(newPath, client);
}
So i explain you, in my server i have a sharing of doc, and i just travel him in order to catch all my doc and index then in elasticsearch
I have to node with 0 replica and 5 shards
Thanks you

set content-available using moon apns

referring to this link : http://www.objc.io/issue-5/multitasking.html i can now send a silent push notification on ios by setting content-available=1
i'm using moon apns on c# to send the push notification but i can not find this property to send a silent push (i'm using a development certificate)
below is my code :
string p12File = "test.p12";
string p12FilePassword = "1234";
bool sandbox = false;
var push = new PushNotification(sandbox, p12File, p12FilePassword);
NotificationPayload payload1;
payload1 = new NotificationPayload(testDeviceToken, message, 0, "Silence.m4R");
payload1.AddCustom("message", "HIDDEN");
var notificationList = new List<NotificationPayload>() { payload1 };
var rejected = push.SendToApple(notificationList);
foreach (var item in rejected)
{
return false;
}
any idea how can send this using moon apns :
{
"aps" : {
"content-available" : 1
},
"content-id" : 42
}
System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace MoonAPNS
{
public class NotificationPayload
{
public NotificationAlert Alert { get; set; }
public string DeviceToken { get; set; }
public int? Badge { get; set; }
public string Sound { get; set; }
internal int PayloadId { get; set; }
public int Content_available { get; set; }
public Dictionary<string, object[]> CustomItems
{
get;
private set;
}
public NotificationPayload(string deviceToken)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert();
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge, string sound)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge, string sound,int content_available)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
Content_available = content_available;
CustomItems = new Dictionary();
}
public void AddCustom(string key, params object[] values)
{
if (values != null)
this.CustomItems.Add(key, values);
}
public string ToJson()
{
JObject json = new JObject();
JObject aps = new JObject();
if (!this.Alert.IsEmpty)
{
if (!string.IsNullOrEmpty(this.Alert.Body)
&& string.IsNullOrEmpty(this.Alert.LocalizedKey)
&& string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
&& (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0))
{
aps["alert"] = new JValue(this.Alert.Body);
}
else
{
JObject jsonAlert = new JObject();
if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);
if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());
if (!string.IsNullOrEmpty(this.Alert.Body))
jsonAlert["body"] = new JValue(this.Alert.Body);
if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);
aps["alert"] = jsonAlert;
}
}
if (this.Badge.HasValue)
aps["badge"] = new JValue(this.Badge.Value);
if (!string.IsNullOrEmpty(this.Sound))
aps["sound"] = new JValue(this.Sound);
if (this.Content_available == 1)
aps["content-available"] = new JValue(this.Content_available);
json["aps"] = aps;
foreach (string key in this.CustomItems.Keys)
{
if (this.CustomItems[key].Length == 1)
json[key] = new JValue(this.CustomItems[key][0]);
else if (this.CustomItems[key].Length > 1)
json[key] = new JArray(this.CustomItems[key]);
}
string rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);
StringBuilder encodedString = new StringBuilder();
foreach (char c in rawString)
{
if ((int)c < 32 || (int)c > 127)
encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
else
encodedString.Append(c);
}
return rawString;// encodedString.ToString();
}
public override string ToString()
{
return ToJson();
}
}

Categories

Resources