Get creation date for the file with SharpSvn - c#

I'm playing with SharpSvn and have to analyze folder in repository
and I need to know when some file has be created there,
not last modification date, but when it was created,
Do you have any idea how to do that?
I started with the following:
Collection<SvnLogEventArgs> logitems;
var c = client.GetLog(new Uri(server_path), out logitems);
foreach (var i in logitems)
{
var properties = i.CustomProperties;
foreach (var p in properties)
{
Console.WriteLine(p.ToString());
Console.WriteLine(p.Key);
Console.WriteLine(p.StringValue);
}
}
But I don't see any creation date there.
Does someone know where to get it?

Looks like I can't do that. Here is how I solved this problem:
I'm getting the time if it was the SvnChangeAction.Add.
Here is the code (SvnFile is my own class, not from SharpSvn):
public static List<SvnFile> GetSvnFiles(this SvnClient client, string uri_path)
{
// get logitems
Collection<SvnLogEventArgs> logitems;
client.GetLog(new Uri(uri_path), out logitems);
var result = new List<SvnFile>();
// get craation date for each
foreach (var logitem in logitems.OrderBy(logitem => logitem.Time))
{
foreach (var changed_path in logitem.ChangedPaths)
{
string filename = Path.GetFileName(changed_path.Path);
if (changed_path.Action == SvnChangeAction.Add)
{
result.Add(new SvnFile() { Name = filename, Created = logitem.Time });
}
}
}
return result;
}

Slightly different code than the previous one:
private static DateTime findCreationDate(SvnClient client, SvnListEventArgs item)
{
Collection<SvnLogEventArgs> logList = new Collection<SvnLogEventArgs>();
if (item.BasePath != "/" + item.Name)
{
client.GetLog(new Uri(item.RepositoryRoot + item.BasePath + "/" + item.Name), out logList);
foreach (var logItem in logList)
{
foreach (var changed_path in logItem.ChangedPaths)
{
string filename = Path.GetFileName(changed_path.Path);
if (filename == item.Name && changed_path.Action == SvnChangeAction.Add)
{
return logItem.Time;
}
}
}
}
return new DateTime();
}

Related

Iterating through a list populated by a text file to look for a reference C#

I'm new to C# and i'm trying to check whether a guest has checked in on a hotel app. I'm trying to get all bookings in a text file pass them in to a list then read through the list looking for the booking in reference.
The problem i'm having is that it only seems to put the first line of the text file into the list. Could anyone help me solve this?
One way i've tried:
public void CheckBookingReference()
{
List<string> BookingList = File.ReadAllLines(BookingFilePath).ToList();
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
Console.WriteLine("Booking found, check in complete.");
break;
}
else
{
throw new Exception("BookingNotFoundException");
}
}
}
Another way i've also tried:
public void CheckBookingReference()
{
List<string> BookingList = new List<string>();
using (var sr = new StreamReader(BookingFilePath))
{
while (sr.Peek() >= 0)
BookingList.Add(sr.ReadLine());
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
//throw new Exception("GuestAlreadyCheckedInException");
Console.WriteLine("booking found");
break;
}
else if (_BookingReferenceNumber != BookingReferenceNumber)
{
Console.WriteLine("not found");
break;
}
}
}
}
With the code you have, if the first line doesn't match, you throw the exception.
Try this:
public void CheckBookingReference()
{
List<string> BookingList = File.ReadAllLines(BookingFilePath).ToList();
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
Console.WriteLine("Booking found, check in complete.");
return;
}
}
throw new Exception("BookingNotFoundException");
}

Object multiple reference IEntityTracker error while saving audit table

first I know this question has been asked but I really couldn't find an answer nor find the root of the problem so maybe a someone points me in the right direction.
I'm having the An entity object cannot be referenced by multiple instances of IEntityChangeTracker. error when trying to save into the log tables.
for the log table, I'm using
https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.EntityFramework
so inside my DbContext class where I define the dbset, I have to override the onscopecreated function
the problem here is that when context.Savechanges run for the first audit record for each table it works but after first record, I get the multiple reference error.
so let's say I have the following tables
Languages table. with the following values
English,French,German
Countries Table with the following values
UK,France,Germany
for languages table, if I change English to English3 and save it works It records to the audit table but then for languages table, I can not do any changes at any records it's the same in every table
what am I missing?
private void SaveToLogTable(AuditScope auditScope)
{
foreach (var entry in ((AuditEventEntityFramework)auditScope.Event).EntityFrameworkEvent.Entries)
{
if(entry.Action is null) return;
if (TABLES.Any(x => x.T_TABLE_NAME.Equals(entry.Table)))
{
var newLog = new LOGS
{
LOG_ACTION = ACTIONS.FirstOrDefault(x => x.A_DESC == entry.Action)?.A_CODE,
LOG_DATE = DateTime.Now,
USERS = MyGlobalSettings.MyUser
};
if (entry.Changes != null)
{
foreach (var changes in entry.Changes)
{
var ch = new CHANGES
{
CH_COLUMN = changes.ColumnName,
CH_NEW_VALUE = changes.NewValue.ToString(),
CH_ORIGINAL_VALUE = changes.OriginalValue.ToString()
};
newLog.CHANGES.Add(ch);
}
}
if (entry.ColumnValues != null)
{
foreach (var kv in entry.ColumnValues)
{
var val = new VALUES
{
ColumnName = kv.Key,
ColumnValue = kv.Value.ToString()
};
newLog.VALUES.Add(val);
}
}
TABLES.First(x => x.T_TABLE_NAME.Equals(entry.Table)).LOGS.Add(newLog);
}
else
{
var table = new TABLES {T_TABLE_NAME = entry.Table};
var newLog = new LOGS
{
LOG_ACTION = ACTIONS.FirstOrDefault(x => x.A_DESC.Equals(entry.Action))?.A_CODE,
LOG_DATE = DateTime.Now,
LOG_USER_REFNO = MyGlobalSettings.MyUser.U_ROWID
//USERS = MyGlobalSettings.MyUser
};
if (entry.Changes != null)
{
foreach (var changes in entry.Changes)
{
var ch = new CHANGES
{
CH_COLUMN = changes.ColumnName,
CH_NEW_VALUE = changes.NewValue.ToString(),
CH_ORIGINAL_VALUE = changes.OriginalValue.ToString()
};
newLog.CHANGES.Add(ch);
}
}
if (entry.ColumnValues != null)
{
foreach (var kv in entry.ColumnValues)
{
var val = new VALUES
{
ColumnName = kv.Key,
ColumnValue = kv.Value is null? "": kv.Value.ToString()
};
newLog.VALUES.Add(val);
}
}
table.LOGS.Add(newLog);
//TABLES.Attach(table);
//TABLES.First(x => x.T_TABLE_NAME.Equals(entry.Table)).LOGS.Add(newLog);
TABLES.Add(table);
//TablesList.Add(table);
}
//entry.Entity
}
}

Instagram API: How to insert all user media in c# asp.net mvc?

I am trying the get all user media from the instagram api and store into database but how can do that i don't know. i am write the code but using this code just add one media in the database. any one have the idea then please let me know how can do that. here below list the my code.
This is my C# method :
public string makePostFromInstagram()
{
var serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
var nodes1 = serializer1.Deserialize<dynamic>(GetData(strInstagramUserId));
foreach (var date in nodes1)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
int userCount = 0;
foreach (var post in thisNode)
{
if (thisNode[userCount]["username"] == strInstagramUserId)
{
id = thisNode[userCount]["id"].ToString();
}
userCount++;
}
}
}
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> csObj = serializer.Deserialize<Dictionary<string, object>>(GetRecentPost(id, accessToken));
int length = ((ArrayList)csObj["data"]).Count;
var nodes = serializer.Deserialize<dynamic>(GetRecentPost(id, accessToken));
foreach (var date in nodes)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
foreach (var post in thisNode)
{
UsersOnInstagram objUserInsta = new UsersOnInstagram();
string result = null;
//here i am add just one image so i want to here add multiple image insert
if (post["type"] == "image")
result = UsersOnInstagram.addInstagramPost(strPtId, HttpUtility.UrlEncode(post["caption"]["text"]), post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), null, post["type"]);
else if (post["type"] == "video")
result = objUserInsta.addInstagramPost(HttpUtility.UrlEncode(post["caption"]["text"]), strPtId, post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), post["videos"]["standard_resolution"]["url"], post["type"]);
}
}
}
Response.End();
}
this is my api method :
public static string GetRecentPost(string instagramaccessid, string instagramaccesstoken)
{
Double MAX_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-1));
Double MIN_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-2));
string url = "https://api.instagram.com/v1/users/" + instagramaccessid + "/media/recent?access_token=" + instagramaccesstoken + "&min_timestamp=" + MIN_TIMESTAMP + "&maz_timestamp=" + MAX_TIMESTAMP;
var webClient = new System.Net.WebClient();
string d = webClient.DownloadString(url);
return d;
}
any one know how can do that please let me know.

sbyte arrays always coming back null

I have a function to writes a bunch of "ImageSignatures" to a DbContext:
using (var db = new ImageContext())
{
foreach (var file in files)
{
var sig = new ImageSignature
{
FileName = file,
Signature = Signature(file),
};
Console.WriteLine("{0}: {1}", Path.GetFileName(sig.FileName), Sig2Str(sig.Signature));
if (sig.Signature != null)
{
db.Images.Add(sig);
}
}
try
{
records = db.SaveChanges(); // where the heck is this saving to!?
}
...
Where the Signature property is defined as
[MinLength(420)]
[MaxLength(420)]
[Required]
public sbyte[] Signature { get; set; }
If I put a breakpoint just before I Add the sig, I can see that it's not null, but a 420 byte array as I expect.
On a later run of the application I try to loop over the ImageSignatures I inserted,
foreach (var img1 in db.Images)
{
var set = new List<string> { img1.FileName };
foreach (var img2 in db.Images)
{
if (Distance(img1.Signature, img2.Signature) < 0.6)
{
set.Add(img2.FileName);
}
}
if (set.Count > 1)
{
dupeSets.Add(set);
}
}
But Signature is always coming back as null. What happened to it? How did it become null, when it wasn't null when I saved it?
Make sure you have saved the changes to your DbContext before disposing it which will ensure that those changes got persisted in the underlying data store:
using (var db = new ImageContext())
{
foreach (var file in files)
{
var sig = new ImageSignature
{
FileName = file,
Signature = Signature(file),
};
Console.WriteLine("{0}: {1}", Path.GetFileName(sig.FileName), Sig2Str(sig.Signature));
db.Images.Add(sig);
}
db.SaveChanges();
}

C# Extract text from PDF using PdfSharp

Is there a possibility to extract plain text from a PDF-File with PdfSharp?
I don't want to use iTextSharp because of its license.
Took Sergio's answer and made some extension methods. I also changed the accumulation of strings into an iterator.
public static class PdfSharpExtensions
{
public static IEnumerable<string> ExtractText(this PdfPage page)
{
var content = ContentReader.ReadContent(page);
var text = content.ExtractText();
return text;
}
public static IEnumerable<string> ExtractText(this CObject cObject)
{
if (cObject is COperator)
{
var cOperator = cObject as COperator;
if (cOperator.OpCode.Name== OpCodeName.Tj.ToString() ||
cOperator.OpCode.Name == OpCodeName.TJ.ToString())
{
foreach (var cOperand in cOperator.Operands)
foreach (var txt in ExtractText(cOperand))
yield return txt;
}
}
else if (cObject is CSequence)
{
var cSequence = cObject as CSequence;
foreach (var element in cSequence)
foreach (var txt in ExtractText(element))
yield return txt;
}
else if (cObject is CString)
{
var cString = cObject as CString;
yield return cString.Value;
}
}
}
I have implemented it somehow similar to how David did it.
Here is my code:
...
{
// ....
var page = document.Pages[1];
CObject content = ContentReader.ReadContent(page);
var extractedText = ExtractText(content);
// ...
}
private IEnumerable<string> ExtractText(CObject cObject)
{
var textList = new List<string>();
if (cObject is COperator)
{
var cOperator = cObject as COperator;
if (cOperator.OpCode.Name == OpCodeName.Tj.ToString() ||
cOperator.OpCode.Name == OpCodeName.TJ.ToString())
{
foreach (var cOperand in cOperator.Operands)
{
textList.AddRange(ExtractText(cOperand));
}
}
}
else if (cObject is CSequence)
{
var cSequence = cObject as CSequence;
foreach (var element in cSequence)
{
textList.AddRange(ExtractText(element));
}
}
else if (cObject is CString)
{
var cString = cObject as CString;
textList.Add(cString.Value);
}
return textList;
}
PDFSharp provides all the tools to extract the text from a PDF. Use the ContentReader class to access the commands within each page and extract the strings from TJ/Tj operators.
I've uploaded a simple implementation to github.

Categories