Overriding image issue - c#

Here is my issue:
I'm trying to loop through folder get the files from the folder and save each file to an image and then to the DataBase but for some reason the length of the image is the same all the time. like it's not creating a new instance of an image.
Here is my code + comments:
Dim dba As New DBAccess
Dim folderName As String = String.Empty
Dim imageFileName As String = String.Empty
Dim ms1 As New MemoryStream()
Dim ds As DataSet = New DataSet
If m_IncidentCaseID > 0 Then
If Not String.IsNullOrEmpty(Sessions.GetKeyValueSessionFile(m_SessionID, "IRPicturesPath")) Then
m_IncidentPicturesPath = Convert.ToString(Sessions.GetKeyValueSessionFile(m_SessionID, "IRPicturesPath"))
End If
folderName = m_IncidentPicturesPath '!= Set the path of the folder.
'!= For Each file get the data from the DataBase: PictureID,PictureIndex,PictureFileName.
m_HashTableIRPicturesWriter = New Hashtable
m_DictionaryEntryIRPicturesWriter = New DictionaryEntry
Dim strArr As String() = Directory.GetFiles(folderName)
For Each filePath As String In strArr
ds = dba.GetPicturesIDFromPath(filePath, m_User.CompanyCode)
If Not ds Is Nothing Then
m_HashTableIRPicturesWriter.Add(ds.Tables(0).Rows(0).Item("PictureID").ToString(), filePath)
End If
Next
'!= We saved each file Path +PictrureID to Hashtable
'!== Loop through the hashtable and for each file in the folder create an image.
For Each filename As DictionaryEntry In m_HashTableIRPicturesWriter
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename.Value())
Dim bytes As Byte()
img.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg)
bytes = ms1.ToArray()
'!=================================== Delete and Insert to the Temp_Table in the DB ==============================!
Dim dBConnection As String
dBConnection = Globals.GetConnectionStringMain(m_User.CompanyCode())
Dim connString As New SqlConnection(dBConnection)
'# First Delete the table from the IncidentID that we want to insert.
Dim sql1 As String = "Delete From Temp_Incident_Images Where PictureID =" & filename.Key()
Dim cmd1 As New SqlCommand(sql1, connString)
If connString.State = ConnectionState.Closed Then
connString.Open()
End If
cmd1.Parameters.Add(New SqlParameter("#IncidentID", m_IncidentCaseID))
cmd1.ExecuteNonQuery()
connString.Close()
If connString.State = ConnectionState.Closed Then
connString.Open()
End If
'# Second Inserst the PictureID to the Table.
Dim sql As String = "Insert Into Temp_Incident_Images(PictureID,IncidentID,IncidentImage) values (#PictureID,#IncidentID,#IncidentImage)"
Dim cmd As New SqlCommand(sql, connString)
cmd.Parameters.AddWithValue("#IncidentID", m_IncidentCaseID)
cmd.Parameters.AddWithValue("#PictureID", filename.Key())
Dim data As Byte() = ms1.GetBuffer() '!=When checking the Data it's same all the time.
Dim p As New SqlParameter("#IncidentImage", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw New SystemException(ex.Message.ToString.Trim)
End Try
ms1.Close()
connString.Close()
img.Dispose()
Next
End If
How can I create a new instance of an image from this lines of code:
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename.Value())
Dim bytes As Byte()
img.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg)
bytes = ms1.ToArray()

if you having image path issues with database here is simple code you can work with.
add file upload and a label or anything like this,
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
after that add a button which performs the any operation you want.
<asp:Button runat="server" class="btn btn-info pull-right" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
inside the button add
Try
If FileUploadControl.PostedFile.ContentType = "image/jpeg" Then
If FileUploadControl.PostedFile.ContentLength < 102400 Then
Dim filename As String = Path.GetFileName(FileUploadControl.FileName)
FileUploadControl.SaveAs(Server.MapPath("~/ProductImages/") & filename)
StatusLabel.Text = "Upload status: File uploaded!"
Else
StatusLabel.Text = "Upload status: The file has to be less than 100 kb!"
End If
Else
StatusLabel.Text = "Upload status: Only JPEG files are accepted!"
End If
Catch ex As Exception
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message
End Try
Please let me know if it solves your problem I can edit the code if you need any more help.

Related

editing html string having text and several images using regex

I am new to this forum and hoping to get some help.
I have a an HTML string having text and several base64 images.
I need to loop through all image tags adding a slash / before
the closing tag > so that each image ends with /> and return
a new html string with the changes.
so each
<IMG src="data:image/png;base64,iVBORw0KG....">
should then be
<IMG src="data:image/png;base64,iVBORw0KG...."/>
I am not versed with html and I am wondering how to do it
(using regex?).
Here is some pseudo code:
Function GetSourceImges(Sourcehtml As String) As List(Of String)
Dim listOfImgs As New List(Of String)()
'use regex to find image tags
'Return list of base64 image tags
End Function
For each image in list
insert a slash appropriately
next
Reconstitute a new html string with edited images
Thanks
Map all "IMG" tags using LINQ and use their indexes as an anchor to fix the missing "/" characters. please see my comments inside the code.
Sub Main()
Dim htmlstring As String = "<IMG src=""data:image/png;base64,iVBORw0KG....""> " & vbCrLf _
& "<img src=""data:image/png;base64,iVBORw0KG...."">" & vbCrLf _
& "<p>blahblah</p>" & vbCrLf _
& "<IMG src=""data:image/png;base64,iVBORw0KG...."">" & vbCrLf _
& "<p>blahblah</p>"
' find all indxes of img using regex and lambda exprations '
Dim indexofIMG() As Integer = Regex.Matches(htmlstring, "IMG", RegexOptions.IgnoreCase) _
.Cast(Of Match)().Select(Function(x) x.Index).ToArray()
' check from each index of "IMG" if "/" is missing '
For Each itm As Integer In indexofIMG
Dim counter As Integer = itm
While counter < htmlstring.Length - 1
If htmlstring(counter) = ">" Then
If htmlstring(counter - 1) <> "/" Then
' fix the missing "/" using Insert() method '
htmlstring = htmlstring.Insert(counter, "/")
End If
Exit While
End If
counter += 1
End While
Next
Console.WriteLine(htmlstring)
Console.ReadLine()
End Sub
Surprisingly it works with the console app but doesn't when I view it on a richtextbox as in btnEditHTML method below. The generated pdf has only one red dot and not two.
Can't say why.
I must say you have been very helpfull.
'SetTable and customimagetagprocessor borrowed from [here] iTextsharp base64 embedded image in header not parsing/showing
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.tool.xml
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml.parser
Imports iTextSharp.tool.xml.pipeline.css
Imports iTextSharp.tool.xml.pipeline.html
Imports iTextSharp.tool.xml.pipeline.end
Imports iTextSharp.tool.xml.html
Imports System.Text.RegularExpressions
Public Class Form1
Dim dsktop As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Public Function GetFormattedHTML(str As String) As String
'format images by changing > to />
' find all indxes of img using regex and lambda exprations '
Dim indexofIMG() As Integer = Regex.Matches(str.ToString, "IMG", RegexOptions.IgnoreCase) _
.Cast(Of Match)().Select(Function(x) x.Index).ToArray()
' check from each index of "IMG" if "/" is missing '
For Each itm As Integer In indexofIMG
Dim counter As Integer = itm
While counter < str.ToString.Length - 1
If str(counter) = ">" Then
If str(counter - 1) <> "/" Then
' fix the missing "/" using Insert() method '
str = str.ToString.Insert(counter, " /")
End If
Exit While
End If
counter += 1
End While
Next
Return str.ToString
End Function
Private Sub btnEditHTML_Click(sender As Object, e As EventArgs) Handles btnEditHTML.Click
Rtb.Text = String.Empty
'the 2 base64 images in the html below are actually just small red dots
Dim RawHTML As String = "<P>John Doe</P><IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==""> Jackson5<IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="">"
Rtb.Text = GetFormattedHTML(RawHTML)
'notice that the 2nd base64 string is not edited as required.
End Sub
Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
'here I create a 2 column itextsharp table to parse my html into the cells
Dim doc As New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 30)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New System.IO.FileStream(dsktop & "\testtable.pdf", System.IO.FileMode.Create))
doc.Open()
'set table columnwidths -------------------------------------------------------------
Dim MainTable As New PdfPTable(2) '2 column table
MainTable.WidthPercentage = 100
Dim Wth(1) As Single
Dim u As Integer = 2
For i As Integer = 0 To 1
Wth(i) = CInt(Math.Floor(2 * 500 / u))
Next
MainTable.SetWidths(Wth)
Dim htmlstr As String = GetFormattedHTML("<P>John Doe</P><IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==""> Jackson5<IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="">")
Dim Elmts = New ElementList()
Elmts = XMLWorkerHelper.ParseToElementList(htmlstr, Nothing)
Dim MinorTable As New PdfPTable(1)
MinorTable = SetTable(Elmts, htmlstr)
For i = 1 To 2
Dim Cell As New PdfPCell
Cell.AddElement(MinorTable)
MainTable.AddCell(Cell)
Next
doc.Add(MainTable)
doc.Close()
Process.Start(dsktop & "\testtable.pdf")
End Sub
Public Function SetTable(ByVal elements As ElementList, ByVal htmlcode As String) As PdfPTable
Dim tagProcessors As DefaultTagProcessorFactory = CType(Tags.GetHtmlTagProcessorFactory(), DefaultTagProcessorFactory)
tagProcessors.RemoveProcessor(HTML.Tag.IMG) ' remove the default processor
tagProcessors.AddProcessor(HTML.Tag.IMG, New CustomImageTagProcessor()) ' use our new processor
Dim cssResolver As ICSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(True)
cssResolver.AddCssFile(Application.StartupPath & "\pdf.css", True)
'see sample css file at https://learnwebcode.com/how-to-create-your-first-css-file/
'Setup Fonts
Dim xmlFontProvider As XMLWorkerFontProvider = New XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS)
xmlFontProvider.RegisterDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/fonts/"))
Dim cssAppliers As CssAppliers = New CssAppliersImpl(xmlFontProvider)
Dim htmlContext As HtmlPipelineContext = New HtmlPipelineContext(cssAppliers)
htmlContext.SetAcceptUnknown(True)
htmlContext.SetTagFactory(tagProcessors)
Dim pdf As ElementHandlerPipeline = New ElementHandlerPipeline(elements, Nothing)
Dim htmlp As HtmlPipeline = New HtmlPipeline(htmlContext, pdf)
Dim css As CssResolverPipeline = New CssResolverPipeline(cssResolver, htmlp)
Dim worker As XMLWorker = New XMLWorker(css, True)
Dim p As XMLParser = New XMLParser(worker)
'Dim holderTable As New PdfPTable({1})
Dim holderTable As PdfPTable = New PdfPTable({1})
holderTable.WidthPercentage = 100
holderTable.HorizontalAlignment = Element.ALIGN_LEFT
Dim holderCell As New PdfPCell()
holderCell.Padding = 0
holderCell.UseBorderPadding = False
holderCell.Border = 0
p.Parse(New MemoryStream(System.Text.Encoding.ASCII.GetBytes(htmlcode)))
For Each el As IElement In elements
holderCell.AddElement(el)
Next
holderTable.AddCell(holderCell)
'Dim holderRow As New PdfPRow({holderCell})
'holderTable.Rows.Add(holderRow)
Return holderTable
End Function
End Class
Public Class CustomImageTagProcessor
Inherits iTextSharp.tool.xml.html.Image
Public Overrides Function [End](ctx As IWorkerContext, tag As Tag, currentContent As IList(Of IElement)) As IList(Of IElement)
Dim attributes As IDictionary(Of String, String) = tag.Attributes
Dim src As String = String.Empty
If Not attributes.TryGetValue(iTextSharp.tool.xml.html.HTML.Attribute.SRC, src) Then
Return New List(Of IElement)(1)
End If
If String.IsNullOrEmpty(src) Then
Return New List(Of IElement)(1)
End If
If src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase) Then
' data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Dim base64Data As String = src.Substring(src.IndexOf(",") + 1)
Dim imagedata As Byte() = Convert.FromBase64String(base64Data)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagedata)
Dim list As List(Of IElement) = New List(Of IElement)()
Dim htmlPipelineContext As pipeline.html.HtmlPipelineContext = GetHtmlPipelineContext(ctx)
list.Add(GetCssAppliers().Apply(New Chunk(DirectCast(GetCssAppliers().Apply(image, tag, htmlPipelineContext), iTextSharp.text.Image), 0, 0, True), tag, htmlPipelineContext))
Return list
Else
If File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src)) Then
Dim imagedata As Byte() = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src))
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src))
Dim list As List(Of IElement) = New List(Of IElement)()
Dim htmlPipelineContext As pipeline.html.HtmlPipelineContext = GetHtmlPipelineContext(ctx)
list.Add(GetCssAppliers().Apply(New Chunk(DirectCast(GetCssAppliers().Apply(image, tag, htmlPipelineContext), iTextSharp.text.Image), 0, 0, True), tag, htmlPipelineContext))
Return list
End If
Return MyBase.[End](ctx, tag, currentContent)
End If
End Function
End Class
I highly recommend just using AngleSharp to parse the HTML, edit the document if required, and save it again.
There are many posts on here about why trying to parse HTML with regular expressions is a bad idea.
var doc = new HtmlParser().Parse(html);
As you aren't actually changing the HTML content, just fixing up the tags, your should be able to just parse it and save it with no changes to fix the tags.

Generate PDF in using windows form

I want to generate a PDF using windows form in the desktop application. I have readymade pdf design and I just want to feed data from database in that blank section of pdf for each user. (One type of receipt). Please guide me. I have searched but most of the time there is the solution in asp.net for the web application. I want to do in the desktop app. Here is my code I am able to fatch data from database and print in pdf. But main problem is trhat I have already designed pdf and I want to place data exactly at same field (ie name, Amount, date etc.)
using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace printPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
int yPoint = 0;
string pubname = null;
string city = null;
string state = null;
connetionString = "Data Source=EEVO-SALMAN\\MY_PC;Initial Catalog=;User ID=s***;Password=******";
// var connectionString = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
sql = "select NAME,NAME,uid from tblumaster";
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
connection.Close();
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = "Database to PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Regular );
yPoint = yPoint + 100;
for (i = 0; i <=ds.Tables[0].Rows.Count-1; i++)
{
pubname = ds.Tables[0].Rows[i].ItemArray[0].ToString ();
city = ds.Tables[0].Rows[i].ItemArray[1].ToString();
state = ds.Tables[0].Rows[i].ItemArray[2].ToString();
graph.DrawString(pubname, font, XBrushes.Black, new XRect(10, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
graph.DrawString(city, font, XBrushes.Black, new XRect(200, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
graph.DrawString(state, font, XBrushes.Black, new XRect(400, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
yPoint = yPoint + 40;
}
string pdfFilename = "dbtopdf.pdf";
pdf.Save(pdfFilename);
Process.Start(pdfFilename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Instead of modifying the document, please create a new document and copy the pages from the old document to new document
sample code can be found here,
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637
Because modifying pdf is not recommended using 'PdfSharp' library. if you still want to edit you can use 'ISharp' library which needs a license.
Here is some VB.Net code I use to fill PDF forms. You need a PDF fillable form with form control names matching the SQL record field names.
It calls a routine Gen.GetDataTable() that just builds a typical DataTable. You could re-code to accept a pre-built Datatable as a parameter. Only the top row is processed. The code can be modified to work with a DataRow (.Table.Columns for column reference) or a DataReader.
Public Function FillPDFFormSQL(pdfMasterPath As String, pdfFinalPath As String, SQL As String, Optional FlattenForm As Boolean = True, Optional PrintPDF As Boolean = False, Optional PrinterName As String = "", Optional AllowMissingFields As Boolean = False) As Boolean
' case matters SQL <-> PDF Form Field Names
Dim pdfFormFields As AcroFields
Dim pdfReader As PdfReader
Dim pdfStamper As PdfStamper
Dim s As String = ""
Try
If pdfFinalPath = "" Then pdfFinalPath = pdfMasterPath.Replace(".pdf", "_Out.pdf")
Dim newFile As String = pdfFinalPath
pdfReader = New PdfReader(pdfMasterPath)
pdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
pdfReader.Close()
pdfFormFields = pdfStamper.AcroFields
Dim dt As DataTable = Gen.GetDataTable(SQL)
For i As Integer = 0 To dt.Columns.Count - 1
s = dt.Columns(i).ColumnName
If AllowMissingFields Then
If pdfFormFields.Fields.ContainsKey(s) Then
pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
Else
Debug.WriteLine($"Missing PDF Field: {s}")
End If
Else
pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
End If
Next
' flatten the form to remove editing options
' set it to false to leave the form open for subsequent manual edits
If My.Computer.Keyboard.CtrlKeyDown Then
pdfStamper.FormFlattening = False
Else
pdfStamper.FormFlattening = FlattenForm
End If
pdfStamper.Close()
If Not newFile.Contains("""") Then newFile = """" & newFile & """"
If Not PrintPDF Then
Process.Start(newFile)
Else
Dim sPDFProgramPath As String = INI.GetValue("OISForms", "PDFProgramPath", "C:\Program Files (x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe")
If Not IO.File.Exists(sPDFProgramPath) Then MsgBox("PDF EXE not found:" & vbNewLine & sPDFProgramPath) : Exit Function
If PrinterName.Length > 0 Then
Process.Start(sPDFProgramPath, "/t " & newFile & " " & PrinterName)
Else
Process.Start(sPDFProgramPath, "/p " & newFile)
End If
End If
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
Finally
pdfStamper = Nothing
pdfReader = Nothing
End Try
End Function

how to associate crystalreport to my own form add-on sap

hi firends i have started with sap b1 i created my own add-on sap using c# in visual studio 2010 my form will sent a value to my crystal report directly without showing previou any one can help my version sap is 9.2
i tried this code but it doesn't work
//add crystalreport to my add-on
SAPbobsCOM.ReportTypesService rptTypeService = (SAPbobsCOM.ReportTypesService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService);
SAPbobsCOM.ReportType newType = (SAPbobsCOM.ReportType)
rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType);
newType.TypeName = "CodeBarre_etat";
newType.AddonName = "PRINT_CODEBARRE";
newType.AddonFormType = "PRINT_CODEBARRE";
newType.MenuID = "PRINT_CODEBARRE";
SAPbobsCOM.ReportTypeParams newTypeParam = rptTypeService.AddReportType(newType);
//add layout to my report
SAPbobsCOM.ReportLayoutsService rptService = (SAPbobsCOM.ReportLayoutsService)
Menu.company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService);
SAPbobsCOM.ReportLayout newReport = (SAPbobsCOM.ReportLayout)
rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout);
newReport.Author = Menu.company.UserName;
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal;
newReport.Name = "PRINT_CODEBARREL";
newReport.TypeCode = newTypeParam.TypeCode;
SAPbobsCOM.ReportLayoutParams newReportParam = rptService.AddReportLayout(newReport);
// Set the report layout into the report type.
newType = rptTypeService.GetReportType(newTypeParam);
newType.DefaultReportLayout = newReportParam.LayoutCode;
rptTypeService.UpdateReportType(newType);
SAPbobsCOM.BlobParams oBlobParams = (SAPbobsCOM.BlobParams)
Menu. company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams);
oBlobParams.Table = "OITM";
oBlobParams.Field = "Template";
SAPbobsCOM.BlobTableKeySegment oKeySegment = oBlobParams.BlobTableKeySegments.Add();
oKeySegment.Name = "ItemCode";
oKeySegment.Value = newReportParam.LayoutCode;
FileStream oFile = new FileStream("CodeBarre_etat.rpt", System.IO.FileMode.Open);
int fileSize = (int)oFile.Length;
byte[] buf = new byte[fileSize];
oFile.Read(buf, 0, fileSize);
oFile.Dispose();
//SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)
//Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob);
SAPbobsCOM.Blob oBlob = (SAPbobsCOM.Blob)(Menu.company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob));
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize);
Menu.company.GetCompanyService().SetBlob(oBlobParams, oBlob);
Not sure what the issue might be with your code, but below is a working implementation of what you're trying to do (albeit in VB, not in C#, but translating it should be fairly trivial).
Here's a sample call:
setCrystalReport(REPORT_TITLE_SUMMARY, My.Settings.ReportsPath.TrimEnd("\") & "\" & "comm_report_summary.rpt", _
oForm, "myFormTypeID", "My Add-On Name", "MENU_ID_VALUE")
Function:
'Returns new CR TypeCode
Private Function setCrystalReport(ByVal rptName As String, ByVal rptPath As String, ByRef oForm As SAPbouiCOM.Form, ByVal formType As String, _
ByVal addOnName As String, ByVal menuID As String) As String
Try
'1. Ad a new report type => ReportTypesService (8.81+ only)
Dim rptTypeService As SAPbobsCOM.ReportTypesService
Dim newType As SAPbobsCOM.ReportType
rptTypeService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportTypesService)
newType = rptTypeService.GetDataInterface(SAPbobsCOM.ReportTypesServiceDataInterfaces.rtsReportType)
newType.TypeName = rptName
newType.AddonName = addOnName
newType.AddonFormType = formType
newType.MenuID = menuID
Dim newTypeParam As SAPbobsCOM.ReportTypeParams
newTypeParam = rptTypeService.AddReportType(newType)
'2. Add a new report layout => ReportLayoutService
Dim rptService As SAPbobsCOM.ReportLayoutsService
Dim newReport As SAPbobsCOM.ReportLayout
rptService = SBO_Company.GetCompanyService().GetBusinessService(SAPbobsCOM.ServiceTypes.ReportLayoutsService)
newReport = rptService.GetDataInterface(SAPbobsCOM.ReportLayoutsServiceDataInterfaces.rlsdiReportLayout)
newReport.Author = SBO_Company.UserName
newReport.Category = SAPbobsCOM.ReportLayoutCategoryEnum.rlcCrystal
newReport.Name = rptName
newReport.TypeCode = newTypeParam.TypeCode
Dim newReportParam As SAPbobsCOM.ReportLayoutParams
newReportParam = rptService.AddReportLayout(newReport)
'3. Set the report layout into the report type
newType = rptTypeService.GetReportType(newTypeParam)
newType.DefaultReportLayout = newReportParam.LayoutCode
rptTypeService.UpdateReportType(newType)
'4. Link the Report layout code to the Crystal Report file
Dim oBlobParams As SAPbobsCOM.BlobParams
Dim oKeySegment As SAPbobsCOM.BlobTableKeySegment
oBlobParams = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlobParams)
oBlobParams.Table = "RDOC"
oBlobParams.Field = "Template"
oKeySegment = oBlobParams.BlobTableKeySegments.Add()
oKeySegment.Name = "DocCode"
oKeySegment.Value = newReportParam.LayoutCode
Dim oFile As New FileStream(rptPath, System.IO.FileMode.Open)
Dim fileSize As Integer
fileSize = oFile.Length
Dim buf(fileSize) As Byte
oFile.Read(buf, 0, fileSize)
oFile.Dispose()
Dim oBlob As SAPbobsCOM.Blob
oBlob = SBO_Company.GetCompanyService().GetDataInterface(SAPbobsCOM.CompanyServiceDataInterfaces.csdiBlob)
oBlob.Content = Convert.ToBase64String(buf, 0, fileSize)
SBO_Company.GetCompanyService().SetBlob(oBlobParams, oBlob)
'5. Link the new report type to your form
Return newType.TypeCode
Catch ex As Exception
Dim exString As String = ""
exString = "Exception caught in setCrystalReport Method. Details: " & ex.Message
If Not ex.InnerException Is Nothing Then
exString += " Inner Exception: " + ex.InnerException.Message
End If
SBO_Application.StatusBar.SetText(exString, SAPbouiCOM.BoMessageTime.bmt_Medium, _
SAPbouiCOM.BoStatusBarMessageType.smt_Error)
Return "-1"
End Try
End Function

Get image from url in database

I have a database with image URL's. I have a stored procedure hat GET's the url's (SP_GET_Image) I want execute the stored proc then for each of the URL's get the image.
I want the actual image locally not the url.
Then for each image I want to save them locally. I have this code but want to know how do I save each image in a datarow.
I have started with the code.
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("#Parameter1", sqlDBType.Int).value = Param_1_value
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'Fill the dataset'
Dim DS as DataSet
adapter.Fill(ds)
connection.Close()
'Now, read through your data:'
For Each DR as DataRow in DS.Tables(0).rows
'<-- Im not sure here how to GET EACH images locally saved.
Next
c# or vb help is fine.
The url looks like this :
http://img.myCompany.net/p/1483/278227_20094171232290.jpg
You can use My.Computer.Network.DownloadFile in order to download and store the file on local machine or a remote server supplying a user name and password (if required). As you need to specify the file name when downloading, you can extract it from the URL with SubString(URL.LastIndexOf("/") + 1)
For Each DR as DataRow in DS.Tables(0).Rows
Dim URL as String = DR("Your_URL_Column_Name").ToString()
Dim Destination as String = "\\SERVERNAME\FolderName\"
My.Computer.Network.DownloadFile(URL, Destination & SubString(URL.LastIndexOf("/") + 1), "name", "password")
Next
This function will help you download a list of images to a specified local path
public void DownloadFiles(IEnumerable<string> urls, string path)
{
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
System.Threading.Tasks.Parallel.ForEach(urls, url =>
{
using (var downloader = new WebClient())
{
var filePath = System.IO.Path.Combine(path, System.IO.Path.GetFileName(url));
downloader.DownloadFile(url,filePath);
}
});
}
You can use it similar to this:
var urlList= DS.Tables[0].Rows
.Cast<DataRow>()
.Select(x => x["YourColumnNameOfUrl"].ToString());
DownloadFiles(urlList,"C:\Directory\Of\Ur\Choice\");
Here is a small utility function to help you with your task
Function SaveRemoteImage(remoteImageUrl As String) As Integer
Try
Dim request = WebRequest.Create(remoteImageUrl)
Dim folderName = Server.MapPath("~/VB/Images/")
Using response As WebResponse = request.GetResponse()
Using stream As Stream = response.GetResponseStream()
Dim imageExtension = String.Empty
Select Case response.ContentType.ToLower
Case "image/bmp",
"image/x-bmp",
"image/x-ms-bmp"
imageExtension = ".bmp"
Case "image/jpeg"
imageExtension = ".jpeg"
Case "image/gif"
imageExtension = ".gif"
Case "image/png"
imageExtension = ".png"
Case Else
imageExtension = ".png"
End Select
'renaming image name as GUID to avoid conflicts
Dim imageName = Guid.NewGuid().ToString()
' Download the file
Dim destinationPath = String.Concat(
folderName,
imageName,
imageExtension)
Using tempFile = File.OpenWrite(destinationPath)
' Remark: if the file is very big read it in chunks
' to avoid loading it into memory
Dim buffer = New Byte(response.ContentLength - 1) {}
stream.Read(buffer, 0, buffer.Length)
tempFile.Write(buffer, 0, buffer.Length)
End Using
End Using
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
I am not using the WebClient method as we need the correct Image Content-Type to get the local files extension.
Now, get all ImageUrls as an IEnumerable(Of String) from the DataTable and call it like this
Dim images = table.AsEnumerable().
Select(Function(row) row.Field(Of String)("ImageUrl"))
For Each remoteImage In images
SaveRemoteImage(remoteImage)
Next
If you want some parallel programming magic, replace the For Each like this.
System.Threading.Tasks.Parallel.ForEach(images,
Function(remoteImage) SaveRemoteImage(remoteImage))

Send Multiple Documents To Printer

I have one Requirement in .net wpf.
There are some images in format of .gif or .jpg in a local folder.
I have prepared one List of string , to store file names
i want to send all images in a list to a printer in button click.
I have searched Google but for Print document we can give only one file PrintFileName.
But i want to give each file name in for each loop . any one can explain how is it possible?
Thanks..
question subject is look like wrong...
answer;
var filenames = Directory.EnumerateFiles(#"c:\targetImagePath", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".bmp"));
foreach (var filename in filenames)
{
//use filename
}
Private Sub btnPrint_Click(sender As Object, e As RoutedEventArgs) Handles btnPrint.Click
Dim printDialog = New System.Windows.Controls.PrintDialog()
If printDialog.ShowDialog = False Then
Return
End If
Dim fixedDocument = New FixedDocument()
fixedDocument.DocumentPaginator.PageSize = New System.Windows.Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight)
For Each p In _lablefilenames
Dim page As New FixedPage()
Dim info As System.IO.FileInfo = New FileInfo(p)
'If info.Extension.ToLower = ".gif" Then
' page.Width = fixedDocument.DocumentPaginator.PageSize.Height
' page.Height = fixedDocument.DocumentPaginator.PageSize.Width
'Else
page.Width = fixedDocument.DocumentPaginator.PageSize.Width
page.Height = fixedDocument.DocumentPaginator.PageSize.Height
'End If
Dim img As New System.Windows.Controls.Image()
' PrintIt my project's name, Img folder
'Dim uriImageSource = New Uri(p, UriKind.RelativeOrAbsolute)
'img.Source = New BitmapImage(uriImageSource)
Dim Bimage As New BitmapImage()
Bimage.BeginInit()
Bimage.CacheOption = BitmapCacheOption.OnLoad
Bimage.UriSource = New Uri(p)
If info.Extension.ToLower = ".gif" Then Bimage.Rotation += Rotation.Rotate90
Bimage.EndInit()
'img.Width = 100
'img.Height = 100
img.Source = Bimage
page.Children.Add(img)
Dim pageContent As New PageContent()
DirectCast(pageContent, IAddChild).AddChild(page)
fixedDocument.Pages.Add(pageContent)
Next
' Print me an image please!
printDialog.PrintDocument(fixedDocument.DocumentPaginator, "Print")
End Sub

Categories