Showing posts with label .NET 2010. Show all posts
Showing posts with label .NET 2010. Show all posts

Thursday, January 23, 2014

Resolve C:\fackpath in upload field instead o the full path

For the security reason this fackpath introduced and there is no way to show the actual path instead of the fackpath.

Just one way to replace the fackpath and show only the uploaded file name.

// check for IE's lovely security speil
if(filePath.match(/fakepath/)) {
  // update the file-path text using case-insensitive regex
  filePath = filePath.replace(/C:\\fakepath\\/i, '');
}

To replace the "\" in the URL use the below line of code.


this.value.replace(/\\\\/g, '');


Post data from client to a web service (.asmx, .svc) in C#

If you want to post data from your web application to web service then use the below line of code and change it according your requirement.

ClientSection clientSettings = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
                string address = string.Empty;
                foreach(ChannelEndpointElement endpoint in clientSettings.Endpoints)
                {
                    if (endpoint.Name == "WarrantyXServiceSoap")
                    {
                        address = endpoint.Address.ToString();   
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(address))
                {
                    HttpWebRequest request;
                    string url = WebService URL;
                    string action = "http://tempuri.org/MethodName";

                    request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = "POST"; // OR "GET" if you want to make a GET request 
                    request.ContentType = "text/xml; charset=utf-8";
                    request.Headers.Add("SOAPAction: " + action);

                    StringBuilder soapRequest = new StringBuilder("");
                    soapRequest.Append("http://www.w3.org/2001/XMLSchema-instance\
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
                    soapRequest.Append("");
                    soapRequest.Append("http://tempuri.org/\
">");
// these are the parameters of web method to pass data from client machine
                    soapRequest.Append("" + _Name + "
");
                    soapRequest.Append("" + Convert.ToBase64String(_BinaryDoc) + "
");
                    soapRequest.Append("" + _ContentType + "
");
                    soapRequest.Append("" + _ID.ToString() + "
");

                    soapRequest.Append("
");
                    soapRequest.Append("
");
                    soapRequest.Append("
");

                    request.ContentLength = soapRequest.ToString().Length;
                    request.KeepAlive = false;
                    request.Timeout = System.Threading.Timeout.Infinite;
                    request.AllowWriteStreamBuffering = false;
                    request.ProtocolVersion = HttpVersion.Version10;
                    request.ServicePoint.ConnectionLeaseTimeout = 600000;
                    request.ServicePoint.MaxIdleTime = 600000;
                    request.Proxy = null;
                    request.ReadWriteTimeout = 600000;
                    request.Accept = "text/xml";

                    using (Stream requestStream = request.GetRequestStream())
                    {
                        using (StreamWriter requestStreamWriter = new StreamWriter(requestStream))
                        {
                            requestStreamWriter.Write(soapRequest.ToString());
                        }
                    }

                    string result = string.Empty;
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        result = reader.ReadToEnd();
                    }

                    var xDoc = XDocument.Parse(result);
                    _createdAnnotation = new Guid(xDoc.Root.Value);

                }

How do I upload large greater than 5MB files to a web service?

I have a web service that takes a serialize string and saves it.
This works fine for "small" files, but once I hit a large size the web service fails and returns "The request failed with HTTP status 404: Not Found."
From what I've seen this appears to be an IIS setting that limits the size of a file that can be posted. I've tried to increase that setting, but I am having trouble determining what setting and where/how one would set it. I am using IIS7 and the webservice is done in .net (asmx).
In the web.config of the web service I have added the following (which seemed to increase the size of file that can be accepted, but not all the way to this setting size)
IIS 6

 <system.web>
     <httpRuntime executionTimeout="999999" maxRequestLength="2097151" />
     ...
  </system.web>
IIS7
   <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2000000000" />
      </requestFiltering>
    </security>
  </system.webServer>
   
     
       
     
   
 



Sunday, January 19, 2014

LINQ - Concat a column value by a Unique ID

Table 1:

Number               City       
111                         Delhi     
111                         Agra      
112                         Jaipur   
111                         Hapur   
113                         Jodhpur              

Table 2

Number(Unique)  Percent
111                                         10
112                                         20
113                                         30


Output Required

Number                               Cities                             Percent
111                         Delhi ,Agra ,Hapur                           10
112                                         Jaipur                               20
113                                         Jodhpur                            30


By Linq

var varContact = from t2 in Table2.AsEnumerable()
                                    
                 join t1 in Table1.AsEnumerable() on t1.Field("Number") equals t2.Field("Number") into t1t2
                 select new
                 {
                                     Number = t2.Field("Number"),
                     Cities = t1t2.Where(x => x.Field("Number").ToString().Equals(c.Field("Number").ToString())).Select(g => g.Field("City")).Aggregate((i, j) => i + " ," + j),
                     Percent = c.Field("Percent")
                                        

                 };

Tuesday, November 5, 2013

ASP.NET fails to detect IE10 causing _doPostBack is undefined JavaScript error or maintain FF5 scrollbar position

There is a bug in the browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

for more information please visit SCOTT HANSELMAN

A similar bug affects Firefox versions 5 and above, where support for using JavaScript to reposition the scrollbar in the browser is not detected. This basically breaks the MaintainScrollbackPositionOnPostBack property for Web Forms pages.
These "misdetection" bugs affect Web Forms pages in both ASP.NET 2 and ASP.NET 4. If you are using ASP.NET Web Pages, or if you're using ASP.NET MVC or ASP.NET Web Pages and are not using the Browser object to detect JavaScript support, you will not be affected.

FIXES

There are two ways to fix this: one is a machine-wide fix, the other is a way to fix individual sites.

MACHINE-WIDE FIXES

We're releasing a hotfix that will fix these, which you'll be able to get to via some KB articles. These KBs with fixes are live and are the best way to update your system. The fixes solve the browser-detection issue forever for all sites on a machine. These will be rolled up into future versions of the framework and will eventually also be on Windows Update.
What the fixes do is update the ie.browser and firefox.browser files in\Windows\Microsoft.NET\Framework\\Config\Browsers with new and future-proofed versions of these browser definitions. Nothing else is affected.

SITE-ONLY FIXES

App_BrowsersIf you don't have access to the whole machine and/or just want to update a single project, use NuGet to install the App_BrowsersUpdate package. Your site structure in Solution Explorer will then look like the image at right. Note that NuGet uses .NET 4, so for systems that have only .NET 2, you'll need to get the ZIP file and put the new browser files in App_Browsers manually.
Updating the whole machine is the preferred way to fix this.
Note: To install NuGet, follow the below steps
1) Go to VS.NET > Tools > Extension Manager
2) Select Install NuGet from OnLine Gallary
3) Now search App_Browser in the Extension Manager window and click install, it will add one folder with name "App_Browser" and two browser file one for IE and one for FireFox.
4) Add The below script in the body of master page
 <script language="javascript" type="text/javascript">
        //debugger;
        if (typeof (Sys) !== 'undefined' && Sys.Browser.agent === Sys.Browser.InternetExplorer && (Sys.Browser.version === 10 || Sys.Browser.version === 9)) {

            Sys.WebForms.PageRequestManager.getInstance()._onFormElementActive = function Sys$WebForms$PageRequestManager$_onFormElementActive(element, offsetX, offsetY) { if (element.disabled) { return; } this._activeElement = element; this._postBackSettings = this._getPostBackSettings(element, element.name); if (element.name) { var tagName = element.tagName.toUpperCase(); if (tagName === 'INPUT') { var type = element.type; if (type === 'submit') { this._additionalInput = encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value); } else if (type === 'image') { this._additionalInput = encodeURIComponent(element.name) + '.x=' + Math.floor(offsetX) + '&' + encodeURIComponent(element.name) + '.y=' + Math.floor(offsetY); } } else if ((tagName === 'BUTTON') && (element.name.length !== 0) && (element.type === 'submit')) { this._additionalInput = encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value); } } };
        }
     </script>


Immediately Disable Button after On Click - ASP.net/Javascript

In one common scenario it will be helpful if you required to submit payment information online "click only once, or you may receive multiple charges. Or your specific requirement to click only once.

In C#

protected void Page_Load(object sender, EventArgs e)
{
                btnName.Attributes.Add("onclick", @"MovetoTop(); this.disabled = true; " +  this.Page.ClientScript.GetPostBackEventReference(btnName, null) + ";");
}

MovetoTop is the another function used to find the top of the webpage.

function MovetoTop() {      
        $("html, body").animate({ scrollTop: 0 }, "slow");
}

Saturday, February 4, 2012

CRM 4.0: Reopen or reactivate a closed task / activity with SDK

Once a time Some tasks and opportunities closed wrongly in CRM4.0, so I need to reopen all these tasks and opportunity, to do this you will follow some steps:


Task: loop through for all the selected tasks
foreach (BusinessEntity TaskEntity in result.BusinessEntities)
{
try
{
task objtaskEntity = (task)TaskEntity;
task objtaskEntity1 = (task)TaskEntity;

//Create the request of the Task for State
SetStateTaskRequest objtask = new SetStateTaskRequest();
objtask.EntityId = new Guid(objtaskEntity.activityid.Value.ToString());
objtask.TaskState = 0;
objtask.TaskStatus = 2;
//Execute the request
SetStateTaskResponse res = (SetStateTaskResponse)service.Execute(objtask);


//You need to update the attribute of task entity then use the following line of code
objtaskEntity1.category = string.Empty;
service.Update(objtaskEntity1);
break;
}
catch(Exception ex)
{
continue;
}
}

Opportunity: to update or reopen Opportunity you will follow the following line of code

Picklist plSalesStage = new Picklist();
lSalesStage.Value = 1;
RenOpp.salesstagecode = plSalesStage;

OpportunityStateInfo objstateinfo = new OpportunityStateInfo();
objstateinfo.Value = OpportunityState.Open;
RenOpp.statecode = objstateinfo;
service.Update(RenOpp);

Monday, August 8, 2011

c# Windows Service not appearing in services list after install

Many times user create a windows service and add installer to it, but when user try to install, it will installed successfully but dosn't appear in service list.

use the below mentioned steps to find a best solution:

Add a custom action to the setup project.

1.In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.

2.In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.

3.Double-click the application folder in the list box to open it, select primary output from MyNewService (Active), and click OK. The primary output is added to all four nodes of the custom actions � Install, Commit, Rollback, and Uninstall.

4.Build the setup project.

Monday, July 4, 2011

Extension Methods in .NET 3.5

Introduction
Extension method is new to C#.Its allow you to add new method to the existing class.
Description
1.Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.
2.Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by “this” modifier.
3.Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.
For Example in string object there is no method call “Reverse()” function .But if you need to extend the string ….
Sample Code
namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static bool IsValidEmailAddress(this String EmailAddress)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(EmailAddress);
}
}
}

How to Use?
string email = harish@company.com;
if ( email.IsValidEmailAddress() ) {

}
Note how the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type "string".

for more information follow the Link

Friday, May 27, 2011

Hide Console Window in Console Application with C#

1) First write below code above your console main method:
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

2) Put below line of code in starting of main Method
// hide the console window
setConsoleWindowVisibility(false, Console.Title);

3) use below lie of code in your class
public static void setConsoleWindowVisibility(bool visible, string title)
{
//Sometimes System.Windows.Forms.Application.ExecutablePath works for the caption depending on the system you are running under.
IntPtr hWnd = FindWindow(null, title);

if (hWnd != IntPtr.Zero)
{
if (!visible)
//Hide the window
ShowWindow(hWnd, 0); // 0 = SW_HIDE
else
//Show window again
ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA
}
}

Finally you will see your console window hide.

Wednesday, January 5, 2011

Message Queue in .Net

Queue is nothing but FIFO (First In First Out).

Before going to Message Queue concept, why we need Message Queuing?
Answer is that, we require Message Queue mechanism when we want to store insignificant data which is not required to store and we want to do some operations on it.

For example, we want to accept data from multiple users and we have to do some operations on that data, after that we require writing data to some files. Then in this situation we need not require data to store in database, we just want to do some operations on that data and copy that to some files. This requirement will be fulfilled by Message Queue.

If we take another example, where we have two applications in two different systems. One application will send the data and another will need to process the data.

Here I am explaining second example but two applications are in same system.

To run Message Queue concept in .Net, we need Message Queue service to be installed in our system. By default installation of Operating System, it will not install. To install Message Queue service
Start->settings->control panel ->Add/Remove programs-> Click on Add/Remove window components-> Check Message Queuing ->Click Next button

If you unable install, please refer documentation of corresponding Operating System.

After successful installation of Message Queue, you have to write the code to use it.
Here I am explaining Message Queue by using VB.Net.

In this example we need two applications, one is to store data in Message Queue and another is to retrieve data from Queue.

namespace is "System.Messaging"

Step 1: Push Data in Queue

static void PushDatainQueue(string QueueData, string QueueLable)
{
#region Queue
string strQuePath = string.Empty;
MessageQueue objMessageQueue = new MessageQueue();
strQuePath = @".\Private$\syccrm";

if (MessageQueue.Exists(strQuePath))
//creates an instance MessageQueue, which points
//to the already existing MyQueue
objMessageQueue = new System.Messaging.MessageQueue(strQuePath);
else
//creates a new private queue called MyQueue
objMessageQueue = MessageQueue.Create(strQuePath);
#endregion

#region Message
System.Messaging.Message objMessage = new System.Messaging.Message();
objMessage.Priority = MessagePriority.Normal;
objMessage.Body = QueueData;
objMessage.Label = QueueLable;
#endregion

#region Push Message in Queue
objMessageQueue.Send(objMessage);
#endregion
}

Step 2: Receive Data from Queue

static void ReceiveDataFromQueue(string strQuePath)
{
MessageQueue objMessageQueue = new MessageQueue();
if (MessageQueue.Exists(strQuePath))
objMessageQueue = new System.Messaging.MessageQueue(strQuePath);
else
objMessageQueue = MessageQueue.Create(strQuePath);
Message objMessage = new Message();
objMessageQueue = objMessageQueue.Receive();
String strOperation = objMessageQueue.Label.ToString();
string queueData = objMessageQueue.Body.ToString();
}

Note:for private and public queue syntax
// References public queues.
public void SendPublic()
{
MessageQueue myQueue = new MessageQueue(".\\myQueue");
myQueue.Send("Public queue by path name.");

return;
}

// References private queues.
public void SendPrivate()
{
MessageQueue myQueue = new
MessageQueue(".\\Private$\\myQueue");
myQueue.Send("Private queue by path name.");

return;
}

Tuesday, January 4, 2011

Parallel ForEach on DataTable

i would like to use the new Parallel.ForEach function to loop through a datatable and perform actions on each row.

Example:

Normal foreach loop
foreach (DataRow dr in objDS.Tables[0].Rows)
{
if (!objHT.Contains(dr["MessageKey"].ToString()))
objHT.Add(dr["MessageKey"].ToString(), dr["MessageValue"].ToString());
}

Parallel.ForEach loop for above DataTable
Parallel.ForEach(objDS.Tables[0].AsEnumerable(), dr =>
{
if (!objHT.Contains(dr["MessageKey"].ToString()))
objHT.Add(dr["MessageKey"].ToString(), dr["MessageValue"].ToString());
});

Tuesday, December 28, 2010

Parallel Tasks in .NET 4.0 – Methods that Return value

For methods that return a value, you would need to use the Task(TResult) class which represents an asynchronous operation that can return a value. We will explore how to use this class in this article.

For Example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Threading.Tasks;

namespace URLRoutingDemoApp.Parallel_For
{
public partial class ParallelInvokeWithReturnValue : System.Web.UI.Page
{
static string stValues = string.Empty;
string strTaskResult = string.Empty;
string strTaskResult1 = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
stValues = "";
strTaskResult = "";
strTaskResult1 = "";
//Two Approaches
//Approach 1-> First Initialize the task and then execute
Task Task Task
Task1.Start();
Task2.Start();
Task3.Start();

strTaskResult += "Task1=" + Task1.Result.ToString() + "</br>";
strTaskResult += "Task1=" + Task2.Result.ToString() + "</br>";
strTaskResult += "Task1=" + Task3.Result.ToString() + "</br>";

lblparallelInvokewithreturnvalue.Text = stValues + "::::</br>" + strTaskResult;

//Approach 2-> Initialize and execute task at the same time
stValues = "";
var TaskApp1=Task var TaskApp2 = Task var TaskApp3 = Task
strTaskResult1 += "Task1=" + TaskApp1.Result.ToString() + "</br>";
strTaskResult1 += "Task1=" + TaskApp2.Result.ToString() + "</br>";
strTaskResult1 += "Task1=" + TaskApp3.Result.ToString() + "</br>";

lblparallelInvokewithreturnvalue1.Text = stValues + "::::</br>" + strTaskResult1;
}

static int GenerateNumbers()
{
int i;
for (i = 0; i < 10; i++)
{
stValues += "Method1 - Number " + i.ToString() + " </br>";
Thread.Sleep(1000);
}
return i;
}

static string PrintCharacters()
{
string str = "blog";
for (int i = 0; i < str.Length; i++)
{
stValues += "Method2 - Character " + str[i].ToString() + " </br>";
Thread.Sleep(1000);
}
return str;
}

static int PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
foreach (int i in arr)
{
stValues += "Method3 - Array " + i.ToString() + " </br>";
Thread.Sleep(1000);
}
return arr.Count();
}
}
}

Used the Task(TResult) class to call methods that returned a value.

Parallel Tasks in .NET 4.0

In .NET 4.0, we have a set of new API's to simplify the process of adding parallelism and concurrency to applications. This set of API's is called the "Task Parallel Library (TPL)" and is located in the System.Threading and System.Threading.Tasks namespaces.

For Example:
using System.Threading;
using System.Threading.Tasks;

public partial class ParallelInvoke : System.Web.UI.Page
{
static string stValues = string.Empty;

protected void Page_Load(object sender, EventArgs e)
{
stValues = "";
Parallel.Invoke(new Action(GenerateNumbers), new Action(PrintCharacters), new Action(PrintArray));
parallelInvokelbl.Text = stValues;
}

static void GenerateNumbers()
{
for (int i = 0; i < 10; i++)
{
stValues += "Method1 - Number " + i.ToString() + "
";
Thread.Sleep(1000);
}
}

static void PrintCharacters()
{
string str = "blog";
for (int i = 0; i < str.Length; i++)
{
stValues += "Method2 - Character " + str[i].ToString() + "
";
Thread.Sleep(1000);
}

}

static void PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
foreach (int i in arr)
{
stValues += "Method3 - Array " + i.ToString() + "
";
Thread.Sleep(1000);
}
}
}

Monday, December 27, 2010

What is the difference between For(C#) and Parallel.For(.NE 4.0) Loop.

The difference is that with the C# for statement, the loop is run from a single thread. However the Parallel class uses multiple threads. Moreover the order of the iteration in the parallel version is not necessarily in order.

Let us see an example:
1) Add one web page with Name "ParallelForVSFor"
2) Add two label controls on the page "ParallelForVSFor.aspx" file

<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td><asp:Label ID="parallelfor" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="csharpfor" runat="server" Text=""></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>

3) Add the following code in "ParallelForVSFor.aspx.cs" file
using System;
using System.Threading;
using System.Threading.Tasks;

protected void Page_Load(object sender, EventArgs e)
protected void Page_Load(object sender, EventArgs e)
{
parallelfor.Text += "Using Parallel.For \n";
Parallel.For(0,10,i =>
{
parallelfor.Text += "i="+i.ToString()+"\n";
Thread.Sleep(10);
});

csharpfor.Text += "Using C# For Loop \n";
for (int i = 0; i < 10; i++)
{
csharpfor.Text += "i=" + i.ToString() + "\n";
Thread.Sleep(10);
}
}

As you can see, the Parallel.For method is defined as Parallel.For Method (Int32, Int32, Action(Of Int32)). Here the first param is the start index (inclusive), the second param is the end index (exclusive) and the third param is the Action delegate that is invoked once per iteration. Here’s the output of running the code:

Using Parallel.For i=0 i=5 i=1 i=6 i=2 i=7 i=3 i=8 i=4 i=9
Using C# For Loop i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9

As you can see, with the C# for loop statement, the results are printed sequentially and the loop is run from a single thread. However with the Parallel.For method uses multiple threads and the order of the iteration is not in order.

The Parallel.For() construct is useful if you have a set of data that is to be processed independently. The construct splits the task over multiple processor.

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...