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

Garbage collector: behavior with class instances & events

$
0
0

Hello everybody,

I have a small question about memory usage. When there are no longer references to an instance of a given class, can it be "garbage collected" even if I subscribed to static event handler from it ? Here is a small example as it's difficult to me to explain:

publicclassMyClass{publicdelegatevoidOnItemSavedHandler;publicstaticeventOnItemSavedHandlerOnItemSaved;publicMyClass(){OnItemSaved+=MyClass_OnItemSaved;}voidMyClass_OnItemSaved(){...}}

If yes, I could implement a destructor to unsubscribe from event handler.

But I want to keep active subscribtion to event handler as long as the object lives.

I read a lot of things about that but the examples I found are too complicated for me.

Thanks in advance for your help.


LINQ to XML with xmlns

$
0
0

<?xml version="1.0" encoding="utf-8" ?><Reports><Detail>

<Table1><Grade xmlns="numeric">0</Grade>

    <ShortDateFormat:Start_Date xmlns:ShortDateFormat="datetime">9/15/2016</ShortDateFormat:Start_Date>

</Table1></Detail></Reports>

XDocument studentData = XDocument.Load(pathToExcelFile);
XNamespace num = "numeric";
XNamespace shortDate = "ShortDateFormat";
var students = (from item in studentData.Descendants("Table1")
                select new
                {
                    grade = item.Element(num + "Grade").Value,
                    startDate = item.Element(shortDate + "Start_Date").Value
                }).ToList();
I am able to retrieve "Grade" but how would the "Start_Date" element be parsed?

UI development recommandation for .NET version

$
0
0

Hi,<o:p></o:p>

We are migrating the UI part for JEFE Application. Currently, JEFE application GUI is developed in Java/JRE and dependent on JRE version. We need to remove the JRE version so new UI development will be Microsoft technology.<o:p></o:p>

We need recommendation from this forum based on your experience for UI development to make this project success.<o:p></o:p>

Thanks,<o:p></o:p>

Chirag Patel<o:p></o:p>



ckp

Encrypt with certificate - SHA512

$
0
0

Hi all,

I'm encrypting/decrypting data with a self-created certificate using SHA512 algorithm.

I've used the following code to create the certificate:

makecert -r -pe -n "CN=MyCertificate" -a sha512 -b 09/01/2016 -sky exchange C:\Temp\MyCertificate.cer -sv C:\Temp\MyCertificate.pvk
pvk2pfx.exe -pvk C:\Temp\MyCertificate.pvk -pi "MyP@ssw0rd" -spc C:\Temp\MyCertificate.cer -pfx C:\Temp\MyCertificate.pfx -po "MyP@ssw0rd"


After that I've imported successfuly the certificate into my local root authority store.

In C#, I run the following code without any problem:

string input = "test";
            string output = string.Empty;

            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection collection = store.Certificates.Find(X509FindType.FindBySubjectName, "MyCertificate", false);

            X509Certificate2 certificate = collection[0];

            using (RSACryptoServiceProvider cps = (RSACryptoServiceProvider)certificate.PublicKey.Key)
            {
                byte[] bytesData = Encoding.UTF8.GetBytes(input);
                byte[] bytesEncrypted = cps.Encrypt(bytesData, false);
                output = Convert.ToBase64String(bytesEncrypted);
            }

            store.Close();

This works very well, but I'm wondering, if I'm specifying SHA512 algorithm for the certificate, shouldn't I also use SHA512CryptoServiceProvider in order to encrypt data?

If I replace RSACryptoServiceProvider with SHA512CryptoServiceProvider this doesn't work. Am I not understanding anything here or am I missing something?

Thank you.

How to access SOAP exception in a Task fault

$
0
0

We have a client application which hits some older services. The client application will call multiple service methods asynchronously. Sometimes the service returns a SOAP exception. The client application needs access to the SOAP exception. Can this be done when executing multiple Tasks asynchronously?

Below, the client needs the SOAP exception where the Console.Write is

var allTasks = new List<Task>();

var t1 = client.methodOneAsync(eaRequest1);
allTasks.Add(t1);

var t2 = client.methodTwoAsync(eaRequest2);
allTasks.Add(t2);

var t3 = client.methodThreeAsync(eaRequest3);
allTasks.Add(t3);

try
{
    Task executeTasks = Task.WhenAll(allTasks);
    executeTasks.Wait();
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

Update:

The service's WSDL has a Fault exception schema which is extending a basic SOAP fault. The extended fault has an array of messages. The generated reference classes have these objects. However, when the fault occurs, they are not populated. The fault does have a Detail of the classname[], however, the array is empty.

Sort by multiple columns, ordering type and the columns to be sorted which will be selected by user ?

$
0
0

Hi everyone,

I have an IQueryable<MyObject>.

In MyObject, i have there propreties:

class MyObject{
   string firstName;
   string lastName;
   string mail;
   string city;
   int old;
}

I want to sort my IQueryable<MyObject> by multiple columns. And the ordering type and the columns to be sorted which will be selected by user.

If i use the if else condition or switch case,  i have write 243 conditions like that :

if(orderByFirstName=="A-Z" && orderByLastName="A-Z" && orderByOld = "A-Z" && orderByMail="A-Z" and orderByCity ="A-Z"){
   persons = persons.OrderBy(p => p.firstName).ThenBy(p => p.lastName).ThenBy(p => p.old).ThenBy(p => p.mail).ThenBy(p => p.city);
}
//243 conditions for all cases
else if ...{
...
}

Can you please help me find a solution ?

Thanks in advanced,

Best Regards,

Cao


How make set up file include Crystal report , database in C#

$
0
0

Hi Everyone,

i am new to programming, i am working on a project, it is almost finished now i want to create an exe file which includes database and crystal report, i searched for many article over internet but i could find a single article regarding my question,

so please help me how to do this,

please waiting for a positive reply 

thanks


MohammedKhadir

Process.Exit event is not fire

$
0
0
Hi ,

i'm working on c# ,i run an  another .exe using Process .But after i  close the .exe, the process.exit event is not fire..

Dim prcinfo As ProcessInfo = new ProcesInfo(@D:/Folder/File1.exe)
prcinfo.UseShellExecute= true
prcinfo.WorkingDirectory=@"filepath"
prcinfo.argument=@"//d//d/d/d"

 Dim process1 As Process= new Process(prcinfo)
 process1.EnableRaisingEvent =true
 process1.Exited += new EventHandler( RuntheMethod11)
 process1.WaitForExit()
 process1.Close()



Visual C#

$
0
0

Hi again guys. I have a little problem, heres what i did :

int x, y;
            Console.WriteLine("Ievadiet veselu skaitli x - ");
            x = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Ievadiet veselu skaitli y - ");
            y = Convert.ToInt32(Console.ReadLine());

            float dalisana1;
            Console.WriteLine("Summa {0} + {1} = " + (x + y), x, y);
            Console.WriteLine("Atnemt {0} - {1} = " + (x - y), x, y);
            Console.WriteLine("Reizinat {0} * {1} = " + (x * y), x, y);
            Console.WriteLine("Dalit (dalisana vesela dala) {0} / {1} = " + (x / y), x, y);
            Console.WriteLine("Dalit (dalisanas atlikums) {0} % {1} = " + (x % y), x, y);
            Console.WriteLine("Dalit (dalskaitlis) {0} / {1} = " + ((float)x / y), x, y);
            Console.WriteLine("Kvadrata " + Math.Pow(x, 2) + " + " + Math.Pow(y, 2) + " = " + (Math.Pow(x, 2) + (Math.Pow(y, 2))));

This is the task :

Create a program that requires you to enter two integer numbers x and y, and outputs the following activities

results : 

1)x+y

2)x-y

3)x*y

4)x/y

5)x%y

6)x/y (fraction)

7)x2+y2 (2 = square)

 

Im Latvian and dont look at that language.

 

ERROR_MORE_DATA exception thrown by DirectorySeacher

$
0
0

I have developed an application that talks to the Directory Server and gets user information.

This application is a generic one and can talk to Active Directory or Any other Directory Services.

In one case where i use this application to read data from Radiant One VDS, the application fails with the ERROR_MORE_DATA. Following is the code that returns this error:

try
{
  using (DirectoryEntry de = new DirectoryEntry("LDAP://" + server + "/" + basedn, username, pwd,AuthenticationTypes.None))
  {
    using (DirectorySearcher Searcher = new DirectorySearcher(de))
    {
      Searcher.Filter = "(&(objectClass=user))";
      Searcher.ReferralChasing = ReferralChasingOption.All;
      Searcher.PropertiesToLoad.Add("cn");
      Searcher.PropertiesToLoad.Add("memberof");
      Searcher.PageSize = 1000;

      using (SearchResultCollection allUsers = Searcher.FindAll())
      {
        foreach (SearchResult user in allUsers)
        {
          .
          .
          .
          .
        }
      }
    }
  }
}
catch(System.Exception ex)
{
}

In the above code ERROR_MORE_DATA is thrown When the code tries to go through the foreaach loop. i searched and found the below article.

https://support.microsoft.com/en-us/kb/833789

But, this article talks about .NET 1.0 and my application runs with .NET 3.5

Can you anyone please help me here? Is there any way to fix this without going for DirectoryServices.Protocols?

Thanks in advance.


Best practice for loading multiple dynamic services and them dependencies services

$
0
0

I want to devleop a custom system for my self.

I want to loading custom services by configuratin with dependency services - for example:

<Services><Service name="ServiceA" args="" type="IServiceA" dependencies=""/><Service name="ServiceB1" args="" type="IServiceB1" dependencies="ServiceA"/><Service name="ServiceB2" args="" type="IServiceB2" dependencies="ServiceA"/><Service name="ServiceC1" args="" type="IServiceC1" dependencies="ServiceA,ServiceB1"/><Service name="ServiceC2" args="" type="IServiceC2" dependencies="ServiceA,ServiceB2"/><Service name="ServiceD" args="" type="IServiceD" dependencies="ServiceA,ServiceB2,ServiceC2"/><Service name="ServiceE" args="" type="IServiceE" dependencies="ServiceA,ServiceB2,ServiceC2,ServiceD"/><Service name="ServiceF" args="" type="IServiceF" dependencies="ServiceA,ServiceB1,ServiceC1,ServiceD,ServiceE"/></Services>

All those services are implement custom interface:

public interface IService { bool Start(); bool Stop(); bool IsReady {get;}

 event EventHandler Stopped; }

I perform a topological sort and i getting:

Level 0: ServiceA
Level 1: ServiceB1, ServiceB2
Level 2: ServiceC2, ServiceC2
Level 3: ServiceD
Level 4: ServiceE
Level 5: ServiceF

So i loop every level and start a services...
It's good enough?

var sortedGroups = PerformLogicalSort();
foreach (var group in sortedGroups)
{
	List<Task<bool>> tasks = new List<Task<bool>>();
	foreach (var module in group.Value)
	{
		var task = Task.Factory.StartNew<bool>(() =>
		{
			try
			{
				Console.WriteLine("TaskUserWorkItem " + module.Id +" is started...");
				module.Start();
				while (!module.IsReady)
				{
					Console.WriteLine("TaskUserWorkItem " + module.Id + " still not ready..");
					Thread.Sleep(1000);
				}
				Console.WriteLine("TaskUserWorkItem " + module.Id + " is ready..");
				if (module.Dependencies != null && module.Dependencies.Count > 0)
				{
					foreach (var depend in module.Dependencies)
					{
					  dependModule.Stopped += (a, b) =>
						{
							if (IsShuttingDown)
								return;

							if (!module.IsReady)
								return; //has been stoped allready

							module.Stop();

							while (!DependenciesReady(module.Dependencies))
							{
								Console.WriteLine("Module " + module.Id + " Postponed until all its dependecies will be ready");
								Thread.Sleep(1000);
							}

							Console.WriteLine("all dependecies of Module " + module.Id + " are ready.");
							Console.WriteLine("TaskUserWorkItem " + module.Id + " is started...");
							module.Start();
						};
					}
				}
				return true;
			}
			catch (Exception e)
			{
				Console.WriteLine(e.ToString());
			}
			return false;
		});
		tasks.Add(task);
	}
	bool connected = true;
	Task.Factory.StartNew(()=>
	{
		while(connected)
			Console.WriteLine("Level " + group.Key +" : still not ready");
	});
	Task.WaitAll(tasks.ToArray());
	connected = false;
	foreach (var task in tasks)
	{
		if (!task.Result) return;
	}
}



Image Segmentation of mri brain tumor using c#

$
0
0
I need help how to develop a system to segment a mri of brain tumor using c#.

WSDL generates a class called System that invalidates System.Xml, System.ComponentModel etc

$
0
0

Hello,

I have a WSDL that I generated proxies for.   One of the proxies classes created was MyNamespace.System.

A snippet of the proxies is below.

namespace MyNamespace

{

     [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1067.0")]
     [System.SerializableAttribute()]
     [System.Diagnostics.DebuggerStepThroughAttribute()]
     [System.ComponentModel.DesignerCategoryAttribute("code")]
     [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://mysite.com/canonical/v2")]

     public partial class System { etc }

}

All of the proxy classes have the same attributes etc.

When I try to compile I get the following error:

The type XML does not exist in the type MyNamespace.System.   

Why a vendor would supply a WSDL with their own System class makes no sense to me.

That's not the namespace I want it to refer to.  How do I fix it so it refers to my System.XML or System.ServiceModel references in my project?

Thank you very much!!

Jim

Task continuation in async method.

$
0
0

I have an async method which in a couple spots calls a method which returns a Task (which is not started), I then add a continuation (which closes over several objects) on that task reference. I then start the original task and perform other work. Later I await the original task when desired.

The IDE marks this as CS4014, I know I can assign the continuation to an unused variable but I assume there is a better way. I do not want to handle an error when I await the task (or its continuation), if an error occurs in the primary task I want to handle it at once. What am I missing?

Task task = GetUnstartedTask(foo, bar, myManualResetEvent); task.ContinueWith( antecedent => { // Signal termination within other tasks. myCancellationTokenSource.Cancel(); // Observe and report the exception, then close app down. }, TaskContinuationOptions.OnlyOnFaulted);

task.Start() // Do some other work that interacts with the above running task. // Once that is done, signal the running task to end. myManualResetEvent.Set() // Wait for task to end. await task.ConfigureAwait(false);


Run windows tray application when system boots up

$
0
0

I have developed a windows tray application which acts as HUB to manage requests, I have routed it to startup, and so starts automatically when user logs into PC and stops when user logs off.

(Did create a windows service earlier but had to switch to tray app due to installation issues and other corporate permission issue.)

Is there any way, can we configure to start this tray app when system boots up (like windows service works without logging in).


shrik36


My feedback about disposing

$
0
0

I want that compiler when compile program check if all diposable object was disposed and do not compile program if it is not or show warning.

This is my feedback to Microsoft. I don't know where to write my idea.

Read All Events using ManagementEventWatcher(WMI query) in C# - Help me read all Event properties

$
0
0

Hi All,

I have tried to read all windows events from all Event logs using ManagementEventWatcher with WMI query. I could collect and read all those event's properties. I have used the below code for collecting event and read its properties. I can read all properties mentioned in this link- https://msdn.microsoft.com/en-us/library/aa394226%28v=vs.85%29.aspx

CODE:

WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance ISA 'Win32_NTLogEvent'");
 ManagementEventWatcher eventWatcher = new ManagementEventWatcher();
eventWatcher.Query = query;

ManagementBaseObject eventObject = eventWatcher.WaitForNextEvent();
PropertyData targetInstanceProData = eventObject.Properties["TargetInstance"];
          if ((targetInstanceProData != null))
               {
                    ManagementBaseObject targetInstanceObject = targetInstanceProData.Value as ManagementBaseObject;
                    PropertyDataCollection proDataCollection = targetInstanceObject.Properties;
                     foreach (PropertyData proData in proDataCollection)
                         {
                                Console.WriteLine("PropertyName: " + proData.Name +" || Value: " + proData.Value);
                         }
                }

Here i have missed out to read few Event properties and its values from Event. I could not found any methods/properties to read properties in Friendly view and Xml view of Event viewer. So i could not read the below Event properties and values in Event Log.


Help me to read all properties of event showing under friendly and xml view.

Is it possible or Is any other way to achieve?. I want to read all Event properties.

Thanks

Satheesh






An object reference is required for the non-static field, method, or property

$
0
0

Hello everyone, good afternoon too

I was trying to create a class to improving the code but i received the error that i need to create a reference, however i create but now the TextBox text and the text of button doesn't change... what should i do to solving this problem ?

private static void SelectDirectory()
{

Form1 FR = new Form1(); FR.checkDiretorioButton.Text = "Directory"; FR.PathDiretory.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + path;

}

Other question, when the method will be called many times with over time the content of the last class variable will be destroyed? or the program will create another reference?




Taking a certain value from a different line in a text file

$
0
0

Hello,

I have a text file that has this structure:

1|2|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:55:35|x

1|2|3

4|5|6

END-OF-LINE

5|7|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:42:35|y

7|8|9

1|4|5

END-OF-LINE

Records

I want to take the value of the date which is in index 10 (24 Sep 2016 02:42:35)

and put it in a variable named y and then use it depending on the file structure

Sometimes the file only consists of this

1|2|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:55:35|x

1|2|3

4|5|6

END-OF-LINE

I made a snippet for this, using the help of your Answers, but now the value that is written in the variable y is always the same

how can i change it depending on the line i am reading from. In other words. If i am reading from this line: 

1|2|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:55:35|x

Variable Y should equals 24 Sep 2016 02:55:35

else 

If i am reading from this

5|7|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:42:35|y

Variable Y should equals 24 Sep 2016 02:42:35

Here is the snippet. Thanks in Advance

var templines1 = File.ReadAllLines(fileName).ToList();


                        int currentLine1 = 0;
                        while (currentLine1 < templines1.Count)
                        {
                            // Peek ahead for the END-OF-LINE to get the name of the file.
                            int terminatorLine1 = templines1.IndexOf("END-OF-LINE", currentLine1);

                            if (terminatorLine1 <= 0) break; // If not found, or no penultimate line

                            int penultimateLine1 = terminatorLine1 + 1;


                             if (templines1[penultimateLine1].Length > 11)
                            {
                                var fields1 = templines1[penultimateLine1].Split('|'); // get the comma separated fields
                                y = fields1[10];
                             //   Console.WriteLine(y);

                            }
                             currentLine1 = terminatorLine1 + 1;
                             goto Assign;
            }

Convert HTML saved emails to msg files

$
0
0

Is there a way to convert emails, that were saved from outlook as HTML files, to msg files? Without having to manually open in outlook and save as msg's?

Viewing all 31927 articles
Browse latest View live


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