I am VERY new to C# so it is possible this is a really easy problem, but even after all my reading I cant find a way to add the definitions Visual Studio 2010 wants despite having added the using statements and the references on the MSDN docs page for each expression.
My Error:
System.windows.forms does not contain a definition for document
I added the reference "presentationframework" based on something I was reading on the Microsoft site. Thanks to some of the comments below I discovered I was apparently mixing two different ways to get text from the box. All I need to be able to do is paste content into the textbox, and get the contents of the box when i press a button. Can someone tell (or better yet show) me definitively how to do this without mixing strategies?
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Controls.RichTextBox;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class HackController : Form
{
ArrayList ipList = new ArrayList();
ArrayList acctList = new ArrayList();
int myAcct = 0;
string myIp = "";
public HackController()
{
InitializeComponent();
}
public void sync_Click(object sender, EventArgs e)
{
string data = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;// ERROR HERE
string[] lines = Regex.Split(data, "\n");
Regex ipMatch = new Regex(#"\d+.\d+.\d+.\d+");
Regex acctMatch = new Regex(#"#\d+");
foreach(string line in lines)
{
foreach(Match m in ipMatch.Matches(line))
{
ipList.Add(m);
}
foreach( Match m in acctMatch.Matches(line))
{
acctList.Add(m);
}
}
}
}
}
Here's a (rather strange) sample showing one way to display data in a WinForms RichTextBox control. (Sorry, but it's the only sample I can find in my programming because I'm usually using Developer Express WinForms controls instead of the basic .Net ones.)
But first, to be 100% sure you are not mixing WinForms and WPF, make sure that when you create the project you select WinForms as the project template type (not WPF). And when you drag-and-drop the RichTextBox control from the Visual Studio toolbox onto your form, make sure it is the WinForms RichTextBox, not the WPF one.
You can check this by looking in the .Designer.cs file, and find the definition of the RTB control created by the Visual Studio designer. It should look something like this:
this.rtbResults = new System.Windows.Forms.RichTextBox();
...
...
//
// rtbResults
//
this.rtbResults.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtbResults.Location = new System.Drawing.Point(12, 52);
this.rtbResults.Name = "rtbResults";
this.rtbResults.Size = new System.Drawing.Size(640, 133);
this.rtbResults.TabIndex = 17;
this.rtbResults.Text = "";
...
...
private System.Windows.Forms.RichTextBox rtbResults;
The important thing being that it says "System.Windows.Forms.RichTextBox", not something else.
OK, here's my strange example, which displays the results of a Scrabble cheater program:
/// <summary>
/// Method to display the results in the RichTextBox, prefixed with "Results: " and with the
/// letters J, Q, X and Z underlined.
/// </summary>
private void DisplayResults(string resultString)
{
resultString = UnderlineSubString(resultString, "J");
resultString = UnderlineSubString(resultString, "Q");
resultString = UnderlineSubString(resultString, "X");
resultString = UnderlineSubString(resultString, "Z");
rtbResults.Rtf = #"{\rtf1\ansi " + "Results: " + resultString + "}";
}
/// <summary>
/// Method to apply RTF-style formatting to make all occurrences of a substring in a string
/// underlined.
/// </summary>
private static string UnderlineSubString(string theString, string subString)
{
return theString.Replace(subString, #"\ul " + subString + #"\ul0 ");
}
This uses Microsoft's proprietary Rich Text Format, but RichTextBox can also use straight text. And this demo only writes to the RTB, it doesn't read from it, although doing that is fairly trivial.
Hope this helps.
Related
I am writing a C# class to use for generating email lists to use when a process either succeeds or fails. In running through XmlReader examples from the web, I found that validating the Read() is tougher than it looks.
I can use string.IsNullOrEmpty(x) to test for a null value or and empty node, but it will still blow by that test showing a "\n " in the tooltip for x. Testing for "\n ", '\n ', '\n'. "\n" or char(13) all fail. If I use x.Contains((char)13), it always find it and goes into the code trying to build the email address list. So far, it either always fails or always succeeds.
I found some old posts on stackoverflow where it seemed like the question was the same, but my results don't match with the answers. My environment is Windows 8.1 running Visual Studio 2013 with .Net Framework 4.51. The example from the web I was trying to make work before using the solution in my class is at Microsoft.com
My conversion is below:
using System;
using System.Text;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Collections.Generic;
namespace XMLDemo
{
public class project
{
public static void Main()
{
string uri = #"C:\\events\items.xml";
string process_state = "Item";
string emails = StreamEmailAddress(uri, process_state);
}
private static string StreamEmailAddress(string uri, string process_state)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create(uri, settings);
string returnValue = "";
reader.MoveToContent();
while (reader.Read())
{
string x = reader.Value;
if ((string.IsNullOrEmpty(x) == false) && (x.Contains((char)13)))
{
returnValue = returnValue + x + "; ";
}
}
Console.WriteLine("Made it to the end: " + returnValue);
return returnValue;
}
}
}
You should use string.IsNullOrWhiteSpace
SOLVED: After futzing with it all day, I looked at it with slightly fresher eyes after posting and saw the blatant error. I was using the incorrect function and trying to resolve line feeds by myself. By replacing IsNullOrEmpty(x) with IsNullOrWhiteSpace(x), I got the string of data as expected. Doing the code with email addresses will be easy now.
I am aware that there are already a few threads on this already created and closed (like 2-dimensional Integer array to DataGridView)
My problem is that since I have only been working with console applications, I am not aware of what I need to do in order to apply the code.
Up till now I have drag and dropped a new dataGridView and chose program.cs (where my main is) as a source. Now when I apply the code from the aforementioned link in program.cs, visualstudio is saying that dataGridView1 "does not exist in the current context". When I try to declare it beforehand, I get that the type/namespace can't be found. Any ideas?
With regard to the errors you got: All you need to do is add the namespace: using System.Windows.Forms; and also a reference to it! This works just fine for Console applications. Of course it will never show up but other than that you can make use of its abilities..
But the real question is: What do you want to achieve and why do you stick to a console application?
This is not to say that you may not have a good reason! For example it is sometimes necessary to run a service application without a display screen. This could still create output from DataGridViews or from Chart controls..
But it always helps to understand the situation fully when we answer questions here..
Here is an example that creates and fills a DataGridView DGV and then saves an image of the data to a png file.
For this to work you also need to add System.Drawing. As for Windows.Forms you need to add both the using clause and the reference:
(I have only a German VS version here; instead of the 'Aktuell' (ie 'Current') group you should search the references in the 'Framework'! The result is the same - I chose the other one becasue it is not so big on the screenshot..)
Once the references are in place..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; // <--- add namespace AND reference!!
using System.Drawing; // <--- add namespace AND reference!!
..this simple console application will compile and run:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataGridView DGV = new DataGridView();
List<string> test = new List<string>()
{ "Anna", "Bertha", "Carol", "Doreen", "Erica", "Fran", "Gisa" };
DGV.Columns.Add("No", "Number");
DGV.Columns.Add("Name", "Name");
DGV.Columns.Add("Age", "Age");
DGV.Columns["Name"].DefaultCellStyle.Font =
new Font(DGV.Font, FontStyle.Bold);
for (int i = 0; i < test.Count; i++) DGV.Rows.Add(new[]
{ (i + 1)+ "", test[i], i + 21 +""}); // cheap string array
DGV.ScrollBars = ScrollBars.None;
DGV.AllowUserToAddRows = false;
DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
DGV.RowHeadersVisible = false;
var width = DGV.Columns.GetColumnsWidth(DataGridViewElementStates.None);
DGV.ClientSize = new Size(width,
DGV.ColumnHeadersHeight + DGV.RowCount * (DGV.Rows[0].Height) );
Bitmap bmp = new Bitmap(DGV.ClientSize.Width, DGV.ClientSize.Height);
DGV.DrawToBitmap(bmp, DGV.ClientRectangle);
bmp.Save("D:\\testDGV.png", System.Drawing.Imaging.ImageFormat.Png);
bmp.Dispose();
}
}
}
I am using coded ui automation in Visual Studio 2012. So I have a requirement where I have to write some generic/common methods which can be used with any type of UI control.
I an new to coded ui. How to write such methods so that i can reuse it in code.
Basically, for example I want common methods for verifying certain control/Tiles/TAB/Objects is visible or not on UI.
NOTE:- I found below solution from some blog, might be this could be helpful.
To replace the UIMap, we are going to use the power of Generics in the .Net Framework. For ease of use in our testing, I built a static extension so that I could attach it to any UITestControl and use a SearchFor method to find things. As you can see in my code below, it is pretty straight forward. I use dynamics to pass in variables that I can use for both the SearchProperties and FilterProperties to go find items in the application. If you need to find more information on the controls you can use the “Coded UI Test Builder” to get more detailed information.
using Microsoft.VisualStudio.TestTools.UITesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blog.Example
{
public static class CodedUIExtension
{
public static T SearchFor<T>(this UITestControl _this, dynamic searchProperties, dynamic filterProperties = null) where T : UITestControl, new()
{
T ctrl = new T();
ctrl.Container = _this;
IEnumerable<string> propNames = ((object)searchProperties).GetPropertiesForObject();
foreach (var item in propNames)
{
ctrl.SearchProperties.Add(item, ((object)searchProperties).GetPropertyValue(item).ToString());
}
if (filterProperties != null)
{
propNames = ((object)filterProperties).GetPropertiesForObject();
foreach (var item in propNames)
{
ctrl.FilterProperties.Add(item, ((object)filterProperties).GetPropertyValue(item).ToString());
}
}
return ctrl as T;
}
private static IEnumerable<string> GetPropertiesForObject(this object _this)
{
return (from x in _this.GetType().GetProperties() select x.Name).ToList();
}
private static object GetPropertyValue(this object _this, string propName)
{
var prop = (from x in _this.GetType().GetProperties() where x.Name == propName select x).FirstOrDefault();
return prop.GetValue(_this);
}
}
}
Next, let’s see how to use this in a test. You can just start out with a basic class template using the File –> New in Visual Studio. You will see in my example below that I have added some “using” statements to bring in the testing framework while also adding some attributes for CodedUITest and TestMethod. Once you have these in place you can get started writing your test. Since we are not using the Coded UI Test Generator here, we will go ahead and add the items we need on our own. Not only are we going to remove the brittleness here but we are also going to be efficient.
The first thing I do in my test is to open a Browser and go to a url. In my case I am going to our blog. This will open up the browser and navigate all in one line (nifty). Next we are going to start to find the items we need to interact with on the screen. As you can see the first item I am going to go get n my test is the header section. This is a custom html control with the tagname “HEADER.” Once I find this control, I am going to use it in the next section so that I have a container to search within. To be honest, I really don’t have to do this, but I did want to show you that you can search for items using a container instead of having to search the entire DOM every time. Next I will get the search button control and use the “Mouse.Click” operation to click and open the search text box. Once the Coded UI Test finds the search box, it automates the text I want and use and then uses keyboard controls to send the ENTER key for the search.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using Mouse = Microsoft.VisualStudio.TestTools.UITesting.Mouse;
using MouseButtons = System.Windows.Forms.MouseButtons;
namespace Blog.Example
{
[CodedUITest]
public class SimpleUITestWithoutCodedUI
{
[TestMethod]
public void SimpleWebTest()
{
//open the default browser and navigate to a web page - blog.falafel.com
BrowserWindow browser = BrowserWindow.Launch(new Uri("http://blog.falafel.com"));
//we can use controls as a way to narrow down the search for other controls
var headerSection = browser.SearchFor<HtmlCustom>(new { TagName = "HEADER" });
//let's search for something
var searchIcon = headerSection.SearchFor<HtmlHyperlink>(new { href = "http://blog.falafel.com/#searchbox" });
Mouse.Click(searchIcon);
var searchInput = browser.SearchFor<HtmlEdit>(new { name = "s" }, new { type = "INPUT" });
searchInput.Text = "treats and tricks";
Keyboard.SendKeys("{ENTER}");
//find our searched for item
var postToLookFor = browser.SearchFor<HtmlCustom>(new { TagName = "ARTICLE" }, new { InnerText = "31 Days of Visual Studio 2015 Tricks and Treats Blog Post" });
//validate our search
Assert.IsTrue(postToLookFor.Exists);
}
}
}
The next thing I do on the search result screen is find the item that I am interested in evaluating. I made that sound really easy, but having dynamic controls show up and find them is one of the hardest things to do in any Testing Framework. With the power of C# and the flexibility of the Coded UI Framework, I am able to dynamically find my items using search and filter properties so that I can evaluate them. The rest of the test, including the assertion, are basic unit testing techniques.
Like that?
public bool IsVisible(Control control)
{
return control.Visible;
}
I implemented a generic search function as such:
public static ControlType IdentifyControlByIdentifierEqualsValue<ControlType>(UITestControl parent, ControlIdentifier identifierTypeAndValue) where ControlType : UITestControl
{
var control = (ControlType)Activator.CreateInstance(typeof(ControlType), new UITestControl[] { parent });
control.SearchProperties.Add(identifierTypeAndValue.Type, identifierTypeAndValue.Value);
var wasFound = control.TryFind();
if (!wasFound)
throw new UITestControlNotFoundException("The control of type " + control.GetType().ToString() + " with the identifier type of " + identifierTypeAndValue.Type + " and the identifying attribute of " + identifierTypeAndValue.Value + " was not able to be found");
return control;
}
With the supporting class
public class ControlIdentifier
{
public ControlIdentifier(string type, string id)
{
Type = type;
Value = id;
}
public string Type { get; set; }
public string Value { get; set; }
}
Called as such:
IdentifyControlByIdentifierEqualsValue<WpfTabList>(workWindow,
new ControlIdentifer(WpfButton.PropertyNames.Name, "OK");
i know i could search proccessId / name of running tasks and kill processes i need .
though till now i was not developing schedualed tasks / self executble Applications,
so i didn't need to know how to make the application close itself after execition
trying to close everything (including WebDriver) via Application.Exit + OR this.Close()
right after i have got what i was looking for. mission Complete .
please close ... no more work for you .
but mr . Program.cs still needs somthing from Form1.
saying somthing about
Cannot access a disposed object.
Object name: 'Form1'.
any combination of both was returning in some point an exeption error
(from program.cs ) even though mission complete . no more code was requested .(?) by me..atleast.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using System.IO;
namespace HT_R_WbBrows2
{
public partial class Form1 : Form
{
public IeEnginGenerator Iengn = new IeEnginGenerator();
public Form1()
{
InitializeComponent();
//setLogView(View.Details);
string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);
string flnm = #" the directory path to file --> \dolarRate.asp";
File.WriteAllText(fn, extractededVal);
this.Close();
Application.Exit();
}
public class IeEnginGenerator
{
private string directory = Environment.CurrentDirectory;///Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
public IWebDriver IwebEngine;
public List<string> ListElementsInnerHtml = new List<string>();
public HtmlAgilityPack.HtmlDocument Dnetdoc = new HtmlAgilityPack.HtmlDocument();
#region <<=========== setupDriver ============>>
public string ExtractPageValue(IWebDriver DDriver, string url="")
{
if(string.IsNullOrEmpty(url))
url = #"http://www.boi.org.il/he/Markets/ExchangeRates/Pages/Default.aspx";
var service = InternetExplorerDriverService.CreateDefaultService(directory);
service.LogFile = directory + #"\seleniumlog.txt";
service.LoggingLevel = InternetExplorerDriverLogLevel.Trace;
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
DDriver = new InternetExplorerDriver(service, options, TimeSpan.FromSeconds(60));
DDriver.Navigate().GoToUrl(url);
Dnetdoc.LoadHtml(DDriver.PageSource);
string Target = Dnetdoc.DocumentNode.SelectNodes("//table//tr")[1].ChildNodes[7].InnerText;
//.Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())
//.ToList();
return Math.Round(Convert.ToDouble(Target), 2).ToString();
//return "";//Math.Round(Convert.ToDouble( TempTxt.Split(' ')[10]),2).ToString();
}
#endregion
}
}
}
Why use a winform application? A Console application would probably suffice for what you are doing. Once Main() ends your app will close as well. Main() never ends in a winform app because of the applications runloop.
Edit:
Here would be the correct way to do this. You need to register to the forms Load event and run your code there, not in the constructor. You can't close a winform from inside a constructor.
Edit 2: Put this code in the Form1() constructor. Somewhere after InitializeComponent();
this.Load += (sender,args)=>{ /*do all your work here*/
string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);
string flnm = #" the directory path to file --> \dolarRate.asp";
File.WriteAllText(fn, extractededVal);
Application.Exit();
};
I'm trying to make a program packer but i always fail because when i concat three strings(one contains prefix of source, one contains executable content, other contains suffix of source) content overflows into suffix. Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.IO.Compression;
namespace ProgramPacker
{
public partial class Form1 : Form
{
static string prefix = #"using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ProgramPacker
{
class Program
{
static string inside = #" + "\"";
static string suffix = "\";\n" + #"static void Main(string[] args)
{
string temp = Path.GetRandomFileName() +" + "\"" + #".exe" + "\"" + #";
BinaryWriter sw = new BinaryWriter(new FileStream(temp, FileMode.Create));
sw.Write(inside);
sw.Flush();
sw.Close();
System.Diagnostics.Process.Start(temp);
}
}
}";
public string code = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
BinaryReader br = new BinaryReader(new FileStream(openFileDialog1.FileName, FileMode.Open));
byte[] data = new byte[br.BaseStream.Length];
br.Read(data, 0, (int)br.BaseStream.Length);
br.Close();
string inside = Encoding.UTF7.GetString(data);
code = string.Concat(prefix, string.Concat(inside, suffix));
}
private void button2_Click(object sender, EventArgs e)
{
Console.Write(code);
CSharpCodeProvider cs = new CSharpCodeProvider();
ICodeCompiler compile = cs.CreateCompiler();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = false;
param.ReferencedAssemblies.Add("mscorlib.dll");
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add("System.Core.dll");
param.GenerateExecutable = true;
param.OutputAssembly = Environment.CurrentDirectory + "/a.exe";
param.WarningLevel = 4;
CompilerResults comp = compile.CompileAssemblyFromSource(param, code);
foreach (CompilerError error in comp.Errors)
{
MessageBox.Show(error.Line + " " + error.Column + " " + error.ErrorText);
}
MessageBox.Show(comp.PathToAssembly);
MessageBox.Show("Finish!");
}
}
}
It outputs:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ProgramPacker
{
class Program
{
static string inside = #"?ãÎoüoy±ôãøÿ?ÿQÔh¦Rt!?^ÿyóë=G:Fÿ»??¿Ç/}òKÿ?úõßû3õMù?c·?Äûòëoª?À_Û>LÖïá^öÿ·õ©üüòcÊ?ª??÷Ô?î:^ȯÏäG¶?ù ?ñË?oñëy:ôã7??ò#ÚyN?w¿=?ëÆ÷ëÛßTëºÓ»yßüø]áå{ö/àïªêL©Oÿ;ú5rù% ä¸?1)Ï?¥?y®ÿ]0QL8û×ÖGòów±?øÿèü[?ª~éá¿ÿó£üüJ~ܹ
Êw¡h??/?úçeñÈ_?¿?ü½L^ywü7?,ùÅû¿ß£ó÷w?É~Ç????ê?ÿQÌyç¿??¹Cö×vZ__>?? ûïx?_ü"õ!ì; ;ùõåÇ?ú3*¿ #ÿV?èÿ¿Ë??/½P¶y?â¡??ùñÿÑæä/A¶_ò?v??ÿ?ÿQtÄx÷w?O'N?u$ÿk÷U«yÆò?£.Y?ùw(?ßÔ6ÿ]2ÿeUÆò¿?ضö·ßO~ü#*y£Jæ·Ä w yóYëï´
õ}y¡ä¨ù÷YPdú?Z©Óé¼R?æg?ÀSyà쬽ÉÿûÁ?ym>ut?ÿA??>?¿[ôçF ê´)9ß9xÿ£¿?
åùïyí ÁTlù
-ùñ?Òÿ·!·
E?£üO5÷]çºy?7Áè¿?Zô?(å§
#ü¥úõ®?o«âû]0Èßä7¿à??¿õ?d?ѵ;Jü_K?úAMìT>Àü1mR0sâ¿ê¨õ{äö×ó??¿.úÿõ½Eä?ÔïÿÎÿ±³v'ÿûìw ?»oÃø1±WtB
É¡wì&øuå£Îÿ?Éw?|úWÿ=ö÷_ÿ·?y®YWöwû¿ßß?Öe'û?%?yß/×Àî-yÿ.?8åóù?ûÇÚ6ÿÂßøï?Áàï?{8Zy?¿Å5yø ÇpÏ9=ó»üÑ>Õ?Èÿ?Y¿,?ëÿ?Êçÿì_}E?÷Ûú|î$ò÷ø}Jÿ^Êtò¿?#á|ò{Ø`<ªÿQ?QLæ½õo)¿ü&¿áÂÿ¼ó¿_÷7yMå8)¿Ùo'¿õ±üü=~#LÚ¿ó§¢Ë÷üO?Æ?å÷WJÍ$¾¸øW?A?Òÿ(09Áÿà³_ëÿù3l?SWYµßô÷¤~?ÀG¿ñ
??Às%ÍyÑ;Ò¸!ÿ?_Iÿ¼¼í/Ôrö
?T´ôÑùyǹßE~üV?ñ¿C~VßùuÿG X8|._¼Å_:Æü-?îü:?øì?|W ¤ÃÓW01?$å×?Û#ùIÿû·1:4û½ü._y^òÙNó?º1?ßIÍ?ÿ¿ß_~|ÖùX?#?në_B?¡µ~_×ãÿhãèïØÏßì¡yïôk_y;HÿÛyÿàâ/sÀ??? $ìw0Jüßü«#?ûo?¿îËX
´úÏ?Æ?Y>øçÿFpyÅÿèËöyK¡²Ì`}ù½Ò¿íÿÀñn"?Í?ëOëi»ò¹Î~çÿ?_òüîÿh£ôáêDøÏÿ¶?ç·fy ÄúçÿÖÿ?yÿ?¿?ã0ÿ¿Ë÷åå?ÿQ|ü/ü9¿?÷×Hè×ÉÏ#õ??æ?ÿâ?x?ß?5µ}~Øy¾ß^øè{¿
y{íü;Òÿ¿óú7¤¡î?» yû?ÀÓøiP?ÿÀ_ôK?Gëªíá#??ú%íwS×ñ¿¨#Û¦ÿÿÛªy\]¼÷Z~yR~ü¶ÿ£hû???ÇãÿQVèÿ©?÷{O?Gë¬ ??¡ø\«L` æcëí¿ ½?»?ü?oë¼Ätÿ>ò÷£_¯ÖiÄ?¯ÿÓ¿÷Ï?(c¦äàéûèó?ü£´çÕè4üy_
r?qÆ¿ø'?KÿÀ_ó×xùkÔ¿FõkÌ~õ¯1y5Ú_ã'??n~âר~å¯ñkü»¿Æø×رÿÿ5~?_ã7ø5~Í_ã?Z4ÔrñkL~ò׸?5Òßûÿ??ñïñnQ¦?yYÕò³vÇ;¥ùrZÍ?åÅg}õæÙöÁGiÓfËYVVËü³®óæ£ßãè7NgM?/&åuJrustInfo>
</assembly>
;
}
}
}
Any help?
EDIT: Why is everyone down-voting? I just asked a question.
Don't use bare UTF7 or UTF8 strings, use Base64 encoding instead.
// given: byte[] data = new byte[...]
string inside = System.Convert.ToBase64String(data);
code = string.Concat(prefix, string.Concat(inside, suffix));
// in your target code
sw.Write(System.Convert.FromBase64String(inside));
You've run into a problem of representation, one that you're not likely to fix with your code as-is.
However, you can choose to follow a similar approach with just minor modifications (which don't actually compress your program much at all).
Remove the # from the definition of the string inside. This is one of the causes of your problems.
You can't just put a BELL character or NUL character in-line in your string, instead write out their unicode escape sequences:
string inside = String.Concat(
data.Select(b => String.Format(#"\u{0:X4}", b)));
Now, in your suffix code, reinterpret your inside string as characters which you cast to bytes:
sw.Write(inside.Select(c => (byte)c).ToArray()); // hardly efficient
I was able to use these modifications and successfully "pack" and execute the following:
C:\temp>type hello.cs
using System;
class M {
static void Main(string[] args) {
System.IO.File.Create("hello.world");
}
}
C:\temp>csc hello.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
C:\temp>pack.exe hello.exe
3584 bytes
C:\temp>a.exe
C:\temp>dir *.world
Volume in drive C is OSDisk
Volume Serial Number is AABD-D663
Directory of C:\temp
03/22/2012 16:36 0 hello.world
1 File(s) 0 bytes
0 Dir(s) 279,351,762,944 bytes free
Better use CodeCompileUnit to generate C# code from a C# program:
http://msdn.microsoft.com/en-us/library/system.codedom.codecompileunit.aspx
You can also use this to compile the generated ATS into an assembley.
Or parse your template parts from files. That would make the code much more readable.
You can't just express executable binary code as a C# string without escaping it. At least you need to replace any occurrences of the double-quote character ('"') with a sequence of two double-quote characters. I would be very surprised if that's the only problem you encounter, however.
Note that the string might contain control characters that cause the screen to display the string in a garbled way, but that wouldn't necessarily cause the code containing that string to compile improperly. For example, if you have a verbatim string containing a backspace ("stac{backspace}koverflow", say), the character after the backspace would overwrite the character before the backspace, so viewing the string on the screen would give an inaccurate representation of its contents ("stakoverflow"). The compiler would presumably see the full 14-character string including the backspace.