vendredi 8 mai 2015

Control that web page could be loaded only from an specific PC

I'm looking for just some orientation about how to control that an ASP.NET web site could be only loaded from an specific PC.

It seems obvious that the login web page should get the IP address or PC name from the client and check with a database query if that IP address plus the userid account match its database record.

However, catching the IP address with

Request.ServerVariables("REMOTE_ADDR") 

could get a IP address distorted by a firewall, NAT or router configuration. So that option is discarded.

Other option that I've heard is about creating a dll file with a name like "license.dll", and store inside that dll file some credential or IP address or serial number. That data plus the userid account have to be stored in database . When user loads the web page, it should read first that dll file and get the credential inside it, make a query to database and match userid account and dll credential. If matching is correct, then web page is loaded.

Is it possible to store some credential in a dll file and make the web page able to read that dll?

HttpListener with SSL certificate hanging on GetContext()

I've created a windows service which uses a HttpListener to respond to some third-party requests using .NET Framework 4.0. The listener is bound to a https prefix via the following:

listener.Prefixes.Add("https://+:" + Properties.Settings.Default.ListeningPort.ToString() + "/");

The service also self registers the https certificate in the computer store via:

X509Certificate2 certificate = new X509Certificate2(Properties.Settings.Default.HttpsCertPath, "", X509KeyStorageFlags.MachineKeySet);
X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();

Further more, the service also registers the certificate - ip:port binding in Http API using the following:

ProcessStartInfo psi = new ProcessStartInfo();            
psi.FileName = "netsh";
psi.Arguments = "http add sslcert ipport=0.0.0.0:" + Properties.Settings.Default.ListeningPort.ToString() + " certhash=" + certificate.Thumbprint + " appid=" + appId;
Process proc = Process.Start(psi);                
proc.WaitForExit();
psi.Arguments = "http add sslcert ipport=[::]:" + Properties.Settings.Default.ListeningPort.ToString() + " certhash=" + certificate.Thumbprint + " appid=" + appId;
Process proc = Process.Start(psi);
proc.WaitForExit();

Everything works well, as expected... EXCEPT... (and here comes the EVIL part): After running for some time, an hour or so, listener.GetContext() no longer returns and the clients get dropped with a "connection reset" like error.

How to extract latest reply text from email, and cut out previous messages?

I am using OpenPop.dll to read emails in my application. I want to read only the reply of the email not original email which it was replied to. But email is read with previous emails in quotes. I want to remove those previous mail contents.

I tried using RegEx for this but that is not very robust way to read replies because different email clients have different reply format.

Is there any way by which I can read only the reply text from mail thread in OpenPop.dll or some other open source library.

Below is how the reply email text looks like when read from OpenPop.dll.

My phone number is 123456789.

On Fri, May 8, 2015 at 2:57 PM,  wrote:

>  Hi,
>
> This mail is regarding your *Phone*. Please reply to this email with your
> *Phone*.
>
> Thanks
>

This format is such that because it was replied from Gmail. Outlook has different format and so does yahoo.

I want to read only

My phone number is 123456789.

Is there any way I could achieve this? Any solution is welcome.

"WriteLine" does not work

I have a problem

I use this code to save to txt file, how to do not to overwrite the file, but would write line by line the next time a function call??

Command WriteLine does not work. Write overwrite the file.

private async Task WriteToFile()
{
    string ResultString = string.Join("\n", locationData.ToArray());

    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(ResultString);

    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var dataFolder = await local.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
    var file = await dataFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.OpenIfExists);

    using (var s = await file.OpenStreamForWriteAsync())
    {
        s.Write(fileBytes, 0, fileBytes.Length);
    }
}

I used Windows Phone 8.1 for my app.

Digitally signing a strong named .NET assembly

I have a .NET assembly which I've strongly named, to put it in the GAC. However, the same assembly is also digitally signed using a .pfx file later on, for digital signature.
I've noticed that this assembly, which has been so dual signed, fails the strong name validation, and does not install in the target machine's GAC.

Could it be possible that the digital signing procedure removes the SN-key generated strong naming procedure?

The digital signature is essential and if the 2 are not compatible, then can the file be signed by the .pfx file instead, as easily as the SN-naming process?

Also, the assembly is in C++/CLI, not in C#.

Merging custom configuration files at runtime in .NET

My question is about working with standard .NET configuration objects and custom configuration elements as well, (which one can define by extending the System.Configuration.ConfigurationSection class). We usually obtain these from the System.Configuration.ConfigurationManager class's methods, GetSection(...) being an example.

The loaded configuration object appears to be a merged configuration object containing the setup present in the application config file (the the app.config or web.config file which a developer may have created) and what is defined in the machine.config file (the latter coming with the .NET Framework installation).

So, we can assume that the configuration is loaded in hierarchical manner with the machine.config first, and any user-defined configuration overlaying that default setup, and could be looked at like this:

  • machine.config
    • app.config (overrides / merges with respective elements found in machine.config )

My goal is to create multiple layers of configuration, so that there might be other config files between (and if possible, after) the machine.config and the app.config file:

  • machine.config
    • custom.config (a custom config interfering between the machine.config and the app.config file)
      • app.config - now app.config is merged with both machine.config and custom.config

Normally, I would write my own configuration manager class and will try to get as far as I could to get the desired result, but assuming the .NET framework has this working for machine.config and app.config, I thought I might benefit from the built-in functionality of the framework. In addition, I do not know how to manually trigger such merging, if I am indeed supposed to resort to a config manager implementation of my own.

So, is it possible to leverage the built-in mechanisms of configuration section/element merging with custom configuration files? I am especially interested in developing and supporting this for custom configuration sections. The System.Configuration namespace contains base objects to build configuration section and elements, and those allow some settings related to the merging (like setting the appropriate ConfigurationElementCollectionType for example). Are these related to only merging with machine.config (or multiple layers of web.config files in a web application), or is it possible to manually trigger the merging of pre-loaded config files?


Note: I would appreciate better a solution that would work on .NET 3.0+. Please add a note if your answer targets a higher version of the framework.

What is the DNVM?

Im playing with the new VsCode editor, and created an ASPNET 5 template project. To restore the packages, I found in the tutorials that I need to run the dnu restore command, which gets all the server side references that I need.

After that, to build it I must run the dnx: web or kestrel command, and everything goes as expected.

But, what are those tools? In the git repository of the DNVM we dont have much information about it.

Does the dnu restore uses the nuget?

Someone have some complete documentation about all that in the new .NET?

I would like to know too if its possible to use the Roslyn compiler within the VSCode on Windows 8.1.

Text vanishing in Winforms Textbox

I'm running into a strange issue with a WinForms textbox. When I set the Text property to a long string, the text seems to vanish. My understanding is that a textbox in Winforms has a default MaxLength of 32767, which can be set to any value less than or equal to int.MaxValue. The steps to reproduce the issue are as follows:

  1. Fire up Visual Studio 2013
  2. Create a new Windows Form Application. Choose to target the .NET 3.5 framework.
  3. Drag a textbox control onto the form.
  4. In the form load event, type in the following code:

    private void Form1_Load(object sender, EventArgs e)
    {
        // Setting the MaxLength property should be unnecessary since the
        // default is 32767, but I'm implicitly setting it anyway.
        textBox1.MaxLength = int.MaxValue;
        string s = "";
    
        // Weird things happen when the value in the next line
        // is set to anything >= 4680
        for (int i = 0; i < 15000; i++)
        {
            s = s + "A";
        }
    
        textBox1.Text = s;
    }
    
    

Run this application and you'll that the textbox "appears" empty. I say "appears" because if you put your cursor in the textbox, you can see that it behaves as though something is in the textbox, but nothing is there visually.

Whatever is going on, 4680 seems to be the "magic number". If you change the number in the for loop to 4680, you still get no text in the textbox (although clicking in the textbox will make the text show up). If you change it to 4679 or anything smaller, then it works just fine.

Does anyone have any ideas or workarounds for this odd behavior?

Dashing.net Jobs not loading

dashing.net\Controllers\EventsController.Get() not firing after publishing to IIS web site(inetpub\wwwroot...) locally. This event is needed to load the jobs. Not sure why. It works fine in VS 2012 IDE.

why in the collection interface the index is of type int? (signed) [duplicate]

This question already has an answer here:

Why the index type for the collection allow to accept negative index if they are not implemented?

silly ex:

List students = new List();
students[-1]; // will throw an OutOfRangeException

in other languages the -1 Index mean the last element. in C# is an out of range exception.

My question is:

Why in the collection interface is not used the Uint instead of int?

Any particular reason for this design policy?

Wrapping My Head Around await async and NHibernate

Given this code:

private ISession _session;

public async Task<T> GetAsync<T>(int id) where T : ISomeEntity
{
    //how to call and return _session.Get<T>(id) asynchronous
}

Is it possible to call NHibernate ISession.Get<T>() asynchronously? Advisable? Not worth it?

Unlimited number of bullets [GameDev]

I try to make shooter game on C# with SFML.NET, but I can`t imagine how to make an ability to shoot more than 1 bullet, because now I have just one null-object of bullet-class, and when player presses Space key this object gets link to the new bullet.

So, I have the Bullet-class, null-object public static Bullet bullet = null; and condition if (Keyboard.IsKeyPressed(Keyboard.Key.Space)) {if(bullet == null) bullet = new Bullet(t, p.rect.Left, p.rect.Top, p.reverse);}

When bullet reaches the wall or enemy bullet object gets equated to null. The problem is to make ability to shoot more bullets before this bullet reaches the wall or enemy (and disappear). I think this is not a good solution to make null-objects for every possible pullet, because then we have limited amount of possible bullets.

The connection was not closed [duplicate]

This question already has an answer here:

This is doing my head in. I have tried try and catch with finally and other things but this error keeps coming back. Please some one help. My c# code:

 void show()
    {
       string str = "SELECT PID, Pname, Gender, ContactNum, Category, Department, Ward, AdmitDate, DischargeDate, NumOfDays, CostOfTest, NumOfDocsVisited, DocFee, BedCost, TotalCost, GrandTotal FROM Patient";
        cmd = new SqlCommand(str, con);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataBind();
                con.Close();
    }

error is: The connection was not closed. The connection's current state is open. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The connection was not closed. The connection's current state is open.

Source Error:

Line 50:            string str = "SELECT PID, Pname, Gender, ContactNum, Category, Department, Ward, AdmitDate, DischargeDate, NumOfDays, CostOfTest, NumOfDocsVisited, DocFee, BedCost, TotalCost, GrandTotal FROM Patient";
Line 51:             cmd = new SqlCommand(str, con);
Line 52:                 con.Open();
Line 53:                 SqlDataAdapter adp = new SqlDataAdapter(cmd);
Line 54:                 DataTable dt = new DataTable();

Stack Trace:

[InvalidOperationException: The connection was not closed. The connection's current state is open.]

System.Data.ProviderBase.DbConnectionInternal.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +14 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) +94 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110 System.Data.SqlClient.SqlConnection.Open() +96 SMC.Billing.show() in e:\VS2013 projects\SMC\SMC\Billing.aspx.cs:52 SMC.Billing.Button3_Click(Object sender, EventArgs e) in e:\VS2013 projects\SMC\SMC\Billing.aspx.cs:97 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628722 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Run action and defined speed

I am trying to create a performance test in .NET and one of the steps is to "call" server at defined speed like: persistent ~400 calls per second.

The problem is that running server call has different length from: 10ms to 100ms. My first try was simple for loop with Thread.Sleep but this gives me results form 250-600 calls per second, depending on moment and server responses :(

Adapting grid with expanders to available height

I have a 'pile' of expanders on top of each other, which can be opened/closed independently.

All but one have a fixed height (when expanded). The other has a MinHeight, but I would like it to stretch to fill the remaining available height. If the combined heights of the expanders is greater than the available height, then scrollbars appear.

I've got that far using a Grid, with one expander per grid, and the row Height set to * for the stretching expander, and Auto for the others.

This works fine except in one case: if the stretchy expander is collapsed, and the combined height of the other expanders is less than the available height, then the stretching expander fills the remaining space anyway, just with it's content collapsed so I get a big blob of background colour.

I've also tried a StackPanel, or nested Grids, but haven't managed to resolve that problem without creating others.

Any ideas?

(Paste this into a Window)

<ScrollViewer>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*" MinHeight="23"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Expander IsExpanded="False" Grid.Row="0" Header="Fixed">
            <Border Background="Red" Height="200" />
        </Expander>
        <Expander IsExpanded="False" Grid.Row="1" Header="Stretchy">
            <Border Background="Blue" />
        </Expander>
        <Expander IsExpanded="False" Grid.Row="2" Header="Fixed">
            <Border Background="Green" Height="300" />
        </Expander>
    </Grid>
</ScrollViewer>

Incorrect syntaxt error when using 'IN @Ids'

I'm using Dapper, and trying to get a collection of Players using the following query:

public ICollection<Player> GetPlayersWithPointsInMatch(int id)
{
    const string sql =
                    @"SELECT
                        p.Id, 
                        p.FirstName, 
                        p.LastName, 
                        pmr.Goals, 
                        pmr.Assists 
                    FROM Players p 
                    LEFT JOIN PlayerMatchStats pmr ON p.Id = pmr.PlayerId 
                    WHERE pmr.MatchId IN @Ids
                    AND (pmr.Goals > 0 OR pmr.Assists > 0)";
    return Get<Player>(sql, new[]{id});
}

The Get method looks like this:

public ICollection<T> Get<T>(string sql, ICollection<int> ids)
{
    using (var connection = new SqlConnection(ConnectionString()))
    {
        return connection.Query<T>(sql, new { ids }).ToICollection();
    }
}

And, ToICollection looks like this:

public static ICollection<T> ToICollection<T>(this IEnumerable<T> iEnumerable)
        {
            var icollection = iEnumerable as ICollection<T>;
            return icollection ?? iEnumerable.ToArray();
        }

This is the error I'm getting on connection.Query:

Additional information: Incorrect syntax near '@Ids'.

If I run this query in SQL Management Studio, it works:

SELECT
    p.Id, 
    p.FirstName, 
    p.LastName, 
    pmr.Goals, 
    pmr.Assists 
FROM Players p 
LEFT JOIN PlayerMatchStats pmr ON p.Id = pmr.PlayerId 
WHERE pmr.MatchId IN (13)
AND (pmr.Goals > 0 OR pmr.Assists > 0)

I can't really figure out where my error is, as per my understanding the query generated by Dapper should be the same as the one I write myself in SQLMS?

Take a screenshot of a WPF window with the predefined image size without losing quality

When I take a screenshot of a current WPF window, the image resolution is that of my monitor (if the app is maximized), which is ok. However, if I was to print that image to a much bigger format, the image would look blurry. I found the way to capture the current window, and save it as a png file, but it's not doing the trick. The image is saved with the resolution I set, but the actual wpf window takes only a small portion of the saved image. Example is taken from:

http://ift.tt/1wybIDL

        var screen = System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

        var rtb = new RenderTargetBitmap(4000, 4000, 96, 96, PixelFormats.Pbgra32);

        rtb.Render(screen);

        var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
        enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));

        using (var stm = System.IO.File.Create("ScreenShot.png"))
        {
            enc.Save(stm);
            using (Image img = Image.FromStream(stm))
            {
                Rectangle dest = new Rectangle(0, 0, 6000, 4000);

                using (Graphics imgG = Graphics.FromImage(img))
                {
                    imgG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    imgG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    imgG.DrawImage(img, dest);
                }

                img.Save("NewScreenShot.png");
            }
        }

So basically, I'd like to capture the screenshot with the resolution of 4000 x 4000, if that's possible, without losing quality. The above code produces an image of 4000 x 4000, however the screenshot only takes a small portion of it, its original resolution.

Object instantiation using Reflection works in VB.NET but not C#

I'm trying to instantiate an object from a dll without referencing it. I can do it using Reflection in VB.NET but can't figure out how to do it in C#.

In VB.NET:

Public Class Form1

Dim bytes() As Byte = System.IO.File.ReadAllBytes("\\path\directory\file.dll")
Dim assmb As System.Reflection.Assembly = System.Reflection.Assembly.Load(bytes)
Dim myDllClass As Object = assmb.CreateInstance("myNamespace.myClass")

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim conStr As String = myDllClass.publicConString
    Dim dt As DataTable = myDllClass.MethodReturnsDatatable("select * from Part", conStr)
    DataGridView1.DataSource = dt

End Sub

In C#:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    static byte[] bytes = System.IO.File.ReadAllBytes(@"\\path\directory\file.dll");
    static System.Reflection.Assembly assmb = System.Reflection.Assembly.Load(bytes);
    object myDllClass = assmb.CreateInstance("myNamespace.myClass");

    private void Form1_Load(object sender, EventArgs e)
    {
        string conStr = myDllClass.publicConString;
        DataTable dt = myDllClass.MethodReturnsDatatable("select * from Part", conStr);
        dataGridView1.DataSource = dt;
    }                
}

I get these two errors:

Error 1 'object' does not contain a definition for 'publicConString' and no extension method 'publicConString' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) C:\Users\Username\Desktop\C#\FormTest\FormTest\Form1.cs 29 34 FormTest

Error 2 'object' does not contain a definition for 'MethodReturnsDatatable' and no extension method 'MethodReturnsDatatable' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) C:\Users\Username\Desktop\C#\FormTest\FormTest\Form1.cs 30 33 FormTest

Any insight?

Thanks in advance.

How to create a C# Encrypt-Decrypt Program using Visual Studio 2013 Express and Windows Forms?

I've been wanting to create a encrypt decrypt program for a while now and basically I would like to hook up 3 text boxes together with one being text to encrypt. the encrypted code, and the hash used to encrypt the text. so if the program is restarted you can input the hash and the encrypted text to decrypt. Here's what I've got far:

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.Security.Cryptography;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("This Program was created by Ashar Ahmed. You may not redistibute this work without explicit premission from its creator. \r\n\r(C) 2015 All Rights Reserved to Ashar Ahmed Industries LLC.");
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox3_TextChanged(object sender, EventArgs e)
        {

        }

    }

Please help me

Checking that two NTAccount objects refer to the same account

I am trying to check that a service has access rights to a particular local directory:

public static bool HasDirectoryPermissions(String path, FileSystemRights rights, String serviceName)
{
    try
    {
        var directoryAccessControl = Directory.GetAccessControl(path);
        ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_Service where Name='" + serviceName + "'");
        var queryResults = (from ManagementObject x in query.Get() select x);
        if (queryResults.Count() > 0)
        {
            var serviceUser = (string)queryResults.FirstOrDefault().Properties["StartName"].Value;
            var serviceUserAccount = new NTAccount(serviceUser);
            var rules = directoryAccessControl.GetAccessRules(true, true, typeof(NTAccount));
            foreach (var rule in rules)
            {
                if (rule.GetType() == typeof(FileSystemAccessRule))
                {
                    var accessRule = (FileSystemAccessRule)rule;
                    if (accessRule.IdentityReference == serviceUserAccount && accessRule.FileSystemRights == rights && accessRule.AccessControlType == AccessControlType.Allow)
                    {
                        Console.WriteLine("The {0} service has permissions to {1}.", serviceName, path);
                        return true;
                    }
                }
            }
            Console.WriteLine("The {0} service does not have directory permissions for {1}.", serviceName, path);
            return false;
        }
        else
        {
            Console.WriteLine("Could not get directory permissions for {0} because the {1} service is not installed.", path, serviceName);
            return false;
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine("Directory permissions could not be obtained for the {0} service against {1}. {2}", serviceName, path, exception.ToString());
        return false;
    }
}

However, the problem is that accessRule.IdentityReference == serviceUserAccount is never true, because, on one hand, I have an IdentityReference of type NTAccount who's name is NT AUTHORITY\NETWORK SERVICE, and my calculated serviceUserAccount object is NT AUTHORITY\NetworkService. Although these two are the same account, the equality test fails because these strings do not match exactly. How can you properly test that two NTAccount objects are the same, despite their syntax being marginally different?

Regex for non-alphanumeric delimiters (not \W)

I have probably completely missed something, but here is what I have:

  1. -- Need to prevent inadvertent release of phone numbers.
  2. -- all numbers in the form nnn-nnnn
  3. -- may or may not be delimited (e.g, tab, comma, space, whatever)
  4. -- do NOT block journal articles or study numbers having similar (but not identical) form -- for example xxxnnn-nnnnxxx (yeah, sort of contradicts 'delimited', but "x" are alphanumeric only )

So, I have

(\A|\s|\W)\d{3}-\d{4}(\Z|\s|\W)

Which works! Almost the way I want. Almost. However, \W is ^a-zA-Z0-9_ and _ is a potential delimiter. Already tried replacing \W with ^a-zA-Z0-9 with no success (actually, worse), but perhaps specified improperly? FWIW, this will be evaluated by .NET engine.

The remote server returned an error: (404) Not Found. when doing a HttpWebResponse

I am having an issue with my code as I have to verify the status of some websites in order to notify if they are working or not. I can successfully check this for a number of websites, however for a particular one it is always returning 404 Not Found, even though the site is up and I can view it if I try to open the page on the browser, this is my code:

 public HttpStatusCode GetHeaders(string url, bool proxyNeeded)
    {

        HttpStatusCode result = default(HttpStatusCode);

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "HEAD";

        request.Credentials = new NetworkCredential(username, password, domain);

        if (proxyNeeded)
        {
            IWebProxy proxy = new WebProxy("127.0.0.1", port_number);
            proxy.Credentials = new NetworkCredential(username, password, domain);
            request.Proxy = proxy;
        }
        try
        {
            var response = (HttpWebResponse) request.GetResponse();
            result = response.StatusCode;
            response.Close();
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                WebResponse resp = e.Response;
                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                {
                    //TODO: capture the exception!!
                }
            }
        }
        return result;
    }

The exception does not tell me anything different than "Not Found" which really confuses me as I don't know where else to look.The URL failing is: http://cbprod-app/InterAction/home

If I request the page without setting the proxy, comes back with an "401 Not authorized" as it requires the proxy authentication to be displayed, I am running out of ideas, any suggestion about what am I doing wrong?

Thank you very much in advance.

Implementing IDisposable to new class [duplicate]

This question already has an answer here:

Feel free to mark this as duplicate but it's a question that's probably basics which I have come across during my interview preparations.

If I write following class.

Public Class Class1{


}

Will any of the following two be any different/beneficial in terms of when/how resource is disposed after it's use

var c=new Class1();   or

using(var c=new Class1())
{

}

If no difference between those, my next questions are reduntant. If second is better, the class1 must implement IDisposable ,

Provided I implement IDisposable

Public Class Class1:IDisposable
{

}

assuming there will be methods properties in the class. what would be correct way to implement.

Dispose method in this class, to make sure all resources are disposed correctly.

Storing WCF rest request data with SQL Server stored procedure

I have a simple interface in my WCF service with one method which gets a myRequest parameter

public interface IService
{
    [OperationContract]
    string MyOperation(myRequest request);
}

When I'm posting the data from the client, the content type is application/json, so the request body auto deserialise into myRequest object.

myRequest is a WCF DataContract:

[DataContract]
public class myRequest
{
    string id;
    string name;
    List<Phone> phones

    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string ID { get; set; }
    [DataMember]
    public List<Phone> Phones { get; set; }
}

and the Phone class

public class Phone
{
    public string Number { get; set; }
    public string Type { get; set; }

    public override string ToString()
    {
        return "[" + Number + "," + Type + "]";
    }
}

Ok, so now I would like to store the request data into my local SQL Server database and for that I need to use stored procedures. I want to send the myRequest object to SQL Server and let it deal with insert/update (I think what I will have to keep 2 tables: people and phones).

I don't have to much background about stored procedures but I will great to get from you guys the right approach to solve this.

Thanks.

Deploying .NET Application on Bluemix, connecting to external databases, Watson

I have an application built on .NET Framework using MVC 5 and SQL Server 2008 R2 Enterprise Edition which I want to deploy on Bluemix.

  1. Does Bluemix Support .NET. If I deploy my .NET application on Bluemix, would it work?
  2. I have Virtual Servers hosting the application and data for my Application on a separate hosting provider. If I deploy some components of my application (built on Bluemix supported technologies such as Java/ php/ node.js/ DB2) on Bluemix, will I still be able to communicate with my database etc. deployed outside of the Bluemix (and on a different hosting provider).
  3. If I deploy my application on Bluemix, will I need to necessarily consume Watson APIs? Does my deployment on Bluemix necessarily have to do anything with Watson or Watson Services? Can I deploy my application without consuming Watson APIs?

Many Thanks!!

How to download files with filename containing special characters using .Net WebClient

I am getting an error “400 – Bad Request” while using .Net WebClient to download files with filename containing certain characters:

For example if the file is named: 5L1XQE6FTest #.mp4 this generates an error.

If I remove the # sign the file is downloaded fine:

Here is my code:

  public ActionResult DownloadVideoFile(string filepath)
        {
            try
            {

               filepath = "http://localhost:1832/VideoUploads/" + filepath;
                var type = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                var path = Path.GetFileName(filepath);

                using (var client = new WebClient())
                {

                    var buffer = client.DownloadData(filepath);
                    return File(buffer, type.ToString(), path);
                }

            }
            catch (Exception e)
            {
                var test = e.Message;
            }
            return null;

        }

When I url encode the file name I still get the same error.

I have no control over the filename that I am trying to download as files are user submitted.

How can I resolve the Bad Request error while downloading files with special or reserved characters?

Loading Winamp's in_midi.dll from .NET

I am trying to load a Winamp input plugin and work with it in C#. According to the Winamp SDK, this is the proper way to load a plugin:

in_mp3_lib = LoadLibraryW(path);
if (in_mp3_lib)
{
    PluginGetter pluginGetter = (PluginGetter)GetProcAddress(in_mp3_lib, "winampGetInModule2");
    if (pluginGetter)
    {
        in_mp3 = pluginGetter();
    }
}

So I've created a similar code in C#:

[DllImport("kernel32", SetLastError=true, CharSet=CharSet.Unicode)]
static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

delegate IntPtr PluginGetter();

IntPtr hmod = LoadLibrary("in_midi.dll");
var getmod = (PluginGetter)Marshal.GetDelegateForFunctionPointer(GetProcAddress(hmod, "winampGetInModule2"), typeof(PluginGetter));
IntPtr modptr = getmod();

However, on the line with LoadLibrary, an error (not exception) window is shown:

---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Runtime Error!

Program: C:\Users\...

R6034

An application has made an attempt to load the C runtime library incorrectly.
Please contact the application's support team for more information.

---------------------------
OK   
---------------------------

And hmod is null.

Apparently, the plugin tries to load msvcrt90.dll, but this error keeps showing even if I have it in the directory.

How can I stop Automapper converting enum values into strings

Our code currently uses a very old version of Automapper (1.1) to the more recent 3.3. A change in automapper behaviour is causing some problems.

We have fields of type object which may take values that are either reference types or enum values. When the field values are enum values, then Automapper maps the value to the string representation.

See the code example below which illustrates our problem - could someone please tell me how to persuade Automapper to map the enum value to the target enum value.

Thanks in advance - chris

    using AutoMapper;
    using AutoMapper.Mappers;
    using NUnit.Framework;

    namespace AutoMapperTest4
    {
        [TestFixture]
        public class AutomapperTest
        {
            [Test]
            public void TestAutomapperMappingFieldsOfTypeEnumObject()
            {
                // Configure 
                var configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
                var mapper = new MappingEngine(configuration);
                IMappingExpression<Source, Target> parentMapping = configuration.CreateMap<Source, Target>();
                parentMapping.ForMember(dest => dest.Value, opt => opt.MapFrom(s => ConvertValueToTargetEnumValue(s)));

                var source = new Source { Value = SourceEnumValue.Mule };

                var target = mapper.Map<Target>(source);

                Assert.That(target.Value, Is.TypeOf<TargetEnumValue>()); // Fails.  targetParent.Value is a string "Mule".
            }

            private static TargetEnumValue ConvertValueToTargetEnumValue(Source s)
            {
                return (TargetEnumValue)s.Value;
            }
        }

        public enum SourceEnumValue
        {
            Donkey,
            Mule
        }

        public enum TargetEnumValue
        {
            Donkey,
            Mule
        }

        public class Source
        {
            public object Value { get; set; }
        }

        public class Target
        {
            public object Value { get; set; }
        }
    }

Why does the RadioButton's Click events fire before CheckedChanged?

In my .NET application's GUI (done in C#, but I don't think that matters) are TextBoxes and RadioButtons handling user changeable data.

For the TextBoxes, I handle the KeyDown and the TextChanged event. During the initial setting of the TextBoxes' Text, of course the TextChanged event fires, but since there was no KeyDown event first, the data is not changed by the user (so it does not have to be written back to the store).

Now I wanted to use the same technique for the RadioButtons using the Click or MouseClick event as a user interaction detector. Unfortunately both Click events fire before the CheckedChanged event.

This - IMHO - is just wrong. The Checked property cannot change before the control is clicked. Is this a logical error or does this happen for a reason? Is there any way to force correct behaviour?

(To solve the GUI problem, of course I could just introduce a variable for initial setting of the Control's values. But this is about understanding the logic here.)

C# create object for same class in the class itself

I am just trying out some things in c# and i came across this where i have created an object for the same class in the class itself

class Class1
    {
        public int test1 { get; set; }
        Class1 x = new Class1();
    }

and then i have tried to create object from an other class which is throwing an error

An unhandled exception of type 'System.StackOverflowException' occurred in Test.exe

class Program
    {
        static void Main(string[] args)
        {
            Class1 x = new Class1();
        }
    }

i have googled and i havent found any related links to c# but i found it in c++ where they say a Class1 is an incomplete type, as it has not been defined yet, rather it's being defined. I would like to know whether its the same case for c# also

How many pixels are drawn between edges of the WPF panel

Here is the problem. I try to build chart control. And i want to calculate coordinates for data values via some calculator class.

Lets assume i have a canvas with height = 35. If move mouse vertically, mouse move events will bring in position all the values 0, 1, 2 ... 35. So It seems that there are 36 pixels between edges. Is this correct ?

Because i thought that actual amount of pixels is 35, because indexes are from 0 to n-1.

So the question is, during calculation in calculator class, do i need to consider n-1 (subtract 1 from actual size of the panel)

How can i fix Index Out Of Range Exception of a char?

First the project it self i didn't do it i took it from github:

spazzarama/Direct3DHook

The problem the exception happen when i try to use any directx11 game. The exception happen in the DXHookD3D11.cs

#region Draw overlay (after screenshot so we don't capture overlay as well)
                if (this.Config.ShowOverlay)
                {
                    // Initialise Overlay Engine
                    if (_swapChainPointer != swapChain.NativePointer || _overlayEngine == null)
                    {
                        if (_overlayEngine != null)
                            _overlayEngine.Dispose();

                        _overlayEngine = new DX11.DXOverlayEngine();
                        _overlayEngine.Overlays.Add(new Capture.Hook.Common.Overlay
                        {
                            Elements =
                            {
                                //new Capture.Hook.Common.TextElement(new System.Drawing.Font("Times New Roman", 22)) { Text = "Test", Location = new System.Drawing.Point(200, 200), Color = System.Drawing.Color.Yellow, AntiAliased = false},
                                new Capture.Hook.Common.FramesPerSecond(new System.Drawing.Font("Arial", 16)) { Location = new System.Drawing.Point(5,5), Color = System.Drawing.Color.Red, AntiAliased = true }
                            }
                        });
                        _overlayEngine.Initialise(swapChain);

                        _swapChainPointer = swapChain.NativePointer;
                    }
                    // Draw Overlay(s)
                    else if (_overlayEngine != null)
                    {
                        foreach (var overlay in _overlayEngine.Overlays)
                            overlay.Frame();
                        _overlayEngine.Draw();
                    }
                }
                #endregion

Then when it's trying to Draw() i used a breakpoint it's going to the class DXOverlayEngine.cs to this line:

_spriteEngine.DrawString(textElement.Location.X, textElement.Location.Y, textElement.Text, textElement.Color.R, textElement.Color.G, textElement.Color.B, textElement.Color.A, font);

Then it's going to the DXSprite.cs to this part:

public void DrawString(int X, int Y, string text, int R, int G, int B, int A, DXFont F)
        {
            Color4 blendFactor = new Color4(1.0f);
            Color4 backupBlendFactor;
            int backupMask;
            var backupBlendState = _deviceContext.OutputMerger.GetBlendState(out backupBlendFactor, out backupMask);
            _deviceContext.OutputMerger.SetBlendState(_transparentBS, blendFactor);

            BeginBatch(F.GetFontSheetSRV());


            int length = text.Length;

            int posX = X;
            int posY = Y;

            Color4 color;
            Vector4 Vec = new Vector4(R > 0 ? (float)(R / 255.0f) : 0.0f, G > 0 ? (float)(G / 255.0f) : 0.0f, B > 0 ? (float)(B / 255.0f) : 0.0f, A > 0 ? (float)(A / 255.0f) : 0.0f);
            color = new Color4(Vec);

            for (int i = 0; i < length; ++i)
            {
                char character = text[i];

                if (character == ' ')
                    posX += F.GetSpaceWidth();
                else if (character == '\n')
                {
                    posX = X;
                    posY += F.GetCharHeight();
                }
                else
                {
                    Rectangle charRect = F.GetCharRect(character);

And last it's doing the line F.GetCharRect(character) in the DXFont.cs class:

public Rectangle GetCharRect(char c)
        {
            Debug.Assert(_initialized);

            return _charRects[c - StartChar];
        }

I used a breakpoint on the method GetCharRect and for example in this case the variable c value is: 163'£ and the value in the variable StartChar is 33 '!'

Then it's showing the exception on the line:

return _charRects[c - StartChar];

I tried to ask the owner about this problem and so far all he told me is:

"Sounds like it is trying to draw a character that it hasn't prepared..."

I tried to narrow the code here as much as i can but it's all connect each other.

How do I use Automapper to map objects from their IDs

I have a doubt about automapper's functioning..

we have a Function import returning a table say t_MyTable

t_MyTable is

ID ----- ForeignID ----- Data

where is ForeignID is id from other table and we have foreign key setup on this column.

so the result set returned by ef contains all ID, ForeignID and Data also I can see reference to t_Foreign table returned to which ForeignID belongs.

We use autoMapper to map from ef result to our entities..

CreateMap(Of t_MyTable , Concrete.Entities.MyTable)()

and to populate object Foreign we have to do this..

CreateMap(Of t_MyTable , Concrete.Entities.MyTable)().
ForMember(Function(d) d.Foreign, Sub(o) o.MapFrom(Function(e) Mapper.Map(Of t_Foreign, Foreign)(e.t_Foreign)))

this ofcourse is very slow as there are lots of foreign keys and lots of rows. I think there must be a way to tell ef the relation implicitly so that this can be made faster.

Any guidance around this will be appreciated.

outbound web requests fail when made from IIS sites using shared IP address

  • IIS 7.5 / Windows Server 2008 R2
  • Multiple IIS sites bound to the same IP address, using host names.
  • Inbound traffic to sites working fine.
  • Outbound web requests made by the back-end site code fail. Remote site returns 404 (NotFound).
  • Verified via a network trace that the traffic is making it to the remove server.
  • Same requests work fine if done from a site using a dedicated IP address (i.e. not shared w/ any other sites).

Anyone have any ideas on how to make this work or what could be going wrong?

Network trace on hosting server:

Successful request from site w/ non-shared IP address:

No.     Time            Source                Destination           Protocol Info
   6366 15:54:35.590463 192.168.1.76          173.194.77.121        HTTP     GET /key/value/one/two HTTP/1.1 
   6369 15:54:35.599879 173.194.77.121        192.168.1.76          TCP      http > 55407 [ACK] Seq=1 Ack=110 Win=344 Len=0
   6370 15:54:35.621587 173.194.77.121        192.168.1.76          HTTP     HTTP/1.1 200 OK  (application/json)
   6608 15:54:35.815774 192.168.1.76          173.194.77.121        TCP      55407 > http [ACK] Seq=110 Ack=357 Win=509 Len=0

Failed request from site using a shared IP address:

No.     Time            Source                Destination           Protocol Info
   9720 15:54:39.244192 192.168.1.80          173.194.77.121        HTTP     GET /key/value/one/two HTTP/1.1 
   9760 15:54:39.256958 173.194.77.121        192.168.1.80          TCP      [TCP segment of a reassembled PDU]
   9761 15:54:39.256962 173.194.77.121        192.168.1.80          HTTP     HTTP/1.1 404 Not Found  (text/html)
   9762 15:54:39.257027 192.168.1.80          173.194.77.121        TCP      55438 > http [ACK] Seq=212 Ack=1676 Win=512 Len=0

Code:

public static HttpWebRequest CreateWebRequest(string url, string method = "GET", string referer = null, string contentType = null, int timeout = 100000, string authentication = null, string bindToIpAddress = null, string host = null)
{
    var request = (HttpWebRequest)WebRequest.Create(url);

    if (!string.IsNullOrWhiteSpace(bindToIpAddress))
    {
        IPAddress bindIp;
        if (!IPAddress.TryParse(bindToIpAddress, out bindIp))
        {
            throw new ArgumentException("bindToIpAddress");
        }

        request.ServicePoint.BindIPEndPointDelegate = ((sp, rep, rc) =>
        {
            return new IPEndPoint(bindIp, 0);
        });
    }

    request.Accept = "*/*";
    request.ContentType = contentType;
    request.Referer = referer;
    request.Method = method;
    request.Timeout = timeout;

    if (!string.IsNullOrWhiteSpace(host))
    {
        request.Host = host;
    }

    return request;
}

string GetData()
{
    try
    {
        string result;

        var request = CreateWebRequest("http://ift.tt/1pLXQ3d", 
                                       "GET", 
                                       "somedomain.com", 
                                       timeout: (10 * 1000), 
                                       bindToIpAddress: "192.168.27.133" /*site IP*/);

        request.Accept = "application/json";

        using (var response = request.GetResponse())
        {
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                result = sr.ReadToEnd();
            }
        }

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}

LINQ connection in app.config

I have been reading how to store the connection string for a dbml in the app.config whereby I would create a partial class with the same name as the existing one for the dbml. One thing I haven't seen though, should this be created within the dbml's designer.cs file?

thanks

Splitting string into multiple strings using LINQ

I am trying to split this string

string s = sn DC0000002; mac 00:0c; uuid 564d6ae4-979

I need to get these values from above string DC0000002 , 00:0c , 564d6ae4-979

For this I have tried below query but not able to able to get last two values I mean these two values (00:0c , 564d6ae4-979)

Below is the query for splitting

List<string> decryptedList = new List<string>();
decryptedList = decodePP.Split(';').Select(x => x.Split(' ')[1]).ToList();

orgSNo = decryptedList[0]; //Output - DC0000002
orgMacID = decryptedList[1];// output - mac // this is wrong need to get value
orgUUID = decryptedList[2]; //output - uuid // this is also wrong 

Would anyone please help on this query how extract values from the above string using LINQ query in a single shot?

What are the benefits and drawbacks of indexer methods in C#?

I have a collection class that implements an indexer method like so:

public class ProductCollection : IEnumerable {
    private ArrayList products = new ArrayList();

    public Product this[int index] {
        get { return (Product)products[index]; }
        set { products.Insert(index, value); }
    }

    public int Count {
        get { return products.Count; }
    }

    public IEnumerator GetEnumerator() {
        return products.GetEnumerator();
    }
}

It allows me to manipulate its elements using indexes, just like a standard array:

ProductCollection collection = new ProductCollection();
collection[0] = new Product {Description = "Product 1"};
collection[1] = new Product {Description = "Product 2"};

for (int index = 0; index < collection.Count; index++) {
    Console.WriteLine(collection[index].Description);
}

Alternatively, I could have the same collection without the indexer method by implementing simple Add and Get methods. It would look like this:

public class ProductCollection : IEnumerable {
    private ArrayList products = new ArrayList();

    public void Add(int index, Product product) {
        products.Insert(index, product);
    }

    public Product Get(int index) {
        return (Product)products[index];
    }

    public int Count {
        get { return products.Count; }
    }

    public IEnumerator GetEnumerator() {
        return products.GetEnumerator();
    }
}

Then I could perform the same operations as before, only with a slightly modified syntax:

ProductCollection2 collection = new ProductCollection2();
collection.Add(0, new Product {Description = "Product 1"});
collection.Add(1, new Product {Description = "Product 2"});

for (int index = 0; index < collection.Count; index++) {
    Console.WriteLine(collection.Get(index).Description);
}

Keeping syntax aside and considering the internals of the language, are there any benefits and/or drawbacks of using one form or another?

Transactionally delete all files and folders in a directory

This is similar with this question but with one more requirement:

Since the deletion of files can fail for whatever reasons. So I want the operation to be "transacted" which mean the whole operation either success in total, or fail and do not change anything at all.

In general this will be very very hard and I can't see any possibility to recover when the physical hard drive suddenly broken. So a weakened clause would be: if it success, we finished. Otherwise if fail, restore everything to the original state when possible.

Some kind of errors I could think of would be:

  1. Access violation. You simply don't allowed to delete some files or folders. This is the case that I wanted to handle the most.

  2. File/folder was used by somebody else and so it is "locked". In Linux this is not a problem but in Windows it is. This is also to be handled.

  3. If it is a network folder there could be network issues. The recover can be hard or impossible. I would not expect this kind of error to be properly handled.

  4. Hardware failure. I don't think any recover can happen here.

Scenario

You have a software that can export its internal data. The result is in a folder and with sub-folder names timestamped.

Now if the user specified a folder that is not empty (probably a previous output folder), the software will create new sub-folders on top of it, which is a mass. So you want to ensure the folder is empty before performing the export.

You can easily detect the folder emptiness and alert the user if not. But if the user say "go ahead and do it" you should do something then. Now, what if you were deleted some of the files and failed on others?

Going ahead in this case is just creating worse mass. At the same time the user would not expect a damaged folder without getting anything working. So it is better to either give them a fully working output or does not change the previous output at all.

Fallback mechanism for logging xml errors in Elmah

We are using Elmah extensively to log exceptions as xml files in our applications. These errors are logged on a shared network drive. This network drive has gone down several times in the past in the production(Please see below). How would Elmah behave in this case? Is there a fallback mechanism that we can use to tell Elmah to not log the error if the network drive is down?

System.IO.IOException: The device does not recognize the command.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
   at System.IO.Directory.CreateDirectory(String path)
   at Elmah.XmlFileErrorLog.Log(Error error) in C:\Elmah\XmlFileErrorLog.cs:line 137
   at Realpage.Portals.Leasing.UI.MVC.MvcApplication.ErrorLog_Filtering(Object sender, ExceptionFilterEventArgs e) in c:\test\Global.asax.cs:line 154

Exception not marked as serializable

With no changes to code (that I recall) formatter.Serialize fails for on type of object
It works for 5 other types tested
I have made no changes to that class (that I recall) - is is marked as Serializable It is a fairly simple class and has no reverence to a system.Windows.Documents.FlowDocument

How can I tack down the error and fix it?

public static T DeepClone<T>(T obj)
{
    using (var ms = new MemoryStream())
    {
        var formatter = new BinaryFormatter();

        try
        {
            formatter.Serialize(ms, obj);
        }
        catch (Exception Ex)
        {
            Debug.WriteLine(Ex.Message);
            Debug.WriteLine(Ex.Source);

A first chance exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll

Additional information: Type 'System.Windows.Documents.FlowDocument' in Assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

InnerExeption is null

How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n

Anyone can elaborate some details on this code or even give a non-Linq version of this algorithm:

public static IEnumerable<IEnumerable<T>> Combinations<T>
    (this IEnumerable<T> elements, int k)
{
   return k == 0 ? new[] { new T[0] }
                 : elements.SelectMany(
                       (e, i) =>
                         elements
                         .Skip(i + 1)
                         .Combinations(k - 1)
                         .Select(c => (new[] {e}).Concat(c)));
}

Distinction between a program and library

Typically the CLR deals with two kinds of binary:

A program has a file name ending in .exe, is marked as a program in the PE header, and has an entry point.

A library has a file name ending in .dll, is marked as a library in the PE header, has no entry point, and has metadata describing the callable functions it contains.

What parts of this distinction are actually enforced?

For example, I think the extension in the filename doesn't actually matter for anything except the command search path; once the file is being read, the filename is ignored and only the PE header counts. Is this correct?

Can you take a program and treat it as a library, referring to it from another program and calling some of its functions without using its entry point?

Can a library have an entry point? If so, can it be run like a program?

Is there a way to use the MongoDB C# driver synchronously

I have a 2 layered C# project. The 1st one is a data layer which connects to mongodb and sends collections to the web service layer. The problem is that I couldn't find in the new driver non-async methods (i.e. synchronous).

Is there a way to use synchronous methods with the C# driver for mongodb version 2.0?

Hint: Is it possible to run mongodb shell functions with c#?

Thanks

Select Query and Update Query in same StoredProcedure

I have a stored procedure in which I'll select some rows based on a condition and I need to update the status of those rows within the same stored procedure. For e.g.

Create Procedure [dbo].[myProcedure]
As
BEGIN
BEGIN TRAN T1
SET NOCOUNT ON
SELECT TOP 5 * INTO #TempTable FROM myTable WHERE ENABLED = 1;
UPDATE myTable SET [Status] = 'Locked' From myTable Inner Join on #TempTable myTable.id = #TempTable.id;
SELECT * FROM #TempTable;
DROP Table #TempTable;
COMMIT TRAN T1
END

The Stored Procedure works fine when I debug in SQL. I'm accessing the StoredProcedure through C# like this.

private ProcessData[] ReadFromDb(string StoredProcedure, SqlConnection Connection)
        {
            List<ProcessData> Data = new List<ProcessData>();
            SqlCommand Command = new SqlCommand(StoredProcedure, Connection);
            Command.CommandType = System.Data.CommandType.StoredProcedure;
            try
            {
                Command.CommandTimeout = CONNECTION_TIMEOUT;
                using (SqlDataReader Reader = Command.ExecuteReader())
                {
                    while (Reader.Read())
                    {
                        Data.Add(new ProcessData()
                        {
                              Id = Reader["Id"];
                              ...
                           });
                    }
                }
            }
            catch (Exception ex)
            {}
        }

The problem is I'm getting the required rows in C# but the update query in stored procedure is not working. Can anyone give some suggestions where I'm going wrong.

SerialPort visible in device manager but SerialPort.Open() reports that it cannot be found

I have a .NET application that listens on a COM port. The other side of the connection is a UDOO board running lubuntu.

After the udoo board is rebooted, the COM port temporarily goes missing and then re-appears on the device manager. However, when I call the "Open" function of the SerialPort object, I get an exception which says "The port COM4 does not exist". The full exception stack trace is as follows.

 at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   at System.IO.Ports.SerialPort.Open()

Even when this exception is thrown, device manager shows the very same COM port as visible as in the following screenshot.

enter image description here

And yes I did refresh the device list. Unplugging and plugging the cable back to the computer solves this problem but, it isn't elegant.

Are there any thoughts on how I could work around this problem ?

F# Plot Weighted Zip Codes on US Map

I have a list of weighted Zip Codes (i.e. number of occurrences in the data) That I want to map on a US map in a heat map style. I have seen demonstrations using R in conjunction with F#.

I am new to F# and have never used R, but want to learn. What I have so far is loading R into F# and getting the data. I have created simple scatter plots and line graphs with the code below, but think it will be more appealing when mapped on a US map.

open System
open RDotNet
open RDotNet
open RProvider
open RProvider.graphics
open System.Linq
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq
open RProvider.spatial

type dbSchema = SqlDataConnection<"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;">
let db = dbSchema.GetDataContext()

let addresses = db.Address

let zips = query {
        for row in db.Address do
        groupBy row.PostalCode into x
        select (x.Key, x.Count())
    }

Declaring variables for intermediate calculations and performance

I have a program that runs billions of calculations and I'm trying to get it to run faster. In my program, I declare a lot of variables for intermediate calculations. For example, in pseudo code:

public bool FunctionThatGetsCalledInMain(manyparameters)
{
    for (int i = 0; i < 10000000; i++)
    {
        int x = bigFunctionThatReturnsAnInt(manyparameters)
        double y = bigFunctionThatReturnsADouble(manyparameters)
        string z = bigFunctionThatReturnsAString(manyparameters)

        bool b = someFunctionOfXYZ(x,y,z)
    }
}

I'm wondering if I can improve performance by doing something like:

public bool FunctionThatGetsCalledInMain(manyparameters)
{
    for (int i = 0; i < 10000000; i++)
    {
        bool b = someFunctionOfXYZ(bigFunctionThatReturnsAnInt(manyparameters),bigFunctionThatReturnsADouble(manyparameters),bigFunctionThatReturnsAString(manyparameters))
    }
}

I know it looks horrendous, but I really need to cut the time. Not sure if this theoretically makes a difference at all.

WCF: UseStrTransform with IssuedToken produces SecurityTokenReference with duplicated Id

I'm implementing a service that needs o comply with http://ift.tt/1KRmCJk using WCF and WIF 4.5.

The specification requires that STR transformation must be used. The end message may look like:

    <Assertion ID="_f23ef5f3-9efb-40f0-bf38-758d3a9589db" IssueInstant="2015-05-08T09:07:09.311Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
       ...
    </Assertion>
    <o:SecurityTokenReference b:TokenType="http://ift.tt/1m2LCTl" u:Id="str1" xmlns:b="http://ift.tt/1eWSHNW">
      <o:KeyIdentifier ValueType="http://ift.tt/1KRmCZy">_f23ef5f3-9efb-40f0-bf38-758d3a9589db</o:KeyIdentifier>
    </o:SecurityTokenReference>

If I use the following binding:

        var messageSecurity = new AsymmetricSecurityBindingElement();

        messageSecurity.AllowSerializedSigningTokenOnReply = true;
        messageSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
        messageSecurity.RecipientTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Any, SecurityTokenInclusionMode.AlwaysToInitiator);
        messageSecurity.RecipientTokenParameters.RequireDerivedKeys = false;
        var initiator = new CustomIssuedSecurityTokenParameters("http://ift.tt/1m2LCTl");
        messageSecurity.ProtectTokens = true;
        initiator.UseStrTransform = true;
        initiator.KeyType = SecurityKeyType.AsymmetricKey;
        initiator.RequireDerivedKeys = false;

The generated message is:

    <Assertion ID="_f23ef5f3-9efb-40f0-bf38-758d3a9589db" IssueInstant="2015-05-08T09:07:09.311Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
       ...
    </Assertion>
    <o:SecurityTokenReference b:TokenType="http://ift.tt/1m2LCTl" u:Id="_f23ef5f3-9efb-40f0-bf38-758d3a9589db" xmlns:b="http://ift.tt/1eWSHNW">
      <o:KeyIdentifier ValueType="http://ift.tt/1KRmCZy">_f23ef5f3-9efb-40f0-bf38-758d3a9589db</o:KeyIdentifier>
    </o:SecurityTokenReference>

What is not right is that the SecurityTokenReference element has the same Id as that of the Assertion element which causes an error:

<Message>The '_f23ef5f3-9efb-40f0-bf38-758d3a9589db' id occurred twice in the message that is supplied for verification.</Message>
<StackTrace>
at System.ServiceModel.Security.ReceiveSecurityHeaderElementManager.VerifyIdUniquenessInSecurityHeader(String id)

Looking at WCF's source code told me that WCF always creates the SecurityTokenReference with Id set to that of the referenced element. To overcome this issue, I created a custom Paratemers class:

public class CustomIssuedSecurityTokenParameters : IssuedSecurityTokenParameters
{...
    protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
    {
        var clause = base.CreateKeyIdentifierClause(token, referenceStyle);
        clause.Id = "";
        return clause;
    }
}

If I use that custom class, another error will pop up:

<ExceptionType>System.ServiceModel.Security.MessageSecurityException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>Cannot resolve KeyInfo for verifying signature: KeyInfo 'SecurityKeyIdentifier
(
IsReadOnly = False,
Count = 1,
Clause[0] = Saml2AssertionKeyIdentifierClause( Id = '_str1' )
)
', available tokens 'SecurityTokenResolver
(
TokenCount = 1,
TokenEntry[0] = (AllowedReferenceStyle=Internal, Token=System.IdentityModel.Tokens.Saml2SecurityToken, Parameters=Kombit.Samples.Common.Binding.CustomIssuedSecurityTokenParameters:
InclusionMode: AlwaysToRecipient
ReferenceStyle: Internal
RequireDerivedKeys: False
TokenType: http://ift.tt/1m2LCTl
KeyType: AsymmetricKey
KeySize: 0
IssuerAddress: null
IssuerMetadataAddress: null
DefaultMessgeSecurityVersion: null
UseStrTransform: True
IssuerBinding: null
ClaimTypeRequirements: none)
)

Could anyone please show me a way to get the UseStrTransform setting work? What am I missing here?

Why don't some diacritics get stripped?

I am using the method from this answer to remove special characters from words and change them to a simple form. This works pretty nicely for many basic accents, e.g.

Malmö becomes "Malmo"
München becomes "Munchen"
Åge becomes "Age"

However this doesn't work on some other characters, for example:

Strømsgodset remains "Strømsgodset"
Kulħadd remains "Kulħadd"

Is there any reason why these characters are not converted like the others?

Also is there any way to similarly convert 'combined' characters such as:

æ -> ae
ẞ -> ss

how to insure that a user's browser is running the latest version of a web page after a server side update

I develop an app with angularJS and Breeze, everytime there are changes on server side, user has to press Ctrl F5 to clear cache to make changes take effect on client side. I am wondering if there is a way to make it auto happen so that users don't have to manually refresh their broswer?