[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

C#

93K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

I have a c# application and need to run a stored procedure in local  postgresql database

Postgre 9.5.1 is installed on my PC  and

I have tried the stored procedure .  It works ( Its a simple select statement)

Below  are the following:

1. My connection  string
2.  Segment that  generated the error
3. Details of the error
4. Screen Print of where error occured using the Visual Studio Debugger

1. Connection String

<add name="Tournaments" connectionString="Server=(localhost:5432);Database=Tournaments;Integrated Security=true;Provider=PostgreSQL;" providerName="System.Data.OleDb.OleDbConnection"/>

2. Error on Output =  Line

public List<AbseCodeModel> getabsecode_all()
        {
            List<AbseCodeModel> output;
            using (IDbConnection connection = new System.Data.OleDb.OleDbConnection(GlobalConfig.CnnString(db)))
            {
                output = connection.Query<AbseCodeModel>("spgetabsecode_all").ToList();
            }
            return output;
        }


3. Detailed Error

System.Data.OleDb.OleDbException
  HResult=0x80040E21
  Message=Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
  Source=System.Data
  StackTrace:
   at System.Data.OleDb.OleDbServicesWrapper.GetDataSource(OleDbConnectionString constr, DataSourceWrapper& datasrcWrapper)
   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection …
0
Become a Microsoft Certified Solutions Expert
LVL 12
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

I have a text box, for user input. I read the user input,  and run a sql query in the back end , as such
 
select * from table where column like "%userinput%".

what should I do before including , the user input to the sql query , in order to prevent sql injection.

I am using C# and oracle database.
0
Hello all,

I cannot seem to find the answer that I am looking for so... I have a combo box with the DropDownStyle set to DropDown. I want users to be able to type and get the suggested options, but I do not want user's to type and leave a value that is not on the list. I have the SuggestAppend set for AutoComplete, but users can set the combo boxes text value to something that is not on the list.  Originally, I had the DropDownStyle set to DropDownList but the color change bothered me and all the solutions I found did not seem to let me change the BackColor. Can some please help me with getting the BackColor changed to "white" for a DropDownList  combo box or help me programically change the behavior of the combo box to not allow the value to equal something that is not on the list?

**Change the FlatStyle property to Popup is not an option.

Thank you for your assistance.
Shannon
0
Hi,

I have this webrequest looking like this:

 Public Sub SendFile(ByVal filename As String)
            coRequest = CType(WebRequest.Create(sURL), HttpWebRequest)
            coRequest.ProtocolVersion = TransferHttpVersion
            coRequest.Method = "POST"
            coRequest.ContentType = "multipart/form-data; boundary=" & BeginBoundary
            coRequest.Headers.Add("Cache-Control", "no-cache")
            coRequest.KeepAlive = True
            Dim strFields As String = GetFormfields()
            Dim strFileHdr As String = GetFileheader(filename)
            Dim strFileTlr As String = GetFiletrailer()
            Dim info As FileInfo = New FileInfo(filename)
            coRequest.ContentLength = strFields.Length + strFileHdr.Length + strFileTlr.Length + info.Length
            Dim io As System.IO.Stream
            io = GetStream()
            WriteString(io, strFields)
            WriteString(io, strFileHdr)
            Me.WriteFile(io, filename)
            WriteString(io, strFileTlr)
            GetResponse()
            io.Close()
            coRequest = Nothing
        End Sub

Open in new window


The GetResponse sub looks like this:
Public Overridable Sub GetResponse()
            If coFileStream Is Nothing Then
                Dim stream As Stream
                Dim response As WebResponse

                Try
                    response = coRequest.GetResponse()
                Catch web As WebException
                    response = web.Response
                End Try

                If response IsNot Nothing Then
                    stream = response.GetResponseStream()
                    Dim sr As StreamReader = New StreamReader(stream)
                    Dim str As String
                    ResponseText.Length = 0

                    For Each str In sr.ReadLine
                        ResponseText.Append(str)
                    Next

                    response.Close()
                Else
                    Throw New Exception("MultipartForm: Error retrieving server response")
                End If
            End If
        End Sub

Open in new window


The coRequest.ContentLength is 100507 and everything seems ok, but I get this error:
you must write contentlength bytes to the request stream before calling begin getresponse

Open in new window


I do the exact same in C#:

Open in new window

0
We have a site and it has a global search feature which is very very slow. It looks up 4 tables and does a wildcard.

This is how it looks like
select ....
 from 
 [dbo].[Unit] AS u
	LEFT join [dbo].[Schedule] AS s
    ON u.[ScheduleID] = s.[ID]
    LEFT OUTER JOIN [dbo].[MasterLease] AS m
        ON s.[MasterLeaseID] = m.[ID]
		INNER JOIN dbo.Portfolio p ON p.ID = m.PortfolioID
 
WHERE 
u.[Deleted] <> 1
          AND (1 <> s.[Status])
   
          AND (m.[Deleted] <> 1)
          AND (m.[Active] = 1)
AND
      (
          (s.[Sched] LIKE @searchtext)
          OR (u.[SerialNo] LIKE @searchtext)
        
          OR (u.[CustomerRef] LIKE @searchtext )
          OR (u.[Model] LIKE @searchtext )
          OR (u.[Manufacturer] LIKE @searchtext)
          OR (u.[SiteAddress] LIKE @searchtext )
          OR (m.[CustomerName] LIKE @searchtext )
          OR (s.[LesseeName] LIKE @searchtext )
      );

Open in new window


1. My manager doesn't want to do a FullText Search
2. We have used indexes
3. The wildcard slows down the search, I think
4. If I join the 4 tables without the where clause, I get 2,827,623 rows. Should we dump this data in a table and just search this table? (update the table every night with fresh data)
5. Tried this as well... I broke down the joins by creating temp tables. First search Units, dumped in the temp table, #Units. Then Schedules in #Scheudles , then MasterLease in #ML.  Then did the join like I have above but what if there's nothing in #Units table...meaning...search didn't bring anything back from and #units is empty. I don't the join going to be correct.

I think #4 is a good option. How do others do a global search?
0
Hi,

I have object called productbzAux  and it product type has value "A". I wanted to duplicate the same product with productType as "C" and add it to the same List object productCategoryBEList

My below code is updating the productType for parent and child object i.e., productbzAux  and productbzCore

Also, please advise the best way to write the below code.

The below code is in C#

Thanks

List<ProductCategoryBE> productCategoryBEList = shoppingCartBE.ArrivalBooking.AvailableProducts;

            if (productCategoryBEList != null)
            {
                ProductCategoryBE productCategoryAUXBE = productCategoryBEList.FirstOrDefault(p => p.CategoryCode.ToUpper().Contains("AUX"));
                ProductItem productbzAux = productCategoryAUXBE.Products.FirstOrDefault(t => t.SubCategoryCode.ToUpper().Contains("bz"));

                if (productbzAux != null)
                {
                    productCategoryBEList.Remove(productCategoryAUXBE);
                    List<ProductItem> products = productCategoryAUXBE.Products;
                    ProductItem productbzCore = new ProductItem();
                    productbzCore = productbzAux;
                    productbzCore.ProductType = "C"; // This is updating the ProductType of parent object i.e., productbzAux.ProductType where as it should be A for parent and C for child.
                    products.Add(productbzCore);

                    productCategoryAUXBE.Products = products;

            

Open in new window

0
I use Dapper in my C# application

My connection strings and the error displayed during run time are in the attached notepad document.

I am connecting to local postgresql installed on my PC

Why is providerName="Npgsql" not seen as the providername.

or is there a conflict some where ?

How can I resolve this error

Thanks

Olukay
C-connection121118.txt
0
Hi Expert
I have added the web service to the Class Library file and created the DLL file.
so my issues are when I added to another project to this DLL file the web services classes method is can call from DLL file.
I need to hide the web service method from the new project. I need to allow only a few methods I have created.
How to do that.if any idea much appreciated.
0
I am using Microsoft.Extension.Logging.Log4Net.AspnetCore.
I want to separate default framework logoutput into a separate file from the logoutput that I program the application to output.

Is this possible, and how?
0
hi i try to use https://pdfium.patagames.com/c-pdf-library/

I found above api/pdf tool that using for (Search for a Text in a PDF File). and return x and y coordiate value.
and I bulit my own codes which is almost the same.

The return is always 0,0 which look like the search keywords feature does not work well.
And anyone try and tell me how your test about?

 public static Tuple<float,float> ExtractTextInfo(string keyword)
           {
            //Initialize the SDK library
            //You have to call this function before you can call any PDF processing functions.
            PdfCommon.Initialize();
            //Open and load a PDF document from a file.
            float x = 0;
            float y = 0;
            using (var doc = Patagames.Pdf.Net.PdfDocument.Load(@"C:\Users\ry24234u.23423\Documents\Workspaces\RNsadfasd\AppStore\ApsdfpMot324orHomeS3423hares\document\rentalcontract.pdf"))
            {
                //Enumerate pages
                foreach (var page in doc.Pages)
                {
                   var found = page.Text.Find("This", FindFlags.MatchWholeWord, 0);
                   if (found == null)
                   {                        
                       return new Tuple<float, float>(0,0);
                   }
                    do
                    {
                        var textInfo = found.FoundText;
                        foreach (var rect in textInfo.Rects)
                        {
                         

Open in new window

0
Angular Fundamentals
LVL 12
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

I am attempting to convert to c# two  methods in vb6 for grids. Below is the pasted vb6 methods and after my work beginning on it. We are using BindingSource for .NET grid binding, label_fields is a list in .NET, . I appreciate any help as I am really behind.

Private Sub grd_label_UnboundGetRelativeBookmark(StartLocation As Variant, ByVal OffSet As Long, NewLocation As Variant, ApproximatePosition As Long)
    
    Dim current_row As Long
    Dim grid_rows As Long

    ' DBGrid calls this routine each time it
    ' needs to position a row.

    ' StartLocation is a bookmark supplied by the grid to
    ' indicate which records the grid wants to positioning from.
    ' If StartLocation is NULL, then data is requested either
    ' from the first row or the last row.
    On Error Resume Next
    grid_rows = UBound(label_fields)
    If Err = 0 Then
        If IsNull(StartLocation) Then
            If OffSet < 0 Then
                current_row = OffSet + grid_rows            ' Reading data from the last row
            Else
                current_row = OffSet - 1                    ' Reading data from the first row
            End If
        Else
            ' Positioning from StartLocation plus the OffSet
            current_row = Val(StartLocation) + OffSet
        End If
        If current_row < 0 Or current_row >= (grid_rows) Then
            NewLocation = Null
        Else
            NewLocation = current_row
            ApproximatePosition = current_row + 1  ' One

Open in new window

0
What would you recommend for the following scenario?  It is concerning the communication.

A thread is to communicate to a win forms window that some updated information is available.  The window will then retrieve this new information and display it.  The thread must not be blocked when signalling to the window.  Also either the thread should not flag the window a second time if the updated information has not been retrieved or the window will only respond to one signal and 'remove' any pending signals to leave the signalling mechanism free.  That is purely for efficiency not that the same piece of information is pulled multiple times into the winform.


For those that understand how windows works classically I would have used PostMessage (non blocking function) in the thread to add a custom message to queue of the window and in the window use a PeekMessage loop to strip out any of the pending messages when responding to the message.
0
I have below codes working fine.
but instead of drop the image into the fixed location (  image.SetAbsolutePosition(100, 100);)

Is it possible to do the look up e.g. if the text called 'signature' is shown on the pdf, then drop the image there on the right side of the 'signature' text?
Or if there is any textbox field called 'signature', drop the image next to it.

Is it possible?

0c8f5c99-4ff8-4863-bb62-3af10ad394a8.pdf
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

class Program
{
    static void Main(string[] args)
    {
        using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            var reader = new PdfReader(inputPdfStream);
            var stamper = new PdfStamper(reader, outputPdfStream);
            var pdfContentByte = stamper.GetOverContent(1);

            Image image = Image.GetInstance(inputImageStream);
            image.SetAbsolutePosition(100, 100);
            pdfContentByte.AddImage(image);
            stamper.Close();
        }
    }
}

Open in new window

0
Hello,

Anyone please can suggest if in Linq I can select records .I am trying  to get  some data as list.
So for example in the attached worksheet if i can get list of data before NULL value yellow cell  of ColumnA.  Please assume this as a DataTable with columns.

Just need an idea of a linq query and c sharp.

Thanks.
abhilash
Book1.xlsx
0
This code currently works but I would like to add some columns to the result set. Once such column is the ContentType of the document in the path column.

Here is the code I am using and it does indeed return a datatable with results but it has ContentTypeID (Some Unique Identifier).

SharePointSearchAPI.QueryService queryService = new SharePointSearchAPI.QueryService(); queryService.Url = SharePointServiceURL;

            queryService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            // set search string
            StringBuilder xmlString = new StringBuilder("<QueryPacket xmlns='urn:Microsoft.Search.Query'>" +
                            "<Query><SupportedFormats><Format revision='1'> urn:Microsoft.Search.Response.Document:Document" +
                            "</Format></SupportedFormats><Context><QueryText language='en-US' type='STRING'>");
            xmlString.Append(SharePointSearchString); // user entered text
            xmlString.Append("</QueryText></Context>");
            xmlString.Append("<Range><Count>5000</Count></Range>");
            xmlString.Append("</Query></QueryPacket>");
            System.Data.DataSet queryResults = queryService.QueryEx(xmlString.ToString());
DataTable dtResults = queryResults.Tables[0];
0
Hi,

how can I reduce video size? When I save a video 10sec video have 100MB. How can I set bitrate for recording?

Thank you


using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.VFW;

namespace Aforge_Web_Cam
{
public partial class VideoForm : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
private AVIWriter AVIwriter = new AVIWriter();
private SaveFileDialog saveAvi;

public VideoForm()
{
InitializeComponent();
}

private void VideoForm_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
}

private void butStart_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}

void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (butStop.Text == "Stop Record")
{
video = (Bitmap)eventArgs.Frame.Clone();
pbVideo.Image = (Bitmap)eventArgs.Frame.Clone();
AVIwriter.Quality = 0;
AVIwriter.AddFrame(video);
}
else
{
video = (Bitmap)eventArgs.Frame.Clone();
pbVideo.Image = (Bitmap)eventArgs.Frame.Clone();
}
}

private 

Open in new window

0
Hi, I have a blog website build using ASP.NET using C# and entity framework.
I have this requirement where I need to list all my published blogs and paginate them as they are too many.
I am new to .NET and have no idea how to do it.

Earlier I got all the blog details from the database and used ajax and JSON as well to fetch it.

A friend gave me a sample code and told me it would help. Please have a look into that as well.


Please help me acheive this.
I am attaching all my code here along with the stored procedure.


STORED PROCEDURE

GO
/****** Object:  StoredProcedure [dbo].[GetBlogs]    Script Date: 05-11-2018 01:50:14 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[GetBlogs]

@count int,
@start int,
@categoryId int,
@blogCount int Output
as
begin
	Declare @LastBlog int
	Set @count = 9
	Set @lastBlog = @count + @start;

	create table #x (id int identity(1,1),blogid int)

	if @categoryId is null
		begin
			insert into #x
			select Id from Blog where IsDeleted=0 and StatusId = 2

		end
	else
		begin
			insert into #x	
			select b.Id from Blog b inner join BlogCategories bc on b.Id = bc.BlogId where bc.CategoryId = @categoryId and b.IsDeleted=0 and b.StatusId = 2;
		end
	
	select @blogCount = COUNT(#x.id) from #x 

	select b.* from #x inner join Blog b on #x.blogid = b.Id where #x.id > @start and #x.id <= @LastBlog

	drop table #x

end

Open in new window




DAL Sample Code

using System;
using 

Open in new window

0
HI,
I can access the oracle tables and stored procedures using C#, but i am getting error when trying to use select oracle VIEW.
Below code i am using. I have access to that view also.
I don't even understand what mistake i did, please do the needful, very urgent.
If you have any piece of code to connect oracle view, please post it.

Error:Operation is not valid due to the current state of the object."

OracleConnection con = null;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr = null;

try
{
    con = new OracleConnection("COnstring");
    con.Open();
    string strQuery = string.Empty;

    strQuery = "select col1,col2 from VW_test_view where col1 ='" + COL1 + "'";
    cmd.CommandText = strQuery;
    cmd.CommandType = CommandType.Text;
    dr =cmd.ExecuteReader(); 

    if (dr.HasRows)
    {
        while (dr.Read())
        {
            statusCode = dr["col2"].ToString();
        }
    } 
}

Open in new window

0
Whats is the best too for Web services Testing Tool?
REST and API Testing
I'm planing to by Smart bear.Any idea is appreciated.
Company happy to pay for that.
0
Rowby Goren Makes an Impact on Screen and Online
LVL 12
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Hello,
Thanks for your time. Can we have a window form list box with image and text or like custom.
Or can we have some custom control like  repeative.

Any ideas please thanks

Abhilash
0
Hi Experts,
My getting following Error Message

"ie.Message      "Object reference not set to an instance of an object."      string"

Any help appriciated.
See my code below

public class SalesRecords
    {

        public List<salesProp> data { get; set; }

    }




  public class salesProp
    {
        public string Name { get; set; }  
    }  





    var  restunVal1=response.Content.ReadAsStringAsync().Result;

   SalesRecords  sr = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<SalesRecords>(restunVal1);

                     foreach (var item in sr.data)
                     {
                         Console.WriteLine("id: {0}",item.Name);
                     }





JSON output like this
"{\n  \"totalSize\" : 1,\n  \"done\" : true,\n  \"records\" : [ {\n    \"attributes\" : {\n      \"type\" : \"Account\",\n      \"url\" : \"/services/data/v40.0/sobjects/Account/0011q000007ZPL3AAO\"\n    },\n    \"Name\" : \"Test\"\n  } ]\n}"
0
I've integrated into a 3rd party java windows app which is forwarding messages via http post and get
They call it forwardURL, and its running locally so just hits http://127.0.0.1/etc

On the other side of this I have  multithreaded c# 4.6 console app which accepts the forwarded messages and saves them
I've noticed recently I've started to miss messages, and in one instance, there were 14 mins of messages missing

I'm trying to figure out the issue with logging etc, but wondered if there is a technology limit/server configuration limit (win 2016)
when I get to 30 messages a second, I've noticed messages start going missing.

Is there a limit that i'm unaware of, or some setting in the console app/windows that needs checking that might be responsible for these missing messages?
0
In c#, For Example the list contains {Eid:67,EName:'dyt',DOB:06/09/2017,Sal:6078}.
Actually i declared a class with properties as Eid,Ename,DOB,Sal etc...
 my question is from list i need to retrieve values and need to assign it to specific property.
For ex: Eid property need to assign 67.
like that for all properties in c#.

could you please help
0
We use iTextSharp to create PDFs throughout our site.  We have a Comments field that can grow.
It doesn't look like iTextSharp supports dynamic attributes - or at least the way we are using it with a pre-defined template.

sample of the code for the comments section:

  stamper.AcroFields.SetField("Comments", sb.ToString());
  stamper.AcroFields.SetFieldProperty("Comments", "textsize", 6f, null);
0
I want to create setup file (EXE) for c# windows application with using database of SQLite.
0

C#

93K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).