How do i write a txt file using Microsoft Dynamics AX? - text-files

I want to write a txt file (just like i'd do in visual studio with c# using string writer and everything, with which i'm already very familiar)
what class and method do i use?
how does it work?
what's the X++ syntax?

You can use the TextIo X++ class or the CLRInterop.
Here are 2 X++ jobs to demonstrate both approaches.
static void Job_TextIO(Args _args)
{
TextIo textIo;
#File
;
textIo = new TextIo(#"C:\textIOtest.txt", #IO_WRITE);
textIo.write("Line 1\n");
textIo.write("Line 2");
}
static void Job_StreamWriter(Args _args)
{
System.IO.StreamWriter sw;
InteropPermission perm = new InteropPermission(InteropKind::ClrInterop);
;
perm.assert();
sw = new System.IO.StreamWriter(#"C:\test.txt");
sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.Flush();
sw.Close();
sw.Dispose();
CodeAccessPermission::revertAssert();
}

Related

C++/CX Metro Windows - create_task implementation prevents using variable not defined in that scope

I am trying to define Uri^ outside of the implementation of create_task. In java, if you have an asynchronous task adding the final modifier would allow you to use that variable (with final modifier) inside the asynchronous code.
How can I use Uri^ source from the below code inside the asynchronous code?
void addDownload(Uri^ source, StorageFolder^ destinationFolder, String^ fileName) {
boolean requestUnconstrainedDownload = false;
IAsyncOperation<StorageFile^>^ asyncOperationStorageFile = destinationFolder->CreateFileAsync(fileName, CreationCollisionOption::GenerateUniqueName);
auto createStorageFileTask = create_task(asyncOperationStorageFile);
createStorageFileTask.then([] (StorageFile^ destinationFile) {
BackgroundDownloader^ downloader = ref new BackgroundDownloader();
DownloadOperation^ downloadOperation = downloader->CreateDownload(source, destinationFile);
downloadOperation->Priority = BackgroundTransferPriority::Default;
HandleDownloadAsync(downloadOperation, true);
});
}
Just capture the variable source in the lambda so it can be accessed in the lambda body of the task:
void addDownload(Uri^ source, StorageFolder^ destinationFolder, String^ fileName) {
boolean requestUnconstrainedDownload = false;
IAsyncOperation<StorageFile^>^ asyncOperationStorageFile = destinationFolder->CreateFileAsync(fileName, CreationCollisionOption::GenerateUniqueName);
auto createStorageFileTask = create_task(asyncOperationStorageFile);
createStorageFileTask.then([source] (StorageFile^ destinationFile) {
BackgroundDownloader^ downloader = ref new BackgroundDownloader();
DownloadOperation^ downloadOperation = downloader->CreateDownload(source, destinationFile);
downloadOperation->Priority = BackgroundTransferPriority::Default;
HandleDownloadAsync(downloadOperation, true);
});
}

Using stanford parser to parse Chinese

here is my code, mostly from the demo. The program runs perfectly, but the result is very wrong. It did not spilt the words.
Thank you
public static void main(String[] args) {
LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/xinhuaFactored.ser.gz");
demoAPI(lp);
}
public static void demoAPI(LexicalizedParser lp) {
// This option shows loading and using an explicit tokenizer
String sent2 = "我爱你";
TokenizerFactory<CoreLabel> tokenizerFactory =
PTBTokenizer.factory(new CoreLabelTokenFactory(), "");
Tokenizer<CoreLabel> tok =
tokenizerFactory.getTokenizer(new StringReader(sent2));
List<CoreLabel> rawWords2 = tok.tokenize();
Tree parse = lp.apply(rawWords2);
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
List<TypedDependency> tdl = gs.typedDependenciesCCprocessed();
System.out.println(tdl);
System.out.println();
// You can also use a TreePrint object to print trees and dependencies
TreePrint tp = new TreePrint("penn,typedDependenciesCollapsed");
tp.printTree(parse);
}
Did you make sure to segment the words? For example try running it again with "我 爱 你." as the sentence. I believe from the command line the parser will segment automatically, however I'm not sure what it does from within Java.

windows phone 7 updating isolated storage

In windows phone 7, what is the protocol for updated an isolated storage text file? Say I have 10 words in a text file arranged at 1 per line. Now suppose, the user uses the application and a new word needs to be stored on the fifth line. How do I write to the file, which already contains 10 words with 1 word per line?
Thanks in advance you guys are awesome.
The way I have been doing it is:
Read in a file from IsolatedStorage to menmory
Update the String
Write the file back to storage
Read in File
public static string ReadFromStorage(string filename)
{
string fileText = "";
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader sr = new StreamReader(new IsolatedStorageFileStream(filename, FileMode.Open, storage)))
{
fileText = sr.ReadToEnd();
}
}
}
catch
{
}
return fileText;
}
Write to File
public static void WriteToStorage(string filename, string text)
{
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string directory = Path.GetDirectoryName(filename);
if (!storage.DirectoryExists(directory))
storage.CreateDirectory(directory);
if (storage.FileExists(filename))
{
MessageBoxResult result = MessageBox.Show(filename + " Exists\nOverwrite Existing File?", "Question", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
return;
}
using (StreamWriter sw = new StreamWriter(storage.CreateFile(filename)))
{
sw.Write(text);
}
}
}
catch
{
}
}
So I would do:
string fileName = "Test.txt";
string testFile = IsolatedStorage_Utility.ReadFromStorage(fileName);
testFile = testFile.Replace("a", "b");
IsolatedStorage_Utility.WriteToStorage(fileName, testFile);
Writing to a file in Isolated Storage is basically a file write operation. It is similar as how you will access a normal file and read write to it in normal operating system. in your scenario if you are sure that you need to update 5th line out of 10 lines, you will read line by line using stream reader and will use stream writer to update the specific line that you want to update. You do not need to re-write all content again and again.
On the other hand if you just want to add new content you can just append it to end of file. You may find this link useful http://goo.gl/IKii5

How do I enumerate a list of Source Files with Pending Changes and get their server location?

I'm trying to write a macro that will generate a plain-text list of files changed based on the list of files in the Pending Changes pane but I can't figure out how to do it. The server location of a file is the property that is formatted like this:
$/TfsName/SomeSolution/Web/SomeFolder/SomeFile1.aspx
$/TfsName/SomeSolution/Web/SomeFolder/SomeFile2.aspx
The closest I can get is opening the properties of the selected item in the pane, which isn't very useful:
DTE.ExecuteCommand ("TeamFoundationContextMenus.SourceControlPendingChangesSourceFiles.TfsContextPendingCheckinsPendingCheckinsProperties")
Edit: here's the entire code for the macro I have so far, the TODOs are where I need help:
Public Class Pending
Public Shared Sub Pending()
OutputClear()
OutputWriteLine("Files Changed:")
Dim outInfo As String = ""
DTE.Windows.Item("{2456BD12-ECF7-4988-A4A6-67D49173F564}").Activate() 'Pending Changes - Source Files
'TODO: loop through each changed file
'TODO: get TFS server location of each file
outInfo &= "some file name"
OutputWriteLine(outInfo)
End Sub
' snip: other supporting functions
End Class
Well I haven't been able to figure out how to do it with a macro yet, but thanks to Bob Hardister on twitter, I can use this command to get what I'm looking for:
"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\tf.exe" status $/ProjectName/SubDir/ /recursive
...but what works even better is a command-line app that uses this code:
const string TFSSERVER = "http://TfsServer:8080";
static void Main(string[] args)
{
//http://blogs.msdn.com/b/buckh/archive/2006/03/15/552288.aspx
//http://blogs.msdn.com/b/jmanning/archive/2005/12/01/499033.aspx
string projectName = args[0];
TeamFoundationServer tfs = new TeamFoundationServer(TFSSERVER);
VersionControlServer versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
PendingSet[] sets = versionControl.GetPendingSets(new String[] { "$/Projects/" + projectName }, RecursionType.Full);
Console.WriteLine(versionControl.AuthenticatedUser + " pending changes for " + projectName + ":");
foreach (PendingSet set in sets)
{
if (set.Type == PendingSetType.Workspace && set.OwnerName == versionControl.AuthenticatedUser)
{
foreach (PendingChange pc in set.PendingChanges)
{
Console.WriteLine(pc.ServerItem);
}
}
}
}
Then I just added the compiled EXE call to the External Tools menu and use it within VS there.
Bonus Edit: Here's the VSS version (not as nice):
const string SSDIR = #"\\VssServer\VssShare";
static void Main(string[] args)
{
string projectName = args[0];
string userName = "user";
VSSDatabaseClass vss = new VSSDatabaseClass();
vss.Open(SSDIR + #"\srcsafe.ini", userName, userName);
VSSItem sourceItem = vss.get_VSSItem("$/Projects/" + projectName, false);
Console.WriteLine(userName + " pending checkins for " + projectName + ":");
int total = GetItems(sourceItem);
Console.WriteLine(total.ToString() + " total changes.");
}
const int VSSFILE_CHECKEDOUT_ME = 2;
const int VSSITEM_PROJECT = 0;
const int VSSITEM_FILE = 1;
public static int GetItems(IVSSItem originalItem)
{
int total = 0;
foreach (IVSSItem subItem in originalItem.get_Items(false))
{
if (subItem.Type == VSSITEM_FILE && subItem.IsCheckedOut == VSSFILE_CHECKEDOUT_ME)
{
Console.WriteLine(subItem.Spec);
total++;
}
else if (subItem.Type == VSSITEM_PROJECT)
{
total += GetItems(subItem);
}
}
return total;
}

Can I copy multiple rows from the Visual Studio "Find Symbol Results" window?

Does anyone know how to copy all the lines in the Visual Studio "Find Symbol Results" window onto the clipboard? You can copy a single line, but I want to copy them all.
I can't believe that I'm the first one to want to do this, but I can't even find a discussion about this apparently missing feature.
Here is some code that uses the .Net Automation library to copy all the text to the clipboard.
Start a new WinForms project and then add the following references:
WindowsBase
UIAutomationTypes
UIAutomationClient
System.Xaml
PresentationCore
PresentationFramework
System.Management
The code also explains how to setup a menu item in visual studio to copy the contents to the clipboard.
Edit: The UI Automation only returns visible tree view items. Thus, to copy all the items, the find symbol results window is set as foreground, and then a {PGDN} is sent, and the next batch of items is copied. This process is repeated until no new items are found. It would have been preferable to use the ScrollPattern, however it threw an Exception when trying to set the scroll.
Edit 2: Tried to improve the performance of AutomationElement FindAll by running on a separate thread. Seems to be slow in some cases.
Edit 3: Improved performance by making the TreeView window very large. Can copy about 400 items in about 10 seconds.
Edit 4: Dispose objects implementing IDisposable. Better message reporting. Better handling of process args. Put window back to its original size.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Automation;
using System.Windows.Forms;
namespace CopyFindSymbolResults {
// This program tries to find the 'Find Symbol Results' window in visual studio
// and copy all the text to the clipboard.
//
// The Find Symbol Results window uses a TreeView control that has the class name 'LiteTreeView32'
// In the future if this changes, then it's possible to pass in the class name as the first argument.
// Use TOOLS -> Spy++ to determine the class name.
//
// After compiling this code into an Exe, add a menu item (TOOLS -> Copy Find Symbol Results) in Visual Studio by:
// 1) TOOLS -> External Tools...
// (Note: in the 'Menu contents:' list, count which item the new item is, starting at base-1).
// Title: Copy Find Symbol Results
// Command: C:\<Path>\CopyFindSymbolResults.exe (e.g. C:\Windows\ is one option)
// 2) TOOLS -> Customize... -> Keyboard... (button)
// Show Commands Containing: tools.externalcommand
// Then select the n'th one, where n is the count from step 1).
//
static class Program {
enum Tabify {
No = 0,
Yes = 1,
Prompt = 2,
}
[STAThread]
static void Main(String[] args) {
String className = "LiteTreeView32";
Tabify tabify = Tabify.Prompt;
if (args.Length > 0) {
String arg0 = args[0].Trim();
if (arg0.Length > 0)
className = arg0;
if (args.Length > 1) {
int x = 0;
if (int.TryParse(args[1], out x))
tabify = (Tabify) x;
}
}
DateTime startTime = DateTime.Now;
Data data = new Data() { className = className };
Thread t = new Thread((o) => {
GetText((Data) o);
});
t.IsBackground = true;
t.Start(data);
lock(data) {
Monitor.Wait(data);
}
if (data.p == null || data.p.MainWindowHandle == IntPtr.Zero) {
System.Windows.Forms.MessageBox.Show("Cannot find Microsoft Visual Studio process.");
return;
}
try {
SimpleWindow owner = new SimpleWindow { Handle = data.MainWindowHandle };
if (data.appRoot == null) {
System.Windows.Forms.MessageBox.Show(owner, "Cannot find AutomationElement from process MainWindowHandle: " + data.MainWindowHandle);
return;
}
if (data.treeViewNotFound) {
System.Windows.Forms.MessageBox.Show(owner, "AutomationElement cannot find the tree view window with class name: " + data.className);
return;
}
String text = data.text;
if (text.Length == 0) { // otherwise Clipboard.SetText throws exception
System.Windows.Forms.MessageBox.Show(owner, "No text was found: " + data.p.MainWindowTitle);
return;
}
TimeSpan ts = DateTime.Now - startTime;
if (tabify == Tabify.Prompt) {
var dr = System.Windows.Forms.MessageBox.Show(owner, "Replace dashes and colons for easy pasting into Excel?", "Tabify", System.Windows.Forms.MessageBoxButtons.YesNo);
if (dr == System.Windows.Forms.DialogResult.Yes)
tabify = Tabify.Yes;
ts = TimeSpan.Zero; // prevent second prompt
}
if (tabify == Tabify.Yes) {
text = text.Replace(" - ", "\t");
text = text.Replace(" : ", "\t");
}
System.Windows.Forms.Clipboard.SetText(text);
String msg = "Data is ready on the clipboard.";
var icon = System.Windows.Forms.MessageBoxIcon.None;
if (data.lines != data.count) {
msg = String.Format("Only {0} of {1} rows copied.", data.lines, data.count);
icon = System.Windows.Forms.MessageBoxIcon.Error;
}
if (ts.TotalSeconds > 4 || data.lines != data.count)
System.Windows.Forms.MessageBox.Show(owner, msg, "", System.Windows.Forms.MessageBoxButtons.OK, icon);
} finally {
data.p.Dispose();
}
}
private class SimpleWindow : System.Windows.Forms.IWin32Window {
public IntPtr Handle { get; set; }
}
private const int TVM_GETCOUNT = 0x1100 + 5;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int msg, int wparam, int lparam);
[DllImport("user32.dll", SetLastError = true)]
static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int Width, int Height, bool Repaint);
private class Data {
public int lines = 0;
public int count = 0;
public IntPtr MainWindowHandle = IntPtr.Zero;
public IntPtr TreeViewHandle = IntPtr.Zero;
public Process p;
public AutomationElement appRoot = null;
public String text = null;
public String className = null;
public bool treeViewNotFound = false;
}
private static void GetText(Data data) {
Process p = GetParentProcess();
data.p = p;
if (p == null || p.MainWindowHandle == IntPtr.Zero) {
data.text = "";
lock(data) { Monitor.Pulse(data); }
return;
}
data.MainWindowHandle = p.MainWindowHandle;
AutomationElement appRoot = AutomationElement.FromHandle(p.MainWindowHandle);
data.appRoot = appRoot;
if (appRoot == null) {
data.text = "";
lock(data) { Monitor.Pulse(data); }
return;
}
AutomationElement treeView = appRoot.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ClassNameProperty, data.className));
if (treeView == null) {
data.text = "";
data.treeViewNotFound = true;
lock(data) { Monitor.Pulse(data); }
return;
}
data.TreeViewHandle = new IntPtr(treeView.Current.NativeWindowHandle);
data.count = SendMessage(data.TreeViewHandle, TVM_GETCOUNT, 0, 0);
RECT rect = new RECT();
GetWindowRect(data.TreeViewHandle, out rect);
// making the window really large makes it so less calls to FindAll are required
MoveWindow(data.TreeViewHandle, 0, 0, 800, 32767, false);
int TV_FIRST = 0x1100;
int TVM_SELECTITEM = (TV_FIRST + 11);
int TVGN_CARET = TVGN_CARET = 0x9;
// if a vertical scrollbar is detected, then scroll to the top sending a TVM_SELECTITEM command
var vbar = treeView.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, "Vertical Scroll Bar"));
if (vbar != null) {
SendMessage(data.TreeViewHandle, TVM_SELECTITEM, TVGN_CARET, 0); // select the first item
}
StringBuilder sb = new StringBuilder();
Hashtable ht = new Hashtable();
int chunk = 0;
while (true) {
bool foundNew = false;
AutomationElementCollection treeViewItems = treeView.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TreeItem));
if (treeViewItems.Count == 0)
break;
if (ht.Count == 0) {
chunk = treeViewItems.Count - 1;
}
foreach (AutomationElement ele in treeViewItems) {
try {
String n = ele.Current.Name;
if (!ht.ContainsKey(n)) {
ht[n] = n;
foundNew = true;
data.lines++;
sb.AppendLine(n);
}
} catch {}
}
if (!foundNew || data.lines == data.count)
break;
int x = Math.Min(data.count-1, data.lines + chunk);
SendMessage(data.TreeViewHandle, TVM_SELECTITEM, TVGN_CARET, x);
}
data.text = sb.ToString();
MoveWindow(data.TreeViewHandle, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, false);
lock(data) { Monitor.Pulse(data); }
}
// this program expects to be launched from Visual Studio
// alternative approach is to look for "Microsoft Visual Studio" in main window title
// but there could be multiple instances running.
private static Process GetParentProcess() {
// from thread: http://stackoverflow.com/questions/2531837/how-can-i-get-the-pid-of-the-parent-process-of-my-application
int myId = 0;
using (Process current = Process.GetCurrentProcess())
myId = current.Id;
String query = String.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
using (var search = new ManagementObjectSearcher("root\\CIMV2", query)) {
using (ManagementObjectCollection list = search.Get()) {
using (ManagementObjectCollection.ManagementObjectEnumerator results = list.GetEnumerator()) {
if (!results.MoveNext()) return null;
using (var queryObj = results.Current) {
uint parentId = (uint) queryObj["ParentProcessId"];
return Process.GetProcessById((int) parentId);
}
}
}
}
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT {
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
}
I solved this by using Macro Express. They have a free 30-day trial which I used because this is a one-off for me. I wrote a simple macro to copy all of the Find Symbol Results, one line at a time, over into a Notepad document.
Sequence:
* Repeat (x) times (however many symbol results you have)
* Activate Find Symbol Results window
* Delay .5 seconds
* Simulate keystrokes "Arrow Down"
* Clipboard Copy
* Activate Notepad window
* Delay .5 seconds
* Clipboard Paste
* Simulate keystrokes "ENTER"
* End Repeat
Had the same requirement and were solving this by using a screenshot tool named Hypersnap which also has some basic OCR functionality.
If you can encode your symbol as an expression for global Find, then copy-pasting all results from the Find Results window is easy.
eg finding all references of property 'foo' you might do a global find for '.foo'
I'm using Visual Studio 2017 (Version 15.6.4) and it has the functionality directly. Here's an example screenshot (I hit Ctrl+A to select all lines):
The text output for that example is this:
Status Code File Line Column Project
Console.WriteLine(xml); C:\Users\blah\Documents\ConsoleApp1\Program.cs 30 12 ConsoleApp1
static void Console.WriteLine(object)
Console.WriteLine(xml); C:\Users\blah\Documents\ConsoleApp1\Program.cs 18 12 ConsoleApp1
Console.WriteLine(xml); C:\Users\blah\Documents\ConsoleApp1\Program.cs 25 12 ConsoleApp1
I had the same problem. I had to make a list of all the occurences of a certain method and some of its overloaded version.
To solve my problem I used ReSharper. (ReSharper -> Find -> Find Usages Advanced).
It also has a very nice tabulated text export feature.
From my previous experience and a few tests I just did, there is no built in feature to do this.
Why do you want to do this? Why do you want to copy all of the references to the clipboard? As I understand it the speed of these features would make having a static copy of all the references would be relatively useless if you can generate a dynamic and complete copy quickly.
You can always extend visual studio to add this functionality, see
this post at egghead cafe.
Hey Somehow you can achieve this in another way,
Just 'FindAll' the selected text and you will be able to catch all the lines
Visual Studio Code works as a browser.
it is possible to open the developer tools and search for that part of the code
Menu: Help > Toggle Developer tools
write the following instructions to the developer tools console:
var elementos = document.getElementsByClassName("plain match")
console.log(elementos.length)
for(var i = 0; i<elementos.length;i++) console.log(elementos[i].title)
and you can see the match results.
Now if you can copy the results

Resources