小编kat*_*tit的帖子

TCP侦听器以1024字节切断消息

问题刚刚开始在客户端.这是我收到TCP/IP消息的代码.在我的本地PC上,这个听众收到很多K没问题.我试图增加缓冲区大小,但在客户端网站上,他们仍然报告与之相关的问题..仍然只获得第一个1K(1024字节)

public void Start()
{
  //Define TCP listener
  tcpListener = new TcpListener(IPAddress.Any, IDLocal.LocalSession.PortNumber);

  try
  {
    //Starting TCP listenere
    tcpListener.Start();

    while (true)
    {
      var clientSocket = tcpListener.AcceptSocket();
      if (clientSocket.Connected)
      {
        var netStream = new NetworkStream(clientSocket);

        // Check to see if this NetworkStream is readable.
        if (netStream.CanRead)
        {
          var myReadBuffer = new byte[1024];
          var myCompleteMessage = new StringBuilder();

          // Incoming message may be larger than the buffer size.
          do
          {
            var numberOfBytesRead = netStream.Read(myReadBuffer, 0, myReadBuffer.Length);
            myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
          } while …
Run Code Online (Sandbox Code Playgroud)

c# sockets tcp tcplistener

5
推荐指数
1
解决办法
3494
查看次数

代码分析抱怨我没有处理对象.这有什么不对?

考虑这段代码

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
        {

            var msg = new MailMessage();

            foreach (var recipient in mailItem.MailRecipients)
            {
                var recipientX = Membership.GetUser(recipient.UserKey);
                if (recipientX == null)
                {
                    continue;
                }

                msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
            }

            msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"],
                                   ConfigurationManager.AppSettings["EmailSenderName"]);

            msg.Subject = sender.UserName;
            if (!string.IsNullOrEmpty(alias)) msg.Subject += "(" + alias + ")";
            msg.Subject += " " + mailItem.Subject;
            msg.Body = mailItem.Body;
            msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" + Environment.NewLine;
            msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" + ContextManager.AccountId …
Run Code Online (Sandbox Code Playgroud)

c# dispose code-analysis mailmessage

5
推荐指数
1
解决办法
608
查看次数

在自定义控件中使依赖项属性绑定两种方式

我有以下自定义控件:

<TextBox Grid.Column="3" Text="{TemplateBinding SampleValue}" />

public static readonly DependencyProperty SampleValueProperty =
            DependencyProperty.RegisterAttached("SampleValue", typeof(string), typeof(IdattFilterBox), new PropertyMetadata(null));

public string SampleValue
        {
            get { return GetValue(SampleValueProperty) as string; }
            set { this.SetValue(SampleValueProperty, value); }
        }
Run Code Online (Sandbox Code Playgroud)

在UserControl中我声明我的自定义控件我有这样的XAML:

<my:SampleBox SampleValue="{Binding SampleValue, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

和ViewModel一样:

public string SampleValue
        {
            get
            {
                return this.sampleValue;
            }

            set
            {
                this.sampleValue = value;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我不关心VM上的INotifyPropertyChanged(所以不要告诉我它:)现在它正在文本框中显示文本,就像我在VM中设置它一样.但是当我修改这个文本时 - 它不会被冒泡回VM.

我该怎么办?我想我必须在自定义控件中编写一些代码?我应该处理TextBox PART并捕获LostFocus吗?或者它如何与TemplateBinding一起使用?

silverlight xaml

5
推荐指数
2
解决办法
2681
查看次数

DataGridView设置行高不起作用

试着像这样设置RowHeight(在代码中):

dgvTruckAvail.RowTemplate.Height = 48;
Run Code Online (Sandbox Code Playgroud)

不行吗?我还尝试设置我添加的每个列的高度 - 不起作用.

这是网格属性:

this.dgvTruckAvail.AllowUserToAddRows = false;
this.dgvTruckAvail.AllowUserToDeleteRows = false;
this.dgvTruckAvail.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
    | System.Windows.Forms.AnchorStyles.Left) 
    | System.Windows.Forms.AnchorStyles.Right)));
this.dgvTruckAvail.BackgroundColor = System.Drawing.Color.White;
this.dgvTruckAvail.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dgvTruckAvail.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
this.dgvTruckAvail.Columns.AddRange(
    new System.Windows.Forms.DataGridViewColumn[] 
    {
        this.colMon,
        this.colTue,
        this.colWED,
        this.colThu,
        this.colFri,
        this.colSat,
        this.colSun});
this.dgvTruckAvail.Cursor = System.Windows.Forms.Cursors.Default;
dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle8.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle8.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle8.SelectionBackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle8.SelectionForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle8.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgvTruckAvail.DefaultCellStyle = dataGridViewCellStyle8;
this.dgvTruckAvail.EnableHeadersVisualStyles = false; …
Run Code Online (Sandbox Code Playgroud)

c# datagridview winforms

5
推荐指数
2
解决办法
4万
查看次数

实现WCF IErrorHandler仅用于日志记录

可能是微不足道的问题..我想实现我自己的错误处理程序来记录错误并监视正在发生的事情.此时我不想向客户提供自己的错误.我希望它是透明的 - 就像默认的WCF行为一样.我应该如何ProvideFault实现这一目标?

namespace IDATT.Web.Services
{
    using System;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Dispatcher;

    public class MyServiceErrorHandler : IErrorHandler 
    {
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            // ????
        }

        public bool HandleError(Exception error)
        {
            return true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# wcf ierrorhandler

5
推荐指数
1
解决办法
4140
查看次数

使用拆分器使ItemsControl子级可以调整大小

我想将小部件插入到我的内容中ItemsControl并使它们可以调整大小.我该如何实现这一目标?

这是我的XAML:

<ItemsControl ItemsSource="{Binding TestForList, Mode=OneWay}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"                
                        VerticalAlignment="Stretch"                
                        HorizontalAlignment="Stretch" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Margin="5" 
                    BorderThickness="1" 
                    BorderBrush="Black">
                <TextBlock FontSize="100" Text="{Binding}" />    
            </Border>                    
        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

哪个绑定到:

public List<string> TestForList
{
    get
    {
        return new List<string> { "A", "B", "C" };
    }
}
Run Code Online (Sandbox Code Playgroud)

我想以某种方式在项目之间添加分割器,以便可以调整它们的大小.有没有内置的功能来实现这一目标?

在此输入图像描述

c# wpf layout xaml

5
推荐指数
1
解决办法
246
查看次数

将protobuf-net添加到我的WCF Rest服务

是否有任何规范的直接方式在.NET 4 WCF上启用protobuf-net序列化?我试图将代码简化到可以轻松构建的程度:

这是我的服务代码:

[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MobileServiceV2
{
    [WebGet(UriTemplate = "/some-data")]
    [Description("returns test data")]
    public MyResponse GetSomeData()
    {
        return new MyResponse { SomeData = "Test string here" };
    }
}

[DataContract]
public class MyResponse
{
    [DataMember(Order = 1)] 
    public string SomeData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在Application_OnStart(Global.asax)中激活此服务路由,如下所示:

RouteTable.Routes.Add(new ServiceRoute("mobile", new MyServiceHostFactory(), typeof(MobileServiceV2)));
Run Code Online (Sandbox Code Playgroud)

我用MyServiceHostFactoryMEF来管理服务,但那是无关紧要的.

我的服务配置都是默认的,Web.Config中唯一的附加功能就在这里:

<system.serviceModel>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint helpEnabled="true" maxReceivedMessageSize="5242880" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" …
Run Code Online (Sandbox Code Playgroud)

.net rest wcf protocol-buffers protobuf-net

5
推荐指数
1
解决办法
1619
查看次数

如何从WCF服务返回流?

我正在玩protobuf-net和WCF.这是我创建的代码:

public class MobileServiceV2
{
    [WebGet(UriTemplate = "/some-data")]
    [Description("returns test data")]
    public Stream GetSomeData()
    {
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-protobuf";

        var ms = new MemoryStream();
        ProtoBuf.Serializer.Serialize(ms, new MyResponse { SomeData = "Test data here" });
        return ms;
    }
}

[DataContract]
public class MyResponse
{
    [DataMember(Order = 1)] 
    public string SomeData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我看到Fiddler时 - 我可以看到正确的传出内容类型,并且看起来都很好,但我得到了空洞的回应.IE提示下载文件,此文件为空.序列化器无法正常工作吗?或者我只是不做对吗?

编辑:

我在方法中添加了以下代码,是的,它正确序列化.我如何从WCF返回流有什么问题..

using (var file = File.Create("C:\\test.bin"))
        {
            Serializer.Serialize(file, new MyResponse { SomeData = "Test data here" });
        }
Run Code Online (Sandbox Code Playgroud)

.net wcf stream protobuf-net

5
推荐指数
1
解决办法
9376
查看次数

一个文件在 Visual Studio IDE 中不断打开

我正在使用 Visual Studio 2010

在一个解决方案中,我有A.XAML文件,并且每次启动解决方案时它都会打开。它也会在某个随机时间打开 - 我没有确切的解释。

这很烦人。为什么VS会自己打开特定文件?

c# wpf visual-studio-2010

5
推荐指数
1
解决办法
766
查看次数

调用 EndReceive 和 BeginReceive 时的 TcpClient 异常

我正在尝试实现包装类,它将简单地连接到 TCP 服务器并等待数据。一旦从服务器提交数据 - 我将接收这些数据并将其传递给我的类的订阅者。

所有这些都有效。现在我想添加外部功能以在计时器上“重置”这个类(强制重新连接每隔一段时间)以保持连接有效。我的想法是Init可以根据需要多次调用该方法来重置套接字。但是,我确实遇到了各种例外情况。

班级代码:

namespace Ditat.GateControl.Service.InputListener
{
    using System;
    using System.ComponentModel;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;

    public class BaseTCPSocketListener : IInputListener
    {
        #region Events/Properties

        public event EventHandler<Exception> OnError;

        public event EventHandler<string> OnDataReceived;

        private string host;

        private int port;

        private int delayToClearBufferSeconds = 5;

        private TcpClient client;

        private readonly byte[] buffer = new byte[1024];

        /// <summary>
        /// Will accumulate data as it's received
        /// </summary>
        private string DataBuffer { get; set; }

        /// <summary>
        /// …
Run Code Online (Sandbox Code Playgroud)

.net c# tcplistener

5
推荐指数
1
解决办法
1136
查看次数