Monday, 12 October 2015

Change page tittle dynamic in asp.net C#



protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)

            {
                if (!string.IsNullOrEmpty(Page.Title))
                {
                    var EmployeeName = Convert.ToString(Request.QueryString["Name"]);
                    var CourseName = Convert.ToString(Request.QueryString["Coursename"]);

                    Page.Title = EmployeeName + "-" + CourseName;
                }
      }
}

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 );