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

/*
I want to be able to open the cvs files read them and compare with the sourceDir, which has multiple sub sub directories  and match  the files, then move the files from source to destinDir

Example of csv files
\\allfiles.current.com\Storage\bfiles\TX\F\818\FL\TX_FFL_8189.pdf
\\allfiles.current.com\Storage\bfiles\TX\W\000\II\TX_WII_0008000.PDF
\\allfiles.current.com\Storage\bfiles\MD\W\000\II\TX_WII_0008791.PDF
\\allfiles.current.com\Storage\bfiles\TX\W\000\DR\(1151168)DS_0008896_00~08-19-015-97W8~0.pdf
\\allfiles.current.com\Storage\bfiles\MS\W\000\DR\(1863880)DS_0003770_00~03-09-089-97W8~3.pdf
\\allfiles.current.com\Storage\bfiles\PA\F\000\DR\DS_0005905_00~19-90-089-95W8~0.PDF
\\allfiles.current.com\Storage\bfiles\TX\GA\031\AN\0315688\7993650_100190306313600_AN_90100817.pas
\\allfiles.current.com\Storage\bfiles\TX\LA\091\AN\0917317\7999130_100-05-39-039-10-W8-00 - 9010-19-10 - AN.pas
\\allfiles.current.com\Storage\bfiles\GA\WI099\RG\0998618\000000966508800.PAS
\\allfiles.current.com\Storage\bfiles\NY\SA\098\AN\0981883\7993887_AN_Dee Three Exploration Ltd._109071908613W59_9011-05-06.PAS
\\allfiles.current.com\Storage\bfiles\TX\W\088\FA\0887866\7388858_Petrobakken Energy 100-01-18-087-01w5 #13189sg.pas
\\allfiles.current.com\Storage\bfiles\MI\W\099\AN\0990896\7999191_100-08-98-038-11-W8-09 - …
0
I have an aspx web form that I want to open with the browser maximized.  To do so I have found this code in a search here at EE.  The post says "Just insert it in your aspx code".  Can anyone tell me where exactly to insert it?

Here is the javascript to insert:
<script language="JavaScript1.2">
top.window.moveTo(0,0);
if (document.all)
{ top.window.resizeTo(screen.availWidth,screen.availHeight); }
else if
(document.layers || document.getElementById)
{
if
(top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth)
{ top.window.outerHeight = top.screen.availHeight;
top.window.outerWidth = top.screen.availWidth; }
}
</script>

Here is my code for default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="LineStatus.LineStatus" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<title>"Production Line Status"</title>
<meta http-equiv="refresh" content="30">
<body>
<form id="form1" runat="server">

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="100%" Width="100%" Font-Size="X-Large" Font-Names="Calibri" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="2" ForeColor="Black" HorizontalAlign="Center" OnRowCreated="GridView1_RowCreated"

0
How to I and what namespaces do I need to call an Web API using VB.net or C#.

I want to populate a dropdown list with the json file passed to my app fro my webAPI.

Isaac
0
I have a C# program that runs perfectly under Windows 10.  It uses Connected Services so that I can add in additional Class and Method functions to connect to Ultimate Software's HR system and pull our employee information from.  What I would like to do is run this application under Linux CentOS.  I installed Mono for Linux on both CentOS 6 and CentOS 7; and verified 100% that it can and does run compiled Visual Studio C# programs under Linux.  No problem.

However, when I run the EXE program under Linux Mono, it does not connect to the external website defined in Connected Services.

Here is the line it is failing on.

loginClient = new LoginServiceClient("WSHttpBinding_ILoginService");


And the error I get back, is (of course), a NullReferenceException as the defined object of 'loginClient' never gets instantiated.

System.NullReferenceException: Object reference not set to an instance of an object.


Has anyone ever successfully taken an EXE file for Windows using Connected Services and run it under Linux Mono?

Thank you,
Jeff
0
I am working in a C#  application

I have constituted  a List with the script Below:

StaffNameListBox.DataSource = GlobalConfig.Connection.GetEmployees_All();
StaffNameListBox.DisplayMember = "FullStaffName";

public string FullStaffName
{
get
{
return \$"{Staff_no}  { Surname } {Firname }";
}
}

(See  the Screen of The list below showing a record in the list

On the Click event on this record I want to return a part of the string (ie just the staff_no)

to a text box on the screen.  The name of the textbox is StaffNoValue

My click event syntax  is as below:

private void StaffNameListBox_Click(object sender, EventArgs e)
{
StaffNoValue.Text = StaffNameListBox.ValueMember;
}

What I want Returned to the text box on screen is as shown below

StaffNoValue.Text = "N001"

How can I get a portion of a list returned into a field using the actual name with which the list was loaded

and not by searching for a sub string of the selected item

Thanks
Selection-From-List--11-01-2019.PNG
0
In a stored procedure I would like to examine 3 SQL char data fields in a table that contain phone numbers. Some of the fields have no value (but they are not null). I want to find the first field that has a value (phone number) and then return that value to a newly created field that I can pass on to my Visual Studio 17 C#  program.

Example:
table1.field1 = ""
table1.field2 = 1234567891
table1.field3 = 2345678966

table1.new_field = 1234567891
0
I need help or examples of how to import a PDF Form using iTextSharp or something similar.  I am using dropbox for the Upload Form. I want to read the contents of the uploaded PDF Form
and write a new record to my database.   I can export to a PDF form using iTextSharp so I hope I can import as well.

My View looks like this:

@{
}

<div class="row" style="margin-bottom: 10px; margin-top: -20px;">
<div class="col-xs-8">
</div>
</div>

<div class="col-xs-10">

<p class="help-block">
Use the form below to add a New Request.  The Form uploaded must be the correct Request form
using PR.#### Rev. # dated 1/9/2019.
</p>

<p class="help-block">
<a href="~/PathtomyForm.pdf" target="_blank">Request Form Version #</a>
</p>

</div>

<div class="col-xs-10">

<div class="row">
{
@class = "dropzone dz-clickable",
@enctype = "multipart/form-data",
@id = "documentDropzone"
}))
{
<div class="dz-message">
Drop files here or click to upload.
…
0
Hi Experts,
I have the following code. I want to display the  message present in Model.UploadIssueMessages  in <li></li> under "InvaliFileFormat" div.

<div class="validation-summary-errors" style="display:none" id="InvaliFileFormat">
<ul>
<li> Invalid file format! Allowed file formats are .ai,.eps,.png,.jpg and .pdf</li>
</ul>
</div>

{
//<li></li> should display the message present in Model.UploadIssueMessages instead of a fixed message
}

0
I'll explain in steps what happened...

1. My manager moved the production database to a new server. It went from server YYY to XXX, for example
2. He changed the webconfig on the server to point to the new database. All good so far.
3. I wanted to update our production webserver with the new code. I don't publish directly to the server. I publish locally and just copy the Bin folder to prod (along with whatever files like JS, etc)
4. This is the publish settings:

5. I published locally in Release mode. Copied the Bin folder. I didn't replace the webconfig on the production webserver. It was pointing to the correct database XXX.
6. I went to the site and the site was down with an error that looked like it was a connection to the database.
7. This is what I did to fix it. I went back to the code and in the Web.Release.Config, I saw the connection string as being the old one; YYY. I changed the connection string to XXX (new one). Compiled, published, copied the Bin folder and this time it worked. Note that I didn't replace the Production webconfig file

So, how does this work... I didn't replace the webconfig on the prod server, I only changed it locally, compiled , republished and only copied the Bin folder.
0
I am trying to work with Thread.CurrentPrincipal and need some help with that. Never used that before so any help will be helpful.

this is what i have so far.

interface IAmSomething
{
bool something(string role);
}

{

if (haveRole.something("some_string_value"))
{
}

I just need to test for now by hardcoding some values so what should i do in order for the if statement to work. as expected if statement is throwing a null exception .
0
I have a stored procedure which is expecting a data table with one column (user defined table type in SQL Server).
The data table has had to include an extra column, so the stored proc is failing due to the extra column.
How can I pass the first column of the data table to the stored proc.
I'm using C# in Visual Studio 2017.
0
I am building a file parser for use to import exported csv files into our DB.
Three has to be some amount of processing on the data before it can be imported
and it depends on which table the ddata is coming from.

I am "copying" a design for a migration tool that was originally built by someone
else to handle only files from 2 tables and am wondering how to facilitate a single
function for multiple tables.

We have a function called FilesToProcess that gets the list of files froma specific
directory in our configuration.

Then, for each of the files in the list, it calls a Load function to actually do the
processing of the rows in the file.

I want the Load function to be able to handle the multiple export files and return the
correct data to the caller.
    public List<ExportInfo> Load(string fileToProcess)
{
switch (fileToProcess)
{
case "CUSTPP_DATA_TABLE.csv":
var importList = new List<CustPPExportInfo>();
{
// skip header row if there...
if (!line.StartsWith("FCUSTPPID,FPPID,"))
{
var export = ParseCustPPRow(line);
}
}
return importList;
break;
case

0
I am creating my first Web API.
I've run into some confusion.

I'm getting a error message during compile in vs2013
which states:
not all all code paths return a value

This message relates to the controller logic
I'm thinking possibly I need a get and set in some format.

The model has me confused.

I want to call the controller.

So during a few attempts with somewhat different logic.

I need a hand.

Isaac
0
Hi Experts,
I have this attached page in MVC. I have 3 required fields Business email address, Homepage URL and Description. When I try to submit the form it shows me error because they are required fields. But also have one not required field "Choose file". When a file is selected I am checking for the extension. If the extension is not allowed then I am displaying the msg at the top. But in that case I don't want the form to be submitted either. But right now I can show the error message but don't know how to stop submitting the form.

I am checking for the input file format in the change event.

<script language="javascript" type="text/javascript">
jQuery("input[type=file]").change(function(e) {
var fileName = e.target.files[0].name;
jQuery.ajax({
type: "POST",
data: '{PageType: "LOGOSUBMIT", FileName: "' + fileName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response == false) {
var msg = "Invalid file format! Allowed file formats are .ai,.eps,.png,.jpg and .pdf";
jQuery('#Wrong_File_Format_msg').html(msg);
jQuery("#File_Format_Msg").show();
}
else {


0
I have some code like this.  I'd like to go through one of the columns and set a cell to numeric if it's a number.  Otherwise leave it as string.  I'm using Visual Studio 2017 C#.
using (var xls = new ExcelPackage())
{
for (int i = 1; i < sheet.Dimension.End.Column + 1; i++) //stop dates appearing as numbers
{
if (sheet.Cells[1, i].Text.ToLower().Contains("date"))
{

sheet.Column(i).Style.Numberformat.Format = "dd/MM/yyyy";
}
else if (sheet.Cells[1, i].Text.ToLower() == "exercisenotice")
{
sheet.Column(i).Style.Numberformat.Format = "0\\D";
}
}
sheet.Column(13).Style.Font.Bold = true;
sheet.Column(14).Style.Font.Bold = true;
sheet.Column(15).Style.Font.Bold = true;
xls.SaveAs(new FileInfo("C:\\0temp\\Accreters.xlsx"));
}

0
I have code like this.  How can I format a column of cells (except for the heading in row 1) like a custom format?  When I look at the source spreadsheet the custom format of the cell is 0"D"
For example the number 2 would be represented as 2D.

using (var xls = new ExcelPackage())
{
for (int i = 1; i < sheet.Dimension.End.Column + 1; i++)//stop dates appearing as numbers
{
if (sheet.Cells[1, i].Text.ToLower().Contains("date"))
{

sheet.Column(i).Style.Numberformat.Format = "dd/MM/yyyy";
}
}
}

0
I have a following class class Result.

public static class Result
{
public static List<string> fromDifferentClass = new List<string>{ "cat", "dog", "bear" };
}

And I am accessing this fromDifferentClass list in a different class.

class Program
{
static void Main(string[] args)
{
List<string> myList = new List<string>();
myList = Result.fromDifferentClass;
Console.WriteLine("Result: " + Result.fromDifferentClass.Count); // prints 3
Console.WriteLine("myList: " + myList.Count); // prints 3
Result.fromDifferentClass.Clear();
Console.WriteLine("Result: " + Result.fromDifferentClass.Count); // prints 0
Console.WriteLine("myList: " + myList.Count); // prints 0

}
}

in Program class, I made myList to refer fromDifferentClass.
And I cleared fromDifferentClass list.
so I understand myList also is cleared.
However, is there any way I can still keep the content of myList even after fromDifferentClass list is cleared();
So the currently the result is
3
3
0
0
But I want it to be
3
3
0
3
0
I am exporting a List to Excel.  I need to loop thru the array to show additional information.

Here is what I have in my class:

using master.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace master.Areas.Test.Models
{
/// <summary>
/// Exports passed in network
/// </summary>
public class Export
{
/// <summary>
/// Exports a excel file
/// </summary>

public static StringWriter exportToExcel()
{
MyDB mDB = new MyDB();

List<vw_Details> reportData = new List<vw_Details>();

reportData = (from x in mDB.vw_Details
select x).ToList();

System.Data.DataTable Export = new System.Data.DataTable("Export");

foreach (vw_Details data in reportData)
{
data.id,
data.requestId,
data.details

);

}

GridView grid = new GridView();
grid.DataSource = Export;
grid.DataBind();

…
0
The business I work for uses MS Exchange and Outlook for the mail and calendar systems.
Up until now access to individual employees' calendars by colleagues has been at the employee's discretion.
To make it easier to organise meetings we have recently taken a decision to have an "Open Calendar" policy across the group.
This means that we will automatically set all the calendars to have open access from within our company.

The problem however is that once open the calendars can be browsed into the past and many people have appointments in their calendars that should not be open to the public.

So, I am looking for a way to set all appointments prior to Jan 1st 2019 to "private".
We have in-house c# skills  and I was wondering if it is possible to write something that could be run against a calendar setting all appointments to private. Presumably we would have to target the Exchange server directly to do this. But we have no experience in doing this so I was hoping for guidance from someone.

Thanks
0
Hi this is a follow on from here  and other questions relating to parsing XML with C#

I'm trying to add a new season to the xml

My CheckSeason fails where no season exists eg for "A Discovery Of Witches"  but returns true or false for any MacGyver season

I'm assuming it's because the parent "season" has to exist before you can check for season number?
I don't understand why this causes an "unhandled exception " and not just return null

AddSeason i've tried to amend from previous question  but i'm missing something

Logic
Add new season in numerical  SeasonNumber order

       public static XDocument xdoc = XDocument.Load(@"J:\Media\TV\TV.xml");
// Load the XML Document using Linq to XML

if (CheckSeason("A Discovery Of Witches", "S01", "77236"))  // fails
//    if (CheckSeason("MacGyver 2016", "S02", "67133"))        // works
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Does Not Exists");
AddSeason("A Discovery Of Witches", "S01", "77236");
}

private static void AddSeason(string showname, string season, string TMDBid)
{
char[] array1 = { 's', 'S', '0'

0
I'm using HtmlAgilityPack to Travers some  HTML   VidsTest.html

In the code bellow I cannot get to the second video block with  <div class='post_title'>Title 2 The Wombles
Even though  the ID of "user_post_2712102" is being set Title and other variables remain at Title 1 Doctor Who

    HtmlAgilityPack.HtmlDocument HTMLdoc = new HtmlAgilityPack.HtmlDocument();
var user_postDiv = HTMLdoc.DocumentNode.SelectNodes("//div[contains(@class,'user_post_')]");
string id = "";
string Title = "";
string VidSrc = "";
string Poster = "";
string postDate = "";
foreach (var divNodes in user_postDiv)
{
id = divNodes.GetAttributeValue("item_id", "").ToString();
if (id != "")
{
Console.WriteLine("id = user_post_" + id);

//    postDate = divNodes.SelectSingleNode("//span[@class='local - time']").InnerHtml;
// can't find postDate
Title = divNodes.SelectSingleNode("//div[@class='post_title']").InnerText;

VidSrc = divNodes.SelectSingleNode("//video/source").Attributes["src"].Value;
Poster = divNodes.SelectSingleNode("//video").Attributes["poster"].Value;
Console.WriteLine("Title end div in divs {0} , {1} , {2} " + Title + Poster + VidSrc);


0
Hi

I have a form something like the image bellow

I wish to add buttons to my form representing sub folders

first I don't how many sub folders buttons there are

How do I position them in a row under the text box up to 5 with adding a new row if required?

The code  is untested but shows what  I'm trying to do

        private void AddButtons()
{
string FolderPath = RootDir + FolderTextBox.Text;
if (Directory.Exists(FolderPath))
{
string[] folders = Directory.GetDirectories(FolderPath, "*", SearchOption.TopDirectoryOnly);

foreach (string folder in folders)
{

FileInfo FI = new FileInfo(folder);
//string folderPath =
string ButtonName = FI.Name + "Btn";
Button Button = new Button();  // can't call this ButtonName??
Button.Name = ButtonName;
Button.Text = FI.Name;
// The event 'Control.Click' can only appear on the left hand side of += or -=

}
}
}

{
// add code to populate  listview
// is this the correct way?
}

0
I'm using DocumentFormat.OpenXml to create spreadsheet like this.
How do I make cells that are in format dd/mm/yyyy date formatted, so the text is aligned to the right of the cell.
How do I make text in particular cells bold?
How do I implement a custom format for a cell 0"D" where 0 represents a number (D is the number of days)

using (SpreadsheetDocument document =
{
workbookPart.Workbook = new Workbook();

var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);

Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet()
{Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1"};

sheets.Append(sheet);

//List<String> columns = new List<string>();
foreach (DataRow dr in Cols.Rows)
{
Cell cell = new

0
Using XML Linq  how do I add a new  TV show to the attached XML TV.xml preferable so the show.names are in alphabetical order?

From MyForm I call Thus

xmlFuncs.AddShowName(ShowName, FolderName, TMDBid, Xdoc);

or

xmlFuncs.AddShowName("Charmed", "Charmed 2018" "79611", Xdoc);


this creates
NewShow = {<Show>
<Name>Charmed</Name>
<FolderName>Charmed 2018</FolderName>
<TMDBid>79611</TMDBid>
</Show>}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace TVDB
{
class XMLFuncs
{
public XDocument Xdoc;

{
if (File.Exists(XMLpath))
{
return Xdoc;

}
else
{
return null;
}
}
public string ChecKShowName(string FolderName, XDocument Xdoc)
{

// // Checks for the existence of a Show and return it's TMDB ID
var results = (from node in Xdoc.Descendants("Show")
where node.Element("FolderName").Value == FolderName
select node.Element("TMDBid").Value).FirstOrDefault();
if (results != null)
{
return results;
}
else


0
I have an MVC C# Web application. I need a way to check a cookie name ="User_Role", if it = "UR500" then hide a menu object which is included in the layout.cshtml. Where would I place this script?
1

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