lundi 29 juin 2015

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.

Handle error converting {null} to type system.Int32 in input json

Platform : C# IDE : Microsoft Visual Studio 2010

I am new to Json and wondering on how to handle the error converting value {null} to type system.Int32 in an input. Any suggestion?

Regular expression lookhead lookbehind

I need some help with a regular expression for .NET, I have an input field for a telephone number.

I use a regex to format the value (050 33 11 00) to this format:

+32(0)50/33.11.00

But when I insert following value 09 323 23 56 I want to get following result:

+32(0)9/323.23.56

I've been looking at lookahead but can't find a working solution.

I'm using the folowing regex: (\x2B{1}3{1}2{1}\x28{1}\d{1}\x29{1}\d{2}\/\d{2}\.\d{2}\.\d{2}) which works for the first value.

The regex is placed on a textbox as editMask, so i would like instant live sanitizing.

textEdit.Mask.EditMask = editMask;

How to writer "Pointer to a pointer to a list of structured elements" in C# and how to read those poninter values in C#?

How to writer " The Pointer to a pointer to a list of structured elements" in C# and how to read those poninter values in C#?

get code coverage percentage in cruisecontrol.net c#

I am trying to get code coverage in cruisecontrol.net. Using the following NANT script:

<target name="code_coverage" description="finds the code covered with tests">
  <exec program="${vstest_console}">
    <arg value="/Settings:CodeCoverage.runsettings" />
    <arg value="/EnableCodeCoverage" />
    <arg value="Tests.dll"/>
  </exec>
</target>

I am able to get a .coverage file. First of all the name of the .coverage file is coming as user name appended with current date time and under a folder named randomly. In .runsettings file documentation, i was unable to find anything about changing the name of .coverage file. I need to change name of this file. The bigger problem is that a sub-folder with some GUID type name is created into which the coverage file is dumped and it changes every time a test is run with code coverage ON.

Secondly can somebody help me in extracting covered path percentage out of this. I just need to fail the build, if coverage is below a point. Lot of help is available on Google but is of VS 2010 and before. I need help for VS 2012 or VS 2013. Currently am working on VS 2013 Ultimate and am using .runsettings file for code coverage.

pinta software customization for resizing image

i want customize pinta software for implementing tool like a pentool in photo shop and convert resize system in pinta software to resize system like a photoshop and i want Guidance for this work. and show me a solution for this work.

Sequential vs parallel solution memory usage

I have a slight issue with the following scenario: I'm given a list of ID values, I need to run a SELECT query (where the ID is a parameter), then combine all the result sets as one big one and return it to the caller.

Since the query might run for minutes per ID (that's another issue, but at the moment I consider it as a given fact), and there can be 1000s of IDs in the input) I tried to use tasks. With that approach I experience a slow, but solid increase in memory use.

As a test, I made a simple sequential solution too, this has normal memory usage graph, but as expected, very slow. There's an increase while it's running, but then everything drops back to the normal level when it's finished.

Here's the skeleton of code:

public class RowItem
{
    public int ID { get; set; }
    public string Name { get; set; }
    //the rest of the properties
}


public List<RowItem> GetRowItems(List<int> customerIDs)
{
    // this solution has the memory leak
    var tasks = new List<Task<List<RowItem>>>();
    foreach (var customerID in customerIDs)
    {
        var task = Task.Factory.StartNew(() => return ProcessCustomerID(customerID));
        tasks.Add(task);
    }

    while (tasks.Any())
    {
        var index = Task.WaitAny(tasks.ToArray());
        var task = tasks[index];
        rowItems.AddRange(task.Result);
        tasks.RemoveAt(index);
    }

    // this works fine, but slow
    foreach (var customerID in customerIDs)
    {
        rowItems.AddRange(ProcessCustomerID(customerID)));
    }

    return rowItems;
}

private List<RowItem> ProcessCustomerID(int customerID)
{
    var rowItems = new List<RowItem>();
    using (var conn = new OracleConnection("XXX"))
    {
        conn.Open();
        var sql = "SELECT * FROM ...";
        using (var command = new OracleCommand(sql, conn))
        {
            using (var dataReader = command.ExecuteReader())
            {
                using (var dataTable = new DataTable())
                {
                    dataTable.Load(dataReader);
                    rowItems = dataTable
                               .Rows
                               .OfType<DataRow>()
                               .Select(
                                   row => new RowItem
                                   {
                                       ID = Convert.ToInt32(row["ID"]),
                                       Name = row["Name"].ToString(),
                                       //the rest of the properties
                                   })
                               .ToList();
                }
            }
        }
        conn.Close();
    }
    return rowItems;
}

What am I doing wrong when using tasks? According to this MSDN article, I don't need to bother disposing them manually, but there's barely anything else. I guess ProcessCustomerID is OK, as it's called in both variations.

update To log the current memory usage I used Process.GetCurrentProcess().PrivateMemorySize64, but I noticed the problem in Task Manager >> Processes

dimanche 28 juin 2015

SingleOrDefault: Catch just "Sequence contains more than one element" InvalidOperationException

In our project we recently added an import tool for old data, in which we convert this old data to usable objects in our application. In this import we have the following piece of code:

using (var session = documentStore.OpenSession())
{
    try
    {
        var cluster = session.Query<ClusterState>().SingleOrDefault(x => x.Name == clusterString);
        return cluster != null
            ? (ClusterId) cluster.AggregateId
            : null;
    }
    catch (InvalidOperationException e)
    {
        if (String.Equals(e.Message, "Sequence contains more than one element"))
        {
            Logger.Warn("More than one cluster found with the given string: {0}", clusterString);
            if (...)
            {
                return ...
            }
            return null;
        }

        throw;
    }
}

My issue is the following line:

if (String.Equals(e.Message, "Sequence contains more than one element"))

It works local, but not on the server. The reason for this is we have a Dutch server, so instead of "Sequence contains more than one element" it gives a "Reeks bevat meerdere elementen" InvalidOperationException. Now I know I can modify the code to this:

if (String.Equals(e.Message, "Sequence contains more than one element")
    || String.Equals(e.Message, "Reeks bevat meerdere elementen"))

Of course this works, and I don't think we intend to have a different language server in the future, but still, it's pretty bad code and if the message ever changes with a new .NET / LINQ version, this doesn't work anymore.

So, is there any other way to catch just "Sequence contains more than one element" InvalidOperationException, and not any other InvalidOperationExceptions?

Should I add a Count check or something to see if I receive more than one matching element instead of the Try-Catch, or is there a distinguished way to filter just the "Sequence contains more than one element" Exceptions? Or should I just catch all "InvalidOperationExceptions" and add an additional log-line so we get notifications of these exceptions?

Charts: InsertEmptyPoints does not work when gap is too wide?

I use DataManipulator.InsertEmptyPoints method to insert empty points in my chart series to align them and making stacked column graphs. I found in the follow simple example, if the data gap is too wide, i.e. too many empty points to insert, this method simply skip working without causing any exception.

The following code wont insert empty points, however it works fine if the gap is shortened (see inline comments). For testing, the code is a window form with a chart control called "Chart1".

Anybody know why?

Imports System.Windows.Forms.DataVisualization.Charting

Public Class Form1

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

    Dim series1, series2 As New Series

    series1.Points.AddXY(Date.Parse("1/1/2012"), 5)   'Try this with 1/1/2013 or 1/1/2014
    series1.Points.AddXY(Date.Parse("1/1/2015"), 10)
    series1.Points.AddXY(Date.Parse("2/1/2015"), 10)
    series1.ChartType = SeriesChartType.Point
    series1.Name = "A"

    series2.Points.AddXY(Date.Parse("1/1/2015"), 20)
    series2.Points.AddXY(Date.Parse("2/1/2015"), 20)
    series2.Points.AddXY(Date.Parse("3/1/2015"), 20)
    series2.ChartType = SeriesChartType.Point
    series2.Name = "B"

    Chart1.Series.Clear()
    Chart1.Series.Add(series1)
    Chart1.Series.Add(series2)

    Chart1.DataManipulator.InsertEmptyPoints(1, IntervalType.Days, "A,B")

    series1.EmptyPointStyle.MarkerColor = Color.Red
    series2.EmptyPointStyle.MarkerColor = Color.Red

    Chart1.ChartAreas(0).AxisX.Minimum = Date.Parse("1/12/2014").ToOADate

End Sub
End Class

MAF Security: How to prevent a "Man-in-the-Middle" Attack

i am using MAF to offer user / customers the possibility to enhance our software. The Add-In will run with limited permissions and can be potentially untrusted code for us as well as for the customer in case they bought the add-in form a 3rd party developer.

In our case, Host and Host-Side Adapter run in the Main AppDomain with full permissions and Add-In as well as Add-In Side Adapter run with nearly no permissions.

When I get the Add-In token via AddInStore.FindAddIns, i can only validate that the Add-In Assembly itself is from the vendor which it should be. If an attacker exchanges the Add-In Assembly, then we will find that out and will not activate that assembly. But anyhow, as that runs with nearly no permissions, an attacker could not really harm the application and the environment (host, intranet etc).

But what is also possible, is that an attacker replaces the host-side adapter Assembly. An Attacker need just to place a new assembly in the right folder. As this runs with full permissions, the attacker code could really harm application and environment. As an attacker is then between host and add-in (more or less a man-in-the-middle), it can change also the data which is exchanges between both.

When i debug my code an check in the debugger the add-in token, i can see all the paths to the different assemblies, which the add-in store took to build up the pipeline:

Add-In Token

Unfortunately, the important information about the Assemblies taken, are private and i can't access them.

Is there a workaround to access this information?

Thank you very much for your help!

Kind Regards,

Tobias Lorentz

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...

DDD and Persistence. Again

I am struggling with persistence in Domain Driven Design. As far as I understand, domain model should never be persistent-aware. Let's say I am building a simple todo-list application. I have a task with following interface:

interface ITask
{
   bool IsCompleted {get;}
   string Description {get;}

   void Complete();
   void ChangeDescription(string description);
}

And the generic implementation should look like this:

class SimpleTask : ITask
{
    public SimpleTask(string description)
    {
       ChangeDescription(description);
    }

    public bool IsCompleted { get; private set; }
    public string Description { get; private set; }

    public void Complete()
    {
       IsCompleted = true;
    }

    public void ChangeDescription(string description)
    {
       // some validation here
       // ...
       Description = description;
    }
}

I want to have a description be necessary - because it's a business rule. So from this moment if I want to save this object via serializers I will fail because no parameterless constructor provided. And I shouldn't provide it because of no persistance-aware rule. If I model my task in a form of DTO\POCO I will end up with another problem - so called anemic model. Moreover, I don't want to provide setters to some properties.

So where is the solution to all of this? I can create a tightly-coupled saver that will know how to save and restore task state. But I can access only public properties and methods, what if internal logic of task will be complex and impossible to save\restore? Should I mark all fields in task internal and have a possibility to save inner state of object? Isn't it kinda code smell and violation of no persistence-aware rule?

How do you solve this?

Draw logarithmic lines in WPF Graph

I have to implement Frequency vs Gain Graph. X axis have logarithmic divisions like 10, 100, 1k and 2k , between each of the them there are other dotted line divisions. I am using WPF Tool kit to draw the graph. Now, I can I implement these dotted lines for x axis, also the dotted line are same between each main x axis values.

.NET tutorial cant understand purpose of certain fields in .cs Model files

I have been following the a tutorial on ASP.NET - http://ift.tt/1edRtVj

They start with building the data layer (the application is a shopping website for toys where each item belongs to one of four categories). So, they start with building out the "products" and "categories" tables. The products table has the following code -

[ScaffoldColumn(false)]
public int ProductID { get; set; }

[Required, StringLength(100), Display(Name = "Name")]
public string ProductName { get; set; }

[Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)]
public string Description { get; set; }

public string ImagePath { get; set; }

[Display(Name = "Price")]
public double? UnitPrice { get; set; }

public int? CategoryID { get; set; }

public virtual Category Category { get; set; }

In the code above, I don't understand what the purpose of the last field,

 public virtual Category Category { get; set; }

is.

And then similarly the categories .cs file has the following code -

[ScaffoldColumn(false)]
public int CategoryID { get; set; }

[Required, StringLength(100), Display(Name = "Name")]
public string CategoryName { get; set; }

[Display(Name = "Product Description")]
public string Description { get; set; }

public virtual ICollection<Product> Products { get; set; }

Again, what is the purpose of

public virtual ICollection<Product> Products { get; set; }

And then finally, there is a context class with the following code -

using System.Data.Entity;
namespace WingtipToys.Models
{
  public class ProductContext : DbContext
  {
    public ProductContext() : base("WingtipToys")
  {
}
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
  }
}

This one has a field called Products but so did the second .cs file. So, what is this one for and won't it conflict with the other "Products" object which was also global?

How should I disable Entity Framework table refrence(foreign) list from each other objects?

I'm using Sqlite database and System.Data.SQLite 1.0.92 There is 2 table here:


Table Person:

PersonId

PersonName


Table Student:

StudentId

PersonId(reference table Person FK)

StudentNo


Now every time I get the Persons Collection in EF5:

using (var ctx = new myEntities)
{
  AllPersons = ctx.Persons.ToList();
}

There is also has AllPersons.student collection will include in the result;

But I don't need it. Of course that's just an example, There is a lot of big table has so many references, it always has performance problems here because of that.

So I'm trying to do not let it in my result. So I change it:

using (var ctx = new myEntities)
{
      ctx.Configuration.ProxyCreationEnabled = false;
      ctx.Configuration.LazyLoadingEnabled = false;
      AllPersons= ctx.Persons.ToList();
}

Now fine, because AllPersons.student collection will always be null

But now I found: If I get Person and Student together:

using (var ctx = new myEntities)
{
    ctx.Configuration.ProxyCreationEnabled = false;
    ctx.Configuration.LazyLoadingEnabled = false;
    AllPersons= ctx.Persons.ToList();
    AllStudents = ctx.Student.ToList();
}

Now the reference still include in.

So Is there anyway to don't let the reference include in any time in this situation? Thank you.

Limit rows displayed in DataGridView when using DataSource

I have a DataTable containing 10000+ rows, resulting from a SQL Server query. The DataTable is used as the DataSource for a DataGridView, like so (simplified code):

MyBindingSource = New BindingSource(MyDataTable, Nothing)
MyDataGridView.DataSource = MyBindingSource

As this takes a looong time to load, I would like to limit the number of rows displayed in the DataGridView, somehow.

I can't use TOP in my query, because I need all the data present in the DataTable for filtering later on, without re-setting the DataSource (MyBindingSource.Filter = MyFilter).

Also, I can't use the Filter property for limiting the number of rows, because there's no relevant data in the query result that I can use for this. To get around this, I've thought about adding TSQL's ROW_NUMBER to the query result (MyBindingSource.Filter = "[RowNumberField] < 100"), but this would only work when no other fields are used in the filter.

Any ideas?

Regex Match qustion

I want to match this pattern: [k1,v1][k2,v2]...

k1...kn cannont be empty while v1...vn can be.

[k,v] can apear more than 1 time.

I wrote this but it ain't work: ^(?=\[).+(?<!\]),.*(?<!\[)(?<=\])$

Export .NET DataTable to Microsoft Excel and Format Results

I want to set the row height with eporting my data to Excel. I tried the below, but am getting a debug error of

Unable To Cast object type of 'System.Web.UI.WebControls.DataGridItem' to type 'System.Web.UI.WebControls.GridViewRow'

And this is my syntax

public void ExportToExcel(DataTable dataTable)
{
  string filename = "Bamo.xls";
  StringWriter tw = new System.IO.StringWriter();
  HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
  DataGrid dgGrid = new DataGrid();
  dgGrid.DataSource = dataTable;
  dgGrid.DataBind();
  int j = 0;
  foreach(GridViewRow gvrow in dgGrid.Items)
  {
    if (j % 2 != 0)
    {
        for (int k = 0; k < gvrow.Cells.Count; k++)
        {
            gvrow.Cells[k].Style.Add("Height", "10");
        }
    }
    j++;
  }
}

Insert and Delete error Gridview ASP.NET

I am using SQL command to insert and delete into the grid but getting following errors while executing.

Error 1 Use of unassigned local variable 'cmd' (This is at INSERT INTO Table(ID,Summary) values ('" + Convert) Error 2 'System.DateTime' does not contain a definition for 'Text'
Error 3 'System.EventArgs' does not contain a definition for 'CommandName' and no extension method 'CommandName' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?)
Error 4 'System.EventArgs' does not contain a definition for 'CommandArgument' and no extension method 'CommandArgument' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?) Error 5 The name 'fillgrid' does not exist in the current context

The HTML part is correct . But I think I have not written the insert and delete function properly 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

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) values ('" +  
            convert.ToInt32(cmd.Parameters["label2"].Value.ToString())   
            + "'" + textbox1.Text  + "'"  DateTime.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();
        }
     }
 }

System.Timer missing from Xamarin PCL

I am building a Xamarin cross platform app targeting IOS Android and Windows Phone 8.1 using .Net 4.5.1. When I try to reference System.Timers in the PCL project, it is not there. How do I fix this?

enum ToString and performance

I was profiling some C# code and wound up investigating the implementation of ToString for enum values.

The ToString method ultimately calls System.Type.GetEnumName. Here's the relevant source code, taken from http://ift.tt/1NpwkVM

public virtual string GetEnumName(object value)
{
    if (value == null)
        throw new ArgumentNullException("value");

    if (!IsEnum)
        throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
    Contract.EndContractBlock();

    Type valueType = value.GetType();

    if (!(valueType.IsEnum || Type.IsIntegerType(valueType)))
        throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value");

    Array values = GetEnumRawConstantValues();
    int index = BinarySearch(values, value);

    if (index >= 0)
    {
        string[] names = GetEnumNames();
        return names[index];
    }

    return null;
}

// Returns the enum values as an object array.
private Array GetEnumRawConstantValues()
{
    string[] names;
    Array values;
    GetEnumData(out names, out values);
    return values;
}

// This will return enumValues and enumNames sorted by the values.
private void GetEnumData(out string[] enumNames, out Array enumValues)
{
    Contract.Ensures(Contract.ValueAtReturn<String[]>(out enumNames) != null);
    Contract.Ensures(Contract.ValueAtReturn<Array>(out enumValues) != null);

    FieldInfo[] flds = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

    object[] values = new object[flds.Length];
    string[] names = new string[flds.Length];

    for (int i = 0; i < flds.Length; i++)
    {
        names[i] = flds[i].Name;
        values[i] = flds[i].GetRawConstantValue();
    }

    // Insertion Sort these values in ascending order.
    // We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and
    // the common case performance will be faster than quick sorting this.
    IComparer comparer = Comparer.Default;
    for (int i = 1; i < values.Length; i++)
    {
        int j = i;
        string tempStr = names[i];
        object val = values[i];
        bool exchanged = false;

        // Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop.
        while (comparer.Compare(values[j - 1], val) > 0)
        {
            names[j] = names[j - 1];
            values[j] = values[j - 1];
            j--;
            exchanged = true;
            if (j == 0)
                break;
        }

        if (exchanged)
        {
            names[j] = tempStr;
            values[j] = val;
        }
    }

    enumNames = names;
    enumValues = values;
}


// Convert everything to ulong then perform a binary search.
private static int BinarySearch(Array array, object value)
{
    ulong[] ulArray = new ulong[array.Length];
    for (int i = 0; i < array.Length; ++i)
        ulArray[i] = Enum.ToUInt64(array.GetValue(i));

    ulong ulValue = Enum.ToUInt64(value);

    return Array.BinarySearch(ulArray, ulValue);
}

If I'm understanding this correctly, whenever an enum's name is requested:

  1. The entire set of enum values and names are inserted into arrays using insertion sort.
  2. The values are copied to an array of ulongs.
  3. This array is searched with binary search.

Am right to think that this is grossly inefficient? (especially for enums with hundreds or thousands of values)

It seems like some sort of dictionary/hashtable structure would be ideal. But even a simple O(n) linear scan of the values would have accomplished the same goal without sorting or binary searching or allocating superfluous arrays.

I was able to precompute a dictionary for one particular case where ToString was being called many times in a loop; and that yielded significant performance gains. But is there any built-in, alternative, more holistic technique that would also facilitate things like JSON serialization?

system.linq solves the exception Class cannot be indexed because it has no default property

here is my code

     Dim ContentSent As HashSet(Of String) = New HashSet(Of String)(SubscriberContent.ContentIdSent.Split(","))

    content = New Content
   '////////////here is the line that is causing this exception
    content = contentCollection.Find(Function(x) x.CntId = Convert.ToInt32(ContentSent(0)))

The weird thing is that when I import System.Linq the compilation error disappears.

any idea why ?

PowerShell crashes when using ref parameter in .NET event

PowerShell crashes when an .NET-event with a ref parameter I've subscribed to, is invoked.

I've reduced the problem to the following code.

.NET:

namespace PSEventTest
{
    public delegate void BadHandler(ref string str);

    public class PSEventTest
    {
        public event BadHandler BadEvent;

        public void InvokeBad()
        {
            var handler = BadEvent;
            if (handler != null)
            {
                var str = "bad";
                handler(ref str);
            }
        }
    }
}

PowerShell:

Add-Type -path $PSScriptRoot"\PSEventTest.dll"

$obj = New-Object PSEventTest.PSEventTest

$bad = Register-ObjectEvent -InputObject $obj -EventName BadEvent -Action {
    Write-Host "bad!" # it also crashes if this script-block is empty 
}

$obj.InvokeBad(); # crash

When i run the PowerShell script i get this:

enter image description here

If i press Debug i get this from Visual Studio:

enter image description here

The copy exception detail to the clipboard gives me this

System.NullReferenceException was unhandled
Message: An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module.
Additional information: Object reference not set to an instance of an object.

I guess i have to provide the string to the -Action script-block somehow, but i don't know how.

P.S. I'm using PowerShell 4:

PS C:\Windows\system32> $PSVersionTable.PSVersion
Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

Text to Decimal Converter Working but UI not getting updated

I wrote for string to decimal converter and it working fine, the binding is getting updated successfully, however, the GUI is not getting updated.

Example: If I enter "0500" it is getting converted to Decimal value but GUI is not getting updated to 500.

Also, convert back is getting control and not the convert in Iconvert.

My Convert Code:

Public Class DecimalConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, language As String) As Object Implements IValueConverter.Convert
        Dim result As Decimal = 0
        If Decimal.TryParse(value, result) Then
            Return result
        Else
            Return 0
        End If
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, language As String) As Object Implements IValueConverter.ConvertBack
        Dim result As Decimal = 0
        If Decimal.TryParse(value, result) Then
            Return result
        Else
            Return 0
        End If
    End Function
End Class

Could you please correct me or advice where I went wrong.

Xaml Code:

xmlns:cn="using:MCPhone81.MCCommonCodes.Converters"
    <Page.Resources>
        <cn:VisibilityConverter x:Name="VisConvert"/>
        <cn:DecimalConverter x:Name="DecConverter"/>
    </Page.Resources>

<TextBox Text="{Binding Obj.Amount, Mode=TwoWay, Converter={StaticResource DecConverter}}" Grid.Row="2" Grid.Column="0" MinWidth="220" InputScope="Number" />

How to prevent client get processes info of server

In C# , there is a method which can get the processes info on current machine as below:

Process[] myprocess = Process.GetProcesses();

But now I am working on how to prevent using this method on client side, if this method being invoked, the server will return "no permission".

This problem is due to the concern of webshell protection. yes, I can ban the upload or provide a series of identity authentication,etc, but I am considering even all the security lines being passed, the codes still cannot work.

Multiple Showdialog

I have a main window which calls another window with ShowDialog(), lets call it window A. Window A calls another window also with ShowDialog(), lets call it window B.

Whenever window B is closed using Close(), I want Window A to be shown, not the main window.

How am I supposed to do that? I already tried using this.Owner, this.Focus, etc. none of them work.

Note: I am using WPF

here is my code from main window:

WindowsA WA = new WindowsA(); WA.showDialog();

at WindowsA, i call another window WindowsB:

WindowsB WB = new WindowsB(); WB.showDialog();

from WindowsB, I pressed button to close:

Close();

Where should I put the owner?

Why when using ffmpeg to create in real time avi video file from images the avi file is only 5.55KB size?

This is my Ffmpeg class i did some time ago

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using DannyGeneral;

namespace Manager
{
    class Ffmpeg
    {
        NamedPipeServerStream p;
        String pipename = "mytestpipe";
        System.Diagnostics.Process process;
        string ffmpegFileName = "ffmpeg.exe";
        string workingDirectory;

        public Ffmpeg()
        {
            workingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
            Logger.Write("workingDirectory: " + workingDirectory);
            if (!Directory.Exists(workingDirectory))
            {
                Directory.CreateDirectory(workingDirectory);
            }
            ffmpegFileName = Path.Combine(workingDirectory, ffmpegFileName);
            Logger.Write("FfmpegFilename: " + ffmpegFileName);
        }

        public void Start(string pathFileName, int BitmapRate)
        {
            try
            {

                string outPath = pathFileName;
                p = new NamedPipeServerStream(pipename, PipeDirection.Out, 1, PipeTransmissionMode.Byte);

                ProcessStartInfo psi = new ProcessStartInfo();
                psi.WindowStyle = ProcessWindowStyle.Hidden;
                psi.UseShellExecute = false;
                psi.CreateNoWindow = false;
                psi.FileName = ffmpegFileName;
                psi.WorkingDirectory = workingDirectory;
                psi.Arguments = @"-f rawvideo -pix_fmt yuv420p -video_size 1920x1080 -i \\.\pipe\mytestpipe -map 0 -c:v mpeg4 -r " + BitmapRate + " " + outPath;
                process = Process.Start(psi);
                process.EnableRaisingEvents = false;
                psi.RedirectStandardError = true;
                p.WaitForConnection();
            }
            catch (Exception err)
            {
                Logger.Write("Exception Error: " + err.ToString());
            }
        }

        public void PushFrame(Bitmap bmp)
        {
            try
            {
                int length;
                // Lock the bitmap's bits.
                //bmp = new Bitmap(1920, 1080);
                Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                //Rectangle rect = new Rectangle(0, 0, 1280, 720);
                System.Drawing.Imaging.BitmapData bmpData =
                    bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    bmp.PixelFormat);

                int absStride = Math.Abs(bmpData.Stride);
                // Get the address of the first line.
                IntPtr ptr = bmpData.Scan0;

                // Declare an array to hold the bytes of the bitmap.
                //length = 3 * bmp.Width * bmp.Height;
                length = absStride * bmpData.Height;
                byte[] rgbValues = new byte[length];

                //Marshal.Copy(ptr, rgbValues, 0, length);
                int j = bmp.Height - 1;
                for (int i = 0; i < bmp.Height; i++)
                {
                    IntPtr pointer = new IntPtr(bmpData.Scan0.ToInt32() + (bmpData.Stride * j));
                    System.Runtime.InteropServices.Marshal.Copy(pointer, rgbValues, absStride * (bmp.Height - i - 1), absStride);
                    j--;
                }
                p.Write(rgbValues, 0, length);
                bmp.UnlockBits(bmpData);
            }
            catch(Exception err)
            {
                Logger.Write("Error: " + err.ToString());
            }

        }

        public void Close()
        {
            p.Close();
        }
    }
}

And i'm using it in form1 in a button click event:

private void button1_Click(object sender, EventArgs e)
        {
            Ffmpeg ffmpeg = new Ffmpeg();
            ffmpeg.Start(@"e:\screenshots\test.avi",25);
            timer1.Start();
        }

the directroy screenshots is where i'm taking a screenshot every 100ms in the timer1 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();
        }
    }

Something is wrong with the Ffmpeg class. In the end i see 1200 images on the hard disk and in same directory i see the video file test.avi but the test.avi size is only 5.55KB

Overwriting ASP.NET errors with IIS httpErrors, except for web services

I am looking at <httpErrors> and I can't figure out what existingResponse mode is correct for my goals.

I want to ensure all ASP.NET error pages are completely hidden from the client, so it is not possible to identify the site as ASP.NET. This means that PassThrough is not the right choice.

However I still want to preserve the error body when it's not aimed at users, e.g. in web service responses, so Replace isn't right either.

This leaves Auto, but the problem I face is that ASP.NET internally sets TrySkipIisCustomErrors = true if an error occurs (see HttpResponse.cs:1297) This includes any errors in handler for customErrors, which, as result, leak ASP.NET error pages -- no stack trace, but not a custom page either.

Is there a bulletproof solution that would replace all ASP.NET error responses with IIS responses by default, while still leaving space for manual override in certain cases? And by manual I mean "in my code only".

How to point the page to difference web.config in c# .net

Just wandering would it be possible for a page in c# .net point to the difference web.config? Example, I have 2 difference config files, one is web.config and the other one is web1.config. How can I point the page to web1.config in c# .net?

C# - Timer System For Game (Ex. Clash of Clans)

So I am new here on Stack Overflow and I looked around for the answer to my question but I didn't find what I was looking for (I did some looking around in Timers). I will try to explain it the best that I can.

I am trying to design, in C#, something similar to the way that games like Clash of Clans use timers when you build stuff. So I thought about it quite a bit but I am really stumped.

I am not really sure how to design this. Would I use the Timer class in the .Net Framework? If so, the API seems to confuse me a bit about how I can set up the timer and then set up a second timer if I am building two things at a time (in the example at least). Or perhaps there is better way than a timer...

To be as direct as possible I guess I am asking how can I design a system that takes time for things to happen after something like a button click?

I want to try to get a skeleton using a console app so I can keep things simple.

Thanks for any input you can give.

Ben

Timeout error when accessing WCF service remotely

When I access the WCF service locally it works. To do this I type into my browser: http://localhost:54123/MyService/GetValue

This shows my expected json formatted output. However, when accessing remotely using http://myIPAddress:54123/MyService/GetValue I get ERR_CONNECTION_TIMED_OUT in Chrome.

I have my inbound IP whitelisted for all TCP ports, so I am not sure why I would be unable to access remotely. This is being hosted on an amazon EC2 instance if that makes any difference.

Here is the code I have in my main() method for hosting the service via Topshelf

    const string serviceUri = "http://localhost:54123/MyService";
    var host = HostFactory.New(configurator =>
    {
        configurator.Service<WcfServiceWrapper<MyServiceClass, IMyServiceClass>>(serviceConfigurator =>
        {
            serviceConfigurator.ConstructUsing(x =>
                new WcfServiceWrapper<MyServiceClass, IMyServiceClass>("MyService", serviceUri));
            serviceConfigurator.WhenStarted(service => service.Start());
            serviceConfigurator.WhenStopped(service => service.Stop());
        });
        configurator.RunAsLocalSystem();

        configurator.SetDescription("Runs My Service.");
        configurator.SetDisplayName("MyService");
        configurator.SetServiceName("MyService");
    });

Here is the relevant code from my WcfWrapper start() method

var webHttpBinding = new WebHttpBinding(WebHttpSecurityMode.None);
    _serviceHost.AddServiceEndpoint(typeof(TServiceContract), webHttpBinding, _serviceUri);

    var webHttpBehavior = new WebHttpBehavior
    {
        DefaultOutgoingResponseFormat = WebMessageFormat.Json
    };
    _serviceHost.Description.Endpoints[0].Behaviors.Add(webHttpBehavior);

    _serviceHost.Open();
    openSucceeded = true;

Below is what I have in my config file

<configuration>
    <system.serviceModel>
        <services>
            <service name="MyServiceClassNS.MyServiceClass">
                <host>
                    <baseAddresses>
                        <add baseAddress="http://myIPAddress:54123/MyService"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="serviceBehavior">
                    <serviceMetadata httpGetEnabled="True"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Why a Panel blinks while removing it and its childs?

I have a form with a custom controls, UserControls. One of these controls is composed with other controls: TableLayoutPanel, PictureBox (it is inside of another UserControl), Label. Visually they are depicted in the following way:

Visual description

As we can see in the image, the red rectangle is a UserControl, the orange rectangles are TableLayoutPanel, the yellow and green chairs are other UserControl controls composed by a PictureBox and a Label.

The chairs (yellow and green ones) are draw dynamically. For example to draw the yellow chairs:

    private void DibujarSillasEconomicas()
    {
        Silla[] cheapChairs = m_avion.GetCheapChairs();
        Silla silla;
        byte fila_silla = 0;
        byte col_silla = 0;
        ControlVisualChair ctlSillaGrafica;

        for(int num_silla = 0; num_silla < cheapChairs.Length; ++num_silla)
        {
            silla = cheapChairs[num_silla];
            ctlSillaGrafica = new ControlSillaGrafica(silla);
            ctlSillaGrafica.Dock = DockStyle.Fill;
            ctlSillaGrafica.BackColor = Color.Black;

            if (num_silla > 0 & num_silla % 6 == 0)
            {
                ++fila_silla;
                col_silla = 0;
            }

            tplSillasEconomicas.Controls.Add(ctlSillaGrafica, col_silla == 3? ++col_silla : col_silla, fila_silla);

            ++col_silla;
        }
    }

These chairs and the yellow ones are drawn correctly. The problem appears when I want to register a passenger:

Adding a passenger

Note that when I add a passenger the controls blink. In code this what I do when I finish adding a passenger:

this.Controls.Remove(ctlAvion); // Removes the actual UserControl (red rectangle)
ctlAvion = new ControlAvion(m_avion); // Creates a new one
ctlAvion.Location = new Point(2, 13);
ctlAvion.Size = new Size(597, 475);
this.Controls.Add(ctlAvion); // Adds the new UserControl to the main controls (a Form).

How I can avoid this blink effect when?

I have tried the following UserControls methods:

ctlAvion.Invalidate();
ctlAvion.Update();
ctlAvion.Refresh();

but they does not work!

Thanks in advance for your help!

Totally new // Make an Android phone calling by ATCommand(?)

NET/C# DEV and I downloaded VS2013 + Xamarin.

I was asked to do a simple app.

Make whatever Android phone make a call from PC. I'm totally new, I don't know where to start.

What things Do I need to have or read in order to do even a small Demo App.

Why i'm getting out of memory exception when saving images even if disposing each time?

I have this class that save images screenshots of the desktop.

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

namespace Manager
{
    public class ScreenShot
    {

    #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

    #region Class Properties
    [Description("Gets the screenshot image")]
    public Bitmap ScreenImage
    {
        get { return _screenShot; }
    }
    #endregion

    #region Constructor

    [Description("Empty constructor, instantiating _screenShot to nothing")]
    public ScreenShot()
    {
        _screenShot = null;
    }              
    #endregion

    #region Methods

    [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

    public void GetScreenShot(string folder, string name)
    {
        _screenShot = new Bitmap(GetScreen());
        string ingName = folder + name + Elgato_Video_Capture.counter.ToString("D6") + ".bmp";
        _screenShot.Save(ingName);
        _screenShot.Dispose();
    }
    }

}

Using it in form1 with a timer:

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

And in 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();
        ScreenShotsPlayer ssp = new ScreenShotsPlayer();
        ssp.Show();
    }
}

The exception is in the new class on the bottom on the line:

_screenShot = new Bitmap(GetScreen());

And it happen all the time after saved image number screenshot000147.bmp

System.OutOfMemoryException occurred
  HResult=-2147024882
  Message=Out of memory.
  Source=System.Drawing
  StackTrace:
       at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
       at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
       at System.Drawing.Bitmap..ctor(Image original, Int32 width, Int32 height)
       at System.Drawing.Bitmap..ctor(Image original)
       at Youtube_Manager.ScreenShot.GetScreenShot(String folder, String name) in d:\C-Sharp\Manager\Manager\Manager\ScreenShot.cs:line 105
  InnerException: 

Line 105 is: _screenShot = new Bitmap(GetScreen());

I'm doing a dispose for the _screenShot variable after each save. Maybe the timer in form1 is too fast ? The timer interval set to 100ms.

winscp Error occurred during logging. It's been turned off

I am developing a solution that uses winscp to upload zip file (contains multiple pdf files) to the remote sftp server. I am keep getting "Error occurred during logging, it's been turned off". Could anyone please tell me how to fix this error.

According to this http://ift.tt/1NoA9cB , I have created the log file.

The following class is the one that I am using.

 public class PSftp
{
    public void PutFile(string localfile)
    {
        //Send Ftp Files - same idea as above - try...catch and try to repeat this code 
        //if you can't connect the first time, timeout after a certain number of tries. 
        var sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = ConfigurationManager.AppSettings["sFTPhost"],
            UserName = ConfigurationManager.AppSettings["sFTPuid"],
            Password = ConfigurationManager.AppSettings["sFTPpwd"],
            PortNumber = int.Parse(ConfigurationManager.AppSettings["sFTPport"]),
            SshHostKeyFingerprint = ConfigurationManager.AppSettings["sFTPhostkey"]

        };

        using (var session = new Session())
        {
            session.SessionLogPath = ConfigurationManager.AppSettings["sFTPlogPath"];
            session.DisableVersionCheck = false;
            session.DefaultConfiguration = false;
            session.Open(sessionOptions); //Attempts to connect to your sFtp site
            //Get Ftp File
            var transferOptions = new TransferOptions
            {
                TransferMode = TransferMode.Binary,
                FilePermissions = null,
                PreserveTimestamp = false
            };
            //<em style="font-size: 9pt;">Automatic, Binary, or Ascii  
            //null for default permissions.  Can set user, 
            //Group, or other Read/Write/Execute permissions. 
            //destination file to that of source file - basically change the timestamp 
            //to match destination and source files.   
            transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;


            //the parameter list is: local Path, Remote Path, Delete source file?, transfer Options  
            TransferOperationResult transferResult = session.PutFiles(localfile, ConfigurationManager.AppSettings["sFTPInboxPath"], false, transferOptions);
            //Throw on any error 
            transferResult.Check();
            //Log information and break out if necessary
        };

    }
}

  //How to use the above class
  public void SaveFiletoFtp(string source)
    {
        var pftp = new PSftp();
        pftp.PutFile(source);
    }

Consuming .Net Generated Web Service from ColdFusion

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

<soap:operation soapAction="http://ift.tt/1ImdfCC" style="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

Move asp.net application out of IIS

We have a VS 2012/.NET 4.51 app, uses MVC, asp.net, and a bunch of other pieces.

For all the usual reasons, we are finding IIS to be a deploy/ops nightmare (how much script are we expected to write to install/configure IIS? crazy!)

Actually, the app is two web sites: - REST API, based on WCF - Web site, based on MVC, ASP.NET, and several other pieces (a whole big .js/handlebars rich js app)

I looked at moving to Nancy, but that would appear to be a lot of work. (It is not clear to me that asp.net would be happy under nancy. But in all events, it does not look like a drop in.)

What are my alternatives? (IIS is the biggest mess of our whole deploy process. Apache or nginx would be cake.)

OWIN + Katana looks close, but from my understanding you cannot (yet?) run a full ASP.NET app in OWIN/Katana.

We have done some work with powershell DSC. It can solve a lot (and is really great... the IIS part is the biggest pain).

We do not use TFS (we are a Visual Studio + Perforce shop).

Is there magic in the next VS/.NET/Windows/IIS to address this?

Alternate perspective : Migrate ASP.NET app on .net 4.5 to ASP.NET v5 - docs? concepts?

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.

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.

The offending line, when opening the .csproj file, corresponds to the first line of the following section:

<Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
    <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
  </Target>

Any idea what could be causing this?

What I've Tried so Far:

  • Commented the section I thought was offending. No change.
  • Removed the section I thought was offending. No change.
  • Realized the line numbers probably refer to the targets file.
  • Tried completely removing / deleting and recreating the web application.
  • Tried creating a new Web Project from within Visual Studio 2013 and committing that. Still failed.
  • Submitted a bug report on this because it truly seems like it shouldn't be happening.

I can't think of any other leads or anything we're doing in a non-standard way.

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(Command Prompt) 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.

I tried this and got errors:

e:\screenshots>ffmpeg -f image2 -i screensh
deo.avi

Error message:

ffmpeg version N-73165-gf1e1730 Copyright (
  built with gcc 4.9.2 (GCC)
  configuration: --enable-gpl --enable-vers
isynth --enable-bzlib --enable-fontconfig -
le-iconv --enable-libass --enable-libbluray
enable-libdcadec --enable-libfreetype --ena
ibilbc --enable-libmodplug --enable-libmp3l
le-libopencore-amrwb --enable-libopenjpeg -
able-libschroedinger --enable-libsoxr --ena
ble-libtwolame --enable-libvidstab --enable
 --enable-libvorbis --enable-libvpx --enabl
e-libx264 --enable-libx265 --enable-libxavs
ble-decklink --enable-zlib
  libavutil      54. 27.100 / 54. 27.100
  libavcodec     56. 45.100 / 56. 45.100
  libavformat    56. 38.102 / 56. 38.102
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 18.100 /  5. 18.100
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  2.100 /  1.  2.100
  libpostproc    53.  3.100 / 53.  3.100
[bmp @ 0000000002f77ce0] bad magic number
    Last message repeated 3 times
[image2 @ 0000000002f76380] decoding for st
[image2 @ 0000000002f76380] Could not find
 bmp, none): unspecified size
Consider increasing the value for the 'anal
screenshot%06d.bmp: could not find codec pa
Input #0, image2, from 'screenshot%06d.bmp'
  Duration: 00:00:02.88, start: 0.000000, b
    Stream #0:0: Video: bmp, none, 25 fps,
Please use -b:a or -b:v, -b is ambiguous
Codec AVOption b (set bitrate (in bits/s))
vi) has not been used for any stream. The m
e (e.g. a video option with no video stream
some encoder which was not actually used fo
Output #0, avi, to 'video.avi':
Output file #0 does not contain any stream

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

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

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?