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

Hi experts,

I have a asp.net mvc 5 application using C#, Razor, jquery.

This is a followup to this ticket:
https://www.experts-exchange.com/questions/29104238/hyperlink-in-ASP-NET-using-Razor.html?anchor=a42592893¬ificationFollowed=208651180#a42592893

in my view on my table my link is set like this it works fine:

<a id="ReportLink" target="_blank" href="http://google.com/employeeid=@item.EmployeeID">@Html.DisplayFor(modelItem => item.EmployeeID)</a>

Because on click i want user to got to
http://google.com/employeeid=1
http://google.com/employeeid=2
http://google.com/employeeid=3


<a id="ReportLink" target="_blank" href="http://google.com/employeeid=@item.EmployeeID">@Html.DisplayFor(modelItem => item.EmployeeID)</a>

Is there a way to set the href attribute to

Having a Javascript variable called firstpartofhref = "http://google.com/employeeid=" and then set it in the href before the @razor tag something like this?

 href=" firstpartofhref + @item.EmployeeID"

Or
can i just store this razor tag @item.EmployeeID in a javascript variable called secondpartofhref also?

and then set the href attribute something like this?

 href=" firstpartofhref + secondpartofhref"
0
I'm trying to update a C# command console application to use Exchange 2013. I used snapins before. I am getting this error on the following code.  What am I doing wrong?

The term 'Enable-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

  public static bool EnableEmailAddress(Employee user)
        {
            bool succeed = true;
            String url = @"http://server/powershell?serializationLevel=Full";
            System.Uri uri = new Uri(url);
            Console.WriteLine(url);
     


            Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();

            PowerShell powershell = PowerShell.Create();
            PSCommand command = new PSCommand();
            command.AddCommand("New-PSSession");


            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", uri);

       
            command.AddParameter("Authentication", "Kerberos");
         

            powershell.Commands = command;

            try
            {
                runspace.Open();

                powershell.Runspace = runspace;

                Collection<PSSession> result = powershell.Invoke<PSSession>();

                foreach (ErrorRecord current in powershell.Streams.Error)
                    Console.WriteLine("The 

Open in new window

0
How to remove trailing decimal zeros from decimal type in C# ?

-0.0000600000 => -0.00006
 0.0000000000 =>  0
0
I'm trying to set up a web page that collects information from a user prior to allowing them to connect to a WiFi network. A similar, desired, scenario would be something like when you use free wireless at a hotel or Starbucks, etc. I've already got things set up so when a new device connects, the user is redirected to my page. That page is set up to do what I need it to do, but now I'm at a point where I need to connect the user to the wireless connection. What do I need to do? I'm working on a Cisco network and coding in C# (ASP.NET).
0
Is there a built in C# control that allows me to view folders in a manner similar to Windows Explorer.  I tried the folder browser dialogue, but I want it to be part of my form not a dialogue box by itself.
In other words, I want a textbox to be updated as the user chooses the directory.
I was thinking of something like the drive and directory list boxes they had in vb6.
0
Hi experts,

I'm learning to work with hyperlinks in MVC views.
So I created the example below to illustrate my question.

I have a ASP.NET MVC 5 application. I'm using C# and Razor.

I have an example that uses database first model.
I'm using the Employees table from the Northwind sql server database.

My application directory looks like this.

p1.PNG
My model looks like this:

EntityModel.PNG
My controller looks like this:

HomeController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using NorthwindApp.Models;

namespace NorthwindApp.Controllers
{
    public class HomeController : Controller
    {
        // ASP.NET Scaffolding in Visual Studio 2013
        // http://www.asp.net/visual-studio/overview/2013/aspnet-scaffolding-overview
        // Getting Started with Entity Framework 6 Database First using MVC 5
        // http://www.asp.net/mvc/overview/getting-started/database-first-development/setting-up-database

        private NorthwindEntities db = new NorthwindEntities();

        //***************************** INDEX *****************************
        // GET: Home
        public ActionResult Index()
        {
            var employees = db.Employees.Include(e => e.Employee1);
            return View(employees.ToList());
        }
        //***************************** INDEX 

Open in new window

0
I have a function that filters the contents of a listbox based on input from a textbox. It works, but it is case sensitive. How can I make it case insensitive? The current code is below. I am using C# in building a Windows Forms application.
List<string> list = new List<string>();

        private void Form1_Load(object sender, EventArgs e)
        {
            list.Clear();

            foreach (String str in listBox1.Items)
            {
                list.Add(str);
            }
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtSearch.Text.Trim()) == false)
            {
                listBox1.Items.Clear();
                foreach (string str in list)
                {
                    if (str.StartsWith(txtSearch.Text.Trim()))
                    {
                        listBox1.Items.Add(str);
                    }
                }
            }
            else if(txtSearch.Text.Trim() == "")
            {
                listBox1.Items.Clear();
                foreach (string str in list)
                {
                    listBox1.Items.Add(str);
                }
            }
        }

Open in new window

0
Looking for examples to prepare test data for DB Integration tests for the complex classes that are interdependent in C#

For example below is the structure of 3 entities and when i wanted to generate some test data how can i ensure the foreign keys are taken care

Are there any tools to easily generate test data

testdata.PNG
for example i am trying to generate sample data as follows

	public static List<ErrorCollection> GetSampleData()
	{
            var notification = new Notification{
		Type = "TestType",
		State = "Dummy",
		EndTime = DateTime.Now.AddDays(10),
		ProductId = 10
		
	    }

            return Enumerable.Range(1, 10).Select(i => new ErrorCollection()
            {

                CollectionName = string.Format("Collection_{0}",i),
                NotificationId = notification.Id

            }).ToList();
	}

Open in new window


Here i am getting Foreign key conflict error, my question here is how can i ensure that the foreign key data is handled if we are trying to add sample date for complex entities

the code is using EF6 and the id for primary key is automatically generated, can i simulate that in Database Integration tests?
0
Hi,

I have the following code:

string input = "aaBBcc";
string str = new string(input.ToLower().Distinct().ToArray())

Open in new window


so  
input.ToLower().Distinct().ToArray()

Open in new window

makes "aaBBcc" to "abc" and put them into char[] array, correct?

Then it creates string object like
new string(input.ToLower().Distinct().ToArray())

Open in new window

I don't understand this part.
How can we convert a array of char to string?  How does this string contain the content of the array?
0
I have this code to search a word document for a given string.  How can I store the page number on which the string was found?

                      string DRow = "";
            DirectoryInfo dir = new DirectoryInfo(@"D:\documents");
            foreach (FileInfo f in dir.GetFiles())
            {
                using (StreamReader sr = new StreamReader(f.FullName))
                {
                    while (sr.Peek() >= 0)
                    {
                        DRow = sr.ReadLine();
                        if (DRow.Contains(","))
                        {

                        }
                    }
                }
            }

Open in new window

0
I'm not able to insert my data from C# Windows Forms Application with the code below, the error message is below as well, please note that my MS SQL Server database name is called CaPremier

System.ArgumentException: 'Keyword not supported: 'initialcatalog ( This is my error message I'm getting)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=SQL EXPRESS;InitialCatalog=CaPremier.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd;
            con.Open();
            string s = "insert into SalesTraining values(@customer,@address)";
            cmd = new SqlCommand(s, con);
            cmd.Parameters.AddWithValue("@customer", txtCustomer.Text);
            cmd.Parameters.AddWithValue("@address", txtAddress.Text);
            cmd.CommandType = CommandType.Text;
            int i = cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show(i + " Row(s) Inserted ");
        }
    }
}

Kindly see how you can help

0
Create assembly [SMS_Attend]
from 'C:\Users\Muhammad\Documents\Visual Studio 2015\Projects\Database3\Database3\bin\Debug\Database3.dll'
with permission_set = unsafe

Open in new window


CREATE ASSEMBLY failed because it could not open the physical file 'C:\Users\Muhammad\Documents\Visual Studio 2015\Projects\Database3\Database3\bin\Debug\Database3.dll': 5(Access is denied.).

0
I would like to parse this in C#

000-40-0703  should be read as 40703

Ignore the first 3 trailing 0's  000
remove all "-"

Remove the second digit "0" in 40
0
Is there a .Net library somewhere that validates emails.

And by validates... I mean...
Pass in a string and it checks for spaces, double periods @@ etc.
0
I'm working with the Duo Auth API and I've run into a minor hitch. When requesting a logo the response is a string which apparently contains the logo as "Content-Type image/png". Specifically, the documentation states
On success, the response body is Content-Type image/png, containing the logo.
(Link here: https://duo.com/docs/authapi#first-steps)
My question is, having successfully retrieved the response, how do I convert the string value into a usable png image?
0
Consider I have a reference to a form.  The base class, not a derived class because the object storing the form reference doesn't 'know' what derived class in advance it will be.
What would be a reliable way to store and call a method in the actual derived class.

eg.
I have a form of type MyForm1 called myForm1 which has a method DoSomething.  So to call the method I normally use myForm1.DoSomething().
I also have another form of Type MyOtherForm myForm2 which has a method DoSomethingElse.   usage: myForm2.DoSomethingElse()

Now I store these particular forms in a List<Form> or a List<tuple<Form, ???>>.  How would I store the address of the methods DoSomething and DoSomethingElse ?

Then at a later stage I would want to iterate through the list and call that method.
Something like
lstForms[0].DoSomething();
lstForms[1].DoSomethingElse();
Not forgetting the list just has the base class Form as the generic type so the above won't even compile.
0
Consider the following.
There is a list  ( List<Form>  ) which contains three different forms.  On some event I want to do something to each form in that list.  Now in the meantime one of those three forms has been closed, not hidden or minimised but frm.Close() called.
Is there an easy way when iterating through that list to detect if the form still exists ?  There is a method - IsDisposed - would this be a safe way to check ?

eg.
if(frm.StillExists())
  frm.DoSomething();
0
using signnow.com c# library, and I have the following case.

1. Web Form fill out the information and click a button
2. save the data into the ms sql server.
3. save the data into selected PDF file and create a new flatten PDF file
4. send to SignNow.com for esignature by using c# API

Question:
1. How to send the flatten document to SignNow by c# API?
2. is it possible to use PDF template that already stored in SignNow portal? If yes, how to get it on item 3?
0
I'm using Postman to send a command to an API method. I put a debug step and the code stops in the API method but one of the parameters comes out as NULL.

1. This is the API method signature. I see that "[FromBody]". Not sure if this is what's causing the null

 [IncludeInApiExplorer]
        [Route("CMDB/Asset/{id}")]
        public ResultModel Post(Guid id, [FromBody]CMDB_Asset asset)
        {

Open in new window


2. Documentation has this as sample request format

api
or this

image
3.  I used postman to build the parameters and I have this. I'm doing it on my local code.

http://localhost:3180/CMDB/Asset/6da60bdc-0272-4f04-89e6-fb48dbc51d31?CMDB_ID=fe0d7fe1dbdd5704b3b33cae7c9619a5
&Schedule=206UK&Serial=7JRDNN2&Manufacturer=test Inc.&Model=test&CustomerReference&CDF01=425003yyy7-TASK0089972&CDF02&CDF03&CDF04&CDF05=GBLHR04&CDF06&CDF07=In stock&CDF08=Available&CDF09&CDF10&SiteAddress=test, Springfield Dr&SiteCity=Leatherhead&SiteState=Surrey&SiteLocale&SiteRegion&SitePostalCode&SiteCountry=GB

Open in new window


4. I run it in Postman. Step thru the code. It gets to this line of code but asset is null. "id" is not null..id comes out as 6da60bdc-0272-4f04-89e6-fb48dbc51d31.

 public ResultModel Post(Guid id, [FromBody]CMDB_Asset asset)

How do I need to call this API?
0
Dear Experts,

 I have an excel file contain few sheets each sheet contain aprroximatly 40000 rows.

How do I in C# using HSSFWorkbook (NPOI.HSSF.UserModel) convert specific sheet to CSV.

from this sheet i need to be copied only column by specific ( input ) name or column by specific order


Thanks
0
Hi,

I have a table in SQL Server and the name of the table is "Employee"

Also i have some records in that table.

I have another Data table called "Dt1".  I just want to compare these two tables and find out the new records and duplicate records.

this i want to perform using stored procedure and the output should display C# in Data table..

What logic we need to use in stored procedure..?

Sample table and output as mentioned in the screenshot.
screeshot.png
0
I am using C#, Visual Studio 2017, and the Microsoft.Office.Interop.Excel assembly for Office 2016 to open a an Excel Workbook, looping through every Worksheet to find the picture named "Picture 1" and save it as a PDF file.

I have two versions of the project. One version is a Console App which grabs a list of all the workbooks in a directory, extracts "Picture 1" from each worksheet, and save it as PDF. This works perfectly.

The second version is a Windows Service and uses a Deployment Package for the installation. When I install the application on the same computer and start the service, it is able to open the excel document and do some tasks like grabbing text from a cell, but when it gets to this part of the code the application hangs and I don't know why:
xlChartObject.Chart.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, destinationDirectory + paymentCode + ".pdf", XlFixedFormatQuality.xlQualityStandard, true, true, 1, 1, false);

I have the service configured to run as Local System so it should have sufficient permissions. I've attached an image of the ProjectInstaller and Deployment Project if that helps.

    public static class ExcelExtensions
    {
        public static int SaveInvoiceData(this Worksheet xlWorksheet, string destinationDirectory, string serialNumber, string depositDate ,string errorFolder, out int errorCount)
        {
            try
            {
                int processCount = 0;
                errorCount = 0;
              

Open in new window

0
How  to JsonConvert.DeserializeObject :
{"status":"ok","message":"","data":[***Array of json data*********]"}

I have JSON response data above, and i want to get array of data so that i can loop thrue the data...

public class Response<T>
    {
        public string IsSuccess { get; set; }
        public string Message { get; set; }
        public IEnumerable<T> ResponseData { get; set; }

        public Response(string status, string message, IEnumerable<T> data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }

Open in new window


And here is code from my function:
if (resp.IsSuccessStatusCode)
                {
                    Console.WriteLine("Request Message Information:- \n\n" + resp.RequestMessage + "\n");
                    Console.WriteLine("Response Message Header \n\n" + resp.Content.Headers + "\n");

                    string responseBody = resp.Content.ReadAsStringAsync().Result;
					var test = JsonConvert.DeserializeObject<Response<string>>(responseBody);
                    
                    Console.WriteLine(responseBody);

                }

Open in new window

0
All,

I have got a problem with a piece of C# code and I cannot see the issue and I need this sorted now as we have a production issue. Thanks to Windows 10 being stupid in swapping applications to different screens when their active screen is turned off and not being clever enough to swap them back when the screens are back on again, we are ending up with applications stacked behind each other on the Primary Screen.

To address this issue we are adding code to the applications so that based on a command line parameter they have a designated screen number on which they run (/Screen:n, where n is the screen number they run on). The parameter is validated and if found to be invalid is defaulted back to 1 (the Primary Monitor). We have a timer that checks the screen position and flips the displayed form over to the required screen if available.

This all works fine in the VB.Net applications, and the applications swap quite happily and correctly.

However, the C# version just ignores the request and remains in the Primary Monitor regardless. The form startup position is set to manual, and the code to re-position is (as far as I can tell) a correct C# version:

        private void SetScreenPosition(int requiredScreen)
        {
            if ((SystemInformation.MonitorCount == 1) || (requiredScreen == 0) || (requiredScreen > SystemInformation.MonitorCount))
            {
                requiredScreen = 0;
            }
            else
            {
           

Open in new window

0
Hello Experts,
in Visual c# how can I convert a png image that is in negative to positive ?
Regards
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).