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

c# get dynamic webpage data

$
0
0

Dear all!

I'm new to programing. I am trying to get data from a webpage. Example: I tring to get if an IP is listed at a blacklist, the webpage takes time to search or fully load the page, and even when it does, the source code does not have the information what i 'd like to obtain, like the IP is on the blacklist. Any help would be welcome

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mxtoolbox.com/SuperTool.aspx?action=blacklist%3a42.51.217.54&run=toolpage");
//set big timeout 30 sec
 request.Timeout = 30 * 1000;
// put result to a textbox to see
 string postData = textBox1.Text;

 request.Method = "Post"; // we will post the data using post method

                // data to be posted using HttpWebrequest post method
                string postData = textBox1.Text;
                // Convert this string into stream of bytes
                byte[] arrPostDAta = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
                // set request content length = post data length
                request.ContentLength = arrPostDAta.Length;
                // get request stream
                System.IO.Stream strmPostData = request.GetRequestStream();

                // write post data to stream of request
                strmPostData.Write(arrPostDAta, 0, arrPostDAta.Length);

                strmPostData.Close();

                // upload post data and Get Response from server 
                  
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                textBox1.Text = reader.ReadToEnd();

                reader.Close();

                response.Close();


LINQ and Except

$
0
0

I'm using Except to select all records (call them delta records) in one file (today's) that were not in another file (yesterday's). These files always grow by zero or more records each day and records are never removed but some may change and some may get added.

The LINQ Except works fine however I also need to report the line number (in today's file) of each record we process from the delta records.

I do this simply by calling todays.IndexOf(record) which works but has a 60% CPU cost in the app I'm writing. The files contains upwards of 75,000 records (yet the delta records may be just 2,000 or so).

I tried creating a list of these record numbers once (at the same time I do theExcept) and then getting the record number is just a matter of looking up theIndexOf on the much smaller list (2000 or so). But the CPU went up because we're doing - overall - more work in total.

So I wanted to know is there anything like Except that can give me not just the records from A that are not in B but also the index of the record within A.

Thanks

How to add custom invoice number like "INNK-5001" with auto increment using Sqlite database in C# Windows Application

$
0
0

I'm using SQLITE Database. I want to create a custom invoice number like this "INNK-5001" with auto increment INNK-5002, INNK-5003... and so on. I write below code for this purpose. Below code working correctly only if i use only number like "5000" but when i use "INNK-5000" i got Error. Please help me how can i get this number "INNK-5000" with auto increment using Sqlite Database. This my code...

// To Create Sqlite Database

public void CreateDB()
    {
        if (!File.Exists("customid.db"))
        {
            SQLiteConnection.CreateFile("customid.db");
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=customid.db;Version=3;"))
            {
                string commandstring = "CREATE TABLE cusid (Id INTEGER PRIMARY KEY NOT NULL, FirstName NVARCHAR(250), LastName NVARCHAR(250))";
                using (SQLiteCommand cmd = new SQLiteCommand(commandstring, conn))
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }

// For Custom Invoice Number

public void CustomId()
    {
        try
        {
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=customid.db;Version=3;"))
            {
                string CommandText = "SELECT Id FROM cusid";
                using (SQLiteDataAdapter sda = new SQLiteDataAdapter(CommandText, conn))
                {
                    conn.Open();
                    DataTable datat = new DataTable();
                    sda.Fill(datat);

                    if (datat.Rows.Count < 1)
                    {
                        textBox1.Text = "INNK-5000";
                    }
                    else
                    {
                        using (SQLiteConnection conn1 = new SQLiteConnection("Data Source=customid.db;Version=3;"))
                        {
                            string CommandString = "SELECT MAX(Id) FROM cusid";
                            using (SQLiteCommand cmd = new SQLiteCommand(CommandString, conn))
                            {
                                conn1.Open();
                                int a = Convert.ToInt32(cmd.ExecuteScalar());
                                a = a + 1;
                                textBox1.Text = a.ToString();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

// For Save a Record into Database

private void savebtn_Click(object sender, EventArgs e)
    {
        try
        {
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=customid.db;Version=3;"))
            {
                string CommandText = "INSERT INTO cusid ([Id], [FirstName], [LastName]) VALUES (@id,@firstname,@lastname)";
                using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
                {
                    cmd.Parameters.AddWithValue("@id", textBox1.Text);
                    cmd.Parameters.AddWithValue("@firstname", textBox2.Text);
                    cmd.Parameters.AddWithValue("@lastname", textBox3.Text);

                    conn.Open();
                    int a = cmd.ExecuteNonQuery();
                    if (a > 0)
                    {
                        MessageBox.Show("Data Saved!!");
                        CustomId();
                        BindDataGridView();
                    }
                    else
                    {
                        MessageBox.Show("Not Saved!!");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Please Help me... Thank You.

Azure Event Hubs JSON Parsing Error

$
0
0

Ok I'm using event hubs in my webapi app.  This was working(reading event hub) for awhile and now a few days later I keep getting this error consistently:

Unexpected character encountered while parsing value: �. Path '', line 0, position 0.

at Newtonsoft.Json.JsonTextReader.ParseValue() at Newtonsoft.Json.JsonTextReader.Read() at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) at Microsoft.ServiceBus.Messaging.BlobLeaseManager.<DownloadLeaseBlob>d__30.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.ServiceBus.Messaging.PartitionManager`1.<InitializeAsync>d__13.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.ServiceBus.Messaging.EventProcessorHost.<InitializeAsync>d__53.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.ServiceBus.Messaging.EventProcessorHost.<StartAsync>d__54.MoveNext()

Whatever is happening isn't happening during any of my application code.  It's occuring at this call:

Task.Run(() => eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>(options)).Wait()

It's never even executing IEventProcessor.OpenAsync() or IEventProcessor.ProcessEventsAsync() but here all of the methods just for clarity:

async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
        {
            Console.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason);
            if (reason == CloseReason.Shutdown)
            {
                await context.CheckpointAsync();
            }
        }

        Task IEventProcessor.OpenAsync(PartitionContext context)
        {
            //Console.WriteLine("SimpleEventProcessor initialized.  Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset);
            WebApiApplication.mymsg += "SimpleEventProcessor initialized";
            //WebApiApplication.numMessages = 0;
            this.checkpointStopWatch = new Stopwatch();
            this.checkpointStopWatch.Start();
            return Task.FromResult<object>(null);
        }

        async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
        {
            WebApiApplication.mymsg += " number of messages: "+messages.Count();
            //WebApiApplication.numMessages = messages.Count();
            foreach (EventData eventData in messages)
            {
                string data = Encoding.UTF8.GetString(eventData.GetBytes());

                WebApiApplication.mymsg += string.Format("\nMessage received.  Partition: '{0}', Data: '{1}'",
                    context.Lease.PartitionId, data);
            }

            //Call checkpoint every 5 minutes, so that worker can resume processing from 5 minutes back if it restarts.
            if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
            {
                await context.CheckpointAsync();
                this.checkpointStopWatch.Restart();
            }
        }

The event hub is being instantiated and called like so:

eventProcessorHost = new EventProcessorHost(eventProcessorHostName, eventHubName, EventHubConsumerGroup.DefaultGroupName, eventHubConnectionString, storageConnectionString);

                //return WebApiApplication.mymsg;

                //Console.WriteLine("Registering EventProcessor...");
                var options = new EventProcessorOptions();
                options.MaxBatchSize = 10000;
                //options.PrefetchCount = 10000;
                options.ExceptionReceived += (sender, e) => {
                    WebApiApplication.mymsg += e.Exception.ToString();
                };

                //eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>(options).Wait();
                WebApiApplication.mymsg = "starting...";
                //WebApiApplication.numMessages = 1;
                Task.Run(() => eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>(options)).Wait();
                started = true;
                Task.Run(() => eventProcessorHost.UnregisterEventProcessorAsync()).Wait();

I get no build errors and other endpoints work fine.

WebApiApplication.mymsg gets set to "starting..." and never changes value and i get the forementioned error. 

Just to reiterate, this was working fine for days just until I tested it again yesterday.  I needed to generate a new auth token for requests.  I did that and now reading the event hub consistently gives me this error. 

Any guidance or assistance?

*moved to the c# forums which I think is the more appropriate place for this.

C# How to access and copy values in objects instead of accessing the reference to the object

$
0
0

 I am attempting to populate a moving average queue but I am getting the same date and close for all of the objects in the moving average queue.  I am stuck as how to not get the reference pointing to the same object instead of getting the current value in the object and placing that value on the queue.  Here is the code

publicclass MA{publicstaticQueue<DateClose>MAMethod(Queue<DateClose>queue,Deque<DateClose> firstMASample,int period){Deque<DateClose> sample =newDeque<DateClose>(firstMASample.ToArray());Queue<DateClose> movingAverageQueue =newQueue<DateClose>(queue.Count()+1);// get the last item or initial MA value from the queueDateClose mA = sample.RemoveFromBack();DateClose dateClose =null;decimal sub =0;DateClose add =null;//put the initial Ma value on the movingAverageQueue
        movingAverageQueue.Enqueue(mA);foreach(DateClose d inqueue.ToList()){
            dateClose = sample.RemoveFromFront();
            sub = dateClose.Close;// subtract previous closing from new current MA
            mA.Close= mA.Close- sub/period;// add the new closing to new current MA
            add = d;
            sample.AddToBack(d);
            mA.Close= mA.Close+ add.Close/period;
            mA.Date= add.Date;
            movingAverageQueue.Enqueue(mA);queue.Dequeue();}return movingAverageQueue;}}

How to create ForeignKey reference to code-first identity tables

$
0
0

Hi,

I'm developing a web application using MVC 5, EntityFramework 6 with a Code-First approach.

How the heck does one create a relationship between the auto-generated code from the Identity Framework and a model I made? Whats the point of using this Individual User Authentication if I can not relate other models/tables to it. Seriously, I hope you guys know because so far, I can not find any legit solution to this matter. 

Thanks,

Jake

Visual C# Button to implement into SharePoint

$
0
0

Dear Pros,

I am moved around, regarding creating a Button in SharePoint.

After talking to some SharePoint people, they recommended to build the button with VisualStudio.

I have unfortunately no experience with VisualStudio nor with C# and to import on such way, that it works.

I was able to build my button for a test and it was running.

Then I opened a new project in VisualStudio - "SharePoint 2016 Visual Web Part" and copied my C# line at the end. (see code at the end)

Trying to add the web part in SharePoint, I get the following message:

$Resources:core,ImportErrorMessage;

At the end, I do not mind, if the code is written in C# or C++ or something similar (I anyway need to learn any language), as long as it is working in SharePoint. Maybe for SharePoint, there is it's own language?

What I will need at the end is, to open a PowerShell file by pressing a button on a sharepoint site and it will open(locally on the host and not on the server) that will be the long term target, that is why I am trying now to play around with notepad as a start.

Can anyone please help me, to explain to me, how I can implement such a button into SharePoint?

Thank you very much,

Mike

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1.ascx.cs" Inherits="VisualWebPartProject2.VisualWebPart1.VisualWebPart1" %>
using System.Windows.Forms;
using System.Diagnostics;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process.Start(@"C:\Windows\notepad.exe");
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

Control is Flickering while using Rotatetransform

$
0
0

Hello,

I am using WPF application where I have added Ellipse and Thumbs on Ellipse. When thumb moves I am calculating angle of that thumb with center point and rotating all children of Canvas. But while rotating it its flickering. Kindly look into following code and provide any solution,

 private void OnKeyPointThumbDragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{

               GetAngleCurvePoint(thumb.Position, e.HorizontalChange, e.VerticalChange, out var angle);

                VisualTransform = new TransformGroup
                {
                        Children =
                        {
                            new RotateTransform(angle, CenterPoint.X, CenterPoint.Y),
                        }
                };

}

private Point GetAngleCurvePoint(Point point, double eHorizontalChange, double eVerticalChange, out double angle)
        {
            var newLocation = new Point(point.X + eHorizontalChange, point.Y + eVerticalChange);
            var yDiff = newLocation.Y - CenterPoint.Y;
            var xDiff = newLocation.X - CenterPoint.X;
            angle = Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI;
            if (angle < 0)
            {
                angle += 360;
            }

            angle += 180;
            //angle += 180;

            var x = (XDiameter-0.5 + AngleGap) / 2 * Math.Cos(angle * Math.PI / 180) + CenterPoint.X;
            var y = (YDiameter-0.5 + AngleGap) / 2 * Math.Sin(angle * Math.PI / 180) + CenterPoint.Y;

            return new Point(x, y);

        }


Latest Windows 10 update kills all my AnyCpu programs.

$
0
0

I know this is a long shot but I have no where to go now.

I have three products on the market.  They are released as 64 bit version (with AnyCPU) and 32 bit versions.  This 64 bit one is  solely due it a specific driver not working correctly on the 32 bit code.

The products have been out for many years. This week, I released an update to one of the products, both the 32 and 64 bit versions.  Both work fine on two different development machines.  One using Windows 10 and the other Windows 7.  These were tested on a Windows 10 client and a windows 7 client.  In both cases the programs ran, at first.

The software was deployed and then I started getting reports of the 64 bit  starting and then just stopping.  No errors.  If the client PC already had an install it worked, just like on my test machine.  However, if it was a fresh install then it would not work. Furthermore, if you rebooted the 64 bit machine the 64 bit version would stop working.  Not only that, none of the other products I have would work either , even though it was months since they were installed.  There are no problems on a Windows 7 machine at all.  I did a build on the Windows 7 machine that hadn't been used in months and it made no difference. So the development machines are acting the same.

Now I traced the error to the first Windows form that opens in the software.  Right at the InitializeComponent there is an access exception c0000005 in the module rtl160.BPL which is a delphi component.  It occurs in the temporary folder c:\user\userid\appdata\local\temp.  So it appears that somehow the wrong version of the delphi component or my code is all of a sudden trying to use temporary files in this folder.

So, my app is written in VS 2010, C#.  I use libraries from Mitov.com that use a combination of a C# .NET wrapper and delphi code along with the Intel performance primitives.

In the 32 bit version, I distribute the dll's such as Mitov.SignalLab.dll which has all the delphi and intel performance primitives in the dll itself.  On the 64 bit version, you distribute the the 64 bit dll's but you have to include the Intel DLL's as well.  There is no reference anywhere to rtl160.bpl.  So somehow, during release, and only it seems after Windows update this month, an rtl160.bpl is being used and it seems it is not the right one.  This is included in windows driver cache(not sure what that is called...).

So, I'm kind of lost.  If I could in some way, determine exactly which external files are being used on both the development machine and a client, perhaps a compare might show me something.  But I have done this on the installed version and everything looks identical.

Can someone help?  I did try a system restore on my client to before the windows update, but as the restore completed it reapplied the update!

This is really tough, since I could just get rid of the 64 bit version but I have a license manager which seems to not be able to determine the existence of the license when you open the 32 bit but had applied the license in the 64 bit.  With 2 thousand users  over 5 years I bet most have no idea where their license is.

Tom

System Resources are exceeded error for Excel with more than 800000 records

$
0
0

Hi, I am working on some migration project where data is exported from Oracle DB to Excel sheets. Extraction tool is different which is able to extract data to Excel around 1 Million also. In extraction tool Oracle Data reader is used and its extracting 1 Million records successfully. Even its extracting more than 1 M data as well in to multiple sheets in the same excel with multiple sheets like Sheet1,Sheet2 etc. I need to read the entire excel data and store it in Data table for my Ingestion. its working fine for below 8 lac data. But when i am trying to read the data from Excel using OleDb Data Adapter or Data Reader its failing when records exceed 8 Lac and giving error like "System Resources exceeded." My server is free and nothing is running there and its 64 GB ram as well.

Extraction separate tool which is fetching data from Oracle DB using Oracle Data reader. My tool is different which needs to read the excel data at a time and store in Data table for xml preparation. Find the code snap below. tried with both Data Adapter and Data reader. using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM [" + sheet + "]"; OleDbDataReader reader = cmd.ExecuteReader(); dtDocExcelData.Load(reader); LogWriter.LogWrite("No of Files/docs to process for the File : " + inputFilePath + " Sheet Rows Count : " + dtDocExcelData.Rows.Count); //clearing the resources cmd.ResetCommandTimeout(); cmd.Dispose(); reader.Dispose(); } visual studio is 2013 version and code is in C#. Excel version is also latest as 2016 (.XLSX). please check the above code part and let me know where it is failing to load the bulk data from excel. Is there any other way to resolve this.? Provide me any other alternative solutions to over come this. Project is going to live by month end. UAT is phase is failing. please give me alternate solution at earliest. Awaiting for your valuable suggestions. Thanks in advance. Regards, Venky

net::ERR_CONNECTION_RESET while uploading .xlsx files

$
0
0
while upload .xlsx files the error returned is net:<g class="gr_ gr_14 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style replaceWithoutSep" data-gr-id="14" id="14">:ERR_CONNECTION_RESE</g>T  and the application hosted outside .when it changed to .xls it can upload. I also add a simple page with a file uploader and submit button without any codes it's also lead to same error.

XLSX file uploads with ASP.NET and IIS7

$
0
0

I did a simple file upload for XLS and XLSX files. The web server can be accessed from inside the company domain with an internal IP address and from outside the DMZ for client use.

The file limits are set to 10Mb but there is a problem. Any upload done on the local network inside the DMZ works perfectly but from outside there is a problem with XLSX file over 2Mb, under 2Mb everything uploads.

These are the tests files I did:

Test_XLS.xlsThis is a 9Mb XLS file and it uploads no problem.

Test_XLS.xlsxThe same file as above just renamed to XLSX and it uploads no problem.

Test_XLSX.xlsx This is a 6Mb XLSX file and it errors within about 2 to 3 seconds of hitting the upload button.

Test_XLSX.xlsThe same file as above I just renamed with the XLS extension and it uploads no problem.

The error returned is net::ERR_CONNECTION_RESET

I looked at all the normal size limit and time-out settings in the Web.Config and in IIS, looked at the MIME maps, I also have assurance from my tech guys there are no firewall or other limits set but I cannot solve this, please help.

Load Embedded PowerShell Module to use in PowerShell ISE

$
0
0

Hello,

I want to create a C# class that includes an embedded PowerShell module file (*.psm1). When PowerShell ISE starts, I want to load the created DLL via profile.ps1 with the Import-Module command so that the cmdlets are available and usable in PowerShell ISE afterwards. Is that possible? 

I have tried it with the following code (and much more), to load a locally stored module first:

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            using (PowerShell ps = PowerShell.Create())
            {
                ps.AddCommand("Import-Module").AddParameter("Name", @"C:\Temp\Test.psm1");
                ps.Invoke();
                if (ps.Streams.Error.Count > 0)
                    Console.WriteLine(ps.Streams.Error[0].Exception);
                ps.Commands.Clear();
            }
Has anyone done that yet?

Many thanks

Object Reference not set to an object error at BtnSave_Click and cannot save to db

$
0
0

Hi,

I am trying to save user input data into a database. All of my data saving method are coming from WebService. I have assigned and initialized the data values to be ready to save in Webservice. But I am always getting 'Null' to most of them and that is the main issue: that I cannot save into database and getting 'object reference not set to an instance'error at the end of BtnSave method. I am wondering those data becomes Null because I initialized that become override my returned data ? If not, I am getting Object Reference not set error for those individual fields. I've searched online why Null Error occurs, because we haven't initialized variable. But, in my case I am not sure what is happening. Maybe I have initialized them, and returned data cannot be passed into? 

I have 2 sps for this BtnSave method, 1st one has 6 parameters-@enrolmentIntendedCourseId,@intendedCourseId,@weightingEducationalQualification,@weightingAdmissionTest,@status and @created By. 2nd one also have 6 parameters-@enrolmentIntendedCourseId,@intendedCourseId,@specialFactor,@Description,@status and @createdBy.

_newNCSData.WeightingEducationalQualification = Convert.ToDecimal(txtWEQ.Text); _newNCSData.WeightingEducationalAdmissionTest = Convert.ToDecimal(txtWAT.Text); _newNCSData.Status="Active"; _newNCSData.IntendedCourse = new Course(); _newNCSData.IntendedCourse.CourseID = _registerdCourseId; _newNCSData.EnrolmentIntendedCourse = new Course(); _newNCSData.EnrolmentIntendedCourse.CourseID = _selectedIntendedCourse;

_newNCSData.CreatedBy = new User(); _newNCSData.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID; if (resultGrid.RowCount > 0) { _newNCSSpecialFactorData= new List<NormalisedCompositeScoreSpecialFactorSetup>(); for (int i = 0; i < resultGrid.Rows.Count-1; ++i) { NormalisedCompositeScoreSpecialFactorSetup specialFactorSetUp = new NormalisedCompositeScoreSpecialFactorSetup(); if (resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value.ToString() != string.Empty) { specialFactorSetUp.NormalisedCompositeScoreSpecialFactorSetupFoundationID = int.Parse(resultGrid.Rows[i].Cells["NCSSpecialFactorSetupFoundationID"].Value.ToString()); } specialFactorSetUp.IntendedCourse.CourseID = _registerdCourseId; specialFactorSetUp.SpecialFactor = Convert.ToDecimal(resultGrid["SpecialFactor", i].Value); specialFactorSetUp.SpecialFactorDescription = Convert.ToString(resultGrid["Description", i].Value); specialFactorSetUp.Status = "Active"; specialFactorSetUp.CreatedBy = new User(); specialFactorSetUp.CreatedBy.UserId = AuthenticatedUser.UserSingleton.GetSingletonObject().userID; _newNCSSpecialFactorData.Add(specialFactorSetUp); } _calledFrom = "Save"; if (initialBackground.IsBusy == false) initialBackground.RunWorkerAsync(); MessageBox.Show("Record is save successfully.", "Title", MessageBoxButtons.OK, MessageBoxIcon.Information); RefreshGrid();


What is the easiest way to force a winforms apps title bar and text to stay the same?

$
0
0
Hi I have a winforms app which I do not want to resize based on a users dpi settings I have managed to achieve this with every control except the windows forms border and title text. When my app is set to over 150% and over the border width is too big that my content on the form is squashed I just want to force this to be a fixed size so that everything stays in proportion. Please don't advise me to make it dpi aware as I have wasted too much time on that and just need to fix this part.

How to check image is exist or not in database and show in picturebox using combobox value in c# windows application

$
0
0

hi, i am using windows form, i write a code for getting a image from database in picture box when combo box value is selected. my code is working correctly when combo box value is select and show the data (only show data that have a image). BUT i have a data without a image, when i select combo box value to show data that have no image, it show me a "ERROR" - "Parameter is not valid".

i tried if condition on it but code don't work for me.

here is the code...

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection("Data Source=combolist.db;Version=3;"))
                {
                    string CommandText = "SELECT * FROM combo WHERE [Id]=@id";
                    using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
                    {
                        cmd.Parameters.AddWithValue("@id", comboBox1.SelectedItem.ToString());
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        DataTable dt = new DataTable();
                        SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
                        da.Fill(dt);
                        foreach (DataRow dr in dt.Rows)
                        {
                            textBox1.Text = dr["Id"].ToString();
                            textBox2.Text = dr["FirstName"].ToString();
                            textBox3.Text = dr["LastName"].ToString();
                            textBox4.Text = dr["Age"].ToString();
                            textBox5.Text = dr["Address"].ToString();

                            byte[] img = (byte[])(dr["Pic"]);
                            if (img == null)
                            {
                                pictureBox1.Image = null;
                            }
                            else
                            {
                                MemoryStream ms = new MemoryStream(img);
                                pictureBox1.Image = System.Drawing.Image.FromStream(ms);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Please help me... Thanks

SharePoint migration from 2010 to 2013

$
0
0

We have upgraded the Solution from VS2012 .Net frame work 3.5 to VS 2013 .Net framework 4.5, then we are getting the error messages:

'System.Workflow.ComponentModel.ActivityExcutionStatus' is obsolete.The 'system.Workflow.' are deprecated. Instead please use the new types from 'System.Activities.*'

Please find below the code getting an error:

PublicStaticActivityExcutionStatusHandleFault(ActivityExcutionContext excutionContext,Exception exception,GuidWorkflowInstanceId)
{
  
if(excutionContext==null|| exception==null)
  
{
     
returnActivityExcutionStatus.Faulting;
  
}
}

reading a csv file with excel from c#

$
0
0

Hi,

I am trying to convert a csv and text files to an excel file from c#.

I am trying to open them with excel, then save them.

I find a file at the end of the execution but it's not taking into consideration the seperator.

                    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                    app.DisplayAlerts = false;
                    string FilePathToTreat = this.Search(workingDirectoryv1, FileNameToTreat);
                    //Microsoft.Office.Interop.Excel.Workbook excelWorkbook = app.Workbooks.Open(FilePathToTreat);

                    Microsoft.Office.Interop.Excel.Workbook excelWorkbook = app.Workbooks.Open(FilePathToTreat, 0, false, Excel.XlFileFormat.xlCSV, "", "", false, Excel.XlPlatform.xlWindows, charseparator, true, false, 0, true, false, false);
                    string newFileName = pathtemp1 + Path.GetFileNameWithoutExtension(FilePathToTreat) + ".xlsx";
                    excelWorkbook.SaveAs(newFileName);
                    excelWorkbook.Close();
                    app.Quit();

)

Would you please help ?

Thank you for your time

How Validate remote Workgroup user & change their passwords uisng c#. netapi32.dll (NetUserSetInfo & NetUserSetInfo) works few system but others we are getting Access Denied

$
0
0
I have created windows service. From i am trying to validate remote workgroup user using NetUserGetInfo.  If user is valid i change their password using NetUserSetInfo.  It works few systems but it wont work others, i am getting Access Denied error.  What might be the reason i am getting Access Denied error in few system.

batchblock documentation

$
0
0

I am studying dataflow parallel programming.  According to the msdn documentation on (https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library?view=netcore-2.1), the code below could show the output as 

The sum of the elements in batch 1 is 45.
The sum of the elements in batch 2 is 33.

I must be confused because I don't see how in the same batch the second call could have a lesser value than the first.  If somebody could explain in simple terms what is going on it would be appreciated

// Create a BatchBlock<int> object that holds ten
// elements per batch.
var batchBlock = new BatchBlock<int>(10);

// Post several values to the block.
for (int i = 0; i < 13; i++)
{
   batchBlock.Post(i);
}
// Set the block to the completed state. This causes
// the block to propagate out any any remaining
// values as a final batch.
batchBlock.Complete();

// Print the sum of both batches.

Console.WriteLine("The sum of the elements in batch 1 is {0}.",
   batchBlock.Receive().Sum());

Console.WriteLine("The sum of the elements in batch 2 is {0}.",
   batchBlock.Receive().Sum());

/* Output:
   The sum of the elements in batch 1 is 45.
   The sum of the elements in batch 2 is 33.
 */

Viewing all 31927 articles
Browse latest View live


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