Archive for Maggio, 2008

Cambiar la fecha del sistema

CodeKeep C# Feed Maggio 25th, 2008

Description: Cambiar la fecha del sistema

Link: http://www.codekeep.net/snippets/1caf5b81-b062-46ea-974f-e04c87b36c41.aspx

	class Program
	{

        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        public struct SYSTEMTIME
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }

        [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetLocalTime(ref SYSTEMTIME _time);

        static void Main(string[] args) {

        	SYSTEMTIME _time;

        	_time.wYear = 2000;
            _time.wMonth = 04;
            _time.wDay = 09;

            _time.wDayOfWeek = 1;

            _time.wHour = (short)DateTime.Now.Hour;
            _time.wMinute = (short)DateTime.Now.Minute;
            _time.wSecond = (short)DateTime.Now.Second;
            _time.wMilliseconds = (short)DateTime.Now.Millisecond;

            SetLocalTime(ref _time);

        }

	}

Crop Text remove HTML

CodeKeep C# Feed Maggio 25th, 2008

Description: Classe para realizar um Crop do Texto informado e remover o HTML do texto

Link: http://www.codekeep.net/snippets/e8c5e408-1060-4a06-95f5-82b6c255c8e1.aspx

namespace Crop.Retorna
{
    using System.Text.RegularExpressions;

    public class cropRetorna
    {
        public string CropSentence(string textCrop, int num, string trail)
        {
            int iMax;
            Regex rx = new Regex("<[^>]*>");

            textCrop = rx.Replace(textCrop, "");

            iMax = num - trail.Length;

            if (iMax <= 0)
            {
                return "";
            }
            else if (textCrop.Length <= num)
            {
                return textCrop;
            }
            else
            {
                #region Crop

                string sOut;
                sOut = textCrop.Substring(0, num);

                int iPos;
                iPos = sOut.LastIndexOf(" ");

                return sOut.Substring(0, iPos) + trail;

                #endregion
            }
        }
    }
}

Insert Usando LINQ

CodeKeep C# Feed Maggio 25th, 2008

Description: Insert Usando LINQ

Link: http://www.codekeep.net/snippets/eba23b71-6170-4663-9f8d-440273d8889b.aspx

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
        <SnippetType>Refactoring</SnippetType>
      </SnippetTypes>
      <Title>Delete</Title>
      <Shortcut>Linq List</Shortcut>
      <Description>Delete</Description>
      <Author>Paulo Lima</Author>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>NomedaClasse</ID>
          <ToolTip>
          </ToolTip>
          <Default>NomedaClasse</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>NomedoDataContext</ID>
          <ToolTip>
          </ToolTip>
          <Default>NomedoDataContext</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>VarNome</ID>
          <ToolTip>
          </ToolTip>
          <Default>VarNome</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>Var</ID>
          <ToolTip>
          </ToolTip>
          <Default>Var</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>ID</ID>
          <ToolTip>
          </ToolTip>
          <Default>ID</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[	 [DataObjectMethod(DataObjectMethodType.Delete, false)]
        public static void Delete(int $ID$)
            {
            using ($NomedoDataContext$ pag = new $NomedoDataContext$())
                {
                var $VarNome$ = from $Var$ in pag.$NomedaClasse$
                              where $Var$.$ID$ == $ID$
                              select $Var$;
                $VarNome$.$NomedaClasse$.DeleteOnSubmit($VarNome$.SingleOrDefault());
                pag.SubmitChanges();
                }
            }]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Sort list of custom objects

CodeKeep C# Feed Maggio 23rd, 2008

Description: How to sort a list of custom objects

Link: http://www.codekeep.net/snippets/f9ad5647-8d1d-45ae-bd20-3e5ec077ae43.aspx

    public abstract class MyObjects: IComparable<Actions>
    {
        public Int64 sortnumber { get; set; }

        /// <summary>
        /// Compare two objects
        /// </summary>
        /// <param name="other">The objects to be compared with.</param>
        /// <returns>
        /// A 32-Bit Signed Integer that states the relative sortorder of the two objects
        /// </returns>
        public int CompareTo(Actions other)
        {
            return this.sortnumber.CompareTo(other.sortnumber);
        }
    }

Parse CSV row using Regex

CodeKeep C# Feed Maggio 22nd, 2008

Description: Returns an array of values from a CSV row handling columns in double and single quotes. This has been adapted from the example code found here : http://www.omegacoder.com/?p=60

Link: http://www.codekeep.net/snippets/5d115467-5515-451a-800e-14623f49fc9d.aspx

string[] ParseCSVLine(string text)
{
    Regex rx = new Regex("((?([\\x27\\x22])(?:[\\x27\\x22])(?<Column>[^\\x27\\x22]*)(?:[\\x27\\x22])|(?<Column>[^,\r\n]*]*))(?:,?))+(?:$|[\r\n]{0,2})", RegexOptions.IgnorePatternWhitespace);

    List<string> line = new List<string>();

    foreach (Match m in rx.Matches(text))
    {
         if (m.Success)
         {
              foreach (Capture cp in m.Groups["Column"].Captures)
              {
                  if (string.IsNullOrEmpty(cp.Value) == false)
                  line.Add(cp.Value);
              }
          }
    }

    return line.ToArray();
}

Get last windows error

CodeKeep C# Feed Maggio 22nd, 2008

Description: Get last windows error after messing around with PInvoke

Link: http://www.codekeep.net/snippets/93389a9c-8d9a-4755-9c95-d74d44f73c62.aspx

String error = new Win32Exception(Marshal.GetLastWin32Error()).Message;

add SQL para

CodeKeep C# Feed Maggio 21st, 2008

Description: add SQL para

Link: http://www.codekeep.net/snippets/32b4567a-416d-47e0-8dd1-ecbbff58900c.aspx

SqlParameter para = dbCmd.Parameters.Add("para", SqlDbType.Int, 4);
para.Value = ;

Streaming Object to DB in Binary format

CodeKeep C# Feed Maggio 21st, 2008

Description: Take an objsct, serialize it, store it in a db, retrieve it and recreate the object

Link: http://www.codekeep.net/snippets/3a616b3f-a02c-400c-bb91-b118549ead82.aspx

		/// <summary>
		/// Cache the gpEncounter to DB
		/// </summary>
		private void SaveToCache()
		{
			// Serialize to a memory stream
			MemoryStream stream = new MemoryStream();
			DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
			serializer.WriteObject(stream, _gpEncounter);
			// Just make sure we're pointing at the beginning of the stream
			stream.Seek(0, SeekOrigin.Begin);
			// Save stream to the DB
			CachingDataAccess.CacheGpEncounter(_guid, stream);
			//Clean up
		}
		/// <summary>
		/// Retrieve the GpEncounter from the DB
		/// </summary>
		private void RetrieveFromCache()
		{
			byte[] rawdata = CachingDataAccess.UnCacheGpEncounter(_guid);
			MemoryStream stream = new MemoryStream(rawdata);
			DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
			stream.Seek(0, SeekOrigin.Begin);
			_gpEncounter = (GpEncounter) serializer.ReadObject(stream);
		}

		public static bool CacheGpEncounter(Guid guid, MemoryStream gpEncounterMemoryStream)
		{
			Database db = DatabaseFactory.CreateDatabase("StatConnection");
			byte[] bytes = gpEncounterMemoryStream.ToArray();//NB Do Not use GetBuffer()
			string sqlCommand = @"Delete from Cache where CacheGUID = @guid;
								INSERT INTO Cache (CacheGUID, Blob) VALUES  (@guid, @data )";
			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
			db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
			db.AddInParameter(dbCommand, "data", DbType.Binary, bytes);
			db.ExecuteNonQuery(dbCommand);
			return true;

		}
		public static Byte[] UnCacheGpEncounter(Guid guid)
		{
			Database db = DatabaseFactory.CreateDatabase("StatConnection");
			string sqlCommand = @"SELECT Blob FROM Cache WHERE CacheGUID = @guid";
			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
			db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
			DataTable table = new DataTable();
			byte[] bytes = (byte[]) db.ExecuteScalar(dbCommand);

			return bytes;
		}

root url

Get Rounded Rectangle Path

CodeKeep C# Feed Maggio 18th, 2008

Description: Get Rounded Rectangle Path for Rectangle

Link: http://www.codekeep.net/snippets/f292c56e-be89-4562-aac9-6722649659e4.aspx

     /// <summary>
        /// Gets the path.
        /// </summary>
        /// <param name="rc">The rc.</param>
        /// <param name="r">The radius for corner edges.</param>
        /// <returns></returns>
        private GraphicsPath GetPath(RectangleF rc, int r)
        {

            float x = rc.X, y = rc.Y, w = rc.Width, h = rc.Height;
            GraphicsPath path = new GraphicsPath();
            path.AddArc(x, y, r, r, 180, 90);				//Upper left corner
            path.AddArc(x + w - r, y, r, r, 270, 90);			//Upper right corner
            path.AddArc(x + w - r, y + h - r, r, r, 0, 90);		//Lower right corner
            path.AddArc(x, y + h - r, r, r, 90, 90);			//Lower left corner
            path.CloseFigure();
            return path;
        }

« Prev - Next »