C#

93K

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

I have a VS C# application that reads an Excel spreadsheet and writes data into a table in SQL. The users now want to use this same spreadsheet but separate data into different tabs. Is there a way to prompt the user and display the different tabs in the spreadsheet and allow them to chose which tab has the data they want to import? I will also need to read the data in the corresponding tab.
0
Upgrade your Question Security!
LVL 12
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

I wrote a service.  The service gets data from a database and exports to excel.

Issue I'm having is that the database and application contain the below value:

Humboldt-Universität zu Berlin

However, in excel the value is

Humboldt-Universität zu Berlin

Any idea how to resolve so excel has Humboldt-Universität zu Berlin?
0
Hi

I have a list of URL's in a file that I need to process
and a List of  finished URL's in another Log file
after I've finished with a URL I write / append it to the Log  File

How do check the current URL isn't in the Log File therefore not already processed

using System;
using System.IO;
using System.Linq;

public class Program
{
	public static void Main()
	{
		    string LogFile = System.Environment.CurrentDirectory + "\\Log.txt";
            var URLFromLog = File.ReadAllLines(LogFile).Select(l => l.Trim());
            var URLFromURLs = File.ReadAllLines(@"Path\To\URLs.txt").Select(l => l.Trim()); // This File may contain Duplicates and changes each time the program runs
		// Only Add to URLs if unique and not already in the Log File

// This doesn't look right but unsure what it should be
            var URLs = URLFromLog.Distinct().Concat(URLFromURLs).ToList();
		foreach (string sURL in URLs)
		{
			    var URL = sURL;
			// Do Stuff with URL 
                File.AppendAllText(LogFile, sURL + Environment.NewLine);
		}
	}
}

Open in new window

0
I am developing a C# .net MVC page to allow users to make some selection, query data and display the data with paging function.
I use a partial view for the data display but fail to maintain the main view and the data after click on different page.

Please advise me, have attached the code as below (Index.cshtml, SearchController.cs, WebGrids.cshtml)

Index.cshtml
______________

@model DLTWeb.Models.SearchModel

@{
    ViewBag.Title = "Index";    
}

<header>
    <script src="~/Scripts/jquery-3.0.0.js"></script>
    <script src="~/Scripts/jquery-3.0.0.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>  
    <script src="~/Scripts/gridmvc.min.js"> </script>
    <link href="@Url.Content("~/Content/style.css")" rel="stylesheet" type="text/css" />  
    <link href="@Url.Content("~/Content/PagedList.css")" rel="stylesheet" type="text/css" />
</header>

<h2><font color="blue">@Html.Label("lblReport", "DLT Web Report")</font></h2>

<br />

<table>
    <tr>
        <td>Report Name</td>
        <td>@Html.DropDownListFor(m => m.ReportName, (IEnumerable<SelectListItem>)ViewBag.ListReport, "---------------Select Report----------------", new { @id = "ddlReport", @onchange = "javascript:GetFields(this.value);" })</td>        
    </tr>
    <tr>
        <td>Fields Name</td>
        <td>
            <select id="ddlFields" name="ddlFields">
                <option>---Select Fields---</option>
            </select>
        …
0
This is my first experience with WCF and I am having a hard time wrapping my head around what is going on here. I have created an N-Tier application that uses a SQL database on our server. The application runs fine while running within Visual Studio because it automatically creates the WCF service. What I don't understand is how to create the service when the application is run outside of VS.

I have read many articles that detail the different ways to host the service but none that explain the steps to do it. Most take for granted a certain degree of knowledge with IIS, which I have no experience with it. I know you can also self-host the service. It seems like this would be the way to go, but again, I can't find documentation for setting this up.

Any help would be greatly appreciated.

Thanks,

Randy
0
Hello,

I am creating a razor page in asp.net core 2.0 with C#

I have a form listing a variable number of  jobs from a database.  

I want a button next to each job number (field from database) that is named button + job_number

What syntax do I use for creating a variable button name?  

Any info would help to point me in the right direction.  I am a newbie (sorry!) and am not really sure where to start.

Thanks!
Bonnie
0
Using C# .NET, I'm looking for a way to convert Excel documents to PDF without using paid third party tools or Office Interop assemblies (free third party tools are ok). This application needs to run on a server, so unmanaged code (i.e, Office Interop) is a big no.

Appreciate any insight about where to begin my research!
0
Hi,

I am using HSSFCellStyle for font and color in excel.

i am merging some cells and set the border.

unfortunately, the border set only top for the merged cells. border not set while merging cells.even though i have given and set border top,bottom,left and right.

what is the problem and where we need to give the code...

Sample code and screenshot for your reference..

Code :

  		IRow rowOne2 = sheet2.CreateRow(0);
                IRow rowTwo2 = sheet1.CreateRow(1);
                HSSFCellStyle style1 = (HSSFCellStyle)excelFile.CreateCellStyle();
                var palette1 = excelFile.GetCustomPalette();
                palette1.SetColorAtIndex((short)20, (byte)146, (byte)208, (byte)80);
                style1.FillForegroundColor = (short)20;
                //style1.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.FillPattern = FillPattern.SolidForeground;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.Alignment = HorizontalAlignment.Left;
                // font color
                HSSFFont fontstyle1 = (HSSFFont)excelFile.CreateFont(); // text font
                fontstyle1.Color = 

Open in new window

0
Using C# .NET, I'm looking for a way to convert Excel documents to PDF without using paid third party tools or Office Interop assemblies. This application needs to run on a server, so unmanaged code is a big no.

Appreciate any insight about where to begin my research!
0
Experts

I need a way out to write a c# windows  service that needs to get triggered every n seconds. And try to keep session alive by either by sending keystrokes or any way possible without showing anything on screen. Everything should be behind the scenes and silent. Service part is done. I am in need of the logic that could keep session of the machine alive and not allow machine to lock out or idle out.Please help.
0
Cloud Class® Course: Microsoft Windows 7 Basic
LVL 12
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

i have the following code, and i wanted to know if its a possible issue for a deadlock
its a multithreaded console app

 lock (thisLock)
                    {
                        try
                        {
                            bool messageSent = getSmtpClientAndSendMessage(companyID, msg);
                        }
                        catch (Exception ex)
                        {
                            WriteErrorsToLogAndScreen(ex, "exception on lock: getSmtpClientAndSendMessage");
                        }
                        finally
                        {

                        }
                    }

Open in new window


if it is, what can i do to eliminate a deadlock?
0
I am writing a program to read a number of excel files which will in turn export one excel file with defined data.

I have the below code.  With System.Array I can't do MyValues[1,1].  It returns an error.

So, I decided to return a List<>.  However, the nulls are not populating.  

Is there a way to get all the values of system.array to a List<>.  I included a screenshot to show the diff between the two variables.  I want all values copied over to List<>.
System.Array MyValues = (System.Array)MySheet.get_Range(AppSettings.GetColumnStart() +
                               index.ToString(), AppSettings.GetColumnEnd() + index.ToString()).Cells.Value;

var lst = MyValues.OfType<Object>().ToList(); 

Open in new window


I came up with the below solution.  Is there an easier way than looping through the System.Array?
List<string> test = new List<string>();

foreach (var r in MyValues)
{
	if (r != null)
		test.Add(r.ToString());
	else
		test.Add("");
}

Open in new window

0
Hi,
How to set and apply RGB Color in HSSFCellStyle.

For example, below is my code.

HSSFCellStyle styleHeaderSum = (HSSFCellStyle)excelFile.CreateCellStyle();
styleHeaderSum.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index;

instead of "LightGreen" color, i just want to apply RGB (250,250,250) color.

How to set the color in  "styleHeaderSum.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.??????
0
In my MVC app I have a JsonResult

public JsonResult AddNewRegionofInterest(string _roi_data)

Open in new window


the roi_data is
[[182,216],[182,217],[182,218],[182,219],[182,220],[182,221],[183,212],[183,213],[183,214],[183,215],[183,216],[183,217],[183,218],[183,219],[183,220],[183,221],[183,222],[183,223],[183,224],[183,225],[183,226],[184,209],[184,210],[184,211],[184,212]]

Open in new window


In the C# i need to cast this to a list of points:
List<Point> points = new List<Point>();

Open in new window


I've tried this
List<Point> points = new List<Point>();

            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            points = (List<Point>)json_serializer.DeserializeObject(_roi_data);

Open in new window



but it errors on the last line with the exception
System.InvalidCastException: 'Unable to cast object of type 'System.Object[]' to type 'System.Collections.Generic.List`1[System.Drawing.Point]'.'

Open in new window


any ideas?
0
Dear Experts!

I have create a calculator in Window Form Application using C#, it is working very well, now I want your assistance to improve it further.
(1)      The calculator works as long as you are using the clicking data way of input only.
(2)      The calculator is part of the form like the input form.

Now I want your help on the following:
(1)      How to allow the inputting of data through the keyboard as well
(2)       In an event where I decide to create a project for this calculator, then how do I call it if I want to use it?

Please  forgive me I’m a fun of VBA that is why my condition logic has something to do with VBA except convention from text to integer (Parse) and from integer to string (Tostring) which are purely C# products

Below is a full code for the said calculator:

double total1 = 0;
double total2 = 0;
bool plusButtonClicked = false;
bool minusButtonClicked = false;
bool divideButtonClicked = false;
bool multiplyButtonClicked = false;

==================================================

//This calculator has buttons for inputing data

==================================================

private void btnOne_Click(object sender, EventArgs e) 
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e) 
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnThree.Text;
}
private void btnFour_Click(object sender,

Open in new window

0
i have a validateall method()

the code inside this method runs all the way and then in the end displays all the errors at once, how could i run though each individual piece of code inside a method and display one error then break wait for user to fix it and again run validate all error now skip the first error and move on to the next one.

 public bool validateall(int runtime, decimal useful, string line, string machine, string plant, string starttime, string stoptime, string prodcode, decimal underperformance)
        {
            
            int val = 0;
            bool final = false;
                if (runtime < 0)[b] ->>>> run this if there is a error i want the response.write to go to work immediately instead of the entire validateall method and in the end displaying all the response.write messages for the user.[/b]
                {
                    Response.Write("<script language=\"javascript\">alert('" + "You have a production time < 0 minutes.Please check your Start and Stop times." + "');</script>");
                    //string script = "alert(" + "You have a production time < 0 minutes.Please check your Start and Stop times." + "\");";
                    //ScriptManager.RegisterStartupScript(this, GetType(),
                    //                      "ServerControlScript", script, true);
                    secondcheck = false;
                }
                else
                {
                    secondcheck = true;

                }
 

Open in new window

0
I am creating the following html field on the fly in c# code....and trying to validate if its a number or not.
 contact.allocation = @"<input type='number'   onblur='validateDecimal(this);'  pattern='\d + '   step='0.01' value='" + contact.allocationValue + "' placeholder='0.00'  id='txtAllocation_" + contact.clientxcontactId + @"'>%</input>";

Open in new window

When I leave the input box the validateDecimal is always telling me to please return a valid number....even if I just put a value like 6 or 6.00

Here is the validate function:
function validateDecimal(value) {
    if (!($.isNumeric(value)))
        Conarc.UI.Messenging.getErrorPopup("Please enter a numeric value for Allocation");
}

Open in new window

0
I have an MVC.Net application with C#.Net codebehind.

In one of my views I use a Telerik.UI grid.  I need help using the Replace function in the grid's template.
I want to Replace the backslash in the FileName value, with a Double backslash (something like this:    #=Filename.Replace('\','\\')  

How can I do this?  in my code below:

                        {
                            field: "HIPBatchID",
                            title: "EDI Portal Batch ID",
                            template: "&nbsp;<input type='button' value='#=kendo.toString(HIPBatchID)#' class='RoundCorner' onclick='getErrorLogByBatchID(\"#=HIPBatchID#\",\"#=Filename#\")' style='width: 90px;border:0; background-color:white; color:darkblue;' />",
                        },

Open in new window



Thank you in advance,
mrotor
0
i have a method called validateall()

user enters values into a gridview header template clicks on the insert button and before the insert occurs it runs thorough the validateall method to make sure all the rules are correct.

public bool validateall(int runtime, decimal useful, string line, string machine, string plant, string starttime, string stoptime, string prodcode, decimal underperformance)
        {
        bool firstcheck = false;
        bool secondcheck = false;
        bool thirdcheck = false;
        bool fourthcheck = false;
        bool fifthcheck = false;
        bool sixthcheck = false;
        bool sevnthcheck = false;
        bool eightcheck = false; 
            int val = 0;
            bool final = false;
          
          
            try
            {

                if (useful / runtime > 1)
                {
                    if (IsPostBack)
                    {
                        List<string> message = new List<string>();
                        message.Add("You have a TE>100%.");
                        message.Add(" Please check your values:");
                        message.Add("- Volume produced (quantity and unit)");
                        message.Add("- Start and Stop times");
                        message.Add(" - Setup and Break");
                        message.Add(" - Item Code(s) and Line/Machine");

                        Response.Write("<script language=\"javascript\">alert('" + message[0] + "' + '\\n' + '" + 

Open in new window

0
Free Tool: SSL Checker
LVL 12
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hello, I need your advice in which program can i accomplish the following either with C# or Python.
I am a Sys Admin working for a DevOps environment.

We have QA, UAT and PROD environments.
100% of the the time we need to help developers in Copying, Pasting  From / To, Starting a service, Stopping a service and Recycling an app pool in IIS.
But in PROD night, we are done around 8pm, 1hr approx which includes: Copying, Pasting  From / To, Starting a service, Stopping a service and Recycling an app pool in IIS then we have to wait, wait wait and wait if the developers find any issues in PROD and they need the Sys Admin help for Copying, Pasting  From / To, Starting a service, Stopping a service and Recycling an app pool in IIS.

It was my first time that I experienced that and I said: Damn, the whole Copying, Pasting  From / To, Starting a service, Stopping a service and Recycling an app pool in IIS can done programmatically and we do not need to wait till midnight or so if Developers need a SysAdmin, in other words i can try to develop an executable that can do the following:

Which environment are you working: QA, UAT, PROD
Servers are listed: 1, 2, 3, 4
Which windows service are you going to work ? (List of services)
Browse the source, Get the file,.
Need to stop the service (Yes/No)
Browse to the target ? Place
This server has the following App Pools (List of the App Pools)
Do they need to be recycle ?

Thoughts ? Thanks for your help
0
When I check in my website using Paypal it gives me this message: "Checkout Error - Amount total mismatch" I used Microsoft tutorial to implement PayPal:

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal

I did exactly what it said I even did twice but somehow keep getting this error Appreciate your help Thanks

public partial class CheckoutReview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { NVPAPICaller payPalCaller = new NVPAPICaller();

            string retMsg = "";
            string token = "";
            string PayerID = "";
            NVPCodec decoder = new NVPCodec();
            token = Session["token"].ToString();

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                Session["payerId"] = PayerID;

                var myOrder = new Order();
                myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                myOrder.Username = User.Identity.Name;
                myOrder.FirstName = decoder["FIRSTNAME"].ToString();
                myOrder.LastName = decoder["LASTNAME"].ToString();
                myOrder.Address = decoder["SHIPTOSTREET"].ToString();
                myOrder.City = decoder["SHIPTOCITY"].ToString();
                myOrder.State = …
0
I am trying to read an excel file.  The excel file is set up like a form and not with columns and rows.  I found the below example to work with but unsure if it will get the data I need the way I need it.

I am using below for the connection string    

<add key="ConnectionString" value="Provider=Microsoft.Ace.OLEDB.12.0; data source={0}; Extended Properties='\Excel 8.0;HDR=NO;\'"/>
                foreach (var fn in fnm)
                {
                    var connectionString = string.Format(AppSettings.GetConnectionString(), fn.FileName);
                    Console.WriteLine(connectionString);

                    var adapter = new OleDbDataAdapter("SELECT * FROM [" + AppSettings.GetWorkSheetName() + "]", connectionString);
                    var ds = new DataSet();

                    adapter.Fill(ds, "MySpreadsheet");

                    DataTable data = ds.Tables["MySpreadsheet"];

Open in new window


Anyone have any code sample to read an excel file in C#?
0
Hi,  I have another error in my .NET application.

"Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. "


Error
0
hi,

I have an ASP.NET error and I am unsure what is causing it...  Please see.. Error
I am hoping someone will be able to help me.
0
Dear All;
We have one issue with one of our superior, he wants an interface which was done in window form application using C# programming language opposed to the MS access interface done with VBA, according to him, VBA is too junior compared to C#. Correct me if I’m wrong:
(1)      VBA & C# code are very much similar, the only major notable differences are :
•      In C# we use curly blackest ({}) while in VBA they are not applicable
•      VBA works only along a program for example Excel, Word or Ms Access while C# work in windows not necessary a program
•      VBA uses Subs & Functions while in C# uses Functions
•      Variables C# are declared in one standard way while in VBA you opt to use Dim function, for example in C# an integer will be declared like ( int firstNumber ) if we want to store a number we will just now write like ( firstNumber = 12) while in VBA we will use Dim ( intFirstNumber as integer ) and then say intFirstNumber  = 12)
Now my question is how we are going to deploy an interface written in C # connecting to MS Access Back End through Sql scripts to our clients.
Currently all our interface are based within Ms Access (FE), we simply tell our client to download Ms Access runtime for all the users and put the Backend on the server while all the users will have their FE installed on their machine.
Any idea how to deploy this C# interface based application to the clients??????????
0

C#

93K

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).