Local AppData Monitor in Metro app (StorageFileQueryResult.ContentsChanged event not firing) - windows-8.1

how would a monitor just a particular file in AppData folder.
I've tried using StorageFolderQueryResult.ContentsChanged event to handle this, but this one actually callbacks for any changes through the folder.
My problem is to just a monitor a single file and use the eventhandler when its changed.
I've tried to use this "UserSearchFilter" property to QueryOptions. That didnt work actually.
cAn someone help with this ? It would also be helpful if you could additionally provide the syntax for the whole problem.
My contentschanged event is not firing on modifying the "filename" in the folder.
auto fileTypeFilter = ref new Platform::Collections::Vector<Platform::String^>();
fileTypeFilter->Append("*");
auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderBySearchRank, fileTypeFilter);
//use the user's input to make a query
queryOptions->UserSearchFilter = InputTextBox->Text;
auto queryResult = musicFolder->CreateFileQueryWithOptions(queryOptions);
auto localFolder = ApplicationData::Current->LocalFolder;
auto currPath = localFolder->Path;
auto fileTypeFilter = ref new Platform::Collections::Vector<Platform::String^>();
fileTypeFilter->Append(".dat");
auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByName, fileTypeFilter);
//use the user's input to make a query
queryOptions->UserSearchFilter = L"filename";
auto queryResult = localFolder->CreateFileQueryWithOptions(queryOptions);
queryResult->ContentsChanged += ref new TypedEventHandler<IStorageQueryResultBase^, Platform::Object^>(this, &Scenario1::OnLocalAppDataChanged);
//find all files that match the query
create_task(queryResult->GetFilesAsync()).then([this, queryOptions] (IVectorView<StorageFile^>^ files)
{
String^ outputText = "";
//output how many files that match the query were found
if ( files->Size == 0)
{
outputText += "No files found for '" + queryOptions->UserSearchFilter + "'";
}
else if (files->Size == 1)
{
outputText += files->Size.ToString() + " file found:\n\n";
}
else
{
outputText += files->Size.ToString() + " files found:\n\n";
}
//output the name of each file that matches the query
for (unsigned int i = 0; i < files->Size; i++)
{
outputText += files->GetAt(i)->Name + "\n";
}
OutputTextBlock->Text = outputText;
});
}
void Scenario1::OnLocalAppDataChanged(Windows::Storage::Search::IStorageQueryResultBase^ sender, Platform::Object^ args)
{
Platform::String^ hello = L"hello world, I'm called back";
}

You have to call the method GetFilesAsync() at least once, otherwise the event will never fire.
Add
queryResult->GetFilesAsync();
before
queryResult->ContentsChanged += ref new TypedEventHandler<IStorageQueryResultBase^,...
I know you don't really need the files at that point, but that's the offical way the ContentsChanged event should be used. Have a look at the first paragraph of the documentation.

Related

How to check Shipment lines before confirming?

I'm trying to cycle though the SOShipLines before confirming to validate the data. I've got the override to work, but can't seem to figure out how I move through the records. The error (which is set to always trip) always returns 0 lines. I'm pretty sure I need to be looking at the shiporder variable but don't know how.
public void ConfirmShipment(SOOrderEntry docgraph, SOShipment shiporder, ConfirmShipmentDelegate baseMethod)
{
int TheCount = 0;
int TheLines = 0;
string TheTest = "";
SOShipLineExt TheSOLineExt = null;
foreach (SOShipLine line in Base.Transactions.Select())
{
TheLines += 1;
TheSOLineExt = PXCache<SOShipLine>.GetExtension<SOShipLineExt>(line);
TheTest += "-" + TheSOLineExt.UsrSpeedyShippedPieces;
if (TheSOLineExt.UsrSpeedyShippedPieces==null)
{
TheCount += 1;
}
//UpdateLineDirect(Base.Caches[typeof(SOLine)], line);
};
//}; if (TheCount > 0 )
throw new PXException("What the hell!!!" + Convert.ToString(TheCount) + "/" + Convert.ToString(TheLines));
baseMethod(docgraph,shiporder);
}
Thanks in advance.
-Travis
It looks like the problem is in an undefined current SOShipment record. Please look at Base.Transactions view - there is Current<SOShipment.shipmentNbr> definition there
public PXSelect<SOShipLine,
Where<SOShipLine.shipmentNbr, Equal<Current<SOShipment.shipmentNbr>>>,
OrderBy<Asc<SOShipLine.shipmentNbr, Asc<SOShipLine.sortOrder>>>> Transactions;
Then look at base ConfirmShipment method and you will see special code which sets current record equal to your SOShipment shiporder parameter
this.Clear();
Document.Current = Document.Search<SOShipment.shipmentNbr>(shiporder.ShipmentNbr);
I suppose that the current SOShipment record is skipping somewhere before the ConfirmShipment method - this why Base.Transactions.Select() returns nothing
There are 2 possible solutions from my standpoint:
Set current SOShipment record equal to your SOShipment shiporder parameter as it is done inside the base ConfirmShipment method
Base.Clear() // maybe this is a good idea to call the Clear method too
Document.Current = Document.Search<SOShipment.shipmentNbr>(shiporder.ShipmentNbr);
Or write your own BQL select with a required parameter instead of current
foreach (SOShipLine line in PXSelect<SOShipLine,
Where<SOShipLine.shipmentNbr, Equal<Required<SOShipment.shipmentNbr>>>,
OrderBy<Asc<SOShipLine.shipmentNbr, Asc<SOShipLine.sortOrder>>>>
.Select(Base, shiporder.ShipmentNbr))
{
// do something here
}

Export Rich Text to plain text c#

Good day to Stackoverflow community,
I am in need of some expert assistance. I have an MVC4 web app that has a few rich text box fields powered by TinyMCE. Up until now the system is working great. Last week my client informed me that they want to export the data stored in Microsoft SQL to Excel to run custom reports.
I am able to export the data to excel with the code supplied. However it is exporting the data in RTF rather than Plain text. This is causing issues when they try to read the content.
Due to lack of knowledge and or understanding I am unable to figure this out. I did read that it is possible to use regex to do this however I have no idea how to implement this. So I turn to you for assistance.
public ActionResult ExportReferralData()
{
GridView gv = new GridView();
gv.DataSource = db.Referrals.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=UnderwritingReferrals.xls");
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Index");
}
I would really appreciate any assistance. and thank you in advance.
I have looked for solutions on YouTube and web forums with out any success.
Kind Regards
Francois Muller
One option you can perform is to massage the Data you write to the XML file.
For example, idenfity in your string and replace it with string.Empty.
Similarly can be replaced with string.Empty.
Once you have identified all the variants of the Rich Text HTML tags, you can just create a list of the Tags, and inside a for FOR loop replace each of them with a suitable string.
Did you try saving the file as .xslx and sending over to the client.
The newer Excel format might handle the data more gracefully?
Add this function to your code, and then you can invoke the function passing it in the HTML string. The return output will be HTML free.
Warning: This does not work for all cases and should not be used to process untrusted user input. Please test it with variants of your input string.
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < source.Length; i++)
{
char let = source[i];
if (let == '<')
{ inside = true; continue; }
if (let == '>') { inside = false; continue; }
if (!inside) { array[arrayIndex] = let; arrayIndex++; }
}
return new string(array, 0, arrayIndex);
}
So I managed to resolve this issue by changing the original code as follow:
As I'm only trying to convert a few columns, I found this to be working well. This will ensure each records is separated by row in Excel and converts the Html to plain text allowing users to add column filters in Excel.
I hope this helps any one else that has a similar issue.
GridView gv = new GridView();
var From = RExportFrom;
var To = RExportTo;
if (RExportFrom == null || RExportTo == null)
{
/* The actual code to be used */
gv.DataSource = db.Referrals.OrderBy(m =>m.Date_Logged).ToList();
}
else
{
gv.DataSource = db.Referrals.Where(m => m.Date_Logged >= From && m.Date_Logged <= To).OrderBy(m => m.Date_Logged).ToList();
}
gv.DataBind();
foreach (GridViewRow row in gv.Rows)
{
if (row.Cells[20].Text.Contains("<"))
{
row.Cells[20].Text = Regex.Replace(row.Cells[20].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[21].Text.Contains("<"))
{
row.Cells[21].Text = Regex.Replace(row.Cells[21].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[22].Text.Contains("<"))
{
row.Cells[22].Text = Regex.Replace(row.Cells[22].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[37].Text.Contains("<"))
{
row.Cells[37].Text = Regex.Replace(row.Cells[37].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[50].Text.Contains("<"))
{
row.Cells[50].Text = Regex.Replace(row.Cells[37].Text, "<(?<tag>.+?)(>|>)", " ");
}
}
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Referrals " + DateTime.Now.ToString("dd/MM/yyyy") + ".xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
//This code will export the data to Excel and remove all HTML Tags to pass everything into Plain text.
//I am using HttpUtility.HtmlDecode twice as the first instance changes null values to "Â" the second time it will run the replace code.
//I am using Regex.Replace to change the headings to more understandable headings rather than the headings produced by the Model.
Response.Write(HttpUtility.HtmlDecode(sw.ToString())
.Replace("Cover_Details", "Referral Detail")
.Replace("Id", "Identity Number")
.Replace("Unique_Ref", "Reference Number")
.Replace("Date_Logged", "Date Logged")
.Replace("Logged_By", "File Number")
.Replace("Date_Referral", "Date of Referral")
.Replace("Referred_By", "Name of Referrer")
.Replace("UWRules", "Underwriting Rules")
.Replace("Referred_To", "Name of Referrer")
);
Response.Flush();
Response.End();
TempData["success"] = "Data successfully exported!";
return RedirectToAction("Index");
}

Why is UILabel not updating?

I have created a view that shows lost connection messages to users which pops over the current view. I want to update the view periodically based on connection status changes.
I can properly get the view and change the text of a label (verified with WriteLines), but nothing changes on the actual display. I even tried removing the view and readding it and calling SetNeedsDisplay, but nothing seems to help.
I have a global variable called OverView:
public static UIView OverView;
I create the label subview, add it to the overview and pop the overview in front of the current view:
UILabel labelTitle = new UILabel();
labelTitle.Text = title;
UIView labelTitleView = (UIView) labelTitle;
labelTitleView.Tag = 5000;
OverView.AddSubview(labelTitleView);
curView.InsertSubviewAbove(OverView, curView);
curView.BringSubviewToFront(OverView);
And then at a later time, I try to modify it like this from another function:
if ((OverView != null) && (OverView.Subviews != null))
{
for (int i = 0; i < OverView.Subviews.Length; i++)
{
WriteToConsole("Type: " + OverView.Subviews[i].GetType());
if (OverView.Subviews[i] is UILabel)
{
WriteToConsole("Found Label with Tag: " + ((UILabel)(OverView.Subviews[i])).Tag + " Text: " + ((UILabel)(OverView.Subviews[i])).Text);
if (((UILabel)(OverView.Subviews[i])).Tag == 5000)
{
WriteToConsole("Setting subview Title to: " + lostConnectionTitle);
lock (overViewLocker)
{
appReference.InvokeOnMainThread(delegate
{
UILabel tempLabel = ((UILabel)(OverView.Subviews[i]));
tempLabel.Text = lostConnectionTitle;
OverView.Subviews[i].RemoveFromSuperview();
OverView.AddSubview(tempLabel);
OverView.BringSubviewToFront(tempLabel);
OverView.SetNeedsLayout();
OverView.SetNeedsDisplay();
WriteToConsole("SetNeedsDisplay");
});
}
}
}
}
}
Have you tried to use delegate methods on your label, and change their value when events occur ?
For example, if your event is clicking on a button, you should have something like that:
yourLabel.Text = "Init";
buttonExample.TouchUpInside += (sender, e) => {
yourLabel.Text = "I touched my button";
};
When your View loads, you'll see "Init" and your button and once you click on it, the label text changed.
Xamarin has some explanation about events and delegate methods here.
I hope that helped.

cloning/copying a dojo data store

Hi can some one please tell me how to copy one data store to another in dojo. I tried it in following way but it doesn't work. Here I'm try to copy data from jsonStore to newGridStore.
jsonStore.fetch({query:{} , onComplete: onComplete});
var onComplete = function (items, request) {
newGridStore = null;
newGridStore = new dojo.data.ItemFileWriteStore({
data : {}
});
if (items && items.length > 0) {
var i;
for (i = 0; i < items.length; i++) {
var item = items[i];
var attributes = jsonStore.getAttributes(item);
if (attributes && attributes.length > 0) {
var j;
for (j = 0; j < attributes.length; j++) {
var newItem = {};
var values = jsonStore.getValues(item, attributes[j]);
if (values) {
if (values.length > 1) {
// Create a copy.
newItem[attributes[j]] = values.slice(0, values.length);
} else {
newItem[attributes[j]] = values[0];
}
}
}
newGridStore.newItem(newItem);
}
}
}
}
Based on the comments asked above. You are trying to copy values to a new Store for the single reason to be able to detect which values have changes and then save them individually, without having to send the entire store.
This approach is totally wrong.
Dojo has isDirty() and offers you the ability to revert() a store back to it's original values. It knows which values have changed and you don't need to do this.
Take a look at the bog standard IFWS here: http://docs.dojocampus.org/dojo/data/ItemFileWriteStore
Make sure you read everything from here: http://docs.dojocampus.org/dojo/data/ItemFileWriteStore#id8
What you want to do is create your own _saveCustom method which you will override your store with, and then when you save, you will be able to see which values have changed.
Click on the demo at the very bottom of the page. It shows you EXACTLY how do to it using _saveCustom

EntityDataReader to ToList()

my code :
public List<Book> GetBook(string Field, object Value)
{
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
conn.Close();
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
return (null);
}
why The result is always empty???
What is the correct code?
Why are you closing connection before you started to read from the reader? Reader is like cursor - it doesn't buffer all results to memory when you open it but it loads them incrementally so you could easily terminate connection (and reading functionality as well) before you read any result. You don't have to close the connection explicitly - that is responsibility of using block.
You can also use SQL profiler to validate the it really builds the query you expect.
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
s.ToList().Count returns 0 because rdr.OfType<Book> is always empty collection. EntitDataReader doesn't materialize entities - it is just wrapper about database related DataReader and it works in the same way. You must read columns and fill them to properties of your entity.
If you don't want to do it you can use objectContext.Translate method but once you start to work with ObjectContext you don't need EntityCommand and EntityDataReader at all.

Resources