SQLite table doesn't get updated - c#

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

Related

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

Is creating an EPT (MS PS Enteprise Project Type) via PSI/CSOM possible?

The following code does not throw any exception but it also doesn't create a new EPT:
public void CreateEnterpriseProjectType(Guid eptGuid, string eptName, string eptDescription)
{
ProjectContext pwaContext = new ProjectContext("http://serverName/pwaName");
pwaContext.Credentials = new NetworkCredential("adminUsername", "adminPassword", "domainName");
EnterpriseProjectTypeCreationInformation eptData = new EnterpriseProjectTypeCreationInformation();
eptData.Id = eptGuid;
eptData.Name = eptName;
eptData.Description = eptDescription;
eptData.IsDefault = false;
eptData.IsManaged = true;
eptData.WorkspaceTemplateName = "PROJECTSITE#0";
eptData.ProjectPlanTemplateId = Guid.Empty;
eptData.WorkflowAssociationId = Guid.Empty;
// Get the maximum order of the existing EPTs and increment by 1 in order to use an order that does not already exist
eptData.Order = Convert.ToInt32(Database.GetValue("SELECT MAX(ENTERPRISE_PROJECT_TYPE_ORDER) FROM [ProjectWebApp].[pub].[MSP_ENTERPRISE_PROJECT_TYPES]")) + 1;
pwaContext.Load(pwaContext.ProjectDetailPages);
pwaContext.ExecuteQuery();
List<ProjectDetailPageCreationInformation> projectDetailPages = new List<ProjectDetailPageCreationInformation>() {new ProjectDetailPageCreationInformation() { Id = pwaContext.ProjectDetailPages[1].Id, IsCreate = false }};
eptData.ProjectDetailPages = projectDetailPages;
EnterpriseProjectType newEpt = pwaContext.EnterpriseProjectTypes.Add(eptData);
pwaContext.EnterpriseProjectTypes.Update();
}
Any ideas on what I'm doing wrong or what I'm missing? Is it possible to create an EPT programmatically?
Yes, it is possible to create an EPT programmatically. Turns out three things were missing:
A second PDP having IsCreate = true (at least one with IsCreate = true and one with IsCreate = false are required for successfully creating an EPT)
A query for iterating through the existing EPTs before adding a new one:
pwaContext.Load(pwaContext.EnterpriseProjectTypes);
pwaContext.ExecuteQuery();
A pwaContext.ExecuteQuery(); after the pwaContext.EnterpriseProjectTypes.Update(); command.
The following code works fine for me:
public class PSI
{
private ProjectContext _context;
private string basicEpt = "Enterprise Project"; // Basic enterprise project type.
private static readonly PSI psi = new PSI();
private int timeoutSeconds = 60;
SvcProject.ProjectClient _prClient;
private PSI ()
{
_context = new ProjectContext(System.Configuration.ConfigurationManager.AppSettings["PwaUrl"]);
//credentials of currently running acount or enable line below
//_context.Credentials = new System.Net.NetworkCredential("user", "pass", "domain");
timeoutSeconds = int.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultTimeoutPwa"]);
_prClient = new SvcProject.ProjectClient("basicHttp_Project");
}
public static PSI Instance
{
get{ return psi; }
}
public Guid GetEptUid(string eptName)
{
Guid eptUid = Guid.Empty;
try
{
var eptList = _context.LoadQuery( _context.EnterpriseProjectTypes.Where(ept => ept.Name == eptName));
_context.ExecuteQuery();
eptUid = eptList.First().Id;
}
catch (Exception ex)
{
string msg = string.Format("GetEptUid: eptName = \"{0}\"\n\n{1}", eptName, ex.GetBaseException().ToString());
throw new ArgumentException(msg);
}
return eptUid;
}
public PublishedProject CreateProject(string prName, string description, DateTime startDate)
{
try
{
System.Console.Write("\nCreating project: {0} ...", prName);
ProjectCreationInformation newProj = new ProjectCreationInformation();
newProj.Id = Guid.NewGuid();
newProj.Name = prName;
newProj.Description = description;
newProj.Start = startDate;
newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt);
PublishedProject newPublishedProj = _context.Projects.Add(newProj);
QueueJob qJob = _context.Projects.Update();
JobState jobState = _context.WaitForQueue(qJob, timeoutSeconds);
if (jobState == JobState.Success)
return newPublishedProj;
else
return null;
}
catch (Exception ex)
{
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("\nError: {0}", ex.Message);
System.Console.ResetColor();
return null;
}
}
}

Delete row in gridview using linq

I wrote this code to delete rows from Gridview but its not working.
code in class.cs:
public bool bDeleteItem(int nItemID)
{
bool flag = false;
try
{
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
IMS_Items oIMS_Items = sNairoukhEntities1.IMS_Items.Where(Entity => Entity.ItemID == nItemID).Single();
sNairoukhEntities1.IMS_Items.Remove(oIMS_Items);
int nResult = sNairoukhEntities1.SaveChanges();
if (nResult > 0)
{
flag = true;
}
}
catch (Exception ex)
{
}
return flag;
}
code in Aspx.cs:
int nId = Convert.ToInt32(gvManageItem.DataKeys[Convert.ToInt32(e.CommandArgument)]["ItemID"].ToString());
if (e.CommandName == "cmDelete")
{
ManageItem oManageItem = new ManageItem();
if (oManageItem.bDeleteItem(nId))
{
lblValidation.Text = "Delete is successfully";
}
else
{
lblValidation.Text = "isnt delete";
}
}
Remove method "Marks the given entity as Deleted such that it will be deleted from the database when SaveChanges is called. Note that the entity must exist in the context in some other state before this method is called."
Below command will work:
sNairoukhEntities1.Entry(oIMS_Items).State = System.Data.Entity.EntityState.Deleted;
sNairoukhEntities1.SaveChanges();

DistinguishedName attribute of Active Directory

This is my code :
public bool ActiveDirectoryAuthenticate(string username, string password)
{
var result = false;
using (var entry = new DirectoryEntry("LDAP://*****/DC=******,DC=biz",username,password,AuthenticationTypes.Secure))
{
var searcher = new DirectorySearcher(entry){Filter = "objectClass=user"};
try
{
var sr = searcher.FindOne();
var PathDic = sr.Properties["distinguishedName"][0].ToString();
result = true;
}
catch (Exception exception)
{
}
}
return result;
}
The problem is
sr.Properties["distinguishedName"][0].ToString();
does not return correct value.
Please help me
Just an idea but don't you need to put value like this :
var PathDic = sr.Properties["distinguishedName"][0].Value.ToString();
My problem resolve:
public bool ActiveDirectoryAuthenticate(string username, string password)
{
var result = false;
using (
var entry = new DirectoryEntry("LDAP://PT/DC=pt,DC=biz", username, password,
AuthenticationTypes.Secure))
{
var searcher = new DirectorySearcher(entry) {Filter = "sAMAccountName=Bank.Members"};
searcher.PropertiesToLoad.Add("distinguishedName");
try
{
var sr = searcher.FindOne();
var name = sr.Properties["distinguishedName"][0].ToString();
result = true;
}
catch (Exception exception)
{
}
}
return result;
}

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