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

C# beginner question

$
0
0

Picture 1.


Picture 2.

Sorry for my English in advance.

 I made method for checking if all pieces are in base or goal if yes it returns true,now i need another method.

If its like on Picture 1. i need to change number of throws to 3 ,if its ordered like on Picture 2 i can allow only 1 throw.

I got 4 goalPositions and 4 piecePositions,and need to check if pieces are ordered on them from 54-51 path positions(path is array of 55 fields 0-54) ,if yes return true if not return false.

I am new to C# never had chance to work with order checking till now.

Any help is appreciated.

I was trying to do it with 3 int lists goalPositions (populated with 51,52,53,54 path positions),piecePositions(populated with pieces positions with getPosition()),and piecesOnGoal. but no luck with that.

ill add some code. part of player class with that lists and method for checking pieces in goal or base  


class Player
    {
        protected PieceSet[] pieces;
        Color color;
        int numberOfThrows;
        Dice dice;
        public List<int> goalPositions;
        public List<int> piecePositions;
        public List<int> piecesOnGoal;

        public enum Color
        {
            Yellow, Green, Blue, Red
        }

        public Player(Color color)
        {
            int[] path = new int[55];
            this.color = color;
            dice = new Dice();
            numberOfThrows = 3;
            switch (color)
            {
                case Color.Yellow:
                    path = BoardHelper.getYellowPath();
                    break;
                case Color.Green:
                    path = BoardHelper.getGreenPath();
                    break;
                case Color.Blue:
                    path = BoardHelper.getBluePath();
                    break;
                case Color.Red:
                    path = BoardHelper.getRedPath();
                    break;
            }
            pieces = new PieceSet[4];
            pieces[0] = new PieceSet(path, 0);
            pieces[1] = new PieceSet(path, 1);
            pieces[2] = new PieceSet(path, 2);
            pieces[3] = new PieceSet(path, 3);

            piecePositions = new List<int>(4);
            piecePositions.Add(pieces[0].getPosition());
            piecePositions.Add(pieces[1].getPosition());
            piecePositions.Add(pieces[2].getPosition());
            piecePositions.Add(pieces[3].getPosition());

            goalPositions = new List<int>(4);
            goalPositions.Add(51);
            goalPositions.Add(52);
            goalPositions.Add(53);
            goalPositions.Add(54);


        }
public bool isAllPiecesInBaseOrGoal()
        {
            if ((pieces[0].getPosition() < 4 || pieces[0].getPosition() > 50) &&
               (pieces[1].getPosition() < 4 || pieces[1].getPosition() > 50) &&
               (pieces[2].getPosition() < 4 || pieces[2].getPosition() > 50) &&
               (pieces[3].getPosition() < 4 || pieces[3].getPosition() > 50))
                return true;
            else
                return false;
        }

and this is how i was thinking to solve my problem ,check if goalPositions contains piecePositions  if yes add that position into piecesOnGoal ...now i need somehow to check are that piecesOnGoal are ordered if yes return true if not false.

I am open for any suggestion.

public bool isAllPiecesAreOrderedInGoal()
        {
            for (int i = 0; i < 4; i++)
            {
                if (goalPositions.Contains(piecePositions[i]))
                {
                    piecesOnGoal.Add(piecePositions[i]);
                }



            }
        }




Datetime truncated on exporting to CSV

$
0
0

case 1:
I have something like this on the UI screen
 5/30/2015 10:09:48 AM .... This is getting converted to 5/30/2015 10:09
I am using DateTime type in the get, set and converting it to string while exporting

case 2:
00:00:40.020 (hh:mm:ss:milliseconds)  is getting converted to00:40.0
Using a TimeSpan type for get, set

(There is no problem exporting to pdf)
How can I prevent this for CSV export. I need the total datetime on exporting. Please help!!

SignedXml.CheckSignature always returns false when for correct SOAP message

$
0
0

Hi All,

Thanks in advance.

I am struggling since many days.

1. When I create SignedXML with my own code and try to validate it . It's working fine but when I am getting the SOAP message from other party (which is  working perfect with other JAVA plaftform we have verified.) SignedXml.CheckSignature always giving false result. I tried many options (including reflector for checking source code for SignedXML) but coudn't get any clue.

2. Following is the format of SOAP message with WS-Security which I need to verify (without using WCF framework).

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soap:mustUnderstand="1">
      <wsse:BinarySecurityToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="CertId-11465961">MIID+jCCAuKgAwIBAgICBrowDQYJKoZIhvcNAQEFBQAwPzELMAkGA1UEBhMCU0UxEjAQBgNVBAoTCVN0ZXJpYSBBQjEcMBoGA1UEAxMTU3RlcmlhIEFCIEVJRCBDQSB2MjAeFw0xMzA1MTMxMTE1MDdaFw0xNTA3MTMxMDMwMDNaMGUxCzAJBgNVBAYTAlNFMRwwGgYDVQQKFBNM5G5zZvZyc+RrcmluZ2FyIEFCMRMwEQYDVQQLEwo1NTY1NDk3MDIwMSMwDAYDVQQDEwVMRkxpdjATBgNVBAUTDDE2NTU2NTQ5NzAyMDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAumKsk/yZOfi9886w4GmTcCLdF9YE2Y97vB8Db77ifzABW3ovK3n+yC7ZI626j85hu9Elh08winNPXm9Tv6yU9PuOal18rwIHLer8zvcYgAmSCj7ND+dVezkOKSmNi6ZUGkk0vYaY6rD1bb+YOofcDnDy3TUlMwK8Ml3U9QR/VKsCAwEAAaOCAVwwggFYMB8GA1UdIwQYMBaAFJCAgCvzWv1A2zP4Uyk8pNbR7osoMB0GA1UdDgQWBBSL1qEqD6UDpPsfDRw/UQ3NkyMYJDAOBgNVHQ8BAf8EBAMCBkAwIwYDVR0RBBwwGoEYc3Nla0BsYW5zZm9yc2FrcmluZ2FyLnNlMBUGA1UdIAQOMAwwCgYIKoVwNgkCDQEwgZUGA1UdHwSBjTCBijBDoEGgP4Y9aHR0cDovL2NkcDIuc3RlcmlhLnNlL2NkcC9laWQvU3RlcmlhJTIwQUIlMjBFSUQlMjBDQSUyMHYyLmNybDBDoEGgP4Y9aHR0cDovL2NkcDEuc3RlcmlhLnNlL2NkcC9laWQvU3RlcmlhJTIwQUIlMjBFSUQlMjBDQSUyMHYyLmNybDAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnN0ZXJpYS5zZS8wDQYJKoZIhvcNAQEFBQADggEBAGxhYvom44znVwgNWXZDnklcotlSAPo17C47aMJq9NylMXHSLqYhfjUwRL7Ig6K128StiBhMLG8KbLXE0hgUIEmT/+NYUnlWozC621fxZXIk8sjTFWfcECkXQ1B7sIEYHBiOHlJHyvYINQIetLZgLPzaO4wu2/HWvO/TfXRb0KK4Omix1733YswCylM0ZoZr+meZAmMVTdXkKwSLDw1+xa6IYLTPWNDcl1Ox0lkyYLraVw5R3ihZFLwvn6MApm0OXfuX8dOGiGpXvi8ejwp39Txy9RsBPUYsJcKXW+YQ8Vh9QqF/7Oizy3IW9tzb3IHm6ZYs8C5hH1BVmo4A2Ga8hBs=</wsse:BinarySecurityToken>
      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
          <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod>
          <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
          <ds:Reference URI="#id-533766178">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
            <ds:DigestValue>9rVto1vy/hNACyla+vwnJIGExJk=</ds:DigestValue>
          </ds:Reference>
          <ds:Reference URI="#id-968960127">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
            <ds:DigestValue>T1jD9YbuXbf3l65Abuf9Xw8f6fE=</ds:DigestValue>
          </ds:Reference>
          <ds:Reference URI="#id-944359288">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
            <ds:DigestValue>O9rnP0RRV2Dcy70SRRmU1A7lqB4=</ds:DigestValue>
          </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>
          HACu8a2cc3fm2VDE7ri1vCSeT8ozENo0//BJTAt4RiNQYKxIeka1kWAMZHeHOhRu7V9rnNF+zlLt
          /4fOnaMzEhruRQIJG/DCgUACnb070Mh2fwquAqFOsdpH98kc9We5tHYwfnDufoV8mZozomQ5ex2P
          flcE25QjymvXodg5pP0=
        </ds:SignatureValue>
        <ds:KeyInfo Id="KeyId-1977405101">
          <wsse:SecurityTokenReference xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="STRId-1938095182">
            <wsse:Reference URI="#CertId-11465961" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"></wsse:Reference>
          </wsse:SecurityTokenReference>
        </ds:KeyInfo>
      </ds:Signature>
      <wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-968960127">
        <wsu:Created>2015-06-23T11:15:32.012Z</wsu:Created>
        <wsu:Expires>2015-06-23T11:51:32.012Z</wsu:Expires>
      </wsu:Timestamp>
    </wsse:Security>
    <ssek:SSEK xmlns:ssek="http://schemas.ssek.org/ssek/2006-05-10/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-944359288" ssek:AsynchMethod="AsynchPush" soap:mustUnderstand="1">
      <ssek:SenderId ssek:Type="CN">XXXX</ssek:SenderId>
      <ssek:ReceiverId ssek:Type="CN">XXXX</ssek:ReceiverId>
      <ssek:TxId>deadbeef-9a71-41ca-af2d-a7a333006de8</ssek:TxId>
    </ssek:SSEK>
  </soap:Header>
  <soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-533766178">
    <testOk xmlns="urn:SSEKTestOk" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <hello>KUNDAN test</hello>
    </testOk>
  </soap:Body>
</soap:Envelope>

3. Following is the code which I written.

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.ObjectModel;


namespace VerifyOnlySignature
{
    class Program
    {
        static void Main(string[] args)
        {

            string Certificate = "CN=KundanKServer";
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = false;
            xmlDocument.Load(@"D:\kundan\RnD\BizTalkSSEK_POC\VarifySignature\SampleFiles\BizTalk_SSEK_Out_S_and_P.xml");
            X509Certificate2 cert = GetCertificateBySubject(Certificate);
            SignedXmlWithId signedXml = new SignedXmlWithId(xmlDocument);
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature", SignedXmlWithId.XmlDsigNamespaceUrl);
            signedXml.LoadXml((XmlElement)nodeList[0]);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXmlWithId.XmlDsigExcC14NTransformUrl;
            bool resultSign = signedXml.CheckSignature(cert, true);
            Console.WriteLine(resultSign.ToString());
            Console.ReadKey();
        }

        public static X509Certificate2 GetCertificateBySubject(string CertificateSubject)
        {
            if (null == CertificateSubject)
                throw new ArgumentNullException("CertificateSubject");
            X509Certificate2 cert = null;
            X509Store store = new X509Store("My", StoreLocation.LocalMachine);
            try
            {
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                // Get the certs from the store.
                X509Certificate2Collection CertCol = store.Certificates;

                // Find the certificate with the specified subject. 
                foreach (X509Certificate2 c in CertCol)
                {
                    if (c.Subject == CertificateSubject)
                    {
                        cert = c;
                        break;
                    }
                }

                // Throw an exception of the certificate was not found. 
                if (cert == null)
                {
                    throw new CryptographicException("The certificate could not be found.");
                }
            }
            finally
            {
                // Close the store even if an exception was thrown.
                store.Close();
            }

            return cert;
        }
    }

    public class SignedXmlWithId : SignedXml
    {



        public SignedXmlWithId(XmlDocument xml)
            : base(xml)
        {
        }

        public SignedXmlWithId(XmlElement xmlElement)
            : base(xmlElement)
        {
        }

        public override XmlElement GetIdElement(XmlDocument doc, string id)
        {
            // check to see if it's a standard ID reference
            XmlElement idElem = base.GetIdElement(doc, id);

            if (idElem == null)
            {
                XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
                nsManager.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

                idElem = doc.SelectSingleNode("//*[@wsu:Id=\"" + id + "\"]", nsManager) as XmlElement;

            }

            return idElem;

        }



    }

}

Regards

Kundan

Store and Display data in a Particular Format using C#

$
0
0

Hello All;

I want to save the data in this format while clicking a Save Button in the form. I have the Form like this as shown in the fig. below:- 

What i have is when i enter some text box next to Enter Profile Name, and click the Create Profile button, it will add item to 1st listbox namely,lb_ProfileList. Now when i select projects from the 2nd listbox and check the item in 1st listbox it will show the items selected in 2nd listbox to 3rd listbox (lb_Selectedprojects). Now when i click the Save Profile button the items will be saved in the File ProfileList.txt.  

I want to store the data in this format:- 

(1) Item from 1stListbox(ABCD)  #Project1 #Project2 #Project3(Projects from 3rdListbox)

(1) Item from 1stListbox(EFGH)  #Project4 #Project5 #Project6(Projects from 3rdListbox).

How to save in above format to the file. I have written code like this :- but it is not storing the data in above format. 

 private void bn_SaveProfile_Click(object sender, EventArgs e)
        {

           const string spath = "ProfileList.txt";
            System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(spath,false);

 foreach (var profileitem in lb_ProfileList.Items)
            {

                SaveFile.Write(profileitem + " ");
                //SaveFile.WriteLine();
                foreach (var selecteditems in lb_SelectedProjects.Items)
                {
                    SaveFile.Write("#" + lb_SelectedProjects.Items);
                }

            }
            SaveFile.WriteLine();

            SaveFile.Close();

            MessageBox.Show("Profile Saved");
}


Tanmay

2nd call to InternetExplorer ie in new ShellWindows() fails

$
0
0

I am using the following C# code to automatically populate and validate a web page:

namespace Web_Browser_Manipulation

{
    public partial class Form1 : Form
    {
    AutoResetEvent waitHandle = new AutoResetEvent(false);

    public Form1()
    {
        InitializeComponent();
    }

    public void ie_DocumentComplete(object pDisp, ref object URL)
    {
        InternetExplorer ie = pDisp as InternetExplorer;
        ie.DocumentComplete -= ie_DocumentComplete;
        waitHandle.Set();
    }

    private void UploadSignature(string Nome_SW, string Codice_SW, string Codice_Conc, string Codice_Gioco)
    {
        foreach (InternetExplorer ie in new ShellWindows())
        {
            if (ie.LocationURL.Contains("aams"))
            {
                int index = FindLineIndex(Codice_Conc, Codice_Gioco);
                ie.DocumentComplete += ie_DocumentComplete;

                if (index != -1)
                {
                    ie.Document.GetElementsByTagName("option")[index].SetAttribute("selected", "true");
                    ie.Document.GetElementsByTagName("input")["aggiungi"].Click();

                    ie.Document.GetElementById("num").SetAttribute("value", "1");
                    ie.Document.GetElementsByTagName("input")["prepara"].Click();
                    ie.Document.GetElementById("nome_sftw1").SetAttribute("value", Nome_SW);
                    ie.Document.GetElementById("cod_sha11").SetAttribute("value", Codice_SW);
                    ie.Document.GetElementsByTagName("input")["Acquisisci"].Click();
                }
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        UploadSignature("Nome1", "1234567890123456789012345678901234567890", "15023", "1");
        waitHandle.WaitOne();
        UploadSignature("Nome2", "1234567890123456789012345678901234567891", "15023", "1");
        waitHandle.WaitOne();
    }
}

The code works great, however, when the function "UploadSignature" is called the 2nd time, the "InternetExplorer ie" fails and therefore the program crashes (it raises an exception:'(((SHDocVw.InternetExplorer)(ie)).Document).baseUrl' generated 'System.NotImplementedException' and fileCreatedDate = '(((SHDocVw.InternetExplorer)(ie)).Document).fileCreatedDate' generaed 'System.Runtime.InteropServices.COMException'). When the program reaches the line

ie.Document.GetElementsByTagName("option")[index].SetAttribute("selected", "true");

it crashes.

I really do not mange to figure out why. Could anyone help? Thank you so much for any hint you might provide!



Meeting Invite (iCalendar) does not block the time for Resources (Meeting Room)

$
0
0

I am trying to send a meeting invite through C# application using iCalendar format. Though i mentioned the Resource and Location details, it is not blocking the time in the Resource Calendar. Time is blocked for normal users only...Anyone know how to fix the issue

My code is as foll

public void SendMail()
        {
            StringBuilder sw = new StringBuilder();
            sw.AppendLine("BEGIN:VCALENDAR");
            sw.AppendLine("PRODID: -//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN");
            sw.AppendLine("VERSION:2.0");
            sw.AppendLine("METHOD:REQUEST");
            sw.AppendLine("BEGIN:VEVENT");
            sw.AppendLine("CLASS:PUBLIC");
            sw.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmss}", DateTime.UtcNow));
            sw.AppendLine("DESCRIPTION: " + "Hello");
            sw.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmss}", DateTime.UtcNow.AddHours(1)));
            sw.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmss}", DateTime.UtcNow.AddHours(2)));
            //sw.AppendLine(string.Format("DTSTART;VALUE=DATE:{0:yyyyMMdd}", DateTime.UtcNow));
            //sw.AppendLine(string.Format("DTEND;VALUE=DATE:{0:yyyyMMdd}", DateTime.UtcNow.AddDays(1)));
            sw.AppendLine(string.Format("ORGANIZER;CN=\"{0}\":MAILTO:{1}", "xxxx", "xxxx.com"));
            sw.AppendLine(string.Format("ATTENDEE;ROLE=REQ-PARTICIPANT;CN=\"{0}\";RSVP=TRUE:mailto:{1}", "xxx", "xxx.com"));
            sw.AppendLine(string.Format("ATTENDEE;ROLE=NON-PARTICIPANT;CN=\"{0}\";CUTYPE=RESOURCE;RSVP=TRUE:mailto:{1}", "IT Conference Room", "Room.com"));
            sw.AppendLine(string.Format("ATTENDEE;ROLE=OPT-PARTICIPANT;CN=\"{0}\";RSVP=TRUE:mailto:{1}", "yyy", "yyy.com"));
            sw.AppendLine("SEQUENCE:4");
            sw.AppendLine("UID:" + Guid.NewGuid().ToString());
            //if (lblIntLocation != null && lblIntLocation.Text != "")
            sw.AppendLine("LOCATION:" + "IT Conference Room");
            //if (lblCandidateName != null && lblCandidateName.Text != "")
                sw.AppendLine("SUMMARY;LANGUAGE=en-us: Scheduled for " + "candidate 1");
           // else
              //  sw.AppendLine("SUMMARY;LANGUAGE=en-us: Scheduled");
            sw.AppendLine("PRIORITY:5");
            sw.AppendLine("TRANSP:OPAQUE");
            sw.AppendLine("X-Microsoft-CDO-BUSYSTATUS:BUSY");
            sw.AppendLine("X-MICROSOFT-CDO-IMPORTANCE:1");
            sw.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:FALSE");
            sw.AppendLine("X-MS-OLK-APPTLASTSEQUENCE:1");
            sw.AppendLine("X-MS-OLK-AUTOFILLLOCATION:TRUE");
            sw.AppendLine("X-MS-OLK-CONFTYPE:0");
            sw.AppendLine("BEGIN:VALARM");
            sw.AppendLine("TRIGGER:-PT15M");
            sw.AppendLine("ACTION:DISPLAY");
            sw.AppendLine("DESCRIPTION:Reminder");
            sw.AppendLine("END:VALARM");
            sw.AppendLine("END:VEVENT");
            sw.AppendLine("END:VCALENDAR");
            string from = "xxx.com";// SPContext.Current.Web.Site.WebApplication.OutboundMailSenderAddress;

            string smtpAddress = SPContext.Current.Web.Site.WebApplication.OutboundMailServiceInstance.Server.Address;

            // Assign SMTP address
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = smtpAddress;

            MailMessage mailMessage = new MailMessage("abcd.com", "xxx.com,yyy.com,Room.com");
            mailMessage.Subject = "NEW BOOKING";

            // Create the Alternate view object with Calendar MIME type
            System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar;method=REQUEST; name=myCalendar.ics; filename=myCalendar.ics");

            //Provide the framed string here
            AlternateView avCal = AlternateView.CreateAlternateViewFromString(sw.ToString(), ct);
            mailMessage.AlternateViews.Add(avCal);

            smtpClient.Send(mailMessage);
        }

I tried making the room as required participant, but it is still not blocking the time in the conference room calendar.

How can I write a variable to a textbox?

$
0
0

I am trying to write a variable to a textbox. I keep getting a null exception.

debugging          display_line_1.Text = (CHRstring);

        display_line_1 = null

        CHRstring = xyz

The variable isn't null when debuging, the textbox is but so......?

I'm missing something here so simple I can't see it.

Any valuable assistance would be appreaciated.

Thanks

tac


tac

TCP socket class no replied

$
0
0

ok here is my TCP connection code :

            //sck.Bind(new IPEndPoint(0, 1234));

            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(IP_AddressTXT.Text), Convert.ToInt16(IP_PortTXT.Text));
                sck.Connect(localEndPoint);
                //sck.h
            }
            catch( Exception e)
            {
                MessageBox.Show("Unable to connect to remote end point! ", e.Message);
                return;
            }
            MessageBox.Show("Connected to : " + IP_AddressTXT.Text);
            Enter1.Text = "connected...";  }

so that part works .. it connects...

here is my send code :

  public void Send( byte[] buffer, int offset, int size, int timeout)
        {
            int startTickCount = Environment.TickCount;
            int sent = 0;  // how many bytes is already sent

                try
                {
                    sent = sck.Send(buffer);
                }
                catch (SocketException ex)
                {
                    MessageBox.Show("error", ex.Message); // any serious error occurr
                }
        }


I used WireShark says I am sending this :

0000   00 90 e8 30 f8 e0 34 e6 d7 15 0d d5 08 00 45 00  ...0..4.......E.
0010   00 30 3c a3 40 00 80 06 60 fa a9 fe 08 2d a9 fe  .0<.@...`....-..
0020   01 01 fe 20 10 a4 a6 74 fa 75 17 c7 ca e0 50 18  ... ...t.u....P.
0030   40 29 17 9a 00 00 01 03 01 a6 00 01 65 d5        @)..........e.

The 01 03 a6 00 01 65 d5 is my modbus message. I am not sure what everything else is.

This is what I am getting back from the Moxa on Wireshark:

0000   34 e6 d7 15 0d d5 00 90 e8 30 f8 e0 08 00 45 00  4........0....E.
0010   00 28 16 ec 40 00 80 06 86 b9 a9 fe 01 01 a9 fe  .(..@...........
0020   08 2d 10 a4 fe 85 09 13 68 d7 c4 1c 89 ee 50 10  .-......h.....P.
0030   83 24 00 66 00 00 00 00 00 00 00 00              .$.f........

but when I go to read that message and when I call the function Receive the program just sits there and does not do anything

here is my read function :

public void Receive(byte[] buffer, int offset, int size, int timeout)
    {
        int startTickCount = Environment.TickCount;
        int received = 0;  // how many bytes is already received
        //sck.Listen(100);
            try
            {

                received = sck.Receive(buffer);
            }
            catch (SocketException ex)
            {
                MessageBox.Show("error", ex.Message);
            }
        processingData(buffer);
    }

what am I doing wrong? why does it just sit at received = sck.Receive(buffer); and never does anything ?



Close or hide a form from another form, C#

$
0
0
i have form1 and form2. In the form1 a have a button1 who open form2. Then i want to press again on  button1. when i press again on button1 i want to colse/hide form2 then reopen the form 2. So i want to know how can i hide a form, from another form and check if that form is already opened

Setup Wizard tries to install to wrong framework version

$
0
0

Hi, 

I've created simple one line Console application for the 3.5 framework and was attempting to try out the "Visual Studio Installer" setup wizard project to install on a server. Both Console and "Setup Wizard"are for the .net 3.5 framework however when I try the setup.exe on the target server I get a message regarding 4.5 framework pre-requisites.  

Any ideas where this reference to 4.5 is likely to be coming from?

Thanks  


The following properties have been set:
Property: [AdminUser] = true {boolean}
Property: [InstallMode] = HomeSite {string}
Property: [NTProductType] = 3 {int}
Property: [ProcessorArchitecture] = Intel {string}
Property: [VersionNT] = 5.2.2 {version}
Running checks for package 'Microsoft .NET Framework 4.5 (x86 and x64)', phase BuildList
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full'
Unable to read registry value
Not setting value for property 'DotNet45Full_TargetVersion'
The following properties have been set for package 'Microsoft .NET Framework 4.5 (x86 and x64)':
Running checks for command 'DotNetFX45\dotNetFx45_Full_x86_x64.exe'
Result of running operator 'ValueEqualTo' on property 'InstallMode' and value 'HomeSite': true
Result of checks for command 'DotNetFX45\dotNetFx45_Full_x86_x64.exe' is 'Bypass'
Running checks for command 'DotNetFX45\dotNetFx45_Full_setup.exe'
Result of running operator 'ValueNotEqualTo' on property 'InstallMode' and value 'HomeSite': false
Skipping ByPassIf because Property 'DotNet45Full_TargetVersion' was not defined
Result of running operator 'ValueEqualTo' on property 'AdminUser' and value 'false': false
Result of running operator 'VersionLessThan' on property 'VersionNT' and value '6.0.0': true
Result of checks for command 'DotNetFX45\dotNetFx45_Full_setup.exe' is 'Fail'
'Microsoft .NET Framework 4.5 (x86 and x64)' RunCheck result: Fail
A prerequisite failed for Package "Microsoft .NET Framework 4.5 (x86 and x64)"
Package failed with message "Installation of the Microsoft .NET Framework 4.5 is not supported on this operating system. Contact your application vendor."


C# Costum Permission throws exception when loading other AppDomain using MAF

$
0
0

Hi,

i am trying to enable our application for extensibility by using MAF Framework. We are using .Net 4.5 and our UI technology is WPF. 

As shown in the Picture, we load the Add-Ins into a seperate AppDomain. The Add-In Infrastructure does the Add-In discovery, creates the AppDomain and then activates the Add-Ins (every Add-In has its own AppDomain). The Add-In gets a reference to the API-Instance, which it can use to execute business logic. Different Add-Ins should now have different permissions for executing API Functions. Therefore i created my own permission, more or less as describted herehttps://msdn.microsoft.com/en-us/library/ff647073.aspx . I did all steps beside the last one, as this seems only be an example for web applications. I have registered the Permission DLL in GAC. I also have build an Permission Attribute which i then added to my function in the API. I tested my application and the Permission was checked correctly and producted a Security Exception as intended, because the Add-In AppDomain has nearly no permissions and the permission checks the complete call stack. So for so good.

Now i have added the new permission to the permission set of the Add-In AppDomain. When the MAF tries now to activate an Add-In in the Add-In AppDomain, i am getting the following exception:

Could not load file or assembly 'AddInInfrastructure.Contract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79837fedfd04b150' or one of its dependencies.

Normally the MAF Contract does not make any problems. It does not have a direct nor indirect dependecy to the permission.

I have also put the Permission assembly into Add-In AppDomains base folder, but that doesn't make a difference as permission assemblies are anyhow only taken from GAC.

It is somehow strange, as no assembly from within the Add-In Appdomain is referencing this assembly.

Does anyone has an idea how to solve this?

Kind Regards,

Tobi

This is the complete error message (i have just only shorten namespaces and paths):

System.IO.FileLoadException: Could not load file or assembly 'AddInInfrastructure.Contract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79837fedfd04b150' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)
File name: 'AddInInfrastructure.Contract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79837fedfd04b150' ---> System.Security.SecurityException: Request failed.
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
   at System.Security.Util.XMLUtil.CreatePermission(SecurityElement el, PermissionState permState, Boolean ignoreTypeLoadFailures)
   at System.Security.SecurityElement.ToPermission(Boolean ignoreTypeLoadFailures)
   at System.Security.PermissionSet.CreatePerm(Object obj, Boolean ignoreTypeLoadFailures)
   at System.Security.PermissionSet.CreatePermission(Object obj, Int32 index)
   at System.Security.PermissionSet.InplaceIntersect(PermissionSet other)
   at System.Security.PermissionListSet.UpdateDomainPLS(PermissionSet grantSet, PermissionSet deniedSet)
   at System.Security.CodeAccessSecurityEngine.UpdateAppDomainPLS(PermissionListSet adPLS, PermissionSet grantedPerms, PermissionSet refusedPerms)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.PermissionSet
The demand was for:<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>

The granted set of the failing assembly was:
<PermissionSet class="System.Security.PermissionSet"
version="1"><IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="RestrictedMemberAccess"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/><IPermission class="AddInBackendApi.Permissions.CostItem.CostItemPermission, AddInBackendApi.Permissions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79837fedfd04b150"
version="1"
Unrestricted="True"/></PermissionSet>

The assembly or AppDomain that failed was:
System.AddIn, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
The Zone of the assembly that failed was:
MyComputer
The Url of the assembly that failed was:
file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.AddIn/v4.0_4.0.0.0__b77a5c561934e089/System.AddIn.dll
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at System.AddIn.Hosting.ActivationWorker.Activate()
   at System.AddIn.Hosting.ActivationWorker.Activate()
   at System.AddIn.Hosting.AddInActivator.ActivateInAppDomain[T](AddInToken pipeline, AppDomain domain, AddInControllerImpl controller, Boolean weOwn)
   at System.AddIn.Hosting.AddInActivator.Activate[T](AddInToken token, AppDomain target)
   at System.AddIn.Hosting.AddInActivator.Activate[T](AddInToken token, AppDomain target)
   at System.AddIn.Hosting.AddInToken.Activate[T](AppDomain target)
   at AddInInfrastructure.Provider.AddInProvider.ActivateAddIns(IList`1 addInTokens) in c:\[...]\Extensibility\AddInInfrastructure\AddInProvider\AddInProvider.cs:line 118

How can i draw the shape with vml path and equation infomration using GDI+?

$
0
0

Hi Everyone,

I have to draw the vml shapes for mage conversion. I have all the information regarding vml shape, path and equations. But the provided path information were like m@7,l@8,m@5,21600l@6,21600e

in all the resources m - move to , l - line to, qx -ellipticalqaudrantx, etc., Can you all please help me for how i can achieve this functionalists with gdi+

Thanks,

Pradeep L

how to animate paticular listbox items in windows 8 phone when selected

$
0
0
want to animate listbox items when selected (animation like sliding or turnstile)

System.Net.WebExceptionStatus.ProtocolError When I rename a file on an FTP server

$
0
0

Hi!

I'm making a program to rename an XML file on an FTP server and gives me the following error

`The remote server returned an error: (501) Syntax error in parameters or arguments`

I get to see the error and see the following Status `System.Net.WebExceptionStatus.ProtocolError`

The program I have developed with `Microsoft Visual C # 2010 Express`.

I tested this program with `Windows 7` and it works correctly, but testing the program in `Windows XP` does not work, and the program has to work with `Windows XP`.

Do I have to download some library or install something extra on `Visual C # 2010` or on `Windows XP`?

My program is this:

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

     FtpWebRequest request = null;

            string filename = "FI_SINC_QH60_S16104_20150615115359.XML;1";

           request = ((FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://10.160.190.175/" + filename)));

           request.Credentials = new NetworkCredentialuser, pass);

            string newfileame = filename.Replace(";1", "_OLD");

           request.Method = WebRequestMethods.Ftp.Rename;

           request.RenameTo = newfileame;

           request.GetResponse();

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

and the error is this:

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

    Not monitored System.Net.WebException

    Message=The remote server returned an error: (501) Syntax error in parameters or arguments.

    Source=System

     StackTrace:

       at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)

       at System.Net.FtpWebRequest.RequestCallback(Object obj)

       at System.Net.CommandStream.Dispose(Boolean disposing)

       at System.IO.Stream.Close()

       at System.IO.Stream.Dispose()

       at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)

       at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse)

       at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)

       at System.Net.FtpWebRequest.GetResponse()

       at WindowsFormsApplication1.Form1..ctor() in C:\Documents and Settings\SAM844\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 41

       at WindowsFormsApplication1.Program.Main() in C:\Documents and Settings\SAM844\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 18

       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)

       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

       at System.Threading.ThreadHelper.ThreadStart()

    InnerException:

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

Any Ideas??

Thanks for the help

C# AXL Soap write Per index.

$
0
0

Hi All,

Can some one help me with the folloring problem.

I have the following AXL/Soap output:

<speeddials>
            <speeddial index="1">
              <dirn>00621806350</dirn>
              <label>jan Mobiel</label>
              <asciiLabel />
            </speeddial>
            <speeddial index="2">
              <dirn>00383326777</dirn>
              <label>Jan Thuis</label>
              <asciiLabel />
            </speeddial>
            <speeddial index="3">
              <dirn>00886607000</dirn>
              <label>jAN wERK</label>
              <asciiLabel />
            </speeddial>
          </speeddials>

So a you can see I have tree speeddial with <speeddial index="1">;

i have the following partial code:


                foreach (var item in respdoc.Descendants("speeddial"))

                {



                    textBox4.Text = ((string)item.Element("dirn"));

                    textBox5.Text = (string)item.Element("label");

                }

I get the last in my textbox but I want the first one.

Thanks

Regards,

Jan Meeling


UTILDEFS.H equivalent in c#

$
0
0

Hi,

I am converting c++ project to c#. In c++ methods like 'ar_get_latest','ar_loadslv'and 'ar_init_slave'are been used which belongs to UTILDEFS.H. Which c# dll ll comprise methods mentioned above?

Issue in Web Browser User Control Timer

$
0
0

Hi Greetings,

I am facing a problem in user Control Timer and is stuck for almost 1 month now.

I have a User control with web browser which can open any website . In my case it is opening our clients website page. They have a File upload dialog box in their website. On every event (mouse up,mouse down etc) we get from the web browser we are resetting the timer .

Now the issue is when a user clicks the file upload dialog box the timer is not getting reset because none of the events are captured when the dialog box is open. As a result the transaction time outs even though the user is using the application.

Can anyone please help me out of this.

Thanks in advance,

Karthika Rajendran

Error "m_safecertcontext is an invalid handle" in "system.security.cryptography.pkcs" when I deploy the solution on azure

$
0
0

Hi, I am develop a aplication using azure. My problem is that in my local pc this is working good, but when I publish this on azure is throwing this error "m_safecertcontext is an invalid handle", here I am showing my code:

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

try
            {
                X509Certificate2 certFirmante = CertificadosX509Lib.ObtieneCertificadoDesdeArchivo();


                // Convierto el login ticket request a bytes, para firmar 
                Encoding EncodedMsg = Encoding.UTF8;
                byte[] msgBytes = EncodedMsg.GetBytes(XmlLoginTicketRequest.OuterXml);
                
                // Firmo el msg y paso a Base64 
                byte[] encodedSignedCms = CertificadosX509Lib.FirmaBytesMensaje(msgBytes, certFirmante);

                cmsFirmadoBase64 = Convert.ToBase64String(encodedSignedCms);
            }

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

when I call this method trhow the error.

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

public static byte[] FirmaBytesMensaje(byte[] argBytesMsg, X509Certificate2 argCertFirmante)
        {
            try
            {
                
                // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms) 
                ContentInfo infoContenido = new ContentInfo(argBytesMsg);
                SignedCms cmsFirmado = new SignedCms(infoContenido);

                // Creo objeto CmsSigner que tiene las caracteristicas del firmante 
                CmsSigner cmsFirmante = new CmsSigner(argCertFirmante);
                cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;

                // Firmo el mensaje PKCS #7 
                cmsFirmado.ComputeSignature(cmsFirmante);

                // Encodeo el mensaje PKCS #7. 
                return cmsFirmado.Encode();
            }
            catch (Exception excepcionAlFirmar)
            {
                throw new Exception("***Error al firmar: " + excepcionAlFirmar.Message);
            }
        }

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

Similarly, for this code to work, I had to include the library "System.Security". I try to copy locally, but do not take me azure.

I need your help, I do not know what else to try!!!!!

Note: sorry for my english.


Pdf Viewer

$
0
0

hey, this is my Pdf Viewer. As being difference from the others, pdf is firstley saved in database and called as datagridview. And I wantto use datagridview event cellclik. but i couldnt. Help me?

DatagridView Cellclik code;

kmt = new OleDbCommand("select * from Stok where Serino=" + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "", bag);
                bag.Open();
                OleDbDataReader oku = kmt.ExecuteReader();
                oku.Read();
                if (oku.HasRows)
                {
                    axAcroPDF1.src = oku[2].ToString();
                    id = Convert.ToInt32(oku[0].ToString());
                }
                bag.Close();
            

The method in the builder/compilation file Don't exist

$
0
0

Problem:
When I build/compile the C# project, it contains alot of different methods. When you review the object browser, the specific method that you added in the sourcecode do not exist in the compile/build file.

Do you have any idea for troubleshooting?

Thank you!

Describing what Object browser is below.


Viewing all 31927 articles
Browse latest View live


Latest Images