response.BinaryWrite problems (Text file contains PDF encoding) - c#

So I have something very strange happening in my Asp.Net Website.
I have 2 seperate pages with the same code to download files stored in a SQL database.
One page is an admin version of the page where you can delete and upload files and also see the files ID.
The user end version of this page only displays the download button and the filename. The ID is hidden and used as a DataKey in the grid to select the file from the database.
Both pages work perfectly in development. But when I switched to our production staging server the user end version of the page will turn a simple one line text file into a bunch of gargly-goop PDF encoding when saving and opening it, while the admin version of the page still functions properly. PDF's download and view normal and word documents do the same thing that the text files do.
Here is the code behind for the admin download section:
protected void btnSaveAttachment_Click(object sender, EventArgs e)
{
GridViewRow selectedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
string AttachmentID = "";
string AttachmentName = "";
if (selectedRow.Cells[1].Text != null && selectedRow.Cells[2].Text != null)
{
AttachmentID = selectedRow.Cells[1].Text;
AttachmentName = selectedRow.Cells[2].Text;
}
byte[] objData = Utility.SaveAttachmentBytes(AttachmentID);
HttpResponse response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ClearHeaders();
response.AddHeader("Cache-Control", " no-store, no-cache ");
response.AddHeader("Content-Disposition", "attachment; filename=" + AttachmentName + ";");
response.BinaryWrite(objData);
response.Flush();
if (response != null)
{
response.End();
}
}
Here is the code behind for the user download section:
protected void btnSaveAttachment_Click(object sender, EventArgs e)
{
GridViewRow selectedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
//string AttachmentID = selectedRow.Cells[1].Text;
string AttachmentID = grdAttachments.DataKeys[0].Value.ToString();
string AttachmentName = "";
if (selectedRow.Cells[1].Text != null)
{
AttachmentName = selectedRow.Cells[1].Text;
}
byte[] objData = Utility.SaveAttachmentBytes(AttachmentID);
HttpResponse response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ClearHeaders();
response.AddHeader("Cache-Control", " no-store, no-cache ");
response.AddHeader("Content-Disposition", "attachment; filename=" + AttachmentName + ";");
response.BinaryWrite(objData);
response.Flush();
//File.Delete(SavePath);
if (response != null)
{
response.End();
}
}
I am at a point where I just dont know what the heck is going on. The only other difference in the pages front end code is the user page load some text from the database into a label and has a telerik textbox control. (I have tried stripping out all other items on the page but still files other than PDF try to encode as a PDF.)
Here is what a 1 line text file looks like when saving and opening it.
%PDF-1.4
%âãÏÓ
9 0 obj<</H[516 160]/Linearized 1/E 5419/L 14363/N 2/O 12/T 14137>>
endobj
xref
9 11
0000000016 00000 n
0000000676 00000 n
0000000516 00000 n
0000000753 00000 n
0000000881 00000 n
0000000976 00000 n
0000001511 00000 n
0000001903 00000 n
0000002142 00000 n
0000002387 00000 n
0000002463 00000 n
trailer
<</Size 20/Prev 14127/Root 10 0 R/Info 8 0 R/ID[<3d8f2faf909b30f75011a461bd4aff97><b62071c85b58ab4d8f0b23af1811506f>]>>
startxref
0
%%EOF
11 0 obj<</Length 82/Filter/FlateDecode/L 90/S 53>>stream
xÚb```f``
‘BVœÀ cf`aàXÀàΰ…Ql
HT ÈAPÌÀàÃÀÃì ,³Ñ†Ë`%·Hˆ…Aý!fb€ O{Ì
endstream
endobj
10 0 obj<</Pages 6 0 R/Type/Catalog/PageLabels 4 0 R/Metadata 7 0 R>>
endobj
12 0 obj<</Contents 19 0 R/Type/Page/Parent 6 0 R/Rotate 0/MediaBox[0 0 612 792]/CropBox[0 0 612 792]/Resources 13 0 R>>
endobj
13 0 obj<</Font<</TT2 14 0 R/TT4 15 0 R>>/ProcSet[/PDF/Text]/ExtGState<</GS1 18 0 R>>>>
endobj
14 0 obj<</Type/Font/Encoding/WinAnsiEncoding/BaseFont/TimesNewRomanPSMT/FirstChar 32/LastChar 150/Subtype/TrueType/FontDescriptor 16 0 R/Widths[250 0 0 0 0 833 778 0 333 333 0 564 250 333 250 278 500 500 500 500 500 500 500 500 500 500 278 0 0 0 0 0 0 722 667 667 722 611 556 722 0 333 389 0 611 889 722 722 556 722 667 556 611 722 722 944 722 722 0 0 0 0 0 0 0 444 500 444 500 444 333 500 500 278 278 500 278 778 500 500 500 500 333 389 278 500 500 722 500 500 444 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 500]>>
endobj
15 0 obj<</Type/Font/Encoding/WinAnsiEncoding/BaseFont/TimesNewRomanPS-BoldMT/FirstChar 32/LastChar 121/Subtype/TrueType/FontDescriptor 17 0 R/Widths[250 0 0 0 0 0 0 0 0 0 0 0 0 0 250 0 500 500 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 722 722 0 0 0 0 389 0 0 0 0 0 778 0 0 0 556 667 722 0 0 0 0 0 0 0 0 0 0 0 500 0 444 0 444 333 500 0 278 0 0 0 833 556 0 0 0 444 389 333 556 500 722 0 500]>>
endobj
16 0 obj<</Type/FontDescriptor/FontBBox[-568 -307 2028 1007]/FontName/TimesNewRomanPSMT/Flags 34/StemV 82/CapHeight 656/XHeight 0/Ascent 891/Descent -216/ItalicAngle 0/FontFamily(Times New Roman)/FontStretch/Normal/FontWeight 400>>
endobj
17 0 obj<</Type/FontDescriptor/FontBBox[-558 -307 2034 1026]/FontName/TimesNewRomanPS-BoldMT/Flags 34/StemV 136/CapHeight 656/XHeight 0/Ascent 891/Descent -216/ItalicAngle 0/FontFamily(Times New Roman)/FontStretch/Normal/FontWeight 700>>
endobj
18 0 obj<</Type/ExtGState/SA false/OP false/SM 0.02/op false/OPM 1>>
endobj
etc....................
endstream
endobj
4 0 obj<</Nums[0 5 0 R]>>
endobj
5 0 obj<</S/D>>
endobj
6 0 obj<</Count 2/Kids[12 0 R 1 0 R]/Type/Pages>>
endobj
7 0 obj<</Length 3339/Type/Metadata/Subtype/XML>>stream
<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>
<?adobe-xap-filters esc="CRLF"?>
<x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='XMP toolkit 2.9.1-13, framework 1.6'>
<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:iX='http://ns.adobe.com/iX/1.0/'>
<rdf:Description rdf:about='uuid:d5ef0fdf-fd89-4be0-a57d-fcab92aa8d2b' xmlns:pdf='http://ns.adobe.com/pdf/1.3/' pdf:Producer='Acrobat Distiller 6.0 (Windows)'></rdf:Description>
<rdf:Description rdf:about='uuid:d5ef0fdf-fd89-4be0-a57d-fcab92aa8d2b' xmlns:xap='http://ns.adobe.com/xap/1.0/' xap:CreatorTool='PScript5.dll Version 5.2' xap:ModifyDate='2005-06-10T14:07:36-04:00' xap:CreateDate='2005-06-10T14:07:36-04:00'></rdf:Description>
<rdf:Description rdf:about='uuid:d5ef0fdf-fd89-4be0-a57d-fcab92aa8d2b' xmlns:xapMM='http://ns.adobe.com/xap/1.0/mm/' xapMM:DocumentID='uuid:2aee5402-c607-44cd-a815-8ad3a0bf0a56'/>
<rdf:Description rdf:about='uuid:d5ef0fdf-fd89-4be0-a57d-fcab92aa8d2b' xmlns:dc='http://purl.org/dc/elements/1.1/' dc:format='application/pdf'><dc:title><rdf:Alt><rdf:li xml:lang='x-default'>Microsoft Word - 1 - DTOD Overview.doc</rdf:li></rdf:Alt></dc:title><dc:creator><rdf:Seq><rdf:li>AttardA</rdf:li></rdf:Seq></dc:creator></rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end='w'?>
endstream
endobj
8 0 obj<</ModDate(D:20050610140736-04'00')/CreationDate(D:20050610140736-04'00')/Title(Microsoft Word - 1 - DTOD Overview.doc)/Creator(PScript5.dll Version 5.2)/Producer(Acrobat Distiller 6.0 \(Windows\))/Author(AttardA)>>
endobj
xref
0 9
0000000000 65535 f
0000005419 00000 n
0000005544 00000 n
0000005638 00000 n
0000010369 00000 n
0000010402 00000 n
0000010425 00000 n
0000010482 00000 n
0000013897 00000 n
trailer
<</Size 9>>
startxref
116
%%EOF
RESOLVED
The issue was the DataKeys[0] was always selecting the 0 item in the array of keys. I changed that to:
string AttachmentID = grdAttachments.DataKeys[selectedRow.RowIndex].Value.ToString();
And now all is working fine! Wish I would have debugged closer into the attachmentID!
It just so happened that there was 2 documents that were the same and I though I was downloading the correct document.

In your admin section:
string AttachmentID = selectedRow.Cells[1].Text;
In your user section:
string AttachmentID = grdAttachments.DataKeys[0].Value.ToString();
I would have to assume that the user section assignment is not doing what you expect it to, since the logic isn't the same for both. Verify what AttachmentID is set to in each case, perhaps via logging.

Related

how to groupby items List<keyvaluepair <string,datetime[]>> over date

I have a datatable filled by date , day ,name and type so I read from this datatable into List> using C#.net so
the code is this :
dicArray = dtrd.AsEnumerable()
.Select(Row => Row["IDp"]).Distinct()
.Select(Id => new KeyValuePair<string, string[]>(
Id.ToString(),
dtrd.AsEnumerable()
.Where(Row => Row["IDp"].ToString() == Id.ToString())
.Select(Row => Row["date"].ToString()+";"+ Row["day"].ToString()+";"+Row["nobatkari"].ToString() + ";" + Row["pname"].ToString())
.ToArray()))
.ToList();
now I want to count each item over date I mean that I want to know how many rows are with the same date
please help me to solve it
for example:
1 **2017-02-19** 15:12:20 1 0 1 0
1 **2017-02-19** 15:12:37 1 0 1 0
1 **2017-02-19** 15:12:41 1 0 1 0 Count:3
1 **2017-02-20** 15:14:10 1 2 1 0
1 **2017-02-20** 16:38:14 1 2 1 0
3 **2017-02-20** 16:38:19 1 2 1 0 Count:3
3 **2017-02-21** 16:39:09 1 0 1 0
3 **2017-02-21** 17:25:06 1 0 1 0
2 **2017-02-21** 18:28:50 1 0 1 0 Count:3
2 **2017-02-22** 18:29:04 1 0 1 0 Count:1
2 **2017-02-23** 18:29:17 1 0 1 0
3 **2017-02-23** 18:30:45 1 0 1 0 Count:2
2 **2017-02-24** 18:31:32 1 0 1 0
2 **2017-02-24** 18:31:47 1 0 1 0 Count:2
2 **2017-02-25** 18:32:18 1 4 1 0 Count:1
Of course I want date section not time include
var res = yourList.GroupBy(x => x.date.Date).Select(x=> new { date = x.Key, count = x.Count() });
This will create a new list containtng date and count of elements for each date.

Wrong page count in PDF files

I am using iTextSharp in my C# application. PDF reader gives error:
The document has no page root (meaning: it's an invalid PDF).
Then we again try to fetch count property using below regex:
using (StreamReader sr = new StreamReader(File.OpenRead(#"C:\test.pdf")))
{
Regex regex = new Regex(#"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
Console.WriteLine(matches.Count);
}
But using this regex we get double count..(i.e if actual file has 6 count this regext returns count as 12)
Any solution to get page for this kind of files ?
I can not share file as it is client provided file.
On future verification on file content, i found below matches for regex:
/Type /XObject
/Type /Page
/Type /Catalog
/Type /XObject
/Type /Pages
/Type /Page
/Type /XObject
/Type /Pages
/Type /Page
/Type /XObject
/Type /Pages
/Type /Page
/Type /XObject
/Type /Pages
/Type /Page
/Type /XObject
/Type /Pages
/Type /Page
%PaperPortPDFversion1 0 obj<</Contents 10 0 R/CropBox[0 0 595 842]/MediaBox[0 0 595 842]/Parent 2 0 R/Resources 9 0 R/Rotate 180/Type/Page>>
12 0 obj<</Contents 20 0 R/CropBox[0 0 595 842]/MediaBox[0 0 595 842]/Parent 16 0 R/Resources 19 0 R/Rotate 180/Type/Page>>
21 0 obj<</Contents 29 0 R/CropBox[0 0 595 842]/MediaBox[0 0 595 842]/Parent 25 0 R/Resources 28 0 R/Rotate 180/Type/Page>>
30 0 obj<</Contents 38 0 R/CropBox[0 0 595 842]/MediaBox[0 0 595 842]/Parent 34 0 R/Resources 37 0 R/Rotate 180/Type/Page>>
39 0 obj<</Contents 47 0 R/CropBox[0 0 595 842]/MediaBox[0 0 595 842]/Parent 43 0 R/Resources 46 0 R/Rotate 180/Type/Page>>
48 0 obj<</Contents 56 0 R/CropBox[0 0 595 842]/MediaBox[0 0 595 842]/Parent 52 0 R/Resources 55 0 R/Rotate 180/Type/Page>>
Because of last matches it gives double count then actual.(i.e 12 count instead 6 count)
Is there any solution for solving this kind of file,as this is file specific issue not with all file.
Thanks

MIDI File Read with nAudio Interpet Sustain Values?

.NET Framework 4.6, C#.
Using nAudio to read a MIDI file to convert the below into a notation structure that shows a single column with 16th notes and multiple sustain values if the note needs to be a quarter/half/full. So the result would start to look like this to display "C6" as a quarter note:
C6
S
S
S
I don't nuderstand how to read the Velocity and NoteLength properties/fields to get note duration values. Can someone point me in the right direction?
/*
Format 0, Tracks 1, Delta Ticks Per Quarter Note 480
1:1:0 0 MidiChannel
00
1:1:0 0 SequenceTrackName Classic Electric Piano
1:1:0 0 TrackInstrumentName Classic Electric Piano
1:1:0 0 SetTempo 89bpm (666667)
1:1:0 0 TimeSignature 4/4 TicksInClick:24 32ndsInQuarterNote:8
1:1:0 0 KeySignature 0 0
1:1:0 0 SmpteOffset 33:0:0:0:0
1:1:0 0 NoteOn Ch: 1 C6 Vel:87 Len: 167
1:1:240 240 NoteOn Ch: 1 C6 Vel:69 Len: 199
1:2:0 480 NoteOn Ch: 1 G6 Vel:74 Len: 149
1:2:240 720 NoteOn Ch: 1 G6 Vel:49 Len: 191
1:3:0 960 NoteOn Ch: 1 A6 Vel:65 Len: 165
1:3:240 1200 NoteOn Ch: 1 A6 Vel:50 Len: 171
1:4:0 1440 NoteOn Ch: 1 G6 Vel:89 Len: 401
*/
var dede = midiFile.DeltaTicksPerQuarterNote;
var tempolist = new List<TempoEvent>();
foreach (MidiEvent note in midiFile.Events[0])
{
if ( note.CommandCode == MidiCommandCode.NoteOn )
{
var nono = (NoteOnEvent)note;
var noname = nono.NoteName;
var notime= nono.AbsoluteTime;
double realtime = ( note.AbsoluteTime / dede ) * tempo[ tempo.Count() - 1 ].Tempo;
var nonum = nono.NoteNumber;
var nolen = nono.NoteLength;
}
}
Thanks.

Calling CURL using C#

I have to monitor an url that keeps streaming status of the system.
If i issue following command from Windows CMD curl.exe http://localhost:8081/statusstream, I keep getting output from stream:
[02:10:51.021] Starting to execute testcase
[02:10:51.021] Test01: Preparing
[02:11:03.089] Test01: Executing 1/10
[02:11:11.109] Test01: Executing 2/10
[02:11:19.126] Test01: Executing 3/10
[02:11:27.145] Test01: Executing 4/10
[02:11:35.163] Test01: Executing 5/10
[02:11:43.181] Test01: Executing 6/10
[02:11:51.198] Test01: Executing 7/10
[02:11:59.220] Test01: Executing 8/10
[02:12:07.237] Test01: Executing 9/10
[02:12:15.255] Test01: Executing 10/10
[02:12:33.274] Test01: Transferring data for analysis
[02:12:41.562] WARNING: TestSequencer: No data found
[02:12:41.563] Test01: Analyze results
[02:12:42.064] Test01: Finished executing
[02:12:42.064] Finished executing testcase
However when I run the same command using C#, I don't get any standard output, all I get is standard error. Following is my C# code
ProcessStartInfo _processStartInfo = new ProcessStartInfo();
_processStartInfo.RedirectStandardOutput = true;
_processStartInfo.RedirectStandardError = true;
_processStartInfo.UseShellExecute = false;
_processStartInfo.CreateNoWindow = true;
_processStartInfo.FileName = "curl.exe"
_processStartInfo.Arguments = "http://localhost:8081/statusstream";
_process = new Process();
_process.StartInfo = _processStartInfo;
_process.EnableRaisingEvents = true;
_process.StartInfo.RedirectStandardOutput = true;
_process.StartInfo.RedirectStandardError = true;
_process.ErrorDataReceived += _process_ErrorDataReceived;
_process.OutputDataReceived += _process_OutputDataReceived;
_process.Exited += _process_Exited;
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
The following method is always being hit, but not the the one which is waiting for StandardOutput
private void _process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
this.ConsoleLog = string.Format("[StdErr] {0}",e.Data);
}
Output that i get from running CURL command from C# is:
[StdErr] % Total % Received % Xferd Average Speed Time Time Time Current
[StdErr] Dload Upload Total Spent Left Speed
[StdErr] 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
[StdErr] 100 40 0 40 0 0 33 0 --:--:-- 0:00:01 --:--:-- 33
[StdErr] 100 40 0 40 0 0 18 0 --:--:-- 0:00:02 --:--:-- 18
[StdErr] 100 40 0 40 0 0 12 0 --:--:-- 0:00:03 --:--:-- 12
[StdErr] 100 40 0 40 0 0 9 0 --:--:-- 0:00:04 --:--:-- 9
[StdErr] 100 40 0 40 0 0 7 0 --:--:-- 0:00:05 --:--:-- 7
[StdErr] 100 40 0 40 0 0 6 0 --:--:-- 0:00:06 --:--:-- 0
[StdErr] 100 40 0 40 0 0 5 0 --:--:-- 0:00:07 --:--:-- 0
[StdErr] 100 40 0 40 0 0 4 0 --:--:-- 0:00:08 --:--:-- 0
[StdErr] 100 40 0 40 0 0 4 0 --:--:-- 0:00:09 --:--:-- 0
[StdErr] 100 40 0 40 0 0 3 0 --:--:-- 0:00:10 --:--:-- 0
[StdErr] 100 40 0 40 0 0 3 0 --:--:-- 0:00:11 --:--:-- 0
[StdErr] 100 40 0 40 0 0 3 0 --:--:-- 0:00:12 --:--:-- 0
[StdErr] 100 112 0 112 0 0 16 0 --:--:-- 0:00:06 --:--:-- 16
[StdErr] 100 250 0 250 0 0 32 0 --:--:-- 0:00:07 --:--:-- 47
[StdErr] 100 250 0 250 0 0 29 0 --:--:-- 0:00:08 --:--:-- 47
[StdErr] 100 250 0 250 0 0 26 0 --:--:-- 0:00:09 --:--:-- 47
If I see the received column, its value increases from 40 to 250, that means probably something is being return from the stream.
Issuing other HTTP GET commands from CURL using C# gives proper standardoutput. But other get commands return content immediately and are not streaming continuously.
Can someone please point what I'm doing wrong.
Ok, so I'm not supposed to call cURL.exe from C# code. But is there a way where I can monitor a URL to get continuous stream of data whenever there are updates? I don't want to call HttpClient GetStringAsync in a while loop.

Copy/paste Data from 1 sheet to another by matching specific cell or data (Date)

I have two sheets in Excel. Sheet2 contains data and I need that is on per date for 1 month, I would like to copy/paste the data on sheet1 by matching the date I put on the Blank date, example: Put Oct 1 on the date of sheet1 it will automatically copy the data of Oct 1 on sheet2. put Oct 2 copy data on Oct 2 an so on..
SHEET 1
DATE
Turnover IN out Revenue
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
SHEET 2
1-Oct 2-Oct
Turnover IN OUT RESULT Turnover IN OUT RESULT
14599 4410 4500 -90 1000 54641 737542 -90
67530 9330 1440 7890 100 345 4274 7890
57699 11520 2673 8846 500 4525 275274 8846.5
196425 55960 68800 -12840 60050 42 4247 -12840
92100 17770 2500 15270 136450 4 14 15270
well, to copy certain range(with cell content, ...) you should try following, for example:
Excel.Range selCell1 = ((Excel.Worksheet)Application.ActiveSheet).Range["A1", "CA2000"];
Excel.Range selCell2 = ((Excel.Worksheet)Application.Sheets[2]).Range["A1", "CA2000"];
selCell1.Copy(selCell2);
Do you need a C# solution? Otherwise you can easily construct this type of thing directly in the excel spreadsheet:
=INDEX($11:$20,ROW(),MATCH($A$1,$11:$11,0)+COLUMN()-1)
Good Luck.

Categories

Resources