Search Results

Search found 577 results on 24 pages for 'stringbuilder'.

Page 6/24 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • How can i optimize this c# code?

    - by Pandiya Chendur
    I have converted my Datatable to json string use the following method... public string GetJSONString(DataTable Dt) { string[] StrDc = new string[Dt.Columns.Count]; string HeadStr = string.Empty; for (int i = 0; i < Dt.Columns.Count; i++) { StrDc[i] = Dt.Columns[i].Caption; HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\","; } HeadStr = HeadStr.Substring(0, HeadStr.Length - 1); StringBuilder Sb = new StringBuilder(); Sb.Append("{\"" + Dt.TableName + "\" : ["); for (int i = 0; i < Dt.Rows.Count; i++) { string TempStr = HeadStr; Sb.Append("{"); for (int j = 0; j < Dt.Columns.Count; j++) { if (Dt.Rows[i][j].ToString().Contains("'") == true) { Dt.Rows[i][j] = Dt.Rows[i][j].ToString().Replace("'", ""); } TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString()); } Sb.Append(TempStr + "},"); } Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1)); Sb.Append("]}"); return Sb.ToString(); } Is this fair enough or still there is margin for optimization to make it execute faster.... Any suggestion...

    Read the article

  • template engine implementation

    - by qwerty
    I am currently building this small template engine. It takes a string containing the template in parameter, and a dictionary of "tags,values" to fill in the template. In the engine, I have no idea of the tags that will be in the template and the ones that won't. I am currently iterating (foreach) on the dictionnary, parsing my string that I have put in a string builder, and replacing the tags in the template by their corresponding value. Is there a more efficient/convenient way of doing this? I know the main drawback here is that the stringbuilder is parsed everytime entirely for each tag, which is quite bad... (I am also checking, though not included in the sample, after the process that my template does not contain any tag anymore. They are all formated in the same way: @@tag@@) //Dictionary<string, string> tagsValueCorrespondence; //string template; StringBuilder outputBuilder = new StringBuilder(template); foreach (string tag in tagsValueCorrespondence.Keys) { outputBuilder.Replace(tag, tagsValueCorrespondence[tag]); } template = outputBuilder.ToString(); Responses: @Marc: string template = "Some @@foobar@@ text in a @@bar@@ template"; StringDictionary data = new StringDictionary(); data.Add("foo", "value1"); data.Add("bar", "value2"); data.Add("foo2bar", "value3"); Output: "Some text in a value2 template" instead of: "Some @@foobar@@ text in a value2 template"

    Read the article

  • ADO.NET Batch Insert with over 2000 parameters

    - by Liming
    Hello all, I'm using Enterprise library, but the idea is the same. I have a SqlStringCommand and the sql is constructed using StringBuilder in the forms of "insert into table (column1, column2, column3) values (@param1-X, @param2-X, @parm3-X)"+" " where "X" represents a "for loop" about 700 rows StringBuilder sb = new StringBuilder(); for(int i=0; i<700; i++) { sb.Append("insert into table (column1, column2, column3) values (@param1-"+i+", @param2-"+i, +",@parm3-"+i+") " ); } followed by constructing a command object injecting all the parameters w/ values into it. Essentially, 700 rows with 3 parameters, I ended up with 2100 parameters for this "one sql" Statement. It ran fine for about a few days and suddenly I got this error =============================================================== A severe error occurred on the current command. The results, if any, should be discarded. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNon Any pointers are greatly appreciated.

    Read the article

  • C# - File Encoding Problem.

    - by user301330
    Hello, I'm have a StringBuilder that is writing content to a file. Towards the end of each file, I'm writing the copyright symbol. Oddly, I have noticed that whenever the copyright symbol is written, it is preceeded by a "Â". My code that generates the content of the file looks like this: using (StringWriter stringWriter = new StringWriter()) { stringWriter = GetFileContent(); string targetPath = ConfigurationManager.AppSettings["TargetPath"]; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { StringBuilder sb = new StringBuilder(stringWriter.ToString()); // Attempted fix string content = sb.ToString(); content = content.Replace("Â", ""); streamWriter.Write(content); } } As you can tell, I tried to do a find-and-replace. In the process, I noticed that a "Â" was not in the content itself. This makes me believe there is something occurring in the streamWriter. However, I'm not sure what it could be. Can someone please tell me why a "Â" would be popping up before the "©" symbol and how to fix it? I believe it has something to do with encoding, but I'm not sure Thank you!

    Read the article

  • How do I import and call unmanaged C dll with ansi string "char *" pointer string from VB.net?

    - by Warren P
    I have written my own function, which in C would be declared like this, using standard Win32 calling conventions: int Thing( char * command, char * buffer, int * BufSize); I have the following amount of VB figured out, which should import the dll and call this function, wrapping it up to make it easy to call Thing("CommandHere",GetDataBackHere): Imports Microsoft.VisualBasic Imports System.Runtime.InteropServices Imports System Imports System.Text Namespace dllInvocationSpace Public Class dllInvoker ' tried attributes but could not make it build: ' <DllImport("Thing1.dll", False, CallingConvention.Cdecl, CharSet.Ansi, "Baton", True, True, False, True)> Declare Ansi Function Thing Lib "Thing1.dll" (ByVal Command As String, ByRef Buffer As String, ByRef BufferLength As Integer) Shared Function dllCall(ByVal Command As String, ByRef Results As String) As Integer Dim Buffer As StringBuilder = New StringBuilder(65536) Dim retCode As Integer Dim bufsz As Integer bufsz = 65536 retCode = Thing(Command, Buffer, bufsz) Results = Buffer Return retCode End Function End Class End Namespace The current code doesn't build, because although I think I should be able to create a "buffer" that the C Dll can write data back into using a string builder, I haven't got it quite right. (Value of type System.Text.STringBuilder cannot be converted to 'String'). I have looked all over the newsgroups and forums and can not find an example where the C dll needs to pass between 1 and 64kbytes of data back (char *buffer, int bufferlen) to visual basic.net.

    Read the article

  • How do I get a window caption?

    - by P.Brian.Mackey
    I would like to get a Window Caption as given by spy++ (highlighted in red) I have code to do this (or so I thought)...but it seems to work pretty awful....in some cases 1% of the time... public delegate bool EnumDelegate(IntPtr hWnd, int lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll", EntryPoint = "GetWindowText", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount); [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam); static List<NativeWindow> collection = new List<NativeWindow>(); public static NativeWindow GetAppNativeMainWindow() { GetNativeWindowHelper.EnumDelegate filter = delegate(IntPtr hWnd, int lParam) { StringBuilder strbTitle = new StringBuilder(255); int nLength = GetNativeWindowHelper.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1); string strTitle = strbTitle.ToString(); if (!string.IsNullOrEmpty(strTitle)) { if (strTitle.ToLower().StartsWith("window title | my application")) { NativeWindow window = new NativeWindow(); window.AssignHandle(hWnd); collection.Add(window); return false;//stop enumerating } } return true;//continue enumerating }; GetNativeWindowHelper.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero); if (collection.Count != 1) { //log error ReleaseWindow(); return null; } else return collection[0]; } public static void ReleaseWindow() { foreach (var item in collection) { item.ReleaseHandle(); } }

    Read the article

  • C# TcpClient, getting back the entire response from a telnet device

    - by Dan Bailiff
    I'm writing a configuration tool for a device that can communicate via telnet. The tool sends a command via TcpClient.GetStream().Write(...), and then checks for the device response via TcpClient.GetStream().ReadByte(). This works fine in unit tests or when I'm stepping through code slowly. If I run the config tool such that it performs multiple commands consecutively, then the behavior of the read is inconsistent. By inconsistent I mean sometimes the data is missing, incomplete or partially garbled. So even though the device performed the operation and responded, my code to check for the response was unreliable. I "fixed" this problem by adding a Thread.Sleep to make sure the read method waits long enough for the device to complete its job and send back the whole response (in this case 1.5 seconds was a safe amount). I feel like this is wrong, blocking everything for a fixed time, and I wonder if there is a better way to get the read method to wait only long enough to get the whole response from the device. private string Read() { if (!tcpClient.Connected) throw (new Exception("Read() failed: Telnet connection not available.")); StringBuilder sb = new StringBuilder(); do { ParseTelnet(ref sb); System.Threading.Thread.Sleep(1500); } while (tcpClient.Available > 0); return sb.ToString(); } private void ParseTelnet(ref StringBuilder sb) { while (tcpClient.Available > 0) { int input = tcpClient.GetStream().ReadByte(); switch (input) { // parse the input // ... do other things in special cases default: sb.Append((char)input); break; } } }

    Read the article

  • Add additional content to the middle of string from within a method

    - by Sammy T
    I am working with a log file and I have a method which is creating a generic entry in to the log. The generic log entry looks like this: public StringBuilder GetLogMessage(LogEventType logType, object message) { StringBuilder logEntry = new StringBuilder(); logEntry.AppendFormat("DATE={0} ", DateTime.Now.ToString("dd-MMM-yyyy", new CultureInfo(CommonConfig.EnglishCultureCode))); logEntry.AppendFormat("TIME={0} ", DateTime.Now.ToString("HH:mm:ss", new CultureInfo(CommonConfig.EnglishCultureCode))); logEntry.AppendFormat("ERRORNO={0} ", base.RemoteIPAddress.ToString().Replace(".", string.Empty)); logEntry.AppendFormat("IP={0}", base.RemoteIPAddress.ToString()); logEntry.AppendFormat("LANG={0} ", base.Culture.TwoLetterISOLanguageName); logEntry.AppendFormat("PNR={0} ", this.RecordLocator); logEntry.AppendFormat("AGENT={0} ", base.UserAgent); logEntry.AppendFormat("REF={0} ", base.Referrer); logEntry.AppendFormat("SID={0} ", base.CurrentContext.Session.SessionID); logEntry.AppendFormat("LOGTYPE={0} ", logType.ToString() ); logEntry.AppendFormat("MESSAGE={0} ", message); return logEntry; } What would be the best approach for adding additional parameters before "MESSAGE="? For example if I wanted to add "MODULE=" from a derived class when the GetLogMessage is being run. Would a delegate be what I am looking for or marking the method as virtual and overriding it or do I need something entirely different? Any help would be appreciated.

    Read the article

  • C# Attribute XmlIgnore and XamlWriter class - XmlIgnore not working

    - by Horst Walter
    I have a class, containing a property Brush MyBrush marked as [XmlIgnore]. Nevertheless it is serialized in the stream causing trouble when trying to read via XamlReader. I did some tests, e.g. when changing the visibility (to internal) of the Property it is gone in the stream. Unfortunately I cannot do this in my particular scenario. Did anybody have the same issue and? Do you see any way to work around this? Remark: C# 4.0 as far I can tell This is a method from my Unit Test where I do test the XamlSerialization: // buffer to a StringBuilder StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, settings); XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(writer) {XamlWriterMode = XamlWriterMode.Expression}; XamlWriter.Save(testObject, manager); xml = sb.ToString(); Assert.IsTrue(!String.IsNullOrEmpty(xml) && !String.IsNullOrEmpty(xml), "Xaml Serialization failed for " + testObject.GetType() + " no xml string available"); xml = sb.ToString(); MemoryStream ms = xml.StringToStream(); object root = XamlReader.Load(ms); Assert.IsTrue(root != null, "After reading from MemoryStream no result for Xaml Serialization"); In one of my classes I use the Property Brush. In the above code this Unit Tests fails because of a Brush object not serializable is the value. When I remove the Setter (as below, the Unit Test passes. Using the XmlWriter (basically same test as above) it works. In the StringBuffer sb I can see that Property Brush is serialized when the Setter is there and not when removed (most likely another check ignoring the Property because of no setter). Other Properties with [XmlIgnore] are ignored as intended. [XmlIgnore] public Brush MyBrush { get { ..... } // removed because of problem with Serialization // set { ... } }

    Read the article

  • How to restrict a content of string to less than 4MB and save that string in DB using C#

    - by Pranay B
    I'm working on a project where I need to get the Text data from pdf files and dump the whole text in a DB column. With the help of iTextsharp, I got the data and referred it String. But now I need to check whether the string exceeds the 4MB limit or not and if it is exceeding then accept the string data which is less than 4MB in size. This is my code: internal string ReadPdfFiles() { // variable to store file path string filePath = null; // open dialog box to select file OpenFileDialog file = new OpenFileDialog(); // dilog box title name file.Title = "Select Pdf File"; //files to be accepted by the user. file.Filter = "Pdf file (*.pdf)|*.pdf|All files (*.*)|*.*"; // set initial directory of computer system file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // set restore directory file.RestoreDirectory = true; // execute if block when dialog result box click ok button if (file.ShowDialog() == DialogResult.OK) { // store selected file path filePath = file.FileName.ToString(); } //file path /// use a string array and pass all the pdf for searching //String filePath = @"D:\Pranay\Documentation\Working on SSAS.pdf"; try { //creating an instance of PdfReader class using (PdfReader reader = new PdfReader(filePath)) { //creating an instance of StringBuilder class StringBuilder text = new StringBuilder(); //use loop to specify how many pages to read. //I started from 5th page as Piyush told for (int i = 5; i <= reader.NumberOfPages; i++) { //Read the pdf text.Append(PdfTextExtractor.GetTextFromPage(reader, i)); }//end of for(i) int k = 4096000; //Test whether the string exceeds the 4MB if (text.Length < k) { //return the string text1 = text.ToString(); } //end of if } //end of using } //end try catch (Exception ex) { MessageBox.Show(ex.Message, "Please Do select a pdf file!!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } //end of catch return text1; } //end of ReadPdfFiles() method Do help me!

    Read the article

  • Accept All Cookies via HttpClient

    - by Vinay
    So this is currently how my app is set up: 1.) Login Activity. 2.) Once logged in, other activities may be fired up that use PHP scripts that require the cookies sent from logging in. I am using one HttpClient across my app to ensure that the same cookies are used, but my problem is that I am getting 2 of the 3 cookies rejected. I do not care about the validity of the cookies, but I do need them to be accepted. I tried setting the CookiePolicy, but that hasn't worked either. This is what logcat is saying: 11-26 10:33:57.613: WARN/ResponseProcessCookies(271): Cookie rejected: "[version: 0] [name: cookie_user_id][value: 1][domain: www.trackallthethings.com][path: trackallthethings][expiry: Sun Nov 25 11:33:00 CST 2012]". Illegal path attribute "trackallthethings". Path of origin: "/mobile-api/login.php" 11-26 10:33:57.593: WARN/ResponseProcessCookies(271): Cookie rejected: "[version: 0][name: cookie_session_id][value: 1985208971][domain: www.trackallthethings.com][path: trackallthethings][expiry: Sun Nov 25 11:33:00 CST 2012]". Illegal path attribute "trackallthethings". Path of origin: "/mobile-api/login.php" I am sure that my actual code is correct (my app still logs in correctly, just doesn't accept the aforementioned cookies), but here it is anyway: HttpGet httpget = new HttpGet(//MY URL); HttpResponse response; response = Main.httpclient.execute(httpget); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); From here I use the StringBuilder to simply get the String of the response. Nothing fancy. I understand that the reason my cookies are being rejected is because of an "Illegal path attribute" (I am running a script at /mobile-api/login.php whereas the cookie will return with a path of just "/" for trackallthethings), but I would like to accept the cookies anyhow. Is there a way to do this?

    Read the article

  • Getting the full-name of the current user, returns an empty string (C#/C++)

    - by Nir
    I try to get the full-name of the current log-in user (Fullname, not username). The following code C#, C++ works fine but on XP computers not connected to the Net, I get empty string as result if I run it ~20 minutes after login (It runs OK whithin the first ~20 minutes after login) A Win32 API (GetUserNameEx) is used rather that PrincipalContext since it PrincipalContext may takes up to 15 seconds when working offline. Any Help why am I getting an empty string as result though a user full name is specified??? - C# Code public static string CurrentUserFullName { get { const int EXTENDED_NAME_FORMAT_NAME_DISPLAY = 3; StringBuilder userName = new StringBuilder(256); uint length = (uint) userName.Capacity; string ret; if (GetUserNameEx(EXTENDED_NAME_FORMAT_NAME_DISPLAY, userName, ref length)) { ret = userName.ToString(); } else { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception("GetUserNameEx Failed. Error code - " + errorCode); } return ret; } } [DllImport("Secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetUserNameEx(int nameFormat, StringBuilder lpNameBuffer, ref uint lpnSize); - Code in C++ #include "stdafx.h" #include <windows.h> #define SECURITY_WIN32 #include <Security.h> #pragma comment( lib, "Secur32.lib" ) int _tmain(int argc, _TCHAR* argv[]) { char szName[100]; ULONG nChars = sizeof( szName ); if ( GetUserNameEx( NameDisplay, szName, &nChars ) ) { printf( "Name: %s\n", szName); } else { printf( "Failed to GetUserNameEx\n" ); printf( "%d\n", GetLastError() ); } return 0; }

    Read the article

  • WinRT WebView and Cookies

    - by javarg
    Turns out that WebView Control in WinRT is much more limited than it’s counterpart in WPF/Silverlight. There are some great articles out there in how to extend the control in order for it to support navigation events and some other features. For a personal project I'm working on, I needed to grab cookies a Web Site generated for the user. Basically, after a user authenticated to a Web Site I needed to get the authentication cookies and generate some extra requests on her behalf. In order to do so, I’ve found this great article about a similar case using SharePoint and Azure ACS. The secret is to use a p/invoke to native InternetGetCookieEx to get cookies for the current URL displayed in the WebView control.   void WebView_LoadCompleted(object sender, NavigationEventArgs e) { var urlPattern = "http://someserver.com/somefolder"; if (e.Uri.ToString().StartsWith(urlPattern)) { var cookies = InternetGetCookieEx(e.Uri.ToString()); // Do something with the cookies } } static string InternetGetCookieEx(string url) { uint sizeInBytes = 0; // Gets capacity length first InternetGetCookieEx(url, null, null, ref sizeInBytes, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero); uint bufferCapacityInChars = (uint)Encoding.Unicode.GetMaxCharCount((int)sizeInBytes); // Now get cookie data var cookieData = new StringBuilder((int)bufferCapacityInChars); InternetGetCookieEx(url, null, cookieData, ref bufferCapacityInChars, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero); return cookieData.ToString(); }   Function import using p/invoke follows: const int INTERNET_COOKIE_HTTPONLY = 0x00002000; [DllImport("wininet.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved); Enjoy!

    Read the article

  • Uploading and Importing CSV file to SQL Server in ASP.NET WebForms

    - by Vincent Maverick Durano
    Few weeks ago I was working with a small internal project  that involves importing CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project. In this post I will demonstrate how to upload and import CSV file to SQL Server database. As some may have already know, importing CSV file to SQL Server is easy and simple but difficulties arise when the CSV file contains, many columns with different data types. Basically, the provider cannot differentiate data types between the columns or the rows, blindly it will consider them as a data type based on first few rows and leave all the data which does not match the data type. To overcome this problem, I used schema.ini file to define the data type of the CSV file and allow the provider to read that and recognize the exact data types of each column. Now what is schema.ini? Taken from the documentation: The Schema.ini is a information file, used to define the data structure and format of each column that contains data in the CSV file. If schema.ini file exists in the directory, Microsoft.Jet.OLEDB provider automatically reads it and recognizes the data type information of each column in the CSV file. Thus, the provider intelligently avoids the misinterpretation of data types before inserting the data into the database. For more information see: http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx Points to remember before creating schema.ini:   1. The schema information file, must always named as 'schema.ini'.   2. The schema.ini file must be kept in the same directory where the CSV file exists.   3. The schema.ini file must be created before reading the CSV file.   4. The first line of the schema.ini, must the name of the CSV file, followed by the properties of the CSV file, and then the properties of the each column in the CSV file. Here's an example of how the schema looked like: [Employee.csv] ColNameHeader=False Format=CSVDelimited DateTimeFormat=dd-MMM-yyyy Col1=EmployeeID Long Col2=EmployeeFirstName Text Width 100 Col3=EmployeeLastName Text Width 50 Col4=EmployeeEmailAddress Text Width 50 To get started lets's go a head and create a simple blank database. Just for the purpose of this demo I created a database called TestDB. After creating the database then lets go a head and fire up Visual Studio and then create a new WebApplication project. Under the root application create a folder called UploadedCSVFiles and then place the schema.ini on that folder. The uploaded CSV files will be stored in this folder after the user imports the file. Now add a WebForm in the project and set up the HTML mark up and add one (1) FileUpload control one(1)Button and three (3) Label controls. After that we can now proceed with the codes for uploading and importing the CSV file to SQL Server database. Here are the full code blocks below: 1: using System; 2: using System.Data; 3: using System.Data.SqlClient; 4: using System.Data.OleDb; 5: using System.IO; 6: using System.Text; 7:   8: namespace WebApplication1 9: { 10: public partial class CSVToSQLImporting : System.Web.UI.Page 11: { 12: private string GetConnectionString() 13: { 14: return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; 15: } 16: private void CreateDatabaseTable(DataTable dt, string tableName) 17: { 18:   19: string sqlQuery = string.Empty; 20: string sqlDBType = string.Empty; 21: string dataType = string.Empty; 22: int maxLength = 0; 23: StringBuilder sb = new StringBuilder(); 24:   25: sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName)); 26:   27: for (int i = 0; i < dt.Columns.Count; i++) 28: { 29: dataType = dt.Columns[i].DataType.ToString(); 30: if (dataType == "System.Int32") 31: { 32: sqlDBType = "INT"; 33: } 34: else if (dataType == "System.String") 35: { 36: sqlDBType = "NVARCHAR"; 37: maxLength = dt.Columns[i].MaxLength; 38: } 39:   40: if (maxLength > 0) 41: { 42: sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength)); 43: } 44: else 45: { 46: sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType)); 47: } 48: } 49:   50: sqlQuery = sb.ToString(); 51: sqlQuery = sqlQuery.Trim().TrimEnd(','); 52: sqlQuery = sqlQuery + " )"; 53:   54: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 55: { 56: sqlConn.Open(); 57: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 58: sqlCmd.ExecuteNonQuery(); 59: sqlConn.Close(); 60: } 61:   62: } 63: private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter) 64: { 65: string sqlQuery = string.Empty; 66: StringBuilder sb = new StringBuilder(); 67:   68: sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName)); 69: sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath)); 70: sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter)); 71:   72: sqlQuery = sb.ToString(); 73:   74: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 75: { 76: sqlConn.Open(); 77: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 78: sqlCmd.ExecuteNonQuery(); 79: sqlConn.Close(); 80: } 81: } 82: protected void Page_Load(object sender, EventArgs e) 83: { 84:   85: } 86: protected void BTNImport_Click(object sender, EventArgs e) 87: { 88: if (FileUpload1.HasFile) 89: { 90: FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName); 91: if (fileInfo.Name.Contains(".csv")) 92: { 93:   94: string fileName = fileInfo.Name.Replace(".csv", "").ToString(); 95: string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name; 96:   97: //Save the CSV file in the Server inside 'MyCSVFolder' 98: FileUpload1.SaveAs(csvFilePath); 99:   100: //Fetch the location of CSV file 101: string filePath = Server.MapPath("UploadedCSVFiles") + "\\"; 102: string strSql = "SELECT * FROM [" + fileInfo.Name + "]"; 103: string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'"; 104:   105: // load the data from CSV to DataTable 106:   107: OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString); 108: DataTable dtCSV = new DataTable(); 109: DataTable dtSchema = new DataTable(); 110:   111: adapter.FillSchema(dtCSV, SchemaType.Mapped); 112: adapter.Fill(dtCSV); 113:   114: if (dtCSV.Rows.Count > 0) 115: { 116: CreateDatabaseTable(dtCSV, fileName); 117: Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName); 118:   119: string fileFullPath = filePath + fileInfo.Name; 120: LoadDataToDatabase(fileName, fileFullPath, ","); 121:   122: Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName); 123: } 124: else 125: { 126: LBLError.Text = "File is empty."; 127: } 128: } 129: else 130: { 131: LBLError.Text = "Unable to recognize file."; 132: } 133:   134: } 135: } 136: } 137: } The code above consists of three (3) private methods which are the GetConnectionString(), CreateDatabaseTable() and LoadDataToDatabase(). The GetConnectionString() is a method that returns a string. This method basically gets the connection string that is configured in the web.config file. The CreateDatabaseTable() is method that accepts two (2) parameters which are the DataTable and the filename. As the method name already suggested, this method automatically create a Table to the database based on the source DataTable and the filename of the CSV file. The LoadDataToDatabase() is a method that accepts three (3) parameters which are the tableName, fileFullPath and delimeter value. This method is where the actual saving or importing of data from CSV to SQL server happend. The codes at BTNImport_Click event handles the uploading of CSV file to the specified location and at the same time this is where the CreateDatabaseTable() and LoadDataToDatabase() are being called. If you notice I also added some basic trappings and validations within that event. Now to test the importing utility then let's create a simple data in a CSV format. Just for the simplicity of this demo let's create a CSV file and name it as "Employee" and add some data on it. Here's an example below: 1,VMS,Durano,[email protected] 2,Jennifer,Cortes,[email protected] 3,Xhaiden,Durano,[email protected] 4,Angel,Santos,[email protected] 5,Kier,Binks,[email protected] 6,Erika,Bird,[email protected] 7,Vianne,Durano,[email protected] 8,Lilibeth,Tree,[email protected] 9,Bon,Bolger,[email protected] 10,Brian,Jones,[email protected] Now save the newly created CSV file in some location in your hard drive. Okay let's run the application and browse the CSV file that we have just created. Take a look at the sample screen shots below: After browsing the CSV file. After clicking the Import Button Now if we look at the database that we have created earlier you'll notice that the Employee table is created with the imported data on it. See below screen shot.   That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,CSV,SQL,C#,ADO.NET

    Read the article

  • C # - a variable using the Encrypt md5

    - by Guilherme Cardoso
    When we are dealing with more sensitive data and important as a keyword, it is not appropriate at all stores them in database without encrypting for security reasons.  For this we use MD5  MD5 is an algorithm that allow us to encript an string, but doesn't leave us desencrypt it (not sure if it is already possible, but at least I know there are many databases already having a record).  The method below will return us a variable encrypted with md5. For example: md5_encriptar (pontonetpt.com ");   The result will be: 34efe85d338075834ad41803eb08c0df This way we save tthese encrypted data into a database, and then to make comparisons we often use the method to compare with the records kept. public string md5_encrypt(string md5) { System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(md5); bs = x.ComputeHash(bs); System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); } string password = s.ToString(); return password; }

    Read the article

  • HTML Parsing for multiple input files using java code [closed]

    - by mkp
    FileReader f0 = new FileReader("123.html"); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(f0); while((temp1=br.readLine())!=null) { sb.append(temp1); } String para = sb.toString().replaceAll("<br>","\n"); String textonly = Jsoup.parse(para).text(); System.out.println(textonly); FileWriter f1=new FileWriter("123.txt"); char buf1[] = new char[textonly.length()]; textonly.getChars(0,textonly.length(),buf1,0); for(i=0;i<buf1.length;i++) { if(buf1[i]=='\n') f1.write("\r\n"); f1.write(buf1[i]); } I've this code but it is taking only one file at a time. I want to select multiple files. I've 2000 files and I've given them numbering name from 1 to 2000 as "1.html". So I want to give for loop like for(i=1;i<=2000;i++) and after executing separate txt file should be generated.

    Read the article

  • Unit test SHA256 wrapper queries

    - by Sam Leach
    I am just beginning to write unit tests. So please bear with me. I have the following SHA256 wrapper. public static string SHA256(string plainText) { StringBuilder sb = new StringBuilder(); SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider(); var hashedBytes = provider.ComputeHash(Encoding.UTF8.GetBytes(plainText)); for (int i = 0; i < hashedBytes.Length; i++) { sb.Append(hashedBytes[i].ToString("x2").ToLower()); } return sb.ToString(); } Do I want to be testing it? If so, what do you recommend? My thought process is as follows: What logic is there here. The answer is my for loop and ToString("x2") so from my understanding I want to be testing this part? I can assume Encoding.UTF8.GetBytes(plainText) works. Correct assumption? I can assume SHA256CryptoServiceProvider.ComputeHash() works. Correct assumption? I want to be only testing my logic. In this case is limited to the printing of hex encoded hash. Correct? Thanks.

    Read the article

  • How will closures in Java impact the Java Community?

    - by Ryan Delucchi
    It is one of the most talked about features planned for Java: Closures. Many of us have been longing for them. Some of us (including I) have grown a bit impatient and have turned to scripting languages to fill the void. But, once closures have finally arrived to Java: how will they effect the Java Community? Will the advancement of VM-targetted scripting languages slow to a crawl, stay the same, or acclerate? Will people flock to the new closure syntax, thus turning Java code-bases all-around into more functionally structured implementations? Will we only see closures sprinkled in Java throughout? What will be the effect on tool/IDE support? How about performance? And finally, what will it mean for Java's continued adoption, as a language, compared with other languages that are rising in popularity? To provide an example of one of the latest proposed Java Closure syntax specs: public interface StringOperation { String invoke(String s); } // ... (new StringOperation() { public invoke(String s) { new StringBuilder(s).reverse().toString(); } }).invoke("abcd"); would become ... String reversed = { String s => new StringBuilder(s).reverse().toString() }.invoke("abcd"); [source: http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]

    Read the article

  • Logging Output of Azure Startup Tasks to the Event Log

    - by Your DisplayName here!
    This can come in handy when troubleshooting: using System; using System.Diagnostics; using System.Text;   namespace Thinktecture.Azure {     class Program     {         static EventLog _eventLog = new EventLog("Application", ".", "StartupTaskShell");         static StringBuilder _out = new StringBuilder(64);         static StringBuilder _err = new StringBuilder(64);           static int Main(string[] args)         {             if (args.Length != 1)             {                 Console.WriteLine("Invalid arguments: " + String.Join(", ", args));                 _eventLog.WriteEntry("Invalid arguments: " + String.Join(", ", args));                                 return -1;             }               var task = args[0];               ProcessStartInfo info = new ProcessStartInfo()             {                 FileName = task,                 WorkingDirectory = Environment.CurrentDirectory,                 UseShellExecute = false,                 ErrorDialog = false,                 CreateNoWindow = true,                 RedirectStandardOutput = true,                 RedirectStandardError = true             };               var process = new Process();             process.StartInfo = info;               process.OutputDataReceived += (s, e) =>                 {                     if (e.Data != null)                     {                         _out.AppendLine(e.Data);                     }                 };             process.ErrorDataReceived += (s, e) =>                 {                     if (e.Data != null)                     {                         _err.AppendLine(e.Data);                     }                 };               process.Start();             process.BeginOutputReadLine();             process.BeginErrorReadLine();             process.WaitForExit();               var outString = _out.ToString();             var errString = _err.ToString();               if (!string.IsNullOrWhiteSpace(outString))             {                 outString = String.Format("Standard Out for {0}\n\n{1}", task, outString);                 _eventLog.WriteEntry(outString, EventLogEntryType.Information);             }               if (!string.IsNullOrWhiteSpace(errString))             {                 errString = String.Format("Standard Err for {0}\n\n{1}", task, errString);                 _eventLog.WriteEntry(errString, EventLogEntryType.Error);             }               return 0;         }     } } You then wrap your startup tasks with the StartupTaskShell and you’ll be able to see stdout and stderr in the application event log.

    Read the article

  • ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND

    - by Telanor
    I've stared at this for at least half an hour now and I cannot figure out what directx is complaining about. I know this error normally means you put float3 instead of a float4 or something like that, but I've checked over and over and as far as I can tell, everything matches. This is the full error message: D3D11: ERROR: ID3D11DeviceContext::DrawIndexed: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (COLOR,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND ] This is the vertex shader's input signature as seen in PIX: // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------ ------ // POSITION 0 xyz 0 NONE float xyz // NORMAL 0 xyz 1 NONE float // COLOR 0 xyzw 2 NONE float The HLSL structure looks like this: struct VertexShaderInput { float3 Position : POSITION0; float3 Normal : NORMAL0; float4 Color: COLOR0; }; The input layout, from PIX, is: The C# structure holding the data looks like this: [StructLayout(LayoutKind.Sequential)] public struct PositionColored { public static int SizeInBytes = Marshal.SizeOf(typeof(PositionColored)); public static InputElement[] InputElements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0) }; Vector3 position; Vector3 normal; Vector4 color; #region Properties ... #endregion public PositionColored(Vector3 position, Vector3 normal, Vector4 color) { this.position = position; this.normal = normal; this.color = color; } public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append(" Position="); sb.Append(position); sb.Append(" Color="); sb.Append(Color); return sb.ToString(); } } SizeInBytes comes out to 40, which is correct (4*3 + 4*3 + 4*4 = 40). Can anyone find where the mistake is?

    Read the article

  • DataTable to JSON

    - by Joel Coehoorn
    I recently needed to serialize a datatable to JSON. Where I'm at we're still on .Net 2.0, so I can't use the JSON serializer in .Net 3.5. I figured this must have been done before, so I went looking online and found a number of different options. Some of them depend on an additional library, which I would have a hard time pushing through here. Others require first converting to List<Dictionary<>>, which seemed a little awkward and needless. Another treated all values like a string. For one reason or another I couldn't really get behind any of them, so I decided to roll my own, which is posted below. As you can see from reading the //TODO comments, it's incomplete in a few places. This code is already in production here, so it does "work" in the basic sense. The places where it's incomplete are places where we know our production data won't currently hit it (no timespans or byte arrays in the db). The reason I'm posting here is that I feel like this can be a little better, and I'd like help finishing and improving this code. Any input welcome. public static class JSONHelper { public static string FromDataTable(DataTable dt) { string rowDelimiter = ""; StringBuilder result = new StringBuilder("["); foreach (DataRow row in dt.Rows) { result.Append(rowDelimiter); result.Append(FromDataRow(row)); rowDelimiter = ","; } result.Append("]"); return result.ToString(); } public static string FromDataRow(DataRow row) { DataColumnCollection cols = row.Table.Columns; string colDelimiter = ""; StringBuilder result = new StringBuilder("{"); for (int i = 0; i < cols.Count; i++) { // use index rather than foreach, so we can use the index for both the row and cols collection result.Append(colDelimiter).Append("\"") .Append(cols[i].ColumnName).Append("\":") .Append(JSONValueFromDataRowObject(row[i], cols[i].DataType)); colDelimiter = ","; } result.Append("}"); return result.ToString(); } // possible types: // http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype(VS.80).aspx private static Type[] numeric = new Type[] {typeof(byte), typeof(decimal), typeof(double), typeof(Int16), typeof(Int32), typeof(SByte), typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)}; // I don't want to rebuild this value for every date cell in the table private static long EpochTicks = new DateTime(1970, 1, 1).Ticks; private static string JSONValueFromDataRowObject(object value, Type DataType) { // null if (value == DBNull.Value) return "null"; // numeric if (Array.IndexOf(numeric, DataType) > -1) return value.ToString(); // TODO: eventually want to use a stricter format // boolean if (DataType == typeof(bool)) return ((bool)value) ? "true" : "false"; // date -- see http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx if (DataType == typeof(DateTime)) return "\"\\/Date(" + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + ")\\/\""; // TODO: add Timespan support // TODO: add Byte[] support //TODO: this would be _much_ faster with a state machine // string/char return "\"" + value.ToString().Replace(@"\", @"\\").Replace(Environment.NewLine, @"\n").Replace("\"", @"\""") + "\""; } }

    Read the article

  • Ajax, Callback, postback and Sys.WebForms.PageRequestManager.getInstance().add_beginRequest

    - by user338262
    Hi, I have a user control which encapsulates a NumericUpDownExtender. This UserControl implements the interface ICallbackEventHandler, because I want that when a user changes the value of the textbox associated a custom event to be raised in the server. By the other hand each time an async postback is done I shoe a message of loading and disable the whole screen. This works perfect when something is changed in for example an UpdatePanel through this lines of code: Sys.WebForms.PageRequestManager.getInstance().add_beginRequest( function (sender, args) { var modalPopupBehavior = $find('programmaticSavingLoadingModalPopupBehavior'); modalPopupBehavior.show(); } ); The UserControl is placed inside a detailsview which is inside an UpdatePanel in an aspx. When the custom event is raised I want another textbox in the aspx to change its value. So far, When I click on the UpDownExtender, it goes correctly to the server and raises the custom event, and the new value of the textbox is assigned in the server. but it is not changed in the browser. I suspect that the problem is the callback, since I have the same architecture for a UserControl with an AutoCompleteExtender which implement IPostbackEventHandler and it works. Any clues how can I solve this here to make the UpDownNumericExtender user control to work like the AutComplete one? This is the code of the user control and the parent: using System; using System.Web.UI; using System.ComponentModel; using System.Text; namespace Corp.UserControls { [Themeable(true)] public partial class CustomNumericUpDown : CorpNumericUpDown, ICallbackEventHandler { protected void Page_PreRender(object sender, EventArgs e) { if (!Page.IsPostBack) { currentInstanceNumber = CorpAjaxControlToolkitUserControl.getNextInstanceNumber(); } registerControl(this.HFNumericUpDown.ClientID, currentInstanceNumber); string strCallServer = "NumericUpDownCallServer" + currentInstanceNumber.ToString(); // If this function is not written the callback to get the disponibilidadCliente doesn't work if (!Page.ClientScript.IsClientScriptBlockRegistered("ReceiveServerDataNumericUpDown")) { StringBuilder str = new StringBuilder(); str.Append("function ReceiveServerDataNumericUpDown(arg, context) {}").AppendLine(); Page.ClientScript.RegisterClientScriptBlock(typeof(CorpNumericUpDown), "ReceiveServerDataNumericUpDown", str.ToString(), true); } nudeNumericUpDownExtender.BehaviorID = "NumericUpDownEx" + currentInstanceNumber.ToString(); ClientScriptManager cm = Page.ClientScript; String cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerDataNumericUpDown", ""); String callbackScript = "function " + strCallServer + "(arg, context)" + Environment.NewLine + "{" + Environment.NewLine + cbReference + ";" + Environment.NewLine + "}" + Environment.NewLine; cm.RegisterClientScriptBlock(typeof(CustomNumericUpDown), strCallServer, callbackScript, true); base.Page_PreRender(sender,e); } [System.ComponentModel.Browsable(true)] [System.ComponentModel.Bindable(true)] public Int64 Value { get { return (string.IsNullOrEmpty(HFNumericUpDown.Value) ? Int64.Parse("1") : Int64.Parse(HFNumericUpDown.Value)); } set { HFNumericUpDown.Value = value.ToString(); //txtAutoCompleteCliente_AutoCompleteExtender.ContextKey = value.ToString(); // TODO: Change the text of the textbox } } [System.ComponentModel.Browsable(true)] [System.ComponentModel.Bindable(true)] [Description("The text of the numeric up down")] public string Text { get { return txtNumericUpDown.Text; } set { txtNumericUpDown.Text = value; } } public delegate void NumericUpDownChangedHandler(object sender, NumericUpDownChangedArgs e); public event NumericUpDownChangedHandler numericUpDownEvent; [System.ComponentModel.Browsable(true)] [System.ComponentModel.Bindable(true)] [System.ComponentModel.Description("Raised after the number has been increased or decreased")] protected virtual void OnNumericUpDownEvent(object sender, NumericUpDownChangedArgs e) { if (numericUpDownEvent != null) //check to see if anyone has attached to the event numericUpDownEvent(this, e); } #region ICallbackEventHandler Members public string GetCallbackResult() { return "";//throw new NotImplementedException(); } public void RaiseCallbackEvent(string eventArgument) { NumericUpDownChangedArgs nudca = new NumericUpDownChangedArgs(long.Parse(eventArgument)); OnNumericUpDownEvent(this, nudca); } #endregion } /// <summary> /// Class that adds the prestamoList to the event /// </summary> public class NumericUpDownChangedArgs : System.EventArgs { /// <summary> /// The current selected value. /// </summary> public long Value { get; private set; } public NumericUpDownChangedArgs(long value) { Value = value; } } } using System; using System.Collections.Generic; using System.Text; namespace Corp { /// <summary> /// Summary description for CorpAjaxControlToolkitUserControl /// </summary> public class CorpNumericUpDown : CorpAjaxControlToolkitUserControl { private Int16 _currentInstanceNumber; // This variable hold the instanceNumber assignated at first place. public short currentInstanceNumber { get { return _currentInstanceNumber; } set { _currentInstanceNumber = value; } } protected void Page_PreRender(object sender, EventArgs e) { const string strOnChange = "OnChange"; const string strCallServer = "NumericUpDownCallServer"; StringBuilder str = new StringBuilder(); foreach (KeyValuePair<String, Int16> control in controlsToRegister) { str.Append("function ").Append(strOnChange + control.Value).Append("(sender, eventArgs) ").AppendLine(); str.Append("{").AppendLine(); str.Append(" if (sender) {").AppendLine(); str.Append(" var hfield = document.getElementById('").Append(control.Key).Append("');").AppendLine(); str.Append(" if (hfield.value != eventArgs) {").AppendLine(); str.Append(" hfield.value = eventArgs;").AppendLine(); str.Append(" ").Append(strCallServer + control.Value).Append("(eventArgs, eventArgs);").AppendLine(); str.Append(" }").AppendLine(); str.Append(" }").AppendLine(); str.Append("}").AppendLine(); Page.ClientScript.RegisterClientScriptBlock(typeof(CorpNumericUpDown), Guid.NewGuid().ToString(), str.ToString(), true); } str = new StringBuilder(); foreach (KeyValuePair<String, Int16> control in controlsToRegister) { str.Append(" funcsPageLoad[funcsPageLoad.length] = function() { $find('NumericUpDownEx" + control.Value + "').add_currentChanged(").Append(strOnChange + control.Value).Append(");};").AppendLine(); str.Append(" funcsPageUnLoad[funcsPageUnLoad.length] = function() { $find('NumericUpDownEx" + control.Value + "').remove_currentChanged(").Append(strOnChange + control.Value).Append(");};").AppendLine(); } Page.ClientScript.RegisterClientScriptBlock(typeof(CorpNumericUpDown), Guid.NewGuid().ToString(), str.ToString(), true); } } } and to create the loading view I use this: //The beginRequest event is raised before the processing of an asynchronous postback starts and the postback is sent to the server. You can use this event to call custom script to set a request header or to start an animation that notifies the user that the postback is being processed. Sys.WebForms.PageRequestManager.getInstance().add_beginRequest( function (sender, args) { var modalPopupBehavior = $find('programmaticSavingLoadingModalPopupBehavior'); modalPopupBehavior.show(); } ); //The endRequest event is raised after an asynchronous postback is finished and control has been returned to the browser. You can use this event to provide a notification to users or to log errors. Sys.WebForms.PageRequestManager.getInstance().add_endRequest( function (sender, arg) { var modalPopupBehavior = $find('programmaticSavingLoadingModalPopupBehavior'); modalPopupBehavior.hide(); } ); Thanks in advance! Daniel.

    Read the article

  • Posting from ASP.NET WebForms page to another URL

    - by hajan
    Few days ago I had a case when I needed to make FORM POST from my ASP.NET WebForms page to an external site URL. More specifically, I was working on implementing Simple Payment System (like Amazon, PayPal, MoneyBookers). The operator asks to make FORM POST request to a given URL in their website, sending parameters together with the post which are computed on my application level (access keys, secret keys, signature, return-URL… etc). So, since we are not allowed nesting another form inside the <form runat=”server”> … </form>, which is required because other controls in my ASPX code work on server-side, I thought to inject the HTML and create FORM with method=”POST”. After making some proof of concept and testing some scenarios, I’ve concluded that I can do this very fast in two ways: Using jQuery to create form on fly with the needed parameters and make submit() Using HttpContext.Current.Response.Write to write the form on server-side (code-behind) and embed JavaScript code that will do the post Both ways seemed fine. 1. Using jQuery to create FORM html code and Submit it. Let’s say we have ‘PAY NOW’ button in our ASPX code: <asp:Button ID="btnPayNow" runat="server" Text="Pay Now" /> Now, if we want to make this button submit a FORM using POST method to another website, the jQuery way should be as follows: <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" type="text/javascript"></script> <script type="text/javascript">     $(function () {         $("#btnPayNow").click(function (event) {             event.preventDefault();             //construct htmlForm string             var htmlForm = "<form id='myform' method='POST' action='http://www.microsoft.com'>" +                 "<input type='hidden' id='name' value='hajan' />" +             "</form>";             //Submit the form             $(htmlForm).appendTo("body").submit();         });     }); </script> Yes, as you see, the code fires on btnPayNow click. It removes the default button behavior, then creates htmlForm string. After that using jQuery we append the form to the body and submit it. Inside the form, you can see I have set the htttp://www.microsoft.com URL, so after clicking the button you should be automatically redirected to the Microsoft website (just for test, of course for Payment I’m using Operator's URL). 2. Using HttpContext.Current.Response.Write to write the form on server-side (code-behind) and embed JavaScript code that will do the post The C# code behind should be something like this: public void btnPayNow_Click(object sender, EventArgs e) {     string Url = "http://www.microsoft.com";     string formId = "myForm1";     StringBuilder htmlForm = new StringBuilder();     htmlForm.AppendLine("<html>");     htmlForm.AppendLine(String.Format("<body onload='document.forms[\"{0}\"].submit()'>",formId));     htmlForm.AppendLine(String.Format("<form id='{0}' method='POST' action='{1}'>", formId, Url));     htmlForm.AppendLine("<input type='hidden' id='name' value='hajan' />");     htmlForm.AppendLine("</form>");     htmlForm.AppendLine("</body>");     htmlForm.AppendLine("</html>");     HttpContext.Current.Response.Clear();     HttpContext.Current.Response.Write(htmlForm.ToString());     HttpContext.Current.Response.End();             } So, with this code we create htmlForm string using StringBuilder class and then just write the html to the page using HttpContext.Current.Response.Write. The interesting part here is that we submit the form using JavaScript code: document.forms["myForm1"].submit() This code runs on body load event, which means once the body is loaded the form is automatically submitted. Note: In order to test both solutions, create two applications on your web server and post the form from first to the second website, then get the values in the second website using Request.Form[“input-field-id”] I hope this was useful post for you. Regards, Hajan

    Read the article

  • Problems with data driven testing in MSTest

    - by severj3
    Hello, I am trying to get data driven testing to work in C# with MSTest/Selenium. Here is a sample of some of my code trying to set it up: [TestClass] public class NewTest { private ISelenium selenium; private StringBuilder verificationErrors; [DeploymentItem("GoogleTestData.xls")] [DataSource("System.Data.OleDb", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=GoogleTestData.xls;Persist Security Info=False;Extended Properties='Excel 8.0'", "TestSearches$", DataAccessMethod.Sequential)] [TestMethod] public void GoogleTest() { selenium = new DefaultSelenium("localhost", 4444, "*iehta", http://www.google.com); selenium.Start(); verificationErrors = new StringBuilder(); var searchingTerm = TestContext.DataRow["SearchingString"].ToString(); var expectedResult = TestContext.DataRow["ExpectedTextResults"].ToString(); Here's my error: Error 3 An object reference is required for the non-static field, method, or property 'Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.DataRow.get' E:\Projects\SeleniumProject\SeleniumProject\MaverickTest.cs 32 33 SeleniumProject The error is underlining the "TestContext.DataRow" part of both statements. I've really been struggling with this one, thanks!

    Read the article

  • Write a function that compares two strings and returns a third string containing only the letters th

    - by Pritam
    Hi All, I got this homework. And have solved it in following way. I need your comments whether it is a good approach or I need to use any other data sturcture to solve it in better way. public string ReturnCommon(string firstString, string scndString) { StringBuilder newStb = new StringBuilder(); if (firstString != null && scndString != null) { foreach (char ichar in firstString) { if (!newStb.ToString().Contains(ichar) && scndString.Contains(ichar)) newStb.Append(ichar); } } return newStb.ToString(); }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >