C# Equivalent to ifstream/ofstream in C++ - c++

I know this has probably been asked before, but I can't find it here on SO anywhere, and I can't get a clear answer on anything I look up on Google either.
I need to know the C# equivalent to C++'s ifstream/ofstream.
For instance, if I had the following C++ code:
ifstream input("myFile.txt");
ofstream output;
output.open("out.txt");
What would be the C# equivalent?
I found a site that said (for the in file portion, anyway) that the equivalent was this:
using System.IO;
FileStream fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read);
I tried putting this in:
FileStream fs = new FileStream(input, FileAccess.Read);
I don't have the "FileMode" in mine because VS didn't recognize it. And "input" is a string in the parameters that holds the string value of the input file name (for example - "myFile.txt").
I know I've got to be missing something silly and minor, but I can't figure out what that is. Any help on this would be much appreciated!
I'm developing in VS2010, C#-4.0, WPF API.

FileStream is what you want. Take a look at the MSDN example on stream composition here.

I feel that StreamReader/StreamWriter offer similar functionality to c++'s ifstream/ofstream. FileStream is for dealing with byte[] data, whereas StreamReader/StreamWriter deal with text.
var writer = new StreamWriter(File.OpenWrite("myFile.txt");
writer.WriteLine("testing");
writer.Close();
var reader = new StreamReader(File.OpenRead("myFile.txt");
while ( !reader.EndOfStream )
{
var line = reader.ReadLine();
}

Related

VSIX how to get current snapshot document name?

I have been trying to to create an extension that highlights specific line numbers for me in Visual Studio in the margins.
I manged to get my marking in the margins using predefined line number but for it to work properly I need to know what the current document FullName is (Path and filename)
After much googling I figured out how to do it with the sample code (which is not ideal)
DTE2 dte = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.15.0");
var activeDocument = dte.ActiveDocument;
var docName = activeDocument.Name;
var docFullName = activeDocument.FullName;
Now I know the problems here
is that is for specific version bases on the text
there is no way to select which instance (when running more than one VS)
It seems to be very slow
I have a feeling I should be doing this with MEF Attributes but the MS docs examples are so simple that they do not work for me. I scanned a few SO questions too and I just cannot get them to work. They mostly talk about Services.. which I do not have and have no idea how to get.
The rest of my code uses SnapshotSpans as in the example Extension of Todo_Classification examples which is great if you do NOT need to know the file name.
I have never done any extensions development. Please can somebody help me do this correctly.
You can use following code to get a file from a snapshot without any dependencies.
public string GetDocumentPath(Microsoft.VisualStudio.Text.ITextSnapshot ts)
{
Microsoft.VisualStudio.Text.ITextDocument textDoc;
bool rc = ts.TextBuffer.Properties.TryGetProperty(
typeof(Microsoft.VisualStudio.Text.ITextDocument), out textDoc);
if (rc && textDoc != null)
return textDoc.FilePath;
return null;
}
If you don't mind adding Microsoft.CodeAnalysis.EditorFeatures.Text to your project it will provide you with an extension method Document GetOpenDocumentInCurrentContextWithChanges() on the Microsoft.VisualStudio.Text.Snapshot class. (Plus many other Rosyln based helpers)
using Microsoft.CodeAnalysis.Text;
Document doc = span.Snapshot.GetOpenDocumentInCurrentContextWithChanges();

How to get all collection names in MongoDb using C++

There is a great MongoDb C++ Driver. The only thing that makes it hard for newbies like me to use it - is the lack of teeny-weeny examples. For instance, I know there is a method called getCollectionNames, but I'm not sure how to use it. In Python I would do it like this:
db = MongoClient(host, port)[db_name]
colls = db.collection_names()
and I'm done. But I don't feel so comfortable with C++ and can not figure out myself how to convert raw function declarations in documentation to some working code.
So, this is what I've done by now and see that it works:
ConnectionString cs = ConnectionString::parse(uri, errmsg);
DBClientBase * conn(cs.connect(errmsg));
Now I want to make one step further and get all collection names. Please, give some advice.
EDIT
Well, I found a method somewhere in dbclientinterface.h called getCollectionNames. It is defined like so:
std::list<std::string> getCollectionNames( const std::string& db,
const BSON& filter = BSONObj())
But I find this sole declaration without any informative hints completely useless. It is just a sum of letters and no more.
EDIT
I found a solution and I will post it below.
This is the solution:
std::string uri = "mongodb://127.0.0.1:27017/mydb";
std::string errmsg;
ConnectionString cs = ConnectionString::parse(uri, errmsg);
DBClientBase * conn(cs.connect(errmsg));
std::list<std::string> colls = conn->getCollectionNames("mydb");
for(std::list<std::string>::iterator it = colls.begin();it != colls.end();++it){
do_something(*it);
}

WebClient in C++

I'm writing a program that needs to be able to read in HTML source code into a string.
I've read about WebClient for C# but I need to write my program in C++ and I'm not sure how to do that (I've never used WebClient before).
Can anyone give me a simple C++ example program showing me how to get HTML source code into a string using WebClient? (or any better method)
Thanks.
See this page, A Fully Featured Windows HTTP Wrapper in C++:
http://www.codeproject.com/Articles/66625/A-Fully-Featured-Windows-HTTP-Wrapper-in-C
Sample code from that page, looks like what you want:
void ProgressTest(void)
{
// Set URL and call back function.
WinHttpClient client(L"http://www.codeproject.com/", ProgressProc);
client.SendHttpRequest();
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();
}
I don't know what webclient for c# is. To read a file into a string-:
std::ifstream ifs("webpage.html");
std::string str;
str.assign((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));

How do I use the registry?

In the simplest possible terms (I'm an occasional programmer who lacks up-to-date detailed programming knowledge) can someone explain the simplest way to make use of the registry in codegear C++ (2007).
I have a line of code in an old (OLD!) program I wrote which is causing a significant delay in startup...
DLB->Directory=pIniFile->ReadString("Options","Last Directory","no key!");
The code is making use of an ini file. I would like to be able to use the registry instead (to write variables such as the last directory the application was using)
But the specifics are not important. I'd just like a generic how-to about using the registry that's specific to codegear c++ builder.
I've googled this, but as usual with this type of thing I get lots of pages about c++ builder and a few pages about the windows registry, but no pages that explain how to use one with the other.
Use the TRegistry class... (include registry.hpp)
//Untested, but something like...
TRegistry *reg = new TRegistry;
reg->RootKey = HKEY_CURRENT_USER; // Or whatever root you want to use
reg->OpenKey("theKey",true);
reg->ReadString("theParam",defaultValue);
reg->CloseKey();
Note, opening and reading a ini file is usually pretty fast, so maybe you need to test your assumption that the reading of the ini is actually your problem, I don't think that just grabbing your directory name from the registry instead is going to fix your problem.
Include the Registry.hpp file:
#include <Registry.hpp>
Then in any function you have, you can write the following to read the value:
String __fastcall ReadRegistryString(const String &key, const String &name,
const String &def)
{
TRegistry *reg = new TRegistry();
String result;
try {
reg->RootKey = HKEY_CURRENT_USER;
if (reg->OpenKeyReadOnly(key)) {
result = reg->ReadString(name, def);
reg->CloseKey();
}
}
__finally {
delete reg;
}
return result;
}
So reading the value should be as easy as:
ShowMessage(ReadRegistryString("Options", "Last Directory", "none"));
You can use the following to write the value:
void __fastcall WriteRegistryString(const String &key, const String &name,
const String &value)
{
TRegistry *reg = new TRegistry();
try {
reg->RootKey = HKEY_CURRENT_USER;
if (reg->OpenKey(key, true)) {
reg->WriteString(name, value);
reg->CloseKey();
}
}
__finally {
delete reg;
}
}
Should be self explaining, remembering the try ... finally is actually really helpful when using the VCL TRegistry class.
Edit
I've heard that .ini files are stored in the registry in Windows, so if you want the speed advantage of ini files you should call them something else - like .cfg
This is something I've heard from an although reliable source, I haven't tested it myself.
Tim is right but an even simpler class to use is TIniRegFile but it is also more limited in what you can do.
Please see the documentation for the QSettings class from the Qt 4.5 library. It will allow you to load and store your program's configuration settings easily and in a cross-platform manner. The Windows implementation uses the Windows registry for loading and storing your program's configuration data. On other platforms, the platform's preferred, native mechanism for storing configuration data will be used. This is far better than interacting with the Windows registry directly, as you will not be tied to a specific platform.

How to set text in Carbon textfield on OSX?

I'm trying to set the text of a textfield using the Carbon API like this:
ControlID editId = {'EDIT', 3};
ControlRef ctrl;
GetControlByID(GetWindowRef(), &editId, &ctrl);
CFStringRef title = CFSTR("Test");
OSErr er = SetControlData(ctrl, kControlEntireControl, kControlEditTextTextTag, CFStringGetLength(title), title);
CFRelease(title);
I'm using the C++ code template of XCode, so GetWindowRef() is a call to the predefined TWindow class. The OSErr return value gives me noErr, but my textfield only contains garbage.
It doesn't matter if I set the attribute of my textfield to Unicode or not.
Any ideas what is wrong here?
What does the GetControlID(...) return? Is it noErr?
As a ControlRef is also a HIViewRef, you can also use the function:
HIViewSetText to set the text. This is documented to work with functions that accept kControlEditTextCFStringTag.
By the way, the line you wrote:
CFRelease(title);
Will cause problems. One should only release objects that have been made using functions that have Create or Copy in the API name. You'll want to read: "Introduction to Memory Management Programming Guide for Core Foundation" -- search in the Xcode documentation.
Finally this did the trick:
SetControlData(ctrl, kControlEditTextPart, kControlStaticTextCFStringTag, sizeof(title), &title);
Since this seems to be very old API, a better way seems to be:
HIViewSetText(ctrl, title);
Thx to Lyndsey for the hints.