Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all 8156 articles
Browse latest View live

Strings and their memory utilization

$
0
0

I have two questions about strings

1> When we pass string as a parameter, and if the same string value is getting passed to different methods, and since strings are immutable, will .Net run time creates new instance of string every time it passes through those methods.
For example below

public class Service
{
    public void Run(string largeString)
	{
			logger.LogLargeStringToFileSystem(largeString);

			// call private method
			DoPrepWork(largeString);

			validator.Validate(largeString);

			repository.Save(largeString);
	}

	private void DoPrepWork(string largeString)
	{
	}
}


public class Validator
{
   public void Validate(string largeString)
   {
   }
}

public class Repository
{
   public void Save(string largeString)
   {
   }
}

public class Logger
{
   public void LogLargeStringToFileSystem(string largeString)
   {
      // log string to file system
   }
}

2>Can we set string to null to free up the memory? I know garbage collector eventually collects the string but I think it happens when the control goes out of the scope.So in the code below, I don’t need string variable as soon it gets converted to object. How do I immediately free up the memory occupied by the string variable. I dont want to use GC.Collect() everywhere in the code

public class Service
{
    public void Run(string largeString)
	{

			MyObject obj = ConvertToObject(largeString);

			//i dont need largeString anymore
			// the long running task may take time, so i would like to free up memory as soon as possible

			worker.DoLogRunningTask(obj);
	}
}


public class Worker
{
   public void DoLongRunningTask(MyObject obj)
   {
   }
}



ComboBox bug? SelectedValueChanged of ComboBox(binding to BindingList) doesn't raise

$
0
0

ComboBox is binding to BindingList<T>.
Repro step:

1. add item to empty BindingList<T> (click Add button)

2. clean BindingList<T> (click Clean button)

3. add item to empty BindingList<T> (click Add button)

Result:
Step1: raise SelectedValueChanged event (expected)

Step2: raise event too (expected)

Step3: no event raised (Unexpected)

Test Code:

class Program { class Data { public Data(string s) { Str = s; } public string Str { get; set; } } static void Main(string[] args) { Form form = new Form(); ComboBox cb = new ComboBox(); cb.Dock = DockStyle.Top; var list = new BindingList<Data>(); cb.DataSource = list; cb.DisplayMember = "Str"; cb.SelectedValueChanged += (s, e) => { MessageBox.Show("SelectedValueChanged"); }; Button btnClean = new Button(); btnClean.Text = "Clean"; btnClean.Dock = DockStyle.Top; btnClean.Click += (s,e)=> { list.Clear(); }; Button btnAdd = new Button(); btnAdd.Text = "Add"; btnAdd.Dock = DockStyle.Top; btnAdd.Click += (s, e) => { list.Add(new Data("xyz")); }; form.Controls.Add(btnClean); form.Controls.Add(btnAdd); form.Controls.Add(cb); form.ShowDialog(); } }



Programming

$
0
0
I am a fresher in the programming field. While coding i get much more confused about what to write what not to... would anyone can suggest about how to code efficiently?? please do help me out.

Regarding PEX

$
0
0

I am using VS 2010(.NET FW 4). When I go to "Run Pex", I am not able to see the test units made by Pex. Along with that I am getting these two errors again & again-

1. Microsoft.Pex.Engine.Libraries.MicrosoftVisualBasicLibrary+ProjectErrorRuntimeContextAttribute+Context failed to open

2. Microsoft.Pex.Engine.Libraries.MicrosoftVisualBasicLibrary+ProjectErrorRuntimeContextAttribute+Context failed to rollback.

How can I see those Test cases/units made by Pex?


Events stops firing after about 40 minutes in class library.

$
0
0

Events stops firing after about 40 minutes in class library.

I have a Taskbar application that uses a Class Library that I created that responds to Events from a Com Object and responds back  to a "Are you alive" call from the object every thirty seconds or so.

When I include my class in the main application it works fine but as a separate Class Library it stops responding to the Com Object after about 40 minutes.

Unicode string compare problem

$
0
0

I face string compare problem 

my code is like this

var itemCategory = _itemCategoryDa.ReadAll().Any(m => m.ItemCategoryName.Equals(model.ItemCategoryName, StringComparison.Ordinal));

and it return true for this two texts 

ሰሃን 

ብርጭቆ 

which is completely different words in Amharic (Ethiopian language) / Unicode 

the compare is not working, i tried different approach but it didnt any one with solution 


Binyam Welday

IFsrmClassificationManager EnumFileProperties slow first time

$
0
0

Hi,

I'm attempting to classify a file on disk immediately using the EnumFileProperties method of IFsrmClassificationManager.

When I create a new instance of FsrmClassificationManager object and call EnumFileProperties - it takes a couple of seconds to respond

If I cache the interface and call it a second time (different file), then it returns quickly (just a few ms).

It is difficult to cache the interface in our app as we have processes that go up and down and have lots of different threads that could require calling EnumFileProperties.

Does anyone know the reason why the first time takes so long? Is there a way to speed this up?

Thanks

Multithreading and Datatable

$
0
0

Hi,

I'm building an application which uses a datatable to hold some information.

The datatable is bound to a datagridview and it is constantly being updated by multiple threads.

Each thread is responsible for a unique row in the table and all rows have an owning thread.

The number of rows in the table is constant and is being determined at form initialization.

 

Most of the time, the application works just fine, though in rare occasions I get an "invalid index" exception.

An exception occurs only when the table contains huge amount of records (at least 1000) and the problematic index is always 13, for some reason.

 

In theory, the datatable is only being updated (not altered) by multiple threads, so no synchronization should be requiered here (each thread alters data only in its row).

In addition, datatables are thread-safe for reading, so binding it should not cause any issues.

 

Can someone please point on a problem in this scenario?

The only solution I could find was to lock the entire datatable at each modification (using the SyncRoot object), which makes my application run ridiculously slow.

 

Thanks,

Nir.

 

p.s.

1. The threads are being managed by the Threading.ThreadPool class.

2. The pool limits the number of threads running simultaneously to 50.

3. Each row contains independent data (retrieved separately); no thread access rows other than its own in any way.

4. The only constraint enforced by the datatable is the Primary Key constraint.

5. The column which is being used as the primary key is never being altered after form initialization.

 

 


Cannot access a disposed object. Object name : System.Net.Mail.MailMessage

$
0
0

Hi,

I am trying to send email message in C# using this MSDN article:

http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v=vs.110).aspx

but I am getting this error:

Cannot access a disposed object. Object name : System.Net.Mail.MailMessage

can anyone help please...

private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
    // Get the unique identifier for this asynchronous operation.
    String token = (string)e.UserState;

    if (e.Cancelled)
    {
        Console.WriteLine("[{0}] Send canceled.", token);
    }
    if (e.Error != null)
    {
        MessageBox.Show(String.Format("[{0}] {1}", token, e.Error.ToString()));
    }
    else
    {
        Console.WriteLine("Message sent.");
    }

    mailSent = true;
}

private static void send_message()
{
    // Command line argument must the the SMTP host.
    SmtpClient client = new SmtpClient("smtp.gmail.com");
    client.Port = 587;
    client.Credentials = new System.Net.NetworkCredential("it@mydomain.com", "my_password");
    client.EnableSsl = true;

    // Specify the e-mail sender.
    // Create a mailing address that includes a UTF8 character
    // in the display name.
    MailAddress from = new MailAddress("it@mydomain.com", "My" + (char)0xD8 + " Company", System.Text.Encoding.UTF8);
    // Set destinations for the e-mail message.
    MailAddress to = new MailAddress("jassim@mydomain.com");
    // Specify the message content.
    MailMessage message = new MailMessage(from, to);
    message.Body = "This is a test e-mail message sent by an application. ";
    // Include some non-ASCII characters in body and subject.
    string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
    message.Body += Environment.NewLine + someArrows;
    message.BodyEncoding = System.Text.Encoding.UTF8;
    message.Subject = "test message 1" + someArrows;
    message.SubjectEncoding = System.Text.Encoding.UTF8;
    // Set the method that is called back when the send operation ends.
    client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
    // The userState can be any object that allows your callback
    // method to identify this send operation.
    // For this example, the userToken is a string constant.
    string userState = "test message1";
    client.SendAsync(message, userState);
    Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
    string answer = Console.ReadLine();
    // If the user canceled the send, and mail hasn't been sent yet,
    // then cancel the pending operation.

    // if (answer.StartsWith("c") && mailSent == false)
    // {
        // client.SendAsyncCancel();
    // }

    // Clean up.
    message.Dispose();
    Console.WriteLine("Goodbye.");
}

private void btnSend_Click(object sender, EventArgs e)
{
    // XtraMessageBox.Show("You are about to send this message to all contacts!", "Send", MessageBoxButtons.OK, MessageBoxIcon.Warning);

    if (XtraMessageBox.Show("Are you sure you want to send this message to all contacts now?", "Send", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
    {
        send_message();
    }
}

Trouble with Powershell.

$
0
0

What is the best forum to file PowerShell problems?

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

Problem in short:

Using Set-PrinterProperty i get a "read-only" error when setting propery "FormTrayTable".

On Windows 2012 R2 print server

Need urgent help

AntiForgeryToken not working in IE9

$
0
0

hi Experts,

I am developing web application in asp.net mvc 5. I am using  @Html.AntiForgeryToken() inside @using (Html.BeginForm()) tag. I am also using ValidateAntiForgeryToken attribute against HttpPost action in the respective controllers. But for some reason when I open the application IE 10 then everything works fine. But the same piece of code with no change gives following error in IE9 for HttpPost.

ErrorMessage: The required anti-forgery form field "__RequestVerificationToken" is not present. | File:  | Method: ValidateTokens | LineNumber: 0 | Stack Trace:   at System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)     at System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext)     at System.Web.Helpers.AntiForgery.Validate()    at System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext)     at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)     at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState)


Can you please help me out as to what is causing this error ?

How to get the asp.net apps v2.0.50727 performance counter from C++

$
0
0

How to get the asp.net apps v2.0.50727 performance counter from C++ using COM interface?

Just don't know the Class name for 'asp.net apps v2.0.50727 '

Anyone know?

Handling "Server does not support secure connections" using an SmtpException.StatusCode?

$
0
0

I would like to attempt to send mail via SSL first, and then only if that fails, revert back to EnableSsl = false and try again.  I would prefer to check the exception for a StatusCode that indicates this, however the StatusCode that is returned is StatusCode.GeneralFailure.  The only way I can determine that it failed because of lack of secure connection support is to check the Exception.Message, which is not ideal.

The resulting code is below.  Any ideas for improvement?

try
        {
            client.Send(oMail);
        }
        catch (System.Net.Mail.SmtpException e)
        {
            //If the server does not support TLS, try again without it.
            //Exception will have a SmtpException.StatusCode.GeneralFailure, so only way to check is to check the message
            if (((System.Net.Mail.SmtpException)e).Message.Contains("secure connections"))
            {
                try
                {
                    client.EnableSsl = false;
                    client.Send(oMail);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                throw e;
            }

        }
        catch (Exception e)
        {
            throw e;
        }

How to apply rotate transform for Metafile?

$
0
0

Hi,

I tried to rotate the Metafile to 270 or 180 degree but it does not apply the rotate transform for Metafile. The blank image was return after applying the rotate transform to Metafile. And also I tried RotateFlip method to rotate the metafile but it throw Not Implement exception at System.Drawing.Metafile.

Below code snippet used in my application.

            Metafilemetafile;

            Bitmap bitmapImage =newBitmap("c:/temp/metafile.wmf");

           Graphics g = Graphics.FromImage(bitmapImage);

           IntPtr hdc = g.GetHdc();

           using (MemoryStream stream =newMemoryStream())

            {

               

 

                metafile =newMetafile(stream, hdc,EmfType.EmfOnly);

                g.ReleaseHdc(hdc);

               using (Graphics graphics =Graphics.FromImage(metafile))

                {

                    graphics.TranslateTransform(0, 0);

                         

                    graphics.RotateTransform(270);

                }

           }

Metafile.save("rotatedMetafile.wmf");

Is it have any work around to do the rotate transform for metafile? Please share your idea on this. 

Thanks,

Parthipan


ASP.NET ScriptManager and ToolkitScriptManager do not work together

$
0
0

I read some articles about ASP.NET ScriptManager and ToolkitScriptManager but I dont find the solution for my problem.
I have a webapplication with AJAX updatepanel which is working fine. Now I want add controls from AJAX Toolkit. If I insert ToolkitScriptManager then I got an error only one instance of scriptmanager allowed.

As I read I can solve the issue with the scriptmanaerproxy control. But how? I have  added more than one contentpages to ContentPlaceHolder control in masterpage.


Sourcecode in masterpage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Masterpage.Master.cs" Inherits="Test18_Updatepanel_AJAX.MAsterpage" %><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head><body><form id="form1" runat="server"><asp:ScriptManager ID="Scriptmanager1" runat="server"></asp:ScriptManager><asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager><div class="header"><h1>Header</h1></div><div class="content"><a href="default.aspx">Default</a>  <a href="index.aspx">Index</a><asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate><asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder></ContentTemplate></asp:UpdatePanel></div></form></body></html>

Sorcecode of contentpage:

<%@ Page Title="" Language="C#" MasterPageFile="~/Masterpage.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Test18_Updatepanel_AJAX._default" %><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
   Default<asp:TabContainer ID="TabContainer1" runat="server"><asp:TabPanel><HeaderTemplate>Header1</HeaderTemplate><ContentTemplate>Content1</ContentTemplate></asp:TabPanel><asp:TabPanel><HeaderTemplate>Header2</HeaderTemplate><ContentTemplate>Content2</ContentTemplate></asp:TabPanel></asp:TabContainer></asp:Content>

How can I use both scriptmanager together. Is there a link to an example available?

Many thanks.

Andreas

Not the right forum? Please inform me.


Microsoft OCR Library for Windows Runtime on a Web Application

$
0
0

Hi there,

There is a good OCR library from Microsoft that's been recently released.

I need to use that library in a web application but it looks like it can only be used by windows 8 and windows phone 8 store apps.

Is that true? Is there a work around to get that running in a web application?

Thank you,

-Serk

delete a file like jpg in window host with asp and c#

$
0
0

i want to delete a file in plesk widows host with my asp page. i tried that in visual studio and local host.that worked.but when i uploaded my site on host and tried that, i got this error :

System.UnauthorizedAccessException: Access to the path 'C:\Inetpub\vhosts\xxx\httpdocs\Images\Admin\mpic1.jpg' is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user. 

To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

what i should to do?



Desktop App: Directory.Exists returns false but new FileStream inside it works?

$
0
0

Hi,

I have a weird case with one of our deployments. The application is a Desktop .NET 4 Client Profile Winforms app that is usually started from a network share. During startup, our application does a couple of sanity checks, one of them being checks to see if the directories it requires exist and if the user running the application has write permissions in those folders etc.

The weird thing is that at one deployment only, the initial Directory.Exists check returns false, but subsequent attempts to write files inside that directory work and our application runs just fine.

To make things more interesting: Our users start a small launcher application (from the network share) that in turn starts the most up-to-date version of our program from a subdirectory. The mentioned problem with Directory.Exists returning false happens only if the program is started via the launcher. If the user starts the exe file from the subdirectory directly, then Directory.Exists on those same directories returns true.

The Launcher starts the the versioned executable via a simple Process.Start(exePath, arguments);

The erratic behaviour of Directory.Exists is really puzzling me. Any hints on what might be going on would be much appreciated!

Thanks,

Daniel

FileSystemWatcher high cpu load when no changes happen to the monitored directory (sub directories not included) if the directory contains sub folders with large volume of data.

$
0
0

My case is the following:

  1. Files are creating inside a directory by some process (about 10 files per minute with max file size 5MB each). Lets call this folder MYROOT.
  2. That files need to be moved and categorized into sub directories according some specific logic based on the file name and external settings.
  3. There will be 5 or more sub directories under the MYROOT with some sub directories inside them also, lets name them C1, C2, C3, C4, C5. And some sub directories inside them as A1, A2, A3, An...
  4. So, we will have the following categorization: C:\MYROOT\C1\A1, C:\MYROOT\C1\A2, C:\MYROOT\C2\B1 and so on...
  5. All files are written to C:\MYROOT and have the same file type and same naming convention. No renames, deletes, changes are made into this folder.
  6. I watch the MYROOT directory and then move any new created files inside to its corresponding sub directory

When the MYROOT directory is empty and files are created by another process, they are moved inside the folders as I described. The folders are only created once if they do not exist. The amount of files that exist inside the sub folders are increasing and we are talking about ~200GB and counting.

Now hear this: When no files are created (the "creator" process is not running) nothing should trigger the watcher and I can see that from logs that I enable for debugging before posting this question. But, my process containing the watcher hits a constant 13 to 14% cpu on an octa core processor and increases as the size of the sub directories increase. During processing even if I create (copy-paste) 2000 files at once goes ~1% more than that. The funny part is that when I change the monitoring path to an empty one or the same but with less volume inside it, the cpu utilization of my process is 0% and only when files are created goes to a max of 2% - 5%.

Again as said, the observation is clear, when the monitoring path sub directories contain data, that data affect the watcher internals (implementation of the ReadDirectoryChangesW API) even if you setnot to monitor the sub directories. And if that data volume is big, then high cpu resources are needed by the file system watcher. That is the same even if no changes are taking place to trigger any watcher events.

Is this the normal or by design behavior of the FileSystemWatcher?

Complete solution VS2013 project:

https://onedrive.live.com/redir?resid=3D6EA39B4180B42C!2300&authkey=!ALlFNWdLKKzvHFs&ithint=file%2czip

PS. When I monitor MYROOT folder and move the files outside that folder everything is OK, but that is not an acceptable solution, although, that is the only trick that solved me the high load of the cpu issue.

Thanx.

Marios




BindingList does not propagate property information in ListChanged event for derived types

$
0
0

If I have BindingList(Of T) and T implements INotifyPropertyChanged, every time I raise T.PropertyChanged event with property name, BindingList converts it to PropertyDescriptor, and I get this descriptor in BindingList.ListChanged event. I could hardly see the point of doing this lookup every time, but anyway, this is not my point.

The problem arises when I have a derived type D, which adds new properties. When I raise the T.PropertyChanged, when a D's property is changed, ListChanged event cannot find the property descriptor in T, and happily delivers me null in ListChangedEventArgs.PropertyDescrtiptor.

Is there anything I'm failing to see to make this work?


Mikhail

Viewing all 8156 articles
Browse latest View live


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