create txt file and display it in internet browser inside vfp form - ole

I'm facing difficulty when creating some kind of a report in vfp. I created a text file, used the ?/?? command to write to the file, then opened it using web browser (OLE Object in vfp form).
Set Printer To 'C:\temp\test.txt'
set printer on
set console off
?? 'test'
and then i called my prg :
PARAMETERS pUrl
lcURL = pUrl
PUBLIC oForm
oForm = CREATEOBJECT('IEForm')
oForm.SHOW()
oForm.oIE.Navigate2(m.lcURL)
READ events
DEFINE CLASS IEForm AS FORM
CAPTION = 'Report Preview'
HEIGHT = 512
WIDTH = 792
AUTOCENTER = .t.
ADD OBJECT oIE AS OLECONTROL WITH ;
HEIGHT=512,WIDTH=792,OLECLASS="Shell.Explorer",ANCHOR=195
PROCEDURE oIE.REFRESH
NODEFAULT
ENDPROC
ENDDEFINE
and used the C:\temp\test.txt as the url.
This works fine. But the problem occurs when I use fcreate to create the text file( not using the already existing text file)
lcfile ='C:\temp\'+SYS(2015)+'.txt'
lchandle=FCREATE(lcfile)
Set Printer To lcfile
sometimes the problem occurs when using ? ( resulting in blank doc), and sometimes the browser can't navigate to the file.
The second problem is : the browser can't navigate to the text file if i set the windowtype property to modal in the IEform. I need to set it modal because I have to delay the rest of the execution until the preview form is closed.
I hope I described the situation clear enough.
Thank You for helping Me :)

I would avoid using SET PRINTER TO, and just use the fcreate(), fwrite() and fclose(), especially if writing a large amount of text. If only writing a small amount of data, I would just build one long string by just appending each component to the prior and add cr/lf instead of "?" for new lines, then write the entire result to a file ONCE via StrToFile(). This way, you don't have to worry if things are actually closed (if you dont clear the set printer off, set printer to, or fclose(). Being an incomplete file, the browser won't navigate since the file handle may be "locked" to read anything.
Option 1 -- building a string
lcCRLF = chr(13)+chr(10)
lcMyOutput = "Some Text to Start with" + lcCRLF ;
+ "Today is: " + dtoc( date() ) + lcCRLF
use SomeTable
scan
lcMyOutput = lcMyOutput + "Some Field: " + SomeCharField;
+ "A numeric field: " + transform( SomeNumberField, "999,999.99" ) + lcCRLF
endscan
lcMyOutput = lcMyOutput + "All Done"
lcOutputFile = "C:\Temp\" + sys(2015) + ".txt"
StrToFile( lcMyOutput, lcOutputFile )
Option 2 -- using fcreate(), fwrite(), fclose()
lnHandle = 0
do while .t.
lcOutputFile = "C:\Temp\" + sys(2015) + ".txt"
lnHandle = fcreate( lcOutputFile )
*/ Only get out if we have a proper handle and thus
*/ we are exclusive to it for duration of our process
if( lnHandle > 0 )
exit
endif
enddo
lcCRLF = chr(13)+chr(10)
fwrite( lnHandle, "Some Text to Start with" + lcCRLF ;
+ "Today is: " + dtoc( date() ) + lcCRLF )
use SomeTable
scan
fwrite( lnHandle, "Some Field: " + SomeCharField;
+ "A numeric field: " + transform( SomeNumberField, "999,999.99" ) + lcCRLF )
endscan
fwrite( lnHandle, "All Done" )
fclose( lnHandle )
For running your "batch" file attempt with the RUN command, build the WHAT you want into a string, then run that... ex:
lcCommandToRun = '"' + sys(5) + sys(2003) + '\Compress.tzs"'
run ( lcCommandToRun )
I don't know if it was failing due to a space being in the path of your sys(2003) result turning the RUN into a multi-parameter interpretation, it would fail. By wrapping the entire text within double-quotes, it will prevent such "path" issue.
ADDITIONAL FEEDBACK
Trying to simulate a preview of a DOT-matrix printer using "?" to a text file is not something I would try. I would just do a standard report and draw it with all the data you are doing manually with the "?". If the user want's to preview the report, or send to a laser printer, let the normal report version handled through Windows for generation, font, and such do it for you. Leave the ancient code going to dot-matrix with whatever specific font rendering code as you have. I would just keep the actual report version CLOSE TO your "?" version.

Related

ASP.net VB String builder double double quotes [duplicate]

Everytime I add CharW(34) to a string it adds two "" symbols
Example:
text = "Hello," + Char(34) + "World" + Char(34)
Result of text
"Hello,""World"""
How can I just add one " symbol?
e.g Ideal result would be:
"Hello,"World""
I have also tried:
text = "Hello,""World"""
But I still get the double " Symbols
Furthermore. Adding a CharW(39), which is a ' symbol only produces one?
e.g
text = "Hello," + Char(39) + "World" + Char(39)
Result
"Hello,'World'"
Why is this only behaving abnormally for double quotes? and how can I add just ONE rather than two?
Assuming you meant the old Chr function rather than Char (which is a type).It does not add two quotation mark characters. It only adds one. If you output the string to the screen or a file, you would see that it only adds one. The Visual Studio debugger, however, displays the VB-string-literal representation of the value rather than the raw string value itself. Since the way to escape a double-quote character in a string is to put two in a row, that's the way it displays it. For instance, your code:
text = "Hello," + Chr(34) + "World" + Chr(34)
Can also be written more simply as:
text = "Hello,""World"""
So, the debugger is just displaying it in that VB syntax, just as in C#, the debugger would display the value as "Hello, \"World\"".
The text doesn't really have double quotes in it. The debugger is quoting the text so that it appears as it would in your source code. If you were to do this same thing in C#, embedded new lines are displayed using it's source code formatting.
Instead of using the debugger's output, you can add a statement in your source to display the value in the debug window.
Diagnostics.Debug.WriteLine(text)
This should only show the single set of quotes.
Well it's Very eazy
just use this : ControlChars.Quote
"Hello, " & ControlChars.Quote & "World" & ControlChars.Quote

DM Script to import a 2D image in text (CSV) format

Using the built-in "Import Data..." functionality we can import a properly formatted text file (like CSV and/or tab-delimited) as an image. It is rather straight forward to write a script to do so. However, my scripting approach is not efficient - which requires me to loop through each raw (use the "StreamReadTextLine" function) so it takes a while to get a 512x512 image imported.
Is there a better way or an "undocumented" script function that I can tap in?
DigitalMicrograph offers an import functionality via the File/Import Data... menu entry, which will give you this dialog:
The functionality evoked by this dialog can also be accessed by script commands, with the command
BasicImage ImageImportTextData( String img_name, ScriptObject stream, Number data_type_enum, ScriptObject img_size, Boolean lines_are_rows, Boolean size_by_counting )
As with the dialog, one has to pre-specify a few things.
The data type of the image.
This is a number. You can find out which number belongs to which image data type by, f.e., creating an image outputting its data type:
image img := Realimage( "", 4, 100 )
Result("\n" + img.ImageGetDataType() )
The file stream object
This object describes where the data is stored. The F1 help-documention explains how one creates a file-stream from an existing file, but essentially you need to specify a path to the file, then open the file for reading (which gives you a handle), and then using the fileHandle to create the stream object.
string path = "C:\\test.txt"
number fRef = OpenFileForReading( path )
object fStream = NewStreamFromFileReference( fRef, 1 )
The image size object
This is a specific script object you need to allocate. It wraps image size information. In case of auto-detecting the size from the text, you don't need to specify the actual size, but you still need the object.
object imgSizeObj = Alloc("ImageData_ImageDataSize")
imgSizeObj.SetNumDimensions(2) // Not needed for counting!
imgSizeObj.SetDimensionSize(0,10) // Not used for counting
imgSizeObj.SetDimensionSize(1,10) // Not used for counting
Boolean checks
Like with the checkboxes in the UI, you spefic two conditions:
Lines are Rows
Get Size By Counting
Note, that the "counting" flag is only used if "Lines are Rows" is also true. Same as with the dialog.
The following script improrts a text file with couting:
image ImportTextByCounting( string path, number DataType )
{
number fRef = OpenFileForReading( path )
object fStream = NewStreamFromFileReference( fRef, 1 )
number bLinesAreRows = 1
number bSizeByCount = 1
bSizeByCount *= bLinesAreRows // Only valid together!
object imgSizeObj = Alloc("ImageData_ImageDataSize")
image img := ImageImportTextData( "Imag Name ", fStream, DataType, imgSizeObj, bLinesAreRows, bSizeByCount )
return img
}
string path = "C:\\test.txt"
number kREAL4_DATA = 2
image img := ImportTextByCounting( path, kREAL4_DATA )
img.ShowImage()

Check if WinList() contains a certain title

I am listing all open windows using WinList() to get window title and -handle in AutoIt.
I want to check if resulting array contains a specific title. What is the best way to do this? There is no WinList().Contains("TitleName") or something like that.
Local $aList = WinList() ;Gets a list of Window Titles and IDs
OK, I got it now:
For $i = 1 To $aList[0][0]
If $aList[$i][0] = "Title/String you search for" Then
MsgBox($MB_SYSTEMMODAL, "", "MessageBox shows this text if title is in list.")
EndIf
Next
You could also use something similar to what you wrote.
#include <Array.au3>
Opt("WinDetectHiddenText", 0) ;0=don't detect, 1=do detect
Opt("WinSearchChildren", 0) ;0=no, 1=search children also
Opt("WinTextMatchMode", 1) ;1=complete, 2=quick
Opt("WinTitleMatchMode", 1) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase
Local $title = 'AutoIt Help (v3.3.14.2)'
Local $aList = WinList()
;~ _ArrayDisplay($aList)
Local $iIndex = _ArraySearch($aList,$title)
WinActivate($aList[$iIndex][1], '')
Window exists?
"I am listing all open windows … I want to check if … contains a specific title. What is the best way to do this?"
As per Documentation - Function Reference - WinExists() :
Checks to see if a specified window exists.
Example.
Global Const $g_sWndTitle = 'Window title here'
If WinExists($g_sWndTitle) Then WinFlash($g_sWndTitle)
Retrieve window handle, -text and -title
Handle
"… to get window title and -handle …"
As per Documentation - Function Reference - WinGetHandle() :
Retrieves the internal handle of a window.
Example:
Global Const $g_sWndTitle = 'Window title here'
Global $g_hWnd
If WinExists($g_sWndTitle) Then
$g_hWnd = WinGetHandle($g_sWndTitle)
WinFlash($g_hWnd)
EndIf
Text
As per Documentation - Function Reference - WinGetText() :
Retrieves the text from a window.
Example:
Global Const $g_sWndTitle = 'Window title here'
If WinExists($g_sWndTitle) Then
WinFlash($g_sWndTitle)
ConsoleWrite(WinGetText($g_sWndTitle) & #CRLF)
EndIf
Title
Likewise, WinGetTitle().

Replacing a new line character with streamwriter remove everything after it. (ASP.NET, Json, C#)

I'm having an unexpected problem which I'm hoping one of you can help me with.
I have an ASP.NET Web API with a number of end points, one of which takes user input, received as JSON, and converts it into an order object which is written to a file in .CSV format. The following is a small snippet of the full code as an example.
using (StreamWriter writer = new StreamWriter(file))
{
writer.Write(escape + order.Notes + escape + delim);
writer.Write(escape + order.Reference1 + escape + delim);
writer.Write(escape + order.Reference2 + escape + delim);
writer.WriteLine();
writer.Flush();
}
The problem I am having is that some users are inclined to add line breaks in
certain fields, and this is causing havoc with my order file. In order to remove
these new line characters, I have tried both of the following methods.
writer.Write(escape + product.Notes.Replace("\n", " ") + escape + delim);
writer.Write(escape + product.Notes.Replace(System.Environment.NewLine, " ") + escape + delim);
However, it seems that, rather than just remove the new line character and carry on writing the rest of the fields, when a new line is encountered, nothing else gets written.
Either everything else gets replace with the " " or nothing else is being written at all, but I'm not sure which.
If I remove the .Replace() the whole file is written again but with extra line breaks.
I hope somebody has experienced this one and knows the answer!

Use same output asset for 2 job tasks in Azure Media Services

I am using Windows Azure Media Services for video manipulation after upload. My basic workflow involves uploading the file to an WAMS asset, create a job, create 2 tasks - the first creates thumbnails from the video and the second encodes it to HTML5. Currently, everything is working great however I am forced to create 2 different output asset containers for the individual tasks. Once the job completes, I then copy over the files (thumbnails) to the video asset, and delete the thumbnail asset so all resulting files are in the same asset.
This is working, but feels hacky and comes with some overhead of copying over the files, then deleting the unnecessary asset. Is there a way I can tell the encoding task to use the output asset from the thumbnail task?
Short answer is no.
This is by design and I'd be interested in knowing why your use case requires the .jpg's to be in the same container as your videos.
Please use the following instead.
Start with your desired encoding Preset
You can get the XML for that preset via downloading the sample code from http://go.microsoft.com/fwlink/?linkid=253275, and browsing to the WAMEPresetFiles subfolder
Edit the Preset as follows:
<MediaFile ...
ThumbnailTime="00:00:00"
ThumbnailMode="BestFrame"
ThumbnailJpegCompression="95"
ThumbnailCodec="Jpeg"
ThumbnailSize="100%, 100%"
ThumbnailEmbed="False">
The above instructs the encoder to choose the appropriate frame on the video timeline (ThumbnailMode=”BestFrame”), and create a JPEG image at the same resolution as the input video. You can tweak the above settings further – see http://msdn.microsoft.com/en-us/library/dn554337.aspx for the full list
Save the resulting preset XML to a suitable file, say “EncodeWithImage.xml”
Use the following snippet to submit the encode Task:
string inputPresetFile = #"C:\TEMP\EncodeWithImage.xml";
string presetName = Path.GetFileNameWithoutExtension(inputPresetFile);
IAsset asset = ???; // This is the input Asset for the Task
IJob job = _context.Jobs.Create("Encode Job for " + asset.Name + ", encoded using " + presetName);
Console.WriteLine("Encode Job for " + asset.Name + ", encoded using " + presetName);
// Get a media processor reference, and pass to it the name of the processor to use for the specific task.
IMediaProcessor processor = GetLatestMediaProcessorByName("Windows Azure Media Encoder");
Console.WriteLine("Got MP " + processor.Name + ", ID : " + processor.Id + ", version: " + processor.Version);
// Read the configuration data into a string.
string configuration = File.ReadAllText(inputPresetFile);
// Create a task with the encoding details, using a string preset.
ITask task = job.Tasks.AddNew("Encode Task for " + asset.Name + ", encoded using " + presetName, processor, configuration,
Microsoft.WindowsAzure.MediaServices.Client.TaskOptions.None);
// Specify the input asset to be encoded.
task.InputAssets.Add(asset);
// Add an output asset to contain the results of the job.
task.OutputAssets.AddNew("Output asset for encoding " + asset.Name + " using " + presetName, AssetCreationOptions.None);
// Launch the job.
job.Submit();
If i understood correctly you want to chain two task where input of second task is output of first task.
If so copy/pasting corresponding test from github repository
:https://github.com/WindowsAzure/azure-sdk-for-media-services/blob/dev/test/net/Scenario/JobTests.cs
[TestMethod]
[DeploymentItem(#"Media\Thumbnail.xml", "Media")]
[DeploymentItem(#"Media\SmallWmv.wmv", "Media")]
[Priority(0)]
[TestCategory("DailyBvtRun")]
public void ShouldSubmitAndFinishChainedTasks()
{
IAsset asset = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.StorageEncrypted);
IJob job = _mediaContext.Jobs.Create("Test");
IMediaProcessor mediaProcessor = GetMediaProcessor(_mediaContext, WindowsAzureMediaServicesTestConfiguration.MpEncoderName);
ITask task = job.Tasks.AddNew("Task1", mediaProcessor, GetWamePreset(mediaProcessor), TaskOptions.None);
task.InputAssets.Add(asset);
IAsset asset2 = task.OutputAssets.AddNew("Another asset");
string xmlPreset = File.ReadAllText(WindowsAzureMediaServicesTestConfiguration.ThumbnailXml);
ITask task2 = job.Tasks.AddNew("Task2", mediaProcessor, xmlPreset, TaskOptions.None);
task2.InputAssets.Add(asset2);
task2.OutputAssets.AddNew("JobOutput", options: AssetCreationOptions.None);
job.Submit();
WaitForJob(job.Id, JobState.Finished, VerifyAllTasksFinished);
}

Resources