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 ....
Related
I wrote a bot in C#, I used Selenium.
Problem: When I start more threads at same time, the bot does the work in the first window. All of the e-mail addresses are being added to the "E-mail" textbox in the same window instead of one e-mail address per window.
But it should look like:
Start function: DivisionStart()
private void DivisionStart() {
foreach(var account in BotConfig.AccountList) {
while (CurrentBotThreads >= BotConfig.MaxLoginsAtSameTime) {
Thread.Sleep(1000);
}
StartedBotThreads++;
CurrentBotThreads++;
int startIndex = (StartedBotThreads * BotConfig.AdsPerAccount + 1) - BotConfig.AdsPerAccount - 1;
int stopIndex = BotConfig.AdsPerAccount * CurrentBotThreads;
if (stopIndex > BotConfig.ProductList.Count) {
stopIndex = BotConfig.ProductList.Count;
}
Debug.Print("Thread: " + StartedBotThreads);
var adList = GetAdListBy(startIndex, stopIndex);
foreach(var ad in adList) {
Debug.Print("Für thread: " + StartedBotThreads + " | Anzeige: " + ad.AdTitle);
}
Debug.Print("Parallel");
var ebayBotThread = new Thread(() => {
var botOptions = new IBotOptionsModel() {
CaptchaSolverApiKey = CaptchaSolverApiKey,
ReCaptchaSiteKey = "6LcZlE0UAAAAAFQKM6e6WA2XynMyr6WFd5z1l1Nr",
StartPageUrl = "https://www.ebay-kleinanzeigen.de/m-einloggen.html?targetUrl=/",
EbayLoginEmail = account.AccountEmail,
EbayLoginPassword = account.AccountPassword,
Ads = adList,
};
var ebayBot = new EbayBot(this, botOptions);
ebayBot.Start(StartedBotThreads);
Thread.Sleep(5000);
});
ebayBotThread.Start();
}
}
The class with function which will be executed in each thread:
using OpenQA.Selenium;
using Selenium.WebDriver.UndetectedChromeDriver;
using System.Diagnostics;
using TwoCaptcha.Captcha;
using System.Drawing;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
namespace EbayBot
{
class EbayBot
{
public Selenium.Extensions.SlDriver Driver;
private WebDriverHelper DriverHelper;
private Bot Sender;
private bool CaptchaSolved = false;
public IBotOptionsModel Options;
public EbayBot(Bot sender, IBotOptionsModel options)
{
Sender = sender;
Options = options;
}
public void Start(int threadIndex)
{
var chromeOptions = new ChromeOptions();
/*if (Sender.BotConfig.EnableProxy)
{
chromeOptions.AddHttpProxy(
Options.Proxy.IpAddress,
Options.Proxy.Port,
Options.Proxy.Username,
Options.Proxy.Password
);
}*/
Driver = UndetectedChromeDriver.Instance(null, chromeOptions);
DriverHelper = new WebDriverHelper(Driver);
string status = "";
Debug.Print("Bot-Thread: " + threadIndex);
Driver.Url = Options.StartPageUrl + Options.EbayLoginEmail;
PressAcceptCookiesButton();
Login();
if (!CaptchaSolved) return;
Driver.Wait(3);
if (LoginError() || !IsLoggedIn())
{
status = "Login für '" + Options.EbayLoginEmail + "' fehlgeschlagen!";
Debug.Print(status);
Sender.ProcessStatus = new IStatusModel(status, Color.Red);
return;
}
else
{
status = "Login für '" + Options.EbayLoginEmail + "' war erfolgreich!";
Debug.Print(status);
Sender.ProcessStatus = new IStatusModel(status, Color.Green);
}
Driver.Wait(5);
BeginFillFormular();
}
private bool CookiesAccepted()
{
try
{
var btnAcceptCookies = Driver.FindElement(By.Id(Config.PageElements["id_banner"]));
return btnAcceptCookies == null;
}
catch (Exception)
{
return true;
}
}
private void PressAcceptCookiesButton()
{
DriverHelper.WaitForElement(Config.PageElements["id_banner"], "", 10);
if (CookiesAccepted()) return;
var btnAcceptCookies = Driver.FindElement(By.Id(Config.PageElements["id_banner"]));
btnAcceptCookies.Click();
}
private bool IsLoggedIn()
{
Debug.Print("Check if logged in already");
try
{
var userEmail = Driver.FindElement(By.Id("user-email")).Text;
return userEmail.ToLower().Contains(Options.EbayLoginEmail);
}
catch (Exception)
{
return false;
}
}
private bool LoginError()
{
try
{
var loginErrorH1 = Driver.FindElements(By.TagName("h1"));
return loginErrorH1[0].Text.Contains("ungültig");
}
catch (Exception)
{
return false;
}
}
private void Login()
{
if (IsLoggedIn()) return;
string status = "Anmelden bei " + Options.EbayLoginEmail + "...";
Debug.Print(status);
Sender.ProcessStatus = Sender.ProcessStatus = new IStatusModel(status, Color.DimGray);
Driver.Wait(5);
var fieldEmail = Driver.FindElement(By.Id(Config.PageElements["id_login_email"]));
var fieldPassword = Driver.FindElement(By.Id(Config.PageElements["id_login_password"]));
var btnLoginSubmit = Driver.FindElement(By.Id(Config.PageElements["id_login_button"]));
fieldEmail.SendKeys(Options.EbayLoginEmail);
Driver.Wait(4);
fieldPassword.SendKeys(Options.EbayLoginPassword);
SolveCaptcha();
if (!CaptchaSolved)
{
return;
}
Debug.Print("Clicking login button");
btnLoginSubmit.Click();
}
public void BeginFillFormular()
{
Debug.Print("Formular setup, Inserate: " + Options.Ads.Count);
foreach (var adData in Options.Ads)
{
Debug.Print("Setting up formular for " + adData.AdTitle);
var adFormular = new AdFormular(Driver, adData, Options);
adFormular._EbayBot = this;
adFormular.CreateAd(Sender);
// 10 seconds
Debug.Print("Nächstes Insert für " + adData.AdTitle);
}
}
public string GetSolvedCaptchaAnswer(string captchaUrl = "")
{
string code = string.Empty;
var solver = new TwoCaptcha.TwoCaptcha(Options.CaptchaSolverApiKey);
var captcha = new ReCaptcha();
captcha.SetSiteKey(Options.ReCaptchaSiteKey);
captcha.SetUrl(captchaUrl == "" ? Options.StartPageUrl : captchaUrl);
try
{
solver.Solve(captcha).Wait();
code = captcha.Code;
}
catch (AggregateException e)
{
Sender.ProcessStatus = new IStatusModel("Captcha Api-Fehler: " + e.InnerExceptions.First().Message, Color.Red);
Driver.Wait(10);
}
return code;
}
public void SolveCaptcha(string captchaUrl = "")
{
Debug.Print("Solving captcha...");
var solvedCaptchaAnswer = GetSolvedCaptchaAnswer(captchaUrl);
if (solvedCaptchaAnswer == string.Empty)
{
Debug.Print("Captcha konnte nicht gelöst werden");
Sender.ProcessStatus = new IStatusModel("Captcha konnte nicht gelöst werden", Color.Red);
CaptchaSolved = false;
Driver.Wait(10);
return;
}
CaptchaSolved = true;
Debug.Print("Captcha answer: " + solvedCaptchaAnswer);
Driver.ExecuteScript("document.getElementById('g-recaptcha-response').innerHTML = '" + solvedCaptchaAnswer + "'");
Debug.Print("Captcha solved!");
Driver.Wait(2);
}
}
}
If I remove the Thread.Sleep(5000); in the DivisionStart function it will work, but I need it I actually want to wait for a found proxy but I simulated it with Thread.Sleep
How can I solve my problem?
Thanks for any answer!
I fixed it.
I used UndetectedChromeDriver wich does not use different ports.
I use another Undetected driver now.
Thank you all
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();
}
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();
}
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;
}
}
}
While sending email via System.Net.Mail to multiple recipients (one single email with multiple recipients), if one recipients address fail, will the rest reach the email?
There might be duplicates of the same question, but I'm asking something different in contrast.
For prompting such question, I was taken into consideration of Email clients available like Outlook where such does not happen even if one single address failed. Perhaps, System.Net.Mail is a lightweight client and does not allow such functionality? Or is it the way I'm writing my code incorrectly.
I was asked as if why this happens, hope I can get an explanation so that I can pass it by.
I was running such a scenario from my code below:
public void sendBusinessEmail(communication.email.business.config.BusinessEmailList[] aEmailList)
{
System.Net.Mail.MailMessage objMsg = null;
string[] aEmail = null;
System.Net.Mail.SmtpClient objSmtpClient = null;
int iRetries = 0;
if (aEmailList == null)
{
return;
}
try
{
if (Properties.Settings.Default.IS_SMTP_TLS)
{
objSmtpClient = getSMTP_TLS_Client();
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
}
else
{
objSmtpClient = getSMTP_Default_Client();
}
foreach (communication.email.business.config.BusinessEmailList obj in aEmailList)
{
try
{
objMsg = new System.Net.Mail.MailMessage();
objMsg.From = new System.Net.Mail.MailAddress("jkstock#keells.com", "JKSB Business Services");
aEmail = obj.Emails;
if (Properties.Settings.Default.TO_TEST_EMAIL)
{
objMsg.To.Add(Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString());
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.Body += aEmail[i] + Environment.NewLine;
}
}
else
{
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.To.Add(new System.Net.Mail.MailAddress(aEmail[i]));
}
objMsg.Body = obj.EmailBody;
}
objMsg.Subject = checkAllReadySent(obj.EmailSubject);
objMsg.Attachments.Add(new System.Net.Mail.Attachment(obj.AttachmentPath, (System.IO.Path.GetExtension(obj.AttachmentPath) == ".pdf" ? System.Net.Mime.MediaTypeNames.Application.Pdf : System.Net.Mime.MediaTypeNames.Application.Octet)));
//sending emails
//send for 5 times if error persists, unless otherwise success
for (int i = 0; i < 5; i++)
{
try
{
objSmtpClient.Send(objMsg);
obj.updateLog("OK", (i+1));
break;
}
catch (Exception e)
{
if (i == 4)
{
obj.updateLog(e.Message, (i+1));
}
}
}
objMsg = null;
}
catch (System.Net.Mail.SmtpFailedRecipientsException e0)
{
obj.updateLog("Invalid Recipient(s)",0);
}
catch (Exception e1)
{
obj.updateLog("Error",0);
}
}
objSmtpClient = null;
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
objMsg = null;
objSmtpClient = null;
}
}
References for the above code:
public abstract class BusinessEmailList
{
private string _accountid = string.Empty;
private string _attachmentPath = string.Empty;
private string _emailsubject = string.Empty;
private string _agentid = string.Empty;
private string _response = string.Empty;
private string _ccTo = string.Empty;
private string _bccTo = string.Empty;
protected string _additionalBody = string.Empty;
private string[] _aEmail = null;
public string AccountID
{
get { return _accountid; }
set { _accountid = value; }
}
public string AgentID
{
get { return _agentid; }
set { _agentid = value; }
}
public string Response
{
get { return _response; }
set { _response = value; }
}
public string AttachmentPath
{
get { return _attachmentPath; }
set
{
if (System.IO.File.Exists(value))
{
_attachmentPath = value;
}
else { throw (new Exception("Attachment Not Found")); }
}
}
public string EmailSubject
{
get { return _emailsubject; }
set { _emailsubject = value; }
}
public string[] Emails
{
get { return getEmail(); }
}
public string EmailBody
{
get { return getMsgBody(); }
set { _additionalBody = value; }
}
public string ccTo
{
get { return _ccTo; }
set { _ccTo = value; }
}
public string bccTo
{
get { return _bccTo; }
set { _bccTo = value; }
}
public virtual string[] getEmail()
{
return null;
}
public virtual string getMsgBody()
{
if (System.IO.Path.GetExtension(this.AttachmentPath) == ".pdf")
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"To view the attached PDF files you need Adobe Acrobat Reader installed in your computer. Download Adobe Reader from http://get.adobe.com/reader/ " +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
else
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
}
public void updateLog(string status, int retries)
{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "JKSBSCHEMA.EMAILLOG_ADD_PROC";
string[] aEmail = this.Emails;
OracleParameter p = null;
foreach (string s in aEmail)
{
cmd.Parameters.Clear();
p = new OracleParameter("pemail", OracleType.VarChar);
p.Value = s;
cmd.Parameters.Add(p);
p = new OracleParameter("psubject", OracleType.VarChar);
p.Value = this.EmailSubject;
cmd.Parameters.Add(p);
p = new OracleParameter("pattachement", OracleType.VarChar);
p.Value = this.AttachmentPath;
cmd.Parameters.Add(p);
p = new OracleParameter("presponse", OracleType.VarChar);
p.Value = status;
cmd.Parameters.Add(p);
p = new OracleParameter("pseqno", OracleType.Number);
p.Direction = ParameterDirection.InputOutput;
p.Value = "0";
cmd.Parameters.Add(p);
p = new OracleParameter("pretries", OracleType.Number);
p.Value = retries;
cmd.Parameters.Add(p);
oracleConn.Open();
cmd.ExecuteNonQuery();
oracleConn.Close();
}
}
}
catch (Exception er)
{
this.Response = er.Message;
}
}
}
public class BusinessClientEmailList : BusinessEmailList
{
public override string[] getEmail()
{
string[] aEmail;
//if (Properties.Settings.Default.TO_TEST_EMAIL == false)
//{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
string sql = "SELECT EMAIL " +
"FROM " +
"(" +
"SELECT A.EMAIL AS EMAIL " +
"FROM JKSBSCHEMA.AGENTEMAIL A " +
"WHERE A.AGENTID = '" + this.AgentID + "' " +
"AND A.AGENTID != 'JKSB' "+
"AND A.ISACTIVE = 1 " +
"UNION " +
"SELECT B.EMAILID AS EMAIL " +
"FROM JKSBSCHEMA.CLIENTACCOUNTEMAIL B " +
"WHERE B.CLIENTACCOUNTID = '" + this.AccountID + "' " +
"AND B.IS_CONFIRMATION = 1 " +
") " +
"GROUP BY EMAIL";
int i = 0;
DataTable tbl = new DataTable();
OracleCommand cmd = new OracleCommand(sql, oracleConn);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(tbl);
aEmail = new string[tbl.Rows.Count];
foreach (DataRow rw in tbl.Rows)
{
aEmail[i] = rw[0].ToString();
i++;
}
}
}
catch (Exception)
{
aEmail = null;
}
//}
//else
//{
// aEmail = new string[1];
// aEmail[0] = Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString();
//}
return aEmail;
}
public override string getMsgBody()
{
return base.getMsgBody();
}
}