الخميس، 11 يونيو 2015

Flush Memory


        [DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize",                  ExactSpelling = true,
         CharSet = CharSet.Ansi, SetLastError = true)]
        ////[return: MarshalAs(UnmanagedType.Bool)]
        private static extern int SetProcessWorkingSetSize(IntPtr process, int                          minimumWorkingSetSize,
             int maximumWorkingSetSize);
        /// <summary>
        /// Will request to flush the memory
        /// </summary>
        public static void FlushMemory()
        {
            GC.Collect(GC.MaxGeneration);
            GC.WaitForPendingFinalizers();

            //if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
        } 

Validate Email Address

       #region validEmailRegex

        private static readonly Regex validEmailRegex = new Regex(
            @"^(([^<>()[\]\\.,;:\s@\""]+"
            + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
            + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
            + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
            + @"[a-zA-Z]{2,}))$",
            RegexOptions.Compiled);

        #endregion


        public static bool IsValidEmailAddress(string email)
        {
            if(!string.IsNullOrEmpty(email))
            return validEmailRegex.IsMatch(email.Trim());
            return false;
        }

Remove BorderBox,TextAlignment and ForeColor - radGridView1_CellFormatting Event

private void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)
        {
            try
            {
                if (e.CellElement != null && e.RowIndex > -1)
                {
                    //remove border box
                    var style = new BorderBoxStyle();
                    e.CellElement.BorderBoxStyle = style;
                    e.CellElement.BorderWidth = 0;

                    if (e.Column.Name == "UserName")
                    {
                        e.CellElement.Font = new Font("Arial", 8, FontStyle.Bold);
                        if (Convert.ToInt32(e.Row.Cells["UserId"].Value) == MyParameters.userProfile.UserId)
                            e.CellElement.ForeColor = Color.DodgerBlue;
                        else
                        {
                            e.CellElement.ForeColor = Color.Black;
                        }
                        e.CellElement.TextAlignment = ContentAlignment.TopLeft;
                    }
                    else
                        e.CellElement.ForeColor = Color.Black;
                }
            }
            catch (Exception ex)
            {
                RadMessageBox.Show(MyMethods.ExceptionDetails(ex), "Exception", MessageBoxButtons.OK,
                    RadMessageIcon.Error);
            }
        }

System.Threading.Timer and Control.Invoke

private System.Threading.Timer _updateCommentsTimer;
_updateCommentsTimer = new System.Threading.Timer(UpdateComments);
_updateCommentsTimer.Change(0, 3500);
_timerStarted = true;
private void UpdateComments(object status)
{
  // do what u want, invoke UI maybe required..
  if (txtBoxProcess.InvokeRequired)
                            {
                                txtBoxProcess.Invoke(new MethodInvoker(() =>
                                {
                                      txtBoxProcess.Text="ant text";//
                                }));
                            }
                            else
                            {
                                      txtBoxProcess.Text="";
                            }
}

// you can dispose the timer (stop)..
if (_timerStarted)
   _updateCommentsTimer.Dispose();  

Output parameters - StoredProcedure and Code Behind

Stored Procedure: (get all comments for the other users with me in the same session)

CREATE PROCEDURE [dbo].[GetSessionCommentsNotmine]
@SessionId int,
@UserId int,
@SessionCommentsId int,
-- return output parameters
@SessionStatus bit out,
@IsSessionCompleted bit out
AS
SELECT * FROM SessionComments
WHERE SessionComments.SessionId=@SessionId
AND SessionComments.UserId!=@UserId
-- this condition to get all comment befor this id..
AND SessionComments.SessionCommentsId>@SessionCommentsId
BEGIN
SET @IsSessionCompleted =(select SessionMembers.IsSessionCompletedfrom SessionMembers where SessionMembers.SessionId=@SessionId andSessionMembers.UserId=@UserId) 
      SET @SessionStatus =(select Sessions.IsClosed from Sessionswhere Sessions.SessionId=@SessionId)           
END
return


Code behind :
ObjectParameter sessionStatus = 
                new ObjectParameter("SessionStatus", typeof (bool));
ObjectParameter isSessionCompleted = 
                new ObjectParameter("IsSessionCompleted", typeof(bool));
//This will provide the parameter, and contain the returned value.
ICollection<SessionComments> comments =
       _entities.GetSessionCommentsNotmine(_session.SessionId,MyParameters.userProfile.UserId,
       _lastSessionId, sessionStatus, isSessionCompleted).ToList();


الأربعاء، 10 يونيو 2015

Control.InvokeRequired Property, Radgridview AutoSizeColumnsMode

// add comment to grid
if (radGridView1.InvokeRequired)
{
       radGridView1.Invoke(new MethodInvoker(() =>
       {
               this.radGridView1.BeginEdit();
               radGridView1.Rows.Add(MyParameters.userProfile.UserId,
                                MyParameters.userProfile.UserName + " (" +                                                   DateTime.Now.ToString("hh:mm") + "): ",
                                comment);
               radGridView1.EndEdit();
                         
       })); 
 }
   else
        {
              //this.radGridView1.BeginEdit();
              radGridView1.Rows.Add(MyParameters.userProfile.UserId,
                            MyParameters.userProfile.UserName + " (" +                                                   DateTime.Now.ToString("hh:mm") + "): ",comment);
          }                   
radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
radGridView1.MasterTemplate.BestFitColumns(BestFitColumnMode.DisplayedCells);
radGridView1.TableElement.ScrollToRow(radGridView1.Rows.Last());

Export from Radgridview to many types of documents

RadContextMenu Declaration (you can drag this control from toolbox) :

private Telerik.WinControls.UI.RadContextMenu radContextMenuExportTo;
this.radContextMenuExportTo = new Telerik.WinControls.UI.RadContextMenu(this.components);

this.radContextMenuExportTo.Items.AddRange(new Telerik.WinControls.RadItem[] {
this.btnxlsx,
this.btncsv,
this.btnpdf,
this.btntxt});


Display ContextMenu :
private void btnExport_Click(object sender, EventArgs e)
        {
            var btnSender = (RadButton)sender;
            var ptLowerLeft = new Point(0, btnSender.Height);
            ptLowerLeft = btnSender.PointToScreen(ptLowerLeft);
            radContextMenuExportTo.Show(ptLowerLeft);
        }


One event for all the buttons:

private void btnDocExcell_Click(object sender, EventArgs e)
        {
            var btnSender = (RadMenuItem)sender;
            if (btnSender.Tag != null)
                MyMethods.Export(radGridView1, btnSender.Tag.ToString(), lblDocumentSubject.Text);
        }


Export Method :
public static void Export(RadGridView radGridView1, string btnSenderName, string docSubject)
        {
            SpreadExport spreadExporter = new SpreadExport(radGridView1);
            var dialog = new SaveFileDialog();
            dialog.FileName = docSubject.Trim();
            dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            switch (btnSenderName)
            {
                case "xlsx":
                    spreadExporter.ExportFormat = SpreadExportFormat.Xlsx;
                    dialog.Filter = "xlsx files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                    break;
                case "csv":
                    spreadExporter.ExportFormat = SpreadExportFormat.Csv;
                    dialog.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
                    break;
                case "pdf":
                    spreadExporter.ExportFormat = SpreadExportFormat.Pdf;
                    dialog.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
                    break;
                case "txt":
                    spreadExporter.ExportFormat = SpreadExportFormat.Txt;
                    dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                    break;
            }
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // by using FileInfo instance method delete the file if exist.
                    var fi = new FileInfo(@dialog.FileName);
                    fi.Delete();

                    spreadExporter.ExportVisualSettings = true;
                    spreadExporter.SummariesExportOption = Telerik.WinControls.UI.Export.SummariesOption.DoNotExport;
                    spreadExporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
                    spreadExporter.RunExport(dialog.FileName);
                }
                catch (Exception)
                {
                    RadMessageBox.Show("Import not supported, please try again. ");
                }
            }
        }