Tuesday, 8 September 2015

How to Use Take/TakeWhile and Skip/SkipWhile in LINQ

  int[] arr = { 1, 3, 11, 6, 8, 2, 6,};

Take=> Its work like Top keyword in SQL . See below ex

 var Take = arr.Take(2);

//its will return IEnumerable collection 

Output-1,3


TakeWhile=> TakeWhile will return the collection having a value of less than 10 , like on second position we have 11 , so it will break and it will return only 1,3 as output .

          var TakeWhile = arr.TakeWhile(item => item < 10);

            foreach (var item in TakeWhile )
            {
                Console.WriteLine(item );

            }

Output-1,3


Skip=> The Skip method will skip the  items from the collection and return the remaining items as an IEnumerable collection.
like i have skip first element of array
        var Skip = arr.Skip(1);
          foreach (var item in Skip)
            {
                Console.WriteLine(item );
            }

Output-3,11, 6, 8, 2, 6

SkipWhile=>SkipWhile operator will skip the items from the starting position until the conditions fails. Once the condition has failed then it will return the remaining items as an IEnumerable collection.

var SkipWhile = arr.SkipWhile(item => item < 10);

  foreach (var item in SkipWhile )
            {
                Console.WriteLine(item );
            }

Output-11, 6, 8, 2, 6






Creating HTML table in MVC using ViewData or ViewBag in C#


Controller Code here 

       public PartialViewResult searchStation()
        {
            try
            {
                ViewData["station"] = null;
                station = new Station();
                this.TryUpdateModel(station);   //Maps the View values to the station class
               StationDB  stationdb = new StationDB();
                DataTable dtStation = stationdb.searchStation(station);
                List<Station> lstStation = new List<Station>();
                foreach (DataRow dr in dtStation.Rows)
                {
                    lstStation.Add(new Station {
                                                 stationCode    = (string)dr["StationCode"],
                                                 stationName    = (string)dr["StationName"],
                                             
                                                });
                }
                ViewData["station"] = lstStation;
                ViewData.Model = station;
            }
            catch (Exception ex)
            {
               errorlog(ex);
            }
            return PartialView("~/Station/YourUserControlName", station);
        }


This View Code 

I have put my list  value into this  ViewData["Test"]

<%
    if (ViewData["Test"] != null)
    { %>
<div class="Grid" style="height:300px;width:750px;overflow:scroll;border:1px solid #0ADA0A;">
    <table border="1" width="100%" class="GridTable" id="results">
        <tr class="GridHeading">
            <th style="width: 30%">
                Station Code
            </th>
            <th style="width: 30%">
                Station Name
            </th>
         
        </tr>
        <%   int i = 0;
             foreach (var station in (IEnumerable<Your Model Class Name>)ViewData["Test"])
             {
                 i++;
                 if (i % 2 == 0)
                 {%>
        <tr class="GridAlternateRow">
            <%}
                 else
                 { %>
            <tr class="GridRow">
                <%} %>
                <td>
                    <%= Html.Encode(station.stationCode)%></a>
                </td>
                <td>
                    <%= Html.Encode(station.stationName)%>
                </td>
             
            </tr>
            <% }
             if (i == 0)
             { %>
            <tr class="GridRow">
                <td colspan="4" style="color: red;">
                    No Records Found
                </td>
            </tr>
            <%} %>
    </table>
    <div id="pageNavPosition" class="pagination" align="center" style="width:90%;overflow:auto" />
    <%  if (i != 0)
        { %>
    <br />
    <span class="button" id="spnButton"><span>
        <input id="btnPrint" type="button" onclick="return printForm();" value="  Print  " /></span></span>
    <%} %>
</div>
<%}
%>

<script type="text/javascript"><!--
    try {
        var pager = new Pager('results', 1000);
        pager.init();
        pager.showPageNav('pager', 'pageNavPosition');
        pager.showPage(1);
    } catch (e) {
        // alert(e.message);
    }
//--></script>

Monday, 7 September 2015

C# 5: async and await

async and await key word is use for asynchronosly programming.

async and await does not work on multi threading concepts , they use only one thread  through out hole application.

please see below ex i have used


       private async void DownloadPageCount()
        {
            Task<string> getWebPageTask = GetWebPageAsync("http://msdn.microsoft.com");
            Console.WriteLine("In DownloadPageCount before await");
            string webText = await getWebPageTask;
            
            Console.WriteLine("Characters received: " + webText.Length.ToString());
        }

        private async Task<string> GetWebPageAsync(string url)
        {
            var wc = new System.Net.WebClient();
            Task<string> getStringTask = wc.DownloadStringTaskAsync(url); // its will return string as a task.
            Console.WriteLine("In GetWebPageAsync before await");
            string Text = await getStringTask;
            Console.WriteLine("In GetWebPageAsync after await");
            return Text;
        }   


When i call GetWebPageAsync() , so it will come inside that function and its will start downloading page , when he will come down to fourth line await getStringTask
await key going to stay while downloading complete, while in this period await keyword going to UI thread for that moment and he will continue with other process.   

Note => So if use async and await keyword , so its does not speed up you program but its make it easy to work .
like i am showing million on data on page that time we see our UI thread all way block until data will popup on screen , so by using async and await we can handle that problem.  
If we can print our thread id , we can its only one signal thread through out hole application. 

Another ex of  async and await

          public async Task checkfinalresult()
        {
         
            Task<int> result = longruningprocess();
            int result1 = await result;
            Console.WriteLine("Final result ={0}",result1);
        }
        public async Task<int> longruningprocess()
        {
            await Task.Delay(1000); // Here he want wait to complicate process means while he free UI                    thread .
            return 1;

        }

Note => behind the seen he is doing lot of thing  , if you want see you can use reflector to debug Microsoft ddl.
or you can use by changing debug option  in VS 2013. 


Edit Web.config file at run time using C#


 Configuration objconf = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
        AppSettingsSection app = (AppSettingsSection)objconf.GetSection("appSettings");
        if (app != null)
        {
            app.Settings["Name"].Value = "AnkitPanwar";
            objconf.Save();
        }

Passing value from one forms to another forms in window application using C#

Note => This code will be written in first form  and we will create object of second form where we want to send value 

                    String StrValue="I love C#"
                    FrmNameSecond   frm = new  FrmNameSecond ();
                    frm.openform(StrValue); //openform is method of second form
                    this.Hide(); // This will hide current window 
                    frm.ShowDialog();  //Shows the form as a modal dialog box.
                    this.Show(); // this will show Second form window

Note =>  frm.openform is a method  , So i have called this method becoz i want "StrValue" to my next form class "FrmNameSecond" .

I have created method like this and i get my value 

       public void openform(string StrValue)
        {
          string  FirstfrmValue = StrValue;
        }

Thursday, 3 September 2015

Remove All html Tag from string in C#


 string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;", string.Empty);

  string strfinal = Regex.Replace(title, "<.*?>", String.Empty);
                Console.WriteLine(strfinal );

Replace default jquery $ sign


Using this method  we can change $ sign in jquery .

var Ankit =jQuery.noConflict();
Now i will use Ankit("#DIVID").val('I have change $ sign to my Name');
* You can't use # or @ as these are not valid variable names
* Names can only contain contains letters, numbers, $ and underscores so no spaces or other special characters

Wednesday, 2 September 2015

multiple selection validation in dropdown list using Jquery


// for multiple selection in dropdown list and check validation in dropdown list

                     $("#Hidden filed ID").val('');

                       var PCCMasterid = [];
                       $('#DropdownID:selected').each(function (i, selected) {
                          PCCMasterid[i] =$(selected).val();

                       });
                       var lenghtarray = PCCMasterid.length;
                       if (lenghtarray <= 0) {
                           alert("Please select value from dropdown");
                           return false;
                       }

                       $("#Hidden filed ID").val(PCCMasterid );
                       if ($("#Hidden filed ID").val().indexOf('Sub01') != -1) {
                           alert("Please don't select select  option");
                           return false;
                       }

Get SQL multiple row value into one column

ALTER FUNCTION [dbo].[UDF_DETAILS]( @ID INT )
RETURNS VARCHAR(MAX) AS BEGIN
DECLARE @Suggestion VARCHAR(MAX)

SELECT  @Suggestion= COALESCE(@Suggestion + '$#$#','') +  Suggestion

FROM  Suggestion WHERE ID=@ID AND  Status='1'  order by SuggestionID desc

RETURN @Suggestion
END

Sending Mail via SQL server using Escalation matrix


create PROC [dbo].[UDSP_Escalation_SendMail]
as
DECLARE EscalationMail Cursor FOR  
              SELECT
 PendingDays,
 CreatedOn  ,EmailID
 FROM table1



 declare @Email_to varchar(100)=''
 declare @Email_ToFare varchar(100)
 declare @Email_CC varchar(max)=''
 declare @MailSubject varchar(1000) = ''
 DECLARE @tableHTML  NVARCHAR(MAX) ;
 declare @URL varchar(50)=''

 declare @PendingDays int=0
 declare @EmailID varchar(100)
 declare @CreatedOn varchar(30)=''


   
 
 Open EscalationMail
 fetch next from EscalationMail into @PendingDays,@CreatedOn
  while (@@fetch_status = 0)
  begin
  if(@PendingDays <>0)
  begin

set @URL = 'http://ABC.in/'
if(@PendingDays >= 1 and @PendingDays <= 3)
begin
if(@EmailID <> '')
begin
set @Email_ToFare=@EmailID + ';' + (select EmailTo from Table2 where EscalationLevel=1 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=1 and Status='1')

end
else
begin
   set @Email_ToFare=(select EmailTo from Table2 where EscalationLevel=1 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=1 and Status='1')

end
end
else
begin
if(@PendingDays >= 4 and @PendingDays <= 6)

begin
if(@EmailID <> '')
begin
set @Email_ToFare=@EmailID + ';' + (select EmailTo from Table2 where EscalationLevel=2 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=2 and Status='1')

end
else
begin
   set @Email_ToFare=(select EmailTo from Table2 where EscalationLevel=1 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=1 and Status='1')

end
end
else
begin
if(@PendingDays >= 7 and @PendingDays <= 10)

begin
if(@EmailID <> '')
begin
set @Email_ToFare=@EmailID + ';' + (select EmailTo from Table2 where EscalationLevel=3 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=3 and Status='1')

end
else
begin
   set @Email_ToFare=(select EmailTo from Table2 where EscalationLevel=3 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=3 and Status='1')

end
end
end
   end
 
 if(@PendingDays > 11)
begin
if(@EmailID <> '')
begin
set @Email_ToFare=@EmailID + ';' + (select EmailTo from Table2 where EscalationLevel=4 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=4 and Status='1')

end
else
begin
   set @Email_ToFare=(select EmailTo from Table2 where EscalationLevel=4 and Status='1')
set @Email_CC=(select EmailCC from Table2 where EscalationLevel=4 and Status='1')

end
 end

 
   SET @tableHTML = '';
   SET @tableHTML =
    N'<table>' +
    N'<tr><th colspan="2" align="left">Dear Sir/Madam,</th></tr>' +
    N'<tr><th colspan="2" align="left"></th></tr>' +
    N'<tr><td>Pending Day:-</td><td>' + CONVERT(varchar(20), @PendingDays) +'</td></tr>' +
    N'<tr><td>Assign Date:-</td><td>' + ISNULL(@CreatedOn, '1900-01-01 00:00:00.000')  +'</td></tr>' +
    N'<tr><td>Type:-</td><td>Escalation</td></tr>' +
    N'<tr><td>Priority:-</td><td>High</td></tr>' +
    N'<tr><td>Description:-</td><td>This Transaction is open.To know more details please log on to <a><font color="#0000cc">'+@URL+'</font></a></td></tr>' +
    N'<tr><th colspan="2" align="left"></th></tr>' +
    N'<tr><th colspan="2" align="left"><img src="http://SiteName/Images/logo.JPG"/></th></tr>' +
    N'<tr><td colspan ="2">Regards</td></tr>' +
    N'<tr><td colspan ="2">Admin Team</td></tr>' +
    N'<tr><th colspan="2" align="left"></th></tr>' +
    N'<tr><td colspan ="2"><i><u>Please do not reply.This in an autogenerated mail.</u></i></td></tr>' +
    N'</table>' ;
    set @MailSubject =  'Please ignore testing mail'
       
    EXEC [msdb].[dbo].[sp_send_dbmail]
    @profile_name = 'Your SQL server Mail server Profile Name will come here',
    @recipients = @Email_to,
    @copy_recipients = @Email_CC,
    @subject = @MailSubject,
    @body = @tableHTML,    
    @body_format = 'HTML'
    set @MailSubject = ''
    end
   fetch next from EscalationMail into @PendingDays,@CreatedOn
   end  
 CLOSE EscalationMail
 DEALLOCATE EscalationMail  

Create dynamic table and fill with value in jquery

function GetDetails() {
    var url = serverPath + "PageName/MethodName";
    $.post(url, function (data, textStatus, XMLHttpRequest) {

        var content = "";
        if (data.length > 0) {
         
            content += '<table border="1" width="100%" class="" id="OpenCallDetails">';
            content += '<tr class="GridHeading" id="rowHeader">';
            content += '<th>ID</th>';
            content += '<th>PCC</th>';
            content += '<th>Assigned To</th>';
       
            content += '<th>Created On</th>';
       
            content += '<th></th>';

            content += '</tr>';

            for (var i = 0; i < data.length; i++) {

                if (data[i].PendingDays < 5) {
                    content += "<tr id='" + i + "' style='background-color: white;color: black;'>";
                }
                else if (data[i].PendingDays < 10) {
                    content += "<tr id='" + i + "' style='background-color: yellow;color: black;'>";
                }
                else if (data[i].PendingDays < 15) {
                    content += "<tr id='" + i + "' style='background-color: orange;color: black;'>";
                }
                else if (data[i].PendingDays < 20) {
                    content += "<tr id='" + i + "' style='background-color:blue;color: white;'>";
                }
                else if (data[i].PendingDays > 20) {
                    content += "<tr  id='" + i + "' style='background-color:red;color: white;'>";
                }
                content += '<td align="center">';
                content += data[i].ID;
                content += '</td>';
                content += '<td align="center">';
                content += data[i].PCC;
                content += '</td>';
                content += '<td align="center">';
                content += data[i].AssignedTo;
                content += '</td>';

                content += '<td align="center">';
                content += data[i].CreatedOn;
                content += '</td>';
         
                content += '</tr>';
            }
            content += '</table>';

            $("#This is div ID").append(content);
        }
    }, "json");
}

To bind Dropdown list using Jquery

// We can use jquery method like Post or Ajax to bind dropdown list.

Using $.Post

function getStation(region) {

    $.post("/PageName/MethodName?param=" + region,
        function (data, textStatus, XMLHttpRequest) {
            items = "<option value=''>Select City</option>";
            $.each(data, function (i, data) {
               
                    items += "<option value='" + data.StationMasterID + "' selected='selected'>" + data.StationName + "</option>";

            });
            $("#DropdownID").html(items);
        }, "json"); // Json is the return value from C# or Java method
}

Using $.Ajax

 $.ajax({
        url: "/PageName/MethodName",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: { region: region},
        success: function (result) {

            var items = "";
            items = "<option value='Sub01'>Select Sub Category</option>";
            $.each(result, function (i, result) {
                items += "<option value='" + result.StationMasterID + "'>" + result.StationName + "</option>";
            });
            $("#DropdownID").html(items);
        },
        error: function (data) {
            $("#strResult").html(data);
        }
    });

How to use ContinueWith method in Task using C#

// What ever we will get from task , its going to cal task value in task1 and process the final result.

 var task = Task<int>.Run(() => {
                 return  Enumerable.Range(1, 1000).Count(n => n / 2 == 2);
           });
            task.ContinueWith((task1) =>
            {
                if (task1.Result < 10)
                {
                 
                    Console.WriteLine(task1.Result);
                }
                else
                {
                    if (task1.IsFaulted == true) // Is IsFaulted used to check Exception in Task
                    {
                       foreach(var d in task1.Exception.Flatten().InnerExceptions)
                       {
                           Console.WriteLine(d.Message);
                       }
                   
                    }
                    else
                    {
                        Console.WriteLine(task1.Result);
                    }
                   
                }
            }).Wait(); // Wait going to wait finished his work and comeback with final result.
                              suppose if am not going to put wait here , that task is not going wait finished his work and he move to next line , with out giving output. 

How to ping ip address or by url in c#

 static void Main(string[] args)
        {
           string url = "http://stackoverflow.com/";
            Ping p = new Ping();
            PingReply p1 = p.Send("IP address or site url", 3000);
           //3000 -> it is time out time
            if (p1.Status == IPStatus.Success)
            {
                Console.WriteLine("working fine");
            }
            Console.ReadLine();
        }

Thread-Safe Collection using blockingcollection and Task in C#

// Thread-Safe Collection using blockingcollection and Task

static void Main(string[] args)
        {
         
            BlockingCollection<int> block = new BlockingCollection<int>();
         
            var task1 = Task.Factory.StartNew(() => {
                foreach (int i in block.GetConsumingEnumerable()) // GetConsumingEnumerable is used to take element from collection and deleted it
                {
                    Console.WriteLine("Task 1 data {0}", i);
                }

             
               
            });
            var task2 = Task.Factory.StartNew(() =>
            {
                foreach (int i in block.GetConsumingEnumerable())
                {
                    Console.WriteLine("Task 2 data {0}", i);
                }

               
            });

            var task3 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    block.Add(i);
                }
                block.CompleteAdding(); //Its used to check , BlockingCollection list is added or not
               
            });
         
            task3.Wait(); // why we add task3.Wait() , becoz first of all we are going to add item into BlockingCollection  list then we are going to loop on this list at a same time
            Task.WaitAll(task1, task2); // after finished task3 , these task1 and task2 is going to wait until they finished work
            Console.ReadLine();
        }

OutPut->Task 1 data 0
Task 2 data 1
Task 1 data 2
Task 2 data 3

find duplicate value in array using C#

//find duplicate value in array using C#

static void Main(string[] args)
        {

            Console.WriteLine("Please enter limit of arry");
            int i = Convert.ToInt32(Console.ReadLine());
            int[] arry = new int[i];
            for (int j = 0; j < arry.Length; j++)
            {
                Console.Write("\nEnter your number:\t");
                arry[j] = Convert.ToInt32(Console.ReadLine());

            }
            ArrayList list = new ArrayList();
            Console.WriteLine("\n\n");
       
            for (int k = 0; k < arry.Length; k++)
            {
                for (int l = k; l < arry.Length - 1; l++)
                {
                    if (arry[k] == arry[l + 1])
                    {
                        list.Add(arry[k]);
                    }
                }
            }

            if (list.Count == 0)
            {
                Console.WriteLine("No dulicate value");
            }
            else
            {
                foreach (var _list in list)
                {
                    Console.WriteLine("No of value {0}", _list);
                }
            }

         
            Console.ReadKey();
        }

Delete file depend on time using C#

          //to delete file from folder  
           string FileLocation=@"G:\File delete";
           DirectoryInfo source = new DirectoryInfo(FileLocation);
           foreach (FileInfo file in source.GetFiles())
            {
                var creationTime = file.CreationTime;
               //or
                var lasttime = file.LastAccessTime;

                if (creationTime < DateTime.Now)
                {
                  file.Delete();
                }
            }

Find Max value in array and secondMax using C#

            int[] arr = new int[] { 1, 5, 6, 3, 9, 23 };
            int maxvalue = arr[0];
            int secondmaxvalue = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (maxvalue < arr[i])
                {
                    secondmaxvalue = maxvalue;
                    maxvalue = arr[i];
                 
                }
                else if (secondmaxvalue < arr[i])
                {
                    secondmaxvalue = arr[i];
                }

            }
            Console.WriteLine(maxvalue);
            Console.WriteLine(secondmaxvalue);

Or else we can use linq or lemda exp like this

By Linq->
    var checksecondlagestnumber = (from ITEM in arr orderby ITEM descending select ITEM).Skip(1).FirstOrDefault();

By Lemda->
            var checksecondlagestnumber= arr.OrderByDescending(ITEM => ITEM).Select(ITEM => ITEM).Skip(1).FirstOrDefault();

Reverse word and make first element in Upper case

 public static void Revrseword()
        {
            string str = "ankit Panwar frOm muzaFFarnagar";
            StringBuilder sb = new StringBuilder();
            string[] arry = str.Split(' ');
            for (int i = 0; i < arry.Length; i++)
            {
                string check = arry[i];
                for (int j = check.Length - 1; j >= 0; j--)
                {
                    if (j == check.Length - 1)
                    {
                        sb.Append(check[j].ToString().ToUpper());
                    }
                    else
                    {
                        sb.Append(check[j].ToString().ToLower());
                    }
                }
                sb.Append(" ");
            }
            Console.WriteLine(sb.ToString());
        }

OutPut like -> Tikna Rawnap Morf Raganraffazum