Need to update certain columns in table from csv file [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a csv file and I need to update data in only a few columns in my sql database table. What is the best way to do this? I was thinking bulk import however, it will not let me do this without using all of the columns. I was thinking of using format file, but I wanted to know if this is the most efficient way.
Here is how I was trying it from my C# class:
/// <summary>
/// Update all of the PropertyDefinitions
/// </summary>
internal static void InsertPropertyDefinitions()
{
//
// Define the connection
//
SqlConnection insertConnection = null;
try
{
RetryStrategy retryStrategy = new Incremental(5, TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(3000));
RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);
retryPolicy.ExecuteAction(() =>
{
//
// Try to connect to the database
//
using (insertConnection = new SqlConnection(m_ConnectionString))
{
//
// Open the connection
//
insertConnection.Open();
//
// Get the insert command ready
//
using (SqlCommand insertRecordCmd = insertConnection.CreateCommand())
{
//
// Define the Insert command
//
insertRecordCmd.CommandText = #"
BULK INSERT dbo.[PropertyDefinition]
FROM '//my file path'
WITH(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
";
// Execute the INSERT command
insertRecordCmd.ExecuteNonQuery();
}
insertConnection.Close();
}
});
}
catch (Exception ex)
{
//
// This is unexpected so display full exception information
//
m_Log.WriteLine("Exception while creating table");
m_Log.WriteLine(ex.Message.ToString());
throw;
}
}

A recommendation would be to put the csv data into memory and filter out the columns you don't want.
The following SO article has an example of how to populate a DataTable from a CSV and use SqlBulkCopy to bulk insert into SQL Server. You can modify the code to filter out the columns you don't want.
Upload CSV file to SQL server

Related

How can i execute functions with respective sql operation insert and update

I am inserting and updating data from on db table to another db table. For this i have 2 functions. I want that control should go to function based on sql operation.
If i inserted data in a db table then control should go to insert function, if i update the db table data then control should go to update function.
Can some one help how can i wrote conditions here to achieve this.
Many Thanks
C# code
//When service starts controls comes to this block
public ESS_VMint()
{
dLib = new DataLibrary("ESS", false, out essStatus);
dLib = new DataLibrary("VillageMate", false, out villagemateStatus);
InsertFields();
UpdateFields();
}
public DataTable InsertFields()
{
//Insert operations
}
public DataTable UpdateFields()
{
//Update Operations
}

datagridview update row to csv file

I am working with Csv file and datagridview in a C# project for a inventory app, I try to update a row to CSV file!
i need to update if user edit a row current word with a new word but my problem here is i need save the current word and new word and get total in pseudo code example:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(row in column is modified)
update specific row with comma to current file and load it...
}
Csv file is look like,
Current:
1;2;;4;5
Update:
1;2,A;;4;5 changed device A total: 1 time...
Next row modified :
1;A;;4,B,C;5 changed device B and C total change : 2 time...
With a database it's easy to update data but i don't have sql server installed so this option has not for me i think..
My goal is for tracking device out/in so if you have a solution please share it.
Short of using an SQL server, maybe something like this could help? LiteDB You'd have your LiteDB to host your data, and export it CSV whenever you need. Working with CSV files usually means you'll re-write the whole file every time there is an update to make... Which is slow and cumbersome. I recommend you use CSV to transport data from Point A to Point B, but not to maintain data.
Also, if you really want to stick to CSV, have a look at the Microsoft Ace OLEDB driver, previously known as JET driver. I use it to query CSV files, but I have never used it to update... so your mileage may vary.
Short of using an actual DataBase or a database driver, you'll have to use a StreamReader along with a StreamWriter. Read the file with the StreamReader, write the new file with the StreamWriter. In your StreanReader. This implies you'll have code in your StreamReader to find the correct Line(s) to update.
Here's the class I created and am using to interact with LiteDB. It's not all that robust, but it did exactly what I needed it to do at the time. I had to make changes to a slew of products hosted on my platform, and I used this to keep track of the progress.
using System;
using LiteDB;
namespace FixProductsProperty
{
public enum ListAction
{
Add = 0,
Remove,
Update,
Disable,
Enable
}
class DbInteractions
{
public static readonly string dbFilename = "MyDatabaseName.db";
public static readonly string dbItemsTableName = "MyTableName";
public void ToDataBase(ListAction incomingAction, TrackingDbEntry dbEntry = null)
{
if (dbEntry == null)
{
Exception ex = new Exception("dbEntry can not be null");
throw ex;
}
// Open database (or create if not exits)
using (var db = new LiteDatabase(dbFilename))
{
var backupListInDB = db.GetCollection<TrackingDbEntry>(dbItemsTableName);
//ovverride action if needed
if (incomingAction == ListAction.Add)
{
var tempone = backupListInDB.FindOne(p => p.ProductID == dbEntry.ProductID);
if (backupListInDB.FindOne(p => p.ProductID == dbEntry.ProductID) != null)
{
//the record already exists
incomingAction = ListAction.Update;
//IOException ex = new IOException("Err: Duplicate. " + dbEntry.ProductID + " is already in the database.");
//throw ex;
}
else
{
//the record does not already exist
incomingAction = ListAction.Add;
}
}
switch (incomingAction)
{
case ListAction.Add:
backupListInDB.Insert(dbEntry);
break;
case ListAction.Remove:
//backupListInDB.Delete(p => p.FileOrFolderPath == backupItem.FileOrFolderPath);
if (dbEntry.ProductID != 0)
{
backupListInDB.Delete(dbEntry.ProductID);
}
break;
case ListAction.Update:
if (dbEntry.ProductID != 0)
{
backupListInDB.Update(dbEntry.ProductID, dbEntry);
}
break;
case ListAction.Disable:
break;
case ListAction.Enable:
break;
default:
break;
}
backupListInDB.EnsureIndex(p => p.ProductID);
// Use Linq to query documents
//var results = backupListInDB.Find(x => x.Name.StartsWith("Jo"));
}
}
}
}
I use it like this:
DbInteractions yeah = new DbInteractions();
yeah.ToDataBase(ListAction.Add, new TrackingDbEntry { ProductID = dataBoundItem.ProductID, StoreID = dataBoundItem.StoreID, ChangeStatus = true });
Sorry... my variable naming convention sometimes blows...

how to get blocked file extensions and maximum file size for attachment in dynamics crm using c# code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to get blocked file extension and maximum file size for attachment set by admin in c# code .Below image displays what I actually want using c# code.
Please suggest me answer.
Please use the following code to get any property in the System Settings.
var query = new QueryExpression("organization")
{
ColumnSet = new ColumnSet("blockedattachments", "maxuploadfilesize")
};
EntityCollection orgCollection = _service.RetrieveMultiple(query);
if (orgCollection.Entities.Count > 0)
{
Entity org = orgCollection.Entities.First();
string blockedattachments = org.GetAttributeValue<string>("blockedattachments");
int numberMaxUploadFileSize = org.GetAttributeValue<int>("maxuploadfilesize");
}
Try using below code, it is tested and working fine.
var query = new QueryExpression("organization")
{
ColumnSet = new ColumnSet("blockedattachments", "maxuploadfilesize")
};
var record = service.RetrieveMultiple(query).Entities.FirstOrDefault();
if (record != null)
{
var blockedAttachments = record.GetAttributeValue<string>("blockedattachments");
var maxAttachmentSize = record.GetAttributeValue<int>("maxuploadfilesize");
}

Database creation only on first run of visual c# application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Any one help me to create a database in MySQL only on the first run of my c# application. Second time when i run this application if database exists then creation of database code should be skipped.
If you use code first in the Entity Framework you can create your database from the classes in C# that define you tables and relationships.
Once you have your classes you just have to change or setup a connection string to your database and then run code... then the database will be created for you... by magic .. or your classes!!
There are many samples online
Code First with Azure
http://www.dotnetjalps.com/2015/04/entity-framework-code-first--mysql-azure.html
Entity Framework Code First - Create Database with MySql?
private static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name
= '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
tmpConn.Open();
object resultObj = ExecuteScalar();
int databaseID = 0;
if (resultObj != null)
{
int.TryParse(resultObj.ToString(), out databaseID);
}
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
This will work with any database name you pass in as a parameter, and it will return a bool true = database exists, false = database does not exist (or error happened).If true mean skip the creation false mean create database..

How to Create new Database from Existing Data Base in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to create a new database using c#. I just want to pass database name from user interface and for that database name i want to run a sql script of database for creating the same schema of that script for new database.
I do not have exactly whay you intend to do, but I have done some functionality to seed some default data to the master tables.
//sql file location
private static readonly string IndexScriptSeedMasterDataLocation = "SqlSeedMasterData.sql";
In the function I have :
private static void SeedMasterData ( IpDataContext context, string databaseName)
{
context.Database.CreateIfNotExists();
var sqlContent = Content(IndexScriptSeedMasterDataLocation);
var modifiedSqlScript = sqlContent.Replace("#DatabaseName", databaseName);
context.Database.ExecuteSqlCommand(modifiedSqlScript);
}
// Content function :
private static string Content(string fileLocation)
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileLocation))
{
if (stream == null)
{
return string.Empty;
}
var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}

Categories

Resources