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

What does this exception mean? How do I solve this?

INNEREXCEPTION MESSAGE: Invalid viewstate. Client IP: Port: 56646 Referer: https://secure.mdg.com/Search.aspx?search=Ac&PID=mdgusahomepage Path: /Search.aspx User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) CriOS/66.0.3359.122 Mobile/14F89 Safari/602.1 ViewState: a6wfE98MT+TF/7wW7Zt5MoBNMnJfad7AV40clKhJuz6DehSdGCuvBYZyrf/zQqehi/4ymU/c1U4Bh2DtbHZ2TkClD0Y2KlvIE0zdXdD5QEFk5FFTjRBvoWHCHfUdEXTUUW1lbAPjh3bmcM58WFaN2eX4Q8G9uEEW9GWoYTH2q6Mc4+6AVlt8iGxy3cgoferBffC57h+MmvcMhlHLWoEu8XmwPjvU7kvIJVkswMZsRnXJ1tGxvOZ9hWuGEuQtZfWuI7P8SSaClZadgBwlJmjyVWh+4weNBkzB9edWB35Os9b04qttFFA1ff/ciVkjTD7PRGLcSH339XXWUfsWuMg4rwa9rHegwVkByNfxVf7qthYOGYTKklKRSgHfPMFxQAzP/xtRRbYS1jqLSw7dPkkC8XJSCsCVXYIKrKK+8xlaw3YRFWA6bXxAVVnxIefsCPEIiA74otzaTVdHRlIFrobr1voc/BZUmAAAMLmr919LLcbQvNuS40Qb7Sabq9pcddrwrrL9txLtuuRCMQXWQWKt6HAJ5nV5Q8i+gGzaymyRfPvJLyAtSjEtH0ppI6EyKVQhx0zOPP0RV60GiMEPPm5q8fa4TkV+xFM11Tagw63ThUFOyKBAqXYmNdxFjB9on22SrPC5WHtX93D8ZbMJhOUNAQejWohxrR5Gt7/nlBR0U9Wb/PgppCI+D1nFv3Q7HMBevxeNPfvf...
EXCEPTION TARGETSITE: Void ThrowError(System.Exception, System.String, System.String, Boolean)
EXCEPTION GETTYPE: System.Web.HttpException
EXCEPTION STACKTRACE: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at …
Cloud Class® Course: Microsoft Azure 2017
LVL 12
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Hi Experts!

I'm still trying to learn C# , though now I seam to be comfortable with Code, excepts the listed issues below:

(1) How do I create a parent form and a child for purpose of creating an invoice?
(2) Is it possible to nominate a form to become a start up form so that people are able to enter their credentials before accessing the package?

For menus I think that is Okay C# has a better way of creating menus and links, on this one I will try it.


I want to find the permutations of n lists or array.

I can pass in A {1,2,3,4,5} and B {1,2,3,4,5}
I can pass in A {1,2,3,4,5} and B {1,2,3,4,5} C {1,2,3,4,5}

I want to know the permutation of whatever is passed in a method.  Also, how do I pass in to a method?  Create a dictionary?

The results (for first example) would be 1:1, 1:2, 1:3, etc....
The results (for second example) would be 1:1:1, 1:1:2, 1:1:3, etc....

Attaching an entity of type failed

I am an error while editing information, below is full error and code snippet. Can someone help to fix this issue

Error Details
 Attaching an entity of type 'HRPhoenix.Models.SLA' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Code Snippet

var inDb = db.SLAs.Where(x => x.Id == sLA.Id).FirstOrDefault();

                if (inDb == null)
                    ViewBag.UserMsg = "Bad request";
                    return View(sLA);

                //check if SLA name already Exist or not
                var isNewSLAExist = db.SLAs.Where(x => x.SLACode == sLA.SLACode && x.Id != sLA.Id).FirstOrDefault();
                if(isNewSLAExist != null)
                    ViewBag.UserMsg = "SLA code already exist";
                    return View(sLA);

                //set value from database
                sLA.CompanyId = inDb.CompanyId;

Open in new window

the code is from a microsoft tutorial called wingtip toys in asp.net, that code creates a user everytime the user clicks the button what i want is to when someone clicks on the button the program doesnt create the user, only creats if the user confirms his email. thanks

protected void CreateUser_Click(object sender, EventArgs e)
        var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
        var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
        IdentityResult result = manager.Create(user, Password.Text);
        if (result.Succeeded)
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
            //string code = manager.GenerateEmailConfirmationToken(user.Id);
            //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
            //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

            signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);

            using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
                String cartId = …
I had this question after viewing c# PowerShell runspace woes.

Could you please suggest How we can connect to PowerCLI or PowerShell to execute "PowerCLI C:\> Connect-VIServer -Server -User XXXXXX -Password XXXXX"   this command
Because every time I call the .ps1 from c# I got the error as ConnectVIServer is not valid command. My Code is

 string scripttest = "function Test-Me($param1, $param2, $param3) {Connect-VIServer -Server $param1 -User $param2 -Password $param3}";

            using (var powershell = PowerShell.Create())
                powershell.AddScript(scripttest, false);



                powershell.AddCommand("Test-Me").AddParameter("param1", "").AddParameter("param2", "xxxxxx").AddParameter("param3", "xxxxx");

                //var results = powershell.Invoke();

                Collection<PSObject> results;
                Collection<ErrorRecord> errors;
                results = powershell.Invoke();
                errors = powershell.Streams.Error.ReadAll();
                if (errors.Count > 0)
                    foreach (ErrorRecord error in errors)
                        System.IO.File.WriteAllText(@"C:\test.txt", …
Hi ,
Need quick help. Have 2 object lists in C#

list<obj1> a = new list<obj1>(); list<obj2> b = new list<obj2>();
a[0]="test1"     b[0]="hi"
a[1]="test2"     b[1]="hello"
a[2]= "test"      b[2]= "test1"
                          b[3]= "test"

want to remove object in "a list" only if respective obj matched from b list.

kind regards,
How to remove item from ienumerable<obj> using C#

Kind regards,
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.
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)


@model DLTWeb.Models.SearchModel

    ViewBag.Title = "Index";    

    <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" />

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

<br />

        <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>        
        <td>Fields Name</td>
            <select id="ddlFields" name="ddlFields">
                <option>---Select Fields---</option>
Cloud Class® Course: Certified Penetration Testing
LVL 12
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

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.



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

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!

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.
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)
                            bool messageSent = getSmtpClientAndSendMessage(companyID, msg);
                        catch (Exception ex)
                            WriteErrorsToLogAndScreen(ex, "exception on lock: getSmtpClientAndSendMessage");


Open in new window

if it is, what can i do to eliminate a deadlock?
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)

Open in new window

In my MVC app I have a JsonResult

public JsonResult AddNewRegionofInterest(string _roi_data)

Open in new window

the roi_data is

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?
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;
                    secondcheck = true;


Open in new window

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

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 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,
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;

                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

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
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:


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 = …
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. "


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.






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