lundi 27 avril 2015

regular expressions with word boundaries fail in .NET Regex

I have a problem with regular expressions in .NET. We are trying to match special tokens in a text surrounded by the paragraph sign (§). For completeness those the corresponding regular expressions are surrounded by word boundaries (\b). The problem is that the regular expression surrounded by \b does not match words:

    static void Main(string[] args)
    {
        string data = "I would like to replace this §pattern§ with something interesting";
        string requiredResult = "I would like to replace this serious text with something interesting";

        Regex regSuccess = new Regex("§pattern§");
        Regex regFail = new Regex(@"\b§pattern§\b");

        var dataSuccess = regSuccess.Replace(data, "serious text");
        var dataFail = regFail.Replace(data, "serious text");

        Console.WriteLine("regSuccess match: {0}", dataSuccess == requiredResult);
        Console.WriteLine("regFail match: {0}", dataFail == requiredResult);
        Console.WriteLine("Press enter to continue");
        var line = Console.ReadLine();
    }

As you can see, dataFail == requiredResult returns false.

Power shell: create alias for path

Is it possible in Power Shell to create alias for path?

For example: I have to write all time

PS PS C:\Users\Jacek>cd C:\windows\microsoft.net\framework\v4.0.30319

I will happy if I could write

PS PS C:\Users\Jacek>cd dotNet4path

How do I fade a picturebox image to another on mousehover event?

How do I animate a picturebox to change from one image to another on a mouse hover event as a fade-in effect?

I would also like to create the animated picturebox as a class that would show up under my toolbox for ease-of-use.

Example of a button with what I want to make a picturebox do. Animated Button Example-MSDN

I wanted to understand the purpose of this code snippet

Can someone please explain the purpose of this C# code. It's a code snippet in a Windows based application. Is it counting the number of keypress? What is the purpose of 13 here?

Any help would be much appreciated

 private void num2_KeyPress(object sender, KeyPressEventArgs e)
    {
      if ((int) e.KeyChar != 13)
        return;
      this.Calculate();
    }

c# powerpoint interop how do I print horizontally?

The MSDN is making me crazy. I succeeded on printing four pages at a single page, but can't find the option to change it print horizontally. By default, it is printed vertically, not that good looking.

   public void test6()
    {
        try
        {
            Microsoft.Office.Interop.PowerPoint.Application varPPT = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Presentation varPre = varPPT.Presentations.Open(filePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

            varPre.PrintOptions.OutputType = Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputFourSlideHandouts;

            varPre.PrintOut();


        }
        catch (Exception varE)
        {
            MessageBox.Show("Error:\n" + varE.Message, "Error message");
        }
    }

Well, this is my code. It prints well vertically, but that's not good looking at all.

I thought

varPre.PrintOptions.HandoutOrder = Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst;

might do the job, but it doesn't seem to fit at all.

Does anyone knows the method or property for this?

Using DTO in Azure Mobile Service .NET throws target invocation exception

I use Azure Mobile Services .NET backend and we all know we have to use Entity Framework classes to map to the database creation/migration. So I need to use DTOs to serialize only the properties I want, computed properties etc. I'm following the Field Engineer example. But Automapper gave me so much pain although I did everything as supposed to.

I have checked couple of others blog and site, some use Automapper, others not, for example this one. I feel more comfortable not using Automapper and create DTOs on the fly with Select() as I was doing it before when implementing Web API.

I reverted TableController class to Post, use the EntityDomainManager and I left the GetAllPosts method to the following.

public class PostController : TableController<Post>
{
    private MobileServiceContext _context;

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        _context = new MobileServiceContext();
        DomainManager = new EntityDomainManager<Post>(_context, Request, Services);
    }

    //[ExpandProperty("User")]
    // GET tables/Post
    public IQueryable<PostDto> GetAllPost()
    {
        return Query().Include("User").Select(x => new PostDto());
    }
}

I get the following error.

{"message":"An error has occurred.","exceptionMessage":"Exception has been thrown by the target of an invocation.","exceptionType":"System.Reflection.TargetInvocationException","stackTrace":"   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)\r\n   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)\r\n   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)\r\n   at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults(IQueryable queryable, Int32 limit, Boolean& resultsLimited)\r\n   at System.Web.Http.OData.Query.ODataQueryOptions.ApplyTo(IQueryable query, ODataQuerySettings querySettings)\r\n   at System.Web.Http.OData.EnableQueryAttribute.ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)\r\n   at System.Web.Http.OData.EnableQueryAttribute.ExecuteQuery(Object response, HttpRequestMessage request, HttpActionDescriptor actionDescriptor)\r\n   at System.Web.Http.OData.EnableQueryAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","innerException":{"message":"An error has occurred.","exceptionMessage":"The specified type member 'DatePosted' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.","exceptionType":"System.NotSupportedException","stackTrace":"   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberAccessTranslator.TypedTranslate(ExpressionConverter parent, MemberExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.ThenByTranslatorBase.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.ThenByTranslatorBase.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()\r\n   at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()\r\n   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()\r\n   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()\r\n   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n   at System.Web.Http.OData.Query.TruncatedCollection`1..ctor(IQueryable`1 source, Int32 pageSize)\r\n   at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean& resultsLimited)"}}

If I just convert it to the Entity Framework class it works. You will notice that I don't fill any property, just for testing purposes.

I test locally with IIS Express.

Data objects and models.

    public class Post : EntityData
    {
        public DateTimeOffset DatePosted { get; set; }
        public string StatusText { get; set; }
        public PostType TypeOfPost { get; set; }

        [ForeignKey("Id")]
        public virtual User User { get; set; }

        [ForeignKey("Id")]
        public virtual ICollection<PostPhotoUrl> PhotoUrls { get; set; }
    }

    public class PostDto
    {
        public PostDto()
        {
            PhotoUrls = new HashSet<PostPhotoUrlDto>();    
        }

        public DateTimeOffset DatePosted { get; set; }
        public string StatusText { get; set; }
        public int TypeOfPost { get; set; }

        public UserDto User { get; set; }
        public ICollection<PostPhotoUrlDto> PhotoUrls { get; set; }
    }

Searching the internet couldn't find any other more clear tutorial how to use Azure Mobile Services and DTOs, though it shouldn't introduce such difficulty. If you have any resources are welcome.

I should mention that if I don't do the following the test website raises error when trying to test the endpoints.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

The exception snapshot:

JsonMediaTypeFormatter Error

I don't REALLY need to have DTOs for this project, but if I don't resolve what I don't understand right now it will come back and hunt me in the long run of this service.

Activemq list of queues nms .NET

How do I get list of queues and topics using ActiveMQ NMS ( .NET ). Getting the list in JAVA is simple. But what about .NET.

Thanks.

How to restrict the empty file upload control in asp.net

Using JQuery I am restricting the file extension but I am getting an issue is that "If I don't upload any video just I am clicking the upload button its not validating". This is my code, what editing I have to do?

Sample.aspx

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

 $(function () {
    $('#<%=FileUploadbtn.ClientID %>').change(
             function () {
                 var fileExtension = ['mp4'];
                 if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                     // alert("Invalid");
                     $('#<%=uploadbtn.ClientID %>').attr("disabled", true);
                     $('#<%= lblError.ClientID %>').html("Invalid");
                 }
                 else {
                     $('#<%=uploadbtn.ClientID %>').attr("disabled", false);
                     $('#<%= lblError.ClientID %>').html(" ");
                 }
             })
})

ASPX Code

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" CssClass="button" OnClick="uploadbtn_Click" />
<asp:Label ID="lblError" runat="server" Text="Label"></asp:Label>

Twitter Api Call fetch users timeline error 400 bad request error

i am using the following code to fetch tweets from user timeline .but in response it gives error bad request in all api calls that i am making

   public string query = "nouman_engineer";

     public string url = "http://ift.tt/1IdLU4E";


    public void findUserTwitter(string resource_url, string q)
{

    // oauth application keys
    var oauth_token = pass; //"insert here...";
    var oauth_token_secret = pass; //"insert here...";
    var oauth_consumer_key = "pass";
        var oauth_consumer_secret = "pass";

    // oauth implementation details
    var oauth_version = "1.1";
    var oauth_signature_method = "HMAC-SHA1";

    // unique request details
    var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    var timeSpan = DateTime.UtcNow
        - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

    var screen_name = "nouman_engineer";
    // create oauth signature
    var baseFormat = "count=1&exclude_replies=1&include_entities=false&include_rts=false&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}&trim_user=1";
    var baseString = string.Format(baseFormat,
                                oauth_consumer_key,
                                oauth_nonce,
                                oauth_signature_method,
                                oauth_timestamp,
                                oauth_token,
                                oauth_version,
                                 Uri.EscapeDataString(screen_name)
                                );


    baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));



    var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                            "&", Uri.EscapeDataString(oauth_token_secret));
    string oauth_signature;

    using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
    {
        oauth_signature = Convert.ToBase64String(
            hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
    }


    // create the request header
    var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                       "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                       "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                       "oauth_version=\"{6}\"";

    var authHeader = string.Format(headerFormat,
                            Uri.EscapeDataString(oauth_nonce),
                            Uri.EscapeDataString(oauth_signature_method),
                            Uri.EscapeDataString(oauth_timestamp),
                            Uri.EscapeDataString(oauth_consumer_key),
                            Uri.EscapeDataString(oauth_token),
                            Uri.EscapeDataString(oauth_signature),
                            Uri.EscapeDataString(oauth_version)
                    );



    ServicePointManager.Expect100Continue = false;

    // make the request
    var postBody = "q=" + Uri.EscapeDataString(q);//
    resource_url += "?" + postBody ;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
    request.Headers.Add("Authorization", authHeader);
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";

ERROR HERE The remote server returned an error: (400) Bad Request.

            var response = (HttpWebResponse)request.GetResponse();

///////IN CASE OF RESPONSE

          var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd();
          myDiv.InnerHtml = objText;/**/
    string html = "";
    try
    {
        JArray jsonDat = JArray.Parse(objText);
        for (int x = 0; x < jsonDat.Count; x++)
        {
            //html += jsonDat[x]["id"].ToString() + "<br/>";
            html += jsonDat[x]["text"].ToString() + "<br/>";
           // html += jsonDat[x]["name"].ToString() + "<br/>";
            html += jsonDat[x]["created_at"].ToString() + "<br/>";

        }
        myDiv.InnerHtml = html;
    }
    catch (Exception twit_error)
    {
        myDiv.InnerHtml = html + twit_error.ToString();
    }

WHAT SHOULD I DO KINDLY GUIDE ME

How can I check is valid lcid without try\catch block?

Some types has the TryParse method, for example it is Int32, Int64, Boolean, etc. It allows check the string value without try\catch block. It very much influences on productivity when many incorrect values are processing in a cycle. I need to do the same for string value of the LCID. But the CultureInfo class has not the TryParse method.

CultureInfo culture = null;
try {
  culture = CultureInfo.GetCultureInfo(Convert.ToInt32(lcid, 16));
}
catch {
}

How can I rewrite this code?

Can we capture a mobile number through a website?

When my website is visited from a mobile phone, I would like to to capture the mobile number, using php or a .net web application(C#).

How can I do that?

dimanche 26 avril 2015

How define a WebApi route to access method

I'd like have access to a method other than "GET", "PUSH", "PATCH", ....

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Employee",
            routeTemplate: "api/employee/{employeeid}",
            defaults: new { controller = "employee", employeeid = RouteParameter.Optional }
        );
    }
}

I have access to the employee controller :

    [RoutePrefix("api/employee")]
    public class EmployeeController : ApiController
    {
        public HttpResponseMessage Get() { }
        public HttpResponseMessage Get(int employeeid) {}
        public HttpResponseMessage Post([FromBody] EmployeeModel model){}

        [HttpPut]
        [HttpPatch]
        public HttpResponseMessage Patch([FromBody] EmployeeModel model){}

        [Route("create")]
        public HttpResponseMessage Create() {}
    }

That's work I have access to the method

http://localhost/employee
http://localhost/employee/1

I'd like have access to the "Create" method :

http://localhost/employee/create

I tried to add another route but without success.

What can I do to have access to "Create" method and of course without any impact when I call the other methods.

Thanks,

Client Size of the Form doubles after minimizing and maximizing

I have a Mdi Container form which can hold multiple Child forms inside it. Now Each Child Form has a panel added to it so that it can in turn contain multiple User controls inside it. I have a weird issue when i minimize and maximize a child form , the client area of the Child form is doubling. I have AutoSize = false and AutoScroll = true.

Any help on this issue is appreciated.

JsonConvert.DeserializeObject to datatable automatically round the values

 public DataTable DerializeDataTable()
{
    const string json = @"[{""Name"":""AAA"",""Value"":""22.5"",""Job"":""PPP""},"
                       + @"{""Name"":""BBB"",""Value"":""25.3"",""Job"":""QQQ""},"
                       + @"{""Name"":""CCC"",""Value"":""38.9"",""Job"":""RRR""}]";
    var table = JsonConvert.DeserializeObject<DataTable>(json);
    return table;
}

here after converting to tables the values are coming as 23,25 and 39.

can someone help me please?

How to call a microservice in .NET

I've created a very simple REST microservice that receives information about an email and sends it. The microservice send method looks something like this:

//EmailController
[HttpPost]
public IHttpActionResult Send(Email email)
{
    // send email via exchange
}

Now in my application, I call it using RestSharp like this:

var client = new RestClient("http://localhost:51467/api/");
var request = new RestRequest("email/send", Method.POST);
request.RequestFormat = DataFormat.Json;
dynamic obj = new ExpandoObject();
obj.FromAddress = from;
obj.ToAddress = to;
obj.Subject = subject;
obj.Body = body;

request.AddBody(obj);
client.Execute(request);

Questions I have:

  1. Is this the best way to do the call? Obviously i'll later have to add error handling etc, but I'm talking more the way I'm using RestSharp to do the call.

  2. I'm finding it a bit uncomfortable that my app needs to kind of know what object the microservice expects to receive - there's no sort of definition/interface/contract that it uses to know for sure. Is this generally accepted as being ok for REST or should I implement some sort of interface that my app has so it can call my microservice in a bit more of a defined way. Is that even something possible with REST?

Thanks for any help!

Unable to send mail through Gmail

I am trying to send mails using Gmail in my code. It gives me error.

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. "

 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com",587);

            //smtp.Credentials = new NetworkCredential("manishchourasia2000@gmail.com", "justdoit");
            System.Net.NetworkCredential nc = new NetworkCredential("manishchourasia2000@gmail.com", "justdoit", "smtp.gmail.com"); //smtp.Credentials.GetCredential("smtp.gmail.com", 995, "");
            smtp.EnableSsl = true;

            smtp.UseDefaultCredentials = false;

            smtp.Credentials = nc;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            MailMessage mm = new MailMessage("manishchourasia2000@gmail.com", "manish.chourasia@inecomworld.com", "Gmail Testing", "Gmail Testing");
            smtp.Send(mm);

I tried many possibilities but nothing work.

Drag button of DataTemplate and drag whole DataTemplate

    <ListBox x:Name="SelectedItemListBox"  AllowDrop="True"  >
        <ListBox.ItemTemplate>
            <DataTemplate >
                <StackPanel Orientation="Horizontal">
                    <Button Width="22" Height="22" PreviewMouseMove="OnSelectedItemListBoxPreviewMouseLeftButtonDown" Drop="OnSlectedItemDrop"/>
                    <view:SelectedItemView x:Name="SelectedItemView2"   Margin="0,5,0,5" />
                </StackPanel>                                                       
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

so,the single ListBoxItem of ListBox should contain a button and a SelectedItemView. I just want to drag the button of ListBoxItem to drag whole single ListBoxItem( ). It is a qustion.

private void OnSelectedItemListBoxPreviewMouseLeftButtonDown(object sender, MouseEventArgs e)
    {
        if (sender is Button)
        {
            ListBoxItem draggedItem = sender as ListBoxItem;
            draggedItem.IsSelected = true;  
            SelectedItemViewModel viewmodel = draggedItem.DataContext as SelectedItemViewModel;
            DataObject dataObject = new DataObject(viewmodel);
            DragDrop.DoDragDrop(SelectedItemListBox, dataObject, DragDropEffects.Move);             
        }
    }

unfortunately,the draggedItem is null. I can't get the ListBoxItem object. Thank in advanced.

Can't create instance of object like normal

I am trying to access information from a API trading position by going

Position position = new Position();
int positionQuantity = position.Net;
Console.WriteLine("position amount is: " + positionQuantity);

However, it is giving me a red line under new Position();

and saying the T4.API.Position has no default constructors defined.

but then if I go

Position position = default(Position); 
int positionQuantity = position.Net;
Console.WriteLine("position amount is: " + positionQuantity);

"object reference not set to an instance of an object"

So it is wanting me to use the "new" keyword but I can't because it says it does not have a default constructor

I opened up their Position class and it does have a bunch of delegates should I use one of those?

did they take out the default constructor for some reason?

how can i send notification SNS AWS with c# to IOS

I need to send notification (SNS) AWS with .net c#. I saw this post below, but this is about send e-mail and I need to do with SNS. can anybody help me ? I'm newbie in AWS.

Amazon Simple Notification Service AWSSDK C# - S.O.S

Mono C# compiler response file syntax

I have a basic foundation in C#, having used it briefly at a previous job. Right now I'm working on really understanding the language and its paradigms by going through Pro C# 5.0 and the .NET 4.5 Framework. However, my main computing environment is a GNU/Linux system so I'm doing this using Mono.

That said I'm running into a problem using the mono C# compiler (mcs) to run a build using a response file (.rsp). Where can I find documentation about how mono parses these files and the syntax it expects?

Mostly I've run into not knowing how to specify a comment (the # symbol which is a comment under the Microsoft implementation seems to be interpreted as a file by mcs), and not knowing how to specify the options themselves.

# TestApp.rsp
-r:System.Windows.Forms.dll
-target:exe -out:TestApp.exe *.cs

When compiled:

$ mcs @TestApp.rsp
error CS2001: Source file `#' could not be found
TestApp.rsp(2,0): error CS1024: Wrong preprocessor directive
TestApp.rsp(2,0): error CS1525: Unexpected symbol `-'
Compilation failed: 3 error(s), 0 warnings

Can't add skin control

I'm new in using skin in .NET, I can't get any Skin-Control to work, when I add it keep falling down to the box under the form design like this.

http://ift.tt/1EapTRo

(I'm new so can't post image, sorry)

Preferred method for declaring properties in C# [duplicate]

This question already has an answer here:

I have seen property declarations in C# that follow both of the following patterns.

class MyClass
{
    public string MyString { get; set; }
}

class MyOtherClass
{
    public string MyString;
}

Is there a reason for using the first style over the second? Are there any differences between the two?

TPL Dataflow LinkTo only if no others match

I know the following works:

var forwarder = new BufferBlock<SomeType>();
forwarder.LinkTo(target1, item => matchesTarget1(item));
forwarder.LinkTo(target2, item => matchesTarget2(item));
forwarder.LinkTo(DataflowBlock.NullTarget<SomeType>());

The problem is I will be linking and unlinking items continuously at runtime. Will dataflow choose from most specific to least specific or will it go in the order things were linked in when trying to offer messages? I would like to make sure my NullTarget only swallows the message if nothing else can take it at the time, given predicate linking and unlinking will be happening continuously.

Stock trading with c# questions [on hold]

I'm tossing around the idea of writing a stock trading software in my spare time just for poops and hahas. I've got a program already in C# that will scrape the HTML for the current price (currently from google, but can be modified easily). I know it's much better to grab straight from a feed, but parsing HTML is a good start at least. My current question is is there a preferred way to buy/sell without a transaction fee? I'm sure I could use a site like E-Trade, but at $7 a transaction, that essentially punishes diversity and reduces, or eliminates, any profit. Is there a feed of some sort that I can use to buy/sell without any transaction fees?

C# check remote udp socket

I'm trying to create UDP port checker based on question How to test a remote UDP Port however when connected for example to www.google.com on port range 1-100 I receive for each exception "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond". Bellow is code I use.

try
        {
            UdpClient udpCLient = new UdpClient(Port);

            Socket uSocket = udpCLient.Client;

            uSocket.ReceiveTimeout = 5000;

            uSocket.Connect(Adress, Port);
            udpCLient.Connect(Adress, Port);

            IPEndPoint RemoteIpEndPoint = new IPEndPoint(Adress, Port);

            Byte[] sendBytes = Encoding.ASCII.GetBytes("?");


            udpCLient.Send(sendBytes, sendBytes.Length);

            Byte[] receiveBytes = udpCLient.Receive(ref RemoteIpEndPoint);


        }
        catch (SocketException e){

             if (e.ErrorCode == 10054)
            {

                return false;

             }
             else
             return false;
             }
 return true;

allowing a user to define a table at runtime using entity framework

is it possible to dynamically build entities in entity framework 6 using code first?

is it also possible to add properties to those entities at runtime?

Can those entities reference each other using foreign keys?

If someone could point me in the right direction if this is possible, i would really appreicate it.

EDIT

i have changed the title to reflect more of what i would like, so u can see why i asked the questions i asked.

Basically i would like to create a system where a user can define the objects(tables) they want, with the properties on that object (columns in table) as well as the references to each object (relationships between tables).

Now each object would have an Id property/column. i was thinking of atoring these definitions in an eav like table structure but i have other ibjects that are defined at design time and i like to use linq queries on these objects. I would also like to be able to build linq queries on these objects as users will want to report on this data. Building the linq queries should be fine as could use dynamic linq for this (Maybe)?

Currently to create such a system i have created a table that has many text fields, many number fields, many relationship fields and users can use which ones they want. But this is just 1 table and i think this is going to bite me in the bottom in the end, thus why i would like to take it to the next level and build separate tables for each object.

if anyone knows of a better way or maybe experienced something similar, glad to hear opinions.

Measuring relational inheritance distance between types

Does anyone know how I could (or if there is an existing algorithm) measure the relational distance between two .NET types?

By this I mean the number of 'steps' in the hierarchical tree that is required to get from object A to object B.

For example, if object A is a Button, and object B is a LinkButton, there would be 2 steps, Button -> WebControl -> LinkButton. Would I need to create my own static inheritance tree and use a path finding algorithm, or is there a way I can dynamically look at the inheritance structure of .NET to calculate the distance between two objects?

How to arrange controls side-by-side without using TableLayoutPanel?

I have been using TableLayoutPanel for arranging controls. Recently I discovered that TableLayoutPanel does not support visual inheritance. I am now in the process of removing TableLayoutPanel from my project. However, I do not understand how to arrange controls side-by-side. So far, what I see is that I can set the Dock property of controls to either 'Top' or 'Bottom' and they will stack on top of each other in the order they are added to the Form.Controls collection. The problem with this is that I would like to have the controls side-by-side (horizontally) instead of being on top of each other (vertically). Note that I want to use the Dock property so that controls resize automatically when the Form is resized by the user. I do not want static controls that cannot resize.

I do want a solution that supports visual inheritance. There are a number of controls that do not support this, as explained here: http://ift.tt/1GxGqCE

mongodb gridfs in C# new api

i am new with MongoDB, and i can't find GridFS. Where can i get GridFS to store files now ?

I can get it this way:

mongoClient = new MongoClient(Settings.Default.MongoDB);
var server = mongoClient.GetServer();
MongoDatabase = server.GetDatabase(Settings.Default.DatabaseName);
MongoDatabase.GridFS...

but GetServer() method is obsolete.

if I get database as here:

MongoDatabase2 = mongoClient.GetDatabase(Settings.Default.DatabaseName);
MongoDatabase2.GridFS... not working

Then i receive IMongoDatabase instead MongoDatabase, and i didnt have GridFS.

Problems With My Custom Installer

I created a custom installer a bit ago and it works fine but I am having a few issues with it.

Unlike a package installer it is slower at installing and at times the users get error codes with the installer not extracting the files or somewhat related.

This is how the installer works:

  • It deletes all the temporary files on the computer in case the installer was previously installed
    • Then the installers moves a .zip file to the users computer from the resources folder
    • After which it extracts the .zip
    • Then it moves the files it extracted to the correct director(y)(ies)
    • ...and finally it just deletes the .zip and the extracted folder off the computer

I have used installers before their job in around 5 - 7 seconds.

They move the same files as mine, but my installer that was custom made by me does the same exact job in around 40 seconds or so. On my computer... For the users, it could last for up to 3 - 4 minutes.

Those installers do the same thing as mine (could be a different procedure)

...So I was thinking, how do they do that? Maybe there is a way for me to avoid moving the .zip and unpacking it.

Is there a way I could possibly place the already extracted folder into my Resources folder and move it to the computer.

Or maybe add the folder to my Solution explorer and install the files and folders from there.

Also... Without usage of .zips or any extracting tools.

  • There might be other solutions to my problem that I am not aware of. Please help me!

new form dissapear after creation

i'm facing a problem with form show. I have a main form where i have my GUI and i choose an option that creates an instance of a form. For example in my main form i have: Form2 f2 = new Form2(); f2.Show();

The problem is that the form shows for about 1-2 secs and then goes behind the main form. I tried some instructions in the main form below f2.Show() command like

f2.BringtoFront();
this.SendtoBack();

Also i added commands to the new form(Form2) load method:

this.BringtoFront();
this.Activate();
this.Focus();

Nothing of the above commands seems to be a solution for this. Only when I use f2.ShowDialog(); instruction in my main form but i dont want to do that because i need immediate access to both of these forms at the same time.

Any help? thanks

I have C# 5.0 and .NET 4.5. Why can't I find CallerMemberName?

In Visual Studio, it can't find Caller Member, even though I have the correct versions. What should I do to fix this?

using System.Runtime.CompilerServices; 

public static void Bug([CallerMemberName] string callingFunction = null)
    if (callingFunction != null)
        Debug.Log("Calling function name is " + callingFunction);
    else
        Debug.Log("Calling function not supplied.");
    }

Track down UI error

Please get me started on tracking down this error
Problem is that I bind to a lot of FieldValue and clearly not all are failing or I would be getting a lot more of these errors

Convert 
System.Windows.Data Warning: 56 : Created BindingExpression (hash=44291519) for Binding (hash=2717082)
System.Windows.Data Warning: 58 :   Path: 'FieldValue'
System.Windows.Data Warning: 56 : Created BindingExpression (hash=4012957) for Binding (hash=2717082)
System.Windows.Data Warning: 58 :   Path: 'FieldValue'
System.Windows.Data Warning: 62 : BindingExpression (hash=4012957): Attach to System.Windows.Controls.TextBox.Text (hash=30313526)
System.Windows.Data Warning: 67 : BindingExpression (hash=4012957): Resolving source 
System.Windows.Data Warning: 70 : BindingExpression (hash=4012957): Found data context element: TextBox (hash=30313526) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=4012957): Activate with root item DocFieldDecimalSV (hash=12144638)
System.Windows.Data Warning: 107 : BindingExpression (hash=4012957):   At level 0 using cached accessor for DocFieldDecimalSV.FieldValue: RuntimePropertyInfo(FieldValue)
System.Windows.Data Warning: 104 : BindingExpression (hash=4012957): Replace item at level 0 with DocFieldDecimalSV (hash=12144638), using accessor RuntimePropertyInfo(FieldValue)
System.Windows.Data Warning: 101 : BindingExpression (hash=4012957): GetValue at level 0 from DocFieldDecimalSV (hash=12144638) using RuntimePropertyInfo(FieldValue): <null>
System.Windows.Data Warning: 80 : BindingExpression (hash=4012957): TransferValue - got raw value <null>
System.Windows.Data Warning: 82 : BindingExpression (hash=4012957): TransferValue - user's converter produced ''
System.Windows.Data Warning: 89 : BindingExpression (hash=4012957): TransferValue - using final value ''

copy values from enums in different namespaces

I have two object MyObj and MyObjDTO both have same property StarRating of type enum.

public class MyObj
{
    public enum StarRating {
         One = 1,
         Two = 2
    }
}

public class MyObjDTO
{
    public enum StarRating {
         One = 1,
         Two = 2
    }
}

I want to assign value from MyObj to MyObjDTO. I tried

var dto = ... loaded dto object

var data = new MyObj
            {
                ...
                RatingStatus = (int)dto.RatingStatus
            };

But It doesnt work, I'm getting underlined error under int and simple

 RatingStatus = dto.RatingStatus

doesnt work either.

Setting pins of RS232 using SerialPort .NET without overhead

I want to set DTS and RTS pins to true/false in .NET using SerialPort-Class.

When setting pins to true/false and sniffing COM-Port there are alot of other things send to the COM-Port that I don't want.

Sniff-Log: http://ift.tt/1JtqQsF

Code:

SerialPort serialPort = portSelector.SelectedPort;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
serialPort.ReadTimeout = 10;
serialPort.WriteTimeout = 10;
serialPort.BaudRate = 5;
serialPort.Handshake = Handshake.None;

serialPort.Open();
serialPort.DiscardInBuffer();
serialPort.DiscardOutBuffer();
serialPort.DtrEnable = false;

If I do the same thing in C it works and is not sending any garbage I don't want. Can you tell me what I'm doing wrong?

Thank you

Object instance valid only for the current method

Is it possible to create an object that can register whether the current thread leaves the method where it was created, or to check whether this has happened when a method on the instance gets called?

ScopeValid obj;

void Method1()
{
    obj = new ScopeValid();
    obj.Something();
}

void Method2()
{
    Method1();
    obj.Something(); //Exception
}

Can this technique be accomplished? I would like to develop a mechanism similar to TypedReference and ArgIterator, which can't "escape" the current method. These types are handled specially by the compiler, so I can't mimic this behavior exactly, but I hope it is possible to create at least a similar rule with the same results - disallow accessing the object if it has escaped the method where it was created.

Note that I can't use StackFrame and compare methods, because the object might escape and return to the same method.

Authorize user by google account in desktop application without webauthorizationBroker

Google has new api Google.Apis.

I have desktop application which authorize user by google account. Old API stop working.

How can I authorize user by new API, but WITHOUT webauthorizationBroker in C#? I do not want open webbroswer, I have own win form for enter login and password.

Network Stream specify Events

I am trying to send messages over sockets between a .Net client and a Node server using TCPClient and Socket.IO. The problem I am running into is that I can't find how to specify events I am sending or receiving on the .net side. I can only use the data event on the server.

Is there a way to do this? If not what would it be in bad taste to just send the message over a different socket?

Assert verify that mocked object receives expected exception

If I'm getting expected NotImplementedException on my mock object how can I assert verify that behavior is expected.

[Test]
hotelServiceMock
                .Setup(x => x.Create(It.IsAny<HotelToCreateDTO>(), true))
                .Throws<NotImplementedException>();  
...
Assert.Verify ...

Display map with Osm in Side server

i want to create a wab application that display a map using OSM, and i want all the treatment to be side server so, is there any possibility to do that and can use it with C# ????

thank you.

Parse.com Facebook Login .NET WPF not working

I'm trying to implement facebook authentication in a Parse.com enabled .NET desktop application. I've followed the instuctions in the parse .NET documentation but unfortunatelly I keep getting a "Invalid App ID: id" in the WebBrowser control required by the authentication process.

The Facebook app id and secret have been added to my parse app settings. The facebook app has been made "available to the public", "Native/Desktop" app is enabled and the http://ift.tt/1Ot3CpP call also seems to have a valid response.

enter image description here

The C# code is quite straightforward:

ParseClient.Initialize("myappid", "mydotnetkey");
ParseFacebookUtils.Initialize("627062910726940"); //

public async Task<bool> LogInOrRegisterAsync()
    {
        try
        {
            await ParseFacebookUtils.LogInAsync(WebBrowser, _facebookPermissions);
            return true;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return false;
        }
    }

Use related entity multiple times in query

I'm trying to get a list of two tables into one list of a generic class I made.

My question is how I could get the fields from the related table without calling firstOrDefault for each field, please see sample code, I need a verly long line for fields Price and Cost, and I have a few more to do...

    Dim items As IQueryable(Of ItemMain)


    Return items.Where(Function(i) i.Status > -1).Select(Function(x) New ItemViewBasic() With {.ItemID = x.ItemID,
                                                                      .Name = x.Name,
                                                                      .BarcodeNumber = x.BarcodeNumber,
                                                                      .Price = x.ItemStores.Where(Function(itemStore) itemStore.StoreNo = GlobalValues.StoreID).FirstOrDefault().Price,
                                                                      .Cost = x.ItemStores.Where(Function(itemStore) itemStore.StoreNo = GlobalValues.StoreID).FirstOrDefault().Cost})

Why the variable in the library class project value is changing but in the windows application project the variable value is all the time 0 ?

I have a solution with two projects.

The first one is class library the second one is windows forms application.

I added a variable to the class library project class, i will not add here all the class code since it's long.

namespace Capture.Hook
{
    public class DXHookD3D9: BaseDXHook
    {
        public DXHookD3D9(CaptureInterface ssInterface)
            : base(ssInterface)
        {
        }

        LocalHook Direct3DDevice_EndSceneHook = null;
        LocalHook Direct3DDevice_ResetHook = null;
        LocalHook Direct3DDevice_PresentHook = null;
        LocalHook Direct3DDeviceEx_PresentExHook = null;
        object _lockRenderTarget = new object();
        Surface _renderTarget;
        public static int framespersecondtodisplay = 0;

        protected override string HookName
        {
            get
            {
                return "DXHookD3D9";
            }
        }

The variable i added is: framespersecondtodisplay.

And i'm using the variable in this DXHooKD3D9 class in this place:

if (this.FPS.GetFPS() >= 1)
                        {
                            font.DrawText(null, String.Format("{0:N0} fps", this.FPS.GetFPS()), 5, 5, SharpDX.Color.Red);
                        }

                        if (this.TextDisplay != null && this.TextDisplay.Display)
                        {
                            font.DrawText(null, this.TextDisplay.Text, 5, 25, new SharpDX.ColorBGRA(255, 0, 0, (byte)Math.Round((Math.Abs(1.0f - TextDisplay.Remaining) * 255f))));
                            framespersecondtodisplay = (byte)Math.Round((Math.Abs(1.0f - TextDisplay.Remaining) * 255f));
                        }

Then in the form1 of the windows forms application project i'm using the variable like this:

txtDebugLog.Invoke(new MethodInvoker(delegate()
                {
                    fps.Frame();
                    ggg = fps.GetFPS();
                    string s = ggg.ToString("R");
                    txtDebugLog.Text = String.Format("{0:00.0}\r\n{1}", ggg.ToString("N14"), txtDebugLog.Text);
                    txtDebugLog.Text = String.Format("{0}\r\n{1}", DXHookD3D9.framespersecondtodisplay.ToString(), txtDebugLog.Text);

                })               
            );

txtDebugLog is a TextBox

Then what i'm doing is running the windows forms application project and then in the visual studio menu make Debug > Attach to Process and added two breakpoints one in the DXHooKD3D9 class in the library class project on this line:

framespersecondtodisplay = (byte)Math.Round((Math.Abs(1.0f - TextDisplay.Remaining) * 255f));

It stop on this line first and i make F5 continue and i see a value in this variable for example framespersecontodisplay is now with the value 24

I make continue then it stop in the form1 breakpoint on the line:

txtDebugLog.Text = String.Format("{0}\r\n{1}", DXHookD3D9.framespersecondtodisplay.ToString(), txtDebugLog.Text);

But here the value of framespersecondtodisplay is all the time 0.

If the breakpoint first stop in the DXHooKD3D9 class and the value there is 24 or 48 or 244 or 100 why in form1 it's all the time 0 ? Why it's not passing the current value as it is in the DXHooKD3D9 ?

Since it didn't work i tried to change in the library class project the variable to this:

public static byte framespersecondtodisplay = 0;

But still in form1 the variable show 0 all the time. I also tried to change it from static only to public:

public byte framespersecondtodisplay = 0;

And then in form1 to create instance for the DXHookD3D9:

CaptureInterface ci;
DXHookD3D9 dxd9;

In constructor:

ci = new CaptureInterface();
dxd9 = new DXHookD3D9(ci);

Then:

txtDebugLog.Text = String.Format("{0}\r\n{1}", dxd9.framespersecondtodisplay, txtDebugLog.Text);

But framespersecondtodisplay still showing 0 all the time.

Query datatable using linq to get count order by

I have a DataTable something like shown below. i need to query it using linq

Something like this Query in linq

select B, Count(C)
from DataTable
group by B

'Assembly uses xxx which has a higher version' vs 'Could not load file or assembly'

I have a .NET application that has a number of references. Many of those references have their own dependencies.

In other words, there is an application A that depends on application B, which, in turns, references assembly C. There is also a dependency on D that relies on E.

So, if I want to use a different version of C. I just reference that different version in my .csproj of A. I obviously get a runtime exception of Could not load file or assembly... The located assembly's manifest definition does not match the assembly reference. I easily solve that problem by using BindingRedirect.

However, if I'm trying to use a different version of E, I instead get a compilation error saying that 'Assembly uses xxx which has a higher version of yyy. And that compilation error cannot be solved by the runtime directive bindingRedirect.

Both 'B' and 'D' are strongly named assemblies. And there are no noticable differences between the way they are built.

Why in one case I receive a runtime exception (solvable by bindingRedirect) and a compilation error in another?

Free .NET decompiler that allows variable renaming [on hold]

I would have wanted to avoid asking a newbie question like this one on StackOverflow, but I'm having some problems in finding a (free) .NET decompiler that allows me to rename variables and methods. I'm currently doing some reverse engineering of malware, more specifically ransomware, and I need to understand how they work.

I came across the discussion .net decompiler that allows renaming fields, and I'm trying ILSpy and Reflexil, but I'm not able to rename variables, only methods. Is there any way?

Thanks in advance to anyone :)

IL .Net: How to provide step over, step through debugger support for GOSUB

I've implemented a .Net version of a legacy Basic language using IL assembler. It's working just fine. However, there's an issue of how to provide a better debugging experience for the implementation of GOSUB statement in Visual Studio IDE. The GOSUB statement, common in Basic languages, is implemented as a branch into a section of code and a branch back. The issue is that both step into (F10) and step over (F11) behave the same -- both go into the GOSUB section. What is desired is that F10 step over the GOSUB statement while F11 goes in (current behavior).

What can I do to implement step over when user hits F10? Is there some attribute that I can take advantage of?

expecting returned exception from mock object method

Inside my test I'm having mock object which should test expected NotImplementedException thrown from MyService.Create method

I'm struggle in this part

var hotelServiceMock = new Mock<HotelService>();
    hotelServiceMock.Setup(x=>x.Create(It.IsAny<HotelToCreateDTO>(), true))
                    .Throws(() => NotImplementedException());

I was think to use Returns instead of thrown (seen somewhere on net for some expected value, not exception) but on intellisense I'm getting only enter image description here

Change name and move file in C#

private void btn_add_image_Click(object sender, EventArgs e)
    {
        openFileDialog1.Title = "Choose a file";
        openFileDialog1.InitialDirectory = "C:\\";
        openFileDialog1.Filter = "  JPEG Files (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg|All Files (*.*)|*.*";
        openFileDialog1.ShowDialog();
        string file_name = openFileDialog1.FileName;
        string filename2 = openFileDialog1.SafeFileName;
        pictureBox1.Image = Image.FromFile(file_name);
    }


    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            pictureBox1.Image.Dispose();
            pictureBox1.Image = null;
            string[] extension = getExtension("images\\" + userid);
            if (File.Exists("images\\" + userid + extension[0]))
            {   
                File.Delete("resimler\\" + userid + extension[0]);
            }

        }
        catch (Exception)
        {
            MessageBox.Show("İmage cannot find");
        }

I want to Change File name and save , so i wrote this code if file exists , than delete file and save the choosen with userid name but i cant do change name and save file

How do you get skype to read other text in a message vb.net?

I was wondering if there is an easy way to load text from a command from skype using the SKYPE4COMLib.dll API Supported file. I am trying to get the bot to trigger ! Then - Is there an easy way to have it copy it to a textbox? Thanks! -Dom

converting greyscale image from RGB to YUV gives non-zero U and V

I've read that if image is greyscale then it shouldn't have B and R component in RGB and no U and V in YUV color spaces. Does it mean they should be equal to 0?

I'm using this code to get YUV values:

var px = (this.canvas.Image as Bitmap).GetPixel(i, j);

var y = 0.299 * px.R + 0.587 * px.G + 0.114 * px.B;
var u = -0.14713 * px.R - 0.28886 * px.G + 0.436 * px.B;
var v = 0.615 * px.R - 0.51499 * px.G - 0.10001 * px.B;

And I'm getting non-zero u and v values, though they're are close to 0. Should I convert them to int anyway? Was the image really greyscale?

.NET implementation of Locality based Timezone Conversions?

The old way of converting time is obsolete and AFAIK that's the .NET way. With DST changeovers becoming "locality" based and not "region" based, this is becoming a bigger problem in the .NET realm. The mobile platforms such as iOS and Android have been handling this for quite some time yet the larger .NET framework does not AFAIK. With people becoming more and more mobile (i.e. the years since the iPhone was unveiled) and changes to when locale's change time, this has become a problem. Mexico locales such as Cancun for example just decided to move from Central to Eastern time. Locales are changing clocks for DST at varying dates now.

Does anyone know if it's possible or if it's coming that the .NET SDK will support natively Locality based timezone conversions also known as Olsen Timezones? Example: America/New_York.

Anyone know of a good way of implementing this in .NET?

Package Manage Console not working

I am trying to install Npgsql and Npgsql.EntityFramework and getting this error:

Install-Package : The remote name could not be resolved: 'www.nuget.org'
At line:1 char:16
+ Install-Package <<<<  Npgsql
+ CategoryInfo          : NotSpecified: (:) [Install-Package], WebException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

What am I doing wrong? Please help

Multilingual website in asp .net Web Forms without using Globalization

I'm trying to build a site in Visual Studio for a project, using ASP .NET Web Forms along with C#.

The requirement is that the website should be multilingual, however without using the built in Globalization/Resources feature, as the language should be made choosable by the user and not rigidly set based on the OS (for variety of reasons).

Now, I've seen several tutorials on how to do it with help of Javascript/jQuery and localized strings being stored in XML file, however there is another requirement that these tutorials do not follow. That each language has it's own XML localization file, and that the site remembers the language throughout the site (I imagine with help of cookies).

So the question I'm asking, is what I prescribed possible (and there is some 101 to go along) or some better solution using different technologies would be preferable ?

How to do DateTime Comparison in C# Entity Function?

I have certain date time saved in my database, my requirement is to get only those records which are newer than saved date-time.

I tried this code

DateTime last_date_time_saved = GetLastDateTimeFromDB();

List<Item> li = con.Items.Where(p => p.TimeModified > last_date_saved).ToList();
return li;

But it causes error Could not execute the specified command:

Error parsing Date value [26/04/2015 16:42:56]."}

I have tried Convert.ToDateTime function but it still does not resolve the problem.

What is the best way to compare date time in this case?

User impersonation in WCF message inspector

I'm facing a problem while using WCF message inspectors, the problem is I can't get the impersonated user in message inspector and when I try to get current user with WindowIdentity.GetCurrent() it returns AppPool\DefaultAppPool instead of impersonated user.

On the other hand if I try to get the user in OperationContract the impersonated user is available.

private void RequestValidationStart(ref Message request)
{
    // WindowIdentity.GetCurrent() returns IIS AppPool\DefaultAppPool
    // instead of impersonated user
    var user = System.Security.Principal.WindowIdentity.GetCurrent();
}

How to get the impersonated user in WCF Message Inspector?

Can't load assembly libphonenumber Version=5.0.0.0 on Windows Phone 8.0

  1. I add libphonenumber library C# port with nuget to Windows Phone 8.0 project.
  2. Write code
  3. Run, then app crash on this Line _phoneNumberUtil = PhoneNumberUtil.GetInstance(); With this error

Could not load file or assembly 'libphonenumber_csharp_portable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Please, help me! What I doing wrong?

public partial class EnterPage
{
    private readonly EnterPageViewModel _viewModel;
    private readonly PhoneNumberUtil _phoneNumberUtil;
    public EnterPage()
    {
        InitializeComponent();
        _viewModel = new EnterPageViewModel();
        DataContext = _viewModel;
        _phoneNumberUtil = PhoneNumberUtil.GetInstance();
    }
}

In Windows Phone 8.1 project this code run without any errors.

Unable to call com registered dll function in php

I have completed the com registration of a dll file and it is showing in the registry(which I got after entering regedit in command prompt)
If I use $obj1 = new COM("Encryptiondll.ClsEncryption"); I am getting no error
But when I am trying to access a method(which is declared as public string in .net) I am getting the following error from my php code
Fatal error: Call to undefined method com::Encrypt12() in C:\xampp\htdocs\test1\index.php on line 12
Please help

Using DTO in Azure Mobile Service .NET throws target invocation exception

I use Azure Mobile Services .NET backend and we all know we have to use Entity Framework classes to map to the database creation/migration. So I need to use DTOs to serialize only the properties I want, computed properties etc. I'm following the Field Engineer example. But Automapper gave me so much pain although I did everything as supposed to.

I have checked couple of others blog and site, some use Automapper, others not, for example this one. I feel more comfortable not using Automapper and create DTOs on the fly with Select() as I was doing it before when implementing Web API.

I reverted TableController class to Post, use the EntityDomainManager and I left the GetAllPosts method to the following.

public class PostController : TableController<Post>
{
    private MobileServiceContext _context;

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        _context = new MobileServiceContext();
        DomainManager = new EntityDomainManager<Post>(_context, Request, Services);
    }

    //[ExpandProperty("User")]
    // GET tables/Post
    public IQueryable<PostDto> GetAllPost()
    {
        return Query().Include("User").Select(x => new PostDto());
    }
}

I get the following error.

{"message":"An error has occurred.","exceptionMessage":"Exception has been thrown by the target of an invocation.","exceptionType":"System.Reflection.TargetInvocationException","stackTrace":"   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)\r\n   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)\r\n   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)\r\n   at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults(IQueryable queryable, Int32 limit, Boolean& resultsLimited)\r\n   at System.Web.Http.OData.Query.ODataQueryOptions.ApplyTo(IQueryable query, ODataQuerySettings querySettings)\r\n   at System.Web.Http.OData.EnableQueryAttribute.ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)\r\n   at System.Web.Http.OData.EnableQueryAttribute.ExecuteQuery(Object response, HttpRequestMessage request, HttpActionDescriptor actionDescriptor)\r\n   at System.Web.Http.OData.EnableQueryAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","innerException":{"message":"An error has occurred.","exceptionMessage":"The specified type member 'DatePosted' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.","exceptionType":"System.NotSupportedException","stackTrace":"   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberAccessTranslator.TypedTranslate(ExpressionConverter parent, MemberExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.ThenByTranslatorBase.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.ThenByTranslatorBase.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n   at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()\r\n   at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()\r\n   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()\r\n   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()\r\n   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n   at System.Web.Http.OData.Query.TruncatedCollection`1..ctor(IQueryable`1 source, Int32 pageSize)\r\n   at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean& resultsLimited)"}}

If I just convert it to the Entity Framework class it works. You will notice that I don't fill any property, just for testing purposes.

I test locally with IIS Express.

Data objects and models.

    public class Post : EntityData
    {
        public DateTimeOffset DatePosted { get; set; }
        public string StatusText { get; set; }
        public PostType TypeOfPost { get; set; }

        [ForeignKey("Id")]
        public virtual User User { get; set; }

        [ForeignKey("Id")]
        public virtual ICollection<PostPhotoUrl> PhotoUrls { get; set; }
    }

    public class PostDto
    {
        public PostDto()
        {
            PhotoUrls = new HashSet<PostPhotoUrlDto>();    
        }

        public DateTimeOffset DatePosted { get; set; }
        public string StatusText { get; set; }
        public int TypeOfPost { get; set; }

        public UserDto User { get; set; }
        public ICollection<PostPhotoUrlDto> PhotoUrls { get; set; }
    }

Searching the internet couldn't find any other more clear tutorial how to use Azure Mobile Services and DTOs, though it shouldn't introduce such difficulty. If you have any resources are welcome.

I should mention that if I don't do the following the test website raises error when trying to test the endpoints.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

The exception snapshot:

JsonMediaTypeFormatter Error

I don't REALLY need to have DTOs for this project, but if I don't resolve what I don't understand right now it will come back and hunt me in the long run of this service.

resolving dependcies in unity container on some other app than mvc

using unity I'm register concrete types which should be resolved for particular interfaces, like

public static class UnityConfig
{
   public static void RegisterComponents()
   {
       var container = new UnityContainer();                            
       container.RegisterType<IHotelRepository, HotelRepository>();                
       DependencyResolver.SetResolver(new UnityDependencyResolver(container));
   }
}

and inside global.asax to register componentens.

I'm wonder how could I resolve dependicies in desktop app, winforms or wpf, or console (whatever) where to register componentes in container?

How to save a file in a list box into a .txt file?

How to save a file in a list box into a .txt file?

return string.Format("{0} = {1}",   
JaialaiNumber, "₱" + Bet.ToString()); How to save this file on a .txt file?

Here's the code of my program. ): ^_^ .

public partial class frmJaialai : Form
{
    List<Jaialai> source;

    public frmJaialai()
    {
        InitializeComponent();
    }        

    private void frmJaialai_Load(object sender, EventArgs e)
    {
        source = new List<Jaialai>();          
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        int bet;
        if (string.IsNullOrEmpty(txtJaialaiNumber.Text) || !Int32.TryParse(txtBet.Text, out bet))
        {
            MessageBox.Show("Must be a required field.", "Entry Error");
            return;
        }
        var existingProduct = source.Where(x => x.JaialaiNumber == txtJaialaiNumber.Text).SingleOrDefault();
        if (existingProduct != null)
        {
            existingProduct.Bet += bet;
        }
        else
            source.Add(new Jaialai { Bet = bet, JaialaiNumber = txtJaialaiNumber.Text });

        lstJaialaiNumbersList.DataSource = null;
        lstJaialaiNumbersList.DataSource = source;

        txtJaialaiNumber.Text = "";      
    }

    public class Jaialai
    {
        public string JaialaiNumber { get; set; }
        public int Bet { get; set; }

        public override string ToString()
        {
            return string.Format("{0} = {1}", 
                JaialaiNumber, "₱" + Bet.ToString());
        }
    }

No connection string named 'MyAppDbContext' could be found in the application config file

Inside my DAL project I have repositories which I consume from ui. I've refactor project a bit and now on gather data from repository I'm getting error

"No connection string named 'MyAppDbContext' could be found in the application config file."

My App.config on same project (DAL) where repository lives have following context

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://ift.tt/1eigFsq -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />    
  </configSections>
  <connectionStrings>
    <add name="MyAppDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyApp.DAL.MyAppDbContext;Integrated Security=True;AttachDBFilename=MyApp.DAL.MyAppDbContext.mdf" providerName="System.Data.SqlClient" />               
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

I actually have two questions:

  • Why I'm getting this error message: "No connection string named 'MyAppDbContext' could be found in the application config file."
  • How can I set path in conn. string to use db from App_Data directory (after I move it there ofcourse)

C# API for driver installation x64 bit

I would like to install a 64 bit driver using C# API on a installer 32 bit application.

we used devcon and it worked from command line, we would like to know if there is another mehtod to install driver on windows machine for example 1. C# API instead 2. C++ API we can call the DLL from c#

We tried

  1. CoInstaller
  2. Install driver during project installation
  3. DriverPackagePreinstall.

Thanks

What does "Stateful" means in Stateful ViewModel in MVVM

I was reading about some XAML patterns, and there was the Stateful ViewModel, according to what I read it has nothing different than what we as just the "ViewModel".

Here's a description for example :

Stateful View Model:

To create isolation between business logic and presentation, data should be removed from the view. The stateful view model pattern moves data into the view model using XAML data binding. This allows the view model to be tested without constructing a view, and it allows the view to change with minimal impact on the business logic.

What is so special about it to be called Stateful ViewModel ? why isn't just called ViewModel

Link : http://ift.tt/1HHontS

APS.NET MVC 4 WebAPI PostAsJsonAsync Newtonsoft.Json error

In my MVC 4 Web API project stops working. It's can't find Newtonsoft.Json. After running this code :

 Dim response As HttpResponseMessage = MyHttpClient.PostAsJsonAsync("Api/Test", MyObject).Result

I get message error :

An unhandled exception of type 'System.IO.FileLoadException' occurred in System.Net.Http.Formatting.dll

Additional information: Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I know that MS is using this as the default JSON serializer now - and its in my references list for the project. I tried to update Newtonsoft.Json from NuGet but I can't find it I find "Json.Net". So I use package manager console to reinstall Update-Package Newtonsoft.Json -Reinstall But still not work

Does anyone have any idea here as to what could be going wrong?

C#: Bitmap from Drawing not render outside of Load_Form

I'm trying to render bitmap created from drawing to screen but only render after minimize and maximize again.

I follow this steps: Using Bitmaps for Persistent Graphics in C#

But only cannot render bitmap in screen outside of Load_Form.

If I put the code:

Graphics graphicsObj;
 myBitmap = new Bitmap(this.ClientRectangle.Width, 
    this.ClientRectangle.Height, 
    System.Drawing.Imaging.PixelFormat.Format24bppRgb);
 graphicsObj = Graphics.FromImage(myBitmap);
 Pen myPen = new Pen(System.Drawing.Color.Plum, 3);
 Rectangle rectangleObj = new Rectangle(10, 10, 200, 200);
 graphicsObj.DrawEllipse(myPen, rectangleObj);
 graphicsObj.Dispose();

in other place, for example a button I need minimize and mazimize to see the image.

Thanks in Avanced!

samedi 25 avril 2015

Certificate installation in IIS not showing

Hi Guys I installed a certificate given to us by one of our vendors. Since it was a chained cert (3 entries with begin and end certificate) I extract the last section and saved it as a .cer. I verified that everything is ok with the certificate I extracted. I copied this certificate to the server and installed it via IIS then clicked on Complete Certificate Request (browse .cer file, click next2x and ok). Everything went successfully no error messages encountered. But when I tried to refresh IIS or restart I can't view the certificate I just installed. Any reason why its doing this?

Could not load file or assembly (custom dll) - works for console but fails for web project (ASP.NET MVC 5) [duplicate]

This question already has an answer here:

I am building a ASP.NET MVC 5 web app that utilizes SignalR for the communication stack abstraction.

Everything works fine until I add a custom DLL that implements a real-time message bus. Part of the message bus process requires xml files (properly copied to bin deploy folder).

When trying to run the Web project (locally using IISExpress - haven't tried deployment server) I am getting a "Could not load file or assembly 'MSG_BUS.DLL' or one of its dependencies" ... everything works fine when using one of my test harness console projects or before I added the DLL dependency.

Any idea how to troubleshoot or resolve this issue? I suspect it has something to do with the XML files - but have no clue how to resolve it

NBitcoin throws InvalidOperationException with the message: "Mac HMACSHA256 not recognised."

I dig into the opensource NBitcoin API and figured out these lines give me the error message. What can I do? (http://ift.tt/1HG6VV8)

try
            {
                hmac = MacUtilities.GetMac(macName);
            }
            catch(SecurityUtilityException nsae)
            {
                throw new InvalidOperationException(nsae.Message, nsae);
            }

How to Add data to Dropdown in windows forms applications in C#

I am trying to create a windows form application. To create a .Zip file with a password and sending the .zip file to the clients email address in one email and another email to send password of the .zip file to the client...

I am using a dropdown box to enter "TO:" email address... and I want the user not to write the entire email address if it is an frequently used email ID.. So want the whole email ID to display if entered starting part of it... (Like an intellisense) and if it is a new one then make a new entry.. I am not sure how to implement this.. as looks like dropdown does not do this..

Any one please help me or suggest how to achieve this functionality..

Thanks in Advance!

"Reflexil unable to save this assembly. Object reference not set to an instance of an object."

I am using .NET Reflector and Reflexil. I am trying to remove some pieces of code that reference another DLL. I am pretty sure I deleted all entries. Now when I go to save the DLL, I get the error message:

Reflexil unable to save this assembly. Object reference not set to an instance of an object.

Unfortunately, it does not tell me which object reference it is referring to. Is there any way I can find out?

Flatten Nested List using AutoMapper

I'm trying to flatten a nested object into a DTO object in .NET 3.5. Most of what I've seen so far is to use AutoMapper to do this (using v1.x since I need to use .NET 3.5, unfortunately):

Here's what a snippet of my class structures look like:

public class RootObject
{
    [JsonProperty("BaseSupplier")]
    public BaseSupplier BaseSupplier { get; set; }

    [JsonProperty("BaseOrderShipmentLineitem")]
    public IList<BaseOrderShipmentLineitem> BaseOrderShipmentLineitem { get; set; }
}

public class BaseSupplier
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class BaseOrderShipmentLineitem
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("qty_delivered")]
    public int QtyDelivered { get; set; }

    [JsonProperty("BaseOrderLineitem")]
    public BaseOrderLineitem BaseOrderLineitem { get; set; }    
}

public class BaseOrderLineitem
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("product_sku")]
    public string ProductSku { get; set; }
}

public class ShipmentDetailsDTO
{
    public int BaseOrderId { get; set; }
    public string CustomerOrderCode { get; set; }
    public string FulfillLoc { get; set; }
    public string BaseOrderShipmentInvoiceNumber { get; set; }
    public string Sku { get; set; }
}

I've been trying something like this:

Mapper.CreateMap<BaseOrderLineitem, ShipmentDetailsDTO>()
    .ForMember(d => d.Sku, opts => opts.MapFrom(s => s.ProductSku));
Mapper.CreateMap<BaseOrderShipmentLineitem, ShipmentDetailsDTO>();
Mapper.CreateMap<RootObject, ShipmentDetailsDTO>()
    .ForMember(d => d.Sku, opts => opts.MapFrom(s => Mapper.Map<IEnumerable<BaseOrderLineitem>, IEnumerable<ShipmentDetailsDTO>>(s.BaseOrderShipmentLineitem.SelectMany(q => q.BaseOrderLineitem)).FirstOrDefault().Sku))
    ;

var model = Mapper.Map<IEnumerable<RootObject>, IEnumerable<ShipmentDetailsDTO>>(obj);

With that above code I'm getting an error on this bit s.BaseOrderShipmentLineitem.SelectMany(q => q.BaseOrderLineitem):

Cannot implicitly convert type 'IEnumerable<?>' to 'IEnumerable<BaseOrderLineitem>'. An explicit conversion exists (are you missing a cast?)

I'm not sure if it's something simple I'm just overlooking or not.

Why is there time difference between client and server on localhost

Application running on localhost. Server is one hour earlier then client!

Client sends time : Sat Apr 25 2015 00:00:00 GMT-0400 (Eastern Daylight Time)

enter image description here Server receives time: {4/24/2015 11:00:00 PM}

enter image description here

Why is there one hour difference between and how can I handle it? I could guess it is somehow related Daylight time vs Standart time.

Actually I am only interested day part of time. In my db, I am holding it as Date type. But because of this time difference, my days goes one day before.

I tried various ways to handle issue but I got completely lost in datetime conversion world! Even I am lost on localhost application, I could not imagine what will happen on live server.

if it matters:

My timezone: Eastern Time Zone (UTC-05:00)

About web api odata json serializer, from this post I could say that it is other then this one

Here is my server code:

// PATCH: odata/IncomingStudents(5)
[AcceptVerbs("PATCH", "MERGE")]
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<IncomingStudent> patch)
{
    Validate(patch.GetEntity());
    var dateOfArrival = patch.GetEntity().DateOfArrival
... 
}

Client is angularjs sending http patch request

Why does my floating point value have an `E` character when I convert it to a string?

txtDebugLog.Invoke(new MethodInvoker(delegate()
{
    fps.Frame();
    ggg = fps.GetFPS();
    txtDebugLog.Text = String.Format("{0}\r\n{1}", ggg, txtDebugLog.Text);
})

txtDebugLog is a TextBox.

Using a breakpoint i see on ggg in this example it's value is:

0.00000102593151

Then i click on continue and see in the TextBox:

1.025932E-06

How pkg-config decides which look up path to add by default?

I'm trying to run pkg-config on my 64bits elementary (ubuntu 14.04) from a .net gui application and it says that it doesn't find my packages that are found when I run the exact command from a terminal.

For reference, here's the command:

pkg-config --cflags --libs  glib-2.0 gobject-2.0

Using the PKG_CONFIG_DEBUG_SPEW I managed to get detailed debug info for pkg-config and it looks like it initializes itself differently in the two cases.

Initialization in terminal:

Adding directory '/usr/share/pkgconfig' from PKG_CONFIG_PATH
Adding directory '/usr/lib/pkgconfig' from PKG_CONFIG_PATH

Initialization in .net gui application

Adding directory '/usr/local/lib/x86_64-linux-gnu/pkgconfig' from PKG_CONFIG_PATH
Adding directory '/usr/local/lib/pkgconfig' from PKG_CONFIG_PATH
Adding directory '/usr/local/share/pkgconfig' from PKG_CONFIG_PATH
Adding directory '/usr/lib/x86_64-linux-gnu/pkgconfig' from PKG_CONFIG_PATH
Adding directory '/usr/lib/pkgconfig' from PKG_CONFIG_PATH
Adding directory '/usr/share/pkgconfig' from PKG_CONFIG_PATH

Of course my libraries are defined in the missing directory.

Why are the two initializations different?

How can I tell pkg-config to initialize the same it does in the terminal?

Note: I know that I can set the PKG_CONFIG_PATH before calling pkg-config but I would prefer a simpler solution if available.

How can I tell how much memory my application is using in C#?

If I want to see how much memory my java application uses, I can write

 class Test{
  public static void main (String[] args) {
    Runtime rt = Runtime.getRuntime();
    System.out.println(rt.totalMemory() - rt.freeMemory());
  }
}

How can I do the same for C#? This:

using System;
using System.Diagnostics;

public class Test
{
    public static void Main()
    {
        Process proc = Process.GetCurrentProcess();
        Console.WriteLine(proc.PrivateMemorySize64);
    }
}

as explained in this post During execution, how can a java program tell how much memory it is using? seems to only print the total number of bytes allocated for the application, same as "Runtime.getRuntime().totalMemory()" would do.