I am working with video and I want <g class="gr_ gr_60 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="60" id="60">program</g> to send <g class="gr_ gr_64 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="64" id="64">myvideo</g> over <g class="gr_ gr_132 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="132" id="132">socket</g> in the same computer
how send video frame via socket in c#?
Really need your help
I am currently creating a website as an assignment in school, since I started this assignment I have been getting difficulties. However, I managed to overcome some; currently there is one particular issue that has been giving me headache and that is making my webpage responsive. Jumbotron and some other write-ups on the webpage appear not to cover the full width of the page when the windows screen is minimized. Here is a bit of what I mean in picture; the code is bottom
Please help me overcome this thank you.
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --><title>Joscheck Home</title><!-- Bootstrap --><link href="css/bootstrap.min.css" rel="stylesheet"/><link href="css/StyleSheet.css" rel="stylesheet" /><!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --><!-- WARNING: Respond.js doesn't work if you view the page via file:// --><!--[if lt IE 9]><script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]--></head><body style=" background-color:#DCDCDC; background-image:url('images/Dox.png')"><form id="form1" runat="server"><div><div class="navbar navbar-default navbar-inverse navbar-fixed-top" role="navigation" style="background-color:#200662; font-family:Nunito;"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" style="background-color:#200662;color:white"><span class="sr-only">Toggle Navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="Homepage.aspx"></a></div><div class="navbar-collapse collapse"><ul class="nav navbar-nav navbar-right"><li><a href="Homepage.aspx" style="color: #FFFFFF">Home</a></li><li><a href="#" style="color: #FFFFFF">About Us</a></li><li><a href="#" style="color: #FFFFFF">Contact</a></li><li><a href="SignIn.aspx"style="color: #FFFFFF">Login/Register</a></li></ul></div></div></div></div><div class="jumbotron" style="margin-top:15px; border:10px #ccc; box-shadow:4px 8px 10px #ccc; background-color:#A9A9A9; font-family:Nunito; height:200px;"><div class="container"><h1 style="color:#200662; margin-top:2px; font-size:xx-large">Welcome To JosCheck</h1><p><i style="color:black; font-size:large; font-style:normal">Your Home For Tracking Lost Cars and/or Phones</i></p><p><a href="#" class="btn btn-primary" role="button">See More »</a></p></div></div><div class="container-fluid"><div class="jumbotron" style="margin-top:0%; background-image: url('images/pexels-photo-1229861.jpeg'); height:250px; background-size:cover;"><h1 style="color: red; font-size: x-large; font-family: Co Headline Corp">Best Tracking System!</h1><p><i style="color: white; font-family:St Ryde; font-size:large; font-style:normal">Search Our Vast Database To Verify That Vehicle Before You Buy</i></p><p><asp:TextBox ID="TextBox1" runat="server" Height="30px" Width="250"></asp:TextBox><a href="#" class="btn btn-primary"; role="button">Search</a></p></div></div><div class="container"><div class="row"><div class="section"><div class="col-md-4"><h2 style="color: red; margin-top: 0; font-size: x-large; font-family: Capoon PERSONAL USE;">How It Works...</h2></div></div></div></div><div class="container"><!-- Example row of columns --><div class="row"><div class="section"><div class="col-md-4"><h2 style="color: #200662; margin-top: 0; font-size: larger; font-family: St Ryde;">Car Verification and Tracking</h2><hr /><p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p><p><a class="btn btn-primary" href="#" role="button">Read More »</a></p></div></div><div class="col-md-4"><h2 style="color:#200662; margin-top:0; font-size:larger; font-family:St Ryde;">Phone Verification and Tracking</h2><hr /><p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p><p><a class="btn btn-primary" href="#" role="button">Read More »</a></p></div><div class="col-md-4"><h2 style="color:#200662; margin-top:0; font-size:larger; font-family:St Ryde;">Tracking System for Children and Homes Buglars</h2><hr /><p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Ut fermentum justo sit amet risus.</p><p><a class="btn btn-primary" href="#" role="button">Read More »</a></p></div></div></div><hr /><footer class="container" style="background-color:black; width:100%; height:auto;"><p class="pull-right" style="color: white;"><a href="#">Back to Top</a></p><p style="color: white;">Copyright © 2018 Doxtrak Tech. All Rights Reserved. · <a href="Homepage.aspx">Home</a> · <a href="#">About Us</a> · <a href="#">Contact</a> ·</p></footer></form><!-- jQuery (necessary for Bootstrap's JavaScript plugins) --><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><!-- Include all compiled plugins (below), or include individual files as needed --><script src="js/bootstrap.min.js"></script></body></html>
Structures Containing the Reference type
struct MyStruct { public string myString; static void Main(string[] args) { MyStruct myVariable = new MyStruct(); myVariable.myString = "Hello"; //This Line Console.ReadLine(); } }
Where does myString and myVariable.myString gets Stored? Heap or Stack ?
USB freezing.
I have designed a usb pc oscilloscope using a PIC32MX microcontroller.
The C# pc software is from www.waitingforfriday.com
This works great and has no problems.
I have now ported this across to a PIC32MZ microcontroller.
Again this works great.
However, if I exit the pc program 5 seconds later the USB bus goes into suspend.
Then if I go back into the pc program the usb bus is frozen in suspend mode.
If I go back in before 5 seconds are up then it runs fine.
I have disabled power down and selective suspend on my pc but the problem persists.
Is there a C# command I can use to take the USB bus out of suspend ?
n.Wright
Coded UI not using Automation ID for Win32 app that is written to support UIA
I was trying to implement (learn) how to use IRawElementProviderSimple and have copied most of the code from "UI Automation simple provider sample', see link below for the source code. I have also added the following into Provider.cpp
else if (propertyId == UIA_AutomationIdPropertyId){ pRetVal->vt = VT_BSTR; pRetVal->bstrVal = SysAllocString(L"This.Is.My.Automation.Id");}
In short, the custom control now has an Automation ID. The issue I am having is that Coded UI is detecting the control as MSAA therefore not using AutomationID. Can someone please provide input on what is the best way to use Coded UI for native applications that implements UI Automation Provides?
Link:
https://code.msdn.microsoft.com/windowsdesktop/UI-Automation-Simple-735d36a5
yY
TaskFolder.RegisterTaskDefinition method thrown an exceptions [Error] (21,8):UserId:
TaskFolder.RegisterTaskDefinition method thrown an exceptions [Error] (21,8):UserId:
while creating scheduler task programmatically
Piece of code we are using:
ITaskService svc = new TaskScheduler.TaskScheduler();
svc.Connect();
var root = svc.GetFolder("\\");
var sid = (SecurityIdentifier)new NTAccount(username).Translate(typeof(SecurityIdentifier));
principal.UserId = sid.ToString();
var regTask = root.RegisterTaskDefinition(taskName, taskDef, (int) _TASK_CREATION.TASK_CREATE_OR_UPDATE,
principal.UserId, password,_TASK_LOGON_TYPE.TASK_LOGON_PASSWORD);
Want to know in which scenarios RegisterTaskDefinition() throws an exception.
Currently we re receiving the exception
[Error] (21,8):UserId:
Thanks, Harish
InvalidPrinterException
Hi Team,
I have encountered a strange phenomenon, It sometimes and almost randomly happened
that printing document (generated inside the application) fails with this exception:
System.Drawing.Printing.InvalidPrinterException: Settings to access printer are not valid.
at System.Drawing.Printing.PrinterSettings.GetHdevmodeInternal(String printer)
at System.Drawing.Printing.PrinterSettings.GetHdevmodeInternal()
at System.Drawing.Printing.PrinterSettings.GetHdevmode(PageSettings pageSettings)
at System.Drawing.Printing.PrintController.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Drawing.Printing.StandardPrintController.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Drawing.Printing.PrintController.Print(PrintDocument document)
at System.Drawing.Printing.PrintDocument.Print()
We could reproduce the issue inconsistently when running the application in Windows Terminal Server, where more users were logged in. What are the possibilities for occurrence
of the above inconsistent issue?
Please provide us suggestions to resolve the issue.
Regards,
Ayswarya
Service Service OLEDB-connection
Bonjour,
J'ai
un service Windows qui se bloque lors de l'ouverture d'une connexion vers un fichier Excel, comme ceci:
-----------------------
using (var connection = new OleDbConnection
(
"Fournisseur = Microsoft.Jet.OLEDB.4.0;
Source de données ="
+ NomFichier + ";
Propriétés étendues = \" Excel 8.0 \ ""))
{
connection.Open ();
// commence à utiliser la connexion
}
-----------------------
Ce code fonctionne correctement
lorsque vous utilisez une console d'application. Lorsque je débogue le service Windows avec Visual Studio, l’exécution s’arrête jusqu'à l'appel de connexion.Open ().
DatagridView cell edit problem
Hi folks,
I have a datagridView that is linked to a binding source.
When I am inside a cell, I want to be able to click on a "Update" button that will write the changes back to the datasource. The problem is that the value in the current cell does not get saved back to the datasource. The program works fine if I move to another row and then click the update button.
I tried using the cell_leave event but it does NOT fire when I click on the update button. Same with grid_leave. Have also added grid.EndEdit() as the first line of code inside my update event but that does not save the current cells value either.
Can anyone advise on how I can save the "current" value of the cell ? I would rather not go down the road of programatically moving to another row then back again.
Thanks,
John
jppnn
Declare a HomeController on Startup.cs (asp.net mvc)
Hi everyone!
I need to call async method of HomeController at Startup.cs page. How can I do that?
Namely, I want to create background job that calls method at HomeController Minutely.
Get latest directory in a path - with respect to the the name of directory
How to change the base application path of AppDomain
Hi I want to give access to a particular folder so that all IO operations are performed only in that folder.
public class Plugin : MarshalByRefObject { public string TestRead(string path) { try { File.WriteAllText(path, "This is example text."); return "Done"; } catch (SecurityException) { return "Access Denied"; } } } public class Program { static void Main(string[] args) { string sandboxPath = "D:\\test\\public\\"; string basePath = AppDomain.CurrentDomain.BaseDirectory; var setup = new AppDomainSetup(); setup.ApplicationBase = basePath; var perm = new PermissionSet(PermissionState.None); perm.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); perm.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sandboxPath)); perm.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, basePath)); var pluginDomain = AppDomain.CreateDomain("PluginDomain", null, setup, perm); var plugin = pluginDomain.CreateInstanceAndUnwrap( typeof(Plugin).Assembly.FullName, typeof(Plugin).FullName) as Plugin; Console.WriteLine(plugin.TestRead("D:\\test\\public\\test.txt")); Console.WriteLine(plugin.TestRead(@"D:\\test\\secret\\test.txt")); Console.ReadKey(); } }
It works fine and file is written only to sandBoxPath .i.e "D:\\test\\public\\" and the access is denied when file is written to other than sandBoxPath i.e. "D:\\test\\secret\\".
Now I want to specify only a file name without the whole path and program should pick the sandBoxPath .e.g. when I call
Console.WriteLine(plugin.TestRead("test.txt"));
Program should be able to read/write text.txt file from/to sandBoxPath ("D:\\test\\public\\") .
I have tried to set the ApplicationBase but it's not working
pluginDomain.SetupInformation.ApplicationBase = sandboxPath;
Any idea how can I do that?
Thanks.
MW
SQL Row Count in VS
How do I get the query to row count in order 1,2,3,4 it is counting 1111 i have try a few different ways
using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1 where ItemCode = @egg", con)) using (var cmd = new SqlCommand("SELECT ROW_NUMBER() Over (order by ItemCode)as Number, ItemCode FROM Table1 where ItemCode = @egg", con)) using (var cmd = new SqlCommand("SELECT Count(*) Over(PARTITION by ItemCode)as Number, ItemCode FROM Table1 where ItemCode = @egg", con)) using (var cmd = new SqlCommand("SELECT Top 8 ROW_NUMBER() Over (Order by ItemCode) as Number, ItemCode FROM Table1 where ItemCode = @egg", con)) Number 1 EG216455 1 nEG216456 1 nEG216457 1 nEG216458 Number 1 EG216455 2 nEG216456 3 nEG216457 4 nEG216458
Here is the code and you can see the query
private void button1_Click(object sender, EventArgs e) { string egg = textBox1.Text; //egg will show "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460" int k = Convert.ToInt32(textBox2.Text); string[] stringSeparators = new string[]; string[] s = egg.Split(stringSeparators, StringSplitOptions.None); DataTable dtSerial = new DataTable(); DataTable table = new DataTable(); for (int i = 0; i < k; i++) { //ConfigurationManager.ConnectionStrings["pie"].ConnectionString; string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database.mdf;Integrated Security=True"; using (SqlConnection con = new SqlConnection(connString)) { using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1 where ItemCode = @egg", con)) cmd.Parameters.AddWithValue("@egg", s[i]); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); dtSerial.Load(reader); table = dtSerial.Clone(); foreach (DataRow dr in dtSerial.Rows) { table.Rows.Add(dr.ItemArray); } } con.Close(); } } dataGridView1.DataSource = dtSerial; }
Can I get some help to write an xml to binary
hello,
I am trying to create a binary dictionary file for a program.
The settings file is in xml, and I want the program to load the binary file.
here is the code of the xml:
<?xml version="1.0" encoding="utf-16"?><Lang Version="1.0" AppVersion="1.0.0.0"><Dialogs><Main><Menus><I Name="Main_Menu_Load">Load</I><I Name="Main_Menu_Save">Save</I><I Name="Main_Menu_Exit">Exit</I><I Name="Main_Menu_SaveAll">Save All</I><I Name="Main_Menu_Close">Close</I><I Name="Main_Menu_CloseAll">Close All</I><I Name="Main_Menu_Languages">Languages</I><I Name="Main_Menu_Help">Help</I><I Name="Main_Menu_Help_About">About</I><I Name="Main_Menu_Help_CheckForNewVersion">Check For New Version</I><I Name="Main_Text_LoadLanguage">Load Language {0}</I><I Name="Main_Menu_LoadMultiple">Load Multiple</I><I Name="Main_Menu_EmptyTextsColor">Empty Texts Color</I><I Name="Main_Menu_MatchingTextsColor">Matching Texts Color</I><I Name="Main_Menu_ExpandAll">Expand All</I><I Name="Main_Menu_CollapseAll">Collapse All</I><I Name="Main_Menu_ChangeColors">Change Colors</I></Menus><Headers><I Name="Main_HDR_Name">Name</I><I Name="Main_HDR_WarningName">Name</I><I Name="Main_HDR_WarningLanguages">Languages</I><I Name="Main_HDR_ErrorName">Name</I><I Name="Main_HDR_ErrorLanguage">Language</I></Headers><Texts><Logs><I Name="Main_Text_MissingFormatArgument">Missing format arguments : {0}</I></Logs><I Name="Main_Text_Warnings">{0} Warnings</I><I Name="Main_Text_Errors">{0} Errors</I></Texts></Main></Dialogs><Questions><I Name="Question_SaveChangesToFollowingLangs">Save changes to the following language(s) ?</I></Questions><Infos><I Name="Info_XmlSavedTo">'{0}' xml saved to {1}</I><I Name="Info_DicxSavedTo">'{0}' dicx saved to {1}</I><I Name="Info_LanguageAlreadyLoadedAt">'{0}' already loaded at {1}</I></Infos><Errors><I Name="Error_LanguageItemsAreMissing">{0} language item(s) are missing in {1}</I></Errors><XSystem.Update><Dialogs><I Name="Info_UpdateAvailable">Version : {0} is available</I><I Name="Info_CheckingForNewVersion">Checking for new version</I></Dialogs></XSystem.Update></Lang>
What I need is binarywrite code to save this to a binary file
Here is a link to my project:
LanguageEditor and DicxFiler download
any help would be great
Thank you
File System watcher service only runs once.
I have a windows service running with a file system watcher to do a database import. It works great the first time (although it fires twice). But then it stops firing for additional files. the service runs fine but the files do not trigger processing.
someone said make the watcher instance variable but i don't see how?
Its all mess code because i have tried everything...
Code below..
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Microsoft.VisualBasic.FileIO;
using System.Threading;
namespace PayrollUpdateService
{
public partial class Service1 : ServiceBase
{
//started yet?
//static bool transflag = false;
// static int trips = 0;
static string lastfile = "";
public Service1()
{
InitializeComponent();
WriteToFile("Payroll Update Service was initialized at " + DateTime.Now);
}
protected override void OnStart(string[] args)
{
WriteToFile("Payroll Update Service is started at " + DateTime.Now);
// FileProcesser fp = new FileProcesser(ConfigurationManager.AppSettings["FromPath"]);
FileProcesser fp = new FileProcesser(@"\\fileserver\Folders\IT\test");
fp.Watch();
}
protected override void OnStop()
{
WriteToFile("Payroll Update Service is stopped at " + DateTime.Now);
}
///////////////////////////////////////////////////////////////////////////////////
public static void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
///////////////////////////////////////////////////////////////////////////////// write to file end
////////////////////////////////////////////////////////////////////////////////////////
public class FileProcesser
{
FileSystemWatcher watcher;
string directoryToWatch;
public FileProcesser(string path)
{
this.watcher = new FileSystemWatcher();
this.directoryToWatch = path;
}
public void Watch()
{
watcher.Path = directoryToWatch;
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
// if (lastfile = e.FullPath)
// { //only process once
// return;
//}
int timeout = 5000;
while (timeout > 0)
{
try {
File.ReadAllText(e.FullPath);
//all copied..jump out and process it.
WriteToFile("Copy finished, process file.." + DateTime.Now);
timeout = 0;
}
catch (IOException)
{
WriteToFile("waiting for copy to finish.." + DateTime.Now);
}
Thread.Sleep(1000);
timeout -= 100;
}//while
//File.Copy(e.FullPath, @"\\fileserver\Folders\IT\test\processing\"+ Path.GetFileName(e.FullPath), true);
//Create the csv file and parce it...
string csvname = DateTime.Now.Ticks+"_payroll.csv";
WriteToFile(csvname + " sanatize txt file... " + DateTime.Now);
string text = File.ReadAllText(e.FullPath);
text = text.Replace("\",", "\"|");
text = text.Replace("\"\"|", "null|");
File.WriteAllText(@"\\fileserver\Folders\IT\test\processing\" + csvname, text);
WriteToFile("csv parsed...." + DateTime.Now);
WriteToFile(e.FullPath + ".....delete file ...." + DateTime.Now);
//delete text file..no longer needed
//File.Delete(e.FullPath);
///////////////////////////////////////////////////////////////////////
// timeout = 5000;
// while (timeout > 0)
// {
// try
// {
// File.ReadAllText(e.FullPath);
// File.Delete(e.FullPath);
//all copied..jump out and process it.
// WriteToFile("deleting file.." + DateTime.Now);
// timeout = 0;
// }
// catch (IOException)
// {
// WriteToFile("waiting to delete file.." + DateTime.Now);
// }
// Thread.Sleep(1000);
// timeout -= 100;
// }//while
///////////////////////////////////////////////////////////////////////////////
// String name = Path.GetFileName(e.FullPath).ToString();
// WriteToFile(name + " File Changed " + DateTime.Now);
//Truncate the Table
// TruncateTable();
WriteToFile("Temp table truncate done... " + DateTime.Now);
//Parce the CSV
// DataTable ProcessedcsvData = GetDataTabletFromCSVFile(@"\\fileserver\Folders\IT\test\processing\"+ csvname);
WriteToFile("CSV processed... " + DateTime.Now);
//Bulk insert the Datatable
// InsertDataIntoSQLServerUsingSQLBulkCopy(ProcessedcsvData);
WriteToFile("Done! " + DateTime.Now);
//remember last file
// lastfile = e.FullPath;
FileProcesser fp = new FileProcesser(@"\\fileserver\Folders\IT\test");
fp.Watch();
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
String name = Path.GetFileName(e.FullPath).ToString();
WriteToFile(name + " New file payroll received! " + DateTime.Now);
//do not nitify when working
// watcher.EnableRaisingEvents = false;
// File.Copy(e.FullPath, ConfigurationManager.AppSettings["ToPath"] + "\\" + Path.GetFileName(e.FullPath), true);
// File.Delete(e.FullPath);
// if (transflag == false)
// {
//File.Copy(@"\\fileserver\Folders\IT\test\payroll (78).txt", @"\\fileserver\Folders\IT\test\processing\payroll (78).txt",true);
//transflag = true;
//Sanatize the textfile
// string text = File.ReadAllText(@"\\fileserver\Folders\IT\test\payroll (78).txt");
// text = text.Replace("\",", "\"|");
// text = text.Replace("\"\"|", "null|");
// File.WriteAllText(@"\\fileserver\Folders\IT\test\payroll.csv", text);
// WriteToFile("csv parsed" + DateTime.Now);
// }
}
}
/////////////////////////////////////////////////////////////////////////////////////file watcher end
//////////////////////////////////////////////////////////////////////////////////////////////
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{ //Parce the CSV to a databale for insert
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "|" });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
return null;
}
return csvData;
}
////////////////////////////////////////////////////GetDataTabletFromCSVFile end
////////////////////////////////////////////////////////////////////////////////////
static void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
{//Insert the datatable into the database.
//Create Connection
var c = new SqlConnection();
c.ConnectionString = "Server = Donald;Database =hehehehe;User Id=sa;Password=blabla;";
c.Close();
using (c)
{
c.Open();
using (SqlBulkCopy s = new SqlBulkCopy(c))
{
s.DestinationTableName = "NewTempEtime";
foreach (var column in csvFileData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(csvFileData);
}
c.Close();
}
}
//////////////////////////////////////////////////////////////InsertDataIntoSQLServerUsingSQLBulkCopy end
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static void TruncateTable()
{//Truncate the table for the new insert of data
var c = new SqlConnection(); // Your Connection String here
c.ConnectionString = "Server = Donald;Database =heheheh;User Id=sa;Password=blabbla;";
c.Close();
SqlCommand command1 = new SqlCommand("Truncate Table NewTempEtime;", c);
try
{ //connect to the database
c.Close();
c.Open();
}
catch
{
//Could not connect to database.;
return;
}
//ok add the record
try
{
command1.ExecuteNonQuery();
}
catch
{
//failed to execute
c.Close();
return;
}
c.Close();
return;
}
//////////////////////////////////////////////////////////////////////////////////////TruncateTable end
}
}
Searching the Alternate Data Stream of files
Hello,
I'm need to build an application that will allow someone to search for a string inside of the alternate data stream of files. We have files (word, powerpoint, excel, text, .pdf) that have XML stored in the alternate data streams. I'm trying to find a way to let a user enter a string into a text box, select a folder location, then have the application search through each file in the selected directory for that string. Then display a list of the files that have that string in their streams. Any help or ideas is appreciated.
Use CSharp Protobuf ParseFrom(Stream),But Show Wire Type is Invalid,Could Someone Tell me Where am I wrong?Thanks a lot
Below is the code :
FileStream stream = new FileStream("D:\\share_jcy\\ProtoBuf\\demo.proto", FileMode.Open);CodedInputStream inStream = new CodedInputStream(stream);
TestDeprecatedFields f = TestDeprecatedFields.Parser.ParseFrom(stream);
TestDeprecatedFields was the class I compiled from the proto file with protoc.I run these code,but it comes System.InvalidOperationException:“Wire Type is invalid.”
Could Someone Tell me How can I Parse the proto file?Thanks a lot.
send SMS using C#
Google People API sample code to get list of contact groups
I'm using the new Google People API to load the list of a user's Google contacts into my app. I've used the code to get the list of contacts from the People API guide: www.developers.google.com/people/v1/read-people and that works fine, but I can't find any similar code to load the list of contact groups (eg family, workmates etc). I got this working before with the Contacts API and there is lots of sample code for that, but I can't find any for the People API in Csharp.
Thanks.
Converting PHP cURL to C# WebClient
I am trying to convert a piece of PHP cURL code to C# using the WebClient but I can't figure out how to implement the CurlFile parameter from the array.
Here is the original PHP code:
$post_data = array('password'=>'pswd', 'username'=>'usr', 'textfile'=>new CURLFile('C:\data_stats.txt'), ); $curl_obj = curl_init('https://www.website.com'); curl_setopt($curl_obj, CURLOPT_POST, true); curl_setopt($curl_obj, CURLOPT_POSTFIELDS, $post_data); $data = curl_exec($curl_obj);
And there is the C# code I came up with (I managed to send the password and username parameters but I don't know how to send the file with the key 'textfile' along with those parameters)
using (var client = new WebClient()) { var post_data = new NameValueCollection(); post_data["password"] = "pswd"; post_data["username"] = "usr"; var response = client.UploadValues("www.website.com", post_data); }