How to Suppy Data Model to Print Function - c#

I have a Print function which calls by different forms in my Project. Previously I was using DataSet as on my parameter, Now I switched to Data model. I am not sure how to retrieve information from different data model each time. Here is my old code.
public static void Print(string templeteID, DataSet dsSource,bool bPreview)
{
try
{
TPX.HMI.BusinessLogic.SystemSetting.ReportTemplate bll = new TPX.HMI.BusinessLogic.SystemSetting.ReportTemplate();
DataSet dsTemp = bll.RetrieveReportTemplateByID(templeteID);
if (dsTemp.Tables[0].Rows.Count > 0)
{
FileStream fs = new FileStream(Application.StartupPath + #"\\temp.repx", FileMode.Create);
Byte[] aryFile = dsTemp.Tables[0].Rows[0]["TemplateFile"] as Byte[];
fs.Write(aryFile, 0, aryFile.Length);
fs.Close();
}
string reportPatch = Application.StartupPath + #"\\temp.repx";
//开始打印
if (!System.IO.File.Exists(reportPatch))
{
MessageBox.Show(TPX.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "TPX_TF_HMI_Print_TemplateError"));
return;
}
System.IO.FileStream stream = new System.IO.FileStream(reportPatch, System.IO.FileMode.Open);
XtraReport mReport = DevExpress.XtraReports.UI.XtraReport.FromStream(stream, true);
stream.Close();
if (dsSource != null) //传入数据集
{
mReport.DataSource = dsSource;
mReport.DataMember = dsSource.Tables[dsSource.Tables.Count - 1].TableName;
}
mReport.Name = "TPX";
mReport.RequestParameters = false;
mReport.PrintingSystem.ShowPrintStatusDialog = false;
mReport.PrintingSystem.ShowMarginsWarning = false;
if (!string.IsNullOrEmpty(GlobalParameters.DefaultPrinter))
mReport.PrintingSystem.PageSettings.PrinterName = GlobalParameters.DefaultPrinter;
mReport.CreateDocument();
if (bPreview)
mReport.ShowPreviewDialog();
else
mReport.Print();
}
catch (Exception ex)
{
MessageBox.Show((TPX.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "TPX_TF_HMI_Print_TemplatePrintEx")) + ex.Message);
}
}

Related

create a file and upload the chunks to the in team drive from C#

I Have to Upload the file to my teamdrive, the file has been created to team drive but I can not upload the file chunks to it. So, please help to solve it.
On Writing a Chunk I am facing the Error of "The remote server returned an error: (404) Not Found."
I am getting the Teamdrive ID and the File ID which has been created.
/*** Creation of a File to Team Drive ***/
f_ObjFile.TeamDriveId = "/*TeamDrive ID*/";
try
{
f_ObjNewFile.Parents = f_ObjFile.Parents; // f_ObjFile = <Team Driv ID>
f_ObjNewFile.Name = f_ObjFile.Name;
f_ObjNewFile.MimeType = f_ObjFile.MimeType;
f_ObjNewFile.TeamDriveId = f_ObjFile.TeamDriveId;
f_CreateRequest = GoogleHelper.InvokeApiCall(() => { return this.DriveServiceObj.Files.Create(f_ObjNewFile); }, this);
if (f_CreateRequest != null)
{
f_CreateRequest.SupportsTeamDrives = true;
f_CreateRequest.Fields = "*";
f_ObjNewFile = GoogleHelper.InvokeApiCall(() => { return f_CreateRequest.Execute(); }, this);
}
f_ObjDocumentItem = new DocumentItem(UserEmailID, f_ObjNewFile);
f_ObjDocumentItem.ItemID = f_ObjNewFile.Id;
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
f_ObjDocumentItem.ChunkUploadURL = InitiateResumeRequest(f_Url, f_ObjNewFile.Id);
}
catch(Exception ex) { }
finally
{
f_ObjNewFile = null;
f_CreateRequest = null;
}
/* Writing the chunks to the file in TeamDrive */
try
{
httpRequest = GoogleHelper.CreateHttpWebRequestObj(f_ObjChunkData.ChunkUploadURL,true);
httpRequest.Method = GoogleConstant.PATCH;
httpRequest.ContentLength = f_ObjChunkData.FileData.Length;
httpRequest.SendChunked = true;
httpRequest.Headers["Content-Range"] = "bytes " + f_ObjChunkData.StartOffset +
"-" +
f_ObjChunkData.EndOffset + "/" +
f_ObjChunkData.FileSize.ToString();
using (System.IO.Stream f_ObjHttpStream = GoogleHelper.InvokeApiCall(() => { return httpRequest.GetRequestStream(); }, this))
{
if (f_ObjHttpStream != null)
{
System.IO.MemoryStream f_ChunkStream = null;
f_ChunkStream = new System.IO.MemoryStream(f_ObjChunkData.FileData);
f_ChunkStream.CopyTo(f_ObjHttpStream);
f_ObjHttpStream.Flush();
f_ObjHttpStream.Close();
f_ChunkStream.Close();
f_ChunkStream = null;
}
}
using (HttpWebResponse httpResponse = GoogleHelper.InvokeApiCall(() => { return (HttpWebResponse)(httpRequest.GetResponse()); }, this))
{
if (httpResponse != null)
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
httpResponse.Close();
}
}
}
}
catch (Exception ex) { }
In Followin Line :
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
Insted Of
"https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable"
Use following URL :
https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable&supportsTeamDrives=true
and its Done...
Now you can upload the chunks...

file lock on write and read

I have an xml file that has different marks in it that i need to update and need to pick up. this mark is from an api and is used so i only get new data. however when i try to write away the data or read the file it get locks all the time. these are the 2 functions that i use to write or read from the file.
private void SetMark(string name, string mark)
{
var marksfile = (string)_appSettings.GetValue("MarksFile", typeof(string));
_marks = new dsMarks();
try
{
if (File.Exists(marksfile))
{
using (var reader = new StreamReader(marksfile))
{
_marks.ReadXml(reader);
}
}
}
catch (Exception)
{
_marks = null;
throw;
}
var row = _marks.Mark.FindByName(name);
row.TimeMark = mark;
_marks.AcceptChanges();
using (var writer = new StreamWriter(marksfile))
{
_marks.WriteXml(writer);
}
}
private string GetMark(string name)
{
var marksfile = (string)_appSettings.GetValue("MarksFile", typeof(string));
_marks = new dsMarks();
try
{
if (File.Exists(marksfile))
{
using (var reader = new StreamReader(marksfile))
{
_marks.ReadXml(reader);
}
}
}
catch (Exception)
{
_marks = null;
throw;
}
var row = _marks.Mark.FindByName(name);
var mark = row.TimeMark;
return mark;
}
You might want to use FileStream instead of StreamReader as the former locks the file from other accessors. FileStream is better for read sharing.
private string GetTrimbleMark(string name)
{
var marksfile = (string)_appSettings.GetValue("MarksFile", typeof(string));
_marks = new dsMarks();
try
{
if (File.Exists(marksfile))
{
using (var reader = new FileStream(marksfile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
_marks.ReadXml(reader);
}
}
}
catch (Exception)
{
_marks = null;
throw;
}
var row = _marks.Mark.FindByName(name);
var mark = row.TimeMark;
return mark;
}
I 'll add fileAccess before openning my streamreader
if (File.Exists(marksfile))
{
FileStream fs = new FileStream(marksfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (var reader = new StreamReader(fs))
{
_marks.ReadXml(reader);
}
}

File used by another process ; PDF.JS ; iText

I'm using PDF.JS to display document that I upload to the server in canvas element using PDF.JS that's working perfectely. That time i'm using iTextSharp to digitally sign the document. When i try to sign the document an Exception is throwed (Exception.IO.Exception) The file is already used by another process. here is my Code for uploding the file :)
[HttpPost]
public async Task<JsonResult> Upload()
{
string fileName = null;
try
{
foreach (string item in Request.Files)
{
var fileContent = Request.Files[item];
if(fileContent != null && fileContent.ContentLength > 0)
{
var inputStream = fileContent.InputStream;
fileName = fileContent.FileName;
string path = Path.Combine(Server.MapPath("~/UploadFolder"), fileName);
using (fileContent.InputStream)
{
using (var stream = new FileStream(path, FileMode.Create))
{
await inputStream.CopyToAsync(stream);
}
}
}
}
}
catch (Exception e)
{
return Json("Upload failed");
}
return Json(fileName);
}
There's how i display PDF in canvas
$(document).ready(function () {
$("#btn2").click(function () {
var url = document.getElementById("document-to-sign").getAttribute("required-document");
if (url != "" && url != null) {
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1.5,
canvas = document.getElementById('document-to-sign'),
ctx = canvas.getContext('2d');
function renderPage(num) {
pageRendering = true;
pdfDoc.getPage(num).then(function (page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
pageRendering = false;
if (pageNumPending !== null) {
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
document.getElementById('page_num').textContent = pageNum;
}
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
PDFJS.getDocument(url).then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
renderPage(pageNum);
});
PDFJS.disableStream = true;
$("#document-to-sign").removeAttr("required-document");
}
});
I finally that's how i'm signing the document (Adding the empty field to sign)
public static void AddField(string src,
Double x1X, Double x1Y, Double x2X, Double x2Y, int page,
string User)
{
try
{
PdfReader reader = new PdfReader(src);
using (PdfStamper s = new PdfStamper(reader, new FileStream(src, FileMode.Open)))
{
PdfFormField field = PdfFormField.CreateSignature(s.Writer);
field.FieldName = "Signature de " + User;
field.SetWidget(new Rectangle(Convert.ToSingle(x1X), Convert.ToSingle(x1Y), Convert.ToSingle(x2X), Convert.ToSingle(x2Y)), PdfAnnotation.HIGHLIGHT_PUSH);
field.Flags = PdfAnnotation.FLAGS_PRINT;
s.AddAnnotation(field, page);
}
}
catch (Exception e)
{
logger.Fatal(e.ToString());
throw e;
}
}
I'm stacked in this line
using (PdfStamper s = new PdfStamper(reader, new FileStream(src, FileMode.Open)))
EDIT:
I'm just adding the siging field in this step. Signing the document will be the next task, in console application i'm singing the document with a self-certificate.
Upload the document, and adding the signing field and signing it will be further :)
Sorry for the confussion.
Thanks a lot. :)
I just found what i'm missing in reading the file
refer to this
Cannot access the file because it is being used by another process
i was passing the url of the file instead of reading the all bytes from stream
PdfReader reader = new PdfReader(src);
PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath))

Display Image retrieving from DB

This is my code to Insert and display an image in an Image control from DB:
try
{
Byte[] imgbyte = null;
if (ImageUpload.HasFile && ImageUpload.PostedFile != null)
{
HttpPostedFile file = ImageUpload.PostedFile;
imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
}
if (c.cn.State == ConnectionState.Closed)
{
c.cn.Open();
}
c.cmd = c.cn.CreateCommand();
c.cmd.CommandText = "uploadImage";
c.cmd.CommandType = CommandType.StoredProcedure;
c.cmd.Parameters.Add("#ppr", SqlDbType.Int);
c.cmd.Parameters.Add("#imagename", SqlDbType.VarChar);
c.cmd.Parameters.Add("#imagecontent", SqlDbType.VarChar);
c.cmd.Parameters.Add("#imagebinary", SqlDbType.Image);
c.cmd.Parameters.Add("#TypeOperation", SqlDbType.Int);
c.cmd.Parameters["#ppr"].Value = Session["Code"];
c.cmd.Parameters["#imagename"].Value = ImageUpload.FileName;
c.cmd.Parameters["#imagecontent"].Value = ImageUpload.PostedFile.ContentType;
c.cmd.Parameters["#imagebinary"].Value = imgbyte;
c.cmd.Parameters["#TypeOperation"].Value = 0;
int id = c.cmd.ExecuteNonQuery();
Label3.Text = ("id is <br>" + id);
Response.Write("Yosh!!!!!!!!!!");
Image1.ImageUrl = "~/Handlerr.ashx?ppr=" + id ;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (c.cn.State == System.Data.ConnectionState.Open)
{
c.cn.Close();
}
}
and this is my class .ashx :
public class Handlerr : IHttpHandler
{
Connexion c = new Connexion();
public void ProcessRequest(HttpContext context)
{
//if (context.Request.QueryString["ppr"] != null)
int ppr = Convert.ToInt32(context.Request.QueryString["ppr"]);
//else
//throw new ArgumentException("No param specified");
context.Response.ContentType = "image/jpeg";
Stream st = DisplayImage(ppr);
byte[] buffer = new byte[4096];
int byteseq = st.Read(buffer, 0, 4096);
while (byteseq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteseq);
byteseq = st.Read(buffer, 0, 4096);
}
}
public Stream DisplayImage(int ppr)
{
SqlConnection cc = new SqlConnection(ConfigurationManager.ConnectionStrings["CVtechConnectionString"].ToString());
//c.cmd = c.cn.CreateCommand();
string sql = "Select ImageBinary from ImageStoragee where ImageID=#p_pr ";
SqlCommand cm = new SqlCommand(sql, cc);
cm.CommandType = CommandType.Text;
cm.Parameters.AddWithValue ("#p_pr" , ppr);
if (c.cn.State == ConnectionState.Closed)
{
cc.Open(); //
}
cm.ExecuteReader();
try
{
DataClasses1DataContext context1 = new DataClasses1DataContext();
var r = (from a in context1.ImageStoragee where a.PPR == ppr select a).First();
return new MemoryStream(r.ImageBinary.ToArray());
}
catch
{
return null;
}
finally
{
if (cc.State == ConnectionState.Open)
{
cc.Close();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
the problem that image is not displayed there is a little Icon as shown in the picture :
Thank you
I know you are not using EF6, but maybe you can compare with one method released on my server and working fine. Check the types...
public ActionResult GetImageUser(Int64 id_User)
{
try
{
return File(db.DUser_Image.Find(id_User).file_Data, "image/jpeg", "userimage");
}
catch (Exception)
{
return Content("0|Image not found!");
}
}
public ActionResult UploadImageUser(Int64 id_User)
{
ImageConverter converter = new ImageConverter();
Image img = System.Drawing.Image.FromStream(Request.InputStream);
try
{
var dUser_Image = db.DUser_Image.Find(id_User);
dUser_Image.file_Data = (byte[])converter.ConvertTo(img, typeof(byte[]));
var entry = db.Entry(dUser_Image);
entry.Property(e => e.file_Data).IsModified = true;
db.SaveChanges();
return Content("1");
}
catch (Exception)
{
DUser_Image dUser_Image = new DUser_Image();
try
{
dUser_Image.id_User_Image = id_User;
dUser_Image.file_Data = (byte[])converter.ConvertTo(img, typeof(byte[]));
db.DUser_Image.Add(dUser_Image);
db.SaveChanges();
return Content("1");
}
catch (Exception)
{
return Content("0");
}
}
}

SSRS wont publish report but it returns successful as if it did

public static void ListFolders()
{
HomeFolderListing = new List<string>();
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
CatalogItem[] HomeFolders = null;
string reportPath = "/";
rs.ListChildren(reportPath, true, out HomeFolders);
foreach (var homeF in HomeFolders)
{
if (homeF.Name.ToString().ToLower().Contains("base"))
{
if (homeF.Path.ToString().ToLower().Contains("/data sources/"))
{
}
else
{
Console.WriteLine("Adding reporting folder: " + homeF.Name.ToString());
HomeFolderListing.Add(homeF.Path.ToString());
}
}
}
}
public static void PublishReport()
{
foreach (string HomeFold in HomeFolderListing)
{
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
BatchHeader bh = new BatchHeader();
string batchID = null;
rs.CreateBatch(out batchID);
bh.BatchID = batchID;
Byte[] definition = null;
Warning[] warnings = null;
try
{
FileStream stream = File.OpenRead(ReportInformation.Report2Deploy);
definition = new Byte[stream.Length];
stream.Read(definition, 0, (int)stream.Length);
stream.Close();
}
catch (Exception ex)
{
}
try
{
string filename = ReportInformation.ReportDeployNameOnly;
Console.WriteLine("Deploying Report: " + filename + " to: " + HomeFold);
rs.CreateReport(bh, filename, HomeFold, true, definition, null, out warnings);
if (warnings != null)
{
foreach (Warning warning in warnings)
{
Console.WriteLine(warning.Message);
}
}
else
Console.WriteLine("Report: {0} created successfully with no warnings", filename);
}
catch (Exception ex)
{
}
}
}
when i execute rs.CreateReport() it comes back as if it was successful with no warning, however, when i view the server it just isn't there. And yes I've looking in all the folders.
Are you sure there is no error? There's an empty catch block. The documenation says to catch a SoapException. Try this in the catch:
catch (SoapException e)
{
//Do something with the error, sample code write to console
Console.WriteLine(e.Detail.InnerXml.ToString());
}
Taken from:
http://msdn.microsoft.com/en-us/library/aa225813(v=sql.80).aspx

Categories