inserting into SQL via sqlbulk - sqlbulkcopy

hallo i have this sniped code like this:
public static void Put_CSVtoSQL_Adhesion()
{
bool IsFirst = true;
DataTable dt = new DataTable();
string line = null;
int i = 0;
try
{
string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);
using (StreamReader sr = File.OpenText(fileName))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(';');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
// Pour enlever la tete
if (!IsFirst) dt.Rows.Add(row);
IsFirst = false;
}
}
}
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
{
int CountColl = dt.Columns.Count;
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
copy.DestinationTableName = "cotisation";
copy.WriteToServer(dt);
}
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
this code work well, but now i have more than 60 column, should i type manualy from 1 to 60 column or there are another methode ?
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
...until 60 column ?
the column is all the same i just shifted 1 column, because the first one is autoincremented column as an ID

Write a loop?
for (int i = 0; i < dt.Columns.Count - 1; i++)
{
copy.ColumnMappings.Add(i, i + 1);
}

Related

DOCX4J conditional paragaph update merge FieldUpdater Does not work

Using a legacy IF field code:
enter image description here
and content controls:
private static byte[] mergingDocxFileWithXml(File file, File fileXml) {WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file)
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart()
ArrayList<String> datas
List<Object> contentControls = ContentControl.getAllContentControl(mainDocumentPart)
List<String> arrayListXpathToBoucle = new ArrayList<>()
for (Object contenControl : contentControls) {
ContentControl cControl = new ContentControl(contenControl)
String xPath = cControl.getXPath()
String title = cControl.getTitle()
if (xPath != null) {
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
}
switch (title) {
case "DateDuJour":
cControl.setValue(getDateDay())
break
case "checkbox":
String checkValue = new String(Character.toChars(0x2612))
if (datas[0] != "1") {
checkValue = new String(Character.toChars(0x2610))
}
cControl.setValue(checkValue)
break
case "Boucle_Ligne":
xPath = cControl.getTag()
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int totalNode = nodeList.getLength()
for (int j = 0; j < totalNode; j++) {
wordMLPackage = mapingDataNode(j, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, null, 0)
}
wordMLPackage.mainDocumentPart.getContent().remove(indexBoucleContent)
break;
case "Boucle_Colonne":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
String boucleValue = ""
for (int i = 0; i < totalNode; i++) {
datas = XmlPath.getXmlDataFrom(fileXml, dataXpath.get(0))
boucleValue += datas.get(i) + ", "
}
boucleValue = boucleValue.substring(0, boucleValue.length() - 2)
addValueInContentControl(contentControls, dataXpath.get(0), 0, boucleValue, null, wordMLPackage)
break
case "Boucle_Ligne_Table":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int nodeIndex = 0
Tbl arraysBoucle = getArraysBoucle(wordMLPackage, indexBoucleContent)
Tr trContent
for (int i = 0; i < totalNode; i++) {
nodeIndex = i + 1
if (arraysBoucle.getContent().stream().count() > 1) {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(1))
} else {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(0))
}
wordMLPackage = mapingDataNode(i, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, trContent, nodeIndex)
}
int lastIndexTr = wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.stream().count()
wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.remove(lastIndexTr - 1)
break
case "IMAGE":
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
byte[] imageByte = base64ToImage(datas.get(0))
Inline inlineImage = newImage(wordMLPackage, imageByte)
cControl.setValue(null, inlineImage)
break
default:
String xpathBoucle = arrayListXpathToBoucle.find { it.startsWith(xPath) }
if (xpathBoucle != xPath) {
addValueInContentControl(contentControls, xPath, 0, "", fileXml,wordMLPackage)
}
break
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wordMLPackage= mergingFieldWordMlPackage(wordMLPackage)
FieldUpdater updater = new FieldUpdater(wordMLPackage)
updater.update(true);
wordMLPackage.save(outputStream);
return outputStream.toByteArray();
}
Docx4j's legacy field processing does not parse IF fields: http://webapp.docx4java.org/OnlineDemo/ecma376/WordML/IF.html
If you need to do that, you'll need to write code to do the parsing.
An alternative would be to use OpenDoPE conditional content controls. With one of these, the content of the SDT is included only if the associated XPath evaluates to true.

get_value of a feature in IFeatureCursor

I'm trying to read the attribute "POSTCODE" of the features in IFeatureCursor. The FID was successful read but the "POSTCODE" was failed. The runtime error 'An expected Field was not found or could not be retrieved properly. Appreciate your advise. Paul
private void test2(IFeatureCursor pFeatc1)
{
IFeature feature = null;
IFields pFields;
int ctcur = 0;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indxid = pFields.FindField("FID");
int indxpost = pFields.FindField("POSTCODE");
object valu = feature.get_Value(indxid);
string valupost = feature.get_Value(indxpost);
string aValu = Convert.ToString(valu);
Debug.WriteLine("FID: " + aValu + " Postcode: " + valupost);
ctcur++;
feature = pFeatc1.NextFeature();
}
MessageBox.Show("count cursor = " + ctcur);
}
I have modified the program and successfully read the feature attribute 'POSTCODE'. I have added IFeatureClass.Search(queryFilter, true) to search the feature again by FID and save in a cursor then use the 'feature.get_Value' to read the attribute. Please see my updated code below. Thanks.
private void test2(IFeatureCursor pFeatc1)
{
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;
IMap map = mxdoc.FocusMap;
IFeatureLayer flayer;
IMaps pMaps = mxdoc.Maps;
for (int i = 0; i <= pMaps.Count - 1; i++)
{
map = pMaps.get_Item(i);
IEnumLayer pEnumLayer = map.get_Layers(null, true);
pEnumLayer.Reset();
ILayer pLayer = pEnumLayer.Next();
while (pLayer != null)
{
if (pLayer.Name == "AddrKey")
{
Debug.WriteLine("Layer: " + pLayer.Name);
flayer = (IFeatureLayer)pLayer;
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeature feature = null;
IFields pFields;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indx = pFields.FindField("FID");
object valu = feature.get_Value(indx);
string sFID = Convert.ToString(valu);
IQueryFilter queryFilter = new QueryFilter();
queryFilter.WhereClause = ("FID = " + sFID);
Debug.WriteLine("FID: " + sFID);
queryFilter.SubFields = "POSTCODE";
int fieldPosition = pFeatureClass.FindField("POSTCODE");
IFeatureCursor featureCursor = pFeatureClass.Search(queryFilter, true);
while ((feature = featureCursor.NextFeature()) != null)
{
MessageBox.Show(feature.get_Value(fieldPosition));
}
feature = pFeatc1.NextFeature();
}
}
pLayer = pEnumLayer.Next();
}
}
}

JavaFX Tableviews - compare and highlight cells

i am quite new to Javafx, and would like your help in solving the below:
I have two tableviews, and i would like to compare the column values between the two and highlight the cell of one of the tables, if the values are different.
(Assumption - both tables have same number of columns, restricting rows to the minimum content among tables)
ex:
table 1 has
column1 column2 column3
1 America Newyork
table 2 has
column1 column2 column3
1 America Washington
The second table last column should be highlighted with a textfill
I have this pseudo code, doesnt seem to work though
int colsize1= tableview1.getColumns().size();
int colsize2= tableview2.getColumns().size();
if(colsize1 != colsize2) {
alert("number of columns do not match, cannot be validated");
return;
}
ObservableList<ObservableList<String>> da1 = FXCollections.observableArrayList();
ObservableList<ObservableList<String>> da2 = FXCollections.observableArrayList();
da1.addAll(tableview1.getItems());
da2.addAll(tableview2.getItems());
int size = Math.min(da1.size(), da2.size());
for(int i = 0; i < size; i++) {
for (int j = 0; j < colsize1; j++) {
if(!(tableview1.getItems().get(i).get(j).equals(tableview2.getItems().get(i).get(j)))) {
String value = tableview1.getItems().get(i).get(j);
String value2 = tableview2.getItems().get(i).get(j);
int currentrow = i;
TableColumn<TableView<ObservableList<String>>, String> columns = (TableColumn) tableview2.getColumns().get(j);
columns.setCellFactory(column -> {
return new TableCell<TableView<ObservableList<String>>, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
System.out.println("item is " + item + " empty is " + empty);
if(empty){
if(value != value2){
this.setStyle("-fx-background-color : yellow");
}
}
if (!empty) {
if((value != item) && currentrow == getTableRow().getIndex()) {
// int rowindex = getTableRow().getIndex();
System.out.println(" item is " + item);
this.setText(item);
this.setTextFill(Color.RED);
this.setStyle("-fx-background-color : yellow");
}else {
this.setText(item);
}
}
}
};
});
}
}
}
}
I found a solution to the given problem.
#FXML
public void onvalidatebutton() {
int colsize1 = tableview1.getColumns().size();
int colsize2 = tableview2.getColumns().size();
if (colsize1 != colsize2) {
alert("number of columns do not match, cannot be validated");
return;
}
int size = tableview1.getItems().size();
for (int i = 0; i < size; i++) {
for (int j = 0; j < colsize1; j++) {
TableColumn columns2 = tableview2.getColumns().get(j);
// String value = tableview1.getItems().get(currentrow).get(j);
settingcell(columns2);
}
}
}
private void settingcell(TableColumn<ObservableList<String>,String> column) {
column.setCellFactory(col -> {
return new TableCell<ObservableList<String>, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
int ind = getTableView().getVisibleLeafIndex(column);
// System.out.println(" ind is " + ind);
String value = tableview1.getItems().get(this.getIndex()).get(ind);
// System.out.println(" value is " + value + " & item is "+ item);
if (!(StringUtils.equals(value,item))) {
this.setText(item);
this.setTextFill(Color.RED);
this.setStyle("-fx-background-color : yellow");
} else {
this.setText(item);
}
}
else{
this.setText("");
}
}
};
});
}

Binary addition in java

I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}

Change label's text with using property

I am working on my C# ADO.NET app. I have connected my SQL Server database with C# app, and I can perform simple CRUD operations. I want to make that my app open my reminder form when someone in my database have birthday, so I made my query and all persons who have birthday on today's day are in my query, and with using property from my reminder form I change label's text with name and surname of person who have birthday. Now I just dont know how to change next label's text when more than one person have birthday in my query... I dont know how to get next element in my foreach loop...
Here is my code:
Form2 forma = new Form2();
TBirthDayEntities today_born = new TBirthDayEntities();
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
private Boolean provjera_rodj()
{
Boolean flag = false;
int cnt = 0;
IQueryable<TBD> query;
using (var data = new TBirthDayEntities())
{
query = (from x in data.TBD
where x.BirthDay.Day == System.DateTime.Now.Day && x.BirthDay.Month == System.DateTime.Now.Month
select x);
foreach (var x in query)
{
today_born.TBD.Add(x);
cnt += 1;
flag = true;
}
}
switch (cnt)
{
case 1:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + " " + x.LName;
}
break;
}
case 2:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + x.LName;
forma.p_label3 = x.FName + x.LName; //wrong
}
break;
}
}
return flag;
}
private void timer1_Tick(object sender, EventArgs e)
{
Boolean flag = provjera_rodj();
if (flag == true)
{
forma.Show();
timer1.Stop();
}
}
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Label>()
{
forma.p_label2
, forma.p_label3
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x in today_born.TBD[i];
lstLabel[x].Text = x.FName + x.LName;
}
break;
}
}
EDIT:
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Action<string>>()
{
new Action<string>(s =>forma.p_label2 = s)
, new Action<string>(s =>forma.p_label3 = s)
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x = today_born.TBD[i];
lstLabel[x](x.FName + x.LName);
}
break;
}
}