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

how to check date falling between two dates.

$
0
0

Hello All,

can anybody help me in resolving the problem

i have below date ranges.

01/10/2014 – 30/09/2015 
01/10/2013 – 30/09/2014
01/10/2012 – 30/09/2013 
01/01/2010 – 31/12/2011 
01/01/2006 – 31/12/2009 
before 31/12/2005

I want to check date coming from the user on which start and end date does this user date falls.

if the user given date falling in any of the above combination then i will assign the class , this class assignment is a separate logic.

I have been trying the below method , but due to multiple combination i am bit confused in it.

public void CalculateClassOnDateAndSex(DateTime targetDt, int i)
        {
            // The date range
            DateTime startDate=new DateTime(2014,10,01);
            DateTime endDate=new DateTime(2015,09,30);
            // Assuming you know d2 > d1
            if (targetDt.Ticks > startDate.Ticks && targetDt.Ticks < endDate.Ticks && i==2)
            {
               // asign class logic here...
            }  
       }

but in my code i am using only one combination , i am bit confused to use the remaining combination to be check.


Make my speech recognition click yes/no on an admin/message box

$
0
0

I need help programing my J.A.R.V.I.S. speech recognition program. I want it to click the button "Yes" when a admin/message box pop's up. ( Note I want to say the word yes/no)

For now I just put in:

if (c.Contains("yes"))

{

// WHAT DO I PUT HERE ???

}

(C is my speech input)


pasing values between C# forms

$
0
0

hi all, what is the simplest way to pass username and password values from the

main form to other forms in c#

thanks all

Sending an object over a socket (TCP)

$
0
0

Hi, I am having a very big problem with serializing. 

NetPacket message = (NetPacket)this.bf.Deserialize(ns);

The top line gives me a bad error, 

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll

Additional information: The input stream is not a valid binary format. The starting contents (in bytes) are: 00-FF-FF-FF-FF-00-00-00-00-02-00-00-00-4E-65-74-77 ...

I really do not know why. I am new to networking and the concept of binary data.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace NetworkLibraryFoo
{
    [Serializable]
    public class NetPacket
    {
        public int Type { get; set; }
        public string Message { get; set; }
        public string Name { get; set; }

        public static void SentToSocket(NetworkStream ns, NetPacket np)
        {
            BinaryFormatter formatter = new BinaryFormatter(); // the formatter that will serialize my object on my stream

            formatter.Serialize(ns, np); // the serialization process


        }

        public static NetPacket ReadPacket(NetworkStream ns)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            ns.Seek(0, SeekOrigin.Begin);

            NetPacket np = (NetPacket)formatter.Deserialize(ns);
            return np;
        }
    }
}

The top  class is a library that the server and client have. This means they will understand the object that is sent. 

        public Form2(Socket client, string userName) : this(client)
        {
            InitializeComponent();
            this.client = client;
            Thread t = new Thread(Listen);
            //t.Start();
            textBoxEnterText.ScrollBars = ScrollBars.Vertical;
            this.userName = userName;
            NetworkStream ns = new NetworkStream(this.client);
            NetPacket np = new NetPacket();
            np.Name = this.userName;
            NetPacket.SentToSocket(ns, np);
        }

The Top code is the client constructor. The client sends this to the server.

        public HandleClient(Socket client)
        {
            this.client = client;
            Program.socketList.Add(this.client);
            Console.WriteLine("I have a client");
            listenForMessageThread = new Thread(listenForMessage);
            listenForMessageThread.Start();
            NetPacket np1 = new NetPacket();
            NetworkStream ns = new NetworkStream(client);
            //  np1 = NetworkLibraryFoo.NetPacket.ReadPacket(ns);
            Thread.Sleep(1000);
            NetPacket message =
                  (NetPacket)this.bf.Deserialize
                      (ns);
            Console.WriteLine(message.Name);
            Console.Read();

           // Console.WriteLine(name + " logged in");

        }

This is the server code, where it gets the info from client. But it crashes here.

Anyone know why? 

C# code

$
0
0

Hi,

If I'm stuck with code, where do I get help?

could I get help here?

the problem too is I don`t know how to put 000.000.00.0 in the .next it won`t let it go in!

i must do this for the job entry:

You are the captain of a starship. You have been tasked with finding the 10 closest habitable planets to your home world and colonizing them.

Your home world is located at these coordinates: 123.123.99.1 X & 098.098.11.1 Y & 456.456.99.9 Z

Your coordinate system ranges from 000.000.00.0 to 999.999.99.9

1. Design and code an algorithm to randomly generate 15 000 coordinates. Each of these coordinates must be randomly marked as a planet or a very hungry space monster. (Space monsters eat starships and should be avoided at all costs)

- Each of these coordinates marked as a planet must be randomly marked as habitable or not.

- Each Habitable planet must have a surface area randomly ranging from 1 million to 100 million square kilometers.

- In order to inhabit a planet, you have to colonize more than 50% of it’s surface.

- Colonization takes place at exactly 0.43 seconds per square kilometer.

- Due to the strange construction of the star system you live in, travel time between any planet and its immediate neighbor is always 10 minutes

 Write the results to a txt file in a format of your choosing.

 2. Design and code an algorithm to read the file created in step 1 which will identify the planets you have to travel to and colonize to achieve the largest amount of colonized space within a 24-hour period.

 Give a detailed explanation of your thought processes used to solve the problem and clearly state any assumptions made.

 Complete your solution in a Visual Studio project using the C# programming language.

I do not know how to put it in it gives errors?




Use IList with JSON in WCF service

$
0
0

Hi!

I trying to create service for next json:

{"FirstId": "id1","SecondId": 3,"Mainid": "id0","event": "eventId","resource": {"id": 5,"fields": {"Custom.Field1": "Value1","Custom.Field2": "Value2","Custom.FieldN": "Value2"
       }
   }
}

I created next service:

[OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "MyFunction")]
        string MyFunction(Content Event);

An I created data contract:

[DataContract]
    public class Content
    {
        [DataMember]
        public String FirstId { get; set; }
        [DataMember]
        public int SecondId{ get; set; }
        [DataMember]
        public String Mainid { get; set; }
        [DataMember]
        public String event { get; set; }
        [DataMember]
        public Resource resource { get; set; }
    }

    [DataContract]
    public class Resource
    {
        [DataMember]
        public int id { get; set; }
        [DataMember]
        public IList<FieldInfo> fields { get; set; }
    }

    [DataContract]
    public class FieldInfo
    {
        [DataMember]
        public String name { get; set; }
        [DataMember]
        public String value { get; set; }
    }

All work fine except the "fields" member. it always has lenght 0.

How can I convert the "fields" member  to List with pair Name/Value?

AES encrypt for C# that matches Java and Javascript?

$
0
0

I have code in Javascript and code in Java that does AES encryption and works together.  That is, the Javascript code and the Java code both encrypt a given string to the same value, and can then decrypt that value to the original string.

However, I cannot get my C# code to work the same way.  Given the same string, it will encrypt it to a different value than the others.

Can anyone help me with this?

I'm mainly concerned right now with getting the Java, Javascript and C# code to all encrypt a given string to the same value.

Here is the Javascript code.  Notice that it uses CryptoJS.  The pass phrase, salt and IV I'm using are the same across all languages.

AesUtil.prototype.encrypt = function(salt, iv, passPhrase, plainText) {
  var key = this.generateKey(salt, passPhrase);
  var encrypted = CryptoJS.AES.encrypt(
      plainText,
      key,
      { iv: CryptoJS.enc.Hex.parse(iv) });
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

The Javascript code above will encrypt the string "guest" to "WsH/YEUqqrWDxD15zxsUPg==".

Here is the Java code:

    public String encrypt(String plainText, String salt, String passphrase, String iv) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
        byte[] plainTextbytes = plainText.getBytes(characterEncoding);
        //byte[] keyBytes = getKeyBytes(salt);
        SecretKey key = generateKey(salt, passphrase);
        byte[] ivBytes = hex(iv);
        return Base64.getEncoder().encodeToString(encrypt(plainTextbytes,key, ivBytes));//, Base64.DEFAULT);
    }

    private static SecretKey generateKey(String salt, String passphrase) {
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new javax.crypto.spec.PBEKeySpec(passphrase.toCharArray(), hex(salt), 10000, 128);
            SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "Rijndael");
            return key;
        }
        catch (NoSuchAlgorithmException e) {
            throw fail(e);
        }
        catch (InvalidKeySpecException e) {
            throw fail(e);
        }
    }
    public static String hex(byte[] bytes) {
        return Hex.encodeHexString(bytes);
    }

The above Java code works great with the Javascript code, and will also encrypt "guest" to "WsH/YEUqqrWDxD15zxsUPg=="

Here is the C# code:

        public String Encrypt(String plainText, String passphrase, String salt, String iv, int iterations) {
            var plainBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(Encrypt(plainBytes, GetSymmetricAlgorithm(passphrase, salt, iv, iterations)));
        }

        public byte[] Encrypt(byte[] plainBytes, SymmetricAlgorithm sa) {
            return sa.CreateEncryptor().TransformFinalBlock(plainBytes, 0, plainBytes.Length);
        }

        public SymmetricAlgorithm GetSymmetricAlgorithm(String passphrase, String salt, String iv, int iterations) {
            var saltBytes = new byte[16];
            var ivBytes = new byte[16];
            //var tempBytes = Encoding.UTF8.GetBytes(salt);
            //Array.Copy(tempBytes, saltBytes, Math.Min(saltBytes.Length, tempBytes.Length));
            Rfc2898DeriveBytes rfcdb = new System.Security.Cryptography.Rfc2898DeriveBytes(passphrase, Encoding.UTF8.GetBytes(salt), iterations);
            saltBytes = rfcdb.GetBytes(16);
            var tempBytes = Encoding.UTF8.GetBytes(iv);
            Array.Copy(tempBytes, ivBytes, Math.Min(ivBytes.Length, tempBytes.Length));
            var rij =  new RijndaelManaged(); //SymmetricAlgorithm.Create();
            rij.Mode = CipherMode.CBC;
            rij.Padding = PaddingMode.PKCS7;
            rij.FeedbackSize = 128;
            rij.KeySize = 128;
            rij.BlockSize = 128;
            rij.Key = saltBytes;
            rij.IV = ivBytes;
             return rij;
        }

Given the string "guest", it encrypts it to "F8t0D0vA2rxU3Ez1O5artA==", which is the same length as the Java and Javascript results, but not the same value, as you can see.  Also, it is not decryptable by the Java code.

How to debug win apps installed and running in remote pc

$
0
0

we have win application which was developed by c# and winform template. some time client show us a error is occurring. error message shown but though we do not understand what is actual error. so what we do that we run the win apps at our pc and debug the code to capture the error.

so i like to know is there any tiny tool which help us to debug exe code in remote pc. looking for suggestion.


How to sort this by the first string List keys = new List();

$
0
0

I want to sort keys based on the first string.  Also can someone point me to how i can do link and lambda expressions.  The key,string values will be formatted like key_name_type, key_name_value, key_something.

I am going to need to group by section of the string before the last index of _ so I can get items that have _type & _value so i can display them together.  The data is all over the place so i cant hope that sorting will solve the issue.

 List<Tuple<string, string, string[]>> keys = new List<Tuple<string, string, string[]>>();

SQLbulkcopy column conversion

$
0
0

Hi,

I am trying to use SQLbulkcopy in C# to insert XML data into SQL dataset.  Some columns in the SQL table are defined as an int32 type.  I am getting type conversion error when I use SQLbulkcopy.Columnmappings.Add method to insert XML string into column defined int32.  How can I convert SQLbulkcopy.Columnmappings.Add into int32 before insert into SQL table?

Thanks,


Brian

I need to make a simple 3 question quiz for School in c#. I need help finding out how to fix my mistakes.

$
0
0
Hi, 
first off here is the terribly written code I have mangled together:

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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What is 9+10");
            Console.WriteLine("A)19");
            Console.WriteLine("B)21");
            Console.ReadLine();
            {
                {
                    if (Console.ReadLine() == "A)19")
                        Console.WriteLine("You think you are so smart don't you");

                    else
                    {
                        Console.WriteLine("You are an idiot");
                       
                    }
                    Console.WriteLine("Which word best descibes a loop?");
                    Console.WriteLine("A)Itteration");
                    Console.WriteLine("B)Banana");
                    Console.ReadLine();
                    {
                        if (Console.ReadLine() == "A)Itteration")
                            Console.WriteLine("not bad =/");

                        else
                        {
                            Console.WriteLine("You shouldn't tell anyone about this");
                        }
                        Console.WriteLine("When you have two parametric equations, what's the name of the rule you can use to work out dy/dx?");
                        Console.WriteLine("A)Substitution rule");
                        Console.WriteLine("B)Chain rule");
                        Console.ReadLine();
                        {
                            if (Console.ReadLine() == ("B)Chain rule"))
                                Console.WriteLine("I r8 8/8");

                            else
                            {

                            }
                        }
                    }
                }
            }
        }
    }
}


Now my problem is I have no idea how to get the console to recognize my input when i type the answers to the questions and it just gives me the else message I set if I press enter. Can you all point out where I have went wrong please.

-Thanks

c# voice recognition Grammer problem

$
0
0

Hi,

I'm making some kind of a Jarvis. Now I was programming so Jarvis could look up on internet what I ask from him. Because I want to ask everything I created a new dictation grammer. ask you can see below. 

Now this is really inaccurate when I ask beer he searches for peace , when I ask Fish he searches for these.

Now my question is now how can I solve this problem? 

Do I need to make a library of words in a database? The problem then is you can't search arbitrary...  so this is also not the best way I think?

attached my code

if (r.Contains("jarvis search for")) // See if the string contains the 'search for' string.
            {
                var googleGrammar = new DictationGrammar();
                rec.LoadGrammarAsync(googleGrammar);
                Google searching = new Google();
                int indexOfSearchWords = r.IndexOf("jarvis search for") + 17; // 17 is length of "jarvis search for" +1
                r = r.Substring(indexOfSearchWords, r.Length - indexOfSearchWords); //sets r to everything in the phrase after "jarvis search for"

                words.Text = r;
                say(r);
                searching.password = r;
                searching.ShowDialog();


                return;

Help with a C# program

$
0
0

Hello everyone, I am fairly new to C#, and I am trying to add some functions to an already existing C# program. Basically what this program does is check logic loops to allow a bot to play a video game. In the existing program, there are elements of what I want to use, but I do not know how C# calls external text files and such (a function I want to use) and how to make a C# file play a sound if a condition is met.

Basically the logic I want to run through is this:

call text file: (would just have 2 card IDs)

if Hand(list from application log files which I can access) contains cardidXXX and cardidXXX (from text file)

{

play sound file

}

else

{

tell application to perform function concede(already have the code for this part)

}

Once again, I understand programming, just not the syntax behind C# and calling files with it. Any help is greatly appreciated and thank you so much!

TextFieldParser way to slow for mass csv files, is there something better?

$
0
0

I'm importing files with over 2 million records. I need something other than TextFieldParser to parse the records (some of the fields have "abc,def,ghi" fields so I need something like TextFieldParser.

Any ideas folks?

Thanks.

i have to get all attributes of elements of namespace to a string array

$
0
0
<thredds:catalog xmlns:thredds="http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0"
                 xmlns:xlink="http://www.w3.org/1999/xlink"
                 xmlns:bes="http://xml.opendap.org/ns/bes/1.0#"><thredds:service name="dap" serviceType="OPeNDAP" base="/opendap/hyrax"/><thredds:service name="file" serviceType="HTTPServer" base="/opendap/hyrax"/><thredds:service name="wms" serviceType="WMS" base="/ncWMS/wms"/><thredds:dataset name="/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014"
                    ID="/opendap/hyrax/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/"><thredds:dataset name="OMI-Aura_L3-OMTO3e_2014m0101_v003-2014m0103t013658.he5"
                       ID="/opendap/hyrax/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0101_v003-2014m0103t013658.he5"><thredds:dataSize units="bytes">3003100</thredds:dataSize><thredds:date type="modified">2014-01-03T06:48:48</thredds:date><thredds:access serviceName="dap"
                         urlPath="/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0101_v003-2014m0103t013658.he5"/><thredds:access serviceName="wms"
                         urlPath="?DATASET=lds/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0101_v003-2014m0103t013658.he5&amp;SERVICE=WMS&amp;VERSION=1.3.0&amp;REQUEST=GetCapabilities"/></thredds:dataset><thredds:dataset name="OMI-Aura_L3-OMTO3e_2014m0102_v003-2014m0104t004027.he5"
                       ID="/opendap/hyrax/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0102_v003-2014m0104t004027.he5"><thredds:dataSize units="bytes">3030178</thredds:dataSize><thredds:date type="modified">2014-01-04T05:49:18</thredds:date><thredds:access serviceName="dap"
                         urlPath="/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0102_v003-2014m0104t004027.he5"/><thredds:access serviceName="wms"
                         urlPath="?DATASET=lds/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0102_v003-2014m0104t004027.he5&amp;SERVICE=WMS&amp;VERSION=1.3.0&amp;REQUEST=GetCapabilities"/></thredds:dataset><thredds:dataset name="OMI-Aura_L3-OMTO3e_2014m0103_v003-2014m0105t013415.he5"
                       ID="/opendap/hyrax/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0103_v003-2014m0105t013415.he5"><thredds:dataSize units="bytes">3019723</thredds:dataSize><thredds:date type="modified">2014-01-05T06:49:33</thredds:date><thredds:access serviceName="dap"
                         urlPath="/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0103_v003-2014m0105t013415.he5"/><thredds:access serviceName="wms"
                         urlPath="?DATASET=lds/HDF-EOS5/Aura_OMI_Level3/OMTO3e.003/2014/OMI-Aura_L3-OMTO3e_2014m0103_v003-2014m0105t013415.he5&amp;SERVICE=WMS&amp;VERSION=1.3.0&amp;REQUEST=GetCapabilities"/>
i need to get the name attributes to array. I tried 
XmlDocument doc = new XmlDocument();
        doc.Load("D:\test.xml");


        XmlNodeList elemList = doc.GetElementsByTagName("thredds:dataset");

        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine("{0}\n",elemList[i].InnerXml);
        } 
but i want only specific name of file. how to get it? please help me. thank you




Change clause to plain text

$
0
0

Hi, 

I have no coding experience but have some code I'm using with a data sync tool. 

The issue is I'm trying to reference a field called 'from' within the code, but it seems to be starting a from clause. How do I get the from to just display as plain text (seems to be blue when it's a clause, black when plain text)

Apologies for the terrible terminology. I understand it probably isn't called plain text.  

string[] NewToValues = DataSchemaTypeConverter.ConvertTo<string[]>(this.from);

this.from is where the issue lies. 

Print PDF file from winform client installed on RDC or VDI using local printer (TS Easy Print)

$
0
0

Dears,

I'm working on a legacy application using winform (.net 4.0 & c#).

The client application is installed on a machine accessible only via RDC or VDI. The OS is Windows 7 or higher.

The client application must be able to print PDF files from that machine to the local printer (local or network) installed on the client machine. This means that the printer selected via RDC is a redirected printer using the TS easy print drivers. Those drivers don't allow the usage of RAW printing.

The printing method used before were:

- Copy of the files directly on the UNC of the printer (\\printername\dc)

- Usage of ImportDll and calls to OpenPrinter, StartDocPrinter, WritePrinter, ....

Both of those solutions don't work anymore because:

- The network printers are not on the same domain anymore and therefore not accessible directly from the RDC.

- The WritePrinter method don't work anymore since the easy print drivers don't understand RAW printing.

So, here comes my question. How can I print on those printer? Do I have to create an EMF file for the printing? If yes, how can I use my PDF file and create an EMF file containing the information? Is there other solutions (modifying the group policy is not an option since we don't want to install the drivers of the different clients that will connect)?

In last resort, the usage of a library could be foreseen but a long discussion with the management will be necessary (so I hope other solutions exists). Is there some library that you could advice?

Thanks in advance,

Benoit Delfosse
Senior .Net Developer/Architect

Windows 10 WinRT

$
0
0
Hi, i'm currently coding a Windows Runtime Component class, the one used to interact with cortana in Windows 10. I need to get the UserName of the User logged in the system. Just like what the Environment.UserName which is not available in WinRT. I found this class https://msdn.microsoft.com/en-us/library/windows/apps/windows.system.user.aspx but i dont know how to use it properly since there are no sample codes. i also tried using system.Environment.GetEnvironmentVariable("UserName"). and Is there a forum for cortana development? thanks

taskbar alteration

$
0
0
how do i get taskbar back to original

Date Format match between client and server

$
0
0
Am posting an object from client to server via AJAX in ASP Net which consist of date Property too.MY Machine's time zone uses the date format **MM/dd/yyyy** in string whereas my server time zone uses the format **dd/MM/yyyy**.Am still wondering that how do the conversion takes place properly and it works as expected result which gets saved in the database.
Say for example am posting a value from client 02/01/2016(MM/dd/yyyy) in string which gets changed properly in server to 01/02/2016(dd/MM/yyyy). How do they know that the incoming value was in (MM/dd/yyyy) and then parses to (dd/MM/yyyy).
Let me know if i was wrong/misunderstood.
Viewing all 31927 articles
Browse latest View live


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