How to parse XAML from Xamarin as a string with C#? [duplicate] - c#

The Error:
System.Windows.Markup.XamlParseException: ''Can't create unknown type
'{schemas.xceed.com/wpf/xaml/toolkit}DoubleUpDown'.' (line number:
'1'; line position: '1706').'
I got the following code:
ParserContext context = new ParserContext();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("materialDesign", "http://materialdesigninxaml.net/winfx/xaml/themes");
context.XmlnsDictionary.Add("smtx", "clr-namespace:ShowMeTheXAML;assembly=ShowMeTheXAML");
context.XmlnsDictionary.Add("l", "clr-namespace:UIControls;assembly=UIControls");
context.XmlnsDictionary.Add("d", "http://schemas.microsoft.com/expression/blend/2008");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
context.XmlnsDictionary.Add("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
context.XmlnsDictionary.Add("sys", "clr-namespace:System;assembly=mscorlib");
context.XmlnsDictionary.Add("xctk", "http://schemas.xceed.com/wpf/xaml/toolkit");
Encoding encoding = Encoding.UTF8;
var ecod = new System.IO.MemoryStream(encoding.GetBytes(xaml));
TabItem element = (TabItem)XamlReader.Load(ecod, context);
DataControl.Items.Add(element);
As request of #mm8 this is a smaller string xaml:
string xaml = "<TabItem>" +
"<TabItem.Header>" +
"<StackPanel Orientation='Horizontal'>" +
"<TextBlock Text='Neutral' Foreground='Black' HorizontalAlignment='Center' VerticalAlignment='Center' Margin='0,0,0,0'/>" +
"</StackPanel>" +
"</TabItem.Header>" +
"<Grid Margin='0,20,0,0'>" +
"<Grid.ColumnDefinitions>" +
"<ColumnDefinition Width='1*'/>" +
"<ColumnDefinition Width='2*'/>" +
"<ColumnDefinition Width='1*'/>" +
"<ColumnDefinition Width='2*'/>" +
"</Grid.ColumnDefinitions>" +
"<StackPanel Grid.Column='0' Orientation='Vertical' HorizontalAlignment='Right'>" +
"<Label HorizontalAlignment='Right'>Sueldo:</Label>" +
"<Label HorizontalAlignment='Right'>Horas semanales:</Label>" +
"<Label HorizontalAlignment='Right'>Valor hora extra:</Label>" +
"<Label HorizontalAlignment='Right'>Valor hora extra nocturna:</Label>" +
"</StackPanel>" +
"<StackPanel Grid.Column='1' Orientation='Vertical'>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"</StackPanel>" +
"<StackPanel Grid.Column='2' Orientation='Vertical' HorizontalAlignment='Right'>" +
"<Label HorizontalAlignment='Right'>Valor de la hora(no extra):</Label>" +
"</StackPanel>" +
"<StackPanel Margin='10,0,0,0' Grid.Column='3' Orientation='Vertical' HorizontalAlignment='Left'>" +
"<TextBlock FontSize='18' Height='23'/>" +
"</StackPanel>" +
"</Grid>" +
"</TabItem>";
Those controls are giving me the error, I get it as if the resource is not being called though I call it in the ParserContext as you can see in the code.
If I add it manually in the XAML it works like a charm, other dll resources are working so I don't think is all about BuildAction.
What am I missing? Any other way to do this?

Mapping the assembly in the parser like this:
context.XmlnsDictionary.Add("xctk", "clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit");
Instead of like this:
context.XmlnsDictionary.Add("xctk", "http://schemas.xceed.com/wpf/xaml/toolkit");
Fixed the problem.

Related

Why this Selenium's drag and drop C# code is not working on Chrome?

This doesn't work (e.g.: https://www.w3schools.com/html/html5_draganddrop.asp)
var item = WebDriver.FindElement(By.XPath(#"//img[#src='img_w3slogo.gif']"), 30);
var container = WebDriver.FindElement(By.XPath(#"//div[#id='div2']"), 30);
var actions = new OpenQA.Selenium.Interactions.Actions(this.WebDriver);
actions.DragAndDrop(item, container).Build().Perform();
System.Threading.Thread.Sleep(3000);
If it helps....
public static void DragAndDrop(IWebElement element1, IWebElement element2)
{
WaitForElementEnabled(element1);
WaitForElementEnabled(element2);
var builder = new Actions(_webDriver);
var dragAndDrop = builder.ClickAndHold(element1).MoveToElement(element2).Release(element2).Build();
dragAndDrop.Perform();
}
public static void WaitForElementEnabled(IWebElement element)
{
try { _wait.Until(webDriver => element.Enabled); }
catch (StaleElementReferenceException) { if (!WaitForNotFoundElement_Enabled(element)) { LogFunctions.WriteError("Enabled - Stale Element Exception"); TakeScreenshot("elementNotFound"); throw; } }
}
The only way I was able to get this to work was by using the helper function located here: https://gist.github.com/druska/624501b7209a74040175 and executing javascript (Java example):
String simulateFunction = "function simulateDragDrop(sourceNode, destinationNode) {\n" +
" var EVENT_TYPES = {\n" +
" DRAG_END: 'dragend',\n" +
" DRAG_START: 'dragstart',\n" +
" DROP: 'drop'\n" +
" }\n" +
"\n" +
" function createCustomEvent(type) {\n" +
" var event = new CustomEvent(\"CustomEvent\")\n" +
" event.initCustomEvent(type, true, true, null)\n" +
" event.dataTransfer = {\n" +
" data: {\n" +
" },\n" +
" setData: function(type, val) {\n" +
" this.data[type] = val\n" +
" },\n" +
" getData: function(type) {\n" +
" return this.data[type]\n" +
" }\n" +
" }\n" +
" return event\n" +
" }\n" +
"\n" +
" function dispatchEvent(node, type, event) {\n" +
" if (node.dispatchEvent) {\n" +
" return node.dispatchEvent(event)\n" +
" }\n" +
" if (node.fireEvent) {\n" +
" return node.fireEvent(\"on\" + type, event)\n" +
" }\n" +
" }\n" +
"\n" +
" var event = createCustomEvent(EVENT_TYPES.DRAG_START)\n" +
" dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event)\n" +
"\n" +
" var dropEvent = createCustomEvent(EVENT_TYPES.DROP)\n" +
" dropEvent.dataTransfer = event.dataTransfer\n" +
" dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent)\n" +
"\n" +
" var dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END)\n" +
" dragEndEvent.dataTransfer = event.dataTransfer\n" +
" dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent)\n" +
"} var toDrag =document.getElementById('drag1'); var toDrop = document.getElementById('div2');";
((JavascriptExecutor)driver).executeScript(simulateFunction + "simulateDragDrop(toDrag, toDrop);");
Did anyone get this working without javascript executor?

Cannot create the unknown type, when adding dynamically

The Error:
System.Windows.Markup.XamlParseException: ''Can't create unknown type
'{schemas.xceed.com/wpf/xaml/toolkit}DoubleUpDown'.' (line number:
'1'; line position: '1706').'
I got the following code:
ParserContext context = new ParserContext();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("materialDesign", "http://materialdesigninxaml.net/winfx/xaml/themes");
context.XmlnsDictionary.Add("smtx", "clr-namespace:ShowMeTheXAML;assembly=ShowMeTheXAML");
context.XmlnsDictionary.Add("l", "clr-namespace:UIControls;assembly=UIControls");
context.XmlnsDictionary.Add("d", "http://schemas.microsoft.com/expression/blend/2008");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
context.XmlnsDictionary.Add("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
context.XmlnsDictionary.Add("sys", "clr-namespace:System;assembly=mscorlib");
context.XmlnsDictionary.Add("xctk", "http://schemas.xceed.com/wpf/xaml/toolkit");
Encoding encoding = Encoding.UTF8;
var ecod = new System.IO.MemoryStream(encoding.GetBytes(xaml));
TabItem element = (TabItem)XamlReader.Load(ecod, context);
DataControl.Items.Add(element);
As request of #mm8 this is a smaller string xaml:
string xaml = "<TabItem>" +
"<TabItem.Header>" +
"<StackPanel Orientation='Horizontal'>" +
"<TextBlock Text='Neutral' Foreground='Black' HorizontalAlignment='Center' VerticalAlignment='Center' Margin='0,0,0,0'/>" +
"</StackPanel>" +
"</TabItem.Header>" +
"<Grid Margin='0,20,0,0'>" +
"<Grid.ColumnDefinitions>" +
"<ColumnDefinition Width='1*'/>" +
"<ColumnDefinition Width='2*'/>" +
"<ColumnDefinition Width='1*'/>" +
"<ColumnDefinition Width='2*'/>" +
"</Grid.ColumnDefinitions>" +
"<StackPanel Grid.Column='0' Orientation='Vertical' HorizontalAlignment='Right'>" +
"<Label HorizontalAlignment='Right'>Sueldo:</Label>" +
"<Label HorizontalAlignment='Right'>Horas semanales:</Label>" +
"<Label HorizontalAlignment='Right'>Valor hora extra:</Label>" +
"<Label HorizontalAlignment='Right'>Valor hora extra nocturna:</Label>" +
"</StackPanel>" +
"<StackPanel Grid.Column='1' Orientation='Vertical'>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"<xctk:DoubleUpDown FontSize='16'/>" +
"</StackPanel>" +
"<StackPanel Grid.Column='2' Orientation='Vertical' HorizontalAlignment='Right'>" +
"<Label HorizontalAlignment='Right'>Valor de la hora(no extra):</Label>" +
"</StackPanel>" +
"<StackPanel Margin='10,0,0,0' Grid.Column='3' Orientation='Vertical' HorizontalAlignment='Left'>" +
"<TextBlock FontSize='18' Height='23'/>" +
"</StackPanel>" +
"</Grid>" +
"</TabItem>";
Those controls are giving me the error, I get it as if the resource is not being called though I call it in the ParserContext as you can see in the code.
If I add it manually in the XAML it works like a charm, other dll resources are working so I don't think is all about BuildAction.
What am I missing? Any other way to do this?
Mapping the assembly in the parser like this:
context.XmlnsDictionary.Add("xctk", "clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit");
Instead of like this:
context.XmlnsDictionary.Add("xctk", "http://schemas.xceed.com/wpf/xaml/toolkit");
Fixed the problem.

Azure REST API - Create, through programming, a database within an elasticPoll

I need to create, through programming, a database in an elasticPoll.
To do this, I'm using the API version 2014-04-01, indicated in "Azure REST APIs > SQL Database > Databases > Create Or Update".
I create a new HttpWebRequest object and launch the .Create() method
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Sql/servers/{2}/databases/{3}?api-version={4}", VariabiliGlobali.SubscriptionID, VariabiliGlobali.ResourceGroup, VariabiliGlobali.SqlServerName, databaseName, VariabiliGlobali.APIVersion));
and compile the properties:
request.Headers["Authorization"] = "Bearer" + token;
request.ContentType = "application/json; charset = utf-8";
request.Method = "PUT"
I create a new StreamWriter object
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
//streamWriter.Close();
}
and the .Write() mothod parameter, assign the complete Json code of the model shown in the "Databases - Create Or Update" example as below.
string json =
"{" +
"\"parameters\": {" +
"\"subscriptionId\": \"" + VariabiliGlobali.SubscriptionID + "\"," +
"\"resourceGroupName\": \"" + VariabiliGlobali.ResourceGroup + "\"," +
"\"serverName\": \"" + VariabiliGlobali.SqlServerName + "\"," +
"\"databaseName\": \"" + databaseName + "\"," +
"\"api-version\": \"" + VariabiliGlobali.APIVersion + "\"," +
"\"parameters\": {" +
"\"properties\": {" +
"\"elasticPoolName\": \"" + elasticPoolName + "\"" +
"}," +
"\"location\": \"West Europe\"" +
"}" +
"}," +
"\"responses\": {" +
"\"200\": {" +
"\"body\": {" +
"\"id\": \"/subscriptions/" + VariabiliGlobali.SubscriptionID + "/resourceGroups/" + VariabiliGlobali.ResourceGroup + "/providers/Microsoft.Sql/servers/" + VariabiliGlobali.SqlServerName + "/databases/" + databaseName + "\"," +
"\"name\": \"" + databaseName + "\"," +
"\"type\": \"Microsoft.Sql/servers/databases\"," +
"\"location\": \"West Europe\"," +
"\"kind\": \"v12.0,user\"," +
"\"properties\": {" +
"\"edition\": \"Standard\"," +
"\"status\": \"Online\"," +
"\"serviceLevelObjective\": \"S0\"," +
"\"collation\": \"SQL_Latin1_General_CP1_CI_AS\"," +
"\"creationDate\": \"2017-02-24T22:39:46.547Z\"," +
"\"maxSizeBytes\": \"268435456000\"," +
"\"currentServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveName\": \"S0\"," +
"\"sampleName\": null," +
"\"defaultSecondaryLocation\": \"Japan West\"," +
"\"earliestRestoreDate\": \"2017-02-10T01:52:52.923Z\"," +
"\"elasticPoolName\": null," +
"\"containmentState\": 2," +
"\"readScale\": \"Disabled\"," +
"\"failoverGroupId\": null" +
"}" +
"}" +
"}," +
"\"201\": {" +
"\"body\": {" +
"\"id\": \"/subscriptions/" + VariabiliGlobali.SubscriptionID + "/resourceGroups/" + VariabiliGlobali.ResourceGroup + "/providers/Microsoft.Sql/servers/" + VariabiliGlobali.SqlServerName + "/databases/" + databaseName + "\"," +
"\"name\": \"" + databaseName + "\"," +
"\"type\": \"Microsoft.Sql/servers/databases\"," +
"\"location\": \"West Europe\"," +
"\"kind\": \"v12.0,user\"," +
"\"properties\": {" +
"\"edition\": \"Standard\"," +
"\"status\": \"Online\"," +
"\"serviceLevelObjective\": \"S0\"," +
"\"collation\": \"SQL_Latin1_General_CP1_CI_AS\"," +
"\"creationDate\": \"2017-02-24T22:39:46.547Z\"," +
"\"maxSizeBytes\": \"268435456000\"," +
"\"currentServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveName\": \"S0\"," +
"\"sampleName\": null," +
"\"defaultSecondaryLocation\": \"Japan West\"," +
"\"earliestRestoreDate\": \"2017-02-10T01:52:52.923Z\"," +
"\"elasticPoolName\": null," +
"\"containmentState\": 2," +
"\"readScale\": \"Disabled\"," +
"\"failoverGroupId\": null" +
"}" +
"}" +
"}," +
"\"202\": { }" +
"}" +
"}";
Launch the .GetResponse() method of the HttpWebRequest object
var httpResponse = (HttpWebResponse)request.GetResponse();
and in response I get the following error:
{'Error': {"code": "InvalidRequestContent", "message": "The request content was invalid and could not be deserialized: 'Could not find member' parameters on object of type 'ResourceDefinition' , Line 1, position 14. '. "}}
Where am I wrong?
Thanks in advance.
I believe the documentation is incorrect. Correct request payload should be:
{"properties": {"elasticPoolName": "XXXXX"},"location": "West Europe"}

Why is EO.PDF Timing Out When Converting HTML File to PDF in C#

I have the following bits of code:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strMovie, strGenre, tmpGenre = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
string strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
foreach (Movie m in mList)
{
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">" : " <tr id=\"even\" style=\"page-break-inside:avoid\">";
catalog.WriteLine(strMovie);
foreach (string genre in m.Genres)
tmpGenre += ", " + genre;
try
{ strGenre = tmpGenre.Substring(2); }
catch (Exception)
{ strGenre = null; }
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
lineID = lineID == 0 ? 1 : 0;
}
catalog.WriteLine(" </table>\r\n" + " </body>\r\n" + "</html>");
catalog.Close();
}
public static void WritePDF(string cFile, string pdfFile)
{
// Sets up PDF to write to
EO.Pdf.HtmlToPdf.Options.PageSize = new SizeF(8.5f, 11f);
EO.Pdf.HtmlToPdf.Options.OutputArea = new RectangleF(0.5f, .25f, 7.5f, 10.25f);
HtmlToPdf.ConvertUrl(cFile, pdfFile);
}
My HTML file writes fine, but when it tried to convert the HTML file to PDF I get an exception that it times out.
I did a test previously, and had it convert the code (not the file) within the WriteHTML function and it worked great. I have confirmed that the cFile exists and is a valid file (created previously in WriteHTML). The path to pdfFile is valid, and the documentation does not state the file needs to already exist (.ConvertHTML did not need an existing file).
Only thing I can think of is that the catalog.html file isn't released and ready to read yet. I made sure I closed it in the WriteHTML function. How can I test that the file is ready to be read?
Tried setting .MaxLoadWaitTime = 120000 with no luck.
Any clues would be greatly appreciated!
After a battery of further testing, and scouring the EO support forums, it appears to be a limitation of the free version of EO. It seems to have difficulty with HTML files over 3MB.
It's a shame since the EO product is very good, but not unfortunately not worth $250 IMO.

Open in memory XML string as an Excel workbook without saving using windows Forms C#

I have an excel string (which I built) in memory; the code looks something like this:
public static void exportToExcel()
{
const string startExcelXML = "<xml version>\r\n<Workbook " +
"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n"
+
" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
"xmlns:x=\"urn:schemas- microsoft-com:office:" +
"excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:"
+
"office:spreadsheet\">\r\n <Styles>\r\n " +
"<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
"\r\n <Protection/>\r\n </Style>\r\n " +
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
" ss:Format=\"#\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"Decimal\">\r\n <NumberFormat/>\r\n </Style>\r\n " +
"<Style ss:ID=\"Integer\">\r\n <NumberFormat "
+
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
"ss:Format=\"dd/mm/yyyy;#\"/>\r\n </Style>\r\n " +
"</Styles>\r\n ";
const string endExcelXML = "</Workbook>";
int sheetCount = 1;
StringBuilder sb = new StringBuilder();
sb.Append(startExcelXML);
sb.Append("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
sb.Append("<Table>");
sb.Append("<Row>");
sb.Append("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
sb.Append("Home country");
sb.Append("</Data></Cell>");
sb.Append("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
sb.Append("Expatriation Type");
sb.Append("</Data></Cell>");
sb.Append("</Row>");
sb.Append("<Row>");
sb.Append("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
sb.Append("Singapore");
sb.Append("</Data></Cell>");
sb.Append("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
sb.Append("Benchmark");
sb.Append("</Data></Cell>");
sb.Append("</Row>");
sb.Append("</Table>");
sb.Append(" </Worksheet>");
sb.Append(endExcelXML);
}
I able to open the file as excel sheet only if I save the file physically; but is there any other way to just open the xml string from the memory as excel sheet?
I think what you'll need is a memory mapped file implementation of some kind.
I believe, though, that .NET 4.0 will have built-in MemoryMappedFile support.
You may be able to find other .net implementations using a search engine.
i don't know for sure, but most Microsoft automation objects support IPersist or IPersistStream, which may let you load from a stream in memory.
Something like (pseudo-code):
xl = new Office.ExcelApplication;
(xl as IPersistStream).Load(myMemoryStream);
You can use the shell helper function CreateStreamOnHGlobal to create an IStream wrapper around some memory:
functionCreateStreamOnMemory(pData: Pointer; nCount: DWORD): IStream;
var
hMem: HGLOBAL;
dwError: DWORD;
p: Pointer;
begin
hMem := GlobalAlloc(GMEM_MOVEABLE or GMEM_NODISCARD, nCount);
//CreateStreamOnHGlobal says "The handle must be
//allocated as movable and nondiscardable."
if hMem = 0 then
RaiseLastWin32Error;
p := GlobalLock(hMem);
if p = nil then
begin
dwError := GetLastError;
GlobalFree(hMem);
raise EWin32Error.Create('Could not lock global memory object: '+SysErrorMessage(dwError));
end;
try
CopyMemory(p, pData, nCount);
finally
GlobalUnlock(hMem);
end;
OleCheck(CreateStreamOnHGlobal(hMem, True, Result)); //Because we pass True, the stream will take care of freeing the HGLOBAL when the stream is released
end;
Stuff your string in the memory and see if it loads.

Categories

Resources