Wednesday, 21 October 2015

Managing Task Scheduler from front end (Taskschd.msc)

Controlling is behaviour of Task Scheduler is very easy. Follow these steps:

Step 1:

Add Microsoft.Win32.TaskScheduler dll to your project. Download it if not available.

Step 2:

I guess if you workingin winform then take a datagridview.

Step 3:

Here the code part.

using Microsoft.Win32.TaskScheduler;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
 
    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.DataSource = AllTaskNames();
    }
     
public List<SchedulerModel> GetAllTasks()
{
List<SchedulerModel> TaskList = new List<SchedulerModel>();

using (TaskService ts = new TaskService())
{
var tst = ts.GetFolder(@"\Microsoft\MyTasks");

if (tst != null)
{
var tasks = tst.AllTasks;
foreach (var t in tasks)
{
SchedulerModel sM = new SchedulerModel();
sM.Name = t.Name;
sM.Status = t.State.ToString();
sM.LastRunTime = t.LastRunTime;
sM.NextRunTime = t.NextRunTime.ToShortDateString() == "1/1/0001" ? (DateTime?)null : t.NextRunTime;
TaskList.Add(sM);
}
}
}

return TaskList;
}

public void DisableAnyTask()
{
    TaskService ts = new TaskService();
    var t = ts.GetFolder(@"\Microsoft\MyTasks");

    if (t != null)
    {
        var tasks = t.AllTasks;
        foreach (var ee in tasks)
        {
            if (ee.Name.ToLower() == "task one")
            {
                if (ee.State.ToString() == "Running")
                {
                    ee.Stop();
                    ee.Enabled = false;
                }
            }
        }
    }
}

}
public class SchedulerModel
{
    public string Name { get; set; }
    public string Status { get; set; }
    public DateTime LastRunTime { get; set; }
    public DateTime? NextRunTime { get; set; }      
}
 
Step 4:

On Page_Load Call below written function As

dataGridView1.DataSource = GetAllTasks();


So, You have all tasks available of that particular location.
Note:

> You must have rights to access these task so, make sure you using Visual Studio as Administrator.

> Ctrl + R >> Taskschd.msc: here you have Task Scheduler window open you have to make a folder (MyTask)
 Path : Task Scheduler Library > Microsoft > MyTask
 MyTask: Name of you folder where you have to create your tasks.


Thanks!

Cheers!!!   

Friday, 18 September 2015

Return parameter in sql server



Create PROCEDURE USP_IsSearchFinished @Id INT
AS
DECLARE @r BIT;

SELECT @r = COUNT(1)
FROM Table1 AP WITH (NOLOCK)
INNER JOIN Table2 SB WITH (NOLOCK) ON AP.ID = SB.Id
WHERE AP.ID = @Id
AND AP.Flag = 'Finished'

RETURN @r
GO


-- How to execute it in sql server

DECLARE @t BIT
EXEC @t = USP_IsSearchFinished 1
PRINT @t


-- Now, get that in ADO.NET

 public int IsSearchFinished(int id)
{
    int _id = 0;
    try
    {
        using (SqlConnection connection = new SqlConnection(conString))
        {
            using (SqlCommand command = new SqlCommand("USP_IsSearchFinished", connection))
            {
                connection.Open();
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@Id", id);
                
                SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Bit);
                returnParameter.Direction = ParameterDirection.ReturnValue;
                command.ExecuteNonQuery();

                _id = (int)returnParameter.Value;                        
            }
        }
    }
    catch
    {
    }
    return _id;
}

Cheers!

Monday, 17 August 2015

Download DataTable TO Excel By Calling Action in MVC

        [AcceptVerbs(HttpVerbs.Get)]
        public FileResult DownloadSearched(string _file)
        {

DataTable dtRec = {Record};

            MemoryStream MyMemoryStream = null;
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dtRec, "Order");

                MyMemoryStream = new MemoryStream();
                wb.SaveAs(MyMemoryStream);
                MyMemoryStream.WriteTo(Response.OutputStream);

                return File(MyMemoryStream, "application/vnd.ms-excel", _file+".xlsx");
            }
         }
       
       


          Call from client side:
       
          window.location = "/Report/OrderReport/DownloadSearched?_file=Report



Cheers!

Monday, 27 July 2015

Shortest way to split strings

CREATE FUNCTION FN_SplitSTRING (@Text nVarchar(max), @Delimeter nVarchar(50))
RETURNS @Table Table (Item Varchar(200))
/*
Written By: Nitish Kumar.
Objective: To split string with delimeter.
Written On: 28-July-2015.
      SELECT * FROM FN_SplitSTRING('1,2,3,5,6,4,8',',')
      SELECT * FROM FN_SplitSTRING('NITISH, KUMAR, JHA, FROM, SAMASTIPUR',',')
      SELECT * FROM FN_SplitSTRING('17*858*858*8569*89*58*nitish','*')
*/
AS
BEGIN
   
      DECLARE @i INT= LEN(@Text)

      WHILE @i <> 0
      BEGIN

            INSERT INTO @Table SELECT LTRIM(RTRIM(SUBSTRING(@Text,0,CHARINDEX(@Delimeter,@Text))))

            SET @Text= RIGHT(@Text,LEN(@Text) - LEN(SUBSTRING(@Text,0,CHARINDEX(@Delimeter,@Text)+1)) )

            IF(LEN(SUBSTRING(@Text,0,CHARINDEX(@Delimeter,@Text)+1)) = 0)
            BEGIN    
                  INSERT INTO @Table SELECT LTRIM(@Text)
                  SET @i= 1;
            END

            SET @i= @i-1
      END
   
      RETURN
END
GO

Monday, 13 July 2015

jQuery click events firing multiple times

Cause: If your table is binding multiple times then obviously page.bootpag will bind that many times.

So, to resolve this must unbind this on each table bind call.
ex:   $("#page").unbind();

Wednesday, 31 December 2014

Move and remove Listbox item to another listbox using jQuery/ JavaScript

// Option 1: jQuery


<script type="text/javascript" language="javascript">
$(document).keydown(function (e) {
    var element = e.target.nodeName.toLowerCase();
    if (element != 'input' && element != 'textarea') {
        if (e.keyCode === 8) {
            return false;
        }
    }
});

$(document).ready(function () {
                
    $("#<%=hdnAssignedModules.ClientID%>").val('');
    var sAllValue = '';
    $('#<%=lstAssigenedModules.ClientID %> option').each(function () {

    var vImgValue = $(this).val();
    sAllValue = sAllValue + vImgValue + ";";

    });
    $("#<%=hdnAssignedModules.ClientID%>").val(sAllValue);

   
    $('#<%=lstAllModules.ClientID %>').click(function () {
    if ($('#<%=lstAllModules.ClientID %> > option:selected').val() != '')
    $('#btnAddModule').removeAttr('disabled');
    else
    $('#btnAddModule').attr('disabled', 'disabled');
    });
    $('#<%=lstAssigenedModules.ClientID %>').click(function () {
    if ($('#<%=lstAssigenedModules.ClientID %> > option:selected').val() != '')
    $('#btnRemModule').removeAttr('disabled');
    else
    $('#btnRemModule').attr('disabled', 'disabled');
    });
    
    $('#btnAddModule').click(
    function (e) {
    if ($('#<%=lstAllModules.ClientID %> > option:selected').appendTo($('#<%=lstAssigenedModules.ClientID %>')));
    $('#btnAddModule').attr('disabled', 'disabled');

    var sAllValue = '';
    $("#<%=hdnAssignedModules.ClientID%>").val('');
    $('#<%=lstAssigenedModules.ClientID %> > option').each(function () {
    var vImgValue = $(this).val();
    sAllValue = sAllValue + vImgValue + ";";
    });
    $("#<%=hdnAssignedModules.ClientID%>").val(sAllValue);
    });
   
    $('#btnRemModule').click(function (e) {
    if ($('#<%=lstAssigenedModules.ClientID %> > option:selected').appendTo($('#<%=lstAllModules.ClientID %>')));
    $('#btnRemModule').attr('disabled', 'disabled');
        
    $("#<%=hdnAssignedModules.ClientID%>").val('');
    var sAllValue = '';
    $('#<%=lstAssigenedModules.ClientID %> > option').each(function () {
    var vImgValue = $(this).val();
    sAllValue = sAllValue + vImgValue + ";";
    });
    $("#<%=hdnAssignedModules.ClientID%>").val(sAllValue);
    });
 });    



 </script>



 // Option 2: Javascript
  <script type="text/javascript" language="javascript">
        function move(tbFrom, tbTo) {
            var arrFrom = new Array(); var arrTo = new Array();
            var arrLU = new Array();
            var i;
            for (i = 0; i < tbTo.options.length; i++) {
                arrLU[tbTo.options[i].text] = tbTo.options[i].value;
                arrTo[i] = tbTo.options[i].text;
            }
            var fLength = 0;
            var tLength = arrTo.length;
            for (i = 0; i < tbFrom.options.length; i++) {
                arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
                if (tbFrom.options[i].selected && tbFrom.options[i].value != "") {
                    arrTo[tLength] = tbFrom.options[i].text;
                    tLength++;
                }
                else {
                    arrFrom[fLength] = tbFrom.options[i].text;
                    fLength++;
                }
            }

            tbFrom.length = 0;
            tbTo.length = 0;
            var ii;

            for (ii = 0; ii < arrFrom.length; ii++) {
                var no = new Option();
                no.value = arrLU[arrFrom[ii]];
                no.text = arrFrom[ii];
                tbFrom[ii] = no;
            }

            for (ii = 0; ii < arrTo.length; ii++) {
                var no = new Option();
                no.value = arrLU[arrTo[ii]];
                no.text = arrTo[ii];
                tbTo[ii] = no;
            }

            document.getElementById("SiteBody_hdnAssignedModules").value = "";
            var sAllValue = '';
            var list = document.getElementById('SiteBody_lstAssigenedModules');
            for (i = 0; i < list.options.length; i++) {
                sAllValue = sAllValue + list.options[i].value + ";";
            }
            document.getElementById("SiteBody_hdnAssignedModules").value = sAllValue;

            document.getElementById("btnAddModule").disabled = true;
            document.getElementById("btnRemModule").disabled = true;
        }

        function enableAddButton() {
            var list = document.getElementById('SiteBody_lstAllModules');
            if (list.options.length != 0) {

                var indx = list.selectedIndex;

                if (list[indx].value != '')
                    document.getElementById("btnAddModule").disabled = false;
                else
                    document.getElementById("btnAddModule").disabled = true;
            }
        }

        function enableRemoveButton() {
            var list = document.getElementById('SiteBody_lstAssigenedModules');
            if (list.options.length != 0) {
                var indx = list.selectedIndex;

                if (list[indx].value != '')
                    document.getElementById("btnRemModule").disabled = false;
                else
                    document.getElementById("btnRemModule").disabled = true;
            }
        }

        function SetAssignedModules() {
            document.getElementById("SiteBody_hdnAssignedModules").value = "";
            var sAllValue = '';
            var list = document.getElementById('SiteBody_lstAssigenedModules');
            for (i = 0; i < list.options.length; i++) {
                sAllValue = sAllValue + list.options[i].value + ";";
            }
            document.getElementById("SiteBody_hdnAssignedModules").value = sAllValue;
        }
    </script>
    
    
    
    PAGE:
    
<tr>
<td>
<asp:ListBox ID="lstAllModules" onClick="enableAddButton()" runat="server"></asp:ListBox>
</td>
<td>
<input type="button" id="btnAddModule" value="Add &gt;&gt;" style="width: 90px;"
disabled="disabled" onclick="move(this.form.SiteBody_lstAllModules,this.form.SiteBody_lstAssigenedModules)" />
<input type="button" id="btnRemModule" value="&lt;&lt; Remove" style="width: 90px;"
disabled="disabled" onclick="move(this.form.SiteBody_lstAssigenedModules,this.form.SiteBody_lstAllModules)" />
</td>
<td>
<asp:ListBox ID="lstAssigenedModules" onClick="enableRemoveButton()" runat="server">
</asp:ListBox>
<asp:HiddenField ID="hdnAssignedModules" runat="server" />
</td>
</tr>


NOTE:

* SetAssignedModules()-> Setting dropdown values to hidden feilds.
* Change Controls' Id.

Tuesday, 30 December 2014

Finding Unmatched Records in DatatTables Using Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;



namespace MyApp
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("Bay", typeof(string));
            dt1.Rows.Add("S30");
            dt1.Rows.Add("S31");
            //dt1.Rows.Add("S32");

            DataTable dt2 = new DataTable();
            dt2.Columns.Add("Bay", typeof(string));
            dt2.Rows.Add("S31");
            dt2.Rows.Add("S41");
            dt2.Rows.Add("S51");

            var vardt1 = dt1.AsEnumerable().Select(a => a.Field<string>("Bay"));
            var vardt2 = dt2.AsEnumerable().Select(a => a.Field<string>("Bay"));
            var varUnMatched = vardt1.Except(vardt2);
            
            Response.Write(varUnMatched.Count().ToString()+"<br/>");
            foreach (var element in varUnMatched)
            {
                Response.Write(element + "<br/>");
            }
        }
    }
}



Cheers!!!