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

Create Signature field in PDF

$
0
0

Hi ,

  I want to develop create signature field in PDF document , and draw signature on pdf by using c#  


Error mesage when I run a SQLite command - Database is locked.

$
0
0

Hi all,

I have some code, but it shows me an error when I run it.

Werror msg: The database file is locked database is locked

My code:

try
{
    string query = "UPDATE Table1 SET column1 = @col1 WHERE columnID = @colID AND column2 = @col2;";
    using (SQLiteConnection con = new SQLiteConnection(conString))
    {
        con.open();
        using (SQLiteCommand cmd = new SQLiteCommand(query, con))
        {
            foreach (Data d in list)
            {
                cmd.Parameters.AddWithValue("@col1", d._date);
                cmd.Parameters.AddWithValue("@col2", String.Empty);
                cmd.Parameters.AddWithValue("@colID", d._clientID);
                cmd.ExecuteNonQuery();
            }
        }
    }
}
catch(Exception ex)
{
    MessageBox.Show("Error : " + ex.Message);
}

Can you see the problem? Whats wrong?

Why is copying 10 items to an observable collection so slow and how to speed up?

$
0
0

This code operates in a .NET WPF C# environment. The basic code creates a collection of about 10 objects. The collection is sorted and then copied. When the copy happens the time to execute adds an astonishing 7 seconds. The observable collection does not have any subscribers at this point so one would not expect any time to be lost due to broadcast change notifications.

The application is based on a WinForm used to create a System Tray Notification item. When the tray icon is clicked upon a WPF window is shown. At the time that the WPF window becomes visible a DispatcherTimer is created and started. A short delay after that and a web service call is made which collects information which is written into userItems, a local variable. This collection will be passed back to the caller who will put it into a class property that will be bound to the source for a ComboBox. This code works well and fast. There is a problem with it, however, in that the contents of the ComboBox drop down list are not sorted. I thought that it would be trivial to handle that by sorting the contents of the userItems before it is passed back to the caller. Not so, sneaker breath. Here's the important part of the code:

// A local variable is declared.
ObservableCollection<UserItem> userItems = null;

// Snipped from the code is the initial population of userItems.

// A sorted copy of userItems is created. This is quick.
List<UserItem> lui = userItems.OrderBy( a => a.user_id ).ToList();

// The original collection is emptied so that it can be populated with the
// sorted elements.
userItems.Clear();

// The sorted list of items, only about 10 objects, is copied back to userItems.
// This is where the time is being spent, an astonishing 7 seconds to copy 10 items.
// If the copy is commented out then the code runs in almost no time at all.
for (int x = 0; x < lui.Count; x++)    userItems.Add( lui[x] );

Any ideas why the above code fragment runs so slowly and how can I speed it up?


Richard Lewis Haggard


How to use Parallel.Foreach for my scenario

$
0
0

please see my code and tell me how to use Parallel.Foreach for my scenario and my code

                    //Parallel.ForEach(OrderWiseLineItem, data =>
                    foreach (var data in OrderWiseLineItem)
                    {
                        // string Li = data1.LineItem;
                        string section = data.Section;
                        string Li = data.Lineitem;

                        if (!String.IsNullOrEmpty(Li) && !String.IsNullOrEmpty(section))
                        {
                            //Parallel.ForEach(DistinctBroker, broker =>
                            foreach (var broker in DistinctBroker)
                            {
                                //lock (_lock)
                                //{
                                    // for broker row .... weightage 1 (no color)
                                    rowNumber = rowNumber + 1;
                                    //Interlocked.Increment(ref rowNumber);
                                    brokerRowWeightageRowNumber = new WeightageRowNumber();
                                    brokerRowWeightageRowNumber.Section = section;
                                    brokerRowWeightageRowNumber.Lineitem = Li;
                                    brokerRowWeightageRowNumber.Broker = broker;
                                    brokerRowWeightageRowNumber.RowNumber = rowNumber;
                                    brokerRowWeightageRowNumber.Weightage = (int)RowWeightage.BrokerRow;
                                    //WeightageRowNumberall.Add(brokerRowWeightageRowNumber);
                                    WeightageRowNumberall.Add(brokerRowWeightageRowNumber);
                                //}
                            }

                            //lock (_lock)
                            //{

                                // for Consensus row .... weightage 2 (red color)
                                rowNumber = rowNumber + 1;
                                //Interlocked.Increment(ref rowNumber);
                                ConsensusRowWeightageRowNumber = new WeightageRowNumber();
                                ConsensusRowWeightageRowNumber.Section = section;
                                ConsensusRowWeightageRowNumber.Lineitem = Li;
                                ConsensusRowWeightageRowNumber.Broker = "";
                                ConsensusRowWeightageRowNumber.RowNumber = rowNumber;
                                ConsensusRowWeightageRowNumber.Weightage = (int)RowWeightage.ConsenSusRow;
                                //WeightageRowNumberall.Add(ConsensusRowWeightageRowNumber);
                                WeightageRowNumberall.Add(ConsensusRowWeightageRowNumber);
                                //liitemsearchdata.Add(Li + "~" + section + "~" + rowNumber.ToString());
                                //data.Lineitem + "~" + data.Section + "~" + (data.RowNumber + 1).ToString()
                            //}


                            if (qcTrueDistin.Any(x => x.TabName.Equals(section) && x.StandardLineItem.Equals(Li)))
                            {
                                // for QC Check row .... weightage 3, if any  (yellow color)
                                //Parallel.ForEach(DistinctBroker, broker =>
                                foreach (var broker in DistinctBroker)
                                {
                                    //lock (_lock)
                                    //{

                                        //Interlocked.Increment(ref rowNumber);
                                        rowNumber = rowNumber + 1;
                                        QcRowWeightageRowNumber = new WeightageRowNumber();

                                        QcRowWeightageRowNumber.Section = section;
                                        QcRowWeightageRowNumber.Lineitem = Li;
                                        QcRowWeightageRowNumber.Broker = broker;
                                        QcRowWeightageRowNumber.RowNumber = rowNumber;
                                        QcRowWeightageRowNumber.Weightage = (int)RowWeightage.QcRow;
                                        WeightageRowNumberall.Add(QcRowWeightageRowNumber);
                                    //}

                                }
                            }
                        }

                    }

also tell me how to force parallel foreach to init or assign data order wise ?

i used parallel foreach but getting error in other part of same function. hence my function is too big and that is why i can not paste the whole code rather paste the paralle.foreach part only.

C# WPF -- Thread (Callback method) -- Dispatcher

$
0
0
Hello!
I am looking for an explanation why this has to be programmed so complicated.
I cannot update the user text control. Google meant the lower code.
invoke -> to call it
What does Action do?
OK.
Func<...> and Action<...>.
  Funk returns a value
  Action like void, nothing return
MainWindow.xaml.cs
private void RS232_EvHaContentSentBack(object sender, string e)
{
	e += Environment.NewLine;
	Dispatcher.Invoke((Action)(() => txtSentBack.Text += e));

	Dispatcher.Invoke((Action)(() => txtSentBack.Focus()));
	Dispatcher.Invoke((Action)(() => txtSentBack.CaretIndex = txtSentBack.Text.Length));
	Dispatcher.Invoke((Action)(() => txtSentBack.ScrollToEnd()));  // not needed?
}

Logical class    TSerialPort.cs

public delegate void EventHandlerContentSentBack(Object sender, string e);
public event EventHandlerContentSentBack EvHaContentSentBack;
		
private void ReadDataFromSerialPort(object sender, SerialDataReceivedEventArgs e)
{
	try
	{
		DataToReceive += TSerialPort.ReadExisting();
		if (DataToReceive.Contains(SerialBus.BreakCondition))
		{
			EvHaContentReceivedTrigger?.Invoke(this, DataToReceive);

			TSerialPort?.DiscardInBuffer();
			TSerialPort?.DiscardOutBuffer();

			Write(ResponseSendBack);
			EvHaContentSentBack?.Invoke(this, ResponseSendBack);
		}
	}
	catch (Exception ex)
	{
		throw new ArgumentException($"COM port 'ReadDataFromSerialPort'  {ex.Message + ex.StackTrace}");
	}
}

Maybe someone knows an understandable simple explanation. Perhaps also an example.

Greetings Markus

Trigger - Event or delegate with event

$
0
0
Hello,
I want to trigger an action on a trigger, similar to button click.
I have the possibility of an event and a combination of event and delegate.
When do you take something the best?
I see no difference, no sense. It's best to just take the event handler?
Maybe someone knows an understandable simple explanation. Perhaps also an example.
But I hope someone can easy explain it.
With best regards Markus
public delegate void EventHandlerContentSentBack(Object sender, string e);
public event EventHandlerContentSentBack EvHaContentSentBack;
public event EventHandler ThresholdReached;

private void RS232_EvHaContentSentBack(object sender, string e)
{
   // e += Environment.NewLine;
 Dispatcher.Invoke((Action)(() => txtSentBack.Text += e));
 Dispatcher.Invoke((Action)(() => txtSentBack.Focus()));
 Dispatcher.Invoke((Action)(() => txtSentBack.CaretIndex = txtSentBack.Text.Length));
 Dispatcher.Invoke((Action)(() => txtSentBack.ScrollToEnd()));
}
private void RS232_ThresholdReached(object sender, EventArgs e)
{
 throw new NotImplementedException();
}
With best regards Markus


Serial port with trigger and wait maximum time

$
0
0

Hello,
//Send trigger      -->   <STX>Trigger<ETX>
//Receive message   -->   <STX>gd,3200FFFF1!FFFF\r\n

I have to send that, wait until the answer comes or timeout.
Configuration COM1, 8, NONE, 1

Can somebody gives me a good example
  Problems check the end character and the timeout. Do I need a own thread or a event. Manual or auto?

  Next, it can be I received not the whole message, step by step.

Thanks.
Many greetings Markus

Wrongful acces database insertion

$
0
0

I'm having trouble with inserting information in a database, i'm working on a project where i need to be able to store the location of trainwagons in a database. Each column stands for a different track but when i insert a train in column the next one i insert in a different column will be in the next row and this can't happen, they need to be able to be in the same column. I will also post my insert code that i wrote in c#. So my question is, does anybody know how i can fix this ?.

Kind regards Arno.

ps. I wasn't able to put in the picture because my account isn't verified. I hope it's clear enough.

static void Insert(string data,string spoor) // Insert wagons in the database { OleDbConnection connection = new OleDbConnection(); connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Arno\Documents\Code\Visual Studio\Database_GIP20161.accdb; Persist Security Info=False;"; connection.Open(); string query = String.Format(@"INSERT INTO Posities({0}) VALUES ('{1}');", spoor, data); OleDbCommand command = new OleDbCommand(); command.Connection = connection; command.CommandText = query; command.ExecuteNonQuery(); connection.Close(); }


Why is Multiplication Between a Float and a Integer Different in C# Than C++ and FORTRAN 77

$
0
0

I am working on translating a bit of code from FORTRAN 77 to C#. I ran into the problem that an identical looking expression is returning different results than in other languages. For Example:

The C# code below displays the integer 640437496

float f = .29822734f;
int i = (int)(f * 2147480832);
Console.WriteLine(i);

The C++ code below displays the integer 640437504

float f = .29822734;
int i = (int)(f * 2147480832);
std::cout << "i = " << i;

Finally, this FORTRAN 77 code shares the result with C++: 640437504

integer i
real f
f = .29822734
i = int(f * 2147480832)
write ( *, * ) i

I can't find any other people struggling with this? Did I miss a standard that is different from C++ and FORTRAN in C#? Did I do something wrong?

Thanks for the help.


"The remote server returned an error: (401) Unauthorized"

$
0
0

Hi,

I have a console application which will help to download URL file using the System.Net.WebClient. I am having two site to download the file using username and password.  using the below code i am able to download the file from one site however, i am not able to download the URL file from the second site, its trowing the exception "The remote server returned an error: (401) Unauthorized". i am providing correct credentials ( I have checked manually to down load file using the credentials). Using .net framewok version 4.6. Below is the sample code which i am using.

 using (System.Net.WebClient client = new System.Net.WebClient())
{                                      
 client.Credentials = new System.Net.NetworkCredential(usr, pw);
 client.DownloadFile(downloadURL, filePath);

}

Any help on this would be appriciate

Unable to load dll HRESULT: 0x8007007E

$
0
0

I have moved a C# project from Visual Studio 2003 to Visual Studio 2005 Express.

I get the "unable to load dll HRESULT 0x8007007E" error when making a call to an unmanaged dll. This previously worked OK before.

I have tried putting the dll into the bin\debug directory, the windows and system32 directories with no success.

I have also added the debug directory to the environment path variable but still no success.

I have investigated trying to put a dependancy in the project on the dll but can't find a method of achieving this.

I have also tried running the application and the dll outside of the IDE in the same directory and it still can't find the dll.

Is there a difference in the way Framework 2.0 loads unmanged dlls compared to 1.1?

Additional information. I have both 1.1 and 2.0 Frameworks installed. The project still works in Visual Studio 2003.

Any help would be appreciated.

Regards

Kelvin

Get random line from text file

$
0
0

I just decided to learn game dev about 3-4 months ago and mostly started following tutorials on YouTube and googling whatever questions that I had. I don't have a background or previous education or experience with any of it, so it can be confusing. I have a working piece of code that I spliced together from 2 different codes, it works, but I'd like it to work slightly differently. I spliced together a typewriter code and a text reader code, so as of now, the code below works as follows: It gets the entire text of the text file and writes it the UI textbox and therefore displays up to the first 3 lines of the text file that the size of the UI panel will allow. What I have tried with no success is for some way to make it so that only 1 random line of the text file will be displayed whenever the player accesses the scene. Here is what I have, thanks in advance for any guidance on the subject. This is for Unity and C#.

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System;
using UnityEngine;
public class FactGenerator : MonoBehaviour
{
    public Text text;
    public TextAsset textFile;
    public bool playOnAwake = true;
    public float delayToStart;
    public float delayBetweenChars = 0.075f;
    public float delayAfterPunctuation = 0.0025f;
    private string story;
    private float originDelayBetweenChars;
    private bool lastCharPunctuation = false;
    private char charComma;
    private char charPeriod;
    public List<string> facts;
    public string[] lines;
    void Awake()
    {
        text = GetComponent<Text>();
        originDelayBetweenChars = delayBetweenChars;
        charComma = Convert.ToChar(44);
        charPeriod = Convert.ToChar(46);
        if (playOnAwake)
        {
            ChangeText(text.text, delayToStart);
        }
    }
    public void ChangeText(string textFile, float delayBetweenChars = 0f)
    {
        StopCoroutine(PlayText()); //stop Coroutine if exist
        story = Resources.Load<TextAsset>("dinofacts").text;
        text.text = ""; //clean text
        Invoke("Start_PlayText", delayBetweenChars); //Invoke effect
    }
    void Start_PlayText()
    {
        StartCoroutine(PlayText());
    }

    IEnumerator PlayText()
    {
        foreach (char c in story)
        {
            delayBetweenChars = originDelayBetweenChars;
            if (lastCharPunctuation)
            {
                yield return new WaitForSeconds(delayBetweenChars = delayAfterPunctuation);
                lastCharPunctuation = false;
            }
            if (c == charComma || c == charPeriod)
            {
                lastCharPunctuation = true;
            }
            text.text += c;
            yield return new WaitForSeconds(delayBetweenChars);
            TextAsset factText = Resources.Load<TextAsset>("dinofacts");
            lines = textFile.text.Split("\r\n"[0]);

            bool addingFacts = true;
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i] == "facts:")
                {
                    addingFacts = true;
                    Debug.Log("adding facts");
                    continue;
                }
                if (lines[i] != "")
                {
                    if (addingFacts)
                    {
                        facts.Add(lines[i]);
                    }
                }
            }
        }
    }
}

Hangman Console C#

$
0
0

Hello,

I am fairly new to C# and I have this hangman game pretty much working. The only thing I need help with is adding "lives" to the game. Something which would exit the game if the player goes beyond their limit. Any help is always appreciated. 

Thanks a lot.      

Hyrax.

 if (uservalue == "1")
            {
                string[] arrayofwords = { "Blue", "Black", "Yellow", "Orange", "Green", "Purple" };        // my word bank

                Random ran = new Random();   // created variable to randomize word bank
                string mywords = arrayofwords[ran.Next(0, arrayofwords.Length)];          // retrievd this peice of code from http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/dc4bd2ad-166b-416c-875d-5c21984c4796
                Console.WriteLine("You chose colours");




                char[] guess = new char[mywords.Length];                      // cite help from this website http://www.dreamincode.net/forums/topic/173101-c%23-hangman-hang-up/
                for (int p = 0; p < mywords.Length; p++)


                    guess[p] = '*';          // this is for the squiglly lines you usually see on hangman games

                    while (true)
                    {
                        Console.Write("Please enter your guess: ");
                        char playerGuess = char.Parse(Console.ReadLine());
                        for (int j = 0; j < mywords.Length; j++)
                        {

                           if( char.ToLower( playerGuess ) == char.ToLower( mywords[j]) )
                               guess[j] = mywords[j];      // http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/e0c38f78-4cc3-43cc-922d-bca598ffb035



                        }

                        Console.WriteLine(guess);
                        



                    }




                
           
                
                 

               
            }


Hang man code

$
0
0

I am very new to coding and I am trying to do a <g class="gr_ gr_105 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" data-gr-id="105" id="105">hang man</g> code. this is what I have so far but I don't know how to code that the user has three lives. Very simple coding would be nice <g class="gr_ gr_432 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" data-gr-id="432" id="432">so<g class="gr_ gr_443 gr-alert gr_tiny gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling multiReplace" data-gr-id="443" id="443">i</g></g> can understand it 

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to <g class="gr_ gr_26 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="26" id="26">hangan</g>!<g class="gr_ gr_27 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" data-gr-id="27" id="27">Lets</g> begin. ");

            string[] arrayofwords = { "blue", "black", "yellow", "orange", "green", "purple", "red", "pink", "maroon", "gold" };
            Random ran = new Random();
            string mywords = arrayofwords[ran.Next(0, arrayofwords.Length)];
            Console.WriteLine("Category is colours");
            char[] guess = new char[mywords.Length];
            for (int p = 0; p < mywords.Length; p++)
                guess[p] = '*';
            while (true)
            {
                Console.WriteLine("please write your guess");
                char Playerguess = char.Parse(Console.ReadLine());

                for (int j = 0; j < mywords.Length; j++)

                {

                    if (Playerguess == mywords[j])
                        guess[j] = mywords[j];

                    else 
                    {
                        Console.WriteLine("you guessed wrong");
                    }
                }

                Console.WriteLine(guess);


            }




        }
    }

}

                                                                            

Problem migrating asp .net 3.5 vs2010 solution to vs 2017 solution

$
0
0

I have installed both vs 2010 and vs 2017 on windows 7 32 bit.

I was able to build the entire on vs 2017. 

However, when running the application in debug mode, I get the error, below.  The 'ProjAppMod.XmlSerializers'  dll was generated ( via generate serializer assembly set on in project) by another project in the solution which builds ProjAppMod.dll.  I checked the version of all dlls and they are .net version v2.0.50727.  All the projects are .net version 3.5.  No issues when running on the same machine using vs 2010.   

There is something else I found bizzare... if I rename ProjAppMod.XmlSerializers.dll to ProjAppMod.XmlSerializers.dll.src (in web application project which uses this dll) and do debug in vs 2017, it works.

Any help is appeciated.  Thanks in advance.

  


Could not load file or assembly 'ProjAppMod.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.BadImageFormatException: Could not load file or assembly 'ProjAppMod.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Assembly Load Trace: The following information can be helpful to determine why the assembly 'ProjAppMod.XmlSerializers' could not be loaded.


=== Pre-bind state information ===
LOG: User = dom\romang
LOG: DisplayName = ProjAppMod.XmlSerializers
 (Partial)
LOG: Appbase = file:///C:/Users/romang/Source/Repos/weba/ProjWebSvc/
LOG: Initial PrivatePath = C:\Users\romang\Source\Repos\weba\ProjWebSvc\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\romang\Source\Repos\weba\ProjWebSvc\web.config
LOG: Using host configuration file: C:\Users\romang\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/romang/AppData/Local/Temp/Temporary ASP.NET Files/ProjWebSvc/b25fb8bc/4f861caa/ProjAppMod.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/Users/romang/AppData/Local/Temp/Temporary ASP.NET Files/ProjWebSvc/b25fb8bc/4f861caa/ProjAppMod.XmlSerializers/ProjAppMod.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///C:/Users/romang/Source/Repos/weba/ProjWebSvc/bin/ProjAppMod.XmlSerializers.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8013101b). Probing terminated.



Stack Trace: 


[BadImageFormatException: Could not load file or assembly 'ProjAppMod.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.]
   System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0
   System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +43
   System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +127
   System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +142
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +46

[ConfigurationErrorsException: Could not load file or assembly 'ProjAppMod.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +613
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +203
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +105
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +178
   System.Web.Compilation.BuildProvidersCompiler..ctor(VirtualPath configPath, Boolean supportLocalization, String outputAssemblyName) +54
   System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +232
   System.Web.Compilation.BuildManager.CompileGlobalAsax() +51
   System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +337

[HttpException (0x80004005): Could not load file or assembly 'ProjAppMod.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.]
   System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +58
   System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +512
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +729

[HttpException (0x80004005): Could not load file or assembly 'ProjAppMod.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9002803
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +85
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +333



KernalBase.dll taking long time in the execution process on windows 10 compare to windows 7

$
0
0

I have an code in c# which perform copy operation, project with same code on windows 7 taking 6 min for copy option while same copy operation taking 14 min on windows 10

public INode AddNode(INode node)
        {
            ISmarNode smNode = (ISmarNode)node;

            smNode.SmObject.InsertEx(smBehavior);
            if (smNode.SmObject.ClassId == BFCOMPUB.NULL_Int16 || smNode.SmObject.ObjectId == BFCOMPUB.NULL_Int32)
                throw new Exception();
            if (smNode is BaseSmarNode)
            {
                ((BaseSmarNode)smNode).BindToSmObject(smNode.SmObject);
            }
            return node;
        }

when i do profiler of visual studio 15 for sampling following snap shows actual time is taking by KernalBase.dll

what is the solution for this, as only KernalBase.dll function Body taking 53.3 % ? and this is reproducible only on windows 10 not on windows 7.

speed/ram and harddisk are same, no different software are running compare to windows 7. ISmarNode is a class having object to store nodes. IT's nothing but a data structure to store Node


How to use PLINQ for my scenario

$
0
0

see my LINQ query and tell me how to use PLINQ to speed up.

 var WeitageWiseRow = (from tickerBrokerStandardDateLineitemValue in MergedataPerBroker
                                          group tickerBrokerStandardDateLineitemValue by new
                                          {
                                              Section = tickerBrokerStandardDateLineitemValue.TabName,
                                              LineItem = tickerBrokerStandardDateLineitemValue.StandardLineItem,
                                          } into tickerBrokerStandardDateLineitemValuesGroup
                                          orderby tickerBrokerStandardDateLineitemValuesGroup.Key.Section
                                          select new
                                          {
                                              Section = tickerBrokerStandardDateLineitemValuesGroup.Key.Section,
                                              LineItem = tickerBrokerStandardDateLineitemValuesGroup.Key.LineItem,
                                              BrokerGroupData = tickerBrokerStandardDateLineitemValuesGroup.GroupBy(y => y.BrokerName)
                                          }).ToList();
help me with sample code. thanks

Detecting if a specific USB is connected

$
0
0

Looking for some advice on how I can achieve the following:

I'm currently building an C# wpf application and i want to add where the application runs and check if a specific usb is plugged in to any of the usb ports and if not the application cant be interacted till said usb is plugged in and continues to check if the usb is connected and if its remove the application locks any interaction to it till the usb is plugged in again  ?

any ideas on how this can be done?

class DriveDetection
    {
        // Used For Monitoring Of USB Connection 
        private ManagementEventWatcher Connected;
        private ManagementEventWatcher Removed;
        public void USBControl()
        {
            // USB Connection Event Watching
            Connected = new ManagementEventWatcher();
            // USB Removal Event Watching
            Removed = new ManagementEventWatcher();
        }
    }
}

this is the idea of so far but i dont know where to go from here

Query SCCM 2012 from C# to get applications installed/notinstalled remotely from SCCM Client with WMI

$
0
0

Hi All

 

I am asking for help to gather information from the "SELECT * FROM CCM_Application" -namespace "ROOT\ccm\ClientSDK"

and display its information into a DataGrid.
The problem is the data I am getting is not complete and the objects I could actually get the data from is in the DeploymentReport Object it seems.

I need information such as Name,InstallState,EvaluationState

the same query in powershell pulls this information but I am unable to get it from C# correctly.


__GENUS                    : 2
__CLASS                    : CCM_Application
__SUPERCLASS               : CCM_SoftwareBase
__DYNASTY                  : CCM_SoftwareBase
__RELPATH                  : CCM_Application.Id="ScopeId_076322AE-B017-4E62-B3AD-A4FDB580BD1C/Application_faf6010d-6815-4dbc-bd61-c719f9773768",IsMachineTarget=TRUE,Revision="8"
__PROPERTY_COUNT           : 38
__DERIVATION               : {CCM_SoftwareBase}
__SERVER                   : MYCOMPUTERNAMEHERE
__NAMESPACE                : root\ccm\clientsdk
__PATH                     : \\MYCOMPUTERNAMEHERE\root\ccm\clientsdk:CCM_Application.Id="ScopeId_076322AE-B017-4E62-B3AD-A4FDB580BD1C/Application_faf6010d-6815-4dbc-bd61-c719f9773768",IsMachineTarget=TRUE,Revision="8"
AllowedActions             : {Install}
AppDTs                     :
ApplicabilityState         : Applicable
ConfigureState             : NotNeeded
ContentSize                :
Deadline                   : 20180426132700.000000+000
DeploymentReport           :
Description                :
EnforcePreference          : 2
ErrorCode                  : 0
EstimatedInstallTime       :
EvaluationState            : 1
FileTypes                  :
FullName                   : Passport Web to Host Patch 21.1.2.307
Icon                       :
Id                         : ScopeId_076322AE-B017-4E62-B3AD-A4FDB580BD1C/Application_faf6010d-6815-4dbc-bd61-c719f9773768
InformativeUrl             :
InProgressActions          : {}
InstallState               : Installed
IsMachineTarget            : True
IsPreflightOnly            : False
LastEvalTime               : 20190109091731.000000+000
LastInstallTime            : 20181009174722.000000+000
Name                       : Passport Web to Host Patch 21.1.2.307
NextUserScheduledTime      :
NotifyUser                 : False
OverrideServiceWindow      : False
PercentComplete            : 0
Publisher                  : Rocket Software
RebootOutsideServiceWindow : False
ReleaseDate                : 00000000000000.000000+000
ResolvedState              : Installed
Revision                   : 8
SoftwareVersion            : 21.1.2.307
StartTime                  : 20180426132700.000000+000
SupersessionState          : None
Type                       : 1
UserUIExperience           : True
PSComputerName             : MYCOMPUTERNAMEHERE




my code is 
        public CCMView(string targetComputer)
        {
            InitializeComponent();
            // Display loading animations.
            //gridError.Visibility = Visibility.Collapsed;
          //  gridLoading.Visibility = Visibility.Visible;
            new Thread(() => RefreshProcessesList()) { IsBackground = true }.Start();

        }


        private void RefreshProcessesList()
        {
            try
            {
                ManagementScope scope = new ManagementScope(@"\\" + GlobalVar.TargetComputerName + @"\ROOT\ccm\ClientSDK:CCM_SoftwareBase");
                SelectQuery query = new SelectQuery("Select * From CCM_SoftwareBase");
                 var typeDescriptors = new ObservableCollection<ManagementObjectTypeDescriptor>();

                using (var searcher = new ManagementObjectSearcher(scope, query))
                {
                    using (var managementObjects = searcher.Get())
                    {
                        foreach (ManagementBaseObject managementObject in managementObjects)
                        {
                            using (managementObject)
                            {
                                typeDescriptors.Add(new ManagementObjectTypeDescriptor(managementObject));
                            }
                        }
                    }
                }
                this.Dispatcher.Invoke((Action)(() =>
                {
                CcmAppsGrid.ItemsSource = new ArrayList(typeDescriptors);
                    gridError.Visibility = Visibility.Collapsed;
                    gridLoading.Visibility = Visibility.Collapsed;
                    CcmAppsGrid.Items.SortDescriptions.Clear();
                    CcmAppsGrid.Items.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

                }));

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

Why is copying 10 items to an observable collection so slow and how to speed up?

$
0
0

This code operates in a .NET WPF C# environment. The basic code creates a collection of about 10 objects. The collection is sorted and then copied. When the copy happens the time to execute adds an astonishing 7 seconds. The observable collection does not have any subscribers at this point so one would not expect any time to be lost due to broadcast change notifications.

The application is based on a WinForm used to create a System Tray Notification item. When the tray icon is clicked upon a WPF window is shown. At the time that the WPF window becomes visible a DispatcherTimer is created and started. A short delay after that and a web service call is made which collects information which is written into userItems, a local variable. This collection will be passed back to the caller who will put it into a class property that will be bound to the source for a ComboBox. This code works well and fast. There is a problem with it, however, in that the contents of the ComboBox drop down list are not sorted. I thought that it would be trivial to handle that by sorting the contents of the userItems before it is passed back to the caller. Not so, sneaker breath. Here's the important part of the code:

// A local variable is declared.
ObservableCollection<UserItem> userItems = null;

// Snipped from the code is the initial population of userItems.

// A sorted copy of userItems is created. This is quick.
List<UserItem> lui = userItems.OrderBy( a => a.user_id ).ToList();

// The original collection is emptied so that it can be populated with the
// sorted elements.
userItems.Clear();

// The sorted list of items, only about 10 objects, is copied back to userItems.
// This is where the time is being spent, an astonishing 7 seconds to copy 10 items.
// If the copy is commented out then the code runs in almost no time at all.
for (int x = 0; x < lui.Count; x++)    userItems.Add( lui[x] );

Any ideas why the above code fragment runs so slowly and how can I speed it up?


Richard Lewis Haggard


Viewing all 31927 articles
Browse latest View live


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