C#

91K

Solutions

32

Articles & Videos

24K

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

Is it possible to detect, programmatically (using C#), or through a utility or windows service, that Windows 10 is about to reboot (unscheduled)?

I am not necessarily talking about a reboot after Windows Update has installed an update, so for the purposes of this question assume that a legitimate system reboot is not a factor in this.  Just assume that Windows 10 is rebooting at random unannounced times.

I am interested in gathering as detailed information as I can about the last events that are happening **just before** my mouse pointer locks and the laptop reboots.

Related to this question - are there utilities that will absolutely prevent Windows10 from rebooting at random times WITHOUT some sort of permission from the end-user?  That way if I have some sort of warning or reboot prevention I can shutdown my running applications and save my work.

I am not concerned that my laptop wants to reboot.  It may have legitimate reasons to do so.  I just don't want it to be able to reboot (legitimate or otherwise) without checking with me first and letting me click "Yes" or "No". I want to impose this on top of the Windows 10 OS --  so that if it is possible to detect it I want to prevent it and have it alert me.
0
Free Tool: Subnet Calculator
LVL 9
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

i make a desktop application..and i faced problem in receiving an email on a form.i face this error when load the email:
error:
Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
please help............it's urgent
0
I am getting a FileStream Read and Write Timeout error when I try to upload a file. The code is below. Any idea what I have wrong?

        [HttpPost]
        public async Task<IActionResult> Index(ICollection<IFormFile> files)
        {
            var uploads = Path.Combine(_environment.WebRootPath, "uploads");
            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
            }
            return View();
        }
0
We are updating our website and now have two set of members.  One set of those who have registered and one set of those historical members who have yet to re-register.  I am looking for the ability to merge(union) those two tables for a search functionality however I am struggling with the union.

In SQL
select  member_id, ssn
from member a 
union 
select  member_id, ssn
from member_historical

Open in new window


LINQ
     var union = (from members in db.members
                    select new
                    {
                        members.member_id,
                        members.ssn
                    }
                ).Union
                    (from member_historical in db.member_historical
                     select new
                    {
                        member_id = member_historical.member_id,
                        ssn = member_historical.ssn
                    }
                );

Open in new window


When I return view(union) an error:  Argument type 'system.linq.Iquerable<member_id;int ssn:string}>' is not assignable to model type of 'system.collections.generic.IEnumberable<Data.member>'



Tried to cast:  return View((IEnumerable<member>) union);


I'm a  little lost, any help or guidance is appreciated.
0
Hi,
Using these codes (in the project),
        private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
        {
            Worksheet worksheet = worksheetPart.Worksheet;
            SheetData sheetData = worksheet.GetFirstChild<SheetData>();
            string cellReference = columnName + rowIndex;
            Row row;
            if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
            {
                row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
            }
            else
            {
                row = new Row() { RowIndex = rowIndex };
                sheetData.Append(row);
            }
            if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
            {
                return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
            }
            else
            {
                Cell refCell = null;
                foreach (Cell cell in row.Elements<Cell>())
                {
                    if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
                    {
                        refCell = cell;
                        break;
                    }
                }
                Cell newCell = new Cell() { CellReference = cellReference };
                row.InsertBefore(newCell, refCell);
                

Open in new window

0
Hello Experts,

I'm having trouble retrieving/displaying the City value from the database to the City drop down list based on the selected Customer's ID that I wish to Edit.

When I select a Customer to Edit it populates the data from the database properly except for the City drop down list. The City drop down list will show "Select a City" along with all Cities that are related to the State in the State drop down list.

If I select another state then it loads all cities for the selected state properly.

The problem is that it does not show the City value for the City drop down list like it should when I first load the page.

Edit View:
@model WebAppCascadeDropDown.ViewModels.CustomerFormVM

@{
    ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Edit", "Customer"))
{
    <div class="form-group">
        @Html.LabelFor(c => c.FirstName)
        @Html.TextBoxFor(c => c.FirstName, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(c => c.LastName)
        @Html.TextBoxFor(c => c.LastName, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(s => s.StateId)
        @Html.DropDownListFor(s => s.StateId, new SelectList(Model.States, "StateId", "StateAbbr"), "", new { @class = "form-control" })
        @Html.ValidationMessageFor(s => s.StateId)
    </div>

    <div class="form-group">
        @Html.Hidden("hCityId", (object)ViewBag.CityId)
        

Open in new window

0
I am trying to create a Json object in C# that I will convert to XML.   I have a repeating set of Fees that I need to add to the json object.

Here is my code so far:

root.Deal.Fees = new ExpandoObject();
List<ExpandoObject> feeArray = new List<ExpandoObject>();

foreach (DataRow ro in ds.Tables["fees"].Rows)
{
    root.Deal.Fees.DealFees.Fee.Description = ro["fee_type"].ToString();;
    root.Deal.Fees.DealFees.Fee.Amount = ro["amount"].ToString();

feeArray.Add(root.Deal.Fees);
}

Open in new window


No sure what else is needed.   Supply a different example if that is easier for you.
Thank you
0
Hello Experts!

I have a website that uses microsoft.aspnet.Identity for Logging in.  I have a companion windows program that I'd like to be able to create users and make adjustments to the settings of the website.  

Is it possible to Microsoft.aspnet.Identity to create users in a Windows Program or is that only for Web only?
Would anyone have example code?

thanks!
0
I am trying to tie my C# code to one of my SQL databases and am having a bit of difficulty. Ultimately, what I need to do is have the program constantly "listen" to the database for different machine statuses, and if the status changes, I have a script that will turn on a USB LED fob.

I've attached a sample of the table I'm looking to poll. Pretty much, I need to have it set that if "Machine 1" Changes it's status from "RUN" as shown to "OFF," I need it to return a response that ties into my current code, which has three different color statuses for the USB LED fob, which is attached to a stack light. I've also attached a copy of my current code for the fob to show what actions will occur once this trigger is made.

Sorry for being vague, but I am going into this blind, and am just learning how to code. Any assistance is greatly appreciated.
sample.csv
code-sample.txt
0
I have a requirement to develop a solution to enable the administrator to set edit permissions on Ms Word based on the user logged on.

The solution will be hosted by SharePoint 2013 using Office Co authoring. The document must be edited by many users at the same time and each user must only edit the section the admins have configured the user to edit.

Does anyone have any idea how to allow the administrator to set the permissions? Then dynamically disable/enable controls based on template name and user logon on MS Word 2016 using JavaScript API for Word.

The client does not want to use the option available out of the box to restrict edit using passwords because it is easy to crack the password.

http://www.c-sharpcorner.com/UploadFile/8ea152/set-and-remove-editing-restrictions-in-word-2013-documents/

I have looked at the link below but my problem is to disable/enable the controls dynamically without hard cording the controls or users.

https://xomino.com/2017/03/29/office-add-ins-javascript-control-over-the-content-control-lock-in-a-word-document/
0
Instantly Create Instructional Tutorials
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

I am new to entity framework, Whilst i love it, there are still some things i cant figure out. I have good experience with SQL and in SQL this is a easy task.

I have attached a copy of the db tables and their relationships. Hopefully someone can help.

I need to see all items in the orderitems table which have a corresponding statusid of 100 in the orders table.
from that list i then need to see all items in the orderitems table grouped by the store in which they belong.

Any help is appreciated :)
Model.PNG
0
how to add images in panel, and do some operations like crop, select image, rotate, etc in c# windows application.
0
I have an array:
public static readonly string[] OrderStatuses =
       {"Order Placed", // 0
        "Check funds", // 1
        "Waiting for Order Approval", // 2
        "Waiting to Print Label", // 3
        "Waiting to Print Packing Slip", //4
        "Waiting to Charge Credit Card", //5
        "Waiting to Send email", // 6
        "Waiting Completed", // 7
        "Order Completed" }; // 8


The code for the dataGrid I want to take the status value and change in the gridview to the string of orderstatus. So if the status is 0 show Order Placed instead on 0

            Report = commercelLibAccess.GetOrdersByRecent(Count);
            DataSet Output = new DataSet();
            Grid.AutoGenerateColumns = false;

            Grid.ColumnCount = 5;

            Grid.Columns[0].Name = "OrderId";
            Grid.Columns[0].HeaderText = "Order Id";
            Grid.Columns[0].DataPropertyName = "OrderId";

            Grid.Columns[1].Name = "DateCreated";
            Grid.Columns[1].HeaderText = "Date Created";
            Grid.Columns[1].DataPropertyName = "DateCreated";

            Grid.Columns[2].Name = "DateShipped";
            Grid.Columns[2].HeaderText = "Date Shipped/ Pickup";
            Grid.Columns[2].DataPropertyName = "DateShipped";

            Grid.Columns[3].Name = "Status";
            Grid.Columns[3].HeaderText = "Status";
            Grid.Columns[3].DataPropertyName = "Status";
           

            …
0
Si,

I've added a quartz timer to my web app and let it run in Application_start (global.asax).

The idea is that the timer sends mails once a day.

Problem now is that application_start is not always active (application pool restarts, no activity).
The website is on a shared hosting platform (IIS). So my options are limited.

Does anyone have an idea how to keep the ASP.NET web app alive so the timer is Always running and the mails are being send?

Thanks!

Kind regards,
Gery
0
I need to access the registry in my .NET program I am writing and need to know if I reference this registry entry:

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Jet\4.0\Engines\Text

it will not break if the code is running on a 32 bit system.
0
I have been tasked to build an online audit questionnaire/survey. I am fairly new to asp.net. I want to create the questions and server controls dynamically with data from sql server. For each questions I will need to dynamically create two  (Yes/No) radio buttons. Any help would be greatly appreciated. I am using asp.net forms.
0
Hi there
I have a WebGrid that I am populating with columns via the controller since I need the columns to change based on certain user selections. One of the columns is a checkbox and it should show as checked if the value I pass it is true, unchecked if false and disabled if null. At the moment I'm battling to create a condition that checks and unchecks the correct values. It is currently checking all or none.

Any assistance will be appreciated. Thanks in advance.

--My Grid
@grid.GetHtml(tableStyle: "table",
                      alternatingRowStyle: "alternate",
                      selectedRowStyle: "selected",
                      headerStyle: "header",
                      columns: ViewBag.Columns
                     )

--populated from controller. Status is my bool field
List<WebGridColumn> columns = new List<WebGridColumn>();
columns.Add(new WebGridColumn() { Format = (item) => { return new HtmlString(string.Format("<input id = '{0}' name = '{0}' class='box' type = 'checkbox' {1} == 'true' ? checked : '' value ='{1}') />", item.Id, item.Status)); } });
ViewBag.Columns = columns;
0
I need a query using which i can hide the details of Products not selected while shopping..for eg suppose we have 5 products option to buy and we choose only 2 out of 5, is there any sql-query or method(Repeaters,data list..etc) using which we can hide the item details not selected..using asp.net c#
0
I am using lotus notes to send email in .net application using c#. I am able to send mails from this application while i run this in my local host. But the thing is when host the application in local IIS server i am not able to send mails.
 I am getting the following error.
Notes error: Notes shared login failed with this ID file.
Please tell me why i am getting this error after hosting the application.
0
Free Tool: IP Lookup
LVL 9
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

I want to add categories but I have this error
Here Is the source code
Line 70:                                            <asp:DataList ID ="dd" runat="server">
Line 71:                                             <ItemTemplate>
Line 72:                                                 <li><a href="#Events.aspx?type=<%#Eval("EventTypeName") %>"><%#Eval("EventTypeName") %></a></li>
Line 73:                                                </ItemTemplate>  
Line 74:                                             </asp:DataList>    

Open in new window

Code behind
 
con.Open();
        SqlCommand cmd = con.CreateCommand();

        if (Request.QueryString["type"] == null)
        {
            cmd.CommandText = "SELECT * FROM EventDetail";
        }
        else
        {
            cmd.CommandText = "SELECT * FROM EventDetail WHERE EventType_ID= '" + Request.QueryString["type"].ToString() + "' ";
        }

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dd.DataSource = dt;
        dd.DataBind();
        con.Close();

Open in new window


I have 2 tables
1. Event Type ( EventType_ID, EventTypeName )
2. EventDetail (EventDetail_ID, EventType_ID, eventDetailName....)
0
Can anyone recommend a .Net Kafka library?


thanks,

Rick
0
My C# application is showing ominous behaviour.

The application is working perfectly fine for a specific Installation. But it's giving me this exception in another..
- SqlDataAdapter.Fill - Timeout expired.  The timeout period elapsed Prior to executing the query or the Server is not responding.

I've been searching all day for a solution and cant find anything helpful.

The c# Code is

            DataTable dt = new DataTable(tableName);
            try
            {
                using (SqlDataAdapter da = new SqlDataAdapter(SqlQuery, conn))
                {
                    Console.Write(SqlQuery);
                    da.Fill(dt);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Foo String there is nothing good Happening {0}", ex.ToString()));
            }

Open in new window


The SQL is : SELECT * FROM FooTable WHERE ColumnA=0 and ColumnB='15'

Every Google post I've been looking at is about "increase your command timeout". Which makes me almost give up hope.

The same SQL in SSMS Returns only 1 row and I've seriously no idea what is going on.

I've attached a Debugger to the process and can definitely say the code is reaching the Console.Write as a breakpoint.
The exception is thrown at the fill method line.

I'm highly thankful for any responses.
0
How can I validate address using API  in C# or any batch process?
0
I'm new to Entity Framework and looking to move future development of an existing application in that direction.  Previously the development has been 'traditional' with VB, Winforms and SQL DataAdapters.  Looking forward, I'll be moving to C# with EF6 (or EF Core).  I'm currently working out how best to do this.  

To minimise impact on end users, I need the new forms I develop to work the same way as they always have.  In the past, for a data object neededing validation, I would handle the .validating event of the Control to which the data was bound and, if validation failed, display a messagebox to the user, set e.cancel=True and get them to try again.

That way, the validation code is in the Client Side  (the view).  In future I want it on the Object Model so that I can use the same validation for potential future development on other platforms (e.g web access).

I've read a lot about this and it doesn't seem to be the way validation works on EF.  Here's where I am.

I have a 'Schedule' data object in EF that has a field / property for Interval_Mins, which is an Integer value representing Minutes.  I want to ensure this value is between 1 and 59 (for example).

I know about the Range DataAnnotation but I want to do this in code in case I require some validation more complex that DataAnnotation allows (also I'm new to DataAnnotation so not clear on it's limitations - let me know if that's the better approach).

So, in my partial class for my 'Schedule' object I …
0
After clicking the type, it still shows all the items!
source code
   <asp:DataList ID ="dd" runat="server">
                                                <ItemTemplate>
                                                <li><a href="#Events.aspx?type=<%#Eval("EventTypeName") %>"><%#Eval("EventTypeName") %></a></li>
                                               </ItemTemplate>
                                            </asp:DataList>

code behind
 con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;

        if (Request.QueryString["type"] == null)
        {
            cmd.CommandText = "select * from EventDetail";
        }
        else
        {
            cmd.CommandText = "select * from EventDetail where EventTypeID= '"+ Request.QueryString["type"].ToString()  + "' ";
        }

        cmd.CommandText = "select * from EventType";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        dd.DataSource = dt;
        dd.DataBind();
        con.Close();

my two tables
1. EventDetail (EventDetail_ID, EventTypeID, eventDetailName, eventDate......)
2. EventType (EventType_ID, EventTypeName)
0

C#

91K

Solutions

32

Articles & Videos

24K

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