Time of query very long - c#

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

Related

Create a Excel File and Send by email with Microsoft Graph

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.

Using multiple channels, what am I doing wrong?

I want to create an array of Tasks, called listTask, with each element of listTask is a Task of type A, Task of type A is created by the function Task.WhenAll. then I do await Task.WhenAll(listTask) But the program does not perform the work in the listTask array. I set debug and those tasks were completed, I don't understand why
namespace Ding.LearningNewThings
{
public class MultiChannelTask
{
public static async Task RunMiltipleChannel()
{
ConcurrentDictionary<int, Channel<Position>> _dataChannels = new ConcurrentDictionary<int, Channel<Position>>();
var listPlace = Place.InitData();
var numberOfPlace = listPlace.Count();
for (int i = 0; i < listPlace.Count(); i++)
{
_dataChannels.TryAdd(i, Channel.CreateUnbounded<Position>());
}
Task[] listStationTask = new Task[numberOfPlace];
for (var j = 0; j < numberOfPlace; j++)
{
var listTask = new Task[2];
var placeOuter = listPlace[j];
listTask[0] = Task.Run(async () =>
{
int IndexOfPlace = j;
var place = new Place()
{
ID = placeOuter.ID,
Name = placeOuter.Name
};
Channel<Position> dataChannel;
var r = new Random();
if (_dataChannels.TryGetValue(IndexOfPlace, out dataChannel))
{
var position = new Position()
{
PlaceID = place.ID,
PlaceName = place.Name,
ID = r.Next(1, 100)
};
await dataChannel.Writer.WriteAsync(position);
Console.WriteLine($"Push postion ID {position.ID}, Place ID {position.PlaceID}");
}
});
listTask[1] = Task.Run(async () =>
{
var IndexOfPlace = j;
Channel<Position> dataChannel;
var r = new Random();
if (_dataChannels.TryGetValue(IndexOfPlace, out dataChannel)) {
var position = await dataChannel.Reader.ReadAsync();
Console.WriteLine($"Get postion ID {position.ID}, Place ID {position.PlaceID}");
}
});
listStationTask[j] = Task.WhenAll(listTask);
}
await Task.WhenAll(listStationTask);
}
}
public class Place
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Place> InitData()
{
var listData = new List<Place>();
for (int i = 0; i < 10; i++)
{
var data = new Place()
{
ID = i,
Name = $"Postion{i}",
};
listData.Add(data);
}
return listData;
}
}
public class Position
{
public int ID { get; set; }
public int PlaceID { get; set; }
public string PlaceName { get; set; }
public string Name { get; set; }
public static List<Position> InitData()
{
var listData = new List<Position>();
for (int i = 0; i < 10; i++)
{
var data = new Position()
{
ID = i,
Name = $"Postion{i}"
};
listData.Add(data);
}
return listData;
}
}
}
I seem the task have had done ahead of intended. Sometimes it works, but I don't know why the job always completes without running in the list task code.

Applying a filter to an embedded document, filter out distinct values

So I built out a my filter, on the document and sub document, and then passed that filter into a distinct query. I want to use that query in my cursor but I'm getting an error, FindAsync cannot be inferred from the usage. Try specifying the type arguments explicitly.
I'm very new to Mongodb...any help would be fantastic. This works if I just pass the filter, but I need just distinct documents.
var builder = Builders<newMsg>.Filter;
var filter = builder.Eq("type", "CREATE") & builder.Eq("entities.errorCondition", 14);
// var result = collection.Find(filter).ToList();
IList<newMsg> distinct = collection.Distinct<newMsg>("entities.ID", filter).ToList<newMsg>();
if (distinct.Count > 0)
{
using (IAsyncCursor<newMsg> cursor = await collection.FindAsync(distinct))
{
while (await cursor.MoveNextAsync())
{
IEnumerable<newMsg> batch = cursor.Current;
foreach (newMsg document in batch)
{
//This gives me the entire list as a string
var subDocument = document.Entities;
foreach (var sd in subDocument)
{
//do some stuff
}
}
}
}
}
}
my class files look like this
[BsonIgnoreExtraElements]
internal class newMsg
{
[BsonId]
public ObjectId _id { get; set; }
[BsonElement("type")]
public string Type { get; set; }
[BsonElement("entities")]
public List<entity> Entities { get; set; }
}
[BsonIgnoreExtraElements]
internal class entity : newMsg
{
[BsonElement("errorCondition")]
public double ErrorCondition { get; set; }
[BsonElement("ID")]
public string ID { get; set; }
}
I ended up creating 2 loops, 1 for duplicates and another for distinct values, its not beautiful but it worked.
var builder = Builders<newMsg>.Filter;
var filter = builder.Eq("Type", "CREATE") & builder.Eq("Entities.ErrorCondition", 14) & builder.Eq("MsgRead", false);
var result = collection.Find(filter).ToList();
if (result.Count > 0)
{
//Create a list of distinct msgs, then set msgRead to True, then pass that list to a new filter
var distinctMsg = collection.Distinct(new StringFieldDefinition<newMsg, string>("Entities.ID"), FilterDefinition<newMsg>.Empty).ToList();
foreach (var dm in distinctMsg)
{
var entityID = dm;
var msgUnread = Builders<newMsg>.Filter.Eq("msgRead", false);
var msgUpdate = Builders<newMsg>.Update.Set("msgRead", true);
var msgIsRead = collection.UpdateOne(msgUnread, msgUpdate);
//Create another filter on the distinct messages
CreateDistinctFilter(mongoClient, db, collection, entityID, ec);
}
using (IAsyncCursor<newMsg> cursor = await collection.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
IEnumerable<newMsg> batch = cursor.Current;
foreach (newMsg document in batch)
{
//This gives me the entire list as a string
var subDocument = document.Entities;
foreach (var sd in subDocument)
{
//log duplicate msg
}
}
}
}
}
static async void CreateDistinctFilter(MongoClient mongoClient, IMongoDatabase db, IMongoCollection<newMsg> collection, string entityID, string ec)
{
var builder = Builders<newMsg>.Filter;
var distinctFilter = builder.Eq("Entities.ID", entityID) & builder.Eq("MsgRead", true);
var result = collection.Find(distinctFilter).ToList();
using (IAsyncCursor<newMsg> cursor = await collection.FindAsync(distinctFilter))
{
while (await cursor.MoveNextAsync())
{
IEnumerable<newMsg> batch = cursor.Current;
foreach (newMsg document in batch)
{
//This gives me the entire list as a string
var subDocument = document.Entities;
foreach (var sd in subDocument)
{
string DeviceName = sd.Name;
string Title = DeviceName + " Device DOWN";
string Msg = sd.Reason + sd.ID;
string ErrorCondition = ec;
Console.WriteLine("UNIQUE: " + " " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff") + Msg );
Console.WriteLine();
}
}
}
}
}
}

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

The specified table does not exist[entity]

I have spent hours trying to figure out why my database cannot find the table I have found numerous examples and none have seemed to help. I have created a separate class to handle the database operations so I can use it on multiple pages.
Here is the code
[Table]
public class MatchItem
{
[Column(IsPrimaryKey = true, CanBeNull=false,IsDbGenerated=true)]
public int MatchID { get; set; }
[Column(CanBeNull = false)]
public string MatchNumber { get; set; }
[Column(CanBeNull = false)]
public string EventName { get; set; }
[Column(CanBeNull = false)]
public DateTime Time { get; set; }
[Column(CanBeNull = false)]
public string[] RedTeams { get; set; }
[Column(CanBeNull = false)]
public string[] BlueTeams { get; set; }
[Column(CanBeNull = false)]
public int RedFinal { get; set; }
[Column(CanBeNull = false)]
public int BlueFinal{ get; set; }
}
Here is the Data context
public class MatchDataContext:DataContext
{
public MatchDataContext(string connectionString) :
base(connectionString)
{
}
public Table<MatchItem> Matches
{
get
{
return this.GetTable<MatchItem>();
}
}
}
I made a class so I could use it on multiple pages
public class MatchDBManager
{
private static string connectionString = #"Data Source=isostore:/DB.sdf";
public MatchDBManager()
{
initialize();
}
public void initialize()
{
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
if (Mchdb.DatabaseExists())
{
Console.WriteLine("DB already exists");
}
else
{
Mchdb.CreateDatabase();
Console.WriteLine("DB created");
}
}
}
public void addMatchData(IList<MatchItem> data)
{
//this.clearData();
//initialize();
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
Mchdb.Matches.InsertAllOnSubmit(data);
Mchdb.SubmitChanges();
}
}
public IList<MatchItem> getTeamData(string teamNum)
{
IList<MatchItem> MatchList = null;
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
IQueryable<MatchItem> mchQuery = from mch in Mchdb.Matches where (mch.RedTeams[0] == teamNum || mch.RedTeams[1] == teamNum || mch.RedTeams[2] == teamNum || mch.BlueTeams[0] == teamNum || mch.BlueTeams[1] == teamNum || mch.BlueTeams[2] == teamNum) select mch;
MatchList = mchQuery.ToList();
}
return MatchList;
}
public IList<MatchItem> getEventData(string eventID)
{
IList<MatchItem> MatchList = null;
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
IQueryable<MatchItem> mchQuery = from mch in Mchdb.Matches where mch.Event == eventID select mch;
MatchList = mchQuery.ToList();
}
return MatchList;
}
private void clearData()
{
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
if (Mchdb.DatabaseExists())
{
Mchdb.DeleteDatabase();
}
}
}
}
I have the error The specified table does not exist[Match].
Added here is where I download
public IList<MatchItem> ParseXML(XmlReader reader)
{
//List<string> save = new List<string>();
List<MatchItem> MatchList= new List<MatchItem>();
XElement matchData;
matchData = XElement.Load(reader);
StringBuilder output = new StringBuilder();
int count = 0;
var matches = from item
in matchData.Elements("match")
select item;
foreach (XElement eachmatch in matches)
{
MatchItem mch = new MatchItem();
string Time = ((eachmatch.Element("pubdate").Value).ToString());
mch.EventName = ((eachmatch.Element("event").Value).ToString());
mch.MatchNumber = ((eachmatch.Element("mch").Value).ToString() + (eachmatch.Element("typ").Value).ToString());
string[] RT = { eachmatch.Element("red1").Value.ToString(), eachmatch.Element("red2").Value.ToString(), eachmatch.Element("red3").Value.ToString() };
string[] BT = { eachmatch.Element("blue1").Value.ToString(), eachmatch.Element("blue2").Value.ToString(), eachmatch.Element("blue3").Value.ToString() };
string RF = ((eachmatch.Element("rfin").Value).ToString());
string BF = ((eachmatch.Element("bfin").Value).ToString());
// Time = Time.Substring(0, (Time.IndexOf("+") - 1));
mch.Time = DateTime.Parse(Time);
mch.RedTeams = RT;
mch.BlueTeams = BT;
mch.RedFinal = int.Parse(RF);
mch.BlueFinal= int.Parse(BF);
mch.MatchID = count;
count += 1;
MatchList.Add(mch);
}
return MatchList;
}
This is where I call this method
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
initializeDB();
if (e.Error == null)
{
XmlReader reader = XmlReader.Create(new StringReader(e.Result));
DownloadInfo di = new DownloadInfo();
IList <MatchItem>data= di.ParseXML(reader);
outputer(data);
addData(data.ToList<MatchItem>());
}
else
{
IList<MatchItem> data = getTeamData(strMyTeam);
outputer(data);
}
}
I ended up removing the DatabaseManager class and putting the functions in the main code
Then I output them to the screen here
public void outputer(IList<MatchItem> mch)
{
for (int i = 0; i < mch.Count; i++)
{
Score sc = new Score();
sc.Width = lsbData.Width;
sc.Height = sc.Height;
sc.Time = mch[i].Time.ToString();
sc.Event = mch[i].EventName;
sc.RT = mch[i].RedTeams[0] + " " + mch[i].RedTeams[1] + " " + mch[i].RedTeams[2];
sc.BT = mch[i].BlueTeams[0] + " " + mch[i].BlueTeams[1] + " " + mch[i].BlueTeams[2];
sc.RF = mch[i].RedFinal.ToString();
sc.BF = mch[i].BlueFinal.ToString();
lsbData.Items.Add(sc);
}
}
*note:score is a custom control that works(and worked) before the database code *
I don't see where you actually create a Match Object.
if you have you need to include that code in the question as well. and if you haven't, that would explain why it doesn't exist.
Addition
in order to add Match Objects to a list you will have to create the objects first then add them to the list, I don't think you can create the whole list of objects before creating each individual object.
more Additional Information
the object still needs to be created before you can add items to it. that is what the error is telling you. you don't have the object to insert data into.
Match Table1 = new Match();
this creates a new Match object which allows you to access the pieces of the object and insert data into the object like this
Table1.MatchNumber = 42
you can't add to something to a memory location until you set aside that memory location for that specific person and give it a name.
when you create that class you can add functions and all sorts of fun stuff to it, but you can't use any of it until you have created a Match Object.
you can't add something to a list that doesn't exist, you have to create the Match Object first, then add it to the list

Categories

Resources