if (dgArtikujt.SelectedRows.Count >= 1) { decimal total = 0.0M; for (int i = 0; i < dgArtikujt.SelectedRows.Count; i++) { int index = dgTavolina.Rows.Add(); dgTavolina.Rows[index].Cells["TNr"].Value = dgTavolina.RowCount; //dgTavolina.Rows[index].Cells["TBarkodi"].Value = dgArtikujt.SelectedRows[i].Cells["Barkodi"].Value.ToString(); dgTavolina.Rows[index].Cells["TArtikulliID"].Value = dgArtikujt.SelectedRows[i].Cells["ArtikulliID"].Value.ToString(); dgTavolina.Rows[index].Cells["TEmri"].Value = dgArtikujt.SelectedRows[i].Cells["Emri"].Value.ToString(); dgTavolina.Rows[index].Cells["TSasia"].Value = 1.00; dgTavolina.Rows[index].Cells["TDs"].Value = dgArtikujt.SelectedRows[i].Cells["Ds"].Value.ToString(); ; dgTavolina.Rows[index].Cells["TCmimi"].Value = dgArtikujt.SelectedRows[i].Cells["Cmimi"].Value.ToString(); dgTavolina.Rows[index].Cells["TTVSH"].Value = dgArtikujt.SelectedRows[i].Cells["TVSH"].Value.ToString(); //total += fd.Cmimi.GetValueOrDefault(0) * fd.Sasia.GetValueOrDefault(0); dgTavolina.Rows[index].Cells["TVlera"].Value =0.00 ; ; } // dgTavolina.Rows[dgTavolina.Rows.Count - 1].Selected = true; txtSearch.Text = ""; levizshiritin(); }I have fill datagridview from another datagridview and this I will to save in database but i dont know how to do this.
How to insert data direct from datagridview to database using LINQ
C# async tasks
I'm starting learning how use async tasks and I would like to clarify two things:
- I know we should avoid async void taks unless we are in front of a event handler need. In my case, a user click a button and I need to run a bunch of methods (queries) in parallel for each block of information. Could I use it here?
- My code is saying Cannot wait void in the line "await Task.WaitAll(task1, task2, task3, task4);" What am I doing wrong here?
private async Task ExtractAllData(){ var task1 = Extraction1(); var task2 = Extraction2(); var task3 = Extraction3(); var task4 = Extraction4(); await Task.WaitAll(task1, task2, task3, task4); } public async Task Extraction1() { await ExecuteQuery("select * from Cars"); }
How to verify signed file signature in code?
Technology: C# .NET 2.0
Situation:
I would like one exe file to be able to check another exe file to see if it they were both signed by the same private key.
Story so far:
I can include either the CER file or the public key itself inside the first application as a resource, so I guess I'm really just asking how do you verify a signed file using a separate public key using .NET 2.0?
Thanks for reading.
Improve DataTable filling perfomance
I have a list containing 21 YYYYMM (years and months) which I loop though a Parallel processing, executing a query and populating a DataTable which further will be written into a csv file as you can see bellow.
Just the "Load" method in DataTable is taking 30 minutes to be executed, thereof I was looking to some suggestions how could I improve it.
lstFilterValues.AsParallel().ForAll(filterValue => { using (SAConnection _conn = DB_Connection.Connect(_psfAcronym)) { var queryWithFilter = mainQuery.Replace("@FILTER", filterValue.ToString()); IDataReader _dataReader = new SACommand(queryWithFilter, _conn).ExecuteReader(); var _dataTable = new DataTable(); _dataTable.Load(_dataReader); List<T> lstTableRows = new List<T>(TransformToObject.DataTableToList<T>(_dataTable)); using (var sw = new StreamWriter(filePath)) using (var csv = new CsvWriter(sw)) { csv.Configuration.Delimiter = UniversalVariables.csvDelimiter.ToString(); ; csv.Configuration.HasHeaderRecord = true; csv.Configuration.UseNewObjectForNullReferenceMembers = true; csv.WriteHeader<T>(); csv.NextRecord(); csv.WriteRecords(lstRecords); sw.Flush(); } SybaseIQ_Connection.Disconnect(_conn); } });The database table contains 21 million rows, which for each interaction should be something near 1 million.
Shrinking a file from start
Assume a big file, almost occupying the only available drive on a machine.
This file consists of a big number of fixed size chunks.
The chunk size for all the records need to be increased thereby restructuring the file, I think there is no direct operations for doing this.
My first thought is a simple one: Read one by one of the chunks from the file and add them to a new file with extra bytes at the end of each chunk, but this requires that the drive must be able to store both the original file and the new file (which is bigger than the original file) simultaneously until all the write work has been done and then the original file may be deleted.
My second thought was to read the first chunk of the original file, add it with the spare bytes to the new file and delete the first chunk from the original file, doing this iteratively will then require a little more than the size of the new file because the original file is shrinked in parallel with extension of the new file (which is simple by calling e.g. FileStream.SetLength).
How can the original file be shrinked? Shrinking by cutting the end of the file is simple, just do FileStream.SetLength, but is it possible to do similar by cutting from the start of the file?
I could of course doing it all reversed by reading the last chunk, adding it to the new file, but then the new file must be increased by SetLength to expand the start of the file and this seems to be the same problem.
Please note that the drive is not able to hold both files (at full size) simultaneously.
Please don't tell me to add more hardware or replace the drive, the machine is only available remotely and physical access is not currently possible.
How can I increase the width of the Html.TextBoxFor control beyond its default in an MVC 5 View
I am trying to increase the width of an Html.TextBoxFor control in an ASP.NET MVC 5 View page using razor syntax. I am using Visual Studio 2017. I created a css
style (textboxfor) to increase the control's width as shown below but it is not working.
Below is the MVC View:
@using rgmsite.Models
@model LoginTestViewModel
@{
ViewBag.Title = "Log in";
}
<style type="text/css">
.textboxfor-width {
width: 700px;
}
</style>
<h2>SimpleTest</h2>
<section id="loginForm">
@using (Html.BeginForm("Login", "Account",
new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post,
new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.TextBoxFor(m => m.Email,
new { @class = "form-control textboxfor-width",
placeholder = "Enter email address to be used as your user name"
})
</div>
}
</section>
Below is the View Model being used:
public class LoginTestViewModel
{
public string Name { get; set; }
public string Email { get; set; }
}
Using a smaller width value such as 40px in the css .textboxfor class works. But there seems to be some limit imposed on the control preventing it from being
wider (such as 700px) than the default. What needs to be done to make the TextBoxFor control wider than the default? Thanks in advance.
How to do this by C# Linq
Hello:
I want to know how to do this by Linq.
See the following C# code:
public class Scores { public int CourseID { get; set; } public string CourseName { get; set; } public int Credits { get; set; } public string Student { get; set; } } public static void Find_Max_Product_Credits() { List<Scores> binary_credits = new List<Scores>(); List<Scores> triple_credits = new List<Scores>(); Scores score1 = new Scores { CourseID = 2, CourseName = "MBA 1", Credits = 2, Student = "A", }; Scores score2 = new Scores { CourseID = 2, CourseName = "MBA 2", Credits = 3, Student = "A", }; Scores score3 = new Scores { CourseID = 2, CourseName = "MBA 1", Credits = 2, Student = "B", }; Scores score4 = new Scores { CourseID = 2, CourseName = "MBA 2", Credits = 2, Student = "B", }; Scores score5 = new Scores { CourseID = 3, CourseName = "Math 1", Credits = 3, Student = "A", }; Scores score6 = new Scores { CourseID = 3, CourseName = "Math 2", Credits = 4, Student = "A", }; Scores score7 = new Scores { CourseID = 3, CourseName = "Math 3", Credits = 5, Student = "A", }; Scores score8 = new Scores { CourseID = 3, CourseName = "Math 1", Credits = 3, Student = "B", }; Scores score9 = new Scores { CourseID = 3, CourseName = "Math 2", Credits = 6, Student = "B", }; Scores score10 = new Scores { CourseID = 3, CourseName = "Math 3", Credits = 9, Student = "B", }; binary_credits.Add(score1); binary_credits.Add(score2); binary_credits.Add(score3); binary_credits.Add(score4); triple_credits.Add(score5); triple_credits.Add(score6); triple_credits.Add(score7); triple_credits.Add(score8); triple_credits.Add(score9); triple_credits.Add(score10); }
What I want to do is:
I want to find the product of credits for the same CourseID of the same student, and sort the products of credits, then find those with the maximum of product of credits.
For example, for the CourseID = 2(MBA 1/MBA 2): Student ‘A’, his product of credits is: 2 * 3 = 6;
Student ‘B’, his product of credits is: 2 * 2 = 4;
For example, for the CourseID = 3(Math 1/Math 2/Math 3): Student ‘A’, his product of credits is: 3 * 4 * 5 = 60;
Student ‘B’, his product of credits is: 3 * 6 * 9 = 162;
Therefore, for CourseID = 2, Student ‘A’ has the maximum product of credits, which is 6; and for CorseID = 3, Student ‘B’ has the maximum product of credits, which is 162.
I can do this by multiple for loop, but since I have many different Courses (around 50), so I want find a better solution using Linq.
Please advice.
FrontPage Extensions Missing
Hi,
I am struggling to find any information on this error but using Windows 7 (64-bit), Visual Studio 2010, all updated, when I try and publish my C# application to a website it comes up with an error that I do not have FrontPage Extensions installed. This I know, but now that it is no longer supported, and as far as I know there is still not a release by Ready-to-Run for Windows 7, how can I get around this? Surely there is another way besides downgrading Windows?
The exact error is:
Failed to connect to 'ftp://ftp.mywebsite.com/' with the following error: Unable to create the Web site 'ftp://ftp.mywebsite.com'. The components for communicating with FrontPage Server Extensions are not installed.
Universal Click event?
Hello,
I've just started learning programming and started with C#. I'm working in Visual Studio C# .Net and bought a book with example programs with code. So i stumbled upon an example(the description text from the example is the following "To all RadioBox-es apply one universal Click Event threw which the object sender appoints which RadioButton is clicked )" where it is written that i have to assign an universal Click event on Radio boxes(Three radio boxes). In the answer, or to be exact in the finished code, when assigned it shows up like this:
private void rbPrevozUniversal_Click(object sender, EventArgs e)
{
}
Hhow do i assign the universal click event on those 3 radio boxes? I'm literally new to all this i know its a stupid question but can't find the solution.
An extra thing, the radio boxes are inside the groupBox and i need the universal event click because i'm trying to learn how StringBuilder and object sender function.
Thanks.
C# Gratuitous ARP - How to Implement
I Already implemented Sending ARP request using "iphlpapi.dll".
[DllImport("iphlpapi.dll", ExactSpelling = true)]
private static extern int SendARP(uint DestIP, uint SrcIP, byte[] pMacAddr, ref int PhyAddrLen);
Now i need to Implement Gratuitous ARP. Could anyone help
ref variable assignment via varname = condition ? ref a : ref b; doesn't work
Hello. I was going to report a possible bug in C# VS 2019 with ref variable assignment and was transferred to this site. Please redirect my report to the right place if this is a wrong one. Thanks.
I'm using ref var to work with array1 or array2 depending on some condition.
Here is my test code which works fine:
ValueDataSeries[] arr1 = new ValueDataSeries[10]; ValueDataSeries[] arr2 = new ValueDataSeries[10];
int f=5;
arr1[f] = arr2[f] = null;
ref ValueDataSeries vds = ref arr1[0]; //some mandatory initializer of ref variable vds
if (condition)
vds = ref arr1[f];
else
vds = ref arr2[f];
vds = new ValueDataSeries();
after that I see a reference to a new instance of ValueDataSeries class either in arr1[5] or arr2[5] depending on condition value.
The following modification doesn't work. i.e. there is no error reported and I see var vds is pointed to a new class instance but both arr1[5] and arr2[5] remained equal to null
ValueDataSeries[] arr1 = new ValueDataSeries[10];
ValueDataSeries[] arr2 = new ValueDataSeries[10];
int f=5;
arr1[f] = arr2[f] = null;
ref ValueDataSeries vds = ref arr1[0]; //some mandatory initializer of ref variable vds
vds = condition ? ref arr1[f] : ref arr2[f];
vds = new ValueDataSeries();
Insert image to a mysql table
I have used below code to insert student id and picture to my sql database and got an error message and appreciate your assistance.
…….MySQL table creation...
create table mst_image (student_id varchar(11) not null,foreign key(student_id) references mst_student(student_id),image longblob not null);
…..error......
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'student_mgt.insert into mst_image(student_id,image) values ('04190319003',_binar' at line 1'
…..c# coding.....
{
MySqlCommand cmd;
FileStream fs;
BinaryReader br;
string FileName = txtStudentImage.Text;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
string CmdString = "student_mgt.insert into mst_image(student_id,image) values (@id,@image)";
cmd.Parameters.Add("@id", MySqlDbType.VarChar, 11);
cmd.Parameters.Add("@image", MySqlDbType.LongBlob);
cmd.Parameters["@id"].Value = txtbx_prntid.Text;
cmd.Parameters["@image"].Value =picbx_vwid.Image;
int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected > 0)
{
MessageBox.Show("Image saved sucessfully!");
}
conn.Close();
}
Security issue needs to be resolved.
public void AddFileSecurity(string fileName, string account,
FileSystemRights rights, AccessControlType controlType)
{
// Adds an ACL entry on the specified file for the specified account.
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
File.SetAccessControl(fileName, fSecurity);
} // AddFileSecurity
This is how it's called:
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTINAdministrators")]
case "AddFileSecurity":
Console.Clear();
Console.WriteLine("AddFileSecurity\n\n");
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ShowDialog();
string fName = openFileDialog1.FileName;
sd.AddFileSecurity(fName, @"DomainName\AccountName",
FileSystemRights.FullControl, AccessControlType.Allow);
break;
EXCEPTION
System.Security.SecurityException HResult=0x8013150A Message=Request for principal permission failed. Source=mscorlib StackTrace: at System.Security.Permissions.PrincipalPermission.ThrowSecurityException() at System.Security.Permissions.PrincipalPermission.Demand() at System.Security.PermissionSet.DemandNonCAS() at ComeAndGet.SecurityAndDebug.AddFileSecurity(String fileName, String account, FileSystemRights rights, AccessControlType controlType) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\SecurityAndDebug.cs:line 25 at ComeAndGet.Form1.comboSecurity_PG9_SelectedIndexChanged(Object sender, EventArgs e) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Form1.cs:line 7575 at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e) at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m) at System.Windows.Forms.ComboBox.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m) at System.Windows.Forms.Control.WmCommand(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Control.WmCommand(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ComboBox.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at ComeAndGet.Program.Main() in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Program.cs:line 16
how to use dragon speech recognition sdk tools in to c#
hello everyone
I want to use the Dragon speech recognition SDK tools (without Dragon Bar) in c#. Can anybody tell me some tips regarding this. i also need some helpful article or e-books about this.
How to get a List from a public void method
I have saved a book using a public void method:
myLibrarian.SaveBook(newBook);
So my newBook is saved, and i want to show the list of saved books that i made. I also have a public void method for it:
myLibrarian.GetBook(newBook);
My question is how do i make an instance where it will show me the complete list of books that i saved?
public class Librarian { private List<Book> bookList = new List<Book>(); public void SaveBook(Book book) { bookList.Add(book); } public void GetBook(Bok allBook) { foreach (Book book in bokList) { Console.WriteLine(book.ToString()); } } }
rest api consumed from c# desktop application run forever
i have a rest api written in asp.net core and deployed on the server that do a relatively long processing (around 15 minutes) then after finishing it return an "ok" status string.
if i run it from a web browser it work without a problem like expected . it did the job and return "ok" when finished .
but when consumed from a WPF application using httpclient the task is executed but i never get the result back . it continue to run indefinitely even all the tasks are done (i have checked that) .
here my button click event to start the operation
try { (sender as Button).IsEnabled = false; savedtime = DateTime.Now; // this is used to display a timer on the screen so users know how much time it's taking System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 1); dispatcherTimer.Start(); await Task.Run(async () => { await callserverapi(); }); dispatcherTimer.Stop(); (sender as Button).IsEnabled = true; await Task.Delay(10000); this.Close();
and here the callserverapi function
private async Task<string> callserverapi() { var httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromMinutes(30); HttpResponseMessage response = await httpClient.GetAsync("https://myremoteserver.com/Api1"); if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsAsync<string>(); } return result; }
also please note that if i use this same code snippet with a remote api that don't take time it work without a problem .
any idea on how to fix this please ?
thanks
.Contains help? I'm trying to figure out if a collection contains something...
I apologize if my question doesn't make sense, I'm not very technical when trying to ask questions but here goes...
I'm trying to figure out if a collection contains something. The last 'IF' statement is the part I'm having trouble with. I want demosAreDifferent to be set to 'true' if viewModel.CurrentMaster.DemoSelections does not contain what is in 'demo' but it's being set to true even when 'demo' is contained in DemoSelections. What am I doing wrong?
var demosAreDifferent = false; if (campaign.CampaignMediaMaster?[0].DemoSelections.Count != viewModel.CurrentMaster?.DemoSelections.Count) { demosAreDifferent = true; } else { var demoCounter = 0; foreach (var demo in campaign.CampaignMediaMaster?[0].DemoSelections) { var vmDemo = viewModel.CurrentMaster?.DemoSelections[demoCounter++].DemographicID; if (demo.DemographicID != (int)vmDemo) { demosAreDifferent = true; } // the next IF is where I'm having the issue... if (!viewModel.CurrentMaster.DemoSelections.Contains(demo)) { demosAreDifferent = true; } } }
Thanks in advance for any guidance you can provide!
- Joni
Issues with Partner Center API
Hello,
I am trying to use BuildSeekQuery() as shown in the code below:
IQuery customerQuery = QueryFactory.BuildIndexedQuery(pageSize: 50);
SeekBasedResourceCollection<Customer> customers = await partner.Customers.QueryAsync(customerQuery);
var nextQuery = QueryFactory.BuildSeekQuery(SeekOperation.Next,pageSize: 50 token: customers.ContinuationToken);
var customersNext = await partner.Customers.QueryAsync(nextQuery);
It is giving me an exception while running nextQuery to get customersNext. If I get the continuation token from first time querying, how can I use it to get next set of customers? I tried to use BuildSeekQuery() with diff parameters as shown below, but every time, it gives me the exception that
Exception: "Continuation Token can't be null"
although it is not null. Can someone please help me with this?
var query = QueryFactory.BuildSeekQuery(SeekOperation.First, pageSize: 50 token: customers.ContinuationToken);
Thanks.
Send SMS by email or c# program winform to a mobile phone
I want to send SMS by a program in c# code. The code I used is showing below but the short message doesn't sent, I've got an error message.
the c# code :
static SerialPort p10 = new SerialPort("COM3", 9600);
public Form3() { InitializeComponent(); button1.Click += new EventHandler(button1_Click); }
private void button1_Click(object sender, EventArgs e) { //p10.DataReceived += new SerialDataReceivedEventHandler(p10_DataReceived); p10.Open(); p10.Write("ATrn"); Thread.Sleep(500); p10.Write("AT+CMGF=1rn"); Thread.Sleep(500); //p10.Write("AT+CMGS="+ 0667713897 0626291128 + "rn"); p10.Write("AT+CMGS=" + "0626291128" + "rn"); Thread.Sleep(500); p10.Write("!personal gateway!n"); Thread.Sleep(500); p10.Write("Hello yomabeh in jicixipi gateway"); p10.Close(); }
Thanks for your help !
Callback from underlying Get Set methods using Reflection
Hi
I have hundreds of properties in the Model class.
is there a way to intercept or get a callback whenever a "get or set" is made on a particular property using reflection?
i would like to try and achieve this without changing source code of the Model class.
thanks
public class Model { public int one { get; set; } }
var model = new Model();
model.one = 1;var one = model.one;