Porting over to C# from VB6, How to Open, Input, Close? - c#

Dim strTestExample As String
Private colTestExample As Collection
If(FileExists(strFullFile) Then
Open strTestExample For Input As #intFILE
Do While Not EOF(intTEST)
Input #intFILE, strFirstName, strLastName, strFavColor, strAge
Set objTestObject = New PracticeExample
With objTestObject
.FirstName = strFirstName
.LastName = strLastName
.FavColor = strFavColor
.Age = strAge
colTestExample.Add objTestObject, .FirstName
End With
Loop
Close #intFILE
End If
After numerous attempts to recreate this in C# its time that I consult the almighty powers. I have tried using FileSystemObject to open and write to the file. I am attempting to port this over to C#. I believe without checking i am working in .NET 4.0.
If you would like some further elaboration, just ask below. The contents are being input to a .txt file.
C# Attempt:
string Path;
string FullFile;
const string FileName = "People.txt";
TextStream TS;
FileSystemObject FSO = new FileSystemObject();
PracticeExample objTestObject = new PracticeExample();
Path = AppDomain.CurrentDomain.BaseDirectory;
File = FileSystem.FreeFile();
FullFile = Path + "\"" + FileName;
if (File.Exists(FullFile) == true)
{
FileSystem.FileOpen(File, strFirstName, strLastName, strFavColor, strAge);
TS = FSO.OpenTextFile(File.ToString(), IOMode.ForWriting, true);
FSO.
objTestObject.FirstName = strFirstName;
objTestObject.LastName = strLastName;
objTestObject.FavColor = strFavColor;
objTestObject.Age = strAge;
HashTableRouteDefinitions.Add(objTestObject,objTestObject.FirstName);
FileSystem.FileClose(File);
}
I have getters and setters on within PracticeExample.(WARNING, unfinished code.)

Related

Avoid apostrophe with regex with event or saving to file

How to avoid writing into the richTextBox of saving into the file for apostrophe " ’ " and " ' "
I also tried replace:
string text = File.ReadAllText(path);
text = text.Replace("’", "").Replace("'", "");
File.WriteAllText(path, text.ToLower());
But If file content is large program hangs with using in events. Also I have this � instead delete time after time.
So would be good to avoid writing of marks with writing or with saving into the file
Seems like I'm doing it wrong:
string toFile = String.Join(" ", richTextBox1.Lines);
var pat1 = #"\s?(’|')\s?";
var out1 = Regex.Replace(toFile, pat1, "");
File.WriteAllText(path, out1.ToLower());
so this way i lost lines if text is pasted and got whole text in one string.
but want get this result, if insert is:
Could’ve
Couldn’t
Didn’t
Doesn’t
I want write it to the file like this:
couldve
couldnt
didnt
doesnt
Try this:
System.Windows.Forms.OpenFileDialog oFile = new System.Windows.Forms.OpenFileDialog();
oFile.InitialDirectory = "c:\\" ;
oFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
oFile.FilterIndex = 2 ;
oFile.RestoreDirectory = true ;
if(oFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string file = oFile.Filename;
string tmp = file + ".tmp";
if (System.IO.File.Exists(tmp))
System.IO.File.Delete(tmp);
using(System.IO.StreamReader sr = new System.IO.StreamReader(file))
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(tmp, false, Encoding.ASCII ))
{
string line = null;
while((line = sr.ReadLine()) != null)
sw.WriteLine(line.Replace("’", "").Replace("'", ""));
}
System.IO.File.Delete(file);
System.IO.File.Move(tmp, file);
}

SSIS 2015 Script task convert text file to UTF8 in C# or VB

I want to convert my resulting txt file into a UTF8 formatted file so I can load it into my Azure SQL DW via Polybase. It is required the source file be in UTF8.
MSDN has an "IO Streaming example" HERE works perfectly for a single job. I am trying to architect an SSIS solution for around 30 tables though. I believe using this method would cause a race condition where the PS script will be locked by 1 SSIS package when another SSIS package needs it.
I am a sql dev, not a .NET dev so please forgive me. How would one convert the above to an SSIS C# Script task assuming I know how to pass parameters into the Script task?
PowerShell Code from MSDN
#Static variables
$ascii = [System.Text.Encoding]::ASCII
$utf16le = [System.Text.Encoding]::Unicode
$utf8 = [System.Text.Encoding]::UTF8
$ansi = [System.Text.Encoding]::Default
$append = $False
#Set source file path and file name
$src = [System.IO.Path]::Combine("<MySrcFolder>","<MyUtf8stage>.txt")
#Set source file encoding (using list above)
$src_enc = $ascii
#Set target file path and file name
$tgt = [System.IO.Path]::Combine("<MyDestFolder>","<MyFinalstage>.txt")
#Set target file encoding (using list above)
$tgt_enc = $utf8
$read = New-Object System.IO.StreamReader($src,$src_enc)
$write = New-Object System.IO.StreamWriter($tgt,$append,$tgt_enc)
while ($read.Peek() -ne -1)
{
$line = $read.ReadLine();
$write.WriteLine($line);
}
$read.Close()
$read.Dispose()
$write.Close()
$write.Dispose()
Update
I found a similar post which I was able to tweak to my needs, I swear I searched high and low before posting. Anyway here is what IS working for me. If you see anyway to improve it please share:
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Your code indicates that your are trying to convert an ASCII file to UTF-8 however that article also states the following:
As UTF-8 uses the same character encoding as ASCII PolyBase will also
support loading data that is ASCII encoded.
So my advice to you is to try the file first with Polybase, check for any conversion issues before you spend any time trying to convert the files.
var mySrcFolder = ""; // something from user variables?
var myUtf8stage = ""; // something from user variables?
var myFinalstage = ""; // something from user variables?
// Static variables
var ascii = System.Text.Encoding.ASCII;
var utf16le = System.Text.Encoding.Unicode;
var utf8 = System.Text.Encoding.UTF8;
var ansi = System.Text.Encoding.Default;
var append = false;
// Set source file path and file name
var src = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myUtf8stage));
// Set source file encoding (using list above)
var src_enc = ascii;
// Set target file path and file name
var tgt = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myFinalstage));
// Set target file encoding (using list above)
var tgt_enc = utf8;
using (var read = new System.IO.StreamReader(src, src_enc))
using (var write = new System.IO.StreamWriter(tgt, append, tgt_enc))
{
while (read.Peek() != -1)
{
var line = read.ReadLine();
write.WriteLine(line);
}
}
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;

Insert HTML Text Into OpenOffice Document (.odt) Files

I am Trying to Insert HTML Text Inside Apache Open Office .odt File
I try Statement with Bold as show Below but it is not Working.
Is There I am missing Something ?
XComponentContext oStrap = uno.util.Bootstrap.bootstrap();
XMultiServiceFactory oServMan = (XMultiServiceFactory)oStrap.getServiceManager();
XComponentLoader oDesk = (XComponentLoader)oServMan.createInstance("com.sun.star.frame.Desktop");
string url = #"private:factory/swriter";
PropertyValue[] propVals = new PropertyValue[0];
XComponent oDoc = oDesk.loadComponentFromURL(url, "_blank", 0, propVals);
string docText = "<b>This will</b> be my first paragraph.\n\r";
docText += "This will be my second paragraph.\n\r";
((XTextDocument)oDoc).getText().setString(docText);
string fileName = #"C:\test.odt";
fileName = "file:///" + fileName.Replace(#"\", "/");
((XStorable)oDoc).storeAsURL(fileName, propVals);
((XComponent)oDoc).dispose();
oDoc = null;
Output:
As answered already in the other question - you have to use character properties to get bold (or otherwise attributed) text

How to automatically load files into SharePoint

We are having someone manually load weekly generated excel spreadsheets into SharePoint. I'm sure there is a way to automate this. I don't know a lot about SharePoint, and maybe it's really as simple as just knowing the folder SharePoint is moving the files to and copying them directly there. Or maybe it requires some programming to get it automatically load new files put in a given directory into SharePoint.
Either way, I would just like someone to point me in the right direction here.
You will need to upload the file using the copy web service in SharePoint. I am not sure what version of SharePoint you are running but I am assuming 2007. Here is a sample project.
public void UploadFile(string destinationFolderPath,
byte[] fileBytes,
string fileName,
bool overwrite,
string sourceFileUrl,
string lastVersionUrl)
{
List<Sharepoint.FieldInformation> fields = new List<Sharepoint.FieldInformation>();
Sharepoint.FieldInformation fieldInfo;
fieldInfo = new Sharepoint.FieldInformation();
fieldInfo.Id = Microsoft.SharePoint.SPBuiltInFieldId.Title;
fieldInfo.Value = "New title";
fieldInfo.DisplayName = "Title";
fieldInfo.Type = YetAnotherMigrationTool.Library.SP2007.Sharepoint.FieldType.Text;
fieldInfo.InternalName = "Title";
fields.Add(fieldInfo);
string[] url;
if (string.IsNullOrEmpty(destinationFolderPath))
url = new string[] { string.Format("{0}/{1}/{2}", _siteUrl, _name, fileName) };
else
url = new string[] { string.Format("{0}/{1}/{2}{3}", _siteUrl, _name, destinationFolderPath, fileName) };
Sharepoint.CopyResult[] result;
Sharepoint.Copy service = new Sharepoint.Copy();
service.Url = _siteUrl + "/_vti_bin/Copy.asmx";
service.Credentials = new NetworkCredential(Settings.Instance.User, Settings.Instance.Password);
service.Timeout = 600000;
uint documentId = service.CopyIntoItems(sourceFileUrl, url, fields.ToArray(), fileBytes, out result);
}
public void SetContentType(List<string> ids, string contentType)
{
ListsService.Lists service = new YetAnotherMigrationTool.Library.SP2007.ListsService.Lists();
service.Url = _siteUrl + "/_vti_bin/Lists.asmx";
service.Credentials = new NetworkCredential(Settings.Instance.User, Settings.Instance.Password);
string strBatch = "";
for (int i = 1; i <= ids.Count; i++)
{
strBatch += #"<Method ID='"+i.ToString()+#"' Cmd='Update'><Field Name='ID'>" + ids[i-1] + "</Field><Field Name='ContentType'>"+contentType+"</Field></Method>";
}
XmlDocument xmlDoc = new XmlDocument();
XmlElement elBatch = xmlDoc.CreateElement("Batch");
elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ListVersion", "10");
elBatch.SetAttribute("ViewName", "");
elBatch.InnerXml = strBatch;
result = service.UpdateListItems(_name, elBatch);
}
You could write a PowerShell script that copies the document into the document library via WebDav:
Assuming you have your document library at http://server/SomeWeb/DocumentLibrary/Folder:
copy-item somesheet.xlsx \\server\SomeWeb\DocumentLibrary\Folder

how to zip the file using ionic library

I have done this one for backup my database
its working fine ....
private void backupDatabase()
{
txtbackup.AppendText("Starting Backup...");
Process sd = null;
const string backupcmd = #"C:\wamp\www\access\mysqldump.exe";
string filepath = #"C:\folder\Access\";
string dbHost = "local";
string dbuser = "root";
string dbName = "access";
string backupName = "Backup.sql";
ProcessStartInfo r1 = new ProcessStartInfo(backupcmd, string.Format("-h {0} -u {1} {2} -r {3}", dbHost, dbuser, dbName, backupName));
r1.CreateNoWindow = true;
r1.WorkingDirectory = filepath;
r1.UseShellExecute = false;
r1.WindowStyle = ProcessWindowStyle.Minimized;
r1.RedirectStandardInput = false;
sd = Process.Start(r1);
sd.WaitForExit();
if (!sd.HasExited)
{
sd.Close();
}
sd.Dispose();
r1 = null;
sd = null;
txtbackup.Clear();
txtbackup.AppendText("Backup is Finished");
}
its working fine ...but i want to store the backup.sql as a zip file in this path
#"C:\folder\Access\";
i have got this library Ionic.Zip.Reduced but i dont know how to zip the file and stored in the given path....
The library is pretty simple to use :
using (var zip = new ZipFile())
{
zip.AddFile("Backup.sql");
zip.Save(#"C:\folder\Access\"Backup.zip");
}
And even their homepage contains samples good enough for your use.
You should use this compression library or this one may be an option?

Categories