I am using SMS caster to send sms.It has an option to Import csv files.
Now I want to dynamically create csv file of CellNo column of Person table from Visual Studio 2010 connected SQL Server 2008.So that I click on a button and it creates a csv file which I can then access from my software SMSCaster to send sms.
The solutions available are either manual-based or if some query is provided it requires Microsoft OLEDB.....so is there any simple query to convert queryresult into .csv file?
Try this :
Namespace : System.IO;
var _lines = new List<string>();
for(int _i=0;i<gridview1.rows.count;_i++)
{
string[] _mobileNos = gridView1.rows[_i].cells[mobilecolumn index in gridview].text;
var header = string.Join(",", _mobileNos);
_lines.Add(header);
}
File.WriteAllLines("FileName.csv",_lines);
Here is the solution that worked:
public void gridtoCSVFILE()
{
string ing;
List<string> lines = new List<string>();
for (int i = 0; i < gvStudCellNo.Rows.Count; i++)
{
ing = gvStudCellNo.Rows[i].Cells[0].Value.ToString();
lines.Add(ing);
File.WriteAllLines("StudentsCellNo.csv", lines);
}
}
//it will create csv file in your bin folder...also it automatically replaces each new file with the old one
Related
I have the following table :
CREATE TABLE DI_Simulation
(
[city] nvarchar(255),
[profession] nvarchar(255)
);
I load the data from an URL with a Script task where I created a class Simulation and added two string attributes. I then deserialize the downloaded JSON data and create output rows.
I specify that the output columns city and profession are of type DT_WSTR but the following characters [é,à,è,...] are always replaced...
I tried different collations on both columns but no changes were seen. I also tried forcing UTF8 conversion on the Script Task but that also didn't work.
Any suggestions ?
EDIT: I should also mention that I have other tables where the insertion is made correctly, but this one especially has this issue, which I'm thinking the Script Task has something to do with it.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
// Convert json string to .net object using the old school JavaScriptSerializer class
string Uri = "https://....";
JavaScriptSerializer serialize = new JavaScriptSerializer
{
MaxJsonLength = Int32.MaxValue,
};
var simulation = serialize.Deserialize<Simulation[]>(DownloadJson(Uri));
EDIT 2:
WebClient client = new WebClient();
Stream stream = client.OpenRead(Url);
StreamReader streamreader = new StreamReader(stream, System.Text.Encoding.GetEncoding(1252));
var ags = streamreader.ReadToEnd();
/*System.IO.File.WriteAllText(#"C:\Users\hhamdani\Desktop\Data Integration Objetcs\simulation_data.json",
ags,
System.Text.Encoding.GetEncoding(1252));*/
var simulation = serialize.Deserialize<Simulation[]>(ags);
Instead of downloading with DownloadJson, I used streamreader to get the Json Data from the URL and forced the Encoding, when I save the data on a txt file it's good, but on the Database it's the same issue.
Works fine from a script source component based on my reproduction
Setup
Table creation
A trivial table with two columns
CREATE TABLE dbo.[SO_71842511] (
[TestCase] int,
[SomeText] nvarchar(50)
)
SCR Do Unicode
Proof that we can inject unicode characters into the data flow task from a script source.
Define the Script Task as a Source. Add 2 columns to the output, one int, one DT_WSTR
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void CreateNewOutputRows()
{
Output0Buffer.AddRow();
Output0Buffer.SomeText = "e e plain";
Output0Buffer.TestCase = 0;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "é e forward";
Output0Buffer.TestCase = 1;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "à a back";
Output0Buffer.TestCase = 2;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "è e backward";
Output0Buffer.TestCase = 3;
}
}
Results
WebClient client = new WebClient();
Stream stream = client.OpenRead(Url);
StreamReader streamreader = new StreamReader(stream, System.Text.Encoding.UTF8);
var ags = streamreader.ReadToEnd();
This did the job for me.
Thanks #billinkc
I have an automation project in C# that works with Microsoft Excel using WinAppDriver Release Candidate 1.2.
I have a case where I am attempting to get the number of rows that have been populated on a sheet with the code below.
public string GetLastCellBelowStartRange(string sheetName, string startRange)
{
var sheet = FindSheet(sheetName);
var nameBox = this.GetNameBox();
nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");
this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");
var endCellRange = nameBox.GetAttribute("LegacyIAccessible.Value");
return endCellRange;
}
The code successfully goes to the last cell in the workbook and nameBox is known as well as the excel driver (i.e. this.excel).
I cannot determine how to get the contents of the current cell which Inspect shows in both Value.Value and LegacyIAccessible.Value.
Does anybody know of a way to do this?
public string GetLastCellBelowStartRange(string sheetName, string startRange)
{
var sheet = FindSheet(sheetName);
var nameBox = this.GetNameBox();
nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");
this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");
string endCellRange = nameBox.GetAttribute("Value.Value").ToString();
return endCellRange;
}
I'm looking to see if the SQL Database behind TFS2015 (or any version of TFS, in this case 2015 or 2010) stores the full file path for a file. There is information that we include in the Project folder (namely the version number) and while I realize there are better ways to track this information, we have a lot of legacy data that only has the version stored within this path. I want to pull the data into Crystal Reports to strip off the information and then use it.
You want to get a list of folders in TFS Source Control, instead of querying in database, we recommend to achieve it programmatically. The blog below and the sample code associated with it will do what you want:
http://blogs.microsoft.co.il/blogs/shair/archive/2009/02/26/tfs-api-part-16-mapping-source-control-using-versioncontrolserver.aspx
Also, check the code snippet in this case, which should help you:
ICommonStructureService structureService = (ICommonStructureService)Tfscollection.GetService(typeof(ICommonStructureService));
ProjectInfo[] projects = structureService.ListAllProjects();
//combo_projects.ItemsSource = projects;
////Create VersionControlServer object from TFS
//sourceControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
RecursionType recursion = RecursionType.OneLevel;
Item[] items = null;
string path = "$/" + projects[0].Name;//"$/TescoPOC/FetchStoryfromTFS";
ItemSet itemSet = versionControl.GetItems(path, recursion);
items = itemSet.Items;
//Dictionary<string, int> FolderListName = new Dictionary<string, int>();
List<string> FolderListName = new List<string>();
foreach (Item keyItem in items)
{
char[] charSeparators = new char[] { '/' };
//Using split to isolated the Project Name and the File Name
string[] ss = keyItem.ServerItem.Split(charSeparators, StringSplitOptions.None);
if (keyItem != items[0])
{
string filename = keyItem.ServerItem.Replace(path + "/", string.Empty);
if (filename != "BuildProcessTemplates")
{
FolderListName.Add(filename);
//if (FolderListName.ContainsKey(filename))
// FolderListName[filename] = FolderListName[filename] + 1;
//else
// FolderListName.Add(filename, 1);
}
}
}
I want to import the latest csv file into a table using SSIS? I currently have a step that gets the last file in a folder:
Report_201209030655.csv
Report_201209030655.csv
Report_201209030655.csv
Based on created time I want steps to import data of the latest csv to a table.
refer this solution:
[http://blog.sqlauthority.com/2011/05/12/sql-server-import-csv-file-into-database-table-using-ssis/][1]
then use script task to populate the file name and pass that variable as file name for source component.
Getting latest file code:
public void Main()
{
string[] files = System.IO.Directory.GetFiles(#"C:\SSIS\Files");
DataTable NewList=new DataTable();
DataColumn col = new DataColumn("FileName");
NewList.Columns.Add(col);
System.IO.FileInfo finf;
foreach (string f in files)
{
finf = new System.IO.FileInfo(f);
if (finf.LastWriteTime > DateTime.Now.AddHours(-24))
{
NewList.Rows.Add(f);
}
}
Dts.Variables["User::FileNameArray"].Value = NewList;
Dts.TaskResult = (int)ScriptResults.Success;
}
I am trying to insert a .csv file into SQL Server 2008 R2.
The .csv is 300+MB from http://ipinfodb.com/ip_database.php Complete
(City), 4.0M records.
Here're the top 5 lines, with 1st line = column headers:
"ip_start";"country_code";"country_name";"region_code";"region_name";"city";"zipcode";"latitude";"longitude";"metrocode"
"0";"RD";"Reserved";;;;;"0";"0";
"16777216";"AU";"Australia";;;;;"-27";"133";
"17367040";"MY";"Malaysia";;;;;"2.5";"112.5";
"17435136";"AU";"Australia";;;;;"-27";"133";
I tried Import and Export Data, and BULK INSERT, but haven't been able to import them correctly yet.
Shall I resort to use bcp? can it handle stripping the ""? how?
Thank you very much.
Got it, forgot to set Text Qualifier as ":
Your data looks pretty inconsistent since NULL values don't also carry a quotation enclosure.
I believe you can create a format file to customize to your particular csv file and its particular terminators in SQL SERVER.
See more here:
http://lanestechblog.blogspot.com/2008/08/sql-server-bulk-insert-using-format.html
Is this a single import or are you wanting to schedule a recurring import? If this is a one-time task, you should be able to use the Import and Export Wizard. The text qualifier will be the quotation mark ("), be sure to select column names in the first data row, and you'll want to convey that the field delimiter is the semicolon (;).
I'm not certain the file is properly formatted - the last semicolon following each of the data rows might be a problem. If you hit any errors, simply add a new column header to the file.
EDIT: I just did a quick test, the semicolons at the end will be treated as part of the final value in that row. I would suggest adding a ;"tempheader" at the end of your header (first) row - that will cause SQL to treat the final semicolon as a delimiter and you can delete that extra column once the import is complete.
In C# you can use this code, working for me
public bool CSVFileRead(string fullPathWithFileName, string fileNameModified, string tableName)
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["dbConnectionString"]);
string filepath = fullPathWithFileName;
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
//string[] stud = sr.ReadLine().Split(',');
//for (int i = 0; i < stud.Length; i++)
//{
// stud[i] = stud[i].Replace("\"", "");
//}
//value = stud;
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableName;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
return true;
}