C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

how do I do this with a lambda expression?
int[] n1 = new int[18] { 5, 9, 1, 2, 3, 7, 5, 6, 7, 3, 7, 6, 8, 5, 4, 9, 6, 2 };
            var nQuery =
            from VrNum in n1
            group VrNum by VrNum into y
            select y;
            foreach (var i in nQuery)
            {
                Console.WriteLine("Number " + i.Key +" appears " +i.Count()+" times.");
            }

Open in new window

0
Can anyone tell me the voodoo needed to test for BACKUP<DIV is contained in str?

str is declared as a string.

These attempts throw VS errors

if (str.IndexOf("BACKUP<DIV")) != true)
if (str.IndexOf("BACKUP<DIV")) <> true)
if (str.IndexOf("BACKUP<DIV")) != 0)
if (str.IndexOf("BACKUP<DIV")) <> 0)
0
I'm trying to start a new visual studio 2017 C# project and have selected it to be an MVC project with the web API checkbox checked.  I've also checked the add unit test checkbox and changed the authentication to single user.  After I click OK I'm getting this message.

the specified path file name or both are too long. the fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.  The fully qualified file name is D:\OneDrive\Documents\Courses\QAASPNETMVC\Labs\04  DataStorage\01 Setup Projects\Begin\QAForumSolution which is 103 characters.
Why am I getting this message?
0
Hi,

I am working on improving the speed of the webpage.

It is advised that
Image(s) are missing width and/or height attributes.
Now I have image arrow.png.

Used in the site with below code.

<span class="m-currency--icon">
      <img src="~/assets/images/currency/arrow.png" />
</span>

Dimensions of the image is 42 x 119

To improve the performance it is required that image should have width and height.

If I add width and height of the image in img src then my responsiveness of the site will go.

My site is responsive.

How we should use width and height in this case?

Thanks
0
Hi,

My code is in C# using .net framework 4.5

I need to Minify JavaScript and CSS files.
Please advise how to do it in easy way.
0
Hi Experts,
I have the following code. If the ModelState has error then I want to make the  email textbox red. Please help me how to do it. I am using c# MVC.
Thanks in advance!

@Display(Model.Content)
@using (Html.BeginFormAntiForgeryPost()) {
    @Html.ValidationSummary()
<div class="login-page">
    <h3>@T("Your email address")</h3>
    @Html.TextBox("email", string.Empty, new
    {
        maxlength = 100
    })
</div>


public ActionResult ForgotUserName() {
			var model = _LoginViewModelProvider.GetForgotUsernameViewModel();
			return View(model);
		}


[HttpPost]
		public ActionResult ForgotUserName(string email) {			
			if (!isValidEmail) {
				ModelState.AddModelError("_FORM", T("We're sorry. The information you provided does not match an account in our records."));
				return ForgotUserName();
			}
			
		}

Open in new window

0
Hi

I wonder if someone can give me a clue how to fix this

The RegEx is failing because there is a ")" in the string I'm trying to clean it's causing an exception error

"Run-time exception (line 26): parsing "https://Unwanted.com/this/url/file...123).zip" - Too many )'s."

Manually Remove the ")" from the string and all is good

I tested the regEx at regex101 it works

To be clear I only want the first line
so ModName should = "I want all this Line (here)"

		Regex RegHTTP = new Regex(@"(https.*)$");
		  string pattern = @"(https.*\)?.*)$";
		Console.WriteLine("Hello World");
		string ModName = @"I want all this Line (here)
		
		https://Unwanted.com/this/url/file...123).zip";
		
        RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;
        
        foreach (Match m in Regex.Matches(ModName, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
			ModName = Regex.Replace(ModName, m.Value, "");
        }
		ModName = ModName.Trim();// .Replace("\n", string.Empty);

		Console.WriteLine("ModName: [{0}]", ModName);
	}

Open in new window

0
I have a C#  application with a variable  selectedPeriod.mnthyear

I need to have the variable accept both regular values and Null

The test  script (attached)  is ok when there is a value.

When the value of the variable  is null  the application  reports an error as attached

What is wrong with my test syntax for   selectedPeriod.mnthyear  when it is null ?

Thanks

Olukay
HandlingNull16022019.PNG
0
I'm trying to use WIA to scan multiple pages through the document feeder. I can access the scanner, connect to the scanner, and even actually scan but it doesn't quite work as expected. If I have more than one page in the document feeder the scanner scans all pages at once and then creates a single image that is only the first page. I'm following the examples from here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/edaa6de7-e372-4b57-89a5-dd74c5f30983/adf-scanning-using-wia-only-one-image-saved?forum=csharpgeneral

There seems to be some reference to other people experiencing the same problem and a link to a supposed solution here: https://support.microsoft.com/en-us/help/261820

Unfortunately, that link is dead so I'm hoping someone here might have a clue. How do I get the scanner to actually scan multiple pages rather than feed them all but only scan the first one?
0
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps
I am using above form wizard and everything is working fine except the validation. the current code will only validate if the <input> field is empty.
My question is: how to use jquery built-in validation in this case so I do not have to write codes to check one by one? Because in my case, I have over 20+ <input> for each steps and I have at least 5 steps to go.

thanks
0
If our code has a dispose method then why do we also need the Idisposable interface?  Just implement the dispose method without the interface.  This code complies even if the class does implement the IDisposable interface.
Conversely the second piece of code does not compile without the IEnumerable interface.  I'm trying to understand what interfaces do.  I've been told they are used as a contract between developers, so the junior developer know which methods and properties to implement.  However I think there is much more to them.

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class BaseClass //: IDisposable
{
    // Flag: Has Dispose already been called?
    bool disposed = false;
    // Instantiate a SafeHandle instance.
    SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            handle.Dispose();
            // Free any other managed objects here.
            //
        }

        disposed = true;
    }
}

Open in new window



using System;
using System.Collections;
using System.Collections.Generic;

class Example : IEnumerable<string>
{
    List<string> _elements;

    public Example(string[] array)
    {
        this._elements = new List<string>(array);
    }

    IEnumerator<string> IEnumerable<string>.GetEnumerator()
    {
        Console.WriteLine("HERE");
        return this._elements.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this._elements.GetEnumerator();
    }
}

class Program
{
    static void Main()
    {
        Example example = new Example(
            new string[] { "cat", "dog", "bird" });
        // The foreach-loop calls the generic GetEnumerator method.
        // ... It then uses the List's Enumerator.
        foreach (string element in example)
        {
            Console.WriteLine(element);
        }
    }
}

Open in new window

0
Hi. I just found that WFP not working as well as I expected.
My application suppose to work on tablet with touch screen but it works sort off. I found that there is problems with touch screen in WPF.
I try to use the solution I found on Microsoft "DisableWPFTabletSupport" now program crash as soon I touch any button.
I urgently need help.
0
I have these unit tests in a class library which compiles.  When I select run all tests it simply says build succeeded.  There is an App.config file in the test project and the data project.  Could that be causing a problem?
Why are the test not appearing in the text explorer?

using Microsoft.VisualStudio.TestTools.UnitTesting;
using StockControl.Data;

namespace StockControl.Tests
{
	[TestClass]
	public class StockDataTests
	{
		[TestMethod]
		public void DataContextCreationTest()
		{
			using (StockControlEntities db = new StockControlEntities())
			{
				Assert.IsNotNull(db);
			}
		}
		[TestMethod]
		public void ProductToStringTest()
		{
			Product p = new Product()
			{
				UniversalCode = "987654",
				Name = "Something good",
				Price = 5.99M
			};
			Assert.AreEqual("987654 $  5.99 Something good", p.ToString());
		}
        [TestMethod]
        public void RepositoryCreationTest()
        {
            using (Repository repo = new Repository())
            {
                Assert.IsNotNull(repo);
            }
        }
    }
}

Open in new window

0
Hello Experts,
Here is the partial code of my Encryption program which encrypts the data in 256 bits.  Here I am trying to understand the code to take it to next level.

1. What is the meaning of Encryption.m_Key = new byte[0x20] ?  Why it is [0x20], not [0x22] ?
2. What is the meaning of Encryption.m_IV = new byte[0x10] ? Why it is [0x10], not [0x11] ?
3. How line 1 and 2 are related?  I mean to say byte[0x20] and byte[0x10]. Does the 2nd one needs to be 10 byte long because 1st one is 20 bytes?
4. Why do we use m_IV?  Does the name matter here?

Please answer the above questions if possible.  FYI, I am not allowed to post the code.  I modified it as little as possible for explaining things.

Thank you very much in advance.

            public void GenerateKey()
            {
                  Encryption.m_Key = new byte[0x20];
                  Encryption.m_IV = new byte[0x10];
                  
                  RegistryKey key2 = Registry.LocalMachine.OpenSubKey("XXXXXXX").OpenSubKey("SubKey2");
                  if (key2 != null)
                  {
                        RegistryKey key3 = key2.OpenSubKey("SubKey3");
                        if (key3 != null)
                        {
                                      .
                                      .
                                      .
                        }
                  }
            }
0
Hello,
I need an AES-256 encryption/decryption example and found one.  How would I know if this is 256 bit encryption?

https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=netframework-4.7.2

Thank  you!
0
I need to merge a bunch of xml files and save into 1 removing any duplicate entries
I'm getting errors in ConsoleApplication2 @ line         private history = new history();

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS1519	Invalid token '=' in class, struct, or interface member declaration	ConsoleApplication2	d:\VB\Test\ConsoleApplication2\ConsoleApplication2\Program.cs	13	Active

Open in new window


any suggestions what the above is?

Unless there is a better way I was going to use sort on id to filter out duplicates with the newest file taking precedence over older


using System.IO;
using xml;

namespace ConsoleApplication2
{
    class Program
    {
        private history = new history();

        static void Main(string[] args)
        {
            string RootDir = @"C:\Users\user\AppData\Roaming\AppName\user";
            
            if (Directory.Exists(RootDir))
            {
                var Files = Directory.EnumerateFiles(RootDir, "history.xml", SearchOption.AllDirectories);
                foreach (string File in Files)
                {
                    this.history += xml.history.Load(File);
                }

            }
        }
    }
}

Open in new window


xml.cs

using System.Xml.Serialization;

namespace xml
{
    
    public class history
    {
        List<post> post{ get; set; } = new List<post>();
        private static string xmlFile { get; set; }

        public static history Load(string xmlFile)
        {

Open in new window

0
I am looping through a recordset and wish to add up the quantity field.

Is that possible in c#?

I tried Convert and TryParse.
0
The query below returns -1 as a record count.

           
SQLQuery = "select somast.fduedate, somast.fsono, Description,   dateCreated as LastScanDate,sum(fquantity) as doorTotal " +
                    "from somast " +
                    "left outer join soitem on somast.fsono = soitem.fsono " +
                    "left outer join DoorTrak.dbo.Transactions on left(somast.fsono, 6) = left(DoorTrak.dbo.Transactions.SO, 6) " +
                    "left outer join DoorTrak.dbo.Entities on DoorTrak.dbo.Transactions.userID = DoorTrak.dbo.Entities.entityID " +
                    "where somast.fstatus = 'Open'  and somast.fduedate >= '2-12-2018' " +
                    "and(fprodcl in ('SE', 'SD', 'SL', 'SM', 'SR', 'SS', 'ST', 'LV')) " +
                    "and dateCreated in (select max(dateCreated) from DoorTrak.dbo.Transactions where left(somast.fsono, 6) = left(DoorTrak.dbo.Transactions.SO, 6) )  " +
                    "group by somast.fsono, fcompany, somast.fduedate, forderdate, fordername, fprint_dt, dateCreated , Description " +
                    "order by somast.fduedate";

Open in new window


The query below will return a record count of 9,920.
           
SQLQuery = "select * from somast where fduedate > '2/12/2018'";

Open in new window


Anyone have an idea as to why this would happen?  I would think that the cursor location wouldn't matter from one query to the next.
0
I  am using a webapi controller in which I want to use javascript to convert the
current date to mmddyy before passing as a string to the model.

Can I use javascript in the controller and how would I do this?

//controller
using picture_of_the_day.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace picture_of_the_day.Controllers
{
    public class PicOfTheDayController : ApiController
    {
        [Route("api/PicOfTheday/GetPicByDate/{date}")]
        [HttpGet]
        public IHttpActionResult GetPicByDate(string date)
        {
            try
            {
                var pic = new Picture(date);

                return Ok(pic);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}
//Model
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace picture_of_the_day.Models
{
    public class Picture
    {
        public int SequenceNum { get; set; }
        public string Date { get; set; }
        public string Caption { get; set; }
        public bool Active { get; set; }
        public DateTime DisplayDate { get; set; }
        public string FileName { get; set; }

        public Picture(string picDate)
        {
            using (var sqlConn = Database.GetConnection())
            {
     

Open in new window

0
In Excel VBA I will "Add" modules to my code.  Within my modules I'll create subs and functions.  All of this in an effort to manage my code.

I don't ever add classes as I'm not sure what they are.

If I'm using c# in Visual Studio, how do I accomplish the same thing?  Code management...

Thanks
0
Hello Experts,
I am looking for a AES-256 Encryption/Decryption program to deal with my Customer Credit Card numbers.  If possible, please help find me an industry standard sample program.

Thank you very much in advance.
0
Hello all.

I am generating a spreadsheet with multiple sheets and would like to understand how to manage the merged cells on specific sheets.

Here is how I create the sheets (its dynamic based on the size of the array):
Int32 sheetCount = countSheetsFromArray;
                UInt32 sheetIDCount = 1;

                for (uint i = 0; i < sheetCount; i++)
                {
                    Sheet sheet1 = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = sheetIDCount, Name = "ABC " + (i + 1) };
                    sheets.Append(sheet1);

                    sheetIDCount ++;

                    Sheet sheet2 = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = sheetIDCount, Name = "DEF " + (i + 1) };
                    sheets.Append(sheet2);

                    sheetIDCount ++;
                }

Open in new window


I have Mergedcell class that I call a method but it seems to apply the same format on all the sheets.
var rplMergeCells = new RPLMergeCells();
                       worksheetPart.Worksheet.InsertAfter(rplMergeCells.MergeCell(), worksheetPart.Worksheet.Elements<SheetData>().First());

Open in new window


Any input wold be helpful.

Thanks.
Jed-
0
Databases are an must in most programming so I'm wondering what is the best way to do it in C#?
Can someone suggest a online tutorial I can get started with?
I'm not asking how to build a database nor how to Wright SQL queries

I found a tutorial here  I'm surprised he is writing sql statements  within the flow shouldn't they be separated?
In the very first block of code seems wrong

Shouldn't there be a test to see  if the connection is actually open before using it?

  private void button1_Click(object sender, EventArgs e)
  {
   string connetionString;
   SqlConnection cnn;
   connetionString = @"Data Source=WIN-50GP30FGO75;Initial Catalog=Demodb;User ID=sa;Password=demol23";
   cnn = new SqlConnection(connetionString);
   cnn.Open();
   MessageBox.Show("Connection Open  !");
   cnn.Close();
  }

Open in new window

Further in the tutorial he binds a database column to a text box and DataGridView I didn't get that far unsure if this was the correct  method


Anyway I've used that tutorial and some data from here  to create my first console app bellow
I get the feeling I'm missing something especially not hard coding a query with a doctors name  in the real world this would be from a user input so how dose C# combat SQL injection?

I'm using an SQLite database I'm assuming the general principles are the same

using 

Open in new window

0
I have PDF form that users can fill out and upload into our site.  I capture the fields and write to our database.  
I also allow users to edit the information thru edit forms in our site and allow them to export the PDF Form from our site.

I need to add a signature field to the PDF Form and capture this info if they upload the form.
I also need to allow a user to click a button to "Sign" the record and capture their signature info that I can then export to the PDF Form.

If I could just get my hands on a good example, it would be so helpful!
0
In C# I'm trying to implement drag and drop functionality
I used code:

private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            treeView1.Select();
        }

Open in new window


private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
             if (treeView1.SelectedNode.FullPath.Substring(treeView1.SelectedNode.FullPath.Length - 4, 4).ToLower() == ".pdf")
            {

                ls_selected_node = treeView1.SelectedNode.FullPath;
            }
            if(string.IsNullOrEmpty(ls_selected_node) == true)
            {
                MessageBox.Show("Select a valid File.", "Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return;
            }

            if (e.Button == MouseButtons.Left)
            {

                string file = dirpath1_t + ls_policy_no + "\\" + ls_selected_node;
                string[] files = new string[1];
                files[0] = @file;
                DataObject data = new DataObject(DataFormats.FileDrop, files);
                DoDragDrop(data, DragDropEffects.Copy);
                ls_selected_node = "";
            }
        }

Open in new window


But when I press mouse button on a third level node, I got a root node value and if I use event:

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
           treeView1.Select();
        }

Open in new window


user has to click twice, first to select and second to drag, how to do it in a right way?
0

C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).