Search Results

Search found 4216 results on 169 pages for 'dr dot'.

Page 12/169 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • 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

  • Mail "Can't continue" for a AppleScript function

    - by Paul J. Lucas
    I'm trying to write an AppleScript for use with Mail (on Snow Leopard) to save image attachments of messages to a folder. The main part of the AppleScript is: property ImageExtensionList : {"jpg", "jpeg"} property PicturesFolder : path to pictures folder as text property SaveFolderName : "Fetched" property SaveFolder : PicturesFolder & SaveFolderName tell application "Mail" set theMessages to the selection repeat with theMessage in theMessages repeat with theAttachment in every mail attachment of theMessage set attachmentFileName to theAttachment's name if isImageFileName(attachmentFileName) then set attachmentPathName to SaveFolder & attachmmentFileName save theAttachment in getNonexistantFile(attachmentPathName) end if end repeat end repeat end tell on isImageFileName(theFileName) set dot to offset of "." in theFileName if dot > 0 then set theExtension to text (dot + 1) thru -1 of theFileName return theExtension is in ImageExtensionList end if return false end isImageFileName When run, I get the error: error "Mail got an error: Can’t continue isImageFileName." number -1708 where error -1708 is: Event wasnt handled by an Apple event handler. However, if I copy/paste the isImageFileName() into another script like: property imageExtensionList : {"jpg", "jpeg"} on isImageFileName(theFileName) set dot to offset of "." in theFileName if dot > 0 then set theExtension to text (dot + 1) thru -1 of theFileName return theExtension is in ImageExtensionList end if return false end isImageFileName if isImageFileName("foo.jpg") then return true else return false end if it works fine. Why does Mail complain about this?

    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

  • formula for replicating glTexGen in opengl es 2.0 glsl

    - by visualjc
    I also posted this on the main StackExchange, but this seems like a better place, but for give me for the double post if it shows up twice. I have been trying for several hours to implement a GLSL replacement for glTexGen with GL_OBJECT_LINEAR. For OpenGL ES 2.0. In Ogl GLSL there is the gl_TextureMatrix that makes this easier, but thats not available on OpenGL ES 2.0 / OpenGL ES Shader Language 1.0 Several sites have mentioned that this should be "easy" to do in a GLSL vert shader. But I just can not get it to work. My hunch is that I'm not setting the planes up correctly, or I'm missing something in my understanding. I've pored over the web. But most sites are talking about projected textures, I'm just looking to create UV's based on planar projection. The models are being built in Maya, have 50k polygons and the modeler is using planer mapping, but Maya will not export the UV's. So I'm trying to figure this out. I've looked at the glTexGen manpage information: g = p1xo + p2yo + p3zo + p4wo What is g? Is g the value of s in the texture2d call? I've looked at the site: http://www.opengl.org/wiki/Mathematics_of_glTexGen Another size explains the same function: coord = P1*X + P2*Y + P3*Z + P4*W I don't get how coord (an UV vec2 in my mind) is equal to the dot product (a scalar value)? Same problem I had before with "g". What do I set the plane to be? In my opengl c++ 3.0 code, I set it to [0, 0, 1, 0] (basically unit z) and glTexGen works great. I'm still missing something. My vert shader looks basically like this: WVPMatrix = World View Project Matrix. POSITION is the model vertex position. varying vec4 kOutBaseTCoord; void main() { gl_Position = WVPMatrix * vec4(POSITION, 1.0); vec4 sPlane = vec4(1.0, 0.0, 0.0, 0.0); vec4 tPlane = vec4(0.0, 1.0, 0.0, 0.0); vec4 rPlane = vec4(0.0, 0.0, 0.0, 0.0); vec4 qPlane = vec4(0.0, 0.0, 0.0, 0.0); kOutBaseTCoord.s = dot(vec4(POSITION, 1.0), sPlane); kOutBaseTCoord.t = dot(vec4(POSITION, 1.0), tPlane); //kOutBaseTCoord.r = dot(vec4(POSITION, 1.0), rPlane); //kOutBaseTCoord.q = dot(vec4(POSITION, 1.0), qPlane); } The frag shader precision mediump float; uniform sampler2D BaseSampler; varying mediump vec4 kOutBaseTCoord; void main() { //gl_FragColor = vec4(kOutBaseTCoord.st, 0.0, 1.0); gl_FragColor = texture2D(BaseSampler, kOutBaseTCoord.st); } I've tried texture2DProj in frag shader Here are some of the other links I've looked up http://www.gamedev.net/topic/407961-texgen-not-working-with-glsl-with-fixed-pipeline-is-ok/ Thank you in advance.

    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

  • Redhat Kernel patching advice

    - by AndyM
    An audit has pointed out that a RHEL server I manage has not had the latest kernel patches applied. I'm confused about kernel patching and within RHEL in relation to RHEL dot releases i.e 5.2 , 5.3 ,5.4 ..... Can someone answer these questions ? If I want to stay at a dot release of RHEL, say 5.4, can apply just updates to the 5.4 kernel or will applying kernel updates bring the server to a later dot release by default? The reason for this question is that I have applications that are only supported on say RHEL5.4 and going to a more recent dot release of RHEL 5 would break the support. I have some HP psp hba drivers compiled against the currently installed kernel, will applying a kernel update break these drivers as they were complied against the orginal kernel ? Anything else I need to look out for with regards to kernel patching ?

    Read the article

  • DVI splitter not working as expected/confusion between DVI-D and -I

    - by Freakishly
    Hey guys, thanks for looking. I have an ATI FirePro™ V3700 in my desktop machine, and I have been running a dual-monitor setup quite effortlessly, thanks to the two DVI ports on the card. I came upon a third monitor, and wanted to extend my desktop to 3 screens, so I purchased a DVI splitter from Amazon. Now, I can only duplicate the second monitor onto the third, not extend it. I've tried all possible combinations of input to no avail. Here's the setup: The ATI FirePro™ V3700 has two Dual-Link DVI-I outputs The splitter splits a single Dual-Link DVI-I port into two Dual-Link DVI-I outputs Two of the monitors are NEC E222W, and the third monitor is a Dell 2001FP. Each monitor has one D-Sub and one Dual-Link DVI-D input. Cables going from the video card to the monitors are two Dual-Link DVI-D to the NECs and one Single-Link DVI-D to the Dell. Is the problem likely with the DVI-D/DVI-I mismatch? Or is it with the cable on the Dell that is only a Single-Link? The cables are easily replaceable, the monitors not so much. Thanks for your time, I really appreciate it. http://www.amd.com/us/products/workstation/graphics/ati-firepro-3d/v3700/Pages/v3700-specs.aspx http://www.amazon.com/Cables-Unlimited-DVI-D-Splitter-PCM-2260/product-reviews/B000H09RFM/ref=dp_top_cm_cr_acr_txt?ie=UTF8&showViewpoints=1 www dot newegg dot com/Product/Product.aspx?Item=N82E16824002495 accessories dot us dot dell dot com/sna/PopupProductDetail.aspx?cs=19&l=en&c=us&sku=320-1578 Apologies for the fudged links, I'm new here and they won't let me post more than two :P

    Read the article

  • Point inside Oriented Bounding Box?

    - by Milo
    I have an OBB2D class based on SAT. This is my point in OBB method: public boolean pointInside(float x, float y) { float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) * (x - center.x)); float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) * (y - center.y)); return (newy > center.y - (getHeight() / 2)) && (newy < center.y + (getHeight() / 2)) && (newx > center.x - (getWidth() / 2)) && (newx < center.x + (getWidth() / 2)); } public boolean pointInside(Vector2D v) { return pointInside(v.x,v.y); } Here is the rest of the class; the parts that pertain: public class OBB2D { private Vector2D projVec = new Vector2D(); private static Vector2D projAVec = new Vector2D(); private static Vector2D projBVec = new Vector2D(); private static Vector2D tempNormal = new Vector2D(); private Vector2D deltaVec = new Vector2D(); private ArrayList<Vector2D> collisionPoints = new ArrayList<Vector2D>(); // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(float centerx, float centery, float w, float h, float angle) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(centerx,centery,w,h,angle); } public OBB2D(float left, float top, float width, float height) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(left + (width / 2), top + (height / 2),width,height,0.0f); } public void set(float centerx,float centery,float w, float h,float angle) { float vxx = (float)Math.cos(angle); float vxy = (float)Math.sin(angle); float vyx = (float)-Math.sin(angle); float vyy = (float)Math.cos(angle); vxx *= w / 2; vxy *= (w / 2); vyx *= (h / 2); vyy *= (h / 2); corner[0].x = centerx - vxx - vyx; corner[0].y = centery - vxy - vyy; corner[1].x = centerx + vxx - vyx; corner[1].y = centery + vxy - vyy; corner[2].x = centerx + vxx + vyx; corner[2].y = centery + vxy + vyy; corner[3].x = centerx - vxx + vyx; corner[3].y = centery - vxy + vyy; this.center.x = centerx; this.center.y = centery; this.angle = angle; computeAxes(); extents.x = w / 2; extents.y = h / 2; computeBoundingRect(); } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0].x = corner[1].x - corner[0].x; axis[0].y = corner[1].y - corner[0].y; axis[1].x = corner[3].x - corner[0].x; axis[1].y = corner[3].y - corner[0].y; // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { float l = axis[a].length(); float ll = l * l; axis[a].x = axis[a].x / ll; axis[a].y = axis[a].y / ll; origin[a] = corner[0].dot(axis[a]); } } public void computeBoundingRect() { boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x)); boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y)); boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x)); boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } public void moveTo(float centerx, float centery) { float cx,cy; cx = center.x; cy = center.y; deltaVec.x = centerx - cx; deltaVec.y = centery - cy; for (int c = 0; c < 4; ++c) { corner[c].x += deltaVec.x; corner[c].y += deltaVec.y; } boundingRect.left += deltaVec.x; boundingRect.top += deltaVec.y; boundingRect.right += deltaVec.x; boundingRect.bottom += deltaVec.y; this.center.x = centerx; this.center.y = centery; computeAxes(); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center.x,center.y,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center.x,center.y,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } public static float distance(float ax, float ay,float bx, float by) { if (ax < bx) return bx - ay; else return ax - by; } public Vector2D project(float ax, float ay) { projVec.x = Float.MAX_VALUE; projVec.y = Float.MIN_VALUE; for (int i = 0; i < corner.length; ++i) { float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay); projVec.x = JMath.min(dot, projVec.x); projVec.y = JMath.max(dot, projVec.y); } return projVec; } public Vector2D getCorner(int c) { return corner[c]; } public int getNumCorners() { return corner.length; } public boolean pointInside(float x, float y) { float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) * (x - center.x)); float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) * (y - center.y)); return (newy > center.y - (getHeight() / 2)) && (newy < center.y + (getHeight() / 2)) && (newx > center.x - (getWidth() / 2)) && (newx < center.x + (getWidth() / 2)); } public boolean pointInside(Vector2D v) { return pointInside(v.x,v.y); } public ArrayList<Vector2D> getCollsionPoints(OBB2D b) { collisionPoints.clear(); for(int i = 0; i < corner.length; ++i) { if(b.pointInside(corner[i])) { collisionPoints.add(corner[i]); } } for(int i = 0; i < b.corner.length; ++i) { if(pointInside(b.corner[i])) { collisionPoints.add(b.corner[i]); } } return collisionPoints; } }; What could be wrong? When I getCollisionPoints for 2 OBBs I know are penetrating, it returns no points. Thanks

    Read the article

  • Huge google impression drop after cleaning html

    - by olgatorresfoundation
    Good morning, I am the webmaster of a non-profit organization that donates grants to colorectal cancer research projects and funds various colorectal cancer information campaigns. We have three domains: www.fundacioolgatorres dot org (Catalan) www.fundacionolgatorres dot org (Spanish) www.olgatorresfoundation dot org (English) So what happened? I redesigned olgatorresfoundation on the 20th and the fundacionolgatorres on the 30th of May. In both cases, exactly two days later, the number of impressions on both dropped to a halt. Granted, we did not have the traffic of Microsoft, but a 90% decrease a disaster of incredible proportions for us. My only real changes were cleaning up the old ineffective HTML to a cleaner form (mostly moving away from redundant table construction to a table-less view). Here is a before and after snapshot of what the change looks like: Before: http://www.fundacioolgatorres.org/aparell_digestiu/introduccio/ (unchanged page in Catalan) After: http://www.olgatorresfoundation.org/digestive_system/introduction/ (changed page in English) Anybody has a clue to what just happened? Why should a normal, sane html improvement be punished and so dramatically? No URLs have been changed, neither have page names or descriptions. Possible secondary question: If it is so that Google sees it as a major overhaul and decides to drop the pagerank sharply, does it come back to pre-change levels if the content "checks out" or will the page start over from scratch earning those pagerank points (which would mean that we would have to wait 6 months for the pages to recover to the level they had two weeks ago)? (duplicated from productforums.google dot com/forum/#!category-topic/webmasters/crawling-indexing--ranking/YsnyX0JzOpY, hoping to reach a wider audience)

    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

  • Implementing Circle Physics in Java

    - by Shijima
    I am working on a simple physics based game where 2 balls bounce off each other. I am following a tutorial, 2-Dimensional Elastic Collisions Without Trigonometry, for the collision reactions. I am using Vector2 from the LIBGDX library to handle vectors. I am a bit confused on how to implement step 6 in Java from the tutorial. Below is my current code, please note that the code strictly follows the tutorial and there are redundant pieces of code which I plan to refactor later. Note: refrences to this refer to ball 1, and ball refers to ball 2. /* * Step 1 * * Find the Normal, Unit Normal and Unit Tangential vectors */ Vector2 n = new Vector2(this.position[0] - ball.position[0], this.position[1] - ball.position[1]); Vector2 un = n.normalize(); Vector2 ut = new Vector2(-un.y, un.x); /* * Step 2 * * Create the initial (before collision) velocity vectors */ Vector2 v1 = this.velocity; Vector2 v2 = ball.velocity; /* * Step 3 * * Resolve the velocity vectors into normal and tangential components */ float v1n = un.dot(v1); float v1t = ut.dot(v1); float v2n = un.dot(v2); float v2t = ut.dot(v2); /* * Step 4 * * Find the new tangential Velocities after collision */ float v1tPrime = v1t; float v2tPrime = v2t; /* * Step 5 * * Find the new normal velocities */ float v1nPrime = v1n * (this.mass - ball.mass) + (2 * ball.mass * v2n) / (this.mass + ball.mass); float v2nPrime = v2n * (ball.mass - this.mass) + (2 * this.mass * v1n) / (this.mass + ball.mass); /* * Step 6 * * Convert the scalar normal and tangential velocities into vectors??? */

    Read the article

  • Making particle bounce off a line with friction

    - by Dlaor
    So I'm making a game and I need a particle to bounce off a line. I've got this so far: public static Vector2f Reflect(this Vector2f vec, Vector2f axis) //vec is velocity { Vector2f result = vec - 2f * axis * axis.Dot(vec); return result; } Which works fine, but then I decided I wanted to be able to change the bounciness and friction of the bounce. I got bounciness down... public static Vector2f Reflect(this Vector2f vec, Vector2f axis, float bounciness) //Bounciness goes from 0 to 1, 0 being not bouncy and 1 being perfectly bouncy { var reflect = (1 + bounciness); //2f Vector2f result = vec - reflect * axis * axis.Dot(vec); return result; } But when I tried to add friction, everything went to hell and back... public static Vector2f Reflect(this Vector2f vec, Vector2f axis, float bounciness, float friction) //Does not work at all! { var reflect = (1 + bounciness); //2f Vector2f subtract = reflect * axis * axis.Dot(vec); Vector2f subtract2 = axis * axis.Dot(vec); Vector2f result = vec - subtract; result -= axis.PerpendicularLeft() * subtract2.Length() * friction; return result; } Any physics guys willing to help me out with this? (if you're not sure what I mean with the friction of a bounce see this: http://www.metanetsoftware.com/technique/diagrams/A-1_particle_collision.swf)

    Read the article

  • What is causing this behavior with the movement of Pong Ball in 2D? [closed]

    - by thegermanpole
    //edit after running it through the debugger it turned out i had the display function set to x,x...TIL how to use a debugger I've been trying to teach myself C++ SDL with the lazyfoo tutorial and seem to have run into a roadblock. The code below is the movement function of my Dot class, which controls the ball. The ball seems to ignore yvel and moves with xvel to the bottom right. The code should be pretty readable, the rest of the relevant facts are: All variables are names Constants are in caps dotrad is the radius of my dot yvel and xvel are set to 5 in the constructor The dot is created at x and y equal to 100 When I comment out the x movement block it doesn't move, but if i comment out the y movement block, it keeps on going down to the right. void Dot::move() { if(((y+yvel+dotrad) <= SCREEN_HEIGHT) && (0 <= (y-dotrad+yvel))) { y+=yvel; } else { yvel = -1*yvel; } if(((x+xvel+dotrad) <= SCREEN_WIDTH) && (0 <= (x-dotrad+xvel))) { x +=xvel; } else { xvel = -1*xvel; } }

    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

  • COM INTEROP Support - which is better? C# or VB

    - by dot
    I keep hearing that c# is "better" than vb... but as far as I can see, aside from syntactical differences, both compile down to the same IL. I've found some good articles by googling that explain what the differences are between the two and so I feel comfortable in "diffusing" conversations between developers arguing over vb / c#. =) But I did read an article that said vb.net 2005 had better support for com interop stuff. But i'm wondering if this is still the case? This is of interest to me because we are in the middle of redesigning an old vb6 app that communicates with some older COM components. Does anyone have recent experience with .NET and COM interop? Thanks.

    Read the article

  • Configurable tables in sql database

    - by dot
    I have the following tables in my database: Config Table: ====================================== Start_Range | End Range | Config_id 10 | 15 | 1 ====================================== Available_UserIDs ========================== ID | UserID | Used_YN | 1 | 10 | t | 1 | 11 | f | 1 | 12 | f | 1 | 13 | f | 1 | 14 | f | 1 | 15 | f | ========================== Users ========================== UserId | FName | LName | 10 |John | Doe | ========================== This is used in a reservation system of sorts... which lets an administrator specify a range of numbers that will be assigned to users in the config table. Once the range has been defined, the system then populates the Available_userIDs table with all the numbers in between the range, and sets the Used_YN flag to false As users sign up, they grab the next user_id number that's not in use... and reserve it. Then the system adds a record to the Users table. Once the admin has specified a range, it is possible that they can change it. For example, they can start with 10-15... and then when the range is used up, they should be able to specify another range like 16 - 99. I've put a unique constraint on the Available_UserIDs table, as well as on the Users table - to ensure that UserIds can't be duplicated. My questions are as follows: What's the best way to prevent the admins from using a range that's already in use? I thought of the following options: -- check either the Users table to see if the start range or ending range numbers are being used. If they are, assume that all the numbers in between are in use too, and reject the range. -- let them specify whatever they want, try to populate the Available_UserIDs table. If there are duplicates, just ignore that specific error message from the database and continue on. How do I find gaps in the number ranges? For example, if they specify 10-15, and then 20-25, it'd be nice to be able to somehow suggest on my web page that 16-19 is currently available. I found this article: http://stackoverflow.com/questions/1312101/how-to-find-a-gap-in-running-counter-with-sql But it only seems to return the first available number... so in my example above, it would only return the number 16. I'm sure there's a simpler way to do things that I'm overlooking!

    Read the article

  • install android sdk on kubuntu

    - by dot
    I'm trying to follow the instructions for installing the android sdk found here: http://developer.android.com/sdk/installing/adding-packages.html After i've unpackaged and i run the android program under tools, I don't get all the options that I'm supposed to. The only 2 folders that show up are tools, and extras. Under tools, it only shows the "Android SDK Tools" with the status "Installed". Under the "extas" folder, I have nothing. I've made sure that my http: proxy settings are correct. And I've checked the logs. there are no errors. According to the android developer site, I'm supposed to install the SDK platform tools. has anyone tried this on ubuntu? I also checked and saw others were instructed to do an apt-get install ia32-libs but it failed for me. Besides which, I am running the 32bit os... so I don't think i would need to install that... ?? I've also tried following the instructions found here: http://forums.team-nocturnal.com/showthread.php/772 But... I can't seem to add the personal archive nilarimogard without getting an error message. when i attempt: sudo add-apt-repository ppa:nilarimogard/webupd8 I get the message: Traceback (most recent call last): File "/usr/bin/add-apt-repository", line 125, in ppa_info = get_ppa_info_from_lp(user, ppa_name) File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 80, in get_ppa_info_from_lp curl.perform() pycurl.error: (7, "couldn't connect to host") root@jll:/home/me/Documents# any suggestions? Thanks.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >