Affichage des articles dont le libellé est Active questions tagged .net - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged .net - Stack Overflow. Afficher tous les articles

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