Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

C# Subracting Inputted Textbox Value to the Label value

$
0
0
I'm building these POS Desktop application in Windows form and it's almost done but i'm having problem in processing the customer bills.

To be specific:  
SIMSProduct Usercontrol  

 - cart.lbl_price.Text = lbl_totalprice.Text;  
First the total of the customer bought is in lbl_totalprice.Text  
Next that total is used to ProcessCart Form which is the cart.lbl_price.Text
 - lbl_price.Text is now successfully getting the value of lbl_totalprice.Text

ProcessCart Form

 - txt_amount(Textbox) is where user input the pay value of customer that should be subracted to the lbl_price.Text which is fail.
 - lbl_totalprice.Text corresponds to the output of subracted lbl_price and txt_amount which is fail too


Note: lbl corresponds to Windows form Label

The problem is when i tried to input to my txt_amount, let's say i input 5000 and that 5000 is not subracting the value of lbl_price, also the lbl_totalprice is equal to what i type to txt_amount. Below these code, What I've done wrong here ?, something that i should not made? or i forgot something ?. I hope someone would be able to help in these matter. Thank you
public partial class SIMSProduct : UserControl
    {
        ITEMCount item;
        ProcessCart cart;
        public SIMSProduct()
        {
            InitializeComponent();         
        }
     private void btn_process_Click(object sender, EventArgs e)
        {
            cart = new ProcessCart();
            cart.Show();
            cart.lbl_price.Text = lbl_totalprice.Text; 
        }
    }

    public partial class ProcessCart : Form
    {     
        public ProcessCart()
        {
            InitializeComponent();
        }
     private void txt_amount_TextChanged(object sender, EventArgs e)
        {
            decimal value1;
            decimal value2;
            decimal value3;
            if (decimal.TryParse(lbl_price.Text.Trim(), out value1))
            {
                Total = Convert.ToInt32(lbl_price.Text);            
            }
            if (decimal.TryParse(txt_amount.Text.Trim(), out value2))
            {

                Paid = Convert.ToDecimal(txt_amount.Text);          
            }
            if (decimal.TryParse(lbl_totalprice.Text.Trim(), out value3))
            {
                Change = Convert.ToDecimal(lbl_totalprice.Text);
            }
            Change = Paid - Total;

        }
    }


when page is scrolled drop down is moved, detaching from combobox

$
0
0

In visual studio 2015,when page is scrolled drop down is moved, detaching from combobox. Open drop down on bottom left combobox. Use mouse wheel to scroll the page down. Drop drop down is moving down with page.As shown in this attached image.Please give the solution for the following issue.

Saving a triangle in an object list and draw another one

$
0
0
I am trying to save the triangle I drew and draw again while the previous triangle is still there. I did this in rectangle, square, circle and ellipse and it worked. I don't know why it won't in Triangle. IS there something wrong in the code?

>This is how I draw and "save (not working)"

**Shape Class**    


        public void DrawTriangle(Color c, int stroke,PointF[] tpoints, float w, Graphics g)
        {
            this.width = w;
            this.strokeThickness = stroke;
            this.tPoints = tpoints;
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.DrawPolygon(new Pen(c, stroke), tpoints);
        }
**Form 1**  

        public void DrawTriangle()
        {
            tC = Color.Red;
            strokeTriangle = trackBar_Stroke.Value;
            tW = Convert.ToInt32((Convert.ToInt32(tbox_Width.Text) * 96) / 25.4);
            tH = (Convert.ToInt32((tW * (Math.Sqrt(3))) / 2));
            tX = (pictureBox_Canvass.Width - tW) / 2;
            tY = ((pictureBox_Canvass.Width - (tH)) / 2) + tH;

            float angle = 0;
            t_Points[0].X = tX;
            t_Points[0].Y = tY;
            t_Points[1].X = (float)(tX + tW * Math.Cos(angle));
            t_Points[1].Y = (float)(tY + tW * Math.Sin(angle));
            t_Points[2].X = (float)(tX + tW * Math.Cos(angle - Math.PI / 3));
            t_Points[2].Y = (float)(tY + tW * Math.Sin(angle - Math.PI / 3));
        }
        public void AcceptTriangle()
        {
            Shape shape = new Shape();
            tC = Color.Gray;
            shape.strokeThickness = strokeTriangle;
            shape.width = tW;
            shape.x = tX;
            shape.y = tY;
            shape.tPoints = t_Points;
            s._triangle.Add(shape);
        }
    s.DrawTriangle(tC, strokeTriangle,t_Points, tX, tY, tW, e.Graphics);
>This is how I iterate it.


    public List<Shape> _triangle = new List<Shape>();
    foreach(Shape shapes3 in s._triangle)
            {
                shapes3.DrawTriangle(shapes3.color, shapes3.strokeThickness, shapes3.tPoints, shapes3.width, e.Graphics);
            }

IMAGE REPETITION IN RDLC

$
0
0

i have a idcard image.

i am selecting data from datagridview and try to print selected data over the image.

the issue is how to repeat image according to selected data

if i select single data from grid then set single image as a background and set selected data over the image but i select multiple data from grid and print image will repeat multiple times and set selected data over the image.

and 1 page contains only 5 card image then page will break and create new page and set next data to new page.

how can i do this?

[UWP] How do I get a ListView with active sorting and filtering

$
0
0

I need a view into an ObservableCollection that permits sorting and filtering in a dynamic/live way.What I see is simple filtering and sorting where a LINQ query is re-run and a new collection is created and displayed. This is not what I want. I want the view to react to any changes in the underlying ObservableCollection, or changes to the sort or filter.

- As items are added, removed or updated in the underlying ObservableCollection, the view is dynamically updated according to whatever filter and sort are currently set. I.e as items are added or removed from the ObservableCollection they are correspondingly added or removed form the view as appropriate to the filter and sort selected.

- If the filter is changed, items are added or removed from the view to bring it in compliance ... NOT a wholesale replacement of the collection.

- If the sort is changed, items are moved to their new position … NOT a wholesale replacement of the collection.

- When the view changes for any reason, either because the underlying ObservableCollection changes, or the sort or filter changes, then any ListView that is displaying the view keeps the current item selected if it still exists, or keeps the scroll position relative to whatever the originally selected it's closest neighbor would have been if it still existed in the view.

Is there a solution for this?

How to use NetFwTypeLib in .NET core 2.1

$
0
0

Hello:

I had a C# project using C# Version 7.3; and I setup a firewall rule using PowerShell with a name like "My_Firewall_Rule".

I added Reference to Interop.NetFwTypeLib.dll, and the following code works:

using NetFwTypeLib;

bool firewall_rule_found = false;
var firewallRule = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
foreach (INetFwRule rule in firewallRule.Rules)
{
    if (rule.Name == My_Firewall_Rule)
    {
    firewall_rule_found = true;
    Console.WriteLine("My Firewall Rule is in place!");
    }
}

However, in order to use .NET core for further development, I have to migrate my project to .NET Core 2.1 or later to .NET Core 2.2.

But the same code simply stop working.  I got error message:

System.IO.FileNotFoundException
  HResult=0x80070002
  Message=Could not load file or assembly 'Interop.NetFwTypeLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. 
System can't find the file.

But from Visual Studio 2017, in Solution Explorer, I can see the file is there, with the path: obj\Debug\netcoreapp2.1\Interop.NetFwTypeLib.dll

with identity: Interop.NetFwTypeLib

But the version information is empty.

Please advice how to fix this issue?  Or is there any nuget package I can use in .NET Core, I don't like to still use the old Interop COM package.

Thanks,

css issue in string builder

$
0
0
i am creating string builder table and apply css on it.i set table background image like this
sb.Append("<table style = 'background-image:url(C:\\Users\\Archit\\Downloads\\itbp.jpg)>")
but when i print to this table on pdf, background image not display and some columns height also not set.
 
any idea how to set table background image which shown on pdf.
and how to set column height manually? 

Is there any way to convert PSObject to string in C# while working with Powershell Api

$
0
0

I need to convert PSObject to String(). Is there any standard way available to do this task? Somehow powershell also does ToString() or spits out a readable stream on ISE console. I used PSSerializer.Serialize(PSObject) but it serializes everything. I want in my application seemlessly everything shown in a way the way Powershell does.

Is there anyway to convert PSObject to a.readable string. At the moment when I use following line of code

PSObject.ToString()

or

PSObject.BaseObject.ToString()

both just print out complete type name. ( e.g. "System.Collection.HashTable" ) But I want complete displayed contents in C# to see the way powershell exposes.




Merge multiple rows using C#

$
0
0

Hi,

I have a csv file with data as follows:

id C1 C2 C3 C4
R1 12   
R1  13  
R1   14 
R1    15
R2  13  
R3 12   
R4   13 
R2 12   15

I would like the data to be merged based on the 'id' in column 1 so that the output is as follows :

idC1C2C3C4
R112131415
R2121315
R312
R413

How to Open a .file extension file and read data into dataset in C#

$
0
0

I have a file with extension "File". The data in it is row column format with space. I wanted this file open in excel and bulk insert in Sql Server records. I am facing "External table is not in the expected format." because may be the file is in File type.

I wanted to this file to load data and bulk insert in sql.Need script.

Thanks in Advance.

Mahesh

Using Signal R with dotnet core and IIS

$
0
0

Hi everyone,

I've been learning the signal r library for dotnet core, I've set up a basic app for testing it before we use it in one of our applications, and I used following tutorial:

docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio

I have the following Startup.cs file:

namespace SignalRChat
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("/chatHub");
            });

            app.UseMvc();
        }
    }
}

And my ChatHub.cs file is as shown below:

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Now this runs fine in visual studio, but when I publish this to IIS we get a 503 error.

Does anyone know if there are any settings that you need to add to get it to work in IIS?

Thanks in advance.

Calling a web service, trying to pass JSON but getting a 403 error

$
0
0

Hi 

I am trying to use the HttpClient class but getting a 403 error.

My code lokks like this

********

private async static Task post(stepPayload payload, string logicalStatus, DateTime? dt, string databaseRef)
        {
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                // 
                WebRequestHandler handler = new WebRequestHandler()
                {
                    CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
                };
                using (HttpClient client = new HttpClient(handler))
                {
                    string stringPayload = JsonConvert.SerializeObject(payload);
                    System.Net.Http.HttpContent httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
                    string stepURL = config.AppSettings.Settings["stepTest"].Value;
                    var httpResponse = await client.PostAsync(stepURL, httpContent);
                    if (httpResponse.Content != null)
                    {
                        var responseContent = await httpResponse.Content.ReadAsStringAsync();
     ....

***************

As per the line 

string stringPayload = JsonConvert.SerializeObject(payload);

string payload has the value 

{\"case_id\":\"FS-Case-75363670\",\"stage_name\":\"Back Office\",\"data\":{\"Outcome\":\"CO\",\"SiteResponseDateTime\":\"2018-09-13T11:12:25.1134296+01:00\"}}

After setting the variable 

 System.Net.Http.HttpContent httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");

I cannot see the JSON String in httpcontent in the debugger, and the postAsync returns a 403 forbidden error...

Can anyone see anything obviously wrong ?

Thanks

G



How to open the wss website in browser?

$
0
0

Hi,

I created a digital signature demo.

I can't connect to this website when I use HTTPS protocol in IE11/edge.

the console says:

 SCRIPT12038: WebSocket Error: Network Error 12038, The host name in the certificate is invalid or does not match Connection is closed...

and other browser report bugs

WebSocket connection to 'wss://127.0.0.1:8987/SignFile' failed: Error in connection establishment: net::ERR_CERT_WEAK_SIGNATURE_ALGORITHM

what should I do?

I searched the Internet for this question for a period of time but in vain.

I'm looking forwark to your help!

Thank you.

I created a digital signature demo
I created a digital signature demo
I created a digital signature demo
I created a digital signature demo

Cannot see the value of httpcontent when debugging

$
0
0

I have some code as follows

string Payload ="{\"case_id\":\"FS-Case-88062659\",\"stage_name\":\"Back Office\",\"data\":{\"Outcome\":\"CO\",\"siteResponseDateTime\":\"2018-09-13T12:07:32.7798361+01:00\"}}"

System.Net.Http.HttpContent httpContent  = new StringContent(Payload, Encoding.UTF8, "application/x-www-form-urlencoded");

// same if I use "application/json"

If I look at httpContent in the visual studio (2015) debugger... its an object of type System.Net.Http.HttpContent 

Headers = Content-Type: application/x-www-form-urlencoded; charset=utf-8

But I cannot see any of the Payload in the httpContent.

Am I doing anything wrong ?

Is does say Headers - then ContentLength = 153 - which is the  same length as my payload (if I remove the \ chars ), but I cannot see the payload itself....



Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host in windows service

$
0
0

Hi,

We are sending bulk mails through windows service using third party(PMT).I am getting bellow exception regularly in our windows service.The logic we have written in this method is ,we are reading more than 600k records from the database and holding it in dataset.From the dataset we are processing 5k records.i.e sending 5k mails at one batch.

Message: [Exception][Message]: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.. [StackTrace]:    at OnePointEmailBuilder.ExecuteEmailBuilder.ProcessSingleEmailMessageJob(DataSet dsJobData, String trackReads, String ContentType). [Method]: Void ProcessSingleEmailMessageJob(System.Data.DataSet, System.String, System.String). [Source]: OnePointEmailBuilder. [InnerException]: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size).
Severity: Error

Any body aware of this?


Linq searching ignoring accents.

$
0
0

I have a collection with objects. Each object has a variable of type String. I wanna make some searchs on this collection ignoring accents that could have on variable of t ype String.

 

Cheers.

Merging values in list

$
0
0

I have created a list as below:

List<string> templist = newList<string>

string.Add(newstring() {Name="crank arm"PartId=1234,Address =" ",city =" "});

string.Add(newstring() {Name="crank arm",PartId =" ",Address = "New York",city = " " });

string.Add(newstring() {Name="crank arm",PartId =" ",Address =" ",city ="USA"});

I need to merge all the three records into a single record and store it in the same list.

Required Output:

"crank arm","1234","New York","USA"

video in c#

$
0
0

hi every one

can any one help me please?

i need to learn how show video and convert it to gray color in c#

Application crashes on Windows Server 2012 R2 - w3wp.exe crashes

$
0
0

Hi,

I am working on a MVC application that works locally absolutely fine. But when i host it on IIS on Windows Server 2012 R2, I get below error.

this is really critical for me to fix it ASAP. Appreciate any suggestions?

When I check in Fiddler, it gives me below error:

HTTP/1.1 504 Fiddler - Receive Failure

Event Viewer Log shows below error:

--------------------------------------------------------------------------------------

Log Name:      Application
Source:        Application Error
Date:          9/13/2018 12:13:47 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      WebApps2016TEMP.halton.local
Description:
Faulting application name: w3wp.exe, version: 8.5.9600.16384, time stamp: 0x52157ba0
Faulting module name: sslcnapi.dll, version: 1.0.0.0, time stamp: 0x5af62379
Exception code: 0xc00000fd
Fault offset: 0x00026757
Faulting process id: 0x%9
Faulting application start time: 0x%10
Faulting application path: %11
Faulting module path: %12
Report Id: %13
Faulting package full name: %14
Faulting package-relative application ID: %15
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2018-09-13T16:13:47.000000000Z" />
    <EventRecordID>39924</EventRecordID>
    <Channel>Application</Channel>
    <Computer>WebApps2016TEMP.halton.local</Computer>
    <Security />
  </System>
  <EventData>
    <Data>w3wp.exe</Data>
    <Data>8.5.9600.16384</Data>
    <Data>52157ba0</Data>
    <Data>sslcnapi.dll</Data>
    <Data>1.0.0.0</Data>
    <Data>5af62379</Data>
    <Data>c00000fd</Data>
    <Data>00026757</Data>
  </EventData>
</Event>


Kanthi

download a file from sharepoint online using caml and by filename

$
0
0

Hi,

Here is my code and i am getting exception "The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. - "

in the this line of the code:   var list = context.Web.Lists.GetByTitle(library);

Below is the whole code:-

public void Main()
        {
            var site = (string)Dts.Variables["$Package::SiteUrl"].Value;
            var library = (string)Dts.Variables["$Package::Library"].Value;
            var directory = (string)Dts.Variables["$Package::fileDestination"].Value;
            var ErrorFile = (string)Dts.Variables["$Package::ErrorLog"].Value;
            var filename_1 = (string)Dts.Variables["User::fileName_1"].Value;

            try
            {
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml =

         @"<View>

               <Query>

                  <Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>" + filename_1 + @"</Value></Eq></Where>

               </Query>

                <ViewFields><FieldRef Name='FileRef' /><FieldRef Name='FileLeafRef' /></ViewFields>

         </View>";
                 ClientContext context = new ClientContext(site);
                var securePassword = new SecureString();
                var password = "1234abc";
              
                foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
                context.Credentials = new SharePointOnlineCredentials(@"johnd@xyz.com", securePassword);
                var list = context.Web.Lists.GetByTitle(library);
                ListItemCollection listItems = list.GetItems(camlQuery);
                
                context.Load(listItems);

                context.ExecuteQuery();

                var listItem = listItems.FirstOrDefault();

}

Pls guide me through this.

Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>