I'm trying to make C# program that gets a line on a website and use it.
Unfortunately, I don't know the full line on the site. I only know "steam://joinlobby/730/". Although, what comes after "/730/" is always different.
So i need help getting the full line that comes after it.
What I've got:
public void Main()
{
WebClient web = new WebClient();
// here is the site that i want to download and read text from it.
string result = web.DownloadString("http://steamcommunity.com/id/peppahtank");
if (result.Contains("steam://joinlobby/730/"))
{
//get the part after /730/
}
}
I can tell you that it always ends with "xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxx"
so: steam://joinlobby/730/xxxxxxxxx/xxxxxxxx.
What's to prevent you from just splitting the string on '/730/'?
result.Split(#"/730/")[1]
https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
The easiest method for this particular case would be to take the first part, and then just skip that many characters
const string Prefix = #"steam://joinlobby/730/";
//...
if(result.StartsWith(Prefix))
{
var otherPart = result.SubString(Prefix.Length);
// TODO: Process other part
}
Make sure your result is not null and begins with steam://joinlobby/730/
if(string.IsNullOrWhiteSpaces(result) && result.StartsWith("steam://joinlobby/730/"))
{
string rest = result.SubString(("steam://joinlobby/730/").Length);
}
Related
I'm writing a visual studio extension based on the Concord Samples Hello World project. The goal is to let the user filter out stack frames by setting a list of search strings. If any of the search strings are in a stack frame, it is omitted.
I've got the filter working for a hardcoded list. That needs to be in a non-package-based dll project in order for the debugger to pick it up. And I have a vsix project that references that dll with an OptionPageGrid to accept the list of strings. But I can't for the life of me find a way to connect them.
On the debugger side, my code looks something like this:
DkmStackWalkFrame[] IDkmCallStackFilter.FilterNextFrame(DkmStackContext stackContext, DkmStackWalkFrame input)
{
if (input == null) // null input frame indicates the end of the call stack. This sample does nothing on end-of-stack.
return null;
if (input.InstructionAddress == null) // error case
return new[] { input };
DkmWorkList workList = DkmWorkList.Create(null);
DkmLanguage language = input.Process.EngineSettings.GetLanguage(new DkmCompilerId());
DkmInspectionContext inspection = DkmInspectionContext.Create(stackContext.InspectionSession, input.RuntimeInstance, input.Thread, 1000,
DkmEvaluationFlags.None, DkmFuncEvalFlags.None, 10, language, null);
string frameName = "";
inspection.GetFrameName(workList, input, DkmVariableInfoFlags.None, result => GotFrameName(result, out frameName));
workList.Execute();
CallstackCollapserDataItem dataItem = CallstackCollapserDataItem.GetInstance(stackContext);
bool omitFrame = false;
foreach (string filterString in dataItem.FilterStrings)
{
if (frameName.Contains(filterString))
{
omitFrame = true;
}
}
The CallstackCollapserDataItem is where I theoretically need to retrieve the strings from user settings. But I don't have access to any services/packages in order to e.g. ask for WritableSettingsStore, like in You've Been Haacked's Example. Nor can I get my OptionPageGrid, like in the MSDN Options Example.
The other thing I tried was based on this StackOverflow question. I overrode the LoadSettingsFromStorage function of my OptionPageGrid and attempted to set a static variable on a public class in the dll project. But if that code existed in the LoadSettingsFromStorage function at all, the settings failed to load without even entering the function. Which felt like voodoo to me. Comment out the line that sets the variable, the breakpoint hits normally, the settings load normally. Restore it, and the function isn't even entered.
I'm at a loss. I really just want to pass a string into my Concord extension, and I really don't care how.
Ok, apparently all I needed to do was post the question here for me to figure out the last little pieces. In my CallstackCollapserDataItem : DkmDataItem class, I added the following code:
private CallstackCollapserDataItem()
{
string registryRoot = DkmGlobalSettings.RegistryRoot;
string propertyPath = "vsix\\CallstackCollapserOptionPageGrid";
string fullKey = "HKEY_CURRENT_USER\\" + registryRoot + "\\ApplicationPrivateSettings\\" + propertyPath;
string savedStringSetting = (string)Registry.GetValue(fullKey, "SearchStrings", "");
string semicolonSeparatedStrings = "";
// The setting resembles "1*System String*Foo;Bar"
if (savedStringSetting != null && savedStringSetting.Length > 0 && savedStringSetting.Split('*').Length == 3)
{
semicolonSeparatedStrings = savedStringSetting.Split('*')[2];
}
}
vsix is the assembly in which CallstackCollapserOptionPageGrid is a DialogPage, and SearchStrings is its public property that's saved out of the options menu.
I am trying to convert RTF to plain text in a c# program. I figured out how to do it but it isn't very clean. It uses RichTextBox which I'm not a huge fan of:
using (System.Windows.Forms.RichTextBox rtfBox = new System.Windows.Forms.RichTextBox())
{
rtfBox.Rtf = cTrans.NoteDescription;
tItem.ProcedureShortDescription = rtfBox.Text;
}
I was wondering if there is a better way to go about accomplishing this. Perhaps using RichEditDocumentServer? I could not find a ton of info on it though and was wondering if I could get some help on it. My thought was:
var documentServer = new RichEditDocumentServer();
documentServer.Document.RtfText = cTrans.NoteDescription;
tItem.ProcedureShortDescription = documentServer.Document.Text;
I did some more digging and this works. I figured I'd just post this as I couldn't see it answered anywhere on the site. I'm not sure if that is proper protocol.
I ended up putting it in a helper class so it can be called if needed again:
namespace ABELSoft.Dental.Interface.Helper
{
public class RtfToText
{
public static string convert(string rtfText)
{
string _text;
var documentServer = new RichEditDocumentServer();
documentServer.Document.RtfText = rtfText;
_text = documentServer.Document.Text;
return _text;
}
}
}
This is how I called it:
tItem.ProcedureShortDescription = RtfToText.convert(cTrans.NoteDescription);
I have a security application called Siteminder. It creates unique URLS for every authentication. HTTPS://SITE/idp/**RANDOMURLSTRING**/resumeSAML20/idp/startSSO.ping
How can i capture the Unique URL and have the test continue to login.
A webtest assumes the next URL in the process. It does not support[Or I don't know how] a unique redirect to a random URL. Does anyone know of a way to handle this case?
EDIT:
My Solution -- Replace the SessionID with {{SessionID}} in all the URLS and use this extraction rule
public class ExtractSiteMinderCustomUrl : ExtractionRule
{
public string SiteMinderSessionID { get; private set; }
// The Extract method. The parameter e contains the web performance test context.
//---------------------------------------------------------------------
public override void Extract(object sender, ExtractionEventArgs e)
{
//look for anchor tags with URLS
Regex regex = new Regex("<a\\s+(?:[^>]*?\\s+)?href=\"([^\"]+\\?[^\"]+)\"");
MatchCollection match = regex.Matches(e.Response.BodyString);
if (match.Count > 0)
{
foreach (Match ItemMatch in match)
{
if (ItemMatch.ToString().Contains("/idp/"))
{
//start and ends string from the sitemindersession is in the link on the page
e.WebTest.Context.Add(this.ContextParameterName, GetStringBetween(ItemMatch.ToString(), "/idp/", "/resume"));
e.Success = true;
return;
}
}
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "Not Found in Link : /idp/");
}
else
{
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "No href tags found");
}
}
public static string GetStringBetween(string token, string first, string second)
{
if (!token.Contains(first)) return "";
var afterFirst = token.Split(new[] { first }, StringSplitOptions.None)[1];
if (!afterFirst.Contains(second)) return "";
var result = afterFirst.Split(new[] { second }, StringSplitOptions.None)[0];
return result;
}
}
The simple answer is to have use extraction rule that gets the **RANDOMURLSTRING** then change the URLs in the requests to be, for example, HTTPS://SITE/idp/{{TheRandomString}}/resumeSAML20/idp/startSSO.ping where TheRandomString is the context parameter that holds the extracted value. Note the doubled curly braces ({{ and }}) around the context parameter.
Suppose a value returned by the first redirection needs to be captured but a normal web test would redirect again and so the response is not seen by the extraction rules. In this case need to handle the redirect explicitly. Set the Follow redirects property of the initial request to false then add extraction rule(s) to gather the wanted values. Add a new request after the initial request and use the extracted values in it as necessary. It is possible to extract the entire redirected url and set the Url field to the extracted value.
....
case "DOWNLOAD":
if (File.Exists(commandContent)) {
MessageBox.Show(commandContent);
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
result = HttpUtility.UrlEncode(result);
}
break;
And Unhandled Error exception says "illegal characters" in path. The MessageBox shows a correct path
C:\Users\Me\Myfile.exe
I tried to do the following :
commandContent = commandContent.replace(#"\",#"\\");
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
I also tried the following :
commandContent = #""+commandContent+"";
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
but this doesn't work. And the more strange is that it was working correctly as it is, but once I made some modification in the way I'm inserting commandContent into db (using ajax instead of regular form submit), this problem appears ?
EDIT:
I tried to hard code the path using
commandContent = #"C:\Users\Me\file.exe";
That worked correctly. How can I force the variable not to contain any illegal characters?
i'm pretty sure that you have \n or \r or \t or ... at the end or beginning of the string commandContent
can you do a
System.Text.Encoding.UTF8.GetBytes (commandContent)
and check each byte?
maybe the ajax call doesn't make a proper string/path
you can use this to find which one
class Program
{
static void Main(string[] args)
{
var commandContent = "C:\\Users\\Me\\file.exe\n";
var commandContentBytes = System.Text.Encoding.UTF8.GetBytes(commandContent);
var invalidPathChars = System.IO.Path.GetInvalidPathChars().Select(x=>Convert.ToByte(x));
var found = commandContentBytes.Intersect(invalidPathChars);
}
}
I am developing an Desktop Application in WPF using C# .
For the sake of simplicity, Assume my Application has functions which draw lines in said direction goleft() , goright() , goforward() , goback() .
when any of these function is called a line of one inch will be drawn on screen.
I want to make application where user will write code in a file in any editor (say notepad) and save that file in some fixed format (say .abc or .xyz)
Imaginary Example :
(section_start)
For(int i = 0 ; i<= 20 ; i++ )
{
if(i<5)
goforward();
else if(i==5)
goleft();
else if(i < 10)
forward();
.......
........
}
(section_End)
Can i make application which should be capable of reading this file and execute code which is written in between of (section_start) and (section_End). and only if possible can check for syntax errors too... (Not compulsory).
Please guide me on this issue :
Disclosure : My actual Application is somewhat else and could not discuss here due to my company's rules.
Thanks to all who replied to my question. Stackoverflow is fantastic site , i have found the roadmap where to go , till today morning i did not have any clue but now i can go ahead , thanks all of you once again
Will ask question again if i get stucked somewhere
You can read the file content using FileInfo and get the code you need to execute.
Then you can execute the code using CSharpCodeProvider like in this post:
using (Microsoft.CSharp.CSharpCodeProvider foo =
new Microsoft.CSharp.CSharpCodeProvider())
{
var res = foo.CompileAssemblyFromSource(
new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true
},
"public class FooClass { public string Execute() { return \"output!\";}}"
);
var type = res.CompiledAssembly.GetType("FooClass");
var obj = Activator.CreateInstance(type);
var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
}
You can choose CodeDOM or IL Emit
More help on CodeDOM
More information on IL Generator / Emit
This is called scripting your application if I understand correctly. C# does not support this out of the box. One thing to look into could be the new Roselyn compiler from Microsoft (it is a new take on the C# compiler, which lets you do just this).
For more info on Roselyn check out:
http://blogs.msdn.com/b/csharpfaq/archive/2011/12/02/introduction-to-the-roslyn-scripting-api.aspx
I've only seen a demo of it, but it looks very promissing, and should solve your problem.
It's not clear what kind of code you want compiled but here is a guide on how to compile code code with C#.
You could use IronPython to handle the script.
Here's an example of how to do this:
First you need a navigation object to perform the operations on:
public class NavigationObject
{
public int Offset { get; private set; }
public void GoForwards()
{
Offset++;
}
public void GoBackwards()
{
Offset--;
}
}
Then the code to execute the file:
public void RunNavigationScript(string filePath, NavigationObject navObject)
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("navigation", navObject);
var source = engine.CreateScriptSourceFromFile(filePath);
try
{
source.Execute(scope);
}
catch(Exception
{
}
}
The script file can then take the form of something like:
for x in range(0,20):
if x == 5:
navigation.GoBackwards()
else:
navigation.GoForwards()