dimanche 28 juin 2015

SignalR or simillar for winforms

I need to know if there is something like SignalR but for Winforms, some nuggets or library for paid, someone who can guide me please.

The beginning of my problem is that I have the need to obtain data automatically when the table is updated.

Thanks.

Parallel.ForEach stops being parallel for the last few items

I have an external singlethreaded program that needs to be run multiple hundred times with different parameters. To make it faster I want to run it once for each core at the same time. To do that I used Parallel.ForEach running on a list with the different parameters to pass to the external program:

var parallelOptions = new ParallelOptions {
    MaxDegreeOfParallelism = Environment.ProcessorCount // 8 for me
};

Parallel.ForEach(ListWithAllTheParams, parallelOptions, DoTheStuff);

...

private void DoTheStuff(ParamType parameter, ParallelLoopState parallelLoopState, long index)
{
    // prepare process parameters etc.
    theProcess.Start();
    theProcess.WaitForExit();
}

Pretty straightforward and works nicely... until the last ~10 items - they don't get parallelized for some reason and just run one after another. I've confirmed this by looking at the cpu usage and the running programs in the Task Manager.

This does not happen when I populate the parameter list with only a few (say, 10) items.

Can somebody explain this behavior to me? Any hints or tips appreciated!

Accuracy of the decimal number type versus the double type in .Net

Consider the following code:

    Dim doubleResult = (21 / 88) * 11
    Dim decimalResult = Decimal.Divide(21, 88) * 11

The doubleResult is 2.625, as it should.

The decimalResult is 2.6249999999999996, so when rounding this to two decimal places will give an incorrect result.

When I change the assignment to:

    Dim decimalResult = Decimal.Divide(21 * 11, 88) 

The result is 2.625!

We adopted the decimal type in our application hoping that it would give us increased accuracy. However, it seems that the decimal type just gives slightly incorrect results on other calculations than the double type does, due to the the fact that it is ten based, rather than two based.

So, how do we have to deal with this idiosyncrasies to avoid rounding errors as above?

Keeping graphics unaltered when TabPage changes

I have a form that displays a set of graphics using a Paint event on a Panel that is docked inside a particular TabPage of a TabControl.

The problem is the following:

When the user switches to a different TabPage and then decides to go back to the TabPage where the graphics were originally displayed, those graphics are invalidated by default so the Panel appears blank.

I would like those graphics to stay unaltered and totally independent from the user's action when switching between different TabPages.

One Requirement:

Since the graphics are complex and take some time to be drawn by the computer, I don't want to repaint the graphics each time by calling the Paint event repeatedly. Instead, I only need to avoid the default invalidation of the graphics.

I have read this other question which may be helpful to solve my problem but it goes beyond my knowledge.

ODBC vs JDBC in social network mobile app?

I want to create an social network app. I use odbc connection in mvc web services to connect database.

I want to know in the future if many users use my app ODBC is enough for many connections or should I use JDBC connection ?

thanks in advance

After deploying site created with last version of Umbraco on iss the css and images are broken

enter image description here

I have made all the usual steps for deploy on iss. The IUSRS -NetworkService has full rights on the web project

Suitable Control for displaying various game levels in a WP8 App

There is a mobile game on which I am working. It has various difficulty sections and each section has numerous levels, 250 levels in each section precisely.

Now, I need a suitable control which can display all the levels and by tapping on a certain level's button/icon, the user is able to move on and play that level.

I tried using a simple ScrollViewer, but that is way too much scrolling for the user even if I display 10 levels in a single row.

So, is there any inbuilt/existing control in WP that I can use to solve my problem?

P.S. Do remember, there are more than 250 levels that need to be displayed.

Many thanks in advance. Cheers!

Add the Text Form Field to the MS Office Word Document

Does anybody know how can I insert the Text Form Field to the MS Office Word 2003 Document (.doc)? And I also want to set the read-only property fo this field. How can I do this with C#?

How to do a SQL Server DB schema update with zero downtime

What do you think is the best way of updating an existing SQL Server (we are using SQL Server 2014, but could update to 2016) database schema (incl its data) with zero downtime of the overall system, i.e. applications using the database?

The business requirements is to have a zero downtime of all the applications and services using the database. We could say we only do backwards and forward compatible database schema changes, e.g. adding columns, but not removing existing columns.

Of course the business would like to have a backup before we do the database change, in case something goes really wrong and we need to rollback.

The system is transactions heavy, meaning potentially thousands of transactions per second.

The applications are .net applications, where most of them run in an IIS execution container at the moment (maybe we switch to some other form like self-hosted service etc.) and exopsing their functionality through Web Services.

What would be your approach?

unit test to check uniqueness of million generated strings

I would like to write a unit test to

1) go through a list of 1 million unique random generated strings.

2) Ensure that each numer is 100% unique and there are no duplicates.

What is the best way to check and compare that there are no duplicates.

I have a List<List<int>> set of data, with string representation like this (to give the idea!):

 {{1,3},{-1,-3},{2,5},{-2,-5},{-3,4},{-5,4},{3,5,-4},{6,-8},{7,-8},{-6,-7,8},{7,9},{-7,-9},{3,8,-10},{-3,-8,-10},{-3,8,10},{3,-8,10},{4,9,-11},{-4,-9,-11},{-4,9,11},{4,-9,11},{10,11},{-1,6},{1,-6},{-2,7},{2,-7}}

I want to check if ,in all present numbers, exist a number or set of numbers which only are in positive form. I mean if in the whole data, there is 3 and -3 I should return false, otherwise I have to add 3 as a number which only is present as positive 3, in to another list. (Same thing for only negated number)

Here is how I am trying to do it:

First, generate a unique set of numbers and remove negatives:

private void GenerateCurrentExistingVariables()
{
    _uid = new List<int>();
    var all = _cnf.Data.SelectMany(list => list).ToList();
    _uid = all.Distinct().ToList(); //make list unique
    _uid.Sort(); //sort numbers
    _uid.Reverse(); //reverse so highest numbers would evalaute first!
    _uid = _uid.Where(i => i >= 0).ToList(); //remove negative numbers
}

Then I do something like this:

in a method, I call the code below:

    for (var i = 0; i < _uid.Count; i++)
    {
        if (ExistOnlyInNegatedForm(_uid[i]))
        {
            onlyNegatedList.Add(_uid[i]);
        }

        //perhaps continue

        if (ExistOnlyInPositiveForm(_uid[i]))
        {

            onlyPositiveList.Add(_uid[i]);
        }
    }

Which in turns calls the methods below:

private bool ExistOnlyInPositiveForm(int id)
{
    for (var i = 0; i < _cnf.Data.Count; i++)
    {
        for (var j = 0; j < _cnf.Data[i].Count; j++)
        {
            if (_cnf.Data[i][j] == id)
            {
                return false;
            }
        }
    }

    return true;
}

private bool ExistOnlyInNegatedForm(int id)
{
    var toCheck = -id;
    for (var i = 0; i < _cnf.Data.Count; i++)
    {
        for (var j = 0; j < _cnf.Data[i].Count; j++)
        {
            if (_cnf.Data[i][j] == -toCheck)
            {
                return false;
            }
        }
    }

    return true;
}

This is too much code for this simple task and I feel that this is getting slower and slower when data grows larger...please let me know how can I improve this. Also I would like this to be done using LINQ at least for the sake of less lines of code!

I would love to see a C++ solution as well, so I am tagging c++ in my question (not doing language spam!)

How can i convert and compress in real time batch of images to mp4 video file?

In my directory on the hard disk i have many images: screenshot000001.bmp , screenshot000002.bmp....screenshot001200.bmp

I want to do two things:

  1. For testing using the CMD and to compress and convert the images to mp4 video file.

  2. In my program in real time while my program take the screenshots and save them to the hard disk to compress them and build the mp4 video file in real time.

For the first part i tried to type in cmd :

ffmpeg -f image2 -i screenshot%d.bmp -vcodec libx264 -b 800k video.avi

But what i got is two errors:

[image2 @ 0000000004766380] Could find no file with path 'screenshot%d.bmp' and index in the range 0-4 screenshot%d.bmp: No such file or directory

I copied the ffmpeg.exe to the directory where the images are in. E:\screenshots

For the second part this how i'm taking the screenshots in real time:

A button click event that start a timer:

private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

Then in the tick event:

    ScreenShot shot = new ScreenShot();
    public static int counter = 0;
    private void timer1_Tick(object sender, EventArgs e)
    {
        counter++;
        shot.GetScreenShot(@"e:\screenshots\", "screenshot");
        if (counter == 1200)
        {
            timer1.Stop();
        }
    }

This line shot.GetScreenShot(@"e:\screenshots\", "screenshot"); save the screenshots to the hard disk. Here after each screenshot save i want to compress and build the mp4 video file in real time.

Showing widget demo in mobile view

I am creating a intranet application to my company which contains different plugins developed by us or commonly used plugins. It is a responsive design. Now I have a new requirement to show the widget demos in different mobile devices like iphone, android etc.

My lead show me this example http://ift.tt/1GUdTos

Based on the device selection we need to show plugins in different devices. For example I have a widget named datatable, I need to enable different views for this. How can i achieve it. I dont have any idea how to implement it. Please help

TeamCity + ASP.NET Webapp: Error about unclosed string literal?

I have a solution where all projects are targeting .NET v4.5.1.

TeamCity (v9.0.4) previously has built the solution just fine.

Added an Asp.Net web application (MVC + WebAPI) to the solution, still targeted at .NET 4.5.1.

It Works on My Machinetm, but TeamCity now fails the build with the following MSBuild error:

[src\app\Web\Web.csproj] C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets(186, 67): error MSB4025: The project file could not be loaded. There is an unclosed literal string. Line 186, position 67.

Those might be the line numbers in the targets file that threw the error, because in my file all I see is a </ProjectReference> (which corresponds correctly to two project references that are there.

Any idea what could be causing this?

Insert and Delete error Gridview ASP.NET

I am using SQL command to insert and delete into the grid but getting errors in implementation. How can I write the syntax This is the HTML code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html xmlns="http://ift.tt/lH0Osb">
    <head id="Head1" runat="server">
        <title> </title>
    </head>





<body>

    <form id="form1" runat="server">
        <div>
            <asp:Label ID="label" runat="server">New Task</asp:Label>
            <asp:TextBox ID="textbox1" runat="server" placeHolder="Type  
            new task summary here, and click add" Width="353px">    
            </asp:TextBox>
            <asp:Button ID="button1" runat="server" OnClick="click_add" 
            Text="Add" style="margin-left: 54px" Width="67px" />
            <br />
        </div>

        <asp:GridView ID="grdStatus" runat="server" 
        OnRowCommand="grdStatus_RowCommand" AutoGenerateColumns="false">
        <Columns> 
            <asp:TemplateField HeaderText="Done?">
                <ItemTemplate>
                    <asp:CheckBox ID="checkbx" runat="server" 
                    Checked='<%#Eval("Done") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ID">
                <ItemTemplate>
                    <asp:Label ID="label12" runat="server" 
                    Checked='<%#Container.DataItemIndex+1 %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Summary">
                <ItemTemplate> 
                    <asp:Label ID="label3" runat="server" 
                    Checked='<%#Eval("Summary") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Created On">
                <ItemTemplate>
                    <asp:Label ID="label4" runat="server" 
                    Checked='<%#Eval("Date")%>' ></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:ImageButton ID="dltButton" runat="server" 
                    ImageUrl="~/images/delete.png"   
                    CommandName="DeleteTask" Text="Delete" Width="30px" 
                    Height="30px" CommandArgument="<%#     
                    Container.DataItemIndex%>" />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
        </asp:GridView>


    </form>
</body>
</html>

The c# code is this using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.Configuration; using System.Data.SqlClient;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string connectionString =    
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        string selectSQL = "SELECT * FROM Table";
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            adapter.Fill(ds, "Table");

            grdStatus.DataSource = ds;
            grdStatus.DataBind();
        }
    }
    protected void click_add(object sender, EventArgs e)
    {

            string connectionString =   
  WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("INSERT INTO 
            Table(ID,Summary,Created) values ('" + checkbx.Text + "'" + 
            Convert.ToInt32(cmd.Parameters["label2"].Value.ToString()) + 
            "'" + label3.Text + "'" + label4.Text + "'", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();


    }

    protected void grdStatus_RowCommand(object sender, EventArgs e)
    {
        if(e.CommandName == "DeleteTask")
        {
            string connectionString =    
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string query = "delete from Table where id=" + 
            e.CommandArgument + "'";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
            fillgrid();
        }
   }

}

VB.Net Code Formatter Like perltidy for perl

Good day!

Are there any code formatter for vb.net that can automate code formatting? like perl's perltidy.

I know I can do it manually but the class that I'm working on is getting bigger and I need a constant formatting for all.

Thank you!

Applying dynamically built expression on collection throws exception

I have the following class:

public class Order
{
    public string Code { get; set; } 
}

And I have built dynamically an Expression, which looks like this:

enter image description here

and I'm building an extension method which looks like:

enter image description here

I have a list of orders which, List<Order> of the expression type and when I apply the filter like this:

var buildExpressionFilter = dynamically constructed Expression here
var orders = GetOrders();
var result = orders.Where(buildExpressionFilter).ToList();

I get the following error: enter image description here

Is obviously that buildExpressionFilter is not properly constructed but I cannot figure out what is the issue.

Does anyone have an idea on how to fix this issue? What may be wrong with my buildExpressionFilter?

Calling a VST plugin with VST.net in Unity3D. Is it possible?

I dont have any experience with VST. Just started researching.

I need to call the member function VSTPluginMain from my VST dll to do some custom audio processing in my Unity 5 project. For a VST host, I added VST.NET 1.0 CLR2 X64 Release dlls in my project. I've read Unity supports only Common Language Runtime 2.

The documentation for VST.net is not working (a blank .chm file and the online version is incomplete). I wasn't able to find any useful samples in the VST.net project templates. Also, does Unity support VST? (the Unity forums are silent about this matter)

Any help is greatly appreciated.

Thank you

Self-hosting ASP.NET 5 within .NET 4.5 Application (without DNX and IIS)

Is it possible to add an ASP.NET 5 Web Application as a reference to a traditional .NET 4.5 project (Windows Service or Console App) and start it in-process?

Ideally within one solution, so that ASP.NET application and host service can share references to other projects in the same solution.

Tried so far:

dnu publish produces packages, but attempting to add them produces following error: Install-Package : Could not install package 'WebApplication1 1.0.0'. You are trying to install this package into a project that targets '.NETFramework, Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. When changing framework dnx451 to net451, Web Application doesn't compile because of missing ASP references.

dnu build produces binaries, but how to run the application? (where to get IApplicationBuilder and IHostingEnvironment instances?)

C# searching and getting Absolute Path of Software

I am new to C# and I want to create a little Autorun Manager in a Console Application. To do that I want to read from the console a keyword like "Steam" and my programm should search on "C:\" and in all subdirectories for a folder called like my keyword but as I say I have no Idea how I can search in all subdirectories.

Thats a little code sample with steam how I would write in registry

//filePath would be the Path of the .EXE file that was found    
string filePath = "\"C:\\Programme\\Steam\\Steam.exe\""; 
string autostartPath = @"Software\Microsoft\Windows\CurrentVersion\Run\";
RegistryKey autostart = Registry.CurrentUser.OpenSubKey(autostartPath, true);
autostart.SetValue("Steam", filePath);

If someone know how to search in all subdirectories and find the correct .exe file.

I would be really grateful for a code sample.

Thanks in advance

How can i take a screenshot of the pictureBox1 handle window?

I'm using this class but that take a screenshot of the desktop handle. And i need to take a screenshot of the pictureBox1 handle.

#region Class Imports 
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
#endregion

namespace Test
{
    /// <summary>
    /// Class for taking a screen shot in code
    /// </summary>
    public class ScreenShot
    {
    /// <summary>
    /// Global variable declarations
    /// </summary>
    #region Global Variables
    private Bitmap _screenShot;
    protected static IntPtr newBMP;
    #endregion

    #region Constants
    public const int SRCCOPY = 13369376;
    public const int SCREEN_X = 0;
    public const int SCREEN_Y = 1;
    #endregion
    /// <summary>
    /// Hold the definition for the
    /// class properties
    /// </summary>
    #region Class Properties
    [Description("Gets the screenshot image")]
    public Bitmap ScreenImage
    {
        get { return _screenShot; }
    }
    #endregion

    #region Constructor
    /// <summary>
    /// Constructors for our class
    /// </summary>
    [Description("Empty constructor, instantiating _screenShot to nothing")]
    public ScreenShot()
    {
        _screenShot = null;
    }              
    #endregion

    #region Methods
    /// <summary>
    /// Method for creating an image of the current desktop
    /// </summary>
    /// <returns>A Bitmap image</returns>
    [Description("Creates an image of the current desktop")]
    public Bitmap GetScreen()
    {
        int xLoc;
        int yLoc;
        IntPtr dsk;
        IntPtr mem;
        Bitmap currentView;

        //get the handle of the desktop DC
        dsk = Win32API.GetDC(Win32API.GetDesktopWindow());

        //create memory DC
        mem = Win32API.CreateCompatibleDC(dsk);

        //get the X coordinates of the screen
        xLoc = Win32API.GetSystemMetrics(SCREEN_X);

        //get the Y coordinates of screen.
        yLoc = Win32API.GetSystemMetrics(SCREEN_Y);

        //create a compatible image the size of the desktop
        newBMP = Win32API.CreateCompatibleBitmap(dsk, xLoc, yLoc);

        //check against IntPtr (cant check IntPtr values against a null value)
        if (newBMP != IntPtr.Zero)
        {
            //select the image in memory
            IntPtr oldBmp = (IntPtr)Win32API.SelectObject(mem, newBMP);
            //copy the new bitmap into memory
            Win32API.BitBlt(mem, 0, 0, xLoc, yLoc, dsk, 0, 0, SRCCOPY);
            //select the old bitmap into memory
            Win32API.SelectObject(mem, oldBmp);
            //delete the memoryDC since we're through with it
            Win32API.DeleteDC(mem);
            //release dskTopDC to free up the resources
            Win32API.ReleaseDC(Win32API.GetDesktopWindow(), dsk);
            //create out BitMap
            currentView = Image.FromHbitmap(newBMP);
            //return the image
            return currentView;
        }
        else  //null value returned
        {
            return null;
        }    
    }
    #endregion

    #region Helpers
    [Description("Takes the information from GetScreen and creates a Bitmap image")]
    public void GetScreenShot(string folder, string name)
    {
        //check to see if the folder provided exists
       /* if (!Directory.Exists(Application.StartupPath + "\\" + folder))
        {
            //if it doesnt exist then we need to create it
            Directory.CreateDirectory(Application.StartupPath + "\\" + folder);
        }*/
        //set the ScreenImage Property to the
        //BitMap created in GetScreen()
        _screenShot = new Bitmap(GetScreen());
        //create a name based on the name passed in
        string ingName = folder + name + Elgato_Video_Capture.counter.ToString("D6") + ".bmp";
        //save the image
        _screenShot.Save(ingName);
        _screenShot.Dispose();
    }
    #endregion
    }

}

Then i'm using it like that:

    ScreenShot shot = new ScreenShot();
    public static int counter = 0;

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter++;

        shot.GetScreenShot(@"e:\screenshots\", "screenshot");
        if (counter == 1200)
        {
            timer1.Stop();
        }
    }

I need to take a screenshot of the pictureBox1.Handle window not the pictureBox1.Image. The problem is that the class ScreenShot take a screenshot of the desktop Handle and i want to take a screenshot only of the pictureBox1.Handle

Outlook Message - Disable left mouse click on a hyper-link or prevent Outlook to follow clicked hyper-link

Is there a way to intercept mouse click on a hyper-link within current Outlook Message? What I need is to figure out a way to either intercept LEFT mouse click when user tries to click on a hyper-link or to prevent Outlook to open clicked hyper-link...

I hope this is not too confusing and someone can help me with it.

Thank you!

Socket connection coming from LAN?

Is there a way to check if an incoming connection on a TCP socket is coming from a LAN or not?

I'm currently checking the incoming address and seeing if it resides in the private network range (192.168.x.x/10.x.x.x etc)

Is there a better way to do it?

I'm particularly interested in solutions in Python and .NET if that helps.

Error while reversing document in SAP using BAPI

Using BAPI_ACC_DOCUMENT_REV_POST to reverse entries posed via BAPI_ACC_DOCUMENT_POST, however we are getting following errors

E RW 609 Error in document: BKPFF $ SYS600 BKPFF

E RW 632 Document BKPFF 900026 SYS600 cannot be reversed BKPFF

E RW 630 Reversal in component Financial Accounting not possible Financial Accounting

E F5A 9 Reversal not possible, accounting document for the ref. does not exist BKPFF

code for reference

Dim companyAPI As IRfcFunction = _ecc.Repository.CreateFunction("BAPI_ACC_DOCUMENT_REV_POST")
    Dim rev As IRfcStructure = companyAPI.GetStructure("REVERSAL")
    rev.SetValue("OBJ_TYPE", "BKPFF")
    rev.SetValue("OBJ_SYS", "$")
    rev.SetValue("OBJ_KEY", "900026N0342016")
    rev.SetValue("OBJ_KEY_R", "900026N0342016")
    rev.SetValue("COMP_CODE", "D756")
    rev.SetValue("REASON_REV", "01")
    Dim transfunction = _ecc.Repository.CreateFunction("BAPI_TRANSACTION_COMMIT")
    transfunction.SetValue("WAIT", "X")
    companyAPI.Invoke(_ecc) 
    transfunction.Invoke(_ecc)
    Dim dt As DataTable = GetDataTableFromRFCTable(companyAPI.GetTable("RETURN"))

After image resize transparency is removed - gdi+

I am reading an image from file that contains transparency area in the center (frame image type).

 Image myFrame = Image.FromFile("d:\mypngfile.png");

After i call image resize custome function:

myFrame = resizeImage(myFrame, new Size(otherbmp.Width, otherbmp.Height));

The problem is that after reszing the image it seems transparency is removed.

resize function:

 public Image resizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;
        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;
        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;
        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);
        Bitmap b = new Bitmap(destWidth, destHeight,PixelFormat.Format32bppArgb);
        b.MakeTransparent();
        Graphics g = Graphics.FromImage((Image)b);
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.CompositingMode = CompositingMode.SourceOver;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();
        return (Image)b;
    }

After i am checking the alpha pixels which doesn't work after resize (it does work before resizing and returns a value). It always return 0!

  public int GetBorderWidth(Bitmap bmp)
            {
                var hy = bmp.Height/ 2;


                while (bmp.GetPixel(0, hy).A == 255 && sz.Width < hx)
                    sz.Width++;

                 return sz.width;
             }

I can't seem to solve this issue no matter what i try...

How to submit form and load view with results

How do I submit a form and loads the results from the request in a new view.

I have the following routes

    routes.MapRoute(
        name: "Default",
        url: "{controller}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "GetResults",
        url: "{gueryString}",
        defaults: new { controller = "Result", action = "ShowResults", gueryString = "" }
    );

I have a index view with includes a partial view of my form I want to submit.

@Html.Partial("../Result/SearchForm")

The form itself is

  @using (Html.BeginForm("ShowResults", "Result", method: FormMethod.Post))
    {
        <form role="form">
            <div class="input-group input-group-lg">
                @Html.TextBoxFor(m => m.searchString, new { @class = "form-control" })
                <a href="javascript:$('form').submit();" class="input-group-addon">
                    <i class="fa fa-search"></i>
                </a>
            </div>
        </form>
    }

The new action itself in class ResultController

 public ActionResult ShowResults(SearchSubmitModel model)
    {

        RequestExternalComparisonData.ValidateSearchString(model);
        ViewBag.GameComparisonList = RequestExternalComparisonData.DoSearch(model.searchString);
        return View();
    }

The problem is the default index action is always ran on the form submit unless I completely remove the default route, but I need to initially load the index with my form. How do I trigger my new action on the form submit?

Unable to dowload file using generic handler

I am using a generic handler to download csv/excel files. It was working fine until yesterday. Today suddenly it stopped working on deployment on IIS 7.5 (though he same code works well in visual studio debugging mode). Here is my code:

ASPX: This is a content page

<input type="button" class="btn-primary" id="btnDownload" title="Download" value="Download" onclick='return downloadReport(this);' data-toggle="modal" data-target="#myModal" navurl='<%: ResolveUrl("~/Handlers/DownloadData.ashx") %>' />

JS:

function downloadReport(btn) {
//I am using a kendoUI combo box and kendo js + also using bootstrap for design & modal popups & also i have applied bundling to kendo & bootstrap files. They seem to be working fine without any conflicts as all their api's are working.
var $mod = $("#masterModal");
    $mod.modal('show');
    //window.location = "Handlers/DownloadData.ashx?rtp=" + combobox.val();
    window.location.href = $(btn).attr("navurl") + "?rtp=" + combobox.val();
    setTimeout(function () {
        $mod.modal("hide");
    }, 2000);

    return false;
}

Master Page:

I am including the js file containing the above method just before end of body tag.

<script src='<%: ResolveUrl("~/Scripts/DataUploader.js") %>'></script>  
</body>
</html>

Handler: In handler Process Request Method

HttpResponse response = this._context.Response;
            HRReportData hrData = new HRReportData(ConfigMaster.DbProvider, ConfigMaster.ConnectionString, ConfigMaster.DBSchemaName);
            ReportDataManager rdm = null;
            ExcelPackage xlPackage = null;
            try
            {
                rdm = new ReportDataManager();
                DataSet ds = rdm.GetReportData(hrData, report_Type);
                if (ds != null && ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        xlPackage = new ExcelPackage();
                        ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add(report_Type.ToString());
                        worksheet.Cells["A1"].LoadFromDataTable(ds.Tables[0], true, TableStyles.Light1);
                        response.ClearHeaders();
                        response.ClearContent();
                        response.Clear();
                        response.ContentType = "application/octet-stream";
                        response.AppendHeader("content-disposition", "attachment;  filename=" + report_Type.ToString() + ".xlsx");
                        xlPackage.SaveAs(response.OutputStream);
                        response.Flush();
                        //response.Close();
                        //response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                //LogError.MethodLevelError(Convert.ToString(Session["Username"]), ex);
                if (!(ex is System.Threading.ThreadAbortException))
                {
                    //Other error handling code here
                }
            }
            finally
            {
                if (xlPackage != null)
                {
                    xlPackage.Dispose();
                    xlPackage.Dispose();
                }
            }

Bundle config:

bundles.Add(new ScriptBundle("~/Kendo/kendo").Include(
                "~/Scripts/jquery-1.11.3.min.js",
                "~/Kendo/js/kendo.all.min.js"
               // "~/Scripts/DataUploader.js"
            ));
            bundles.Add(new ScriptBundle("~/bootstrap/bootstrap").Include(
                "~/bootstrap/js/holder.js",
                "~/bootstrap/js/ie10-viewport-bug-workaround.js",
                "~/bootstrap/js/ie-emulation-modes-warning.js",
                "~/bootstrap/js/bootstrap.min.js"
            ));

All above code works well in debugging mode and was working well in deployment mode as well. Don't know what has changed that it suddenly stopped working and I am unable to find out any reasons :(

Behaviour on deployment: Instead of staying on same page and downloading file it navigates to Handler and a blank screen is displayed. No file is downloaded.

Behaviour in debuuging mode OR when run using vs2012 express: It stays on same page and downloads the file as expected.

Somebody please help me on this.

Rest method in wcf service

I want to create method in my WCF service that will return json.

Service code:

public interface IParseService
{
    [OperationContract]
    IList<SocialEventDto> GetSocialEvents(int pageNumber = 1);

    [OperationContract]
    [WebGet(UriTemplate = "/socialevents/{pageNumber}",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    IList<SocialEventDto> GetSocialEventsJson(string pageNumber);

    [OperationContract]
    IList<ServiceOptionDto> GetServiceOptions();
    //some other methods...
}

web.config:

<system.serviceModel>
    <services>
        <service name="ParserWebRole.ParseService">
        <endpoint address=""
                  binding="webHttpBinding"
                  behaviorConfiguration="webBehavior"
                  contract="ParserWebRole.IParseService"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

When I try to invoke

http://localhost:18549/ParseService.svc/socialevents/1 

I get

This webpage is not available

What am I doing wrong?

I saw similar questions but none of them help me.

Enterprise Windows Store Apps publishing and distribution, Need clarifications on license requirements?

It is understood, need to get license for publishing and distributing Windows Store Apps. But it is not clear how much it costs and procedure. Please clarify the following:

My app has a requirement to not to publish the app in store, but to distribute it internally. Sideloading seems to be option.

  1. But I'm confused what are costs for doing so? For sideloading, it is said we need to buy keys. how much it is?

  2. Do I have to pay for each device that uses this sideloaded app? Is there any other costs or related software/license requirements with it? this blog says there is per month subscription fee for devices.

  3. Is there any other requirement other than sideloading keys like OS version or domain? Should the devices have particular version of OS or anything (such Windows 8.1 premium is must)? this says it devices should be in domain?

  4. If submitted to windows store, is there a way to hide from public view and allow the app to downloaded for intended users who are using Windows 8.1? Hide this app in the store will not work as it has a limitation of not able to use with Windows 8.1.

  5. Technet says app can be sideloaded to all users as an image. But in that option also users have run the powershell and type the command to install the app. Is there a way to make enduser's life easier by making the installation simple as double click?

Thanks in Advance

Create ADO.NET adaptor for SQLite

How to create a ADO.NET adaptor for SQLite (i.e. generate my own DLLs from SQLite C source code, instead of using other existing DLLs or NuGet to install SQLite.) I want to do it as a learning experience but find no instruction on google.

I will use C#.NET in WPF VS2015 on x64. Do I compile the source in VC++ as a DLL and then reference to it in a new solution ? Will the DLL be x86 and x64 compatible or do I generate two separate DLLs?

I'm trying to compile a relatively big legacy c++ project in visual-studio-2013 using /clr flag. The project generates a dll.

I get the following run-time exception:

Type '<Module>' from assembly ... contains more methods than the current implementation allows

I must add that this happens in Debug configuration only (Release - works). Also, the project heavily uses templates and macros, which (I suppose) contribute to the large amount of generated methods...

There is little to no documentation regarding this problem. What I know from searching the net (don't know if it's accurate) is:

There is a limit of ~65K methods in a clr dll. All methods of all native classes go into some special <Module>, so it poses a global limit.

One suggestion was to split the project, but that's not very trivial, due to inter-class-dependencies. I suppose this is doable...

Any help would be appreciated.

compressing wix installer folder into a zip file .net 4.5

I have a post-build script for wix installer which runs a C# console application

public static void ZipInstallerFolder(string inputFolder, string exePath)
        {
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);
            string newVersion = fvi.FileVersion;
            string outputFolder = Path.Combine(inputFolder, "IQStudio_v" + newVersion + ".zip");
            Console.WriteLine("Debug outputFolder " + outputFolder);

            try
            {
                ZipFile.CreateFromDirectory(inputFolder, outputFolder, CompressionLevel.Optimal, true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex.message - " + ex.Message);
                Console.WriteLine("ex.InnerException - " + ex.InnerException);
                Console.WriteLine("ex.StackTrace - " + ex.StackTrace);

            }
        }

here is my exception

Debug outputFolder

D:\Tools\Tools\IPDev\Main\IQStudioSetup\bin\Release\IQStudio_v0.10.3.0.zip ex.message - The process cannot access the file 'D:\Tools\Tools\IPDev\Main\IQStudioSetup\bin\Release\IQStudio_v0.10.3.0.zip' because it is being used by another process. ex.InnerException - ex.StackTrace - at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.IO.Compression.ZipFileExtensions.DoCreateEntryFromFile(ZipArchive destination, String sourceFileName, String entryName, Nullable1 compressionLevel) at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding) at UpdateInstallerVersion.Program.ZipInstallerFolder(String inputFolder, String exePath) in d:\Tools\Tools\IPDev\Main\UpdateInstallerVersion\Program.cs:line 97

I don't understand why is the file being used by another process?

MessageBox closing without user action

I have VB.NET solution targeting .NET 4.0 Client Profile that includes add-ins for Excel and PowerPoint. There is a separate assembly for each, and a third assembly with code that is common to both. So, the common assembly is a dependency of the other two.

Sometimes, but not predictably or reliably, when code in the common assembly opens a MessageBox, it is dismissed automatically without user input. It seems as if the calling assembly (i.e. the Excel add-in) has seized back control of the UI from the common assembly (maybe something to do with threading?), or the calling assembly code just continues executing while the MessageBox is shown.

I have observed this behavior in various and completely separate parts of my solution, and cannot figure out what the problem is. Again, this does not happen all the time, and I cannot reproduce the condition reliably. I am testing this on Windows 8.1 in Office 2013.

Unfortunately, there really isn't any relevant code to post, except:

MessageBox.Show(...)

I am hoping someone can provide some insight into what may be happening here, and provide a fix.

EDIT

After incorporating Hans' suggestion below, my code is now:

MessageBox.Show(New WindowWrapper(handle), [Message], [Caption], MessageBoxButtons.OK, [Icon])

where handle [Integer] = Excel.Application.Hwnd and:

Public Class WindowWrapper
  Implements IWin32Window
  Private hwnd As IntPtr

  Public Sub New(handle As IntPtr)
    hwnd = handle
  End Sub
  Public Sub New(handle As Integer)
    hwnd = New IntPtr(handle)
  End Sub

  Public ReadOnly Property Handle As IntPtr Implements IWin32Window.Handle
    Get
      Return hwnd
    End Get
  End Property
End Class

Still having the same problem.

Image size too big in Firefox works well in Chrome- Asp.net

I am creating an e-commerce website using asp.net and have a page which dynamically displays all the products.

The only 1 issue I have- In chrome the size of the image is correct as written in the CSS code but not sure why image width and height changes when I run the programme in FF- It becomes around 300 px each.

   .productImage 
{
    width:150px;
    height:150px;
    vertical-align:central;
    padding:10px;
    border:10px;
    border-radius:50px;
    -moz-border-radius:50px;
    -webkit-border-radius:50px;
    display:block;
    Text-indent: -9999px;


}

Can someone please help me?

Sleeping/waiting for a long time

I am designing an industrial hardware control program in C#, which will run for periods of 72 hours at a time talking over serial ports.

In psuedo-code, what I am trying to do looks like this:-

while(true) {
    TalkToSerialPort1();
    WaitForXHours(3);
    TalkToSerialPort2();
    WaitForXHours(1);
    // etc
}

I have this code in a separate thread from my main console or GUI program and has to be run procedureally

It seems like Thread.Sleep() for long periods of time seems to be ruining my day! I am looking for a reliable way of sleeping for extended periods of time.

Any information would be helpful.

(c# mono) how to properly use x509certificate2 with chain (CAfile)

I trying to understand why when I create TcpListener server in c# I'm failed to retrive certificate chain from the client ssl connection.

I bought certificate from COMODO with folowing files:

  • Root CA Certificate - AddTrustExternalCARoot.crt
  • Intermediate CA Certificate - COMODORSAAddTrustCA.crt
  • Intermediate CA Certificate - COMODORSADomainValidationSecureServerCA.crt

Then I combined those files into one CAfile:

cat COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > cafile.cer

Next I create pfx certificate:

openssl pkcs12 -export -in new_api_coinpip_com.crt -inkey new_api.coinpip.com.key -chain -CAfile api.coinpip.com.bundle -out my-csharp-cert.pfx

And finally I writed simple test server application (SslServer.exe):

using System;
using System.Security.Cryptography.X509Certificates;
using System.Net.Sockets;
using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;

namespace SslServer
{
    public class Program
    {
        static int Port = 9097;
        static X509Certificate2 serverCertificate = null;
        // The certificate parameter specifies the name of the file  
        // containing the machine certificate. 
        public static void RunServer(string certificate, string password) 
        {
            serverCertificate = new X509Certificate2 (certificate, password);
            // Create a TCP/IP (IPv4) socket and listen for incoming connections11.
            TcpListener listener = new TcpListener(IPAddress.Any, Port);    
            listener.Start();
            while (true) 
            {
                Console.WriteLine("Waiting for a client to connect...");
                // Application blocks while waiting for an incoming connection. 
                // Type CNTL-C to terminate the server.
                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
        static void ProcessClient (TcpClient client)
        {
            // A client has connected. Create the  
            // SslStream using the client's network stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            // Authenticate the server but don't require the client to authenticate. 
            try 
            {
                sslStream.AuthenticateAsServer(serverCertificate, 
                    false, SslProtocols.Default, true);

                // Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                // Read a message from the client.   
                Console.WriteLine("Waiting for client message...");
                string messageData = ReadMessage(sslStream);
                Console.WriteLine("Received: {0}", messageData);

                // Write a message to the client. 
                byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
                Console.WriteLine("Sending hello message.");
                sslStream.Write(message);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine ("Authentication failed - closing the connection.");
                sslStream.Close();
                client.Close();
                return;
            }
            catch(Exception e) {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                // The client stream will be closed with the sslStream 
                // because we specified this behavior when creating 
                // the sslStream.
                sslStream.Close();
                client.Close();
            }
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the client. 
            // The client signals the end of the message using the 
            // "<EOF>" marker.
            byte [] buffer = new byte[2048*2];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                // Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8 
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF or an empty message. 
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes !=0); 

            return messageData.ToString();
        }


        public static int Main(string[] args)
        {

            RunServer (args [0], args[1]);
            return 0;
        } 
    }

}

And when I trying to launch server by

SslServer.exe /path/to/certificate/my-csharp-cert.pfx SomePassword

I'm unable to see certificate chain (which is include in my-csharp-cert.pfx)

openssl s_client -showcerts -connect api.coinpip.com:9097

CONNECTED(00000003)

depth=0 OU = Domain Control Validated, OU = PositiveSSL, CN = api.coinpip.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, OU = PositiveSSL, CN = api.coinpip.com
verify error:num=27:certificate not trusted
verify return:1
depth=0 OU = Domain Control Validated, OU = PositiveSSL, CN = api.coinpip.com
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=api.coinpip.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
-----BEGIN CERTIFICATE-----
MIIFUjCCBDqgAwIBAgIRAI5OrBia65sFYOEOPAE+YcYwDQYJKoZIhvcNAQELBQAw
gZAxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO
BgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMTYwNAYD
VQQDEy1DT01PRE8gUlNBIERvbWFpbiBWYWxpZGF0aW9uIFNlY3VyZSBTZXJ2ZXIg
Q0EwHhcNMTUwNTAzMDAwMDAwWhcNMTYwNTMxMjM1OTU5WjBTMSEwHwYDVQQLExhE
b21haW4gQ29udHJvbCBWYWxpZGF0ZWQxFDASBgNVBAsTC1Bvc2l0aXZlU1NMMRgw
FgYDVQQDEw9hcGkuY29pbnBpcC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQCtTznUdDXEmB2WMjWZNVL/4nfdqvWvRP8zQFx5rhsCFO+N4fsi+FY7
AAC1Mn4/jb0EDjZkxukyz8xbLmMcskDhgFTXlZlhb/5R5mscn2lwlBXwQpTuvjtX
yIwl8a1Ey6cZHVWcjf5vveCa1crwOd7653EsxY9gXf5UEKzST0qRhMMlF2Be120t
nKyqJSvNi6lNYcIrTg3zWLdHRpitZn8uIyVO0i7aq/cujz0O620K4rYR1QJZ7Cij
5hmdGoWIYMsAL0A0qODw5yEGiUqEEGdtHsYHJTopGoQCP1rOyEhlyhoILnyBUDDT
DgUMwYSFLv4JnfXbR52+LBKd5dDImT0LAgMBAAGjggHhMIIB3TAfBgNVHSMEGDAW
gBSQr2o6lFoL2JDqElZz30O0Oija5zAdBgNVHQ4EFgQUAHGRnlng9W4U9qVPYBdS
nfQAW8owDgYDVR0PAQH/BAQDAgWgMAwGA1UdEwEB/wQCMAAwHQYDVR0lBBYwFAYI
KwYBBQUHAwEGCCsGAQUFBwMCME8GA1UdIARIMEYwOgYLKwYBBAGyMQECAgcwKzAp
BggrBgEFBQcCARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLmNvbS9DUFMwCAYGZ4EM
AQIBMFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0NP
TU9ET1JTQURvbWFpblZhbGlkYXRpb25TZWN1cmVTZXJ2ZXJDQS5jcmwwgYUGCCsG
AQUFBwEBBHkwdzBPBggrBgEFBQcwAoZDaHR0cDovL2NydC5jb21vZG9jYS5jb20v
Q09NT0RPUlNBRG9tYWluVmFsaWRhdGlvblNlY3VyZVNlcnZlckNBLmNydDAkBggr
BgEFBQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMC8GA1UdEQQoMCaCD2Fw
aS5jb2lucGlwLmNvbYITd3d3LmFwaS5jb2lucGlwLmNvbTANBgkqhkiG9w0BAQsF
AAOCAQEAe3C8VWbVoXiKj406XOZ7FUwQkiLX9wzlF9jgvXDuKSj/U65d6v2uwTma
VjufWUN6yVFWS+M16qZwcH7e3z1tUeYZ6g6+lIv6h0/hNmiSt+ruqlqXX8qZYGEI
PK39C1udd8tcwhxq0ob/JOWUhU8QRjKiQ/WZEVL0Ps55qMap4rYgWviqiDLkhRVA
kneXMmKBXQrmxa+AvQ4S1pTDmOr/BMmnAkDSUkPvd4J4KnAL4m2rM2yTG3FsGzgk
06pWGqOOcALYe1qxz3pQCFsTpltDKIRXXSlsJCW06UHezRgA9umkt/Mst0E6g7Kb
yM6fV9XhEyrnPGWstjultuD6BQuO2w==
-----END CERTIFICATE-----
---
Server certificate
subject=/OU=Domain Control Validated/OU=PositiveSSL/CN=api.coinpip.com
issuer=/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
---
No client certificate CA names sent
---
SSL handshake has read 1496 bytes and written 621 bytes
---
New, TLSv1/SSLv3, Cipher is AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES256-SHA
    Session-ID: 
    Session-ID-ctx: 
    Master-Key: CE5BF190BCE388CC09ACD846357ECFFED77992C2059A489C8406EAE1CF7A8274B04FF6838DA8182539205331F0F680BE
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1435488120
    Timeout   : 300 (sec)
    Verify return code: 21 (unable to verify the first certificate)
---

Why it's not working? What I missed?

If use same chain cafile.cer for apache there no any problem:

openssl s_client -showcerts -connect api.coinpip.com:443

CONNECTED(00000003)

depth=0 C = SG, ST = Some-State, L = Singapore, O = Internet Widgits Pty Ltd, OU = eztopay.me, CN = eztopay.me, emailAddress = admin@eztopay.me verify error:num=18:self signed certificate verify return:1 depth=0 C = SG, ST = Some-State, L = Singapore, O = Internet Widgits Pty Ltd, OU = eztopay.me, CN = eztopay.me, emailAddress = admin@eztopay.me verify return:1 --- Certificate chain 0 s:/C=SG/ST=Some-State/L=Singapore/O=Internet Widgits Pty Ltd/OU=http://ift.tt/1GTOtaz
i:/C=SG/ST=Some-State/L=Singapore/O=Internet Widgits Pty Ltd/OU=http://ift.tt/1GTOtaz -----BEGIN CERTIFICATE----- MIIEHTCCAwWgAwIBAgIJAPwmQDQj40WhMA0GCSqGSIb3DQEBBQUAMIGkMQswCQYD VQQGEwJTRzETMBEGA1UECAwKU29tZS1TdGF0ZTESMBAGA1UEBwwJU2luZ2Fwb3Jl MSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEzARBgNVBAsMCmV6 dG9wYXkubWUxEzARBgNVBAMMCmV6dG9wYXkubWUxHzAdBgkqhkiG9w0BCQEWEGFk bWluQGV6dG9wYXkubWUwHhcNMTQwNzE1MDQyMjI2WhcNMTUwNzE1MDQyMjI2WjCB pDELMAkGA1UEBhMCU0cxEzARBgNVBAgMClNvbWUtU3RhdGUxEjAQBgNVBAcMCVNp bmdhcG9yZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRMwEQYD VQQLDAplenRvcGF5Lm1lMRMwEQYDVQQDDAplenRvcGF5Lm1lMR8wHQYJKoZIhvcN AQkBFhBhZG1pbkBlenRvcGF5Lm1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAuDk+s91Be9I4QuUnAAriSltbgD8VGkQ5D4F0M3KsGgTlTpUTo4LT49eQ Yg7TaialFK9HtCUZcPOo4wTDrFCsP+GJUURxCTkt6LUOnJu4R/VwScx2Rknh18+0 clq5d8UxkMRcEWJ1vdWdn71jjSSBNuVsDJAljKMh1pib26/LoCyskDTBuUE5VOjC Fc8HlHLy4VGAROCarogNgWIhJVeBOZA9f96IutKLinj8Kh6ANh6HXazShatyB7XG AMLbuFFegPcYp/GbKOd/c3k/KWq+PmN+CmIDHqanlv29YGyXVJSnOT4IjEPbNJs3 CE2qK9h/03+fZJfJfasgMWcHSndoBQIDAQABo1AwTjAdBgNVHQ4EFgQU9B3fsjib bsR7VtYr0l7URsdplmswHwYDVR0jBBgwFoAU9B3fsjibbsR7VtYr0l7URsdplmsw DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEABNOdBR+GX1YZDRenTOqN EybA9urdytLjl9jzxqh3jcPQWXNF1v8rg9jTWhIGxnsxXj6igqKHOV6L3MeGt0Vm tlJgdKhTnJPbYVsXVyo12m0DGfd7y2mrqlrAu4/JkMhAgJRdoOC5ShwZm7JQcU8f EvcgyozEmfZwOd3Oj8gZJu8QXF0i5iGfjC34g9tBLvQYu++fbSaRnLYOpHY7rtDZ 3eC+zN3zE2ENtC5leKVOUOM41NNPvHiEYbhXMSqF0TD9+GktW2dU3Np6HvOEif+F /xSCz3PgVtPB97kcGobWQiv1nome5QzkSz814jzKxEYc6qBOrA4GmmnRrOxYe5AA vg== -----END CERTIFICATE----- --- Server certificate subject=/C=SG/ST=Some-State/L=Singapore/O=Internet Widgits Pty Ltd/OU=http://ift.tt/1GTOtaz issuer=/C=SG/ST=Some-State/L=Singapore/O=Internet Widgits Pty Ltd/OU=http://ift.tt/1GTOtaz --- No client certificate CA names sent --- SSL handshake has read 1748 bytes and written 421 bytes --- New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384 Server public key is 2048 bit Secure Renegotiation IS supported Compression: NONE Expansion: NONE SSL-Session: Protocol : TLSv1.2 Cipher : ECDHE-RSA-AES256-GCM-SHA384 Session-ID: CE13742D4BA8B45D899819FF011B9033ACAFD0DCF65CC53E8F35ADDF60D3DDF6 Session-ID-ctx: Master-Key: 5656D423DED4A8D65EFF63080A514A2C3B9D27A8BBB1D39FFB3367484842D8B0300591C7E837B3894A7172AE3458AE21 Key-Arg : None PSK identity: None PSK identity hint: None SRP username: None TLS session ticket lifetime hint: 300 (seconds) TLS session ticket: 0000 - 49 42 9d c0 a1 c6 13 3d-1e 58 3e 08 8a 7e aa 60 IB.....=.X>..~.` 0010 - 66 1f 2f fc b0 3f 9b 0e-97 91 d8 de fc fd 56 33 f./..?........V3 0020 - 94 43 a0 8b 84 a7 b3 67-10 b1 d0 c6 62 af 5d 0f .C.....g....b.]. 0030 - dc 5f 78 e1 9b 68 ed a5-7a 48 98 11 d9 ae ba 71 .x..h..zH.....q 0040 - 2b 84 3a 82 97 ca 1b 44-52 67 09 31 27 4b 36 5b +.:....DRg.1'K6[ 0050 - 91 7b cd b6 78 05 cf e5-ab b4 4c 83 18 46 dc b0 .{..x.....L..F.. 0060 - 9d 09 41 57 ea 4c 05 a2-44 59 89 d9 42 98 97 89 ..AW.L..DY..B... 0070 - 93 9c cc ce db 8d 64 54-30 08 b7 3c 1e 2c b4 94 ......dT0..<.,.. 0080 - 71 90 d3 0e 7f d1 f7 9c-d2 4d 1f 97 65 4f 4a 9e q........M..eOJ. 0090 - 4a c3 f7 67 20 04 41 ca-b7 15 4f 5e 1a ba fd 3c J..g .A...O^...< 00a0 - 1d 34 1f 5f cf 37 93 79-10 1b d5 b0 ab 46 0c 32 .4..7.y.....F.2 00b0 - bd bf 2f 1c 17 b1 52 43-20 e0 2e 0e f9 89 18 29 ../...RC ......)

Start Time: 1435488467
Timeout   : 300 (sec)

Verify return code: 18 (self signed certificate)

Any suggestion how to fix this and make certificate chain works in c#?

Dead Letter Queue Configuration in Spring-Net-Amqp

I have the following configuration for SimpleMessageListenerContainer in my Spring .NET consumer application. I would like to send the rejected messages to a dead letter queue or exchange. How can I do that in spring-net-amqp ? It is very easy to do that, in the java version of the library.

Thank you.


-->

Consuming .Net Generated Web Service from ColdFusion

I'm trying to consume a .net generated WS from ColdFusion Page. Soap binding sytle of the said WSDL is document.

In the CF documentation, it is clearly mentioned that it is not possible consume such Web services.

To consume a web service that is implemented in a technology other than ColdFusion, the web service must have one of the following sets of options:

    rpc as the SOAP binding style and encoding as the encodingStyle

    document as the SOAP binding style and literal as the encodingStyle

Is there any work around available?

Reference: http://ift.tt/1eRLJBJ

C# how to Download a file with a cookie(login)

I am trying to login on this website. Currently I'm using this code:

private string Login(string username, string password)
{
    string formUrl = "http://ift.tt/1GIXYXM";
    string formParams = string.Format("username={0}&password={1}&affiliate-button=Sign%20In", username, password);
    HttpWebRequest req = WebRequest.Create(formUrl) as HttpWebRequest;
    req.ContentType = "application/x-www-form-urlencoded";
    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36";
    req.Method = "POST";
    req.Referer = formUrl;
    req.AllowAutoRedirect = true;
    req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    req.CookieContainer = new CookieContainer();
    byte[] bytes = Encoding.ASCII.GetBytes(formParams);
    req.ContentLength = bytes.Length;
    using (Stream reqStream = req.GetRequestStream())
    {
        reqStream.Write(bytes, 0, bytes.Length);
    }
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
#if DEBUG
    foreach (Cookie c in resp.Cookies)
        System.Diagnostics.Debug.WriteLine(c.Name + " = " + c.Value);
#endif
    return resp.Headers["set-cookie"];
}

I always get 1 set-cookie back. When I login to this website with web browser(Chrome) I get back 10 + local storage. I have tried to use CookieCollection as follows:resp.Cookies. But i still got back only one cookie.

The other problem is, that i cant download this file with the cookie I get. I only get back the login page. For downloading i use this function:

private void Download(string url, string fileName, string cookies)
    {
        try
        {
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Headers.Add(cookies);
            req.Method = "GET";
            req.Referer = "osu.ppy.sh";
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            using (Stream respStream = resp.GetResponseStream())
            {
                SaveToFile(respStream, fileName); //This reads the stream and writes to file
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

As I said before I used CookieCollection when I log in, I have also tried CookieContainer in this function like this:

req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookies)

What am i doing wrong?

.NET 4.5 Claims Identity Model

We have two ASP .NET web applications living on different servers. All authentication in our organization is done via Windows Authentication against Active Directory - so no username and password authentication in the web apps themselves.

We'd like to use claims based authorization and have these two web applications share information about what claims a given user has.

I'm trying to figure out how to go about this.

We have ADFS 2.0 and I know I can set up Federated Authentication using this...but where should my AD users' claims be stored and how are they hydrated and thus shared. Do the claims themselves end up in cookies after authentication?

Specifically, the scenario should be this:

  • User navigates to web app 1
  • Business decisions are made based on the ClaimsPrincipal's AuthorizationDecision ClaimsTypes
  • Web app 1 redirects to web app 2 (or they navigate there directly later)
  • Business decisions are made based on the same AuthorizationDecision ClaimsTypes' values
  • Why? Because web app 1 and web app 2 both pull some common data from a third party data source - and they both need to know if the user is authorized to view certain entity types in that third party data.

DefinedTypes property throws an error when an assembly is loaded from memory dynamically

I'm trying to load some of my project's assemblies dynamically.

When I load them via their file path like Assembly.LoadFile(path) I can get theirs defined types by calling GetTypes() method from loaded assembly.

var asm = Assembly.LoadFile(path);
var defienedTypes = asm.GetTypes(); //I've got all types without any error

But when I load them from memory like Assembly.Load(System.IO.File.ReadAllBytes(path)), I'm not able to retrieve defined types. So calling GetTypes() method causes an error:

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information

And LoaderExceptions property contains all defined types.

Crystal report not working after setup installed where .net is not installed

I have created a windows application using c# .net 2010. I created setup file of that project and installed in client system. Everything is working fine except crystal reports. I thing it is not install properly. please give me some solution.

Thanks in Advance.

Library to extract text from an image C#

I want to change text of any image with a user define Text in C# .NET The program should work like this: 1. Recocgnize text in any image 2. Put the text in string variable 3. Enter user define text 4. Again Insert the text back to the image

Can anyone suggest some solution. Any library that I can use to change text of a image

Accessing Network Path in Windows Service C#

I have developed a windows service using local system as Account. I have used network path of file

FileInfo fi = new FileInfo(@"\\epm-server\penDocuments_LabMeds\" + Convert.ToString(dr["mrn"]) + "\\SyncedXML\\" + Convert.ToString(dr["xmlfile"]));
if (!fi.Exists)
    boolFileNotFound = true;

A dynamic path of a file that is built from database.

It works fine when I run Windows Service in Debug Mode, but when I install it then fileNotExists returns TRUE always like the file doesnt exist but infact it does exist.

This is bugging me a lot now. Kindly help me why its not working. Its a server path. Its getting opened in my PC.

Thanks

samedi 27 juin 2015

nested unit of work and making unwanted object

I have 3 forms in my application : frmTrucks, frmEditTruck and frmEditContent. frmTrucks shows my Trucks in a grid. I add a truck, or choose one of the trucks from the grid to edit in frmEditTruck

    public void Edit()
    {
        using (NestedUnitOfWork nuow = session.BeginNestedUnitOfWork())
        {
            Truck currentTruck = nuow.GetNestedObject(
        xpcTruck[gvTruck.GetDataSourceRowIndex(gvTruck.FocusedRowHandle)])
              as Truck;
            using (frmEditTruck form = new frmEditTruck(currentTruck))
            {
                if (form.ShowDialog() == DialogResult.OK)
                    nuow.CommitChanges();
            }
        }
    }

in frmEditTruck there are some text boxes for truck properties and two buttons. btnSave and btnAddContent. btnSave saves the changes (now.CommitChanges();). btnAddContent's click code is :

    Truck truck;
    Session session;

    public frmEditTruck(Truck truck)
    {
        InitializeComponent();
        this.truck = truck;
        this.session = truck.Session;
    }


    private void btnAddContent_Click(object sender, EventArgs e)
    {
        TContent content = new TContent(session);
        using (frmEditTContent form = new frmEditTContent(content, truck))
        {
            if (form.ShowDialog() == DialogResult.OK)
                truck.TContents.Add(content);
        }
    }

it shows frmEditContent. I can Add content to my truck. the problem is when I press AddContent and then cancel it. After that when I press the save button on my frmEditTruck it would add an empty row to my Content Table. I want to fix this problem. how can I fix it? I'm not sure my problem is clear enough for you. Please let me know

public class Truck : XPObject
{
    .
    .
    .

    [Association("Truck-TContents")]
    public XPCollection<TContent> TContents { get { return GetCollection<TContent>("TContents"); } }

}

public class TContent : XPObject
{
    .
    .
    .
    private Truck truck;
    [Association("Truck-TContents")]
    public Truck Truck
    {
        get
        {
            return truck;
        }
        set
        {
            SetPropertyValue("Truck", ref truck, value);
        }
    }
}

Mock CollectionValidator using Moq and FluentValidation - Get NullReferenceException

I am trying to mock a child collection validator, so i can write unit tests just for the validator itself.

So i have a validator that looks like this

public class ReportValidator<T> : AbstractValidator<T>
    where T : Report
{
    public ReportValidator(IValidator<Criteria> criteriaValidator) {
        RuleFor(e => e.Name).NotEmpty();

        RuleFor(e => e.MyList).SetCollectionValidator(criteriaValidator);
    }
}

I have wrote a class in my test project to mock a validator, which looks like so

public class MockValidator<T> : Mock<IValidator<T>>
    where T : class
{
    public MockValidator() 
    {
        this.Setup(x => x.Validate(It.IsAny<ValidationContext>()))
            .Returns(new ValidationResult());

        this.Setup(x => x.ValidateAsync(It.IsAny<ValidationContext>()))
            .ReturnsAsync(new ValidationResult());
    }
}

In my unit test i create my ReportValidator, by passing in a mock like so

public class TestReportValidator
{
    private ReportValidator<Report> _validator;

    [TestInitialize]
    public void TestInit()
    {
        var mockListValidator = new MockValidator<ChildObj>();

        _validator = new ReportValidator<Report>(mockListValidator.Object);
    }

}

Now i have created my unit test to make sure that a report is valid like so

[TestMethod]
public void should_return_true_when_entity_is_valid()
{
    var results = _validator.Validate(new Report
    {
        Name = "Test",
        Module =
        {
            Id = 1,
            Name = "Company"
        },
        MyList = new Collection<ChildObj>()
    });

    Assert.AreEqual(true, results.IsValid, results.IsValid ? string.Empty : results.Errors[0].ErrorMessage);
}

But i keep getting this exception

System.NullReferenceException: Object reference not set to an instance of an object.

Not sure what i am doing wrong, anyone shed some light on this?

I have a List<List<int>> set of data, with string representation like this (to give the idea!):

 {{1,3},{-1,-3},{2,5},{-2,-5},{-3,4},{-5,4},{3,5,-4},{6,-8},{7,-8},{-6,-7,8},{7,9},{-7,-9},{3,8,-10},{-3,-8,-10},{-3,8,10},{3,-8,10},{4,9,-11},{-4,-9,-11},{-4,9,11},{4,-9,11},{10,11},{-1,6},{1,-6},{-2,7},{2,-7}}

I want to check if ,in all present numbers, exist a number or set of numbers which only are in positive form. I mean if in the whole data, there is 3 and -3 I should return false, otherwise I have to add 3 as a number which only is present as positive 3, in to another list. (Same thing for only negative number)

Here is how I am trying to do it:

First, generate a unique set of numbers and remove negatives:

private void GenerateCurrentExistingVariables()
{
    _uid = new List<int>();
    var all = _cnf.Data.SelectMany(list => list).ToList();
    _uid = all.Distinct().ToList(); //make list unique
    _uid.Sort(); //sort numbers
    _uid.Reverse(); //reverse so highest numbers would evalaute first!
    _uid = _uid.Where(i => i >= 0).ToList(); //remove negative numbers
}

Then I do something like this:

in a method, I call the code below:

    for (var i = 0; i < _uid.Count; i++)
    {
        if (ExistOnlyInNegatedForm(_uid[i]))
        {
            onlyNegatedList.Add(_uid[i]);
        }

        if (ExistOnlyInPositiveForm(_uid[i]))
        {

            onlyPositiveList.Add(_uid[i]);
        }
    }

Which in turns calls the methods below:

private bool ExistOnlyInPositiveForm(int id)
{
    for (var i = 0; i < _cnf.Data.Count; i++)
    {
        for (var j = 0; j < _cnf.Data[i].Count; j++)
        {
            if (_cnf.Data[i][j] == id)
            {
                return false;
            }
        }
    }

    return true;
}

private bool ExistOnlyInNegatedForm(int id)
{
    var toCheck = -id;
    for (var i = 0; i < _cnf.Data.Count; i++)
    {
        for (var j = 0; j < _cnf.Data[i].Count; j++)
        {
            if (_cnf.Data[i][j] == -toCheck)
            {
                return false;
            }
        }
    }

    return true;
}

This is too much code for this simple task and I feel that this is getting slower and slower when data grows larger...please let me know how can I improve this. Also I would like this to be done using LINQ at least for the sake of less lines of code!

Sending Exchange WS emails - Not enough free threads in the ThreadPool to complete the operation

I need to overcome this error:

There were not enough free threads in the ThreadPool to complete the operation.

I get it 80% of the time when queuing a bunch of Correspondence objects (with SSRS Reports) and sending them via Exchange WS. The reports are generated and emailed using a ThreadPool.

This is what the code looks like, it was built on .Net 2.0 hence no usage of TPL or Async/Await.

public static void QueueCorrespondence(ref Correspondence corr)
{
    Queue corrQ = CorrespondenceQueue(corr.Medium);
    // Create an AsyncOperation, using the CorrespondenceID as a unique id
    AsyncOperation asOp = AsyncOperationManager.CreateOperation(corr.CorrespondenceID);
    SendCorrespondencesInCurrentQueueArgs sendCorrespondencesInCurrentQueueArgs = new SendCorrespondencesInCurrentQueueArgs();
    sendCorrespondencesInCurrentQueueArgs.AsOpArg = asOp;
    sendCorrespondencesInCurrentQueueArgs.CorrQueueArg = corrQ;
    lock (_correspondenceQs) {
        if (corrQ.Count == 0) {
            corrQ.Enqueue(corr);
            ThreadPool.QueueUserWorkItem(new WaitCallback(SendCorrespondencesInCurrentQueue), sendCorrespondencesInCurrentQueueArgs);
        } else {
            corrQ.Enqueue(corr);
        }
    }
}

/// <summary>Do the processing necessary on the new thread</summary>
/// <param name="scicqa"></param>
/// <remarks>This runs on a background thread in the threadpool</remarks>
private static void SendCorrespondencesInCurrentQueue(SendCorrespondencesInCurrentQueueArgs scicqa)
{
    Correspondence corr = null;
    bool allReportsSuccessfullySent = false;
    //Dequeues the correspondence from the queue and returns it (ByRef)
    while (DequeueCorrespondence(ref corr, ref scicqa.CorrQueueArg)) {
        try {
            //This calls Exchange Web Services to send emails
            Send(corr);
            allReportsSuccessfullySent = true;
        } catch (Exception ex) {
            Incident.NewIncident("Unexpected Error", Incident.IncidentLevelEnum.ErrorLevel, ex, true, string.Format("Sending correspondence {0} via Medium {1}", corr.CorrespondenceID.ToString, corr.Medium));
        } finally {
            MailRoomArgs mra = new MailRoomArgs();
            mra.CorrArg = corr;
            mra.TransferSuccessArg = allReportsSuccessfullySent;
            //Success or not, call the RaiseCorrespondenceSentEvent subroutine via this delegate.
            scicqa.AsOpArg.Post(onCorrespondenceSentDelegate, mra);
        }
    }
}

/// <summary>Pull the next correspondence item off the queue, returning true if success</summary>
private static bool DequeueCorrespondence(ref Correspondence corr, ref Queue corrQ)
{
    lock (_correspondenceQs) {
        if (corrQ.Count > 0) {
            corr = corrQ.Dequeue;
            return true;
        } else {
            corr = null;
            return false;
        }
    }
}

Here is the stack trace. See the above functions call into Exchange WS and BeginGetRequestStream throws an exception due to lack of threads in the ThreadPool.

   at System.Net.HttpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
   at Microsoft.Exchange.WebServices.Data.EwsHttpWebRequest.Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetWebRequestStream(IEwsHttpWebRequest request)
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.EmitRequest(IEwsHttpWebRequest request)
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.BuildEwsHttpWebRequest()
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request)
   at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.InternalExecute()
   at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
   at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable`1 items, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode, ServiceErrorHandling errorHandling)
   at Microsoft.Exchange.WebServices.Data.ExchangeService.CreateItem(Item item, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode)
   at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode)
   at Microsoft.Exchange.WebServices.Data.Item.Save(WellKnownFolderName parentFolderName)
   at XYZ.WM.CIMS.BusinessObjects.ExchangeServer.SendCorrespondence(Correspondence& corr)
   at XYZ.WM.CIMS.BusinessObjects.Email.SendCorrespondence(Correspondence& corr)
   at XYZ.WM.CIMS.BusinessObjects.CorrespondenceMediumBase.Send(Correspondence& corr)
   at XYZ.WM.CIMS.BusinessObjects.CorrespondenceMediumBase.SendCorrespondencesInCurrentQueue(SendCorrespondencesInCurrentQueueArgs scicqa)

Sending emails on the main thread works fine. After a couple of days on this I'm pretty certain the problem could be avoided if I didn't call Exchange WS on a worker thread as shown below.

enter image description here

It doesn't matter if I Save, Send or SendAndSave emails I still get the error:

private  exchangeService = new ExchangeService(3); //Exchange2010 SP2
public void SendCorrespondence(ref Correspondence corr)
{
    exchangeService.Url = new Uri("http://ift.tt/1dpOkBc");
    exchangeService.UseDefaultCredentials = true;
    string[] emailAddresses = corr.SubscriptionObject.SubscriptionRecipients.EmailAddresses;

    EmailMessage message = default(EmailMessage);
    message = new EmailMessage(exchangeService);

    if (emailAddresses.Count > 1) {
        message.BccRecipients.Add(string.Join(RECIPIENTS_SEPARATOR, emailAddresses));
    } 
    else if (emailAddresses.Count == 1) {
        message.ToRecipients.Add(emailAddresses(0));
    }

    message.Subject = corr.SubscriptionObject.EmailSubject;
    EmailAddress fromSender = new EmailAddress();
    fromSender.Address = _instOpsSharedOutlookMailAccount;
    fromSender.Name = _instOpsSharedMailAccountName;
    fromSender.MailboxType = MailboxType.Mailbox;
    message.From = fromSender;

    foreach (ReportBase generatedReport in corr.GeneratedReports) {
        message.Attachments.AddFileAttachment(generatedReport.GeneratedDocument.FullName);
    }

    message.Body = new BodyType();
    message.Body.BodyType = BodyType.HTML;
    message.Body.Text = corr.SubscriptionObject.EmailTemplate;
    if (corr.SubscriptionObject.SendToDraft) {
        //Saving causes the problem !!!!!!!!!!!
    } else if (Convert.ToBoolean(Code.GetCodeTextValue(PARENT_CODE, "ExchangeSaveMsgOnSend", RETURN_DEFAULT_STRING_IF_NO_DATA, "True"))) {
        //Sending and Saving causes the problem !!!!!!!!!!!
        message.SendAndSaveCopy();      
    } else {
        //Sending causes the problem !!!!!!!!!!!
        message.Send(); 
    }
}

In fact using any Exchange methods, eg: ExchangeService.ResolveName(logonID) produces the error when called from a thread in the pool.

Does anyone know how I can send the emails without exhausting the ThreadPool? I don't want to re-architect this code too much, but would be happy to implement a simple way to avoid sending the email on a thread if anyone knows how.

The problem does not occur with Lotus Notes (yeah I know... lol!). I was using Exchange WS to get around the Outlook nag when an external program uses it to send emails. I would prefer not to use the Outlook Client but if there is no good solution I guess I will have to. Using Smtp client is not on the cards (as saving drafts in group folders is a major feature). I have also tried reducing the maximum number of threads in the ThreadPool but as I suspected that doesn't make a difference.

Any help would be much appreciated!!

What speed should i set the timer interval to be "normal speed" when playing images ?

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 System.Windows.Forms;
using System.IO;

namespace Player_Manager
{
    public partial class ScreenShotsPlayer : Form
    {
        FileInfo[] images;
        DirectoryInfo di1;
        int current = 0;

        public ScreenShotsPlayer()
        {
            InitializeComponent();

            di1 = new DirectoryInfo(@"e:\screenshots");
            images = di1.GetFiles("*.bmp");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if(pictureBox1.Image!=null)
        {
            var img = pictureBox1.Image;  
            pictureBox1.Image = null;     
            pictureBox1.Image.Dispose(); 
        }

        current = (current >= images.Length - 1) ? 0 : ++current;
        pictureBox1.Image = new Bitmap(images[current].FullName);
        pictureBox1.Refresh();
        }
    }
}

I have a timer in the designer. When it was set to 100ms it was too fast. When it set to 1000ms as it is now it's too slow.

I have 1200 images that i play in the pictureBox. And i wonder what speed should be a normal speed ?

differences between mongo.linq vs c# linq

Are there any differences between MongoDB.Linq vs C# Linq without Join mechanism? In my application, MongoDB is used as storage unit and Client Side Application has been coded via C# Linq Driver.

So, I want to store MongoDB query results to another collection and I want to let Client Side Application for querying Linq.

If there are big differences between C# and MongoDB Linq drivers, it will be big failure for both server and client side applications.