I'm currently working on a generic function for inserting data tables via entity framework. However, with my current solution I ended up with a ton of very repetitive code with only a few minor differences. I would like to simplify what I have and remove the need for large case statements based on my table names (I only included two cases in this example to save space).
Here is what I currently have:
public static void InsertByTable(IEnumerable<DataTable> chunkedTable, string tableName)
{
switch (tableName)
{
#region Parcel
case TaxDataConstant.Parcel:
Parallel.ForEach(
chunkedTable,
new ParallelOptions
{
MaxDegreeOfParallelism = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreads"])
},
chunk =>
{
Realty_Records_ProdEntities entities = null;
try
{
entities = new Realty_Records_ProdEntities();
entities.Configuration.AutoDetectChangesEnabled = false;
foreach (DataRow dr in chunk.Rows)
{
var parcelToInsert = new Parcel();
foreach (DataColumn c in dr.Table.Columns)
{
SetProperty(parcelToInsert, c.ColumnName, dr[c.ColumnName]);
}
entities.Parcels.Add(parcelToInsert);
}
entities.SaveChanges();
}
catch (Exception ex)
{
TaxDataError.AddTaxApplicationLog(
TaxDataConstant.CategoryError,
ex.Source,
ex.Message,
ex.StackTrace);
throw;
}
finally
{
entities?.Dispose();
}
});
break;
#endregion
#region Asmt
case TaxDataConstant.Asmt:
Parallel.ForEach(
chunkedTable,
new ParallelOptions
{
MaxDegreeOfParallelism = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreads"])
},
chunk =>
{
Realty_Records_ProdEntities entities = null;
try
{
entities = new Realty_Records_ProdEntities();
entities.Configuration.AutoDetectChangesEnabled = false;
foreach (DataRow dr in chunk.Rows)
{
var asmtToInsert = new Asmt();
foreach (DataColumn c in dr.Table.Columns)
{
SetProperty(asmtToInsert, c.ColumnName, dr[c.ColumnName]);
}
entities.Asmts.Add(asmtToInsert);
}
entities.SaveChanges();
}
catch (Exception ex)
{
TaxDataError.AddTaxApplicationLog(
TaxDataConstant.CategoryError,
ex.Source,
ex.Message,
ex.StackTrace);
throw;
}
finally
{
entities?.Dispose();
}
});
break;
#endregion
}
}
Is there any way I can make this table agnostic?
You can probably move the logic in the case statement to a helper extension method which is generic. something like this (untested) pseudo code:
public static class EntityAdder
{
public static void AddEntities<T>(this IEnumerable<DataTable> chunkedEntities, Action<Realty_Records_ProdEntities, T entity> addingFunction)
{
Parallel.ForEach(
chunkedTable,
new ParallelOptions
{
MaxDegreeOfParallelism = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreads"])
},
chunk =>
{
Realty_Records_ProdEntities entities = null;
try
{
entities = new Realty_Records_ProdEntities();
entities.Configuration.AutoDetectChangesEnabled = false;
foreach (DataRow dr in chunk.Rows)
{
var toInsert = new T();
foreach (DataColumn c in dr.Table.Columns)
{
SetProperty(parcelToInsert, c.ColumnName, dr[c.ColumnName]);
}
addingFunction(entities,toInsert);
}
entities.SaveChanges();
}
catch (Exception ex)
{
TaxDataError.AddTaxApplicationLog(
TaxDataConstant.CategoryError,
ex.Source,
ex.Message,
ex.StackTrace);
throw;
}
finally
{
entities?.Dispose();
}
});
}
}
this could then be used something like this:
public static void InsertByTable(IEnumerable<DataTable> chunkedTable, string tableName)
{
switch (tableName)
{
#region Parcel
case TaxDataConstant.Parcel:
chunkedTable.AddEntities((entities,newEntity)=> entities.Parcels.Add(newEntity))
break;
#endregion
#region Asmt
case TaxDataConstant.Asmt:
chunkedTable.AddEntities((entities,newEntity)=> entities.Asmts.Add(newEntity))
break;
#endregion
}
}
you might be able to automate the adding bit by finding the property on the class which is a list of the things you want to add and avoid passing the action in if you wanted.
Based on Sams response and some further research I was able to refactor out the case statement.
Here's my solution:
public static void InsertByTable(IEnumerable<DataTable> chunkedTable, Type type)
{
Parallel.ForEach(
chunkedTable,
new ParallelOptions
{
MaxDegreeOfParallelism = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreads"])
},
chunk =>
{
Realty_Records_ProdEntities entities = null;
try
{
entities = new Realty_Records_ProdEntities();
entities.Configuration.AutoDetectChangesEnabled = false;
var set = entities.Set(type);
foreach (DataRow dr in chunk.Rows)
{
var objectToInsert = Activator.CreateInstance(type);
foreach (DataColumn c in dr.Table.Columns)
{
SetProperty(objectToInsert, c.ColumnName, dr[c.ColumnName]);
}
set.Add(objectToInsert);
}
entities.SaveChanges();
}
catch (Exception ex)
{
TaxDataError.AddTaxApplicationLog(
TaxDataConstant.CategoryError,
ex.Source,
ex.Message,
ex.StackTrace);
throw;
}
finally
{
entities?.Dispose();
}
});
}
Related
Topic exists - have checked via Confluent Cloud admin console
admin is setup during code initialisation
static boolean checkForTopic(String topicName) throws InterruptedException {
boolean bRetVal = false;
ListTopicsResult lTR = admin.listTopics();
KafkaFuture<Set<String>> topicNames = lTR.names();
try {
Set<String> s = topicNames.get();
if(s.isEmpty()) {
System.out.println("Empty Topic list");
}else {
Iterator<String> iT = s.iterator();
while(iT.hasNext()) {
String tN = iT.next();
System.out.println(tN);
if(tN.equalsIgnoreCase(topicName)) {
bRetVal = true;
break;
}
}
}
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bRetVal;
}
Any help greatly appreciated
My application this code.
public float yvalue;
public String xvalue;
public void QuerySQL(String COMANDOSQL) {
ResultSet rs;
try {
Statement statement = connect.createStatement();
rs = statement.executeQuery(COMANDOSQL);
while (rs.next()) {
yvalue = rs.getInt( "ORAN" );
xvalue = rs.getString( "URUNGRUBU" );
pieEntries.add(new PieEntry(yvalue, xvalue)); /// this code does not fill pieEntry
}
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
pieChart.setUsePercentValues(true);
pieDataSet = new PieDataSet(pieEntries,label);
pieData = new PieData(pieDataSet);
pieData.setDrawValues(true);
pieChart.setData(pieData);
pieChart.invalidate();
pieChart.setBackgroundColor( Color.TRANSPARENT);
pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
moveoffScreen();
}
I have a SharePoint 2013 document library with three custom lists.
Once a day I would like to backup the custom lists as excel documents.
Is there an inbuilt functionality in SharePoint 2013 which can be configured as a recurring task?
Or should one use PowerShell or CSOM to write script or an application which is then run by a Windows Task?
you dont have any OOB features to do this, i had the same req and i wrote an Utility - PFB the code - this will give you an o/p in .csv file
class Program
{
private static DataTable dataTable;
private static SPList list;
static void Main(string[] args)
{
try
{
Console.WriteLine("Site Url: ");
string _siteUrl = Console.ReadLine();
if (!string.IsNullOrEmpty(_siteUrl))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(_siteUrl))
{
if (site != null)
{
SPWeb web = site.RootWeb;
if (web != null)
{
// Export List code segment
Console.WriteLine("List Name:");
string _listName = Console.ReadLine();
if (!string.IsNullOrEmpty(_listName))
{
list = web.Lists[_listName];
if (list != null)
{
dataTable = new DataTable();
//Adds Columns to SpreadSheet
InitializeExcel(list, dataTable);
string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
if (list.Items != null && list.ItemCount > 0)
{
foreach (SPListItem _item in list.Items)
{
DataRow dr = dataTable.NewRow();
foreach (DataColumn _column in dataTable.Columns)
{
if (dataTable.Columns[_column.ColumnName] != null && _item[_column.ColumnName] != null)
{
dr[_column.ColumnName] = _item[_column.ColumnName].ToString();
}
}
dataTable.Rows.Add(dr);
}
}
}
}
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = dataTable;
grid.DataBind();
using (StreamWriter streamWriter = new StreamWriter("C:\\" + list.Title + ".xls", false, Encoding.UTF8))
{
using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(streamWriter))
{
grid.RenderControl(htmlTextWriter);
}
}
Console.WriteLine("File Created");
#endregion
}
}
}
});
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadLine();
}
// Create excel funution
public static void InitializeExcel(SPList list, DataTable _datatable)
{
if (list != null)
{
string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
if (list.Items != null && list.ItemCount > 0)
{
foreach (SPListItem _item in list.Items)
{
foreach (SPField _itemField in _item.Fields)
{
if (_schemaXML.Contains(_itemField.InternalName))
{
if (_item[_itemField.InternalName] != null)
{
if (!_datatable.Columns.Contains(_itemField.InternalName))
{
_datatable.Columns.Add(new DataColumn(_itemField.StaticName, Type.GetType("System.String")));
}
}
}
}
}
}
}
}
}
I want to download csv file , i take the response content and write to it , apprently wicket write after me and the content iam getting is the page html where it should be my csv
I have seen in the example the usage of throw new AbortException();
I am using version 6.7 , do you know if my version wicket has somthing instead of it ?
or rather I am doing somthing wrong ....
can you please help me ...
add(new Link<Void>("export") {
#Override
public void onClick() {
WebResponse response = (WebResponse) getResponse();
response.setAttachmentHeader("export.csv");
response.setContentType("text/csv");
OutputStream out = getResponse().getOutputStream();
try {
c.exportData(dataSource.getListForExport(), columns, out);
} catch (Exception ex) {
System.err.println(ex);
}
}
});
public <T> void exportData(List<T> list, List<IGridColumn<IDataSource<T>, T, String>> columns, OutputStream outputStream)
throws IOException {
long startTime = System.nanoTime();
PrintWriter out = new PrintWriter(new OutputStreamWriter(outputStream, Charset.forName(characterSet)));
try {
if (isExportHeadersEnabled()) {
boolean first = true;
for (IGridColumn<IDataSource<T>, T, String> col : columns) {
if (first) {
first = false;
} else {
out.print(delimiter);
System.out.println(delimiter);
}
if (col.getId().equals("checkBox")) {
continue;
}
out.print(quoteValue(col.getId()));
System.out.println(col.getId());
}
out.print("\r\n");
System.out.println("\r\n");
}
Iterator<? extends T> rowIterator = list.iterator();
while (rowIterator.hasNext()) {
T row = rowIterator.next();
boolean first = true;
for (IGridColumn<IDataSource<T>, T, String> col : columns) {
if (first) {
first = false;
} else {
out.print(delimiter);
System.out.println(delimiter);
}
if (col.getId().equals("checkBox")) {
continue;
}
Object o = (new PropertyModel<>(row, col.getId())).getObject();// ((AbstractColumn<T,
if (o != null) {
Class<?> c = o.getClass();
String s;
IConverter converter = Application.get().getConverterLocator().getConverter(c);
if (converter == null) {
s = o.toString();
} else {
s = converter.convertToString(o, Session.get().getLocale());
}
out.print(quoteValue(s));
System.out.println(quoteValue(s));
}
}
out.print("\r\n");
System.out.println("\r\n");
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
System.out.println(out);
out.close();
// measure
System.out.print(System.nanoTime() - startTime);
}
}
The best way to do this is using dynamic resources. I'll suggest you to read chapter "Resource managment with Wicket" of this magnific free Wicket guide: https://code.google.com/p/wicket-guide/.
Here you have a similar example given in this guide in the section "Custom resources".
public class RSSProducerResource extends AbstractResource {
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType("text/xml");
resourceResponse.setTextEncoding("utf-8");
resourceResponse.setWriteCallback(new WriteCallback()
{
#Override
public void writeData(Attributes attributes) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
SyndFeedOutput output = new SyndFeedOutput();
try {
output.output(getFeed(), writer);
} catch (FeedException e) {
throw new WicketRuntimeException("Problems writing feed to response...");
}
}
});
return resourceResponse;
}
// method getFeed()...
}
And then you need to add the link in the desired page or component:
add(new ResourceLink("rssLink", new RSSProducerResource()));
I am trying to move between 3 forms. 1 is main form and 2 other simple forms.
I have commands in the soft keys but they are not working...
below is my code...
public class checkOutComponents extends MIDlet implements ActionListener
{
private Form appForm;
private Form f1;
private Form f2;
Command GoTof1 = new Command("GoTof1");
Command GoTof2 = new Command("GoTof2");
Command GoToMainForm = new Command("GoToMainForm");
public void startApp()
{
Display.init(this);
appForm = new Form("Check These Components!! ");
appForm.setLayout(new BorderLayout());
appForm.addCommand(GoTof1);
appForm.addCommand(GoTof2);
appForm.addComponent(BorderLayout.CENTER, formContainer);
appForm.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void actionPerformed(ActionEvent event)
{
Command eventCmd = event.getCommand();
Form f = Display.getInstance().getCurrent();
boolean sentido = false;
if (eventCmd == GoTof1)
{
sentido = true;
Image i1 = null;
try
{
i1 = Image.createImage("/hello/1.jpeg");
}
catch (IOException ex)
{
ex.printStackTrace();
}
Label lab1 = new Label(i1);
f1.addComponent(lab1);
f1.addCommand(GoTof2);
f1.addCommand(GoToMainForm);
f.setTransitionOutAnimator(Transition3D.createCube(300, sentido));
f1.show();
}
else if (eventCmd == GoTof2)
{
sentido = false;
Image i2 = null;
try
{
i2 = Image.createImage("/hello/2.jpeg");
}
catch (IOException ex)
{
ex.printStackTrace();
}
Label lab2 = new Label(i2);
f1.addComponent(lab2);
f1.addCommand(GoTof1);
f1.addCommand(GoToMainForm);
f.setTransitionOutAnimator(Transition3D.createCube(300, sentido));
f2.show();
}
else if(eventCmd == GoToMainForm)
{
appForm.showBack();
}
}
}
Kindly help regarding this.
Thanks in advance and regards,
Swati
Add command listener to the form appForm.
appForm.addCommandListener(this);