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

Read sql table and insert result in a var

$
0
0

I have a table with records, I need to read all the records of certain fields and if those fields are empty assign a variable to the value zero and if it contains some value assign the result to a variable. I have the code in VB but I need the code in c#  with sql db 

CODE IN VB 

Public Sub formT1()
Dim SQL As String
Dim base As Database
Set base = CurrentDb
Dim rst As Recordset

Dim code_em As String

     

Set rst = base.OpenRecordset("SELECT * FROM [MEmp] WHERE [MEmp].[] = 2011")

Do While rst.EOF = False

    
    If IsNull(rst.Fields("CODE")) Then
        code_em = "0"
    Else
        code_em = rst.Fields("CODE")
    End If
    Call Regla_118(code_em)
    SQL = "INSERT INTO VALIDATE(REGLA_118) VALUES" _& "('" & Regla118 & "')"
    DoCmd.RunSQL SQL
 rst.MoveNext

Loop

base.Close
Set base = Nothing
End Sub

CODE I have tried in C#

public static void ValidarT1(string C_E)
        {
            string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {

                string query = "SELECT * FROM Empresas_Relacionadas";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            if (sdr.get)
                            {
                                C_E = "0";
                            }
                            else
                            {
                                //C_E = Value column 

                            }


                            ReglaController.Regla_1(C_E);

                            // INSERT TO Table 


                        }
                    }
                    con.Close();
                }
            }
        }


Cannot connect to Oracle to recreate entity framework

$
0
0

Hi,
•We’re migrating several apps done by consultants in 2013 from .Net Framework 4.0/MVC 4 to 4.5.2/MVC5 and Oracle 12c for Preservation on newer Win2012 Servers.
•All apps were developed in VS 2010 on Win 7 with Oracle 11g
•We are assuming/hoping after updating one the others will be streamlined. The first is always the most difficult.
•We assume migrating with the latest Visual Studio (VS2017 Pro and tools/updated packages) would smooth the process.
•VS2017 prompted us to update several Nuget packages including Entity Frameworks (up to 6.x).
•We have the current set of Oracle Developer Tools for VS 2017 installed.
•I've updated the project to MVC5 (I think...) This was the only option in Nuget.

I've worked through several issues so far but I'm stuck at the EDM wizard and cannot recreate the model from the db (It's unchanged) even though I've followed the steps at https://csharp.today/entity-framework-6-database-first-with-oracle/.  I can read data via VS but not with the app. It's some version discrepancy between my ODAC provider(s) and EF6. I've tried both managed and unmanaged providers from the ODAC and the approved Oracle 12c client.

Any help would be greatly appreciated.

Tim

managed thread

$
0
0

I am studying for the 70-483 exam and one of the examples has me confused.  I cannot tell how the following code determines when to stop i.e. (how is _f.value is determined)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        public static ThreadLocal<int> _f = new ThreadLocal<int>(() =>
           {
               return Thread.CurrentThread.ManagedThreadId;
           });
        static void Main()
        {
            new Thread(() =>
            {
                for (int x = 0; x < _f.Value; x++)
                {
                    Console.WriteLine("A: {0}", x);
                }
            }).Start();
            new Thread(() =>
            {
                for (int x = 0; x < _f.Value; x++)
                {
                    Console.WriteLine("B: {0}",x);
                }
            }).Start();
            Console.ReadKey();
        }
    }
}

how to have the console program return to the first line when specified in an if statement

$
0
0

i'm new to c# i've been making a simple calculator to test my skills in c# and i was wondering is there a way to make the console to restart the console program from the first line from the start when specified.

Console.WriteLine("Do you wish to continue? type yes to continue and no to exit the program");
                    consoleContinue = Console.ReadLine();
                    if (consoleContinue == "yes")
                    {
                        
                    }
                    else
                    {
                        break;
                    }

this is the if and else statements i want to use to do this. i want the console to start over from line 1 when consoleContinue == "yes" but i don't know how to do this. any suggestions on how i could get the console to start over from line 1 without the console having to be closed then reopened? the current program looks like this:

using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Threading;
namespace Calculator
{
    class Class1
    {
        static void Main(string[] args)
        {
            int num1 = 0;
            int num2 = 0;
            double answer = 0.00;
            string sumType = " ";
            string consoleContinue = " ";
            Console.WriteLine("please enter your first value");
            num1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("please enter your second value");
            num2 = Convert.ToInt32(Console.ReadLine());
            while (true)
            {                               
                    Console.WriteLine("would you like to add, subtract, multiply or divide?");
                    Console.WriteLine("alternitavely type quit to exit the program");
                    sumType = Console.ReadLine();
                    if (sumType == "add")
                    {
                        answer = (num1 + num2);
                        Console.WriteLine("{0:0.00}", answer);
                    }
                    else if (sumType == "subtract")
                    {
                        answer = (num1 - num2);
                        Console.WriteLine("{0:0.00}", answer);
                    }
                    else if (sumType == "multiply")
                    {
                        answer = (num1 * num2);
                        Console.WriteLine("{0:0.00}", answer);
                    }
                    else if (sumType == "divide")
                    {
                        answer = (num1 / num2);
                        Console.WriteLine("{0:0.00}", answer);
                    }
                    else if (sumType == "quit")
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("please enter a valid sum type");
                    }
                    Console.WriteLine("Do you wish to continue? type " + "yes" + " to continue and " + "no" + " to exit the program");
                    consoleContinue = Console.ReadLine();
                    if (consoleContinue == "yes")
                    {
                        
                    }
                    else
                    {
                        break;
                    }
                }
            }
            }
        }       


                        

Microsoft Bot Framework with Sharepoint

$
0
0

Hi,

I am absolutely new to Microsoft's amazing Bot Framework.

I have been able to get my Echo bot running and responding nicely. Now, I am trying to integrate this bot to Office365 - SharePoint so that I can pull some data from lists and show it on my Bot's chat session (this will be again integrated to Teams channel).

Can anyone please suggest me good articles where a beginner like me could understand and implement a solution to this problem statement.

I would also be happy to receive design guidelines/instructions about Hows, Whys and Whats of this kind of integration.

Thanks,

Yogesh

Use c# to draw

$
0
0
How can I design a program,which draws a graph  with user input in a textbox.


Send keystroke like OSK

$
0
0

Hello guys, how to send key stroke like on-screen keyboard does?

Any guide or example to begin with.

Thank you.


Every second counts..make use of it. Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.

Assignment chaining - differences between C# and C++

$
0
0

I was trying to give a programming problem to an interviewee at my company and I dug out one of my old C++ problems.  It's intentionally obscure and meant to see if the candidate could read bad code, but I did not expect the code to not work when translated to C#.   The C++ code swaps two values using XOR, and it a pretty simple snippet:

#include "pch.h"
#include <iostream>

int main()
{
int a = 3;
int b = 8;

a ^= b ^= a ^= b;
std::cout << "a=" << a << " b=" << b;
getchar();

return 0;
}

The code spits out "a=8 b=3" as expected.  However, if I translate this to C#:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 3;
            int b = 8;

            a ^= b ^= a ^= b;
            Console.WriteLine($"a = {a} b = {b}");
            Console.ReadKey();
        }
    }
}

The code spits out "a=0 b=3", which is different than the C++.  Interestingly enough, if I remove the assignment chaining, and break it into 3 assignments as below:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 3;
            int b = 8;

            a ^= b;
            b ^= a;
            a ^= b;

            Console.WriteLine($"a = {a} b = {b}");
            Console.ReadKey();
        }
    }
}

Now I get the "a=8 b=3" that I expected.  So, my question is does assignment chaining have different semantics in C# than it does in C++?


Write Json To Excel

$
0
0

Dear experts

i use following code to write a Excel file from .json file

            string ofilepath = @"E:\temp\Gst2-error.json";
            OpenFileDialog fd = new OpenFileDialog();
            fd.FileName = @"E:\temp\Gst2-error.json";
            fd.Filter = "(*.json)|*.json";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                ofilepath = Path.ChangeExtension(fd.FileName, "xls");
            }
            else
            {
                MessageBox.Show("Json File Not Selected");
                return;
            }
            if (!Directory.Exists(@"c:\gstreturns"))
            {
                Directory.CreateDirectory(@"c:\gstreturns");
            }

            using (FileStream s = File.Open(fd.FileName, FileMode.Open))
            using (StreamReader sr = new StreamReader(s))
            using (JsonReader reader = new JsonTextReader(sr))
            {
                JsonSerializer serializer = new JsonSerializer();
                GSTR1 o;
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.StartObject)
                    {
                        //dynamic jr = serializer.Deserialize<dynamic>(reader);

                        o = serializer.Deserialize<GSTR1>(reader);

                        string swFileName = @"c:\gstreturns\" + GetUniqueName("b2b.csv", @"c:\gstreturns\");
                        StreamWriter sw = new StreamWriter(swFileName, cbIsAppend.Checked);

                        string monthyear = new DateTime(2018,Convert.ToInt16(o.fp.Substring(0, 2)), 1).ToString("MMM", CultureInfo.InvariantCulture);
                        monthyear += " " + o.fp.Substring(2);

                        #region b2b
                        string s1 = monthyear +"," + o.gstin,
                            s2 = "", s3 = "", s4 = "";
                        if (o.b2b != null)
                        {
                            b2bcsv(o, swFileName, sw, s1, ref s2, ref s3, ref s4);
                        }
                        #endregion b2b

                        if (o.cdn != null)
                        {
                            cdncsv(o, out swFileName, out sw, monthyear, out s1, out s2, out s3, out s4);
                        }

                        if (o.cdnr != null)
                        {
                            cdnrcsv(o, out swFileName, out sw, monthyear, out s1, out s2, out s3, out s4);
                        }
                    }
                }
            }

here i need first to create json class ( GSTR1) .

can i write excel without creating class dynamically as below. i am unable to think how i can do using following , can some body help me ?

dynamic jr = serializer.Deserialize<dynamic>(reader);



C# code samples for dynamics ms Crm

$
0
0
hi all can you guys please guide me how to learn how c# code  for dynamics MSCRM i have searched for it in google not finding which is relevant please send me the links that will be helpful for me thanks in advance

Why is there an access denied error only on latest publishing of software?

$
0
0

I seek wisdom from the Jedi Counsel, I mean Microsoft technical support and developers.

We have published many times to a Windows 2012 Server and it has always worked however upon publishing almost the exact code there is an access denied error in a module that wasn't there before.

The error comes from Log4Net not being able to access a folder on disk.

The error takes the path entered and replaces all backslashes "\\" with underscore "_" and nothing has changed in the logger for several versions.

When run locally or in azure for other clients it works and no access denied error is given.

When down grading the same client with the same version of the logger no exception exists.

The Web config points to the same folder it always has and the user is the AppPool user which is the same as it always was.

I was thinking that maybe the client gave the folder special permissions or something recently, but when I inquired he said no.

What do you believe is the problem?

C# SAX openXML how write decimal cell with the right format?

$
0
0

Hello,

I'm writing a huge excel file using openXML following the SAX approach.

i'm having problem to write decimal value into a cell, the value is correctly wrote but Excel says me that the number is stored as text and it produce the warning message 'do you want to restore the file?' as soon i open the file.

i have no problem to write any other format ( like sharedString, int etc.)

this is a part of the code:

if(columnType == typeof(decimal) )
{
    //2 = decimal, i tried also others codes
    attributes = GetCellXfsAttributes(columnNum, rowIndex, 2)
    writer.WriteStartElement(new Cell(), attributes);
    writer.WriteElement(new 
    CellValue(row[columnName].ToString()));
    writer.WriteEndElement();
}

private List<OpenXmlAttribute> GetCellXfsAttributes(int columnNumber, int rowNumber, int key = null)
   {
   var attributes = new List<OpenXmlAttribute>();
   attributes.Add(new OpenXmlAttribute("r", null, $" 
   {GetExcelColumnName(columnNumber + 1)}{rowNumber}"));
   if(string.IsNullOrEmpty(key))
   {
       attributes.Add(new OpenXmlAttribute("t", null, "s"));
   } 
   else
   {
       attributes.Add(new OpenXmlAttribute("s", null, key.toString()));
   }
    return attributes;
}

and this is part of my Stylesheet

Stylesheet workbookstylesheet = new Stylesheet();

            Stylesheet workbookstylesheet = new Stylesheet();

            Font font = new Font();         // Default font
            Fonts fonts = new Fonts();      // <APPENDING Fonts>
            fonts.Append(font); 
            Fill fill = new Fill();         // Default fill
            Fills fills = new Fills();      // <APPENDING Fills>
            fills.Append(fill); 
            Border border = new Border();   // Default border
            Borders borders = new Borders();// <APPENDING Borders>
            borders.Append(border);
            List<CellFormat> cellXfs = new List<CellFormat>();
            cellXfs.Add(new CellFormat()
                {
                    FontId = 0,
                    FillId = 0,
                    BorderId = 0,
                });
            cellXfs.Add(new CellFormat(){
                ApplyNumberFormat = true,
                NumberFormatId = 1,
            }); // 0
            cellXfs.Add(new CellFormat(){
                ApplyNumberFormat = true,
                NumberFormatId = 2,
            }); 
            // and so on each format

            // <APPENDING CellFormats>
            CellFormats cellformats = new CellFormats(cellXfs);
            #endregion

            // Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
            workbookstylesheet.Append(fonts);
            workbookstylesheet.Append(fills);
            workbookstylesheet.Append(borders);
            workbookstylesheet.Append(cellformats);

does someone help me?

WPF - Videos

$
0
0

Morning all,

I'm new to these forums so I'm hoping you can help me please.

I've recently started working with C# in Visual Studio to build an application. I've got the majoirty of it in place however, I would like to embed a YouTube video into one of the pages. I'm hoping for it to automatically display to fill the screen of my WebBrowser box in the WPF page. 

I've seen online about using WindowsForms but I was hoping to embed a video in WPF. 

Is this possible at all?

Thanks,

Andy

Retrieve chrome URL using automation Element in C# application

$
0
0
To get the chrome Url we are using Automation element in C#.Its working fine with chrome version till 67.

In recent version of chrome (68.0.3440.106 &  69.0.3497.92 ) we are facing issues to get URL .using Automation Element .please find the Code 

Kindly let me now,how to retreive the URl from Chrome recent version using Automation Element or any other option to achieve the URl from Google chrome.

AutomationElementCollection elm1 = element.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "edit"));
                        if (elm1 == null || (elm1 != null && elm1.Count == 0))


WMI Calls in C# with WBEM_FLAG_FORWARD_ONLY Flag

$
0
0
Using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
                if (searcher != null)
                {
                    ManagementObjectCollection collection  = searcher.Get();
}

To release COM object. Kindly help us how to add the Flags in C# or suggest any other method to execute the WMI Query.

Dividing a Timespan

$
0
0

Hi, 

I need to make a program that will calculate the rentalprice of a car. 

The rental price is depending on the time it will be rented. 

The cost for renting the car between 22:00 and 07:00 will be price*1.2 --> Night-rate
The cost for renting the care between 07:00 and 22:00 will be price *1 --> Day-rate

Now:

I've got 2 DateTime variables (startRent) and (endRent) 
I can make a Timespan of endRent - startRent to get the total rentalTime. 
I just need to know how I would "check" that rentalTime and divide it into 2 pieces

1) piece to calculate the cost using my night-rate

2) piece to calculate the cost using my day-rate

How would you go about checking what part of the Timespan is Night-rate and what part is Day-rate?

I hope someone can help me with this problem. 

Thanks in advance!



How Can I achieve this ?

$
0
0
Hi All,

I have the below existing code which I want to re use for my new model class "NewStocks" but the below code is tightly coupled to the class "OldStocks" and both these classes (NewStocks,OldStocks) have very less things in common
But this below logic is something that will be used in NewStock as well . Could you please suggest me some good approaches to decouple this below logic ?
  private abstract class FieldMapper
        {
            /// <summary>
            /// Gets or sets the name.
            /// </summary>
            public string Name { get; protected set; }

            /// <summary>
            /// Gets or sets the column types.
            /// </summary>
            public Table.ColumnType[] ColumnTypes { get; set; }

            /// <summary>
            /// Gets the copy value to filter delegate.
            /// </summary>
            /// <param name="table">The table.</param>
            /// <returns>The delegate.</returns>
            public abstract CopyValueToFilterDelegate GetCopyValueToFilterDelegate(Table table);

            /// <summary>
            /// Gets the copy value to table delegate.
            /// </summary>
            /// <param name="table">The table.</param>
            /// <returns>The delegate.</returns>
            public abstract CopyValueToTableDelegate GetCopyValueToTableDelegate(Table table);

            /// <summary>
            /// Set filterField to null
            /// </summary>
            /// <param name="filter">The filter to clear the field on.</param>
            public abstract void ClearFilterField(OfferFilter filter);
        }

private abstract class FieldMapper<TData> : FieldMapper
        {
           
            protected Action<OfferFilter, TData> FilterFieldSetter { get; set; }           
            protected Func<OldStocks, TData> OfferFieldGetter { get; set; }
        }

        private class TextFieldMapper : FieldMapper<string>
        {
            
            public TextFieldMapper(string name, Action<OfferFilter, string> filterFieldSetter, Func<OldStocks, string> offerFieldGetter)
            {
                Name = name;
                ColumnTypes = new[] { Table.ColumnType.Text };
                FilterFieldSetter = filterFieldSetter;
                OfferFieldGetter = offerFieldGetter;
            }
}

Microsoft Bot Framework with Sharepoint

$
0
0

Hi,

I am absolutely new to Microsoft's amazing Bot Framework.

I have been able to get my Echo bot running and responding nicely. Now, I am trying to integrate this bot to Office365 - SharePoint so that I can pull some data from lists and show it on my Bot's chat session (this will be again integrated to Teams channel).

Can anyone please suggest me good articles where a beginner like me could understand and implement a solution to this problem statement.

I would also be happy to receive design guidelines/instructions about Hows, Whys and Whats of this kind of integration.

Thanks,

Yogesh

Flags - Log files

$
0
0
Hello,
What does the entry in a text file depend on?
Sometimes I got only 
    just a number, sometimes the list with the enum names.
I see no systematics?
Maybe depend from XML file and only text file.
[Flags]
public enum StatePosition
{
	Not = 0,
	ProcessedAlready = 1,

	ProcessedAndReadIt = ProcessedAlready | 2,
	ProcessedAndNotReadIt = ProcessedAlready | 4,
	ProcessedIsBad = ProcessedAlready | 8
}

Text file output
              Currentstate
        ProcessedAndReadIt
        ProcessedAndReadIt	
                        11
						
Trace.Writeline($"{item.State,35}");	


string stateOfPosition = Convert.ToString((int)sb.State, 2).PadLeft(8, '0');					

My attempt with XML as attributes.
"ProcessedAlready ProcessedAndReadIt ProcessedAndNotReadIt"   // Same position twice, however first with read, second without.
Thanks for your help in advance.
With best regards Markus



state

Deploying Class Library

$
0
0

I have inherited a C# class library that provides add-in functionality to Dynamics GP. In fact, the VS solution includes about 15 projects, each of which holds a class library. A web search for deploying such a class library set has resulted in nothing other than copy/paste or XCOPY. Is there any way for me to provide an MSI or similar for our deployment team to install these to a particular directory? They do not need to be registered in any way, just installed to a GP directory.

Thank you in advance.

Viewing all 31927 articles
Browse latest View live


Latest Images

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