mercredi 6 mai 2015

How to make Transparent Web-browser control

I have a system windows forms where i show the web browser control over the media-player control as shown in image below, enter image description here

I want to make Transparent web browser control. I have try many things but i am not able to make transparency over web browser control, i have try :

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BackColor = Color.FromArgb(0, 0, 0, 0);
            this.TransparencyKey = Color.Red;
            this.BackColor = Color.Magenta;
            this.TransparencyKey = Color.Magenta;*/
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BackColor = Color.Transparent; 

My code is :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.DirectX.AudioVideoPlayback;
using System.Windows.Forms;

namespace Windows_Video
{
    public partial class Form1 : Form
    {
        Video vdo;

        public string mode = "play";
        public string PlayingPosition, Duration;

        public Form1()
        {

            InitializeComponent();
          //  VolumeTrackBar.Value = 4;

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBox1.Text = openFileDialog1.FileName;
            }
            axWindowsMediaPlayer1.URL = textBox1.Text;
            axWindowsMediaPlayer1.Ctlcontrols.play();

        }
    private void button1_Click(object sender, EventArgs e)
        {
         /*   OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBox1.Text = openFileDialog1.FileName;
            }*/
        }    

        private void button2_Click(object sender, EventArgs e)
        {

        //    axWindowsMediaPlayer1.URL = textBox1.Text;
         //   axWindowsMediaPlayer1.Ctlcontrols.play();
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //this.BackColor = System.Drawing.Color.Transparent;
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BackColor = Color.Transparent;
        } 
    }    
}

How to run aspx.cs page load event parallel from asp.net mvc functionality

I'm working on a project which is built in asp.net MVC and is using an aspx/aspx.cs page in order to implement ReportViewer Control. But the thing happening is when i try to view the report the other functionality seems to be on hold until the page is loaded completely. So i'm thinking how can i run it parallel to my asp.net mvc functionality so that both works synchronously. Do i need to use multi-threading here? Please help i'm stuck here.

convert json to object by mapping key as field of class and #text as value of that field

Although there are tons of links to convert json to object but here the requirement is bit different.

I have this xml -

{
  "structure": {
    "-type": "DivideByZeroException",
    "property": [
      {
        "-key": "Message",
        "#text": "Attempted to divide by zero."
      },
      { "-key": "Data" },
      { "-key": "InnerException" },
      {
        "-key": "TargetSite",
        "#text": "Void btnWriteError_Click(System.Object, System.Windows.RoutedEventArgs)"
      },
      {
        "-key": "StackTrace",
        "#text": "   at WpfApplication1.MainWindow.btnWriteError_Click(Object sender, RoutedEventArgs e) in c:\\Users\\Anil.Purswani\\Desktop\\WPF_Application\\WpfApplication1\\MainWindow.xaml.cs:line 169"
      },
      { "-key": "HelpLink" },
      {
        "-key": "Source",
        "#text": "WpfApplication1"
      },
      {
        "-key": "HResult",
        "#text": "-2147352558"
      }
    ]
  }
}

and would like to convert it into -

Class ModelError
{
   string Message;
   Exception InnerException;
   string TargetSite;
   string StackTrace;
   string HelpLink;
   string Source;
   string HResult;
}

So the final object should contain like this -

modelerrorobj.Message =  "Attempted to divide by zero."
modelerrorobj.Data = null;
modelerrorobj.InnerException = null;
modelerrorobj.Targetsite = "Void btnWriteError_Click(System.Object, System.Windows.RoutedEventArgs)";
modelerrorobj.StackTrace = "   at WpfApplication1.MainWindow.btnWriteError_Click(Object sender, RoutedEventArgs e) in c:\\Users\\Anil.Purswani\\Desktop\\WPF_Application\\WpfApplication1\\MainWindow.xaml.cs:line 169"

So basically, "-key" value i.e. "Message", "Data", "StackTrace" is the field in class ModelError and "#text" is the value of that corresponding field.

for e.g.

      {
        "-key": "Message",
        "#text": "Attempted to divide by zero."
      },

in above, "Message" is the field and "Attempted to divide by zero." is the value of that field.

Please note I have Json but how to convert it in ModelError?

The security of dll files in a Client/Server application in .net

I'm going to write a Client/Server application. There are some ambiguous concepts in this that I was not able to get answer to after many hours of searching.

As we all know one of the major caveats of the .Net framework is that the DLL files can be decompiled and reverse-engineered on the client's machine.

Now my question is can I put some of the DLL files required by the Client on the Server?

And if true, will it be completely secure or it will still be open to getting reverse-engineered/decompiled by crackers?

Access denied when downloading CloudBlockBlob

I would like to download a blob from my Azure stockage to the virtual machine which host my cloud service. The problem is, it seems that every disks/folders in that machine is restricted. I got an access denied error to the directory where I want to put the blob. I use blob.downloadToStream method.

That's why I've taken my virtual machine on remote desktop and have set a directory in a disk with fullcontrol/read/write rights to "Everyone". It did not solve the problem.

Next, I've put "Runtime executionContext="elevated" " to my csdef file. Same problem.

Now my idea is, if possible, to put admin rights to the service which host my worker : WaWorkerHost (I think), but I didn't find it in the service list of my virtual machine.

My question is, how to solve this access problem ? Is my idea correct ?

How to get Ip address of a machine by passing the mac address in .Net [duplicate]

This question is an exact duplicate of:

I know the mac address of a machine. By using the mac address I need to get the IP address of the machine. How is it possible in .NET?

Lucene retrieve Values based on conditional of two fields

I've been trying to get Lucene.NET to respect a given condition which requires an evaluation of the index document fields.

I have a database table which stores "Experiences". For each experience there are two field/columns which tell is the row/ExperienceId is current (IsCurrent flag) as well as a StartDate and an EndDate.

Now, when implementing a "search engine" on the platform I need to have an option which, once checked (it's a checkbox) should retrieve only the those where IsCurrent is 1 or, otherwise, the one where the EndDate is the closest to the current date, i.e, EndDate is the highest. All this should be done for each PersonId (a foreing key in my Experiences table)

The thing is, I don't know how to tell Lucene that it should repect these conditions, that is, give me the ones with IsCurrent = 1 or the ones where IsCurrent = 0 but the EndDate is the maximum for each PersonId.

I looked into MultiTermQueries but couldn't make any sense of it.

I was trying the code bellow but I don't think this is working because the results make no sense (and I know the problem lies between the chair and the keyboard).

if (isCurrent)
{
    BooleanQuery queryIsCurrent = new BooleanQuery();
    queryIsCurrent.Add(new TermQuery(new Term("IsCurrent", "1")), BooleanClause.Occur.SHOULD);
    booleanQuery.Add(queryIsCurrent, BooleanClause.Occur.SHOULD);
    //Should I be using SHOULD here?? ^^


    //Should I be using this code for the date at all? I don't think so..
    TermRangeQuery termRangeQuery = null;
    termRangeQuery = new TermRangeQuery("EndDate", null, DateTime.Now.ToString(), true, true);
    booleanQuery.Add(termRangeQuery, BooleanClause.Occur.MUST);
}

linq query conditions by database and a list contents

I want to retrieve all tickets whose badge number is present in the list

i have a listA

public class LigneXls

     {
         public string sup { get; set; }
         public string tiers { get; set; }
        p ublic string badge { get; set; }
   }

i have a method :

            try
            {
                   List<DataObjects.LigneXls> listeLigneXls)
                   var listeTickets = from ti in _AGAPEntitie5.TICKETS
                             join ch in _AGAPEntitie5.CHAUFFEURS on ti.ID_CHAUFFEUR equals ch.ID_CHAUFFEUR
                             join tour in _AGAPEntitie5.TOURNEES on ch.ID_CHAUFFEUR equals tour.ID_CHAUFFEUR
                             join tour2 in _AGAPEntitie5.TOURNEES on ti.ID_TOURNEE equals tour2.ID_TOURNEE
                             join chb in _AGAPEntitie5.CHAUFFEUR_BADGE on ch.ID_CHAUFFEUR equals chb.ID_CHAUFFEUR
                             where chb.NUM_BADGE.Contains(listeLigneXls.Select(lgn => lgn.badge).ToString())
                             _AGAPEntitie5.CHAUFFEUR_BADGE.Where(p=>p..Any(x=>))
                             //where listeLigneXls.Any(s=>chb.NUM_BADGE.Contains(s.badge))
                             select new AGAP4.DataObjects.Ticket
                              {
                                  id = ti.ID_TICKET,
                                  poids_entrant = ti.POIDS_ENTRANT,
                                  poids_sortant = ti.POIDS_SORTANT,
                                  poids_net = ti.POIDS_Net,
                                  id_tournee = ti.ID_TOURNEE,
                                  id_chauffeur = ti.ID_CHAUFFEUR
                              };
                   lines_tickets = listeTickets.ToList();
                   return lines_tickets;
            }

i try this condition but it doesn't work,

try {

                    where chb.NUM_BADGE.Contains(listeLigneXls.Select(lgn =>lgn.badge).ToString())
                    //where listeLigneXls.Any(s=>chb.NUM_BADGE.Contains(s.badge))
                }

doesn't recognize tostring for the first and doesn't recognize the list

Any idea how solve my problem?

PayPal .Net Invoice API multiple Accounts

I cant add multiple PayPal-Merchant-Accounts to my C# PayPal-API. I found this solution, but i get an error by name id field: Is it possible to have multiple seller PayPal accounts a la eBay? (ASP.NET MVC 5) Is it possible to send the API login details by the Paypal-Object?

How to integrate any weather widget in lockscreen apps in WP 8.1?

I have developed a lockscreen app for window phone 8/8.1, that's released in the windows store, but lot of my friends suggested that I should integrate the weather widgets with customize options like location, refresh interval, etc in the app.

I searched a lot in the internet, I googled a lot, but believe me there seems to be nothing is provided to integrate weather widgets in lockscreen. Is there any way? Or is this something not allowed in WP 8.1?

In windows Phone to work with lockscreen apps, developer have to work with Backgroundtask agent, I know and I did that, but how to access the open area left in the lockscreen?

Any sample code, links or even a guide would do, please help. Please guide me, a novice app developer.

MeasureCharacterRanges, Region and IDisposable

Graphics.MeasureCharacterRanges returns an array of Region. Region implements IDisposable. Is it my responsibility as a caller to dispose each of them?

Neither the documentation nor the samples mentions this, which leads me to suspect that it is not necessary, although I fail to see why I would get away with it. At the same time, some other GDI+ objects are very bad to dispose (SystemFont, SystemBrush, SystemPen, etc...)

(I'm about to use this on a heavy loaded web service, where I recently tracked down a memory leak because someone had failed to dispose a bitmap.)

Nuget - unable to resolve package that could previously be resolved

We have a nuget server set up and are using Jenkins for CI integration. For the past two months everything has been working perfectly, however today we got the following error after update one of our Nuget packages:

Jenkins\Trunk\trunk\Solution.sln" (default target) (1) -> "F:\Jenkins\Trunk\trunk\Ioc\TPI.csproj" (default target) (44) -> F:\Jenkins\Trunk\trunk.nuget\NuGet.targets(100,9): error : Unable to find version '1.0.3.2' of package 'Solution.Extensions'. [F:\Jenkins\Trunk\trunk\Ioc\TPI.csproj]

I checked our nuget server and the package is definitely there. Previous versions have resolved fine, however this latest update and publish of our package seems to have inexplicably broken something. It was a simple update to the nuget package, just a single method being added with no dependencies created and the tried and tested publish procedure followed.

Any ideas why MS Build might suddenly be unable to resolve a Nuget dependency? All suggestions welcome.

Thanks

Performance difference in empty array initialization

Recently, I've been working in performance/memory optimization and have stucked in the empty array initialization which uses generic method to initialize empty array:

Code implementation of generic empty array class:

    public static class EmptyArray<T>
    {
        public static readonly T[] Instance;

        static EmptyArray()
        {
            Instance = new T[0];
        }
    }

So, whenever creating empty array of any type,it has been called as like:

var emptyStringArray = EmptyArray<string>.Instance;

Such empty array declaration has been done in many places of codebase. I am confused how would it be differs in performance while using :

var emptyStringArray = new string[0];

I've asked to above code author and he has replied me :

Basically, all empty arrays are readonly, and are equal to one another, which means that you can use the same instance (which will be created lazily on demand during run-time)… That should reduce the total number of allocations, reduce memory usage and GC pressure, and should result in some improvement

Still, I am not able to understand how would EmptyArray Instance boost the performance in array declaration.

How to get a control to fill its container up to its maximum size, then center align

I have a Windows Forms application consisting of a control within a window. I'd like the width of the control to fill the width of the form up to its MaximumSize.Width, at which point it centers itself within the window. Is there a way I can do this without code behind, if possible?

Notification to Application from a crashing windows service

I have a .Net application which manages a number of long running services. Some of the services occasionally crash with the dreaded

Fatal Execution Engine Error

due (I believe) to badly written unmanaged class libraries.

I'd like to know is there a way for the service manager app to receive a notification somehow that the service has crashed and stopped?

I know I can check the list of services to see are they all there regularly but I'd like to know if there is a better way to do it.

IWindsorInstaller Exclude assemblies

I can't exclude some assemblies in install process.

I try this :

 public class InternationnalisationInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
        var filter = new AssemblyFilter(path)
                .FilterByAssembly(a => !a.IsDynamic
                    && !a.FullName.Contains("Microsoft"));

        container.Register(Classes.FromAssemblyInDirectory(filter)
            .BasedOn<ITraductionProvider>()               
            .WithService.AllInterfaces());
    }
}

in dev no problem, but in production :

Impossible de charger le fichier ou l'assembly 'Microsoft.VisualStudio.Shell.Immutable.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ou une de ses dépendances. Le fichier spécifié est introuvable. à System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes) à System.Reflection.RuntimeAssembly.GetExportedTypes() à Castle.Core.Internal.ReflectionUtil.GetAvailableTypes(Assembly assembly, Boolean includeNonExported) à Castle.Core.Internal.ReflectionUtil.GetAvailableTypesOrdered(Assembly assembly, Boolean includeNonExported) à Castle.MicroKernel.Registration.FromAssemblyDescriptor.b__0(Assembly a) à System.Linq.Enumerable.d__14 2.MoveNext() à Castle.MicroKernel.Registration.FromDescriptor.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) à Castle.MicroKernel.Registration.BasedOnDescriptor.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) à Castle.MicroKernel.DefaultKernel.Register(IRegistration[] registrations) à Castle.Windsor.WindsorContainer.Register(IRegistration[] registrations) à Internationnalisation.InternationnalisationInstaller.Install(IWindsorContainer container, IConfigurationStore store)

this assembly is used to tag class for VSIX registration. Can you help me ? Thanks

404 after changing routes in ASP NET MVC application

I had working routes on my app that looked like this:

            routes.MapRoute(
            name: "Category",
            url: "{name}-c{categoryId}",
            defaults: new { controller = "Products", action = "Index", name = "ErrorName" },
            namespaces: new[] { "B2B.Controllers" });

        routes.MapRoute(
            name: "InfoPage",
            url: "{name}-i{id}",
            defaults: new { controller = "InfoPages", action = "Details", name = "ErrorName" },
            namespaces: new[] { "B2B.Controllers" });

I've changed the dash (-) to the hash (#) because spaces are changed in url to dashes.

 url: "{name}#c{categoryId}",
 url: "{name}#i{id}",

Now I've this same routes with only this one char changed and I get 404 on urls like this:

siteadess:1234/1.0.1-Podstawowa%23c4

I've also tried to change hash to under score and it didn't worked either.

How to add view to a PRISM TabControl region WITHOUT making it selected?

We have a WPF application using PRISM, with a region of type TabControl.

    <TabControl prism:RegionManager.RegionName="{x:Static inf:RegionNames.ContentRegion}">
        <TabControl.ItemContainerStyle>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="Header" Value="{Binding TabName}" />
            </Style>
        </TabControl.ItemContainerStyle>
    </TabControl>

And we are registering views with

_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ContentView));

Problem is, this way the registered tab automatically gets selected. Is there a way to add a view as tab but NOT select it??

Experience bad performance IIS 8 200 applications

We are developing an application which is almost ready for launch. We have the vision to host around 200 applications on one server. So we did a loadtest.

When I test with one application and 200 users, no problem at all and seems to work very quick. But the test when having 200 applications and each application one user works very bad. All applications are in one AppPool

We did some optimalisations like:

  • minified the css/javascript
  • put extra mem (2GB for 200 users and one application, no problem, 200 applications was problem, after that we upgraded to 12GB memory but performance keep bad)
  • Set the setting in IIS to release memory when application is not used anymore of idle for a time of 30 min.
  • We used interning of .NET

We will do:

  • Move static files outside the SSL so can be cached

Do anyone have experience with this (in my opinion small set of applications) set of applications? I expected IIS would use his memory better.

How do I make sure the NotifyIcon closes with my app?

This question is in response to many apps that I must use on a daily basis which all seem to have one thing in common that really gets on my nerves. And so, here I am, providing you with a solution you can implement!

How do I make sure my NotifyIcon is removed from the Notification Area when my app closes?

How to bind image and text together in the same column

I want to bind the image and text together in the same column. I managed to bind the text part but failed to bind the image part. This is what I've done so far:

<ListView.View>
  <GridView>
    <GridViewColumn x:Name="TimeColumn" Header="Time" Width="80">
      <GridViewColumn.CellTemplate>
        <DataTemplate>
          <TextBlock>
            <TextBlock.Text>
              <MultiBinding>
                <!--<PUT IMAGE>-->
                <Binding Path="Time"/>
              </MultiBinding>
            </TextBlock.Text>
          </TextBlock>
        </DataTemplate>
      </GridViewColumn.CellTemplate>
    </GridViewColumn>
  </GridView>
</ListView.View>

This is my expected result:

enter image description here

Any suggestion?

restsharp addparameter json For POST not work

I 'm very reading on stack overflow. But it's not work! I'm use RestSharp on REst webservice. I want to sent JSON Format to webservice.

my json fotmat, I'm sent on POSTMAN app in google chrome. It's work! :

{
"boss":[{
    "cus":"454",
    "date":"July 23,2015",
    "mangpo":"9.1",
    "namo":"rattatrayaya"
},{
    "cus":"872",
    "date":"Feb 23,2015",
    "mangpo":"9.1",
    "namo":"nama Arya Vlokita"
}]

}

in this code:

 string url = "http://ShiVamSaRaNum/Uma/index.php/create_sudo/Saranung";
        var client = new RestClient(url);
        var request = new RestRequest(Method.POST);
       request.RequestFormat = DataFormat.Json;
       request.AddBody(
           new{
               cus = "454",
               date = "July 23,2015",
               mangpo = "9.1",
               namo = "rattatrayaya"
                });
       RestResponse response = client.Execute(request);
       var content = response.Content;
       Console.WriteLine(content.ToString());
       Console.ReadLine();

- some one ask: request.AddParameter("application/json", json, ParameterType.RequestBody); - some one ask: request.AddObject(jsonObject) and some one ask: request.Addbody(jsonObject)

Now I'm very confused! Help me now!

P.S. if you can please revise write full my coding with me. and ask me add namespace to use. I'm add references RESTSHARP completely. P.S.1 I'm novice on c# and .net, help me now! Jesus Love You

Fill SERFF template XLSM File using C# EPPLUS library?

How to fill the SERFF template containing MACROS using EPPLUS Library. When i tried to edit template using this code the SERFF template crashes here is code i am using for editing and exporting template we can get SERFF template from here http://ift.tt/1ADYeVq

FileInfo newFile = new FileInfo(@"D:\FFM Sharred\SERFF-PlansBenefits.xlsm");

ExcelPackage pck = new ExcelPackage(newFile);

var ws = pck.Workbook.Worksheets.First();

ws.SetValue("B2", "33333");

Response.BinaryWrite(pck.GetAsByteArray());
Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";           
Response.AddHeader("content-disposition", "attachment;  filename=Sample4.xlsm"); 

ATL project can't find referenced dll from the same solution

I have two projects in my solution. First one is an ATL project (created using this guide: http://ift.tt/1brstZ6 ). Second one is a CLR Class Library project (as per this: http://ift.tt/1GOkhe5 ).

Now the problem is that when I use this COM object in an other program, it crashes. When I attach a debugger to the process, it throws a System.IO.FileNotFoundException: Could not load file or assembly 'CLRClassLibrary, Version=1.0.5604.15598, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

When I build a Release, the program doesn't crash, but simply tells me that method was not found.

I checked both Debug and Release folders and they contain CLRClassLibrary.dll. TargetedNetFramework version 4.5

VC++ JSON parsing and unescaping

In my VC++ project, I have a server response that looks like this that gets assigned to a System::String:

{
    "someValue": "1",
    "someObject": {
        "content": "<div id=\"someContent\">text<\/div>"
    }
}

The true JSON object is a little more complex, but the above demonstrates that the JSON object has some values containing HTML. The response also contains escaped characters.

As I'm using .NET, I'd like to know the best option to:

  1. Read the JSON object
  2. Convert the HTML string to unescaped HTML that can be read with my HTML parser

My previous approach to unescaping the HTML in these types of responses was to use the .NET method Replace.

Is Task.Run or Task.Factory.StartNew a bad practice for windows phone or any other client platform?

I have WP 8.1 app that using web service a lot, and I want to keep it as much responsive as possible. From iOS dev expierense - there is one strict rule: "Do not do in UI thread any complex calculations! Doesnt matter how you will reach this: with blocks or with GCD".

Problem that not all API has async versions, e.g. JSON.NET, SQLite or any own complex algorithm in the app. I have read a lot of articles that are defining Task.Run and Task.Factory.StartNew as bad practice + this.

So, is it good to write code like this? Will it cause some cpu overloading/battery drain or some another performance issues? And if not - what is the right way to make complex operations async(background thread)?

 protected async Task<T> GetDataAsync<T>(string uriString, CancellationToken cancellationToken = default(CancellationToken))
    {
        var uriToLoad = new Uri(uriString);
        using (var httpClient = new HttpClient())
        {
            var data = await httpClient.GetAsync(uriToLoad, cancellationToken).ConfigureAwait(false);
            data.EnsureSuccessStatusCode();
            cancellationToken.ThrowIfCancellationRequested();

            var dataString = await data.Content.ReadAsStringAsync();
            cancellationToken.ThrowIfCancellationRequested();

            // async wrapped call to sync API
            var result = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(dataString), cancellationToken).ConfigureAwait(false);
            cancellationToken.ThrowIfCancellationRequested();

            return result;
        }
    }

Record execution of .Net program in order to debug through it at a later point in time

I have an intergration test and during the execution quite a lot of data originates due to the behaviour of the system under test. Depending on the test run result this data is valuable or not. I therefore have the problem that I must find some "structure" (for every test this would be some other structure I have to come up with because there are many different tests with different data) to store the data in because I might need it - mostly in a later point in time - in order to look it up again.

For me the best (yet I assume quite heavy-weighted in terms of disk usage) solution would be to record the execution (serializing the generated data over time) and have a possibility to "virtually" step through the run any time afterwards.

Is there a tool or a concept with which I can accomplish this or is there some crutial part I'm missing or mistaken about? Looking forward to your input.

mardi 5 mai 2015

Motorola Scanner SDK BarcodeEvent returns Cradle's ID

I have two LI4278 barcode scanners. I want each scanner to beep when one of it reads a barcode that is not in the database. To do this I use BarcodeEvent of the SDK. But the event gives me the id of the cradles not the scanner. Becouse of this i can not beep the scanner. How can i get the id of scanner?

Here is my code;

    private void Form1_Load(object sender, EventArgs e)
    {
            cCoreScannerClass = new CCoreScannerClass();


            //Call Open API
            short[] scannerTypes = new short[1];//Scanner Types you are interested in
            scannerTypes[0] = 1; // 1 for all scanner types
            short numberOfScannerTypes = 1; // Size of the scannerTypes array
            int status; // Extended API return code
            cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
            // Subscribe for barcode events in cCoreScannerClass
            cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
            // Let's subscribe for events
            int opcode = 1001; // Method for Subscribe events
            string outXML; // XML Output
            string inXML = "<inArgs>" +
            "<cmdArgs>" +
            "<arg-int>1</arg-int>" + // Number of events you want to subscribe
            "<arg-int>1</arg-int>" + // Comma separated event IDs
            "</cmdArgs>" +
            "</inArgs>";
            cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
            short numberOfScanners = 2;
            int[] sfScannerIDList = new int[255];
            cCoreScannerClass.GetScanners(out numberOfScanners, sfScannerIDList, out outXML, out status);

    }

    void OnBarcodeEvent(short eventType, ref string pscanData)
    {
        string barcode = pscanData;
    }

Custom attributes in c# for data types

I am thinking about making a custom attribute so that when we are using multiple data readers [SqldataReader] on different objects/tables, we could use the attribute to get the type of the property, and the "columnName" of the property. This way, we could then have a method that takes the data reader as a param, and from there could reflect the attributes to read in the columns. An example of what is currently being done is below, and then an example of what I am trying to accomplish. The problem I am having, is how to manage how to tell it what the (Type) is.

 private static App GetAppInfo(SqlDataReader dr)
    {
        App app = new App();

        app.ID = MCCDBUtility.GetDBValueInt(dr, "APPLICATION_ID");
        app.Name = MCCDBUtility.GetDBValueString(dr, "APPNAME");
        app.Desc = MCCDBUtility.GetDBValueString(dr, "APPDESCRIPTION");
        app.Version = MCCDBUtility.GetDBValueString(dr, "APP_VERSION");
        app.Type = MCCDBUtility.GetDBValueString(dr, "APPLICATIONTYPEID");
        app.AreaName = MCCDBUtility.GetDBValueString(dr, "AREANAME");

        return app;
    }

What I am thinking though, so if I had a class for example like so:

[DataReaderHelper("MethodNameToGetType", "ColumnName")]
public string APPNAME {get;set;}

How could I go about this?

C# .net / mono cross-platform differences?

I've been searching for a while now trying to find an answer for this, basically if I create a visual studio app using .net c# and I want to port it to mac / linux,

  1. Will there be and code I'll have to move around/change when switching to mono?

  2. What things should I avoid doing while developing to make it easier to port later?

  3. Is system.windows.forms usable in mono? Should I just use GTK#? Does it matter?

Fastest way to memoize expression

I have a function, that transform input Expression to output BlockExpression. So I write this code:

    private static readonly Dictionary<Expression, BlockExpression> MemberMemoizeDictionary = new Dictionary<Expression, BlockExpression>(); 
    private static BlockExpression CreateBody<TProperty>(CustomComparer<T> comparer, Expression<Func<T, TProperty>> member, bool createLabel)
        where TProperty : IComparable<TProperty>, IComparable
    {
        BlockExpression expression;
        if (MemberMemoizeDictionary.TryGetValue(member, out expression))
        {
            return expression;
        }

        MemberExpression memberExpression = (MemberExpression) (member.Body is MemberExpression ? member.Body : ((UnaryExpression)member.Body).Operand);
        BlockExpression result = comparer.CreateCompareTo<TProperty>(memberExpression, createLabel);
        MemberMemoizeDictionary[member] = result;
        return result;
    }

but it's not working.

I was thinking that Expressions are immutable, so I can use them as dictionary keys, but I see it's not true.

What is easiest and fastest way to solve this problem? It's always a single member-expression, with a possible convert due to boxing of value-type properties.

How to load and parse HTML without modifying its contents

There are many ways to parse and traverse HTML files using many technologies. But I can not find a suitable one to save that DOM to file again.

I want to be able to load an HTML file into a DOM, change one small thing (e.g. an attribute's value), save the DOM to file again and when diffing the source file and the created file, I want them to be completely identical, except that small change.

This kind of task is absolutely no problem when working with XML and suitable XML libraries, but when it comes to HTML there are several issues: Whitespace such as indentations or linebreaks get lost or are inserted, self-closing start tags (such as <link...>) emerge as <link.../> and/or the content of CDATA sections (e.g. between <script> and </script>) is wrapped into <![CDATA[ ]]>. These things are critical in my case.

Which way can I go to load, traverse, manipulate and save HTML without the drawbacks described above, most importantly without whitespace text nodes to be altered?

Firefox command line print

Have a requirement to print html or html from vb6 application using only firefox as we have already for IE. So, need command to print using firefox.exe.

Something like this firefox.exe -print http://www.google.com which is not working. Is there anyway to do this? Thanks for your help.

How to install executable files of c# windows application in mac os

Please help me. I am developing an application in C# with Front End Visual Studio 2008 and Back End SQL Server 2008 R2. Wen I create an exe of that application will it work on Mac OS?

Need Help. How to start .net programming

I have completed C, C++ and java (object oriented) in previous year. Now, I want to learn .net .But when I am looking for some youtube tutorials, it shows only .net with c#. And also I want to ask how to start journey of .net . If you know any online tutorials, then it will be helpful for me. Thanks in advance

How to bind oxyplot to a gridcontrol?

please i want to bind oxyplot to a gridcontrol to show my data.

<oxy:Plot Title="Binding ItemsSource" Grid.Row="1" Subtitle="123" PlotType="Cartesian" IsRendering="True">
    <oxy:Plot.Series>
        <oxy:LineSeries Title="Value" 
            DataFieldX="Depth"
            DataFieldY="Depth"
            DataContext="{Binding ElementName=grid1}"
            StrokeThickness="2" Color="Blue"  />
     </oxy:Plot.Series>
</oxy:Plot>

what is the practical use of copy Constructor

Ok , I know that Copy Ctor copy the object's data to Another object . But still i m not clear that what is the practical use of Copy ctor in real time Development , I am not finding any satisfying answer , just got definition everywhere

Memory leak in .NET Windows service logging network packets

I am logging packets from the network with a NDIS LWF. The driver sends the packet to a DLL which then passes the data to a .NET service. The service then does some processing on the data and dumps it to a Postgres database. I'm experiencing a memory leak (I think) in the Windows service after what seems to be a random amount of time. When working properly, the average CPU usage for the service is around 3% while the memory is pretty consistent between 15000-20000k. For a yet to be determined reason, the CPU will jump to 25% and stay while the memory will go up to about 95% of total available memory on the system. So a few more implementation details. Within the service, when the DLL calls the .NET service I copy the data over to a byte array within a class object. I then add this object to a ConcurrentQueue and signal an event. Abbreviated code is:

'rawDataIntPtr is an unmanaged BYTE* coming from the C DLL which is then freed once this callback returns

ReDim pkt.data(dataLen)
Marshal.Copy(rawDataIntPtr, pkt.data, 0, dataLen)
gLfq.Enqueue(pkt)
gLfqItemAdded.Set()

A separate thread is used respond to new data and dequeues the data from the queue. As stated above, it does some processing then adds packet information to a Postgres database with a call to ExecuteNonQueryAsync(). Here's the relevant code parts of my consumer thread:

wh(0) = gShutdownEvent
wh(1) = gLfqItemAdded
While (True)
    whRet = WaitHandle.WaitAny(wh)
    If whRet = 0 Then
        Exit While
    End If

    Try
        glfqItemAdded.Reset()
    Catch ex As Exception
        LogError()
    End Try

    While gLfq.TryDequeue(pkt)

        'Do Stuff Here

        query = "INSERT TO DATABASE"
        ExecuteNonQueryWrapperAsync()

        'I've tried the various things to try and clear
        'all references to the byte array and packet object
        'thinking this was my problem
        ReDim pkt.data(0)
        pkt.data = Nothing
        pkt = Nothing
    End While
End While

I've tried SciTech's .NET Memory Profiler 5.0, and it shows, when the CPU and memory spike, that there are an abundance of byte arrays currently allocated which makes sense. But that alone isn't very useful and it's not the easiest tool in the world to understand. I suppose if it was a memory leak though, I'd see a slow increase in memory usage however, that's not the case. So my issue is maybe it is not a memory leak but perhaps a component falling behind in processing which then causes a backlog of data. But I don't understand why it will work fine for a period of time then suddenly just spike and get out of whack. Network usage is pretty consistent as well so I don't believe it has to do with spikes in traffic. If more code is needed or additional details, let me know. Or if my design is messed up, I'd like to hear that too. Thanks.

Testing an asynchronous WCF service using MSTest

I've implemented a WCF service using the async\await method in C#. The service operation contract is as follows:

[OperationContract]
Task<ResponseMessage<ProcessMultipleTransactionsResponse>> ProcessMultipleTransactionsAsync(RequestMessage<ProcessMultipleTransactionsRequest> msgIn);

The method signature for the implementation is:

public async Task<ResponseMessage<ProcessMultipleTransactionsResponse>> ProcessMultipleTransactionsAsync(RequestMessage<ProcessMultipleTransactionsRequest> msgIn)

I'm trying to test this service using a unit test in VS 2012. After building a proxy I consume the method using:

var actual = await target.ProcessMultipleTransactionsAsync(request);

The test method has the async keyword with a Task as the return type. When executing the test I'm getting the following error:

Test method Services.Implementations.UnitTests.CoreBanking.CoreBankingServiceTest.ProcessMultipleTransactions_JMD_JMD_ACHTransactions_Test threw exception: System.ArgumentException: An incorrect IAsyncResult was provided to an 'End' method. The IAsyncResult object passed to 'End' must be the one returned from the matching 'Begin' or passed to the callback provided to 'Begin'. Parameter name: result

Result StackTrace:
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result) at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result) at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result) at System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.<>c__DisplayClass21.<CreateGenericTask>b__3(IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Services.Implementations.UnitTests.CoreBanking.CoreBankingServiceTest.d__10.MoveNext() in c:...\CoreBankingServiceTest.cs:line 5716 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

Any ideas what may be causing this?

how to show new column value in aspx file without compilation [on hold]

I need a mechanism to fetch data from table and put it in aspx file without touching the cs file.I have an asp.net application where back end is SQL server. Label value is populated from SQL tables. Suppose I have added new column in one of the tables and need to show the new column value in aspx page, how it is possible to do without a compilation.

Means I don't want to change cs files, but I am okay to change aspx files

Currently there is no dataset is available in aspx page, each value in columns are assign to each label in c# file, Since dataset is not available how I can add new column value and another new label in aspx file.

Delphi COM vs DLL in .NET

Need to create a Delphi DLL that can be called from Delphi and .NET. What does .NET like more, COM or dll? Or does it matter?

I just remember hearing that COM can be annoying because of versioning.

.Net - Serializable issue with List with Session stored in SQL Server

We are using .Net 4.0 and SQL Server for our Session Store.

We have marked all our objects as [Serializable] but we are still getting the error:

System.Web.HttpException (0x80004005): Unable to serialize the session state.

In turns out the issue is with a call to a ToList method we have implemented

if (licenseHoldings != null && licenseHoldings.**ToList()**.Any())

And the implementation of LicenseHoldings contains this method

public List<License> ToList()
    {
        var list = new List<License>();

        if (SerializableObject != null)
            list.Add(SerializableObject);

        return list;
    }

Appreciate any guidance on why a List of a serializable object is not serializable to a SQL Server session and on an alternative implementation to this method.

A first chance of exception type 'System.FormatException' occurred in mscorlib.dll

I am having some major issues with a program I am writing. I have gotten this far but I can't find the issue with my code at all. The program is supposed to calculate the total cost of an appliance.

All of the appliances in the list work except for the "Washer" which requires me to take the "CostPerGallon" and the "GallonsUsed" and multiply them to find a WaterCost. I add the WaterCostand the "CostPerDay" I've calculated to find the total. For some reason I'm getting this exception ONLY when I try to calculate the Washer cost.

I have tried to find where the exception is occurring, but I am unable to pinpoint exactly where. The best guess I can come up with is the nested "IF" statement that does the calculations for dblCostPerDay and dblWaterCost and then adds them together.

I have put TryParse into both the "GallonsUsed" and "CostPerGallon" inputs to try and catch and issues, but that's still not working. Here is the code:

    ElseIf lstAppliances.SelectedItem = "Washer" Then
        If Double.TryParse(txtGallonsUsed.Text, dblGallonsDay) = False Then
            lblErrorMsg.Text = "Gallons Used must be a number."
            lblErrorMsg.Visible = True
        Else
            dblGallonsDay = Convert.ToDouble(txtGallonsUsed.Text)
        End If
    Else 'If all of the inputs pass validations, the calculation will take place
        dblCostPerHour = Convert.ToDouble(txtCostPerHour.Text)
        dblHoursPerDay = Convert.ToDouble(txtHoursDay.Text)
        dblPowerNeeded = Convert.ToDouble(txtPowerNeeded.Text)
        If lstAppliances.SelectedItem = "Washer" Then
            dblCostPerDay = dblCostPerHour * dblHoursPerDay * dblPowerNeeded
            dblWaterCost = dblCostPerGallon * dblGallonsDay
            dblCostPerDay = dblCostPerDay + dblWaterCost
        Else
            dblCostPerDay = dblCostPerHour * dblHoursPerDay * dblPowerNeeded
        End If
        dblTotalCost = dblTotalCost + dblCostPerDay
        txtApplianceSelection = lstAppliances.SelectedItem.ToString
        txtListString = (txtApplianceSelection & "     " & dblHoursPerDay & "     $" & Math.Round(dblCostPerDay, 2) & "     $" & Math.Round(dblTotalCost, 2)) 'Here we build our string
        ListView1.Items.Add(txtListString)

    End If
End Sub

libgit2sharp create pull request

.NET 4.0 C#

Using libgit2sharp, I've written code to create a new branch, change some files, push branch to GitHub.

Now I need to create a pull-request. However, my Google searches don't turn up any relevant info.

Does libgit2sharp support creating PRs ? If not, what are other options ?

.Net CF: ComboBox.Text setting fails to match exact list item

Compact Framework ComboBox issue. I have several items in the list, 2 of them are "M3" and "m3". When using ComboBox.Text="m3" in code, value only matches "M3". It's matching the first letter without regard to exact match or case.

ComboBox doesn't have the auto-complete settings in CF as far as I know. DropDownStyle is DropDownList. I tried DropDown but it doesn't work consistently, plus I need it as a list. I also tried SelectedValue.

How to reference .dll on a different .NET framework in VS 2010

I work on a product that is running on .NET 2.0. Yes, this is horrible and outdated, I know, but several of our clients have enough trouble just configuring firewalls to connect to our servers that it'd be chaos to change this. I happen to know that several of them are still running XP.

I'm running into problems when I try to convert the product to VS 2010 because the reference to a .dll compiled with a target framework of 3.5 is no longer valid.

Changing the target framework of the dll compiled with .NET 3.5 to .NET 2.0 would be an immense amount of work, because the source would have to be almost entirely rewritten.

Is there any way to add a reference to a dll compiled with .NET 3.5 in the project with a target of .NET 2.0? Again, whether correct or not, the project in VS 2005 is able to reference this without any problems.

How can we debug web application on Visual Studio Code?

Microsoft just released Visual Studio Code a couple of days ago.

How can we debug ASP.NET MVC applications from within that IDE?

Windows Universal App maintain open WebSocket

How to have a WebSocket open on Windows Universal App? Can I have my WebSocket be open even when app is closed?

How do I name my deployed application?

I've successfully installed Windows 10 IoT on my Raspberry Pi 2. I wrote a test "Hello World" UAP app (simple text box and button, using Visual Studio Community 2015 RC) and can run it on the Pi and debug it (set break points, etc). When I build it for Release and deploy it to the Pi, I see the following in the Visual Studio build output:

Full package name: "93b8b47e-8bbe-46d9-8a30-4cf697efc3d9_1.0.0.0_arm__3e1tqk2ntzwa4"

When I run the following command in PowerShell connected to the Pi:

iostartup list

I see a list of server installed applications, including:

Headed   : 93b8b47e-8bbe-46d9-8a30-4cf697efc3d9_3e1tqk2ntzwa4!App

The tutorial I was following says I should see something like:

Headed   : HelloWorld_n2pe7ts0w7wey!App

I don't see anything with the name "HellowWorld" in it, only that GUID'ish looking name that matches the name shown in the build output. How can I set the name of the deployed application to a more friendly name? It would make it easier for setting the application to start during boot of the Pi, etc. BTW, my VS solution and project are both named HelloWorld.

Do I need to secure my private REST API?

I recently developed a RESTful service that my windows desktop application is using for retrieving information from a MySQL DB sitting on a Linode server. The desktop application is written in .Net and obfuscated so that all urls are encoded. I developed the RESTful service in Spring but had a lot of issues with Spring Security and I was thinking that maybe authentication is not necessary as I am the only user. If the code is obfuscated then it will be hard for anyone to get the endpoints and start using my web service. So question is, is my logic valid or should I secure my API even if I have to struggle with OAuth and Spring?