Display Image retrieving from DB - c#

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");
}
}
}

Related

Receiving data from WebClient.UploadString

I am trying to send/receive byte array of image from server to server.
I think i managed to send it but am unable to receive it.
Here is code for sending:
[HttpPost]
[Route("/ARGallery/AUploadImage/{appid}")]
public IActionResult AUploadImage(IFormFile file, int appid)
{
try
{
// Korisnik prosledjuje fajl kroz browser
// Taj fajl ima svoje ime
// Bezbednosti radi proveravam ime fajla i prilagodjavam ga
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
//===============
// Uzimam app model iz buffera
ApplicationsModel am = Buffer.GetApplication(appid);
// Proveravam da li je uspesno uzet model, ako nije uzimam direktno iz faljova
if (am == null)
am = ApplicationsModel.List().Where(a => a.ID == appid).FirstOrDefault();
// Ako je posle svega neuspesno vracam gresku
if (am == null)
return View("Error", "Error loading application info!");
byte[] imageInBytes = null;
System.Drawing.Image img = System.Drawing.Image.FromStream(file.OpenReadStream());
using (var ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
imageInBytes = ms.ToArray();
}
using(var client = new WebClient())
{
return Json(client.UploadString("http://" + am.Name + "/ARGallery/AUploadImage/" + file.FileName, System.Text.Encoding.UTF8.GetString(imageInBytes)));
}
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
and here is receiving code
[HttpPost]
[Route("/ARGallery/AUploadImage/{filename}")]
public IActionResult AUploadImage(string bufferedImage, string filename)
{
try
{
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(bufferedImage));
System.Drawing.Image myimg = Image.FromStream(ms);
while(System.IO.File.Exists(GetPathAndFilename(filename)))
{
string extension = "";
int br = filename.ToString().IndexOf('.');
string ex = filename.ToString().Substring(br);
if (ex == "jpeg")
extension = filename.Substring(filename.Length - 5, 5);
else
extension = filename.Substring(filename.Length - 4, 4);
// Dodajem na ostatak fajl name-a bez extensiona random karaktere i vracam extension nazad
filename = filename.Substring(0, filename.Length - 4) + AR.Security.HashPW(Program.rnd.Next(1000).ToString()).Substring(0, 2) + extension;
}
//Cuvam original format slike u temp folder
myimg.Save(GetPathAndFilename(filename));
// Cuvam osiromaseni format slike u temp folder
LowerQuality((Bitmap)myimg).Save(GetPathAndFilenameLQ(filename));
// Vracam nazad link do slike na remote serveru (serveru aplikacije)
return Json(filename);
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
I get "null" exception on line MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(bufferedImage));
EDIT:
Also what i have tried on sending app side is this but still same problem:
[HttpPost]
[Route("/ARGallery/AUploadImage/{appid}")]
public async Task<IActionResult> AUploadImage(IFormFile file, int appid)
{
try
{
// Korisnik prosledjuje fajl kroz browser
// Taj fajl ima svoje ime
// Bezbednosti radi proveravam ime fajla i prilagodjavam ga
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
//===============
// Uzimam app model iz buffera
ApplicationsModel am = Buffer.GetApplication(appid);
// Proveravam da li je uspesno uzet model, ako nije uzimam direktno iz faljova
if (am == null)
am = ApplicationsModel.List().Where(a => a.ID == appid).FirstOrDefault();
// Ako je posle svega neuspesno vracam gresku
if (am == null)
return View("Error", "Error loading application info!");
byte[] imageInBytes = null;
System.Drawing.Image img = System.Drawing.Image.FromStream(file.OpenReadStream());
using (var ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
imageInBytes = ms.ToArray();
}
using(var client = new HttpClient())
{
var options = new
{
bufferedImage = System.Text.Encoding.UTF8.GetString(imageInBytes),
filename = file.FileName
};
HttpResponseMessage message = await client.PostAsync("http://" + am.Name + "/ARGallery/AUploadImage", new StringContent(JsonConvert.SerializeObject(options), Encoding.UTF8, "application/json"));
return Json(await message.Content.ReadAsStringAsync());
}
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}

SQLite table doesn't get updated

I have a problem. I created a SwitchButton and want to store the state in a database table. So I created this code to debug:
SettingSwitch.CheckedChange += (s, b) =>
{
SettingDb testsetting = new SettingDb
{
Name = mItems[position].Name,
};
SettingDb test = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test != null)
{
bool SwitchValueBool = Convert.ToBoolean(test.Value);
}
bool isChecked = ValueDictionary[position];
if(isChecked == true)
{
isChecked = false;
}
else if(isChecked == false)
{
isChecked = true;
}
SettingDb setting = new SettingDb()
{
Name = SettingName.Text,
Type = "Switch",
Value = isChecked.ToString()
};
MainActivity.db.UpdateTableSettings(setting);
ValueDictionary[position] = isChecked;
SettingDb test2 = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test2 != null)
{
bool SwitchValueBool = Convert.ToBoolean(test2.Value);
}
};
The expected outcome should be:
test.Value = False
test2.Value = Opposite of test.Value, so True
But now the value I get from the table is always False. Here is the update function:
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool UpdateTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
connection.BeginTransaction();
connection.Query<SettingDb>("UPDATE SettingDb SET Value=? WHERE Name=?", setting.Value, setting.Name);
//connection.Update(setting);
connection.Commit();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public SettingDb SelectRowFromTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT * FROM SettingDb WHERE Name=?", setting.Name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
The table value doesn't get updated!!!
Can someone tell me what I am doing wrong?
Please let me know!
According to your description, you want to update sqlite database table, please take a look the following code and modify the update function.
static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
var db = new SQLiteConnection(path, false);
string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
string[] parms = new String[] { newText, newValue.ToString(), primaryKey.ToString() };
var cmd = db.CreateCommand(sql, parms);
cmd.ExecuteNonQuery();
}

Error: Exception of type 'System.OutOfMemoryException' was thrown on my C# win form program with firebird database and DevExpress

I am having trouble with system.outofmemoryexception on my C# win application. I don't know the cause of the error. The computer memory is not freeing.
I am using visual studio 2017 and devexpress 2017 with Firebird 3 as my database.
here is a sample of my database procedures
CREATE PROCEDURE APP_INSERT(
WORKXP_PK INTEGER,
EMP_PK INTEGER,
APP_FRONT BLOB,
APP_BACK BLOB,
USER_PK SMALLINT,
APP_UPDATETIME TIMESTAMP)
AS
BEGIN
INSERT INTO APPOINTMENT (
WORKXP_PK,
EMP_PK,
APP_FRONT,
APP_BACK,
USER_PK,
APP_UPDATETIME)
VALUES (
:WORKXP_PK,
:EMP_PK,
:APP_FRONT,
:APP_BACK,
:USER_PK,
CURRENT_TIMESTAMP);
END;
CREATE PROCEDURE APP_UPDATE(
APP_FRONT BLOB,
APP_BACK BLOB,
USER_PK SMALLINT,
APP_UPDATETIME TIMESTAMP,
WORKXP_PK INTEGER)
AS
BEGIN
UPDATE APPOINTMENT
SET
APP_FRONT = :APP_FRONT,
APP_BACK = :APP_BACK,
USER_PK = :USER_PK,
APP_UPDATETIME = CURRENT_TIMESTAMP
WHERE
(WORKXP_PK = :WORKXP_PK);
END;
And here is a sample of my c# class
using DevExpress.XtraEditors;
using FirebirdSql.Data.FirebirdClient;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
namespace DepEdZDSMS.Class
{
class ClsAppointmntPic : IDisposable
{
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
FirebirdService.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public MemoryStream APP_FRONT { get; set; }
public MemoryStream APP_BACK { get; set; }
public void UpdateAppImage()
{
byte[] x = null; //front image
byte[] y = null; //back image
try
{
var adder = new FbConnection(ClsConnectionImages.FirebirdSQL);
var fbcmd = new FbCommand("APP_UPDATE", adder)
{
CommandType = CommandType.StoredProcedure
};
if (APP_FRONT != null) x = APP_FRONT.ToArray();
fbcmd.Parameters.Add("#APP_FRONT", FbDbType.Binary).Value = x;
if (APP_BACK != null) y = APP_BACK.ToArray();
fbcmd.Parameters.Add("#APP_BACK", FbDbType.Binary).Value = y;
fbcmd.Parameters.Add("#USER_PK", FbDbType.SmallInt).Value = ClsEmployee.USER_PK;
fbcmd.Parameters.Add("#APP_UPDATETIME", FbDbType.VarChar).Value = EventTimestamp;
fbcmd.Parameters.Add("#WORKXP_PK", FbDbType.VarChar).Value = ClsEmployee.UpdateHandler2;
fbcmd.Connection.Open();
fbcmd.ExecuteNonQuery();
fbcmd.Connection.Close();
}
catch (Exception errorcode)
{
XtraMessageBox.Show(String.Format("Error in connection: {0}. Saving failed.", errorcode.Message), #"Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public void SaveAppImage() //122
{
byte[] x = null; //front image
byte[] y = null; //back image
try
{
var adder = new FbConnection(ClsConnectionImages.FirebirdSQL);
var fbcmd = new FbCommand("APP_INSERT", adder)
{
CommandType = CommandType.StoredProcedure
};
fbcmd.Parameters.Add("#WORKXP_PK", FbDbType.VarChar).Value = ClsEmployee.UpdateHandler2;
fbcmd.Parameters.Add("#EMP_PK", FbDbType.VarChar).Value = ClsEmployee.UpdateHandler;
if (APP_FRONT != null) x = APP_FRONT.ToArray();
fbcmd.Parameters.Add("#APP_FRONT", FbDbType.Binary).Value = x;
if (APP_BACK != null) y = APP_BACK.ToArray();
fbcmd.Parameters.Add("#APP_BACK", FbDbType.Binary).Value = y;
fbcmd.Parameters.Add("#USER_PK", FbDbType.SmallInt).Value = ClsEmployee.USER_PK;
fbcmd.Parameters.Add("#APP_UPDATETIME", FbDbType.VarChar).Value = EventTimestamp;
fbcmd.Connection.Open();
fbcmd.ExecuteNonQuery();
fbcmd.Connection.Close();
}
catch (Exception errorcode)
{
XtraMessageBox.Show(String.Format("Error in connection: {0}. Saving failed.", errorcode.Message), #"Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public ClsAppointmntPic(int refID)
{
try
{
var app = new ClsAppointmntPic();
var x = new DataSet();
var y = new FbDataAdapter();
var f = new FbCommand("IMAGE_APPOINTMENT", FirebirdService);
f.Parameters.Add("#X", FbDbType.Integer).Value = refID;
f.CommandType = CommandType.StoredProcedure;
y.SelectCommand = f;
y.Fill(x, "APPOINTMENT");
if (x.Tables[0].Rows.Count > 0)
{
var fx = x.Tables[0].Rows[0];
if (!fx["APP_FRONT"].Equals(DBNull.Value))
{
var i = (byte[])fx["APP_FRONT"];
var fx2 = new MemoryStream(i);
APP_FRONT = fx2;
}
if (!fx["APP_BACK"].Equals(DBNull.Value))
{
var j = (byte[])fx["APP_BACK"];
var fx2 = new MemoryStream(j);
APP_BACK = fx2;
}
}
app.FirebirdService.Close();
}
catch (Exception e)
{
XtraMessageBox.Show(#"Error: " + e.Message, #"DepEdZDSUIS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public ClsAppointmntPic()
{
// TODO: Complete member initialization
}
private void Openconnection()
{
if (FirebirdService.State == ConnectionState.Open)
{
FirebirdService.Close();
}
FirebirdService.Open();
}
private void Closeconnection()
{
FirebirdService.Close();
}
private static readonly string Firebird = ClsConnectionImages.FirebirdSQL;
/// <summary>
///
/// </summary>
private readonly FbConnection FirebirdService = new FbConnection(Firebird);
}
}
and also I used public static string and int frequently and some arrays
public static int sdsapprove_ref = 0;
public static string sdsapprove_word = "";
public static string[] reasonReg = new string[] { "Deceased", "Promoted to", "Retired", "Resigned",
"Transferred to"};
in my main view form I use this code in displaying data
private void GetWorkXPList()
{
picAppFront.Image = Properties.Resources.no_image;
picAppBack.Image = Properties.Resources.no_image;
ClsEmployee.UpdateHandler2 = "0";
gridControl2.DataSource = ClsEmployee.WorkXP_SrvcRcrdListing();
gridView2.OptionsSelection.InvertSelection = false;
gridView2.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView2.OptionsSelection.EnableAppearanceFocusedRow = true;
}
public void GetAppointmentImage()
{
int getID = Convert.ToInt32(ClsEmployee.UpdateHandler2);
var f = new ClsAppointmntPic(getID);
if (f.APP_FRONT != null)
{
var i = new Bitmap(f.APP_FRONT);
picAppFront.Image = i;
}
else
{
picAppFront.Image = Properties.Resources.no_image;
}
if (f.APP_BACK != null)
{
var j = new Bitmap(f.APP_BACK);
picAppBack.Image = j;
}
else
{
picAppBack.Image = Properties.Resources.no_image;
}
}
and in my save/update form, i use this codes when saving and editing
private void UpdateWorXP()
{
var adder = new ClsEmployee()
{
WORKXP_DATEFROM = dateFrom.Text,
WORKXP_DATETO = dateTo.Text,
WORKXP_PRESENT = ifPresent,
WORKXP_POSITION = txtPosition.Text,
WORKXP_ABBR = txtAbb.Text,
WORKXP_ITMENUM = txtItemNo.Text,
WORKXP_AGENCY = txtAgency.Text,
WORKXP_STATION = txtStation.Text,
WORKXP_BRANCH = txtBranch.Text,
WORKXP_SLRYGRD = txtSG.Text,
WORKXP_INCRMNT = cboxIncrmnt.Text,
WORKXP_SALARYANN = txtAnnual.Text,
WORKXP_SALARYMON = txtMonthly.Text,
WORKXP_STATUS = cboxStatus.Text,
WORKXP_GOVORPRIV = cboxGov.Text,
WORKXP_CAUSE = cboxCause.Text,
WORKXP_AMOUNT = Convert.ToDecimal(txtAmount.Text),
};
adder.EditWorkXP();
adder.UpdateLog();
//UpdateEmpLatestApp();
XtraMessageBox.Show("Successfully Updated.", "Update ",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
ClsEmployee.UpdateHandler2 = "0";
switch (ClsArray.Reference)
{
case 1:
obj1.loaddata();
break;
case 2:
obj2.loaddata();
break;
case 3:
obj3.loaddata2();
break;
}
this.Close();
}
private void AddNewWorkXP()
{
var adder = new ClsEmployee()
{
WORKXP_DATEFROM = dateFrom.Text,
WORKXP_DATETO = dateTo.Text,
WORKXP_PRESENT = ifPresent,
WORKXP_POSITION = txtPosition.Text,
WORKXP_ABBR = txtAbb.Text,
WORKXP_ITMENUM = txtItemNo.Text,
WORKXP_AGENCY = txtAgency.Text,
WORKXP_STATION = txtStation.Text,
WORKXP_BRANCH = txtBranch.Text,
WORKXP_SLRYGRD = txtSG.Text,
WORKXP_INCRMNT = cboxIncrmnt.Text,
WORKXP_SALARYANN = txtAnnual.Text,
WORKXP_SALARYMON = txtMonthly.Text,
WORKXP_STATUS = cboxStatus.Text,
WORKXP_GOVORPRIV = cboxGov.Text,
WORKXP_CAUSE = cboxCause.Text,
WORKXP_AMOUNT = Convert.ToDecimal(txtAmount.Text),
};
adder.SaveWorkXP();
adder.UpdateLog();
//UpdateEmpLatestApp();
XtraMessageBox.Show("Successfully Saved.", "Save ",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
ClsEmployee.UpdateHandler2 = "0";
switch (ClsArray.Reference)
{
case 1:
obj1.loaddata();
break;
case 2:
obj2.loaddata();
break;
case 3:
obj3.loaddata2();
break;
}
this.Close();
}

How to Suppy Data Model to Print Function

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);
}
}

How to mapping column from oledbsource to oledbdestination using SSIS in C#

I want to make mapping from
OleDbSource (select mFK_Prefix,mFK_Sufix,mElement_Base,mBase_Value,mPeriode_Start,mPeriode_End,mSandi_Pelapor,mOrder from [dbo].[STG_AAKL])
to
OledbDestination(select FK_Prefix,FK_Sufix,Element_Base,Base_Value,Periode_Start,Periode_End,Sandi_Pelapor,Order from [dbo].[TM_AAKL])
How to programmatically make mapping from oledbsource to oledbdestination using ssis inc#.
for complete or my program there is at below this
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
string DestinationCS = #"Data Source=.\SQL2012;Initial Catalog=DWH_LSMK;Provider=SQLOLEDB.1;Integrated Security=SSPI;Application Name=SSIS-Package;Auto Translate=False;";
string SourceCS = #"Data Source=.\SQL2012;Initial Catalog=DWH_LSMK;Provider=SQLOLEDB.1;Integrated Security=SSPI;Application Name=SSIS-Package;Auto Translate=False;";
GeneratePackage(SourceCS, DestinationCS);
Dts.TaskResult = (int)ScriptResults.Success;
}
protected ConnectionManager AddOleFbConnection(Package pck, string nameConexion, string cadenaConection)
{
ConnectionManager Cm;
Cm = pck.Connections.Add("OLEDB");
Cm.ConnectionString = cadenaConection;
Cm.Name = nameConexion;
return (Cm);
}
protected virtual TaskHost AddDataFlow(Package pck,string dataFlowName)
{
Executable e = pck.Executables.Add("STOCK:PipelineTask");
TaskHost thMainPipe = (TaskHost)e;
thMainPipe.Name = dataFlowName;
return (thMainPipe);
}
protected virtual IDTSComponentMetaData100 AddSourceOledbFromTable(MainPipe flujo,string nombrecomponenete,string nombretable,ConnectionManager Connection )
{
IDTSComponentMetaData100 ConexionAoregen = flujo.ComponentMetaDataCollection.New();
ConexionAoregen.Name = nombrecomponenete;
ConexionAoregen.ComponentClassID = "DTSAdapter.OleDbSource";
CManagedComponentWrapper instance = ConexionAoregen.Instantiate();
instance.ProvideComponentProperties();
ConexionAoregen.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(Connection);
ConexionAoregen.RuntimeConnectionCollection[0].ConnectionManagerID = Connection.ID;
ConexionAoregen.Name = nombrecomponenete;
instance.SetComponentProperty("AccessMode",0);
instance.SetComponentProperty("OpenRowset", nombretable);
try
{
instance.AcquireConnections(null);
instance.ReinitializeMetaData();
instance.ReleaseConnections();
}
catch (Exception e)
{
throw;
}
return (ConexionAoregen);
}
protected virtual IDTSComponentMetaData100 AddOleDbDestinationTable(MainPipe DataFlowTask,ConnectionManager destinationconnection,IDTSComponentMetaData100 fuentedatos,string tabledestination)
{
IDTSComponentMetaData100 ComponentDestino = DataFlowTask.ComponentMetaDataCollection.New();
ComponentDestino.ComponentClassID = "DTSAdapter.OleDbDestination";
CManagedComponentWrapper instance = ComponentDestino.Instantiate();
instance.ProvideComponentProperties();
ComponentDestino.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(destinationconnection);
ComponentDestino.RuntimeConnectionCollection[0].ConnectionManagerID = destinationconnection.Name;
instance.SetComponentProperty("AccessMode",3);
//instance.SetComponentProperty("FastLoadOptions","TABLOCK,CHECK_CONSTRAINTS");
instance.SetComponentProperty("OpenRowset", tabledestination);
IDTSPath100 union = DataFlowTask.PathCollection.New();
union.AttachPathAndPropagateNotifications(fuentedatos.OutputCollection[0], ComponentDestino.InputCollection[0] );
instance.AcquireConnections(null);
instance.ReinitializeMetaData();
instance.ReleaseConnections();
foreach (IDTSOutputColumn100 col in fuentedatos.OutputCollection[0].OutputColumnCollection)
{
for (int i = 0; i < ComponentDestino.InputCollection[0].ExternalMetadataColumnCollection.Count; i += 1)
{
string campo = ComponentDestino.InputCollection[0].ExternalMetadataColumnCollection[i].Name;
if ((col.Name.ToUpper() == "MPERIODE_START") && (campo.ToUpper() == "PERIODE_END"))
{
IDTSInputColumn100 colnueva = ComponentDestino.InputCollection[0].InputColumnCollection.New();
colnueva.LineageID = col.ID;
colnueva.ExternalMetadataColumnID = col.ID;
colnueva.MappedColumnID = col.ID;
colnueva.Name = col.Name;
// break;
}
else if ((col.Name.ToUpper() == "MPERIODE_END") && (campo.ToUpper() == "PERIODE_START"))
{
IDTSInputColumn100 colnueva = ComponentDestino.InputCollection[0].InputColumnCollection.New();
colnueva.LineageID = col.ID;
colnueva.ExternalMetadataColumnID = col.ID;
colnueva.MappedColumnID = col.ID;
colnueva.Name = col.Name;
//break;
}
}
}
foreach (IDTSInputColumn100 inputColumn in ComponentDestino.InputCollection[0].InputColumnCollection)
Console.WriteLine(inputColumn.Name);
Console.Read();
return (ComponentDestino);
}
public void GeneratePackage(string SourceConnectionString, string DestinationConnectionString)
{
OleDbConnection cn = new OleDbConnection(SourceConnectionString);
cn.Open();
Package Mipk = new Package();
Mipk.Name = "KBGK_AAKL";
Application App = new Application();
ConnectionManager ConnOrigen = AddOleFbConnection(Mipk, "Source", SourceConnectionString);
ConnectionManager ConnDestina = AddOleFbConnection(Mipk, "Destination", DestinationConnectionString);
MainPipe Df = AddDataFlow(Mipk,"KBGK AAKL").InnerObject as MainPipe ;
IDTSComponentMetaData100 source = AddSourceOledbFromTable(Df, "Source Component", "STG_AAKL", ConnOrigen);
AddOleDbDestinationTable(Df, ConnDestina,source,"TM_AAKL" );
App.SaveToXml(String.Format(#"D:\\LSMK-source\\SSIS\\AutoGenerate\\Autogenerate_AAKL.dtsx", Mipk.Name), Mipk, null);
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Try using bulkcopy function... it will help you to get ridoff DFT ....

Categories