Search Results

Search found 3873 results on 155 pages for 'dr mike'.

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

  • 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

  • BI-Applications Special Price Promotion for Partners

    - by Mike.Hallett(at)Oracle-BI&EPM
    Partners should keep in mind the “Midsize Market” pricing promotion for BI-Applications solution packages, with reduced minimums applicable to Oracle's Business Intelligence Products, and a pre-approved 50% discount. ·       Partners additionally get their normal e-business reseller discount. This now makes it most attractive to offer the pre-built BI-Applications such as Manufacturing Analytics, Financial Analytics, Procurement and Spend Analytics, Project Analytics, and Human Resources Analytics, to both customers newly implementing Oracle ERP, and for the many existing Oracle ERP (eBusiness suite, Peoplesoft and JDE) customers. To answer any questions, and to get the partner document with further details of this offer, or to work with us on our local sales campaigns targeting existing ERP customers, please send your query to Mike[email protected] or [email protected]: or discuss it with your local Oracle Sales or Channel representative for Applications to Midsize Enterprises.  This promotion is ONLY for End Customers whose organisations have an Annual Revenue (or Public Sector Budget) below $500 million, and who are based in Europe, the Middle East or Africa. For more information see the orginal article, “New fy13 BI-Applications Price Promotion for MIDSIZE CUSTOMERS”  and send your query to Mike[email protected].

    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

  • PHP find first of occurrence of string

    - by mike
    I have a string of data like below and I've been struggling trying to figure out how to split it up so that I can use it efficiently. "United States FirstName: Mike LastName: Wolf City: Chicago" I need to split up the string in to substrings and the list may not always be in the same order. For example it could vary like below: "United States City: Chicago FirstName: Mike LastName: Wolf" "United States FirstName: City: Chicago Mike LastName: Wolf" I need to find which parameter comes first after 'United States'. It could be 'City:', 'FirstName:' or 'LastName:'. And, I also need to know the start position of the first parameter. Thanks in advance!

    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

  • Silverlight Cream for December 08, 2010 -- #1005

    - by Dave Campbell
    In this Issue: Peter Kuhn, David Anson, Jesse Liberty, Mike Taulty(-2-, -3-), Kunal Chowdhury, Jeremy Likness, Martin Krüger, Beth Massi(-2-, -3-)/ Above the Fold: Silverlight: "Rebuilding the PDC 2010 Silverlight Application (Part 1)" Mike Taulty WP7: "WP7: Glossy text block custom control" Martin Krüger Lightswitch: "How to Create a Screen with Multiple Search Parameters in LightSwitch" Beth Massi From SilverlightCream.com: Requirements of and pitfalls in Windows Phone 7 serialization Peter Kuhn discusses Data Contract Serializer issuses on WP7 and how to work around them. Managed implementation of CRC32 and MD5 algorithms updated; new release of ComputeFileHashes for Silverlight, WPF, and the command-line! David Anson ties up some loose ends from a prior post on hash functions, and updates his CRC32 and MD5 algorithms. Windows Phone From Scratch #9 – Visual State Jesse Liberty's latest Windows Phone from Scratch tutorial up... and is on the Visual State... he extends a Button and codes up the State Transitions. Rebuilding the PDC 2010 Silverlight Application (Part 1) Mike Taulty has taken the time to rebuild the PDC2010 Silverlight App that folks wanted the source for... and he's taking multiple posts to explain the heck out of it. This first one is mostly infrastructure. Rebuilding the PDC 2010 Silverlight Application (Part 2) In the 2nd post of the series, Mike Taulty is handling the In/Out of Browser business because he eventually is going to be going OOB. Rebuilding the PDC 2010 Silverlight Application (Part 3) Part 3 finds Mike Taulty delving into WCF Data Services and getting some data on the screen. Paginating Records in Silverlight DataGrid using PagedCollectionView Kunal Chowdhury continues with his investigation of the PagedCollectionView with this post on Pagination of your data. Old School Silverlight Effects If you haven't seen Jeremy Likness' 'Old School' Effects page yet, go just for the entertainment... you'll find yourself hanging around for the code :) WP7: Glossy text block custom control Martin Krüger's latest post is a very cool custom control for WP7 that displays Glossy text... it ain't Metro, but it looks pretty nice... some of it almost like etched text. How to Create a Screen with Multiple Search Parameters in LightSwitch Looks like Beth Massi got a few Lightswitch posts in while I wasn't looking. First up is this one on a multiple-parameter search screen. Adding Static Images and Logos to LightSwitch Applications In the 2nd post, Beth Massi shows how to add your own static images and logos to Lightswitch apps... in response to reader questions. Getting the Most out of LightSwitch Summary Properties In her latest post, Beth Massi explains what Summary Properties are in Lightswitch and how to use them to get the best results for your users. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    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

  • Podcast Show Notes: Evolving Enterprise Architecture

    - by Bob Rhubart
    The latest series of ArchBeat podcast programs grew out of another virtual meet-up, held on March 11. As with previous meet-ups, I sent out a general invitation to the roster of previous ArchBeat panelists to join me on Skype to talk about whatever topic comes up. For this event, Oracle ACE Directors Mike van Alst and Jordan Braunstein  showed up, along with Oracle product manager Jeff Davies.  The result was an impressive and wide-ranging discussion on the evolution of Enterprise Architecture, the role of technology in EA, the impact of social computing, and challenge of having three generations of IT people at work in the enterprise – each with different perspectives on technology. Mike, Jordan, and Jeff talked for more than an hour, and the conversation was so good that slicing and dicing it to meet the time constraints for these podcasts has been a challenge. The first two segments of the conversation are now available. Listen to Part 1 Listen to Part 2 Part 3 will go live next week, and an unprecedented fourth segment will follow. These guys have strong opinions, and while there is common ground, they don’t always agree. But isn’t that what a community is all about? I suspect that you’ll have questions and comments after listening, so I encourage you to reach out to Mike, Jordan, and Jeff  via the following links: Mike van Alst Blog | Twitter | LinkedIn | Business |Oracle Mix | Oracle ACE Profile Jordan Braunstein Blog | Twitter | LinkedIn | Business | Oracle Mix | Oracle ACE Profile Jeff Davies Homepage | Blog | LinkedIn | Oracle Mix (Also check out Jeff’s book: The Definitive Guide to SOA: Oracle Service Bus)   Coming Soon ArchBeat’s microphones were there for the panel discussions at the recent Oracle Technology Network Architect Days in Dallas and Anaheim. Excerpts from those conversations will be available soon. Stay tuned: RSS Technorati Tags: oracle,otn,enterprise architecture,podcast. arch2arch,archbeat del.icio.us Tags: oracle,otn,enterprise architecture,podcast. arch2arch,archbeat

    Read the article

  • Podcast Show Notes: Evolving Enterprise Architecture

    - by Bob Rhubart
    Back in March Oracle ACE Directors Mike van Alst (IT-Eye) and Jordan Braunstein (Visual Integrator Consulting) and Oracle product manager Jeff Davies participated in an ArchBeat virtual meet-up. The resulting conversation quickly turned to the changing nature of enterprise architecture and the various forces driving that change. All four parts of that wide-ranging conversation are now available. Listen to Part 1 Listen to Part 2 Listen to Part 3 Listen to Part 4 As you’ll hear, Mike, Jordan, and Jeff bring unique perspectives and opinions to this very lively conversation. These are three very sharp, very experienced guys, as and you might expect, they don’t always walk in lock-step when it comes to EA. You can learn more about Mike, Jordan, and Jeff – and share your opinions with them -- through the links below: Mike van Alst Blog | Twitter | LinkedIn | Business |Oracle Mix | Oracle ACE Profile Jordan Braunstein Blog | Twitter | LinkedIn | Business | Oracle Mix | Oracle ACE Profile Jeff Davies Homepage | Blog | LinkedIn | Oracle Mix (Also check out Jeff’s book: The Definitive Guide to SOA: Oracle Service Bus) Up Next Next week’s program features highlights from the panel discussion at the Oracle Technology Architect Day event held in Anaheim, CA on May 19. You’ll hear from Oracle ACE Directors Basheer Khan and Floyd Teter, Oracle virtualization expert and former Sun Microsystems principal engineer Jeff Savit, Oracle security analyst Geri Born, and event MC Ralf Dossman, Director of SOA and Middleware in Oracle’s Enterprise Solutions Group. Stay tuned: RSS

    Read the article

  • Silverlight Cream for April 23, 2010 -- #845

    - by Dave Campbell
    In this Issue: Jason Allor, Bill Reiss, Mike Snow, Tim Heuer, John Papa, Jeremy Likness, and Dave Campbell. Shoutouts: You saw it at MIX10 and DevConnections... now you can give it a dance, John Papa announced eBay Simple Lister Beta Now Available Mike Snow posted some info about and a link to his new Flickr/Bing/Google High End Image Viewer and he's looking for feedback From SilverlightCream.com: Hierarchical Data Trees With A Custom DataSource Jason Allor is rounding out a series here in his new blog (bookmark it), and he's created his own custom HierarchicalDataSource class for use with the TreeView. Space Rocks game step 11: Start level logic Bill Reiss has Episode 11 up in his Space Rocks game ... working on NewGame and start level logic Silverlight Tip of the Day #3 – Mouse Right Clicks Mike Snow has Tip 3 up ... about handling right-mouse clicks in Silverlight 4 -- oh yeah, we got right mouse now ... grab Mike's project to check it out. Silverlight 4 enables Authorization header modification Tim Heuer talks about the ability to modify the Authorization header in network calls with Silverlight 4. He gives not only the quick-and-dirty of how to use it, but has some good examples, code, and code results for show and tell. WCF RIA Services - Hands On Lab John Papa built a bookstore app in roughly 10 minutes in the keynote at DevConnections. He now has a tutorial on doing just that plus all the code up. Transactions with MVVM Not strictly Silverlight (or WPF), but Jeremy Likness has an interesting article up on MVVM and transaction processing. Read the post then grab his helper class. Your First Windows Phone 7 Application As with the First Silverlight App a couple weeks ago, if you've got any WP7 experience at all, just keep going... this is for folks that have not looked at it yet, have not downloaded anything... oh, and it's by Dave Campbell Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    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

  • Rumor Mill: New Features SQL 11

    - by Mike Femenella
    For those of you that remember the old Mike Myers SNL skit, talk amongst yourselves..I’ll give you a topic: This is purely based on 1 conversation with 1 person from the mothership (Microsoft). SQL 11 is in the works and supposedly includes readable mirrors and in the version beyond that read/write mirrors. Given the name I would assume that release would be (drum roll) 2011 some time. Discuss.

    Read the article

  • Natural Language parsing of an appointment?

    - by Mike Hugo
    I'm looking for a Java library to help parse user entered text that represents an 'appointment' for a calendar application. For instance: Lunch with Mike at 11:30 on Tuesday or 5pm Happy hour on Friday I've found some promising leads like https://jchronic.dev.java.net/ and http://www.datejs.com/ which can parse dates - but I also need to be able to extract the title of the event like "Lunch with Mike". If such an API doesn't exist, I'm also interested in any thoughts on how best to approach the problem from a coding perspective.

    Read the article

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