hi i write method which must to know that is size of specified directory i get response from server which contains flags of file name size and other info and on the different ftp servers format of answer is different how to know format of answer?
unsigned long long GetFtpDirSize(String^ ftpDir) {
unsigned long long size = 0;
int j = 0;
StringBuilder^ result = gcnew StringBuilder();
StreamReader^ reader;
FtpWebRequest^ reqFTP;
reqFTP = (FtpWebRequest^)FtpWebRequest::Create(gcnew Uri(ftpDir));
reqFTP->UseBinary = true;
reqFTP->Credentials = gcnew NetworkCredential("anonymous", "123");
reqFTP->Method = WebRequestMethods::Ftp::ListDirectoryDetails;
reqFTP->KeepAlive = false;
reqFTP->UsePassive = false;
try {
WebResponse^ resp = reqFTP->GetResponse();
Encoding^ code;
code = Encoding::GetEncoding(1251);
reader = gcnew StreamReader(resp->GetResponseStream(), code);
String^ line = reader->ReadToEnd();
array<Char>^delimiters = gcnew array<Char>{
'\r', '\n'
};
array<Char>^delimiters2 = gcnew array<Char>{
' '
};
array<String^>^words = line->Split(delimiters, StringSplitOptions::RemoveEmptyEntries);
array<String^>^DetPr;
System::Collections::IEnumerator^ myEnum = words->GetEnumerator();
while ( myEnum->MoveNext() ) {
String^ word = safe_cast<String^>(myEnum->Current);
DetPr = word->Split(delimiters2);
}
}
Basically, you can't. You are interpreting the raw result and there is no defined format for this data (or is there any requirement that this data be returned at all in the response). And the FTP protocol does not define any other way of getting this.
What that leaves you with is a collection of parsing patterns for the server types you know about and working through them looking for valid data. Not entirely easy.
Related
I get a .proto definition as a string input, can I load it into a Root object straight from the string, for example the string might look like this
let protoStr = `syntax = "proto3";
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}`
And I want to be able to load it
let searchRequest = protobuf.loadFromStr(protoStr)
Yes you can use protobuf.parse see https://github.com/protobufjs/protobuf.js/blob/master/examples/custom-get-set.js#L7-L12
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");
}
Using the unwieldy and ponderous but full-featured Excel Interop, background error checking can be toggled off like so:
Excel.Application excelApp = new Excel.Application();
excelApp.ErrorCheckingOptions.BackgroundChecking = false;
...as shown here
I am getting the green triangles indicating a bad number like so:
...which I want to turn off. These are just string vals that should not be flagged as bad or suspicious.
So how can I turn background error checking off for the Excel app object, or otherwise programmatically prevent these green triangles, using EPPlus?
UPDATE
Changing the code from this:
using (var custNumCell = priceComplianceWorksheet.Cells[rowToPopulate, DETAIL_CUSTNUM_COL])
{
custNumCell.Style.Font.Size = DATA_FONT_SIZE;
custNumCell.Value = _custNumber;
custNumCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
...to this:
using (var custNumCell = priceComplianceWorksheet.Cells[rowToPopulate, DETAIL_CUSTNUM_COL])
{
custNumCell.Style.Font.Size = DATA_FONT_SIZE;
custNumCell.ConvertValueToAppropriateTypeAndAssign(_custNumber);
custNumCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
// Adapted from https://stackoverflow.com/questions/26483496/is-it-possible-to-ignore-excel-warnings-when-generating-spreadsheets-using-epplu
public static void ConvertValueToAppropriateTypeAndAssign(this ExcelRangeBase range, object value)
{
string strVal = value.ToString();
if (!String.IsNullOrEmpty(strVal))
{
decimal decVal;
double dVal;
int iVal;
if (decimal.TryParse(strVal, out decVal))
{
range.Value = decVal;
}
else if (double.TryParse(strVal, out dVal))
{
range.Value = dVal;
}
else if (Int32.TryParse(strVal, out iVal))
{
range.Value = iVal;
}
else
{
range.Value = strVal;
}
}
else
{
range.Value = null;
}
}
...semi-fixed it; it is now:
But notice that the leading "0" got stripped out. I need that to remain, so this is still only half-solved.
UPDATE 2
I tried the suggestion from the comment below that pointed here, and added this code:
//Create the import nodes (note the plural vs singular
var ignoredErrors =
priceComplianceWorksheet.CreateNode(XmlNodeType.Element, "ignoredErrors",
xdoc.DocumentElement.NamespaceURI);
var ignoredError
priceComplianceWorksheet.CreateNode(XmlNodeType.Element, "ignoredError",
xdoc.DocumentElement.NamespaceURI);
ignoredErrors.AppendChild(ignoredError);
//Attributes for the INNER node
var sqrefAtt = priceComplianceWorksheet.CreateAttribute("sqref");
sqrefAtt.Value = range;
var flagAtt =
priceComplianceWorksheet.CreateAttribute("numberStoredAsText");
flagAtt.Value = "1";
ignoredError.Attributes.Append(sqrefAtt);
ignoredError.Attributes.Append(flagAtt);
//Now put the OUTER node into the worksheet xml
priceComplianceWorksheet.LastChild.AppendChild(ignoredErrors);
...but "CreateAttribute" and "LastChild" are not recognized...?!?
In response to update 2, you just need to reference the XmlDocument and use that to generate the XML:
var xdoc = priceComplianceWorksheet.WorksheetXml;
//Create the import nodes (note the plural vs singular
var ignoredErrors = xdoc.CreateNode(XmlNodeType.Element, "ignoredErrors",xdoc.DocumentElement.NamespaceURI);
var ignoredError = xdoc.CreateNode(XmlNodeType.Element, "ignoredError",xdoc.DocumentElement.NamespaceURI);
ignoredErrors.AppendChild(ignoredError);
//Attributes for the INNER node
var sqrefAtt = xdoc.CreateAttribute("sqref");
sqrefAtt.Value = "C2:C10"; // Or whatever range is needed....
var flagAtt = xdoc.CreateAttribute("numberStoredAsText");
flagAtt.Value = "1";
ignoredError.Attributes.Append(sqrefAtt);
ignoredError.Attributes.Append(flagAtt);
//Now put the OUTER node into the worksheet xml
xdoc.LastChild.AppendChild(ignoredErrors);
I'm working windows 10 10240 Univasal windows app, when i use Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion to get deivce version, it return a string "2814750438211605" instead of a version format (major.minor.revision.build).
Anyone can tell me what the string "2814750438211605" means?
The Windows 10 OS version value is located in this string property:
Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion
It returns string value like "2814750438211613".
To convert this long number to readable format use this:
string sv = AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
ulong v = ulong.Parse(sv);
ulong v1 = (v & 0xFFFF000000000000L) >> 48;
ulong v2 = (v & 0x0000FFFF00000000L) >> 32;
ulong v3 = (v & 0x00000000FFFF0000L) >> 16;
ulong v4 = v & 0x000000000000FFFFL;
string version = $"{v1}.{v2}.{v3}.{v4}"; // == 10.0.10240.16413
Your application should treat the as opaque data and just log it "as is". It's a 64-bit decimal value as a string.
Remember the intent of this API is to provide a log string from which you can reconstruct the OS version number for support/analytics. On your server-side analysis, you'd convert it if needed or just use it as a unique version identifier... If you are actually trying to parse it runtime, then you are using it incorrectly and quite likely to recreate same problems that resulted in GetVersionEx and VerifyVersionInfo being deprecated in the first place.
Do not parse the string at runtime in your app. Just store "as is" Remember that with Windows 10, a customer really has no idea what you mean if you ask "What version of Windows do you have?". The answer is "10" and will likely still be "10" for a long time to come.
If you found this question and like me you are looking for a way to do this in JavaScript, then you might find this useful.
getDeviceFamilyVersion() {
let deviceFamilyVersion = Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamilyVersion;
let deviceFamilyVersionDecimalFormat = parseInt(deviceFamilyVersion);
if (isNaN(deviceFamilyVersionDecimalFormat)) {
throw new Error('cannot parse device family version number');
}
let hexString = deviceFamilyVersionDecimalFormat.toString(16).toUpperCase();
while (hexString.length !== 16) { // this is needed because JavaScript trims the leading zeros when converting to hex string
hexString = '0' + hexString;
}
let hexStringIterator = 0;
let versionString = '';
while (hexStringIterator < hexString.length) {
let subHexString = hexString.substring(hexStringIterator, hexStringIterator + 4);
let decimalValue = parseInt(subHexString, 16);
versionString += decimalValue + '.';
hexStringIterator += 4;
}
return versionString.substring(0, versionString.length - 1);
}
Just a nifty way of doing this .. I Creadted a Enum that is used to match predefined device families
public enum DeviceFamily
{
Unknown,
Desktop,
Tablet,
Mobile,
SurfaceHub,
Xbox,
Iot
}
This method will check and parse it into the enum.
var q = ResourceContext.GetForCurrentView().QualifierValues;
if (q.ContainsKey("DeviceFamily"))
{
try
{
Enum.Parse(typeof(DeviceFamily) , q["DeviceFamily"]);
//send the user notification about the device family he is in.
}
catch (Exception ex) { }
}
i've got problems with the barcode scanner MT2070 from Motorola. I use the EMDK 2.6 for .NET(Update 2) to create strings from the scanned barcode, then transmit them to the host pc. But the transmit failed.
The MT2070 run with Windows CE5.0 and is connected over bluetooth to the cradle STB2078. But everytime i get "send failed" and the ResultCode is "E_INCORRECT_MODE".
The problem is that dont understand what they mean with "INCORRECT_MODE" i set it to DECODE and by RawData what is mean with source?
ScannerServicesClient scannerServices;
scannerServices = new ScannerServicesClient();
SCANNERSVC_MODE mode;
if(scannerServices.Connect(true))
{
Logger("start service with decode rights"); // primitiv method to see what happen
scannerServices.GetMode(out mode);
if (mode != SCANNERSVC_MODE.SVC_MODE_DECODE)
{
mode = SCANNERSVC_MODE.SVC_MODE_DECODE;
if (scannerServices.SetMode(mode) != RESULTCODE.E_OK)
{
Logger("cant set mode: " + mode.ToString());
}
}
// wanna know which connection is use
string connection = "";
switch (scannerServices.HostParameters.CurrentConnection)
{
case SCANNERSVC_DATA_CONNECTION.NO_CONNECTION:
connection = "Not connected";
break;
case SCANNERSVC_DATA_CONNECTION.BLUETOOTH:
connection = scannerServices.HostParameters.BluetoothConnection.ToString();
break;
case SCANNERSVC_DATA_CONNECTION.RS232:
connection = scannerServices.HostParameters.RS232Connection.ToString();
break;
case SCANNERSVC_DATA_CONNECTION.USB_CABLE:
connection = scannerServices.HostParameters.USBConnection.ToString();
break;
}
Logger(connection);
ScannerHostParameters scnHost = new ScannerHostParameters(scannerServices);
//example hello
string input = "hello"; //what should send
byte[] output = new byte[input.Length]; //field with converted data
byte source = 0; //<-- what mean source? i sum all byte-value but this cant be correct
for (int i = 0; i < input.Length; ++i)
{
output[i] = Convert.ToByte(input[i]);
source += output[i];
}
RawData rawData = new RawData(output, input.Length, source);
//RawParameters rawParam = new RawParameters();
//rawParam.BaudRate = RawParameters.RawBaudRates.RAWSERIAL_9600;
//rawParam.Type = RawParameters.RawHostType.Auto;
RESULTCODE result = scannerServices.SendRawData(rawData, 2000);
if(result == RESULTCODE.E_OK)
{
Logger("successful send");
}
else
{
Logger("Send failed: " + result.ToString());
}
Logger("ScannerService kill");
scannerServices.Disconnect();
}
Logger("\n");
scannerServices.Dispose();
scannerServices = null;
Thanks for your help! (and sorry for my english)
At some point (somewhere where you're setting the mode - I do it right after setting the mode) you'll want to do this:
//set raw mode
if (RESULTCODE.E_OK != scannerServices.SetAttributeByte((ushort)ATTRIBUTE_NUMBER.ATT_MIA_HOSTNUM, (byte)ENUM_HOSTS.HOST_RAW))
{
throw new Exception("Can't set RAW mode");
scannerServices.Disconnect();
scannerServices.Dispose();
return;
}
Where you have:
RawData rawData = new RawData(output, input.Length, source);
you can leave source as 0:
RawData rawData = new RawData(output, input.Length, 0);
Unfortunately I'm not the greatest when it comes to programming so I've only managed to stumble my way through getting my scanner to work. The documentation isn't great, in fact I find it severly lacking. Even the people at Motorola don't seem to know much about it or how to program it. I've been given misinformation by them on on at least one point.
I use the CDC COM Port Emulation mode for the scanner so that it shows up under Ports in Device Manager (I need the scanner to work with an old program we have which uses COM ports). A driver is also needed for this.
Depending on how you're using the scanner, the above may or may not work.