Search Results

Search found 1721 results on 69 pages for 'dr evil'.

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

  • I'm a premature optimizer

    - by Matthew Day
    I work in a small sized software/web development company. I have gotten into the habit of optimizing prematurely, I know it is evil and promotes bad code... But I have been working at this firm for a long while and I have deemed this as a necessary evil. It has never caused me an issue so far in the past, but it might if I get partners or a successor. The point of this long-winded speech is that, should I change my evil practices to 'save face' and to help out in the future?

    Read the article

  • C#: Object reference not set to an instance of an object.

    - by Vinzcent
    Hey, I get the following error: Object reference not set to an instance of an object This is my C Sharp code: DataTable tableAcces = dsAcces.Tables["dsPrinterAcces"]; DataTable tableMDF = dsAcces.Tables["dsPrinterMDF"]; DataRow newrow = null; foreach(DataRow dr in tableAcces.Rows) { newrow = tableMDF.NewRow(); newrow["PRINTER_ID"] = dr["PRINTER_ID"]; newrow["MERK"] = dr["MERK"]; newrow["MODEL"] = dr["MODEL"]; newrow["LOKAAL_ID"] = dr["LOKAAL_ID"]; tableMDF.Rows.Add(newrow); } daMDF.Update(dsMDF, "dsPrinterMDF"); lblSucces.Text = "Gelukt. De tabel printers is overgezet."; } In this line, he throws the error: newrow = tableMDF.NewRow(); Thanks a lot, Vincent

    Read the article

  • DataReader - hardcode ordinals?

    - by David Neale
    When returning data from a DataReader I would typically use the ordinal reference on the DataReader to grab the relevant column: if (dr.HasRows) Console.WriteLine(dr[0].ToString()); (OR dr.GetString(0); OR (string)dr[0];)... I have always done this because I was advised at an early stage that using dr["ColumnName"] or a more elegant way of indexing causes a performance hit. However, whilst everything is becoming increasingly strongly-typed I feel more uncomfortable with this. I'm also aware that the above does not check for DBNull. How should data be returned from a DataReader?

    Read the article

  • Referencing a control programatically with external source

    - by James
    Forgive me about the title, I have no idea what this is called. I have a MS Access database set up, with a Period field that has either values 1, 2, 3, 4 or 5. I retrieve these values using a database connection and I would like to reference a particular control based on what period was grabbed from the database. Here's example code, pseudo of course. TextBox(dr(3)).Text = dr(0) dr(3) contains the period, and dr(0) contains the content I would like to put into the text box. I have these text boxes on my form: TextBox1, TextBox2, TextBox3, TextBox4 and TextBox5. So if dr(3) contained 2 then I would want to reference TextBox2. I hope I've made myself clear, any help would be greatly appreciated, thanks. :)

    Read the article

  • Round-twice error in .NET's Double.ToString method

    - by Jeppe Stig Nielsen
    Mathematically, consider for this question the rational number 8725724278030350 / 2**48 where ** in the denominator denotes exponentiation, i.e. the denominator is 2 to the 48th power. (The fraction is not in lowest terms, reducible by 2.) This number is exactly representable as a System.Double. Its decimal expansion is 31.0000000000000'49'73799150320701301097869873046875 (exact) where the apostrophes do not represent missing digits but merely mark the boudaries where rounding to 15 resp. 17 digits is to be performed. Note the following: If this number is rounded to 15 digits, the result will be 31 (followed by thirteen 0s) because the next digits (49...) begin with a 4 (meaning round down). But if the number is first rounded to 17 digits and then rounded to 15 digits, the result could be 31.0000000000001. This is because the first rounding rounds up by increasing the 49... digits to 50 (terminates) (next digits were 73...), and the second rounding might then round up again (when the midpoint-rounding rule says "round away from zero"). (There are many more numbers with the above characteristics, of course.) Now, it turns out that .NET's standard string representation of this number is "31.0000000000001". The question: Isn't this a bug? By standard string representation we mean the String produced by the parameterles Double.ToString() instance method which is of course identical to what is produced by ToString("G"). An interesting thing to note is that if you cast the above number to System.Decimal then you get a decimal that is 31 exactly! See this Stack Overflow question for a discussion of the surprising fact that casting a Double to Decimal involves first rounding to 15 digits. This means that casting to Decimal makes a correct round to 15 digits, whereas calling ToSting() makes an incorrect one. To sum up, we have a floating-point number that, when output to the user, is 31.0000000000001, but when converted to Decimal (where 29 digits are available), becomes 31 exactly. This is unfortunate. Here's some C# code for you to verify the problem: static void Main() { const double evil = 31.0000000000000497; string exactString = DoubleConverter.ToExactString(evil); // Jon Skeet, http://csharpindepth.com/Articles/General/FloatingPoint.aspx Console.WriteLine("Exact value (Jon Skeet): {0}", exactString); // writes 31.00000000000004973799150320701301097869873046875 Console.WriteLine("General format (G): {0}", evil); // writes 31.0000000000001 Console.WriteLine("Round-trip format (R): {0:R}", evil); // writes 31.00000000000005 Console.WriteLine(); Console.WriteLine("Binary repr.: {0}", String.Join(", ", BitConverter.GetBytes(evil).Select(b => "0x" + b.ToString("X2")))); Console.WriteLine(); decimal converted = (decimal)evil; Console.WriteLine("Decimal version: {0}", converted); // writes 31 decimal preciseDecimal = decimal.Parse(exactString, CultureInfo.InvariantCulture); Console.WriteLine("Better decimal: {0}", preciseDecimal); // writes 31.000000000000049737991503207 } The above code uses Skeet's ToExactString method. If you don't want to use his stuff (can be found through the URL), just delete the code lines above dependent on exactString. You can still see how the Double in question (evil) is rounded and cast.

    Read the article

  • INSERT..ON DUPLICATE KEY UPDATE - but NOT using the duplicate key to compare.

    - by calumbrodie
    I am trying to solve a problem I have inherited with poor treatment of different data sources. I have a user table that contains BOTH good and evil users. create table `users`( `user_id` int(13) NOT NULL AUTO_INCREMENT , `email` varchar(255) , `name` varchar(255) , PRIMARY KEY (`user_id`) ); In this table the primary key is currently set to be user_id. I have another table ('users_evil') which contains ONLY the evil users (all the users from this table are included in the first table) - the user_id's on this table do NOT correspond to those in the first table. I want to have all my users in one table, and simply flag which are good and which are evil. What I want to do is alter the user table and add a column ('evil') which defaults to 0. I then want to dump the data from my 'users_evil') table and then run an INSERT..ON DUPLICATE KEY UPDATE with this data into the first table (setting 'evil'=1 where the emails match) The problem is that the 'PK' is set to the user_id and not the 'email'. Any suggestions, or even another strategy to successfully achive this. Can I run this statement but treat another column as PK only for the duration of the statement.

    Read the article

  • Issue with DFS imlemtation in objetive-c

    - by Hemant
    i am trying to to do something like this Below is my code: -(id) init{ if( (self=[super init]) ) { bubbles_Arr = [[NSMutableArray alloc] initWithCapacity: 9]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"1",@"1",@"1",@"1",@"1",nil] atIndex:0]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"3",@"3",@"5",@"5",@"1",nil] atIndex:1]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"3",@"5",@"3",@"1",nil] atIndex:2]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"3",@"5",@"3",@"1",nil] atIndex:3]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"1",@"1",@"1",@"1",@"1",nil] atIndex:4]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"3",@"5",@"1",nil] atIndex:5]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"5",@"5",@"5",nil] atIndex:6]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"5",@"5",@"5",nil] atIndex:7]; [bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"5",@"5",@"5",nil] atIndex:8]; NOCOLOR = @"-1"; R = 9; C = 5; [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(testting) userInfo:Nil repeats:NO]; } return self; } -(void)testting{ // NSLog(@"dataArray---- %@",dataArray.description); int startR = 0; int startC = 0; int color = 1 ;// red // NSString *color = @"5"; //reset visited matrix to false. for(int i = 0; i < R; i++) for(int j = 0; j < C; j++) visited[i][j] = FALSE; //reset count count = 0; [self dfs:startR :startC :color :false]; NSLog(@"count--- %d",count); NSLog(@"test--- %@",bubbles_Arr); } -(void)dfs:(int)ro:(int)co:(int)colori:(BOOL)set{ for(int dr = -1; dr <= 1; dr++) for(int dc = -1; dc <= 1; dc++) if((dr == 0 ^ dc == 0) && [self ok:ro+dr :co+dc]) // 4 neighbors { int nr = ro+dr; int nc = co+dc; NSLog(@"-- %d ---- %d",[[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] integerValue],colori); if ((([[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] integerValue]==1 || [[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] isEqualToString:@"1"]) && !visited[nr][nc])) { visited[nr][nc] = true; count++; [self dfs:nr :nc :colori :set]; if(count>2) { [[bubbles_Arr objectAtIndex:nr] replaceObjectAtIndex:nc withObject:NOCOLOR]; [bubbles[nc+1][nr+1] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"gray_tiger.png"]]; } } } } -(BOOL)ok:(int)r:(int)c{ return r >= 0 && r < R && c >= 0 && c < C; } But it's only working for left to right,not working for right to left. And it is also skipping first object. Thanks in advance.

    Read the article

  • C# and SQL - sub select from a table parameter

    - by Dr.HappyPants
    Below is a code snippet for passing a table as a parameter to a query that can be used in Sql Server 2008. I'm confused though about the "SELECT id.custid FROM @custids id". Why does it use id.custid and @custids id...? private static void datatable_example() { string [] custids = {"ALFKI", "BONAP", "CACTU", "FRANK"}; DataTable custid_list = new DataTable(); custid_list.Columns.Add("custid", typeof(String)); foreach (string custid in custids) { DataRow dr = custid_list.NewRow(); dr["custid"] = custid; custid_list.Rows.Add(dr); } using(SqlConnection cn = setup_connection()) { using(SqlCommand cmd = cn.CreateCommand()) { cmd.CommandText = @"SELECT C.CustomerID, C.CompanyName FROM Northwind.dbo.Customers C WHERE C.CustomerID IN (SELECT id.custid FROM @custids id)"; cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@custids", SqlDbType.Structured); cmd.Parameters["@custids"].Direction = ParameterDirection.Input; cmd.Parameters["@custids"].TypeName = "custid_list_tbltype"; cmd.Parameters["@custids"].Value = custid_list; using (SqlDataAdapter da = new SqlDataAdapter(cmd)) using (DataSet ds = new DataSet()) { da.Fill(ds); PrintDataSet(ds); } } }

    Read the article

  • Reading text out of textbox in Radgrid

    - by Christophe
    I have a Radgrid with 2 Textboxes and 2 DatePickers. The idea is that I have a grid with a Property name, value, valid from and until. I'm filling the first Textbox myself, the user has to fill in the value, from and until. Filling in the propertynames: (In the pageload) foreach (String s in testProperties) { DataRow dr = dt.NewRow(); dr[0] = s; dr[1] = ""; dr[2] = ""; dr[3] = ""; dt.Rows.Add(dr); } When the user hit "Save" I have to read out all the data he filled in. (In the btnSave click) foreach (GridDataItem dataItem in RadGrid1.Items) { String[] str = new String[3]; str[0] = ((TextBox)dataItem["col2"].FindControl("TextBox2")).Text; str[1] = ((RadDatePicker)dataItem["col3"].FindControl("RadDatePicker1")).SelectedDate.ToString(); str[2] = ((RadDatePicker)dataItem["col4"].FindControl("RadDatePicker2")).SelectedDate.ToString(); properties.Add(((TextBox)dataItem["col1"].FindControl("TextBox1")).Text, str); } Now this is where I have the problem. When i read out the data all my 'str' have the value "" instead the data that the user fills in. Question is, how comes my values in the texboxes remain ""? Or is their a better way to read out the data?

    Read the article

  • error: unable to open database file, SQLiteException was unhandled

    - by rose
    My project has a reference to SQLite.Interop.066.dll and even after putting in the correct path to the SQLite database, the application is still unable to find it. A SQLiteException was unhandled is returned. SQLiteConnection conn = new SQLiteConnection(); //SQLiteDataAdapter da; SQLiteCommandBuilder cb; DataTable dt=new DataTable(); int row = 0; conn.ConnectionString = "Data Source=C:\\database\\info"; conn.Open(); DataRow dr = dt.NewRow(); dr["name"] = txtName.Text; dr["address"] = txtAddress.Text; dr["phone"] = txtPhone.Text; dr["position"] = txtPosition.Text; dt.Rows.Add(dr); da.Update(dt); row = dt.Rows.Count - 1; txtName.Text = dt.Rows[row]["name"].ToString(); txtAddress.Text = dt.Rows[row]["address"].ToString(); txtPhone.Text = dt.Rows[row]["phone"].ToString(); txtPosition.Text = dt.Rows[row]["position"].ToString(); da.Fill(dt); cb = new SQLiteCommandBuilder(da); conn.Dispose(); conn.Close(); The exception occur at line: conn.Open(); sorry for the mistake title error before...

    Read the article

  • dataset - set parent child relations

    - by Night Walker
    Hello all I am trying to set the relations of rows in DataSet and then to show that relation in XTraaTreeList as tree with relations. | --| ----| but i get | | | I am doing this code but i get a view without any relations i get them all in one level. Any idea what i am doing wrong ? this.treeList1.BeginUpdate(); this.dataTable1.Clear(); DataRow dr = this.dataTable1.NewRow(); dr[0] = "father"; dr[1] = true; dr[2] = "ddd"; this.dataTable1.Rows.Add(dr); DataRow dr1 = this.dataTable1.NewRow(); dr1[0] = "son"; dr1[1] = true; dr1[2] = "ddd"; dr1.SetParentRow(dr); this.dataTable1.Rows.Add(dr1); DataRow dr2 = this.dataTable1.NewRow(); this.dataTable1.ParentRelations() dr2[0] = "grand son"; dr2[1] = true; dr2[2] = "ddd"; dr2.SetParentRow(dr1); this.dataTable1.Rows.Add(dr2); this.treeList1.EndUpdate();

    Read the article

  • How to differentiate between to similer fields in Linq Join tables

    - by Azhar
    How to differentiate between to select new fields e.g. Description c.Description and lt.Description DataTable lDt = new DataTable(); try { lDt.Columns.Add(new DataColumn("AreaTypeID", typeof(Int32))); lDt.Columns.Add(new DataColumn("CategoryRef", typeof(Int32))); lDt.Columns.Add(new DataColumn("Description", typeof(String))); lDt.Columns.Add(new DataColumn("CatDescription", typeof(String))); EzEagleDBDataContext lDc = new EzEagleDBDataContext(); var lAreaType = (from lt in lDc.tbl_AreaTypes join c in lDc.tbl_AreaCategories on lt.CategoryRef equals c.CategoryID where lt.AreaTypeID== pTypeId select new { lt.AreaTypeID, lt.Description, lt.CategoryRef, c.Description }).ToArray(); for (int j = 0; j< lAreaType.Count; j++) { DataRow dr = lDt.NewRow(); dr["AreaTypeID"] = lAreaType[j].LandmarkTypeID; dr["CategoryRef"] = lAreaType[j].CategoryRef; dr["Description"] = lAreaType[j].Description; dr["CatDescription"] = lAreaType[j].; lDt.Rows.Add(dr); } } catch (Exception ex) { }

    Read the article

  • label as dynamic navigation

    - by KareemSaad
    I Made label to had value from database and linked it . but the problem was it had only one value and i want it keep value when navigation thought site as. xyz.... this is my code < if (Request.QueryString["Category_Id"] != null) { Banar.ImageUrl = "Handlers/Banner.ashx?Category_Id=" + Request.QueryString["Category_Id"] + ""; using (SqlConnection conn = Connection.GetConnection()) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Navcategory"; cmd.Parameters.Add(Parameter.NewInt("@Category_Id", Request.QueryString["Category_Id"])); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { LblNavigaton.Visible = true; LblNavigaton.Text = dr[i].ToString(); NavHref.HRef = "ListView.aspx?Category_Id=" + Request.QueryString["Category_Id"] + ""; } } } else if (Request.QueryString["ProductCategory_Id"] != null) { Banar.ImageUrl = "Handlers/ProCatBanner.ashx?ProductCategory_Id=" + Request.QueryString["ProductCategory_Id"] + ""; using (SqlConnection conn = Connection.GetConnection()) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "NavProductcategory"; cmd.Parameters.Add(Parameter.NewInt("@ProductCategory_Id", Request.QueryString["ProductCategory_Id"])); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { LblNavigaton.Visible = true; LblNavigaton.Text = dr["Name"].ToString(); NavHref.HRef = "ListView.aspx?ProductCategory_Id=" + Request.QueryString["ProductCategory_Id"] + ""; } else { LblNavigaton.Visible = true; LblNavigaton.Text = Page.Title; } }

    Read the article

  • Populate a form from SQL

    - by xrum
    Hi, I am trying to populate a web from from a SQL table. This is what I have right now, though I am not sure if it's the best way to do things, please give me suggestions: Public Class userDetails Public address1 As String Public address2 As String Public city As String ... ... ... End Class Public Class clsPerson 'set SQL connection Dim objFormat As New clsFormat Dim objConn As New clsConn() Dim connStr As String = objConn.getConn() Dim myConnection As New Data.SqlClient.SqlConnection(connStr) Public Function GetPersonDetails() As userDetails 'connection and all other good stuff here Try ' Execute the command myConnection.Open() dr = myCommand.ExecuteReader() ' Make sure a record was returned If dr.Read() Then ' Create and Populate ApplicantDetails userDetails.address1 = dr("address1") userDetails.address2 = objFormat.CheckNull(dr("address2")) userDetails.city = objFormat.CheckNull(dr("city")) .... Else Err.Raise(4938, "clsUser", "Error in GetUserDetails - User Not Found") End If dr.Close() Finally myConnection.Close() End Try Return userDetails End Function i then use GetPersonDetails() function in my backend to populate the form. like so: Dim userDetails as new userDetails userdetails = getPersonDetails() txtAddress.text = userdetails.address1 etc.... however, there are like 50 fields in the User db, and it seems like a lot of retyping... please help me find a better way to do this. Thank you!

    Read the article

  • How to differentiate between two similar fields in Linq Join tables

    - by Azhar
    How to differentiate between two select new fields e.g. Description c.Description and lt.Description DataTable lDt = new DataTable(); try { lDt.Columns.Add(new DataColumn("AreaTypeID", typeof(Int32))); lDt.Columns.Add(new DataColumn("CategoryRef", typeof(Int32))); lDt.Columns.Add(new DataColumn("Description", typeof(String))); lDt.Columns.Add(new DataColumn("CatDescription", typeof(String))); EzEagleDBDataContext lDc = new EzEagleDBDataContext(); var lAreaType = (from lt in lDc.tbl_AreaTypes join c in lDc.tbl_AreaCategories on lt.CategoryRef equals c.CategoryID where lt.AreaTypeID== pTypeId select new { lt.AreaTypeID, lt.Description, lt.CategoryRef, c.Description }).ToArray(); for (int j = 0; j< lAreaType.Count; j++) { DataRow dr = lDt.NewRow(); dr["AreaTypeID"] = lAreaType[j].LandmarkTypeID; dr["CategoryRef"] = lAreaType[j].CategoryRef; dr["Description"] = lAreaType[j].Description; dr["CatDescription"] = lAreaType[j].; lDt.Rows.Add(dr); } } catch (Exception ex) { }

    Read the article

  • Best way to get a single value from a DataTable?

    - by PiersMyers
    I have a number of static classes that contain tables like this: using System; using System.Data; using System.Globalization; public static class TableFoo { private static readonly DataTable ItemTable; static TableFoo() { ItemTable = new DataTable("TableFoo") { Locale = CultureInfo.InvariantCulture }; ItemTable.Columns.Add("Id", typeof(int)); ItemTable.Columns["Id"].Unique = true; ItemTable.Columns.Add("Description", typeof(string)); ItemTable.Columns.Add("Data1", typeof(int)); ItemTable.Columns.Add("Data2", typeof(double)); ItemTable.Rows.Add(0, "Item 1", 1, 1.0); ItemTable.Rows.Add(1, "Item 2", 1, 1.0); ItemTable.Rows.Add(2, "Item 3", 2, 0.75); ItemTable.Rows.Add(3, "Item 4", 4, 0.25); ItemTable.Rows.Add(4, "Item 5", 1, 1.0); } public static DataTable GetItemTable() { return ItemTable; } public static int Data1(int id) { DataRow[] dr = ItemTable.Select("Id = " + id); if (dr.Length == 0) { throw new ArgumentOutOfRangeException("id", "Out of range."); } return (int)dr[0]["Data1"]; } public static double Data2(int id) { DataRow[] dr = ItemTable.Select("Id = " + id); if (dr.Length == 0) { throw new ArgumentOutOfRangeException("id", "Out of range."); } return (double)dr[0]["Data2"]; } } Is there a better way of writing the Data1 or Data2 methods that return a single value from a single row that matches the given id?

    Read the article

  • ListBox Items Not Visible after DataBinding

    - by SidC
    Good Evening All, I am writing a page that allows users to search a parts table, select quantities and a listbox is to be populated with gridview values. Here's a snippet of my aspx page: <asp:ListBox runat="server" ID="lbItems" Width="155px"> <asp:ListItem></asp:ListItem> <asp:ListItem></asp:ListItem> <asp:ListItem></asp:ListItem> <asp:ListItem></asp:ListItem> <asp:ListItem></asp:ListItem> </asp:ListBox> Here's the relevant contents of codebehind: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Define DataTable Columns as incoming gridview fields Dim dtSelParts As DataTable = New DataTable Dim dr As DataRow = dtSelParts.NewRow() dtSelParts.Columns.Add("PartNumber") dtSelParts.Columns.Add("NSN") dtSelParts.Columns.Add("PartName") dtSelParts.Columns.Add("Qty") 'Select those gridview rows that have txtQty <> 0 For Each row As GridViewRow In MySearch.Rows Dim textboxText As String = _ CType(row.FindControl("txtQty"), TextBox).Text If textboxText <> "0" Then 'Create the row dr = dtSelParts.NewRow() 'Fill the row with data dr("PartNumber") = MySearch.DataKeys(row.RowIndex)("PartNumber") dr("NSN") = MySearch.DataKeys(row.RowIndex)("NSN") dr("PartName") = MySearch.DataKeys(row.RowIndex)("PartName") 'Add the row to the table dtSelParts.Rows.Add(dr) End If Next 'Need to send items to Listbox control lbItems lbItems.DataSource = New DataView(dtSelParts) lbItems.DataValueField = "PartNumber" lbItems.DataValueField = "NSN" lbItems.DataValueField = "PartName" lbItems.DataBind() End Sub The page runs fine in that my search functiobnality is intact, and I can input quantity values into my gridview's textbox. When I click Add to Quote the Listbox receives focus, but no list items are visible. I've created several list items in the aspx page, however I don't know how to populate the contents of my datatable in the listbox. Can someone help a newbie with this, seemingly, easy issue? Thanks, Sid

    Read the article

  • Retriving data from ListView control

    - by Josh
    I have a ListView control set up in details mode with 5 columns. It is populated by code using the following subroutine: For j = 0 To 14 cmd = New OleDbCommand("SELECT TeacherName, ClassSubject, BookingDate, BookingPeriod FROM " & SchemaTable.Rows(i)!TABLE_NAME.ToString() & " WHERE (((BookingDate)=" & Chr(34) & Date.Today.AddDays(j) & Chr(34) & ") AND ((UserName)=" & Chr(34) & user & Chr(34) & "));", cn) dr = cmd.ExecuteReader Dim itm As ListViewItem Dim itms(4) As String While dr.Read() itms(0) = dr(0) itms(1) = SchemaTable.Rows(i)!TABLE_NAME.ToString() itms(2) = dr(1) itms(3) = dr(2) itms(4) = dr(3) itm = New ListViewItem(itms) Manage.ManageList.Items.Add(itm) End While Next Note that this is not the full routine, just the bit that populated the grid. Now I need to retrieve data from the ListView control in order to delete a booking in my database. I used the following code to retrieve the content of each column: ManageList.SelectedItems(0).Text But it only seems to work on index 0. If I do: ManageList.SelectedItems(3).Text I get this error: InvalidArgument=Value of '3' is not valid for 'index'. Parameter name: index I'm pretty much stumped, it seems logical to me that index 1 will point to the 2nd column, index 2 to the 3rd etc, as it's 0 based? Any help would be appreciated, thanks.

    Read the article

  • Using the ASP.NET Cache to cache data in a Model or Business Object layer, without a dependency on System.Web in the layer - Part One.

    - by Rhames
    ASP.NET applications can make use of the System.Web.Caching.Cache object to cache data and prevent repeated expensive calls to a database or other store. However, ideally an application should make use of caching at the point where data is retrieved from the database, which typically is inside a Business Objects or Model layer. One of the key features of using a UI pattern such as Model-View-Presenter (MVP) or Model-View-Controller (MVC) is that the Model and Presenter (or Controller) layers are developed without any knowledge of the UI layer. Introducing a dependency on System.Web into the Model layer would break this independence of the Model from the View. This article gives a solution to this problem, using dependency injection to inject the caching implementation into the Model layer at runtime. This allows caching to be used within the Model layer, without any knowledge of the actual caching mechanism that will be used. Create a sample application to use the caching solution Create a test SQL Server database This solution uses a SQL Server database with the same Sales data used in my previous post on calculating running totals. The advantage of using this data is that it gives nice slow queries that will exaggerate the effect of using caching! To create the data, first create a new SQL database called CacheSample. Next run the following script to create the Sale table and populate it: USE CacheSample GO   CREATE TABLE Sale(DayCount smallint, Sales money) CREATE CLUSTERED INDEX ndx_DayCount ON Sale(DayCount) go INSERT Sale VALUES (1,120) INSERT Sale VALUES (2,60) INSERT Sale VALUES (3,125) INSERT Sale VALUES (4,40)   DECLARE @DayCount smallint, @Sales money SET @DayCount = 5 SET @Sales = 10   WHILE @DayCount < 5000  BEGIN  INSERT Sale VALUES (@DayCount,@Sales)  SET @DayCount = @DayCount + 1  SET @Sales = @Sales + 15  END Next create a stored procedure to calculate the running total, and return a specified number of rows from the Sale table, using the following script: USE [CacheSample] GO   SET ANSI_NULLS ON GO   SET QUOTED_IDENTIFIER ON GO   -- ============================================= -- Author:        Robin -- Create date: -- Description:   -- ============================================= CREATE PROCEDURE [dbo].[spGetRunningTotals]       -- Add the parameters for the stored procedure here       @HighestDayCount smallint = null AS BEGIN       -- SET NOCOUNT ON added to prevent extra result sets from       -- interfering with SELECT statements.       SET NOCOUNT ON;         IF @HighestDayCount IS NULL             SELECT @HighestDayCount = MAX(DayCount) FROM dbo.Sale                   DECLARE @SaleTbl TABLE (DayCount smallint, Sales money, RunningTotal money)         DECLARE @DayCount smallint,                   @Sales money,                   @RunningTotal money         SET @RunningTotal = 0       SET @DayCount = 0         DECLARE rt_cursor CURSOR       FOR       SELECT DayCount, Sales       FROM Sale       ORDER BY DayCount         OPEN rt_cursor         FETCH NEXT FROM rt_cursor INTO @DayCount,@Sales         WHILE @@FETCH_STATUS = 0 AND @DayCount <= @HighestDayCount        BEGIN        SET @RunningTotal = @RunningTotal + @Sales        INSERT @SaleTbl VALUES (@DayCount,@Sales,@RunningTotal)        FETCH NEXT FROM rt_cursor INTO @DayCount,@Sales        END         CLOSE rt_cursor       DEALLOCATE rt_cursor         SELECT DayCount, Sales, RunningTotal       FROM @SaleTbl   END   GO   Create the Sample ASP.NET application In Visual Studio create a new solution and add a class library project called CacheSample.BusinessObjects and an ASP.NET web application called CacheSample.UI. The CacheSample.BusinessObjects project will contain a single class to represent a Sale data item, with all the code to retrieve the sales from the database included in it for simplicity (normally I would at least have a separate Repository or other object that is responsible for retrieving data, and probably a data access layer as well, but for this sample I want to keep it simple). The C# code for the Sale class is shown below: using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient;   namespace CacheSample.BusinessObjects {     public class Sale     {         public Int16 DayCount { get; set; }         public decimal Sales { get; set; }         public decimal RunningTotal { get; set; }           public static IEnumerable<Sale> GetSales(int? highestDayCount)         {             List<Sale> sales = new List<Sale>();               SqlParameter highestDayCountParameter = new SqlParameter("@HighestDayCount", SqlDbType.SmallInt);             if (highestDayCount.HasValue)                 highestDayCountParameter.Value = highestDayCount;             else                 highestDayCountParameter.Value = DBNull.Value;               string connectionStr = System.Configuration.ConfigurationManager .ConnectionStrings["CacheSample"].ConnectionString;               using(SqlConnection sqlConn = new SqlConnection(connectionStr))             using (SqlCommand sqlCmd = sqlConn.CreateCommand())             {                 sqlCmd.CommandText = "spGetRunningTotals";                 sqlCmd.CommandType = CommandType.StoredProcedure;                 sqlCmd.Parameters.Add(highestDayCountParameter);                   sqlConn.Open();                   using (SqlDataReader dr = sqlCmd.ExecuteReader())                 {                     while (dr.Read())                     {                         Sale newSale = new Sale();                         newSale.DayCount = dr.GetInt16(0);                         newSale.Sales = dr.GetDecimal(1);                         newSale.RunningTotal = dr.GetDecimal(2);                           sales.Add(newSale);                     }                 }             }               return sales;         }     } }   The static GetSale() method makes a call to the spGetRunningTotals stored procedure and then reads each row from the returned SqlDataReader into an instance of the Sale class, it then returns a List of the Sale objects, as IEnnumerable<Sale>. A reference to System.Configuration needs to be added to the CacheSample.BusinessObjects project so that the connection string can be read from the web.config file. In the CacheSample.UI ASP.NET project, create a single web page called ShowSales.aspx, and make this the default start up page. This page will contain a single button to call the GetSales() method and a label to display the results. The html mark up and the C# code behind are shown below: ShowSales.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowSales.aspx.cs" Inherits="CacheSample.UI.ShowSales" %>   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>Cache Sample - Show All Sales</title> </head> <body>     <form id="form1" runat="server">     <div>         <asp:Button ID="btnTest1" runat="server" onclick="btnTest1_Click"             Text="Get All Sales" />         &nbsp;&nbsp;&nbsp;         <asp:Label ID="lblResults" runat="server"></asp:Label>         </div>     </form> </body> </html>   ShowSales.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;   using CacheSample.BusinessObjects;   namespace CacheSample.UI {     public partial class ShowSales : System.Web.UI.Page     {         protected void Page_Load(object sender, EventArgs e)         {         }           protected void btnTest1_Click(object sender, EventArgs e)         {             System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();             stopWatch.Start();               var sales = Sale.GetSales(null);               var lastSales = sales.Last();               stopWatch.Stop();               lblResults.Text = string.Format( "Count of Sales: {0}, Last DayCount: {1}, Total Sales: {2}. Query took {3} ms", sales.Count(), lastSales.DayCount, lastSales.RunningTotal, stopWatch.ElapsedMilliseconds);         }       } }   Finally we need to add a connection string to the CacheSample SQL Server database, called CacheSample, to the web.config file: <?xmlversion="1.0"?>   <configuration>    <connectionStrings>     <addname="CacheSample"          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=CacheSample"          providerName="System.Data.SqlClient" />  </connectionStrings>    <system.web>     <compilationdebug="true"targetFramework="4.0" />  </system.web>   </configuration>   Run the application and click the button a few times to see how long each call to the database takes. On my system, each query takes about 450ms. Next I shall look at a solution to use the ASP.NET caching to cache the data returned by the query, so that subsequent requests to the GetSales() method are much faster. Adding Data Caching Support I am going to create my caching support in a separate project called CacheSample.Caching, so the next step is to add a class library to the solution. We shall be using the application configuration to define the implementation of our caching system, so we need a reference to System.Configuration adding to the project. ICacheProvider<T> Interface The first step in adding caching to our application is to define an interface, called ICacheProvider, in the CacheSample.Caching project, with methods to retrieve any data from the cache or to retrieve the data from the data source if it is not present in the cache. Dependency Injection will then be used to inject an implementation of this interface at runtime, allowing the users of the interface (i.e. the CacheSample.BusinessObjects project) to be completely unaware of how the caching is actually implemented. As data of any type maybe retrieved from the data source, it makes sense to use generics in the interface, with a generic type parameter defining the data type associated with a particular instance of the cache interface implementation. The C# code for the ICacheProvider interface is shown below: using System; using System.Collections.Generic;   namespace CacheSample.Caching {     public interface ICacheProvider     {     }       public interface ICacheProvider<T> : ICacheProvider     {         T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry);           IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry);     } }   The empty non-generic interface will be used as a type in a Dictionary generic collection later to store instances of the ICacheProvider<T> implementation for reuse, I prefer to use a base interface when doing this, as I think the alternative of using object makes for less clear code. The ICacheProvider<T> interface defines two overloaded Fetch methods, the difference between these is that one will return a single instance of the type T and the other will return an IEnumerable<T>, providing support for easy caching of collections of data items. Both methods will take a key parameter, which will uniquely identify the cached data, a delegate of type Func<T> or Func<IEnumerable<T>> which will provide the code to retrieve the data from the store if it is not present in the cache, and absolute or relative expiry policies to define when a cached item should expire. Note that at present there is no support for cache dependencies, but I shall be showing a method of adding this in part two of this article. CacheProviderFactory Class We need a mechanism of creating instances of our ICacheProvider<T> interface, using Dependency Injection to get the implementation of the interface. To do this we shall create a CacheProviderFactory static class in the CacheSample.Caching project. This factory will provide a generic static method called GetCacheProvider<T>(), which shall return instances of ICacheProvider<T>. We can then call this factory method with the relevant data type (for example the Sale class in the CacheSample.BusinessObject project) to get a instance of ICacheProvider for that type (e.g. call CacheProviderFactory.GetCacheProvider<Sale>() to get the ICacheProvider<Sale> implementation). The C# code for the CacheProviderFactory is shown below: using System; using System.Collections.Generic;   using CacheSample.Caching.Configuration;   namespace CacheSample.Caching {     public static class CacheProviderFactory     {         private static Dictionary<Type, ICacheProvider> cacheProviders = new Dictionary<Type, ICacheProvider>();         private static object syncRoot = new object();           ///<summary>         /// Factory method to create or retrieve an implementation of the  /// ICacheProvider interface for type <typeparamref name="T"/>.         ///</summary>         ///<typeparam name="T">  /// The type that this cache provider instance will work with  ///</typeparam>         ///<returns>An instance of the implementation of ICacheProvider for type  ///<typeparamref name="T"/>, as specified by the application  /// configuration</returns>         public static ICacheProvider<T> GetCacheProvider<T>()         {             ICacheProvider<T> cacheProvider = null;             // Get the Type reference for the type parameter T             Type typeOfT = typeof(T);               // Lock the access to the cacheProviders dictionary             // so multiple threads can work with it             lock (syncRoot)             {                 // First check if an instance of the ICacheProvider implementation  // already exists in the cacheProviders dictionary for the type T                 if (cacheProviders.ContainsKey(typeOfT))                     cacheProvider = (ICacheProvider<T>)cacheProviders[typeOfT];                 else                 {                     // There is not already an instance of the ICacheProvider in       // cacheProviders for the type T                     // so we need to create one                       // Get the Type reference for the application's implementation of       // ICacheProvider from the configuration                     Type cacheProviderType = Type.GetType(CacheProviderConfigurationSection.Current. CacheProviderType);                     if (cacheProviderType != null)                     {                         // Now get a Type reference for the Cache Provider with the                         // type T generic parameter                         Type typeOfCacheProviderTypeForT = cacheProviderType.MakeGenericType(new Type[] { typeOfT });                         if (typeOfCacheProviderTypeForT != null)                         {                             // Create the instance of the Cache Provider and add it to // the cacheProviders dictionary for future use                             cacheProvider = (ICacheProvider<T>)Activator. CreateInstance(typeOfCacheProviderTypeForT);                             cacheProviders.Add(typeOfT, cacheProvider);                         }                     }                 }             }               return cacheProvider;                 }     } }   As this code uses Activator.CreateInstance() to create instances of the ICacheProvider<T> implementation, which is a slow process, the factory class maintains a Dictionary of the previously created instances so that a cache provider needs to be created only once for each type. The type of the implementation of ICacheProvider<T> is read from a custom configuration section in the application configuration file, via the CacheProviderConfigurationSection class, which is described below. CacheProviderConfigurationSection Class The implementation of ICacheProvider<T> will be specified in a custom configuration section in the application’s configuration. To handle this create a folder in the CacheSample.Caching project called Configuration, and add a class called CacheProviderConfigurationSection to this folder. This class will extend the System.Configuration.ConfigurationSection class, and will contain a single string property called CacheProviderType. The C# code for this class is shown below: using System; using System.Configuration;   namespace CacheSample.Caching.Configuration {     internal class CacheProviderConfigurationSection : ConfigurationSection     {         public static CacheProviderConfigurationSection Current         {             get             {                 return (CacheProviderConfigurationSection) ConfigurationManager.GetSection("cacheProvider");             }         }           [ConfigurationProperty("type", IsRequired=true)]         public string CacheProviderType         {             get             {                 return (string)this["type"];             }         }     } }   Adding Data Caching to the Sales Class We now have enough code in place to add caching to the GetSales() method in the CacheSample.BusinessObjects.Sale class, even though we do not yet have an implementation of the ICacheProvider<T> interface. We need to add a reference to the CacheSample.Caching project to CacheSample.BusinessObjects so that we can use the ICacheProvider<T> interface within the GetSales() method. Once the reference is added, we can first create a unique string key based on the method name and the parameter value, so that the same cache key is used for repeated calls to the method with the same parameter values. Then we get an instance of the cache provider for the Sales type, using the CacheProviderFactory, and pass the existing code to retrieve the data from the database as the retrievalMethod delegate in a call to the Cache Provider Fetch() method. The C# code for the modified GetSales() method is shown below: public static IEnumerable<Sale> GetSales(int? highestDayCount) {     string cacheKey = string.Format("CacheSample.BusinessObjects.GetSalesWithCache({0})", highestDayCount);       return CacheSample.Caching.CacheProviderFactory. GetCacheProvider<Sale>().Fetch(cacheKey,         delegate()         {             List<Sale> sales = new List<Sale>();               SqlParameter highestDayCountParameter = new SqlParameter("@HighestDayCount", SqlDbType.SmallInt);             if (highestDayCount.HasValue)                 highestDayCountParameter.Value = highestDayCount;             else                 highestDayCountParameter.Value = DBNull.Value;               string connectionStr = System.Configuration.ConfigurationManager. ConnectionStrings["CacheSample"].ConnectionString;               using (SqlConnection sqlConn = new SqlConnection(connectionStr))             using (SqlCommand sqlCmd = sqlConn.CreateCommand())             {                 sqlCmd.CommandText = "spGetRunningTotals";                 sqlCmd.CommandType = CommandType.StoredProcedure;                 sqlCmd.Parameters.Add(highestDayCountParameter);                   sqlConn.Open();                   using (SqlDataReader dr = sqlCmd.ExecuteReader())                 {                     while (dr.Read())                     {                         Sale newSale = new Sale();                         newSale.DayCount = dr.GetInt16(0);                         newSale.Sales = dr.GetDecimal(1);                         newSale.RunningTotal = dr.GetDecimal(2);                           sales.Add(newSale);                     }                 }             }               return sales;         },         null,         new TimeSpan(0, 10, 0)); }     This example passes the code to retrieve the Sales data from the database to the Cache Provider as an anonymous method, however it could also be written as a lambda. The main advantage of using an anonymous function (method or lambda) is that the code inside the anonymous function can access the parameters passed to the GetSales() method. Finally the absolute expiry is set to null, and the relative expiry set to 10 minutes, to indicate that the cache entry should be removed 10 minutes after the last request for the data. As the ICacheProvider<T> has a Fetch() method that returns IEnumerable<T>, we can simply return the results of the Fetch() method to the caller of the GetSales() method. This should be all that is needed for the GetSales() method to now retrieve data from a cache after the first time the data has be retrieved from the database. Implementing a ASP.NET Cache Provider The final step is to actually implement the ICacheProvider<T> interface, and add the implementation details to the web.config file for the dependency injection. The cache provider implementation needs to have access to System.Web. Therefore it could be placed in the CacheSample.UI project, or in its own project that has a reference to System.Web. Implementing the Cache Provider in a separate project is my favoured approach. Create a new project inside the solution called CacheSample.CacheProvider, and add references to System.Web and CacheSample.Caching to this project. Add a class to the project called AspNetCacheProvider. Make the class a generic class by adding the generic parameter <T> and indicate that the class implements ICacheProvider<T>. The C# code for the AspNetCacheProvider class is shown below: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching;   using CacheSample.Caching;   namespace CacheSample.CacheProvider {     public class AspNetCacheProvider<T> : ICacheProvider<T>     {         #region ICacheProvider<T> Members           public T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry)         {             return FetchAndCache<T>(key, retrieveData, absoluteExpiry, relativeExpiry);         }           public IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry)         {             return FetchAndCache<IEnumerable<T>>(key, retrieveData, absoluteExpiry, relativeExpiry);         }           #endregion           #region Helper Methods           private U FetchAndCache<U>(string key, Func<U> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry)         {             U value;             if (!TryGetValue<U>(key, out value))             {                 value = retrieveData();                 if (!absoluteExpiry.HasValue)                     absoluteExpiry = Cache.NoAbsoluteExpiration;                   if (!relativeExpiry.HasValue)                     relativeExpiry = Cache.NoSlidingExpiration;                   HttpContext.Current.Cache.Insert(key, value, null, absoluteExpiry.Value, relativeExpiry.Value);             }             return value;         }           private bool TryGetValue<U>(string key, out U value)         {             object cachedValue = HttpContext.Current.Cache.Get(key);             if (cachedValue == null)             {                 value = default(U);                 return false;             }             else             {                 try                 {                     value = (U)cachedValue;                     return true;                 }                 catch                 {                     value = default(U);                     return false;                 }             }         }           #endregion       } }   The two interface Fetch() methods call a private method called FetchAndCache(). This method first checks for a element in the HttpContext.Current.Cache with the specified cache key, and if so tries to cast this to the specified type (either T or IEnumerable<T>). If the cached element is found, the FetchAndCache() method simply returns it. If it is not found in the cache, the method calls the retrievalMethod delegate to get the data from the data source, and then adds this to the HttpContext.Current.Cache. The final step is to add the AspNetCacheProvider class to the relevant custom configuration section in the CacheSample.UI.Web.Config file. To do this there needs to be a <configSections> element added as the first element in <configuration>. This will match a custom section called <cacheProvider> with the CacheProviderConfigurationSection. Then we add a <cacheProvider> element, with a type property set to the fully qualified assembly name of the AspNetCacheProvider class, as shown below: <?xmlversion="1.0"?>   <configuration>  <configSections>     <sectionname="cacheProvider" type="CacheSample.Base.Configuration.CacheProviderConfigurationSection, CacheSample.Base" />  </configSections>    <connectionStrings>     <addname="CacheSample"          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=CacheSample"          providerName="System.Data.SqlClient" />  </connectionStrings>    <cacheProvidertype="CacheSample.CacheProvider.AspNetCacheProvider`1, CacheSample.CacheProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">  </cacheProvider>    <system.web>     <compilationdebug="true"targetFramework="4.0" />  </system.web>   </configuration>   One point to note is that the fully qualified assembly name of the AspNetCacheProvider class includes the notation `1 after the class name, which indicates that it is a generic class with a single generic type parameter. The CacheSample.UI project needs to have references added to CacheSample.Caching and CacheSample.CacheProvider so that the actual application is aware of the relevant cache provider implementation. Conclusion After implementing this solution, you should have a working cache provider mechanism, that will allow the middle and data access layers to implement caching support when retrieving data, without any knowledge of the actually caching implementation. If the UI is not ASP.NET based, if for example it is Winforms or WPF, the implementation of ICacheProvider<T> would be written around whatever technology is available. It could even be a standalone caching system that takes full responsibility for adding and removing items from a global store. The next part of this article will show how this caching mechanism may be extended to provide support for cache dependencies, such as the System.Web.Caching.SqlCacheDependency. Another possible extension would be to cache the cache provider implementations instead of storing them in a static Dictionary in the CacheProviderFactory. This would prevent a build up of seldom used cache providers in the application memory, as they could be removed from the cache if not used often enough, although in reality there are probably unlikely to be vast numbers of cache provider implementation instances, as most applications do not have a massive number of business object or model types.

    Read the article

  • Restoring MSDB

    - by David-Betteridge
    We recently performed a disaster recovery exercise which included the restoration of the MSDB database onto our DR server.  I did a quick google to see if there were any special considerations and found the following MS article.  Considerations for Restoring the model and msdb Databases (http://msdn.microsoft.com/en-us/library/ms190749(v=sql.105).aspx).   It said both the original and replacement servers must be on the same version,  I double-checked and in my case they are both SQL Server 2008 R2 SP1 (10.50.2500).. So I went ahead and stopped SQL Server agent, restored the database and restarted the agent.  Checked the jobs and they were all there, everything looked great, and was until the server was rebooted a few days later.Then the syspolicy_purge_history job started failing on the 3rd step with the error message “Unable to start execution of step 3 (reason: The PowerShell subsystem failed to load [see the SQLAGENT.OUT file for details]; The job has been suspended). The step failed.”   A bit more googling pointed me to the msdb.dbo.syssubsystems table SELECT * FROM msdb.dbo.syssubsystems WHERE start_entry_point ='PowerShellStart'   And in particular the value for the subsystem_dll. It still had the path to the SQLPOWERSHELLSS.DLL but on the old server. The DR instance has a different name to the live instance and so the paths are different.   This was quickly fixed with the following SQL Use msdb; GO sp_configure 'allow updates', 1 ; RECONFIGURE WITH OVERRIDE ; GO UPDATE msdb.dbo.syssubsystems SET subsystem_dll='C:\Program Files\Microsoft SQL Server\MSSQL10_50.DR\MSSQL\binn\SQLPOWERSHELLSS.DLL' WHERE start_entry_point ='PowerShellStart'; GO sp_configure 'allow updates', 0; RECONFIGURE WITH OVERRIDE ; GO Stopped and started SQL Server agent and now the job completes.   I then wondered if anything else might be broken, SELECT subsystem_dll FROM msdb.dbo.syssubsystems Shows a further 10 wrong paths – fortunately for parts of SQL (replication, SSIS etc) we aren’t using! Lessons Learnt 1.       DR exercises are a good thing! 2.       Keep the Live and DR environments as similar as possible.    

    Read the article

  • sending email on local machine is not working.

    - by haansi
    I am using my gmail's email account to send emails in asp.net website. It works fine on hosting server but it donot works if I try to sent email on loclserver. Please guide me what I should do to make it sending emails even on localserver ? Do I need to install some smtp server on my local machine ? I have not installed any smtp server on my machine. How and where from I can get smtp server and kindly also guide how I can do its setting to use on local machine. Thnaks Here is my Code public string SendEmail(Email email) { string errmsg = null; if (dt != null) { try { dt = systemrep.GetSystemInfo(); dr = dt.Rows[0]; From = dr["nm_EmailFrom"].ToString(); SMTP = dr["nm_SMTP"].ToString(); Port = dr["amt_Port"].ToString(); EmailId = dr["nm_emailUserId"].ToString(); EmailPassword = dr["nm_emailPassword"].ToString(); DefaultCredations = Convert.ToBoolean(dr["ind_Credentials"].ToString()); MailMessage message = new MailMessage(); SmtpClient smtp = new SmtpClient(); NetworkCredential mailAuthentication = new NetworkCredential(EmailId, EmailPassword); message.To.Add(new MailAddress(email.To)); message.From = new MailAddress(From); message.IsBodyHtml = true; message.Subject = email.Subject; message.Body = email.Message; smtp.UseDefaultCredentials = DefaultCredations; smtp.EnableSsl = true; smtp.Port = 25; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = SMTP; smtp.Credentials = new NetworkCredential(EmailId, EmailPassword); smtp.Send(message); } catch (SmtpException smtpEx) { errmsg = string.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "\\'")); } catch (Exception generalEx) { errmsg = string.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "\\'")); } } else errmsg = "An error accured whilte getting email settings from database, process couldn't be completed"; return errmsg; } }

    Read the article

  • Friday Fun: Turkey Slice

    - by Asian Angel
    In this week’s game you engage in a holiday war with a group of evil turkeys that are determined to ruin your Thanksgiving Day celebrations. Can you put these evil turkeys on the menu where they belong or will they get in the last gobble at your expense? How To Delete, Move, or Rename Locked Files in Windows HTG Explains: Why Screen Savers Are No Longer Necessary 6 Ways Windows 8 Is More Secure Than Windows 7

    Read the article

  • Friday Fun: Museum of Thieves

    - by Asian Angel
    In this week’s game you are lured to the mysterious Museum of Dunt where adventure and an evil force awaits. Can you find the differences in the museum’s strange, shifting rooms as you work your way through it or will the restless evil that dwells within escape? Make Your Own Windows 8 Start Button with Zero Memory Usage Reader Request: How To Repair Blurry Photos HTG Explains: What Can You Find in an Email Header?

    Read the article

  • C++11 Tidbits: access control under SFINAE conditions

    - by Paolo Carlini
    Lately I have been spending quite a bit of time on the SFINAE ("Substitution failure is not an error") features of C++, fixing and tweaking various bits of the GCC implementation. An important missing piece was the implementation of the resolution of DR 1170 which, in a nutshell, mandates that access checking is done as part of the substitution process. Consider: class C { typedef int type; }; template <class T, class = typename T::type> auto f(int) - char; template <class> auto f(...) -> char (&)[2]; static_assert (sizeof(f<C>(0)) == 2, "Ouch"); According to the resolution, the static_assert should not fire, and the snippet should compile successfully. The reason being that the first f overload must be removed from the candidate set because C::type is private to C. On the other hand, before the resolution of DR 1170, the expected behavior was for the first overload to remain in the candidate set, win over the second one, to eventually lead to an access control error (*). GCC mainline (would be 4.8) finally implements the DR, thus benefiting the many modern programming techniques heavily exploiting SFINAE, among which certainly the GNU C++ runtime library itself, which relies on it for the internals of <type_traits> and in several other places. Note that the resolution of the DR is active even in C++98 mode, not just in C++11 mode, because it turned out that the traditional behavior, as implemented in GCC, wasn't fully consistent in all the possible circumstances. (*) In practice, GCC didn't really implement this, the static_assert triggered instead.

    Read the article

  • Binding DataTable To GridView, But No Rows In GridViewRowCollection Despite GridView Population?

    - by KSwift87
    Problem: I've coded a GridView in the markup in a page. I have coded a DataTable in the code-behind that takes data from a collection of custom objects. I then bind that DataTable to the GridView. (Specific problem mentioned a couple code-snippets below.) GridView Markup: <asp:GridView ID="gvCart" runat="server" CssClass="pList" AutoGenerateColumns="false" DataKeyNames="ProductID"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" /> <asp:BoundField DataField="Name" HeaderText="ProductName" /> <asp:ImageField DataImageUrlField="Thumbnail" HeaderText="Thumbnail"></asp:ImageField> <asp:BoundField DataField="Unit Price" HeaderText="Unit Price" /> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="Quantity" runat="server" Text="<%# Bind('Quantity') %>" Width="25px"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Total Price" HeaderText="Total Price" /> </Columns> </asp:GridView> DataTable Code-Behind: private void View(List<OrderItem> cart) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("Cart"); if (cart != null) { dt.Columns.Add("ProductID"); dt.Columns.Add("Name"); dt.Columns.Add("Thumbnail"); dt.Columns.Add("Unit Price"); dt.Columns.Add("Quantity"); dt.Columns.Add("Total Price"); foreach (OrderItem item in cart) { DataRow dr = dt.NewRow(); dr["ProductID"] = item.productId.ToString(); dr["Name"] = item.productName; dr["Thumbnail"] = ResolveUrl(item.productThumbnail); dr["Unit Price"] = "$" + item.productPrice.ToString(); dr["Quantity"] = item.productQuantity.ToString(); dr["Total Price"] = "$" + (item.productPrice * item.productQuantity).ToString(); dt.Rows.Add(dr); } gvCart.DataSource = dt; gvCart.DataBind(); gvCart.Width = 500; for (int counter = 0; counter < gvCart.Rows.Count; counter++) { gvCart.Rows[counter].Cells.Add(Common.createCell("<a href='cart.aspx?action=update&prodId=" + gvCart.Rows[counter].Cells[0].Text + "'>Update</a><br /><a href='cart.aspx?action='action=remove&prodId=" + gvCart.Rows[counter].Cells[0].Text + "/>Remove</a>")); } } } Error occurs below in the foreach - the GridViewRowCollection is empty! private void Update(string prodId) { List<OrderItem> cart = (List<OrderItem>)Session["cart"]; int uQty = 0; foreach (GridViewRow gvr in gvCart.Rows) { if (gvr.RowType == DataControlRowType.DataRow) { if (gvr.Cells[0].Text == prodId) { uQty = int.Parse(((TextBox)gvr.Cells[4].FindControl("Quantity")).Text); } } } Goal: I'm basically trying to find a way to update the data in my GridView (and more importantly my cart Session object) without having to do everything else I've seen online such as utilizing OnRowUpdate, etc. Could someone please tell me why gvCart.Rows is empty and/or how I could accomplish my goal without utilizing OnRowUpdate, etc.? When I execute this code, the GridView gets populated but for some reason I can't access any of its rows in the code-behind.

    Read the article

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