Strings and text, and anger - c#

I am trying to find a certain string in a text file, then create a folder based off of what that string says, somewhere along the lines, what I have just stops, it doesn't exception, it doesn't spit out errors, it just stops.
the strings I am trying to find are set up like this:
50.1 : Oxygas ------> = 1
50.2 : laser -------> = 0
etc.
foreach (string file in files)
{
string thepathoflife = Path.GetFullPath(file);
//CreatetheFolder(file)
string filetocopy = file;
object bob = file.Clone();
string bobby = bob.ToString();
string location = file;
bool b = false;
string extension = Path.GetExtension(file);
string thenameofdoom = Path.GetFileNameWithoutExtension(file);
string filename = Path.GetFileName(file);
////bobby.Move(#"\\TEST12CVG\Public\Posts\Temporaryjunk" + filename);
// string oldlocation = filename+extension;
if (extension == ".pst" ||
extension == ".tec" ||
extension == ".pas" ||
extension == ".snc" ||
extension == ".cst" ||
extension == ".xml")
{
b = true;
}
if (thenameofdoom == "Plasma" ||
thenameofdoom == "Oxygas" ||
thenameofdoom == "plasma" ||
thenameofdoom == "oxygas" ||
thenameofdoom == "Oxyfuel" ||
thenameofdoom == "oxyfuel")
{
b = false;
}
if (b == true)
// System.IO.File.WriteAllText(newlocation, bobby);
{
bool plasma = false;
bool oxygas = false;
bool punch = false;
bool laser = false;
var findLevel = 6;
var path = #thepathoflife;
var levels = path.Split(Path.DirectorySeparatorChar);
var second = levels.Length > findLevel ? levels[findLevel] : null;
//this is where the problem starts.
StreamReader s = new StreamReader(#thepathoflife);
StreamReader st = new StreamReader(#thepathoflife);
string currentLine;
string searchString = "50.2 :";
bool foundText = false;
string searchStringab = "= 1";
bool foundTextab = false;
do
{
currentLine = st.ReadLine();
if (currentLine != null)
{
foundText = currentLine.Contains(searchString);
foundTextab = currentLine.Contains(searchStringab);
}
}
while (currentLine != null && !foundText || currentLine != null && !foundTextab);
if (foundText||foundTextab)
{
plasma = true; //do something
}

You opened two StreamReader on same file without closing first one:
StreamReader s = new StreamReader(#thepathoflife);
StreamReader st = new StreamReader(#thepathoflife);
and finally you didn't dispose any of them, use using to prevent such a mistakes:
using(StreamReader st = new StreamReader(#thepathoflife))
{
do stuff;
}

I think you can simplify things with:
foreach (var currentLine in File.ReadLines(thepathoflife))
{
foundText = currentLine.Contains(searchString);
foundTextab = currentLine.Contains(searchStringab);
if (foundText || foundTextab)
break;
}

surround all your code with a try catch block, then spit out the exception to the console (I am assuming you are using a console project)
try{, your code...
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Related

can not read attached files where i have have embedded file with ImapX

I have code that read email attachments, embedded and not embedded, but if have both in the same email, only read embedded attachment.
Any help will be appreciated..
My code.
{
string strFiltro = String.Format("SINCE {0}-{1}-{2} BEFORE {3}-{4}-{5} {6} ",
strDiaInicial,
strMesInicial,
strAnioInicial,
strDiaFinal,
strMesFinal,
strAnioFinal,
(this.MensajesNoLeidos == true ? "UNSEEN" : "ALL"));
IEnumerable<Message> mensajesFiltrados = folder.Search(strFiltro/*MessageFetchMode.Full,10*/);
mensajesFiltrados = mensajesFiltrados.Where(x => x.Attachments.Count() > 0 || x.EmbeddedResources.Count() > 0);
foreach (Message message in mensajesFiltrados)
{
if (message.Attachments.Count() > 0)
{
ArchivosAdjuntosFiltrados = message.Attachments.Where(x => x.ContentType.Name.ToLower().Contains(".pdf")) x.ContentType.Name.ToLower().Contains(".xml"));
resultado[0] = resultado[0] + ArchivosAdjuntosFiltrados.Count();
}
else
{
if (message.EmbeddedResources.Count() > 0)
{
//never get Embedded pdf or xml files ArchivosAdjuntosFiltrados = message.EmbeddedResources.Where(x => x.ContentType.Name.Contains(".pdf") || x.ContentType.Name.Contains(".xml"));
}
}
}
foreach (Attachment atachemtn in ArchivosAdjuntosFiltrados)
{
strNombreArchivo = atachemtn.FileName;
String attachData = atachemtn.GetTextData().Replace('-', '+'); attachData = attachData.Replace('_', '/');
if (intPosicion > 0)
{
attachData = attachData.Substring(0, attachData.Length - 31);
}
if (strNombreArchivo != String.Empty)
{
if (File.Exists(Path.Combine(strRutaDescargas, atachemtn.FileName)) == true)
{
if (pBlnSobreescribirArchivos == true)
{
byte[] data = Convert.FromBase64String(attachData);
File.WriteAllBytes(Path.Combine(this.strRutaDescargas, strNombreArchivo), data);
}
}
}
}
}
}

Exception thrown filtering IEnumerable collection using Regex on ASP.NET Web API C#

I'm working with a POST method in my ASP.NET MVC + Web API project. The problem is that I want to filter the results of an IEnumerable collection applying a Regex to clear out non alphanumeric characters.
Whenever the program gets to that line it throws an "ArgumentNullException" which also says "Value cannot be null. Parameter name: input".
I understand that it has something to be with the parameters that a method is receiving so I suspect that there might be a problem with the Regex.Replace method so I tried to debug it with no success.
At the beginning I thought that I was using the repository to fill the IEnumerable collection in the wrong way because it's an static attribute declared outside the transaction scope. So then I created another repository instance inside the scope but that didn't resolve the issue.
Any help would be appreciated. Thank you.
Here's my the method with the problematic line (indicated with -------->):
[HttpPost]
public object Post(string token, [FromBody]ExternoApi externo)
{
var ValidateToken = TokensRepository.Validate(token);
if (ValidateToken == null)
throw new NotImplementedException(string.Format("El token ID = \"{0}\" no se encuentra habilitado o aun no se realizo el emparejamiento.", token));
if (externo == null)
throw new ParameterNullException(string.Format("Debe informar un externo."));
Externo externoNew;
var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions()
{
IsolationLevel = IsolationLevel.ReadCommitted
}
);
using (scope)
{
IExternoRepository _repository = new ExternoRepository();
try
{
externoNew = new Externo()
{
dsNombre = externo.dsNombre,
dsApellido = externo.dsApellido,
dsDocumento = externo.dsDocumento,
IdCliente = externo.IdCliente,
dsPatente = externo.dsPatente,
dtCreado = DateTime.Now,
dtModificado = DateTime.Now
};
Regex rgx = new Regex("[^a-zA-Z0-9]");
string pattern = "[^a-zA-Z0-9]";
var _externos = _repository.GetAll();
//var _ExternoExistente = _externos.Where(x => rgx.Replace(x.dsDocumento, "") == rgx.Replace(externoNew.dsDocumento, "")
// && rgx.Replace(x.dsPatente, "") == rgx.Replace(externoNew.dsPatente, "")
// && rgx.Replace(x.IdCliente, "") == rgx.Replace(externoNew.IdCliente, "")).OrderBy(x => x.IdExterno).FirstOrDefault();
This line throws exception --------> var _ExternoExistente = _externos.Where(x => Regex.Replace(x.dsDocumento, pattern, "") == Regex.Replace(externoNew.dsDocumento, pattern, "")
&& Regex.Replace(x.dsPatente, pattern, "") == Regex.Replace(externoNew.dsPatente, pattern, "")
&& Regex.Replace(x.IdCliente, pattern, "") == Regex.Replace(externoNew.IdCliente, pattern, "")).OrderBy(x => x.IdExterno).FirstOrDefault();
if (_ExternoExistente == null)
{
externoNew = _repository.Add(externoNew);
}
else {
externoNew = _ExternoExistente;
}
if (!string.IsNullOrEmpty(externo.binaryImage))
{
var filename = string.Format("E{0}.jpg", externo.IdExterno);
string uploadFolder = WebConfigurationManager.AppSettings["UploadFolder"] != null ? WebConfigurationManager.AppSettings["UploadFolder"] : "upload";
string path = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, uploadFolder);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var imageExterno = ImageEngine.StringToImage(externo.binaryImage);
imageExterno.Save(Path.Combine(path, filename));
externoNew.dsPath = string.Concat("~/", uploadFolder, "/", filename);
_repository.Update(externoNew);
}
var externoDB = _repository.Get(externoNew.IdExterno);
string strPath = HostingEnvironment.ApplicationPhysicalPath;
scope.Complete();
return new ExternoApi()
{
IdExterno = externoDB.IdExterno,
dsNombre = externoDB.dsNombre,
dsApellido = externoDB.dsApellido,
dsDocumento = externoDB.dsDocumento,
IdCliente = externoDB.IdCliente,
binaryImage = !string.IsNullOrEmpty(externoDB.dsPath) ? ImageEngine.ImageToString(string.Concat(strPath, externoDB.dsPath.Replace("~/", "").Replace("/", "\\"))) : "",
dsPatente = externoDB.dsPatente,
};
}
catch (Exception ex)
{
scope.Dispose();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
IApiLogRepository _repoLog = new ApiLogRepository();
var log = new ApiLog();
log.IdDispositivo = ValidateToken.IdDispositivo;
log.dsLog = string.Concat("Dispositivo: ", ValidateToken.IdDispositivo, "\n", ex.Message, "\n || \n", (ex.InnerException != null ? ex.InnerException.Message : ""), (ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ""));
log.dsRequest = serializer.Serialize(externo);
_repoLog.Add(log);
throw new DataRestrictDBException(string.Concat(ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : (ex.InnerException != null ? ex.InnerException.Message : ex.Message), "Externo: ", externo));
}
}
}
either externo.dsDocumento or x.dsDocumento must be null
could do something like:
_externos.Where(x => x.dsDocumento != null && externoNew.dsDocumento != null && Regex.Replace(x.dsDocumento, pattern, "") == Regex.Replace(externoNew.dsDocumento, pattern, "")

Entity attaching to context and unable to remove it

I am creating a context in a method inside my entity to check something but I am not tracking anything with it but when I try to save in the calling code context it throws an exception.
This is the calling code in the main context where I want to save:
var espToProcess = db.RootDomainEmailSeriesProgresses;
foreach (var esp in espToProcess)
{
bool carryOn = esp.MoveNext();
db.SaveChanges(); //Exception
if (!carryOn) continue;
//--> rest of my code
}
This is the methods inside the RootDomainEmailSeriesProgress class.
public bool MoveNext()
{
if (this.CompletedTargets == null) this.CompletedTargets = new List<EmailAddress>();
if (this.CurrentTarget != null)
{
this.CompletedTargets.Add(this.CurrentTarget);
this.CurrentTarget = null;
}
this.CurrentProgress = "";
if (this.RootDomain.ContactFilter != RootDomain.ContactFilterType.None)
{
this.Status = EmailSeriesStatus.Aborted;
return false;
}
var allTargets = RootDomainEmailManager.SortDomainsEmailsByDesirability(this.RootDomain.ID);
var toDo = allTargets.Except(this.CompletedTargets);
if (toDo.Count() < 1)
{
this.Status = EmailSeriesStatus.Completed;
return false;
}
List<string> targetEmailList = allTargets.Select(e => e.Email).ToList();
List<EmailFilter> emailFilters = this.GetFilters(allTargets);
if (emailFilters.Any(x => x.Filter == EmailFilterType.Unsubscribe || x.Filter == EmailFilterType.Responded || x.Filter == EmailFilterType.ManualContactOnly))
{
this.Status = EmailSeriesStatus.Aborted;
if (this.RootDomain.ContactFilter == 0) this.RootDomain.ContactFilter = RootDomain.ContactFilterType.HasAssociatedEmailFilter;
return false;
}
this.CurrentTarget = toDo.First();
return true;
}
private List<EmailFilter> GetFilters(List<EmailAddress> allTargets)
{
using (var db = new PlaceDBContext())
{
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var targetEmailList = allTargets.Select(e => e.Email).ToList();
return db.EmailFilters.AsNoTracking().Where(x => targetEmailList.Contains(x.Email)).ToList();
}
}
It throws out this exception:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
I can't see why esp gets attached to the other context. I only need that context briefly, how do I kill it off so it stops causing me issues?
that because there are difference DbContext instances in foreach loop and GetFilters method
You can retry this code
var espToProcess = db.RootDomainEmailSeriesProgresses;
foreach (var esp in espToProcess)
{
bool carryOn = esp.MoveNext(db);
db.SaveChanges(); //Exception
if (!carryOn) continue;
//--> rest of my code
}
public bool MoveNext(DbContext db)
{
if (this.CompletedTargets == null) this.CompletedTargets = new
List<EmailAddress>();
if (this.CurrentTarget != null)
{
this.CompletedTargets.Add(this.CurrentTarget);
this.CurrentTarget = null;
}
this.CurrentProgress = "";
if (this.RootDomain.ContactFilter != RootDomain.ContactFilterType.None)
{
this.Status = EmailSeriesStatus.Aborted;
return false;
}
var allTargets =
RootDomainEmailManager.SortDomainsEmailsByDesirability(this.RootDomain.ID);
var toDo = allTargets.Except(this.CompletedTargets);
if (toDo.Count() < 1)
{
this.Status = EmailSeriesStatus.Completed;
return false;
}
List<string> targetEmailList = allTargets.Select(e => e.Email).ToList();
List<EmailFilter> emailFilters = this.GetFilters(allTargets, db);
if (emailFilters.Any(x => x.Filter == EmailFilterType.Unsubscribe ||
x.Filter == EmailFilterType.Responded || x.Filter ==
EmailFilterType.ManualContactOnly))
{
this.Status = EmailSeriesStatus.Aborted;
if (this.RootDomain.ContactFilter == 0)
this.RootDomain.ContactFilter =
RootDomain.ContactFilterType.HasAssociatedEmailFilter;
return false;
}
this.CurrentTarget = toDo.First();
return true;
}
private List<EmailFilter> GetFilters(List<EmailAddress> allTargets, DbContext db)
{
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var targetEmailList = allTargets.Select(e => e.Email).ToList();
return db.EmailFilters.AsNoTracking().Where(x =>
targetEmailList.Contains(x.Email)).ToList();
}

Paths from a directory tree array

I am using Directory.GetFiles to find files that will be copied. I need to find the paths of the files so I can use copy, but I have no idea how to find the path.
It iterates through the files fine, but I can't copy or move them because I need the file's source path.
This is what I have:
string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
System.Console.WriteLine("Files Found");
// Display all the files.
foreach (string file in files)
{
string extension = Path.GetExtension(file);
string thenameofdoom = Path.GetFileNameWithoutExtension(file);
string filename = Path.GetFileName(file);
bool b = false;
string newlocation = (#"\\TEST12CVG\Public\Posts\Temporaryjunk\");
if (extension == ".pst" ||
extension == ".tec" ||
extension == ".pas" ||
extension == ".snc" ||
extension == ".cst")
{
b = true;
}
if (thenameofdoom == "Plasma" ||
thenameofdoom == "Oxygas" ||
thenameofdoom == "plasma" ||
thenameofdoom == "oxygas" ||
thenameofdoom == "Oxyfuel" ||
thenameofdoom == "oxyfuel")
{
b = false;
}
if (b == true)
{
File.Copy(file, newlocation + thenameofdoom);
System.Console.WriteLine("Success: " + filename);
b = false;
}
}
Path.GetFullPath works, but also consider using FileInfo as it comes with many file helper methods.
I would use a method similar to this (could use a lot more error handling (try catches...) but it's a good start
EDIT I noticed that you are filtering out the extensions, but requiring them, update to code allows for that
class BackupOptions
{
public IEnumerable<string> ExtensionsToAllow { get; set; }
public IEnumerable<string> ExtensionsToIgnore { get; set; }
public IEnumerable<string> NamesToIgnore { get; set; }
public bool CaseInsensitive { get; set; }
public BackupOptions()
{
ExtensionsToAllow = new string[] { };
ExtensionsToIgnore = new string[] { };
NamesToIgnore = new string[] { };
}
}
static void Backup(string sourcePath, string destinationPath, BackupOptions options = null)
{
if (options == null)
optionns = new BackupOptions();
string[] files = Directory.GetFiles(sourcePath, ".", SearchOption.AllDirectories);
StringComparison comp = options.CaseInsensitive ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
foreach (var file in files)
{
FileInfo info = new FileInfo(file);
if (options.ExtensionsToAllow.Count() > 0 &&
!options.ExtensionsToAllow.Any(allow => info.Extension.Equals(allow, comp)))
continue;
if (options.ExtensionsToIgnore.Any(ignore => info.Extension.Equals(ignore, comp)))
continue;
if (options.NamesToIgnore.Any(ignore => info.Name.Equals(ignore, comp)))
continue;
try
{
File.Copy(info.FullName, destinationPath + "\\" + info.Name);
}
catch (Exception ex)
{
// report/handle error
}
}
}
With a call like:
var options = new BackupOptions
{
ExtensionsToAllow = new string[] { ".pst", ".tec", ".pas", ".snc", ".cst" },
NamesToIgnore = new string[] { "Plasma", "Oxygas", "Oxyfuel" },
CaseInsensitive = true
};
Backup("D:\\temp", "D:\\backup", options);

Why do I get the error DTD is not allowed on this document?

Heres the code:
// iBEC/iBSS -> SHSH Generator Tool
using System;
using System.Collections.Generic;
using System.Text;
namespace SHSH_Tool
{
public enum VersionMode
{
V3_0 = 0,
V3_0_1
}
class Program
{
static void PrintUsage()
{
Console.WriteLine("iBEC/iBSS to SHSH Tool");
Console.WriteLine("Usage: SHSH_Tool -tmpfiles X:\\Path\\To\\Tmp\\Directories -output X:\\Path\\To\\00.SHSH");
Console.WriteLine("Note: If you have files for 3.0.1, use the -301 switch.");
}
static void Main(string[] args)
{
VersionMode toolMode = VersionMode.V3_0;
string firmwareRootPath = null; // #"E:\Work\Dev\iPhone\iBEC_iBSS_Grabber";
string outputFilename = null; // #"E:\Work\Dev\svn\iPhone\SHSH_Tool\3.0.shsh";
string lastArg = null;
foreach (string arg in args)
{
if (arg == "-301")
{
toolMode = VersionMode.V3_0_1;
}
if (lastArg == "-tmpfiles")
{
firmwareRootPath = arg;
}
else if (lastArg == "-output")
{
outputFilename = arg;
}
lastArg = arg.ToLower();
}
if (firmwareRootPath == null || outputFilename == null)
{
PrintUsage();
return;
}
if (!System.IO.Directory.Exists(firmwareRootPath))
{
Console.WriteLine("Unable to open TMP directories path.");
PrintUsage();
return;
}
string restoreRamDiskToIgnore = "018-5304-002.dmg";
string manifestFilename = "BuildManifest.30.xml";
string shshTemplateFilename = "3.0.shsh.template";
if (toolMode == VersionMode.V3_0_1)
{
restoreRamDiskToIgnore = "018-5804-001.dmg";
manifestFilename = "BuildManifest.30.xml";
shshTemplateFilename = "3.0.1.shsh.template";
Console.WriteLine("Operating in 3.0.1 Mode");
}
else
{
Console.WriteLine("Operating in 3.0 Mode");
}
try
{
Console.WriteLine("Reading IPSW Manifest File...");
//System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(Util.ReadEmbeddedResource(manifestFilename));
BuildManifestReader manifestReader = new BuildManifestReader(manifestFilename);
Console.WriteLine("Found Manifest Files:");
foreach (BuildManifestItem manifestItem in manifestReader.ManifestItems.Values)
{
Console.WriteLine(" - Key: " + manifestItem.Key + " [Digest: " + manifestItem.PartialDigest + "]");
}
Console.WriteLine("Processing TMP files...");
string strECID = null;
string[] subdirs = System.IO.Directory.GetDirectories(firmwareRootPath);
foreach (string subdir in subdirs)
{
if (!(subdir.Contains("Per") && subdir.EndsWith(".tmp")))
continue;
Console.WriteLine(" - Entering directory: " + subdir);
ProcessSubdirectory(subdir, manifestReader, ref strECID);
}
// Process current directory
ProcessSubdirectory(firmwareRootPath, manifestReader, ref strECID);
bool blobsOK = true;
Console.WriteLine("Verifying BLOB Data...");
foreach (BuildManifestItem manifestItem in manifestReader.ManifestItems.Values)
{
if (manifestItem.BlobData == null && manifestItem.Path != restoreRamDiskToIgnore)
{
if (manifestItem.Found)
{
Console.WriteLine(" - ERROR: Invalid signed data for " + manifestItem.Path);
}
else
{
Console.WriteLine(" - ERROR: File not found for " + manifestItem.Path);
}
blobsOK = false;
}
}
if (blobsOK)
{
Console.WriteLine("Creating custom SHSH file...");
System.IO.StreamReader shshTemplateFileHdl = new System.IO.StreamReader(Util.ReadEmbeddedResource(shshTemplateFilename));
string shshTemplateFile = shshTemplateFileHdl.ReadToEnd();
foreach (BuildManifestItem manifestItem in manifestReader.ManifestItems.Values)
{
shshTemplateFile = shshTemplateFile.Replace("[BLOB-" + manifestItem.Path + "]", manifestItem.BlobData);
shshTemplateFile = shshTemplateFile.Replace("[DIGEST-" + manifestItem.Path + "]", manifestItem.PartialDigest);
}
System.IO.StreamWriter shshFileWriter = new System.IO.StreamWriter(outputFilename);
shshFileWriter.Write(shshTemplateFile);
shshFileWriter.Close();
if (toolMode == VersionMode.V3_0)
{
Console.WriteLine("Success! 3.0 SHSH File stored at " + outputFilename);
}
else if (toolMode == VersionMode.V3_0_1)
{
Console.WriteLine("Success! 3.0.1 SHSH File stored at " + outputFilename);
}
}
else
{
Console.WriteLine("There were errors while trying to create SHSH file.");
}
}
catch (System.Exception e)
{
Console.WriteLine("There were errors while trying to create SHSH file.");
Console.WriteLine("Diagnostic: " + e.Message + " " + e.StackTrace);
}
finally
{
Console.WriteLine("Complete.");
}
}
static bool ProcessSubdirectory(string subdir, BuildManifestReader manifestReader, ref string strECID)
{
foreach (BuildManifestItem manifestItem in manifestReader.ManifestItems.Values)
{
if (manifestItem.BlobData != null)
continue;
string path = manifestItem.Path.Replace("/", "\\");
string searchPath = subdir + "\\" + path;
if (System.IO.File.Exists(searchPath))
{
Console.WriteLine(" - " + manifestItem.Path);
if (!ProcessFile(searchPath, manifestItem, ref strECID))
return false;
}
else
{
string fileOnly = manifestItem.Path.Substring(manifestItem.Path.LastIndexOf("/") + 1);
searchPath = subdir + "\\" + fileOnly;
if (System.IO.File.Exists(searchPath))
{
Console.WriteLine(" - [Alternate Path] " + fileOnly);
if (!ProcessFile(searchPath, manifestItem, ref strECID))
return false;
}
}
}
return true;
}
static bool ProcessFile(string filename, BuildManifestItem manifestItem, ref string strECID)
{
manifestItem.Found = true;
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(System.IO.File.OpenRead(filename));
binaryReader.BaseStream.Seek(-2125, System.IO.SeekOrigin.End);
byte[] magic = binaryReader.ReadBytes(4);
StringBuilder sb = new StringBuilder(100);
foreach (byte b in magic)
{
sb.Append((char)b);
}
string magicstr = sb.ToString();
if (magicstr != "DICE")
{
Console.WriteLine(" - ERROR: Magic string not found! (DICE)");
return false;
}
// chew bytes to get to the ecid
binaryReader.ReadBytes(8);
// get the ECID
byte[] ecid = binaryReader.ReadBytes(8);
StringBuilder sbECID = new StringBuilder(20);
for (int idxECID = ecid.Length - 1; idxECID >= 0; idxECID--)
{
sbECID.Append(ecid[idxECID].ToString("x2"));
}
string strThisECID = sbECID.ToString();
if (strECID != null && strThisECID != strECID)
{
Console.WriteLine(" - ERROR: ECID Mismatch (Had: " + strECID + " Found: " + strThisECID + ")");
return false;
}
else if (strECID == null)
{
strECID = strThisECID;
Console.WriteLine("Detected ECID: " + strECID);
}
binaryReader.BaseStream.Seek(-2125, System.IO.SeekOrigin.End);
byte[] signedBytes = binaryReader.ReadBytes(2125);
string signedBytesEncoded = System.Convert.ToBase64String(signedBytes);
StringBuilder formattedBlobDataBuilder = new StringBuilder(3000);
for (int idxChar = 0, colCount = 0; idxChar < signedBytesEncoded.Length; idxChar++, colCount++)
{
formattedBlobDataBuilder.Append(signedBytesEncoded[idxChar]);
if (colCount + 1 == 60)
{
formattedBlobDataBuilder.Append("\n\t\t");
colCount = -1;
}
}
string formattedBlobData = formattedBlobDataBuilder.ToString();
manifestItem.BlobData = formattedBlobData;
return true;
}
}
public class BuildManifestItem
{
string _key;
public string Key
{
get { return _key; }
set { _key = value; }
}
string _path;
public string Path
{
get { return _path; }
set { _path = value; }
}
string _partialDigest;
public string PartialDigest
{
get { return _partialDigest; }
set { _partialDigest = value; }
}
string _blobData;
public string BlobData
{
get { return _blobData; }
set { _blobData = value; }
}
bool _found;
public bool Found
{
get { return _found; }
set { _found = value; }
}
}
public class BuildManifestReader
{
private Dictionary<string, BuildManifestItem> _manifestItems;
public Dictionary<string, BuildManifestItem> ManifestItems
{
get { return _manifestItems; }
set { _manifestItems = value; }
}
public BuildManifestReader(string manifestFilename)
{
_manifestItems = new Dictionary<string, BuildManifestItem>();
System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(Util.ReadEmbeddedResource(manifestFilename));
string elementName = null;
bool foundManifest = false;
BuildManifestItem manifestItem = null;
while (xmlReader.Read())
{
if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
{
elementName = xmlReader.Name;
}
else if (elementName == "key" && xmlReader.Depth == 5 && xmlReader.NodeType == System.Xml.XmlNodeType.Text)
{
if (xmlReader.Value == "ApBoardID")
{
foundManifest = false;
}
else if (xmlReader.Value == "Manifest")
{
foundManifest = true;
}
}
else if (elementName == "key" && xmlReader.Depth == 6 && xmlReader.NodeType == System.Xml.XmlNodeType.Text)
{
if (foundManifest)
{
manifestItem = new BuildManifestItem();
manifestItem.Key = xmlReader.Value;
}
}
else if (elementName == "key" && xmlReader.NodeType == System.Xml.XmlNodeType.Text && xmlReader.Value == "Path")
{
string path = GetPath(xmlReader);
manifestItem.Path = path;
}
else if (elementName == "key" && xmlReader.NodeType == System.Xml.XmlNodeType.Text && xmlReader.Value == "PartialDigest")
{
string digest = GetPartialDigest(xmlReader);
digest = digest.Replace("\n", "");
digest = digest.Replace("\t", "");
manifestItem.PartialDigest = digest;
if (!_manifestItems.ContainsKey(manifestItem.Key + "-" + manifestItem.Path))
{
_manifestItems.Add(manifestItem.Key + "-" + manifestItem.Path, manifestItem);
}
manifestItem = null;
}
}
}
string GetPath(System.Xml.XmlReader xmlReader)
{
string elementName = null;
while (xmlReader.Read())
{
if (xmlReader.NodeType != System.Xml.XmlNodeType.Element && xmlReader.NodeType != System.Xml.XmlNodeType.Text)
continue;
if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
{
elementName = xmlReader.Name;
}
else if (elementName == "string" && xmlReader.NodeType == System.Xml.XmlNodeType.Text)
{
return xmlReader.Value;
}
else
{
return null;
}
}
return null;
}
string GetPartialDigest(System.Xml.XmlReader xmlReader)
{
string elementName = null;
while (xmlReader.Read())
{
if (xmlReader.NodeType != System.Xml.XmlNodeType.Element && xmlReader.NodeType != System.Xml.XmlNodeType.Text)
continue;
if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
{
elementName = xmlReader.Name;
}
else if (elementName == "data" && xmlReader.NodeType == System.Xml.XmlNodeType.Text)
{
return xmlReader.Value;
}
else
{
return null;
}
}
return null;
}
}
class Util
{
public static System.IO.Stream ReadEmbeddedResource(string resourceName)
{
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();
string [] resources = curAssembly.GetManifestResourceNames();
foreach (string resource in resources)
{
if (resource.EndsWith(resourceName))
{
return curAssembly.GetManifestResourceStream(resource);
}
}
return null;
}
}
}
Diagnostic: For security reasons DTD is prohibited in this XML document. To enab
le DTD processing set the ProhibitDtd property on XmlReaderSettings to false and
pass the settings into XmlReader.Create method. at System.Xml.XmlTextReaderI
mpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at SHSH_Tool.BuildManifestReader..ctor(String manifestFilename) in C:\Users\A
dministrator\Desktop\shsh\Program.cs:line 323
at SHSH_Tool.Program.Main(String[] args) in C:\Users\Administrator\Desktop\sh
sh\Program.cs:line 87
Complete.
I don't think you gave us the actual XML document that you are reading. It probably has a "DOCTYPE" at the top which specifies a .DTD file.
Either edit the document to not have the DOCTYPE, or programatically ignore the DOCTYPE. Here is how you can do that: Ignore DOCTYPE .dtd, but .dtd file must still exist

Categories