用户代码未处理 System.ArgumentNullException

用户代码未处理 System.ArgumentNullException
HResult=-2147467261
Message=值不能为 null。
参数名: String Source=mscorlib
ParamName=String
StackTrace:
在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
在 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
在 NetOpinion.Form2.webBrowser1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e) 位置 d:\ProgrammingCode\NetOpinion1.2\NetOpinion\Form2.cs:行号 92
InnerException:

代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace NetOpinion
{
public partial class Form2 : Form
{
int ipage,pagenum;
string text;
NameValueCollection nvc; //解析Url用

    VR vr = new VR();
    DataItem di = new DataItem();
    SqlServer db = new SqlServer();

    int start;
    int final;
    string httpbase = "http://www.tianya.cn/new/publicforum/articleslist.asp?pageno=1&stritem=";

    public Form2()
    {
        ipage = 1;
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (toolStripComboBox1.Text == "娱乐—娱乐八卦")
        {
            start = 9;
            final = 108;
            toolStripTextBox2.Text = httpbase + "funinfo&part=1";
        }
        else if (toolStripComboBox1.Text == "社会—天涯杂谈")
        {
            start = 9;
            final = 108;
            toolStripTextBox2.Text = httpbase + "free&part=1";
        }
        else if (toolStripComboBox1.Text == "社会—国际观察")
        {
            start = 9;
            final = 53;
            toolStripTextBox2.Text = httpbase + "worldlook&part=1";
        }
        else if (toolStripComboBox1.Text == "情感—情感天地")
        {
            start = 9;
            final = 53;
            toolStripTextBox2.Text = httpbase + "feeling&part=1";
        }
        else
        {
            MessageBox.Show("请选择论坛版面");
            return;
        }

        if (toolStripTextBox1.Text == "")
        {
            MessageBox.Show("请输入抓取页数");
            return;
        }

        if (toolStripComboBox2.Text == "选择时刻")
        {
            MessageBox.Show("请选择时刻");
            return;
        }
        text = toolStripComboBox2.Text;
        pagenum = int.Parse(toolStripTextBox1.Text);

        webBrowser1.Navigate(toolStripTextBox2.Text, "_self");
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        if (webBrowser1.Document.Url != e.Url || e.Url.AbsoluteUri == "about:blank")
        {
            return;
        }
        ParseUrl(webBrowser1.Url.AbsoluteUri, out nvc);


        if (nvc.Count != 0 && int.Parse(nvc.Get("pageNO")) > pagenum)
        {
            toolStripStatusLabel2.Text = "恭喜你!页面分析完毕,你可以查看结果了";
            return;
        }

        toolStripStatusLabel2.Text = "当前正在抓取处理的页" + ipage.ToString() + "...";

        ParsePage(webBrowser1.Document,start,final);
    }

    public void ParseUrl(string url, out NameValueCollection nvc)  //解析网址,正则匹配
    {
        nvc = new NameValueCollection();

        if (url == "")
        {
            return;
        }
        int questionMarkIndex = url.IndexOf('?');
        if (questionMarkIndex == -1 || questionMarkIndex == url.Length - 1)
        {

            return;
        }
        string ps = url.Substring(questionMarkIndex + 1);

        // 开始分析参数对
        Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
        MatchCollection mc = re.Matches(ps);

        foreach (Match m in mc)
        {
            nvc.Add(m.Result("$2"), m.Result("$3"));
        }
    }

    public void ParsePage(HtmlDocument documentShare,int start,int final)    //解析网页
    {
        int table = 1;
        foreach (HtmlElement htmelt in documentShare.GetElementsByTagName("table"))
        {
            if ( table>=start && table<=final )
            {
                HtmlElement htmtr = htmelt.GetElementsByTagName("tr")[0];
                GetTable(htmelt);
                UpdateDataBase();
            }
            table++;
        }       
        foreach (HtmlElement htmelt in documentShare.GetElementsByTagName("a"))
        {
            if (htmelt.InnerText == "下一页")
            {
                htmelt.InvokeMember("click");
                ipage++;
            }
        }
    }
}

}

2个回答

调试看看
nvc.Get("pageNO")的值不对

longmansing
小菜同学 不知道啊,改错了吧。那个nvc.Get("pageNO")不是这样改的。
大约 6 年之前 回复
feiyun0112
feiyun0112 那就跟踪看代码怎么走的,为什么没执行
大约 6 年之前 回复
longmansing
小菜同学 没执行啊。那样改不可以的吧
大约 6 年之前 回复
longmansing
小菜同学 呵呵,我找不到pageNO这个值啊,不知道是什么意思?我把nvc.Get("pageNO")换为ipage后可以正常运行,不过无法把抓取的数据读到数据库中
大约 6 年之前 回复

public void GetTable(HtmlElement htmelt)
{
int item = 0;
foreach (HtmlElement htmtd in htmelt.GetElementsByTagName("td"))
{
if (item == 1)
{
HtmlElement htmtltle = htmtd.GetElementsByTagName("a")[0];
di.bbstitle = htmtltle.InnerText.Replace("\"", " ").Replace("'", " ");
di.bbsurl = htmtltle.GetAttribute("href");
}
else if (item == 2)
{
HtmlElement htmauthor = htmtd.GetElementsByTagName("a")[0];
di.bbsauthor = htmauthor.InnerText;
}
else if (item == 3)
{
vr.bbsview = int.Parse(htmtd.InnerText);
}
else if (item == 4)
{
vr.bbsreply = int.Parse(htmtd.InnerText);
}
else if (item == 5)
{
di.submittime = htmtd.InnerText;
}
item++;
}
di.vrList.Add(vr);
}

    public void UpdateDataBase()
    {
        string sqlstr;
        if (db.MyTable("select * from bbs where bbstitle like '" + di.bbstitle + "'").Rows.Count == 0)
        {
            sqlstr = "insert into bbs(bbstitle, bbsurl, bbsauthor, submittime, bbsview" + text + ", bbsreply" + text + ") values('" + di.bbstitle + "','" + di.bbsurl + "', '" + di.bbsauthor + "','" + di.submittime + "', '" + di.vrList[0].bbsview + "','" + di.vrList[0].bbsreply + "')";
        }
        else
        {
            sqlstr = "update bbs set bbsview" + text + "='" + di.vrList[0].bbsview + "',bbsreply" + text + "='" + di.vrList[0].bbsreply + "'" + "where bbstitle like '" + di.bbstitle + "'";
        }
        db.ExecuteCommand(sqlstr);
    }
longmansing
小菜同学 这是后面的代码
大约 6 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
System.ArgumentNullException: 值不能为 null

行 47: </script> 行 48: } 行 49: @(X.Viewport() 行 50: .Layout(LayoutType.Border) 行 51: .Items( [ArgumentNullException: 值不能为 null。 参数名: source] System.Linq.Enumerable.Select(IEnumerable`1 source, Func`2 selector) +4091099 ASP._Page_Areas_Facilities_Views_EquipmentPurchasingApplication_Index_cshtml.Execute() in f:\万通(备份)\tfs\湘粮 - 数字粮食管理平台\04 源码库\02 中心版\Wantn.DigitalGranary.Client.Web\Areas\Facilities\Views\EquipmentPurchasingApplication\Index.cshtml:49 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103 System.Web.WebPages.StartPage.RunPage() +17 System.Web.WebPages.StartPage.ExecutePageHierarchy() +62 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +254 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +290 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9659272 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

DataTable.Rows.Add(item)抛出错误:“值不能为 null。参数名: key”

界面功能是选则一个功能范围,然后点击新增,在界面列表中新增一行数据。 错误出现场景:选择同一个功能范围,点击新增后,代码会执行DataTable.Rows.Add(item)这句,大约有20%的概率出现如题错误。具体错误信息如下: 捕捉到 System.ArgumentNullException _HResult=-2147467261 _message=值不能为 null。 HResult=-2147467261 IsTransient=false Message=值不能为 null。 参数名: key Source=mscorlib ParamName=key StackTrace: 在 System.Collections.Generic.Dictionary`2.FindEntry(TKey key) 在 System.Collections.Generic.Dictionary`2.get_Item(TKey key) 在 System.Data.DataView.MaintainDataView(ListChangedType changedType, DataRow row, Boolean trackAddRemove) 在 System.Data.DataViewListener.MaintainDataView(ListChangedType changedType, DataRow row, Boolean trackAddRemove) 在 System.Data.Index.<>c__DisplayClass5.<MaintainDataView>b__4(DataViewListener listener, ListChangedType type, DataRow row, Boolean track) 在 System.Data.Listeners`1.Notify[T1,T2,T3](T1 arg1, T2 arg2, T3 arg3, Action`4 action) 在 System.Data.Index.MaintainDataView(ListChangedType changedType, Int32 record, Boolean trackAddRemove) 在 System.Data.Index.InsertRecord(Int32 record, Boolean fireEvent) 在 System.Data.Index.ApplyChangeAction(Int32 record, Int32 action, Int32 changeRecord) 在 System.Data.Index.RecordStateChanged(Int32 record, DataViewRowState oldState, DataViewRowState newState) 在 System.Data.DataTable.RecordStateChanged(Int32 record1, DataViewRowState oldState1, DataViewRowState newState1, Int32 record2, DataViewRowState oldState2, DataViewRowState newState2) 在 System.Data.DataTable.SetNewRecordWorker(DataRow row, Int32 proposedRecord, DataRowAction action, Boolean isInMerge, Boolean suppressEnsurePropertyChanged, Int32 position, Boolean fireEvent, Exception& deferredException) 在 System.Data.DataTable.InsertRow(DataRow row, Int64 proposedID, Int32 pos, Boolean fireEvent) 在 System.Data.DataRowCollection.Add(DataRow row) InnerException: 跟踪代码结果: item是datatable.row类型。 (不知道怎么放图片)在正常与错误情况下,item.ItemArray有内容,部分为空字符串,内容除时间不一样之外,其余均相同。正常时正常添加,错误时,执行到add方法报错,捕捉错误后,item.ItemArray中的值都变成空,类型为System.DBNull.

asp.net 总是出错 求大神指点啊

文件名不能为空。 参数名: sourceFileName 说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.ArgumentNullException: 文件名不能为空。 参数名: sourceFileName 源错误: 行 190: if (!File.Exists(sPhoPath)) 行 191: { 行 192: File.Move(sTempPath, sPhoPath); 行 193: File.Delete(sTempPath); 行 194: } 源文件: f:\SurveyingPractice\Project\Register.aspx.cs 行: 192 堆栈跟踪: [ArgumentNullException: 文件名不能为空。 参数名: sourceFileName] System.IO.File.Move(String sourceFileName, String destFileName) +2212120 Project_Register.Btn_Register_Click(Object sender, EventArgs e) in f:\SurveyingPractice\Project\Register.aspx.cs:192 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

当DBNull.Value==“”时,为什么返回值是false不是true。

如题:当row["xxx"]=“”的时候 ,row["xxx"] == DBNull.Value的返回值是false, 请问为什么呢。当row["xxx"]为什么的时候row["xxx"] == DBNull.Value值才为真呢

C#如何使Load下的两段代码分开执行?

``` private void Origination_Load(object sender, EventArgs e) { progressBar1.Minimum = 0; progressBar1.Maximum = 50; progressBar1.MarqueeAnimationSpeed = 50; Counter.Start(); //启动计时器 } private void Origination_Load(object sender, EventArgs e) { bit = new Bitmap("25.jpg"); bit.MakeTransparent(Color.Blue); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.DrawImage((Image)bit, new Point(0, 0)); //在窗体上绘制图片 } ``` 第一段是一个进度条代码,第二个是非矩形窗体代码,都要写在Load事件下,这样会报错:已定义了一个名为“Origination_Load”的具有相同参数类型的成员。我改成了 ``` private void Origination_Load_1(object sender, EventArgs e) ``` 这样又会报错 “System.ArgumentNullException”类型的未经处理的异常出现在 System.Drawing.dll 中。 其他信息: 值不能为 null。

C#窗体窗体程序报错了:库没有注册

遇到了这个问题了,哪位打来知道的,怎么解决 ![图片说明](https://img-ask.csdn.net/upload/202003/19/1584604237_536138.png) 文字: 无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类型“IWshRuntimeLibrary.WshShell”。此操作失败的原因是对 IID 为“{41904400-BE18-11D3-A28B-00104BD35090}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 库没有注册。 (异常来自 HRESULT:0x8002801D (TYPE_E_LIBNOTREGISTERED))。

FileStream file显示路径名不能为null

![图片说明](https://img-ask.csdn.net/upload/201806/28/1530148171_778802.png)

将程序中的ascii码改为16进制应该怎么该!求指导

try { // Translate the passed message into ASCII and store it as a Byte array. Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response. // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); return responseData; //Console.WriteLine("Received: {0}", responseData); // Close everything. stream.Close(); } catch (ArgumentNullException e) {

PHP SoapClient异常,我做错了什么?

<div class="post-text" itemprop="text"> <p>I´ve recently started looking a web service calls using PHP. I can´t get the following rather simple snippet to work, instead the web service returns an exception. </p> <pre><code>&lt;?php $client = new SoapClient("http://www.webservicex.net/geoipservice.asmx?wsdl"); print($client-&gt;__soapCall("GetGeoIP", array('IP' =&gt; '83.251.30.62'))); ?&gt; </code></pre> <p>I´ve also tried the simpler <code>$client-&gt;GetGeoIP('83.251.30.62');</code> but they both yield the same result. </p> <p>Is there something wrong with my code? Exception below:</p> <pre><code>Fatal error: Uncaught SoapFault exception: [soap:Server] System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.ArgumentNullException: Value cannot be null. Parameter name: input at System.Text.RegularExpressions.Regex.IsMatch(String input) at WebserviceX.Service.Adapter.IPAdapter.CheckIP(String IP) at WebserviceX.Service.GeoIPService.GetGeoIP(String IPAddress) --- End of inner exception stack trace --- in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\isolda\test.php:16 Stack trace: #0 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\isolda\test.php(16): SoapClient- &gt;__soapCall('GetGeoIP', Array) #1 {main} thrown in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\isolda\test.php on line 16 </code></pre> </div>

C# dns.GetHostName() 获得不了主机名 一直是null

dns.GetHostName() 获得不了主机名 一直是null ArgumentNullException: Argument cannot be null. Parameter name: hostNameOrAddress System.Net.Dns.GetHostAddresses (System.String hostNameOrAddress) UDPServer.Start () (at Assets/Script/UDPServer.cs:30)

新手,求指导,下面用C#编的代码我不想用ascii码,直接想用16进制表示,该怎么改。

private void button_Send_Click(object sender, EventArgs e) { textBox4.Text = sendcommand(tcpClient, textBox3.Text); } private string sendcommand(TcpClient client ,String message) { try { // Translate the passed message into ASCII and store it as a Byte array. Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response. // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); return responseData; //Console.WriteLine("Received: {0}", responseData); // Close everything. stream.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); return ""; } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } //Console.WriteLine("\n Press Enter to continue..."); return ""; //Console.Read(); } private void textBox_Port_TextChanged(object sender, EventArgs e) { } } }

我在发布完unity3d游戏时遇到报错信息,但是在编辑器能正常运行,但是一发布就报错

我在发布完unity3d游戏时遇到报错信息,但是在编辑器能正常运行,但是一发布就报错,而且在Assets文件夹也多了一个XXX_Data文件夹,不知道是什么原因,请各位路过的大神帮我看看吧,谢谢啦 'Assets/mainGame_Data/Managed/Assembly-CSharp.dll' shouldn't be queried by IsAssemblyCompatible, missing IsInternalOrCompiledAssembly check ? UnityEditor.HostView:OnGUI()![图片说明](https://img-ask.csdn.net/upload/201612/14/1481711755_85585.png)

C#到PHP AES解密

<div class="post-text" itemprop="text"> <p>Hi i have c# sample of code but i can't turn it to php. İ tried to rewrite code but i can't do it. In my project other server encrypts data with c# and i have to decrypt it using PHP.</p> <p>I have password and salt value.</p> <p>Here is C# code includes encrypt and decrypt function. </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace EncryptionSample { public static class CipherUtility { public static string Encrypt(string plainText, string password, string salt) { if (plainText == null || plainText.Length &lt;= 0) { throw new ArgumentNullException("plainText"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } if (String.IsNullOrEmpty(salt)) { throw new ArgumentNullException("salt"); } byte[] encrypted; byte[] saltBytes = Encoding.UTF8.GetBytes(salt); using (Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(password, saltBytes)) { using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = derivedBytes.GetBytes(32); aesAlg.IV = derivedBytes.GetBytes(16); ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } } return Convert.ToBase64String(encrypted); } public static string Decrypt(string cipherValue, string password, string salt) { byte[] cipherText = Convert.FromBase64String(cipherValue); if (cipherText == null || cipherText.Length &lt;= 0) { throw new ArgumentNullException("cipherValue"); } if (String.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password"); } if (String.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("salt"); } string plaintext = null; byte[] saltBytes = Encoding.UTF8.GetBytes(salt); using (Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, saltBytes)) { using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = deriveBytes.GetBytes(32); aesAlg.IV = deriveBytes.GetBytes(16); ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } } return plaintext; } } } </code></pre> <p>My php code is here but i think i am totally wrong.</p> <pre><code>function decrypt($encrypted, $password, $salt) { // Build a 256-bit $key which is a SHA256 hash of $salt and $password. $key = hash('SHA256', $salt . $password, true); // Retrieve $iv which is the first 22 characters plus ==, base64_decoded. $iv = base64_decode(substr($encrypted, 0, 22) . '=='); // print_r($iv);die(); // Remove $iv from $encrypted. $encrypted = substr($encrypted, 22); //print_r($encrypted);die(); // Decrypt the data. rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding. $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4"); // Retrieve $hash which is the last 32 characters of $decrypted. $hash = substr($decrypted, -32); // Remove the last 32 characters from $decrypted. $decrypted = substr($decrypted, 0, -32); // Integrity check. If this fails, either the data is corrupted, or the password/salt was incorrect. if (md5($decrypted) != $hash) return false; return $decrypted; } </code></pre> </div>

vb.net做redis接口 TCPclient连接发送接收数据如何扩大容量 stream的读写缓存如何扩大

如果调用get key或set key数据过大会报错,只能接收小数据的get和set 而redis存储字符串最大能有512M,这个接口我不知道怎么扩大数据发送和接收的上限 Imports System.Drawing Imports System.IO Imports System.Net Imports System.Net.Sockets Imports System.Text Imports vRedis.Commands Public Class RedisClient     Private client As TcpClient     Private stream As NetworkStream     Private reply As RedisReply     Private command As IRedisCommand     Private memStream As MemoryStream     Public ReadOnly Property Host As String     Public ReadOnly Property Port As Integer     Public ReadOnly Property [Return] As Object         Get             Return reply.Value         End Get     End Property     Public Sub New(Optional host As String = "127.0.0.1", Optional port As Integer = 6379)         If IsNothing(host) Then             Throw New ArgumentNullException(NameOf(host))         End If         Me.Host = host         Me.Port = port         client = New TcpClient() _**        Try             client.Connect(host, port)             'TCPclient连接发送接收数据如何扩大容量             stream = client.GetStream()         Catch ex As Exception             Throw New RedisException("An existing connection was forcibly closed by remote host.")         End Try**_     End Sub     Public Sub Quit()         command = New QuitCommand()         Execute(command)     End Sub     Public Sub Append(key As String, value As String)         command = New AppendCommand() With {.Key = key, .Value = value}         Execute(command)     End Sub     Public Sub Del(ParamArray keys() As String)         command = New DelCommand() With {.Keys = keys}         Execute(command)     End Sub     Public Function Dump(key As String) As Byte()         command = New DumpCommand() With {.Key = key}         Execute(command)         If IsNothing(reply.Value) Then             Return Nothing         Else             Return Encoding.UTF8.GetBytes(reply.Value)         End If     End Function     Public Sub Echo(message As String)         command = New EchoCommand() With {.Message = message}         Execute(command)     End Sub     Public Function Exists(key As String) As Boolean         command = New ExistsCommand() With {.Key = key}         Execute(command)         Return reply.Value     End Function     Public Sub Expire(key As String, timeout As Integer)         command = New ExpireCommand() With {.Key = key, .Timeout = timeout}         Execute(command)     End Sub     Public Sub ExpireAt(key As String, ttl As DateTime)         command = New ExpireAtCommand() With {.Key = key, .TTL = (ttl - #1/1/1970#).TotalSeconds}         Execute(command)     End Sub     Public Function [Get](key As String) As String         command = New GetCommand() With {.Key = key}         Execute(command)         Return reply.Value     End Function     Public Sub PExpire(key As String, timeout As Integer)         command = New PExpireCommand() With {.Key = key, .Timeout = timeout}         Execute(command)     End Sub     Public Sub PExpireAt(key As String, ttl As DateTime)         command = New PExpireAtCommand() With {.Key = key, .TTL = (ttl - #1/1/1970#).TotalMilliseconds}         Execute(command)     End Sub     Public Sub Ping()         command = New PingCommand()         Execute(command)     End Sub     Public Sub Auth(password As String)         command = New AuthCommand() With {.Password = password}         Execute(command)     End Sub     Public Sub [Select](index As String)         command = New SelectCommand() With {.Index = index}         Execute(command)     End Sub     Public Sub [Set](key As String, value As String, Optional expireTime As TimeSpan? = Nothing, Optional override As Boolean? = Nothing)         command = New SetCommand() With {.Key = key, .Value = value, .ExpireTime = expireTime, .Override = override}         Execute(command)     End Sub     Public Function Time() As Date         command = New TimeCommand()         Execute(command)         'Return #1/1/1970#.AddSeconds(reply.Value(0)).ToLocalTime()     End Function     Private Sub Execute(command As IRedisCommand)         Dim bytes() As Byte = Encoding.UTF8.GetBytes(command.GetCommand() & vbCrLf)         Try **_            stream.Write(bytes, 0, bytes.Length)             stream.Flush()             'ReDim bytes(65535)             '这里stream的读写缓存如何扩大             ReDim bytes(client.ReceiveBufferSize)             stream.Read(bytes, 0, bytes.Length)**_             Dim result = Encoding.UTF8.GetString(bytes)             Select Case result(0)                 Case "$"                     Dim length = Convert.ToInt32(result.Substring(1, result.IndexOf(vbCrLf) - 1))                     If length = -1 Then                         reply = New RedisReply(RESPType.BulkString, Nothing)                     Else                         reply = New RedisReply(RESPType.BulkString, result.Substring(result.IndexOf(vbCrLf) + 2, length))                     End If                 Case "+"                     reply = New RedisReply(RESPType.SimpleString, result.Substring(1, result.IndexOf(vbCrLf) - 1))                 Case ":"                     reply = New RedisReply(RESPType.Integer, Convert.ToInt32(result.Substring(1, result.IndexOf(vbCrLf) - 1)))                 Case "-"                     reply = New RedisReply(RESPType.Error, result.Substring(1, result.IndexOf(vbCrLf) - 1))                     Throw New RedisException(reply.Value)                 Case "*"                     Dim count = Convert.ToInt32(result.Substring(1, result.IndexOf(vbCrLf) - 1))                     Dim items = result.Split(New Char() {vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries).ToList()                     items.RemoveAt(0)                     items.RemoveAll(Function(i) i.StartsWith("$"))                     items.RemoveAt(items.Count - 1)                     'reply = New RedisReply(RESPType.Array, items)             End Select         Catch ex As Exception             Throw New RedisException($"There is an internal error during executing '{command.GetCommand()}'.")         End Try     End Sub End Class

安全wcf(使用用户名密码验证器)不能从PHP客户端工作

<div class="post-text" itemprop="text"> <p>I have construct a simple secured wcf with <code>wsHttpBinding</code> in .Net C# (framework 4.5) and consume it from .Net C# (also) client and every thing work fine. <strong>But</strong> when I try to consume It from php (5.5) client by calling a method from the wcs service, the client not work <strong>and it has entered in an infinite loop and not showing any error message</strong>, just looping.<br><br> <strong>a.</strong> The following is my wcf <code>ServiceContract</code> and <code>OperationContract</code>'s:<br></p> <pre><code>namespace CenteralServices { [ServiceContract] public interface IAdminServices { [OperationContract] int Add(int x, int y); } } </code></pre> <p><br><strong>b.</strong> The following is the configueration file <code>Web.config</code> for the wcf:<br></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;system.serviceModel&gt; &lt;services&gt; &lt;service name= "CentralTicketServicesSystem.AdminSystem" behaviorConfiguration="customBehaviour"&gt; &lt;endpoint address="AdminServices" binding="wsHttpBinding" contract="CentralTicketServicesSystem.IAdminServices" bindingConfiguration="ServiceBinding" behaviorConfiguration="MyEndPointBehavior"&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8080/AdminServicesSystem" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="ServiceBinding" openTimeout="00:10:00" closeTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"&gt; &lt;security mode="Message" &gt; &lt;message clientCredentialType="UserName"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;behaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior name="MyEndPointBehavior"&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="customBehaviour"&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt; &lt;serviceAuthorization principalPermissionMode="Custom"&gt; &lt;authorizationPolicies&gt; &lt;add policyType="CentralServicesHost.AuthorizationPolicy, CentralServicesHost" /&gt; &lt;/authorizationPolicies&gt; &lt;/serviceAuthorization&gt; &lt;serviceCredentials&gt; &lt;userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CentralServicesHost.UserAuthentication, CentralServicesHost"/&gt; &lt;serviceCertificate findValue="15 63 10 5e b6 4b 4d 85 4b 2e 4d 5b ec 85 02 ec" storeLocation="LocalMachine" x509FindType="FindBySerialNumber" storeName="My"/&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; &lt;behavior name="mexBehaviour" &gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p><br><br> <strong>c.</strong> The following is <code>UserAuthentication</code> class:<br></p> <pre><code>namespace CentralServicesHost { public class UserAuthentication : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName"); if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); if (userName != "test" &amp;&amp; password != "test") throw new FaultException("Unknown Username or Incorrect Password."); } } } </code></pre> <p><br><br> <strong>d.</strong> The following is <code>AuthorizationPolicy</code> class:<br></p> <pre><code>namespace CentralServicesHost { public class AuthorizationPolicy : IAuthorizationPolicy { Guid _id = Guid.NewGuid(); // this method gets called after the authentication stage public bool Evaluate(EvaluationContext evaluationContext, ref object state) { // get the authenticated client identity IIdentity client = GetClientIdentity(evaluationContext); // set the custom principal evaluationContext.Properties["Principal"] = new CustomPrincipal(client); return true; } private IIdentity GetClientIdentity(EvaluationContext ec) { object obj; if (!ec.Properties.TryGetValue("Identities", out obj)) throw new Exception("No Identity found"); IList&lt;IIdentity&gt; identities = obj as IList&lt;IIdentity&gt;; if (identities == null || identities.Count &lt;= 0) throw new Exception("No Identity found"); return identities[0]; } public System.IdentityModel.Claims.ClaimSet Issuer { get { return ClaimSet.System; } } public string Id { get { return _id.ToString(); } } } } </code></pre> <p><br><br> <strong>e.</strong> The following is <code>CustomPrincipal</code> class:<br></p> <pre><code>namespace CentralServicesHost { class CustomPrincipal : IPrincipal { IIdentity _identity; string[] _roles; public CustomPrincipal(IIdentity identity) { _identity = identity; } // helper method for easy access (without casting) public static CustomPrincipal Current { get { return Thread.CurrentPrincipal as CustomPrincipal; } } public IIdentity Identity { get { return _identity; } } // return all roles public string[] Roles { get { EnsureRoles(); return _roles; } } // IPrincipal role check public bool IsInRole(string role) { EnsureRoles(); return (_roles != null) ? _roles.Contains(role) : false; } // read Role of user from database protected virtual void EnsureRoles() { using (var s = new SupportedMaterialsSystemEntities()) { _roles = new string[1] { "admin" }; } } } } </code></pre> <p><strong>f.</strong> The following is my php client code:<br></p> <pre><code>&lt;?php $options = array('soap_version' =&gt; SOAP_1_2, 'login' =&gt; 'test', 'password' =&gt; 'test'); $wsdl = "http://localhost:8080/AdminServicesSystem"; $client = new SoapClient($wsdl, $options); $obj = new stdClass; $obj-&gt;x = 3; $obj-&gt;y = 3; $retval = $client-&gt;Add($obj);//here the browser loops for infinite without any response. //var_dump($exc);//THIS POINT NOT REACHED //die(); $result = $retval-&gt;AddResult; echo $result; </code></pre> <p><strong><em>NOTES:</em></strong><br> <strong>1.</strong> My OS is Win. 8.1, and I'm using visual studio 2013 (as adminstrator) and php Wamp Server.<br> <strong>2.</strong> I tried both, hosting the wcf service in IIS 6.2 and console application but non of them changes my php client looping.<br> <strong>3.</strong> I have Created the self-signed certificate usin the IIS manager that stores it in my local machine.<br> <strong>4.</strong> When I change the <code>soap_version</code> in the php code from <code>SOAP_1_2</code> to <code>SOAP_1_1</code> I had <code>Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'.</code>.<br><br> <strong>Last Note:</strong><br> My .Net C# Client code is the following:<br></p> <pre><code> using (var svcProxy = new AdminServiceProxy.AdminServicesSystemClient()) { svcProxy.ClientCredentials.UserName.UserName = "test"; svcProxy.ClientCredentials.UserName.Password = "test"; Console.WriteLine(svcProxy.Add(1, 1));//the service works fine and print 2 } } </code></pre> <p><br> So agin, What is the right way to call a secured wcf (with <code>wsHttpBinding</code>) service from php.</p> </div>

关于百度收录的问题。

楼主我是新来的这家公司。 做的是新闻这一块。因为刚到没多久。 现在的情况是,百度无法收录我们公司新闻编辑发布的稿子。目前我们公司每天是发200篇新闻稿的样子。如图: ![图片说明](https://img-ask.csdn.net/upload/201505/25/1432543500_519985.png) 烦请各位大神帮忙解答解答。是什么导致的呢。 下面描述一下楼主的问题。 代码如下: #region 实时推送到百度 /// <summary> /// 实时推送到百度 /// </summary> /// <param name="sNewsUrl">相对URL地址</param> /// <param name="sIssueTime">发布时间格式:yyyy-MM-dd</param> public static void SendSiteBaiDu(List<Model.News_Issue> list) { StringBuilder sb = new StringBuilder(); string sHost = string.Format("http://{0}/", HttpContext.Current.Request.Url.Host); string sStr = string.Empty; BLL.Area_Province bllap = new BLL.Area_Province(); Model.Area_Province modelap; //sb.Append("POST /sitemap?site=xiaofei.china.com.cn&resource_name=sitemap&access_token=6kSXoZC7 HTTP/1.1 \r\n"); //sb.Append("User-Agent: curl/7.12.1 \r\n"); //sb.Append("Host: ping.baidu.com \r\n"); //sb.Append("Content-Length: 9666 \r\n"); sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); sb.Append("<urlset>\r\n"); foreach (Model.News_Issue m in list) { modelap = bllap.GetModel(m.ProvinceId); sStr = m.ProvinceId == 9 ? sHost : sHost + modelap.JianPin + "/"; sStr = m.NewsUrl.Split(':').Length > 1 ? m.NewsUrl : sStr + m.NewsUrl; sb.Append(" <url>\r\n"); sb.Append(" <loc><![CDATA["); sb.Append(sStr); sb.Append("]]></loc>\r\n"); sb.Append(" <lastmod>"); sb.Append(m.IssueTime); sb.Append("</lastmod>\r\n"); sb.Append(" <changefreq>always</changefreq>\r\n"); sb.Append(" <priority>0.8</priority>\r\n"); sb.Append(" </url>\r\n"); } sb.Append("</urlset>\r\n"); string postUrl = "http://ping.baidu.com/sitemap?site=xiaofei.china.com.cn&resource_name=sitemap&access_token=WLDkBcFq0zlJr4QF"; HttpXmlPostRequest(postUrl, sb.ToString(), Encoding.UTF8); } /// <summary> /// 实时推送到百度 /// </summary> /// <param name="sNewsUrl">相对URL地址</param> /// <param name="sIssueTime">发布时间格式:yyyy-MM-dd</param> public static void SendSiteBaiDu(string sNewsUrl, string sIssueTime, short? ProvinceId) { StringBuilder sb = new StringBuilder(); string sHost = string.Format("http://{0}/", HttpContext.Current.Request.Url.Host); string sStr = string.Empty; BLL.Area_Province bllap = new BLL.Area_Province(); Model.Area_Province modelap = bllap.GetModel(ProvinceId); sStr = ProvinceId == 9 ? sHost : sHost + modelap.JianPin + "/"; sStr = sNewsUrl.Split(':').Length > 1 ? sNewsUrl : sStr + sNewsUrl; //sb.Append("POST /sitemap?site=xiaofei.china.com.cn&resource_name=sitemap&access_token=6kSXoZC7 HTTP/1.1 \r\n"); //sb.Append("User-Agent: curl/7.12.1 \r\n"); //sb.Append("Host: ping.baidu.com \r\n"); //sb.Append("Content-Length: 9666 \r\n"); sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); sb.Append("<urlset>\r\n"); sb.Append(" <url>\r\n"); sb.Append(" <loc><![CDATA["); sb.Append(sStr); sb.Append("]]></loc>\r\n"); sb.Append(" <lastmod>"); sb.Append(sIssueTime); sb.Append("</lastmod>\r\n"); sb.Append(" <changefreq>always</changefreq>\r\n"); sb.Append(" <priority>0.8</priority>\r\n"); sb.Append(" </url>\r\n"); sb.Append("</urlset>\r\n"); string postUrl = "http://ping.baidu.com/sitemap?site=xiaofei.china.com.cn&resource_name=sitemap&access_token=WLDkBcFq0zlJr4QF"; HttpXmlPostRequest(postUrl, sb.ToString(), Encoding.UTF8); } /// <summary> /// HttpPost发送XML并返回响应 /// </summary> /// <param name="postUrl"></param> /// <param name="xml"></param> /// <param name="encoding"></param> /// <returns>Response响应</returns> public static void HttpXmlPostRequest(string postUrl, string postXml, Encoding encoding) { if (string.IsNullOrEmpty(postUrl)) { throw new ArgumentNullException("HttpXmlPost ArgumentNullException : postUrl IsNullOrEmpty"); } if (string.IsNullOrEmpty(postXml)) { throw new ArgumentNullException("HttpXmlPost ArgumentNullException : postXml IsNullOrEmpty"); } var request = (HttpWebRequest)WebRequest.Create(postUrl); byte[] byteArray = encoding.GetBytes(postXml); request.ContentLength = byteArray.Length; request.Method = "POST"; request.ContentType = "text/xml"; using (var requestStream = request.GetRequestStream()) { requestStream.Write(byteArray, 0, byteArray.Length); } //using (var responseStream = request.GetResponse().GetResponseStream()) //{ // return new StreamReader(responseStream, encoding).ReadToEnd(); //} //return retString; } #endregion }

asp.net 求助 ????????

public static object Eval(object container, string expression) { if (expression == null) { throw new ArgumentNullException("expression"); } expression = expression.Trim(); if (expression.Length == 0) { throw new ArgumentNullException("expression"); } if (container == null) { return null; } string[] expressionParts = expression.Split(expressionPartSeparator); return Eval(container, expressionParts); } private static object Eval(object container, string[] expressionParts) { object propertyValue = container; for (int i = 0; (i < expressionParts.Length) && (propertyValue != null); i++) { string propName = expressionParts[i]; if (propName.IndexOfAny(indexExprStartChars) < 0) { propertyValue = GetPropertyValue(propertyValue, propName); } else { propertyValue = GetIndexedPropertyValue(propertyValue, propName); } } return propertyValue; } public static string Eval(object container, string expression, string format) { object obj2 = Eval(container, expression); if ((obj2 == null) || (obj2 == DBNull.Value)) { return string.Empty; } if (string.IsNullOrEmpty(format)) { return obj2.ToString(); } return string.Format(format, obj2); } public static object GetDataItem(object container) { bool flag; return GetDataItem(container, out flag); } public virtual void DataBind() { this.DataBind(true); } protected virtual void DataBind(bool raiseOnDataBinding) { bool flag = false; if (this.IsBindingContainer) { bool flag2; object dataItem = DataBinder.GetDataItem(this, out flag2); if (flag2 && (this.Page != null)) { this.Page.PushDataBindingContext(dataItem);) flag = true; } } try { if (raiseOnDataBinding) { this.OnDataBinding(EventArgs.Empty); } this.DataBindChildren(); } finally { if (flag) { this.Page.PopDataBindingContext(); } } } C# code ? 1 谁能给我详细解释一下上面代码的意思

C#中异步调用委托BeginInvoke第一个参数问题。BeginInvoke(AsynCallback callback,object @object)

``` public delegate int TakesAWhileDelegate(int data, int ms); static void Main(string[] args) { TakesAWhileDelegate d1 = TakeAWhile; ; d1.BeginInvoke(1, 3000,TakesAWhileCompleted, d1); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(50); } Console.ReadKey(); } private static void TakesAWhileCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate; Trace.Assert(d1 != null, "Invalid object type"); int result = d1.EndInvoke(ar); Console.WriteLine("result:{0}",result); } static int TakeAWhile(int a,int ms) { Console.WriteLine("TakesAwhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++a; } } ``` 在这个方法里d1.BeginInvoke(1, 3000,TakesAWhileCompleted, d1),TakesAWhileCompleted不是需要一个IAsyncResult的参数吗?执行TakesAWhileCompleted方法时那个参数在哪?怎么传进去的?

将AES解密从php转换为c#

<div class="post-text" itemprop="text"> <p>I'm attempting to convert some working php code to c# in order to do aes decryption.</p> <p>Working PHP code:</p> <pre><code>function convert_from_hex($h) { $r=""; for ($i=0; $i&lt;strlen($h); $i+=2) if ((isset($h[$i])) &amp;&amp; (isset($h[$i+1]))) $r.=chr(hexdec($h[$i].$h[$i+1])); return $r; } function decryptAES($crypt_text, $key) { $crypt_text=convert_from_hex($crypt_text); // convert from hex $iv = substr($crypt_text, 0, 16); // extract iv $crypt_text = substr($crypt_text, 16); // extract iv $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); // decrypt @mcrypt_generic_init($td, $key, $iv); $package = @mdecrypt_generic($td, $crypt_text); mcrypt_generic_deinit($td); // close encryption mcrypt_module_close($td); $padqty=ord($package[strlen($package)-1]); // remove padding return substr($package, 0, strlen($package)-$padqty); } </code></pre> <p>Broken C# Code:</p> <pre><code>public string test() { string data = ConvertHex("149B56B7240DCFBE75B7B8B9452121B0E202A18286D4E8108C52DBB2149D820B980FFC7157470B9573AA660B2FAAB158E321023922191BCEA5D6E1376ABE6474"); string iv = data.Substring(0, 16); string toDecrypt = data.Substring(16); return AESEncryption.DecryptString(Encoding.Default.GetBytes(toDecrypt), Encoding.ASCII.GetBytes("C728DF944B666652"), Encoding.Default.GetBytes(iv)); } static public string DecryptString(byte[] cipherText, byte[] Key, byte[] IV) { // Check arguments. if (cipherText == null || cipherText.Length &lt;= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length &lt;= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length &lt;= 0) throw new ArgumentNullException("Key"); // Declare the string used to hold // the decrypted text. string plaintext = null; byte[] binaryDecryptedData; // Create an Aes object // with the specified key and IV. using (Aes aesAlg = Aes.Create()) { aesAlg.Mode = CipherMode.CBC; aesAlg.Padding = PaddingMode.PKCS7; aesAlg.KeySize = 128; aesAlg.BlockSize = 128; aesAlg.Key = Key; aesAlg.IV = IV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (MemoryStream srDecrypt = new MemoryStream()) { var buffer = new byte[1024]; var read = csDecrypt.Read(buffer, 0, buffer.Length); while (read &gt; 0) { srDecrypt.Write(buffer, 0, read); read = csDecrypt.Read(buffer, 0, buffer.Length); } csDecrypt.Flush(); binaryDecryptedData = srDecrypt.ToArray(); } } } } StringBuilder sb = new StringBuilder(); foreach (byte b in binaryDecryptedData) sb.Append((char)b); plaintext = sb.ToString(); return plaintext; } public string ConvertHex(String hexString) { StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; hexString.Length; i += 2) { string hs = hexString.Substring(i, 2); sb.Append((char)Convert.ToUInt32(hs, 16)); } return sb.ToString(); } </code></pre> <p>The correct output of the PHP code is: Fail (1) Not a valid Request or Command.</p> <p>The output of the C# code is: ²H,-§±uH¤¥±BÃrY¡|¡JJѾà`ªx"äommand</p> <p>I'm guessing that I have some sort of encoding issue, although I've tried many different options without success. Both code snippets are running on a windows box, so I believe the default encoding is windows-1252.</p> <p>Any suggestions would be appreciated.</p> <p>Replacement for ConvertHex which fixed my issues (thanks to owlstead's help)</p> <pre><code>public static byte[] StringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x =&gt; x % 2 == 0) .Select(x =&gt; Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } </code></pre> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐