mardi 4 août 2015

Can't get Control with FindControl()

I am using a MasterPage site. in default.aspx code-behind, i create many container DIV (ie. each DIV is a SQL result):

HtmlGenericControl div = new HtmlGenericControl("div");
div.Attributes.Add("id", "div_" + postid);

Then create more DIV in code behind (divBottom) programatically and add it to the container DIV, with the following controls inside it:

LinkButton lnkConfirmo = new LinkButton();
lnkConfirmo.ID = "lnkConfirmo_" + postid;
lnkConfirmo.Text = "Foo";
lnkConfirmo.Click += (sender, e) => { UpdateLabel(sender, e, postid); };

Label lblConfirms = new Label();
lblConfirms.ID = "lblConfirms_" + postid;
lblConfirms.Text = "<small><a href=\"javascript:;\">" + GetConfirmTotal(postid) + " pessoas</a> confirmam.</small>";
lblConfirms.Attributes.Add("runat", "server");

And finally add the bottom div to the container.

div.Controls.Add(divBottom);

On the UpdateLabel() method, i am not being able to change Label text when LinkButton is clicked.

    public void UpdateLabel(object sender, EventArgs e, int postid)
    {
        object ctl = (this.FindControl("ContentPlaceHolder1_lblConfirms_" + postid.ToString()) as Label);
        HtmlGenericControl ctl2 = (HtmlGenericControl)this.FindControl("ctl00").FindControl("ContentPlaceHolder1").FindControl("lblConfirms_" + postid);
        //I tried more combinations of this.
    }

I tried Label and HtmlGenericControl because Label is rendering as a span. How can i access that span to change its text, or make this an available control to be accessed? Some controls are available on this.Page.Form (such as some divs, ContentPlaceHolder, ScriptManager and many "Literal), but not the Label as it isn't being rendered as a Control, i guess.

This is the Html output:

<div id="divConfirms_24"><span id="ContentPlaceHolder1_lblConfirms_24" runat="server"><small><a href="javascript:;">190 users</a> confirmam.</small></span></div>



via Chebli Mohamed

Changing ASP.Net label's text with VB.Net

I currently have a form that has a label appear when there is an error with changing your password.

Currently there is a bug that makes a message pop up even when the change is successful that says, "Object reference not set to an instance of an object."

I'm wanting to write a test that says when the label is equal to that message to make the visibility false. I've tried:

If lblMsg.Text = "Object reference not set to an instance of an object." Then
            lblMsg.Visible = False
        End If

This, among other variations, have yet to work successfully for me.

Any idea on what other ways I can write this out to hide the label when that message occurs?



via Chebli Mohamed

How to setup a local wayback machine like that of Internet Archive?

I depend on our Government website for my research. There are some sites in those on which content and links appear and vanish on everyday basis. Their sites are terribly designed and they willfully take down some links or bury some things deep inside to make it hard for any one to find. The problem is I need to refer to something that was on the website months or years ago. Most of the time, I end up not finding it.

Is there a way to locally archive the sites and browse them like we do on wayback machine?



via Chebli Mohamed

How can I navigate to a different URL when user clicks the hyperlink in the GridView with a condition?

I am a beginner in learning asp.net. I have a column in a GridView with header name FORM ID. I want to be able to navigate to the different URL based on the part of the FORM ID.

For example,

  • Clicking on abc10001 will take us to "~/abc1.aspx?formid=abc10001"
  • Clicking on abc20001 will take us to "~/abc2.aspx?formid=abc20001"

I understand the use of the MID function like so v=MID(string,4,1) to capture the 4th value and redirect to page by determining the value v but I do not know how to apply this correctly. Please guide me. Your help is greatly appreciated.

The following is the aspx code I'm currently work on :

<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false">           
    <columns>
        <asp:Hyperlinkfield DataTextField="formid" HeaderText="Form ID" ItemStyle-  Width="150px" 
            DataNavigateUrlFields="formid" DataNavigateUrlFormatString="~/abc1.aspx" />         
    </Columns>
</asp:GridView>



via Chebli Mohamed

ASP MVC 5 Web Application not Rendering CSS. Deployed Via Web Deploy

I deployed a MVC 5 Application via web deploy to IIS 8. It is not rendering my bootstrap.css. I'm not sure where to begin from a troubleshooting perspective as this is my first MVC 5 Deployment.

I attached my web config below

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="JCI.MW.WebFrontEnd" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>

  <system.web>
    <compilation>
      <assemblies>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
  </system.web>
</configuration>



via Chebli Mohamed

Why is localization not working for gridvew?

Why is my localization not working with gridview ?

I have made resx files:

BoundFieldLCode.HeaderText      کد زبان 
BoundFieldText.HeaderText           متن 

and bound fields:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">
        <Columns>
            <asp:BoundField DataField="Text" HeaderText="Text" meta:resourceKey="BoundFieldText" />
            <asp:BoundField DataField="Language" HeaderText="Language Code" meta:resourceKey="BoundFieldLCode" />
        </Columns>
    </asp:GridView>

and put this in header of page directive

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Report.aspx.cs" Inherits="_Default"  Culture="auto:en-US" UICulture="auto" %>



via Chebli Mohamed

What is the default TokenLifespan of GeneratePasswordResetTokenAsync and GenerateUserTokenAsync

I have looked everywhere and cannot seem to find out for sure what the default for each of these is.

I also need to know if there is a way to set different Lifespans for each. Thanks,



via Chebli Mohamed

Can't run asp.net app on os x with dnx . kestrel

I followed this tutorial to install tools to run asp.net on os x. I scaffolded the asp.net web application successfully, but and run all the commands the application isn't running.

macbook$ cd '/Users/macbook/Documents/Leisure/asp/webapp' ; /Users/macbook/.dnx/runtimes/dnx-mono.1.0.0-beta6/bin/dnx . kestrel
info    : [Microsoft.Framework.DependencyInjection.DataProtectionServices] User profile is available. Using '/Users/macbook/.local/share/http://ift.tt/1KG10ju' as key repository; keys will not be encrypted at rest.
Started

Everything seems fine, but when I go to localhost:5000 I get ERR_CONNECTION_REFUSED, even though kestrel is set at this url.

What's not right? how do I get my asp.net app working?



via Chebli Mohamed

Default text from .resx file disappearing from website in C#

I have a project involving a template website, that has a set of default text strings stored in a resx file, Resource.resx

I recently came across the idea of using an English language resx file, Resource.en.resx, to store text specific to each instance of the customized website. This way I can have certain pieces of text (such as addresses or other contact information) stored, while being able to easily change text for all instances of the template website. It is similar to Are resx files a suitable way to customise for different customers? except that each instance of the website has its own environment, so there is no confusion on which "version" of the text should be loaded.

However, I have been encountering a problem where the text on the page is disappearing, with the exception of the text from the Resource.en.resx file. No errors are being thrown, the areas where the text appears are just appearing as blank. This can be fixed temporarily by doing an iis reset on the website's server, but I have not been able to determine how or why this is happening.

I believe that it is a caching issue, that somehow the resx is loading "blank" values for the "missing" values in the Resource.en.resx file, even though my understanding of resx files is that any missing key should default to the text from the default file. I have a theory that the text disappears sometimes after an iis reset (which is also a method for making it reappear).

I am using C# with .Net 4.5. I am not currently changing the website's culture directly, though that is something I will be adding in the future. My methodology works most of the time, but I need to know if there is a solution to this intermittent problem, or if I will need to find another method for more easily loading text.

Has anyone encountered this before, or have any idea why it might be happening?



via Chebli Mohamed

Server updating the model on changes from other users

Imagine having a website with an input field, a text field and a button. The text field contains the sum of all inputs, from the input field. The button submits the input.

2 users loaded the page at the same time. User 1 enters "10" into the field and presses the button. How can i update the text field on user 2's screen with the new data, without reloading the whole site?

Is the best way, to make a setInterval javascript to check for changes once in a while, or is there a way, where the server could push updates to the users when the model has changed?



via Chebli Mohamed

How can i define "DisplayErrorMessage" in this case?

This is a code that I wrote for my open button ... but I have error on "DisplayErrorMessage" part. What should I write instead? or how can I define it in order not to have the error again.

protected void btnOpen_Click(object sender, EventArgs e)
{
    txtFileName.Text = txtFileName.Text.Trim();
    if (txtFileName.Text == string.Empty)
    {
        string strErrorMessage = "you did Not specify file for opening!";
        DisplayErrorMessage(strErrorMessage);
    }

    string strFileName = txtFileName.Text;
    string strRootRelativePath = "~/app_data/pageContent";
    string strRootRelativePathName =
    string.Format("{0}/{1}", strRootRelativePath, strFileName);
    string strPathName = Server.MapPath(strRootRelativePathName);

    System.IO.StreamReader ostreamReader = null;

    try
    {
        ostreamReader = new System.IO.StreamReader(strPathName, System.Text.Encoding.UTF8);
        litPageMessages.Text = ostreamReader.ReadToEnd();
    }
    catch (Exception ex)
    {
        litPageMessages.Text = ex.Message;
    }
    finally
    {
        if (ostreamReader != null)
        {
            ostreamReader.Dispose();
            ostreamReader= null;
        }
    }
}



via Chebli Mohamed

Get the "indexOf" of an ICollection in Entity Framework

I have two objects that are connected in a way such that ObjectA contains an ICollection of ObjectB. I would like to be able to determine the indexOf ObjectB in inside the ICollection<ObjectB> that is stored in ObjectA.

One of the solutions was to convert the ICollection to a list and then use the built in IndexOf. However, when multiple threads access the ICollection, in many cases, I can get the same indexOf value for multiple ObjectBs.

Question Is there any way to have a certain field (of type int) that stores the index of ObjectB inside the ICollection? If not, is there anyway to ensure that indexOf (when multiple threads attempt to access it) gives the right index (i.e. no matter of the thread)?

Possible solutions I've tried to ensure to use a new context for each look up as well as GetDatabaseValues() and Reload(). This has worked better (especially in Debug mode), but when the debug mode is turned off, the same index of value is given to more ObjectBs.



via Chebli Mohamed

Changing the color of a texbox with a table cell VB ASP.Net

I have created a textbox within a cell of a table and I am using this to take input from a user and display it on a webpage. I however cant get the background of the textbox to change when the user clicks in side the textbox, normally I would use simple CSS for this but as the textbox is inside a table cell I cant seem to be able to work out how to do this. Any Ideas on how to approach this?

I have the following VB code to generate and populate my table.

VB

 Protected Sub GenerateTable(noOfRows As Integer)
    Dim table As Table
    Dim row As TableRow
    Dim cell As TableCell
    Dim tb As TextBox
    Dim lbl As Label
    table = Table1
    table.ID = "Table1"

    For i As Integer = 1 To noOfRows Step 1
        row = New TableRow()
        For j As Integer = 0 To 1 Step 1
            cell = New TableCell()
            If j = 1 Then
                tb = New TextBox()
                tb.ID = "TextBoxRow_" & i & "Col_" & j
                cell.Controls.Add(tb)

            ElseIf j = 0 Then
                lbl = New Label()
                lbl.ID = "Label" & i
                lbl.Text = "Volume " & i
                cell.Controls.Add(lbl)
            End If
            row.Cells.Add(cell)
        Next
        table.Rows.Add(row)
    Next
    ViewState("RowsCount") = noOfRows
    Session("RowsCount") = noOfRows
End Sub

HTML

<tr>
    <td colspan="2">
        <asp:Table class="Table1" ID="Table1" runat="server"></asp:Table>

        <br />
            <asp:Button ID="btnAddVolume" class="btnVolumeBreak" runat="server"  Text="Add Volume Break"/>
    </td>
</tr>



via Chebli Mohamed

Oracle 10G Installation on Windows

I have a database: Oracle SQL Developer 3.2.20.9 an asp.net web application running locally on a pc with Windows 7 enterprise 64 bit, and to developed it I used Visual Studio 2013. Now I should connect the application with the db so I' m trying to install:

Oracle 10g ODAC and Oracle Developer Tools for Visual Studio .NET

I get this Error: "Abnormal program termination. an internal error has occured. Please provide the following files to Oracle Support: Unknown Unknown Unknown"

Could I connect the webapp in other ways? When I go to Server Explorer in Visual Studio and I choose connect to database -> add connection -> Oracle database -> .NET framework Data Provider for Oracle I get: "This provider is deprecated and should not be used. Instead, download Oracle Developer Tools for visual Studio for comprehensive integration with Oracle databases."



via Chebli Mohamed

Why doesn't the value of SPAN update

ASP.net:

<span id="lblScore" class="lblScore">Your Score is: 0</span>
<asp:Label ID="lblHiddenScore" runat="server" CssClass="lblHScore" Text="" ClientIDMode="Static"></asp:Label>

The following jquery is executed after a certain event:

$(".lblScore").text("");
$(".lblScore").text("Your Score is: " + score);
$(".lblHScore").text(score);

I can see in the front-end, the value is changing but when I view the source of the HTML, it doesn't show the changes.

I am trying to use the score value from code-behind:

string yr = lblHiddenScore.Text; //it is always ""

How can I retrieve the value from the front end to use in code-behind



via Chebli Mohamed

Self hosting request logging

With ASP.NET 5 self-hosting, is there any way to configure request logging (as a separate module) much like you can do with IIS logging?

I want to avoid having to add a dependency to Microsoft.Framework.Logging in all my controllers or to hijack a common entry/exit point (such as authentication) for logging (because I want to log the total request processing duration).



via Chebli Mohamed

Example of using ASP.NET Identity 3.0 without Entity Framework

All examples I've seen by now for ASP.NET Identity 3.0 use Entity Framework to store user-related data.

Are there any example which does not use Entity Framework and where ApplicationUser class is not derived from Microsoft.AspNet.Identity.EntityFramework.IdentityUser?

In ASP.NET Identity 2.x it was needed to implement IUser interface. It seems there is not such interface now - so we're not sure how to define User class correctly. There is almost no documentation on this subject.

Second problem is with AddIdentity call in Startup.ConfigureServices. It's pretty tied to the particular classes from Microsoft.AspNet.Identity.EntityFramework namespace and it's unclear how to register identity services without those classes.



via Chebli Mohamed

Facebook share url with query strings

I have the following problem in Sharing pages from my website through Facebook. When I try to Share a complicated URL that containing a lot of query strings and their values using Graph API or Sharer.php or Sharing button, Facebook neglects the query string and omits them. As an example Sharing this URL http://ift.tt/1IK9arH which has been shared through many ways:

1- Through Sharer.php http://ift.tt/1IhJ11X ; Generates error cause all query strings and their values are deleted after sharing.

2- Through Facebook Share Button and embedding the code in my website; Also the same problem happened.

When I debug my url using Facebook debugger ,It gives me the canonical URL without any query string.

Are there any way to share the URL link exactly as it is with its query strings and their values or a way to control the Canonical URL or og:url , Image og:Image, Title og:title, and description og:description, while Sharing any page.



via Chebli Mohamed

how to map from a ViewModel to Model

i have to model and viewModel like this

public class Estate:BaseEntity
{

    public virtual BaseInformation floorType { get; set; }

}

 public class EstateViewModel:BaseEntityViewModel
{

    public  long floorType { get; set; }

}

and i wrote the code in controller like this :

[HttpPost]
    public long save(EstateViewModel estateViewModel)
    {
        Estate entity = new Estate();
       BaseInformation bi = new BaseInformation();
       bi.id = 1;
       entity.floorType = bi;
       EstateViewModel ev = new EstateViewModel(); 
                 Mapper.CreateMap<EstateViewModel, Estate>();
                 var model = AutoMapper.Mapper.Map<EstateViewModel,Estate>(estateViewModel);

            return estateRepository.save(entity);
    }

when call the action autoMapper give an error like this : An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code

please help how can fix it thanks



via Chebli Mohamed

Order of execution of fields and set/get in C#?

I am confused about the order of execution in C# regarding the setting of fields and set/get properties. Why is the value in Test2 not set when the constructor gets called while the value in Test is?

When an instance of a class is created is there some type of hidden/default "constructor" that sets the fields but does not call the setter of properties?

Does the setter get automatically called after the constructor or do I explicitly have to call it?

And finally is there good reasoning for this order of execution?

OUTPUT:

Test: 5
Test2: 0

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Test test = new Test();
        Test2 test2 = new Test2();
    }
}

class Test
{
    private int x = 5;
    public Test(){
        Console.WriteLine("Test: " + x);
    }
}

class Test2
{
    private int _x;
    private int x{
        get
        {
            return _x;
        }
        set
        {
            _x = 5;
        }
    }
    public Test2(){
        Console.WriteLine("Test2: " + x);
    }
}



via Chebli Mohamed

Stored Procedures and asp.net programmability; variable or SQL

Trying to display a users Lastname, Firstname --- Website And I need to insert a comma and space after Lastname to a GridView. I am trying to add a CASE statement in SQL and having trouble figuring it out.

Perhaps I need to use @parameter (scalar variable?) to abstract the memory read from CASE statement; or my syntax is wrong and I just don't understand.

SELECT 
CASE
          WHEN IsNull(people_Table.firstName, '') = ''
          THEN CONCAT(people_Table.lastName, ', ',
          people_Table.firstName) 
          ELSE people_Table.lastName
          END as fullName, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName

Otherwise I suppose I should use an asp databoundevent in the template. What is better for performance and security?



via Chebli Mohamed

Sorting of date column in GridView ASP.Net

I want to Sort this Invoice date column to go from the latest date "July 2015" to the oldest. I can't figure out how sort the Date Column. Any help would be really appreciated. Here is my code <asp:BoundField DataField="Month" DataFormatString="{0:Y}" HeaderText="Invoice Date" HtmlEncode="False"/>



via Chebli Mohamed

set point on map and getting data by that

I want set some point on some city on google map , and when user click on that , culculate some data on database by CityId wicth clicked on that .

I don't know how can Implement it ? I use Asp.net web forms and C# .

Anyone I need this and I don't have any idea ?

how can I do this ? thanks



via Chebli Mohamed

Looking for well established .Net CMS that supports direct querying of SQL Tables and/or Views

I currently use Sitefinity which does have a SQL Database but they discourage people from accessing it directly. Is there a CMS that actually supports/encourages direct access of database Tables/Views? Ideally it would support both MVC and WebForms. Needs to be .Net.



via Chebli Mohamed

I am reading an MVC 5 tutorial online (here). It says to use this code:

 List<Employee><employee> employees = new List<Employee><employee>();

I get an red underline. I understand I am trying to create an list of type Employee (there is an Employee class). But why don't I do it like this:

 List<Employee>employees = new List<Employee>();

What does the...

 <employee> 

...part of the code do? Why do I need it? It's just giving me a red underline. Maybe I need to upgrade to MVC 5 from MVC 4? I'm using Visual Studio 2012 (MVC 4)



via Chebli Mohamed

Datatable.rows.add is overwriting the same row

We are reading rows of one table in a loop and getting a column value in a datarow and using Datatable.rows.add(datarow) method adding the row into a new databale2.

But the data is getting overwritten in one single row in datatable2.

Regards, Vitus



via Chebli Mohamed

Angular Modal Only Works Within Index.html

My angular modal is working:

enter image description here

However, to get it to work, the modal script has to be within my index.html:

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
        <h3 class="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body">
        <ul>
            <li ng-repeat="item in items">
                <a href="#" ng-click="$event.preventDefault(); selected.item = item">{{ item }}</a>
            </li>
        </ul>
        Selected: <b>{{ selected.item }}</b>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" ng-click="ok()">OK</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
    </div>
</script>

And this is the call in the controller to it:

    $scope.addRecipe = function () {
        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.items;
                }
            }
        });

If I create an HTML file and put that above modal script in it, the modal stops showing up. (The page still gets grayed-out but there is no modal.) I've tried putting the HTML file in the root folder (right next to index.html) and I've had it in a separate folder, but it just won't show up. When I try to use this separate file, I change the templateUrl property of the call:

'app/partials/recipeAdd.html'

And I change the ID in the HTML:

<script type="text/ng-template" id="app/partials/recipeAdd.html">

What am I missing?



via Chebli Mohamed

changing label text and label background color in ASP.MVC WebGrid

I am rewriting an ASP.NET webform app to ASP.NET MVC. In the webform, there is a gridview with the the following gridview column code:

<asp:TemplateField HeaderText="PREV STAT MISSION"  ItemStyle-HorizontalAlign="Center" >

' BackColor= '<%# Item.PREV_STAT_MISSION == 1 ? System.Drawing.Color.Green : Item.PREV_STAT_MISSION == 2 ? System.Drawing.Color.Yellow : Item.PREV_STAT_MISSION == 3 ? System.Drawing.Color.Red : Item.PREV_STAT_MISSION == 4 ? System.Drawing.Color.Black : Item.PREV_STAT_MISSION == 5 ? System.Drawing.Color.Blue : System.Drawing.Color.Transparent %>' Font-Bold="true" Text='<%# Item.PREV_STAT_MISSION == 1 ? " F1 " : Item.PREV_STAT_MISSION == 2 ? " F2 " : Item.PREV_STAT_MISSION == 3 ? " F3 " : Item.PREV_STAT_MISSION == 4 ? " F4 " : Item.PREV_STAT_MISSION == 5 ? " F5 " : "" %>' />

I am using ASP.NET MVC WebGrid. So far, I rewritten the code like this

grid.Column("PREV_STAT_MISSION", format: @ @item.PREV_STAT_MISSION == 1 ? " F1 " : @item.PREV_STAT_MISSION == 2 ? " F2 " : @item.PREV_STAT_MISSION == 3 ? " F3 " : @item.PREV_STAT_MISSION == 4 ? " F4 " : @item.PREV_STAT_MISSION == 5 ? " F5 " : "" ),

But it does not work. I am not sure how to change the label text and color using Grid.Column. Any help is greatly appreciated. Thanks.



via Chebli Mohamed

ASP.net get max value from Profile field

I have a classic ASP website containing a users table with a ID_USER field (int, primary key, auto increment). The ID_USER value is used to track user's activity and is saved in other tables as part of the "Saved by","Saved date" logic.
Now, the website was updated and moved to ASP.NET, with the authentication rewritten using the ASP.NET membership and Profile providers. The old user's table was imported in the new structure. The ID_USER field became a Profile value in the new Membership/Profile logic.
All the other tables remained the same becouse of the compatibility between the two websites.

Question:
When creating new users I need to set the value for the ID_USER field too.
How can I do this? Can I somehow get the max value of the ID_USER profile field?
Thanx



via Chebli Mohamed

Partial view data not refreshing in mvc

i have a bootstrap table in asp.net mvc view with a link to open model dialog for selected item id. it calls action method and action methos returns partial view. every thing working on refreshing page but problem is everytime it is showing first time loaded vaues. what i observed in debug is action methos is not calling on every click , it called only for first time. i am not getting where to make change. below is my approach..

Here is HTML

<td>
<a href="~/Trainer/DislayTrainerDetails/@item.trainerid" aria-hidden="true" 
 style="cursor:pointer" data-toggle="modal" data-   
 target="#myModalTrainer">More</a>
 </td>

popup Model Code :

<div class="modal fade" id="myModalTrainer" tabindex="-1" role="dialog" 
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">

    </div>
  </div>
</div>

Controller :

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public ActionResult DislayTrainerDetails(int id)
    {
        ModelState.Clear();

        TrainerService tser = new TrainerService();

        var trainer = tser.GetAllTrainer();

        var c = from i in trainer where i.trainerid == id select i;

        return View("_PartialTrainerDetails", c.FirstOrDefault());
    }

please help in this.. thanks in advance.



via Chebli Mohamed

Retrieve client certificate from a smart card without IIS validation

I need to authenticate my WEB users by their smart card certificate. I am using IIS with SSL Settings: "Require SSL" and with "Accept" client certificate. This part works fine, the user is trying to enter the WEB page (.aspx) and being asked to choose its certificate and to enter a PIN code. In the next step the browser sends the certificate to the server and the IIS validates it. I don't want IIS to validate the certificate, I m u s t validate it myself. I am using the IIS mechanism to retrieve the client certificate because I can't use ActiveX or JAVA Applets.

How can I bypass the IIS certificate validation and yet get the client certificate from the smart card?



via Chebli Mohamed

Implementing a proxy in C# MVC

I'm struggling with a feature in my asp.net MVC application, in a controller action I am passed the URL of a PDF file which I want to return to the user, but I'm having difficulty implementing it. I'm currently using a WebClient but I'm not sure this is the best approach. I cannot return a RedirectResult as our firewalls will not allow it, so I need to download it and return it as the result of the controller action.

Below is a simplified snippet. I cannot use an off the shelf reverse proxy like Managed Fusion as we need to perform additional steps in the Action.

Any help would be appreciated.

public ActionResult GetPDF()
{
    var documentUrl = Request["documentUrl"];
    var wc = new WebClient();
    var d = wc.DownloadData(documentUrl);
    MemoryStream ms = new MemoryStream(d);
    return new FileStreamResult(ms, "application/pdf");
}



via Chebli Mohamed

How to connect to (localdb) database on server for Asp.Net membership?

I'm trying to output a list of users membership.GetAllUsers(), but I get an exception:

When establishing a connection to SQL Server error has occurred that is associated with the network or with a specific instance. Server not found or unavailable. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error upon detection of the specified server or instance)

My connection string :

<connectionStrings>
    <add name="DefaultConnection" 
         connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-SDC-20150804171038;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-SDC-20150804171038.mdf" 
         providerName="System.Data.SqlClient" />
</connectionStrings>



via Chebli Mohamed

How to disable a textbox without fading text?

Is there anyway of getting all of the properties of a !enabled textbox except the faded text?

I cannot use a Label because I want the textbox to be enabled eventually. I cannot use readonly because I do not want the user's cursor to appear within.



via Chebli Mohamed

global.asax Application_Error event not firing

In my web.config, I don't have anything like CustomErrors. As I want everything to be handled by Global.asax .

This is my web.config:

<?xml version="1.0"?>

<configuration>
  <system.web>
    <compilation targetFramework="4.5" debug="false"/>
    <authentication mode="Forms" >
      <forms loginUrl="login.aspx" name=".ASPNETAUTH" protection="None" path="/" timeout="20" >
      </forms>
    </authentication>

    <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,:,\,?" targetFramework="4.5" maxRequestLength="1048576"/>

    <httpModules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </httpModules>

  </system.web>

  <system.webServer>

    <validation validateIntegratedModeConfiguration="false"/>

    <modules>
  <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule"/>
  <remove name="UrlAuthorization"/>
  <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
  <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
</modules>
    <security>
      <requestFiltering allowDoubleEscaping="true">

      </requestFiltering>
    </security>

  </system.webServer>

</configuration>

And this is Application_Error event in Global.asax :

void Application_Error(object sender, EventArgs e)
{
    try
    {
        Response.Redirect("~/error.html");
    }
    catch
    {
    }
}

Do I need web.config?



via Chebli Mohamed

.NET/IIS 7.5 Azure DownloadToFile method local permission difficulty

I have to sync down blobs from Azure into each server for our custom C# CMS I'm writing. (we're planning on servers in different locations) I am creating a local directory on each server to hold 'research articles' content'. that works fine. setting permissions for it, works fine. However, upon calling .DownloadToFile(...) on Azure's 'CloudBlockBlob' hits the permission error.

My code is smart enough to get the appPoolIdentity name and use that to set permissions. but am I setting what's needed?...

// === Get body content from Azure blobs ===
        // 1. if local directory doesn't exist, create it
        var localdirectory =
            ConfigurationManager.AppSettings["ResearchArticleBodyRelativeLocalDirectory"] +
            researchArticle.BodyRelativeLocalPath;
        var exists = System.IO.Directory.Exists(Server.MapPath(localdirectory));
        if (!exists)
        {                
            // 2a. if it didn't exist, create it, set write perms, and pull azure blobs
            // create
            System.IO.Directory.CreateDirectory(Server.MapPath(localdirectory));
            // --perms--
            // get user for app
            var info = new DirectoryInfo(Server.MapPath(localdirectory));
            var security = info.GetAccessControl();
            var appPoolName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            security.AddAccessRule(new FileSystemAccessRule(appPoolName, FileSystemRights.Modify, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
            security.AddAccessRule(new FileSystemAccessRule(appPoolName, FileSystemRights.Modify, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); //(I've tried 'write' as well) 
            info.SetAccessControl(security); 
            // pull blobs
            Azure.GetBlobsFromAzureByContainerName(researchArticle);
        }
        else
        {
            // 2b. If it does exist, check/compare lastModifiedDate and pull blobs if necessary
            if (Azure.ContainerNewerThanLocal(researchArticle))
                Azure.GetBlobsFromAzureByContainerName(researchArticle);                
        }

Here's the static 'Azure' class:

  public static List<CloudBlockBlob> GetBlobsFromAzureByContainerName(ResearchArticle researchArticle)
    {
        // Retrieve storage account from connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.AppSettings["StorageConnectionString"]);

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve a reference to a container.
        CloudBlobContainer container = blobClient.GetContainerReference(researchArticle.BodyAzureContainerName);

        List<CloudBlockBlob> contentBlobList = new List<CloudBlockBlob>();

        // TODO: Delete everything in local directory ..?
        System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HostingEnvironment.MapPath(ConfigurationManager.AppSettings["ResearchArticleBodyRelativeLocalDirectory"] +
                    researchArticle.BodyRelativeLocalPath));

        foreach (FileInfo file in downloadedMessageInfo.GetFiles())
        {
            file.Delete();
        }
        foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
        {
            dir.Delete(true);
        }
        // Loop over items within the container and output the length and URI.
        foreach (IListBlobItem item in container.ListBlobs(null, false))
        {
            if (item.GetType() == typeof(CloudBlockBlob))
            {
                CloudBlockBlob blockBlob = (CloudBlockBlob)item;
     *explodes here-->blockBlob.DownloadToFile(HostingEnvironment.MapPath(
                    ConfigurationManager.AppSettings["ResearchArticleBodyRelativeLocalDirectory"] +
                    researchArticle.BodyRelativeLocalPath), FileMode.Create); 

FYI: I even manually set the permissions on the folder using 'NETWORK_SERVICE', 'IIS_IUSRS', and 'IIS_WPG' all set to write and then full control... then I tried 'Everyone' set to full control to no avail... not sure what is going on. I'm in an active directory here, so that might be an issue?

there is no authentication on the public side/site, all anonymous.

<authentication mode="None" />
<authorization>
  <allow users="?" />
</authorization>

Could this be a part of the issue? Web.config saying all anonymous, but then setting NTFS perms on sub-folders causes a problem?

The error I am getting is always:

Access to the path 'C:\...\ResearchArticleBodyLocal\abc' is denied.



via Chebli Mohamed

How to save items from a CheckBoxList To dataBase

I am using a CheckBoxList that bind from database,

Now saving these values is becoming problematic.

I want to save the selected value to new data table, and than show the items that chacked.

<div style="position: absolute; left: 600px; top: 220px;">
        <asp:CheckBoxList ID="CheckBoxList1" runat="server" Width="200px" TextAlign="Left" CssClass="mycheckbox" DataSourceID="SqlDataSource1" DataTextField="TypeGeare" DataValueField="IdGeare">
        </asp:CheckBoxList>
        <asp:SqlDataSource runat="server" ID="SqlDataSource1" 
        ConnectionString='<%$ ConnectionStrings:RegistrationConnectionString %>'
        SelectCommand="SELECT * FROM [InstituteGeare]" OnSelecting="SqlDataSource1_Selecting">
        </asp:SqlDataSource>
    </div>

<div style="position: absolute; left: 650px; top: 500px;">
<asp:Button ID="pricegearebtn" runat="server" Text="send " Height="50" Width="160" />
</div>

Another thing, I tried to creat a table with 2 forgien key, but without success. I get this error : "SQL72031 :: This deployment may encounter errors during execution because changes to [dbo].[GearReq].[UserId] are blocked by [dbo].[GearReq]'s dependency in the target database."

CREATE TABLE [dbo].[GearReq] (
[UserId] NVARCHAR(50) NOT NULL, 
[GearId] INT NULL
FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([Id]), 
FOREIGN KEY ([GearId]) REFERENCES [dbo].[InstituteGeare]([IdGeare])

);



via Chebli Mohamed

Strategy for breaking 1 Visual Studio web project into 2 in a way that's least painful for source control

I've got a solution in Visual Studio that has an ASP.NET web project as well as some other projects. Everything is in Git. I want to split the functionality of what's now a single website (single web project) into 2 sites (2 web projects) for administrative reasons and I'm looking for recommendations on how to do the split with the least impact on source control and file version history.

One option is to copy the project directories to a 2nd location, designate the source as project 1 and the copy as project 2, then remove the bits of each which aren't needed in their respective projects. The problem with this approach is that I will end up with tons of deletions in Git and I am not sure if I will lose history for the files which are copied to the new location because they'd be new according to Git.

The other option is to create a 2nd project file but leave the underlying source files alone, then modify both project files to point to just their respective relevant bits by doing a "remove from solution" in each. This would modify the .csproj files only which is a much "lighter" change. Naturally of course some files (eg global.cs) will need to exist in both projects and be unique.

I'm sure there are additional options on how to do this, or perhaps better ways of thinking about the problem.

What are some thoughts on accomplishing this split?



via Chebli Mohamed

qq fine uploader multiple files not able to upload

I've used qq fine uploader for uploading files.
According to requirement,at max 5 files can be uploaded.
It works but sometimes it behaves strange. If I select 5 files, few files get uploaded and few shows processing message continuously.

   var manualUploader = new qq.FineUploader({
            element: document.getElementById('fine-uploader-manual-trigger'),
            template: 'qq-template-manual-trigger',
            request: {
                endpoint: 'UploadQCDoc.aspx'
            },
            thumbnails: {
                placeholders: {
                    waitingPath: '/fine-uploader/placeholders/waiting-generic.png',
                    notAvailablePath: '/fine-uploader/placeholders/not_available-generic.png'
                }
            }, deleteFile: {
                enabled: true,
                forceConfirm: true

            },
            autoUpload: false,
            debug: true,
            messages: {
                tooManyItemsError: 'You can not upload more than ' + '<%=ConfigurationManager.AppSettings["QCMaxUpload"].ToString() %>' + ' documents.'
            },
            validation: {
                allowedExtensions: ['jpeg', 'jpg', 'png', 'gif', 'pdf', 'docx', 'csv', 'xlsx', 'xls'],
                sizeLimit: 10485760, // 10mb
                itemLimit: thermoMaxUploadLimit
            },
            callbacks: {
                onSubmitted: function (id, name) {

                }, onUpload: function (id, name) {

                },
                onCancel: function (id, name) {

                },
                onValidate: function () {

                },

                onComplete: function (id, fileName, responseJSON) {
                    if (responseJSON.success) {
                        tempFileName = fileName + ":" + responseJSON.filename + "\\";
                        fArray[id] = tempFileName;

                    }
                },
                onSubmitDelete: function (id) {
                    if (confirm("Are you sure you want to delete?")) {
                        var fileName = fArray[id].split(":")[0];
                        if (fileName != null && fileName != '') {
                            DeleteFile(0, fileName, id); //for files that are not stored in db but in folder only , filename will be used to delte file
                        }
                    }
                    return false;
                }

            }
        });

        qq(document.getElementById("trigger-upload")).attach("click", function () {
            manualUploader.uploadStoredFiles();
        });

What the issue can be? Any help will be appreciated.



via Chebli Mohamed

Fix the row and column as header dynamically in html without modifying the code [on hold]

I have a html page which contains a table in it and I have add that page into my asp.net project. Now I want freeze the panes(fix 1st five rows as header and 1st column) without modifying the html page..

In that html page the table did not contain 'thead', 'tbody' and 'th' tags.

It just like this...

 <table>
   <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
 </table>

I don't want to add 'th', 'thead' tags to my html page... because I don't want modify my page... I think we may add them and freeze the panes dynamically.....

ex: http://ift.tt/1DqekbK



via Chebli Mohamed

Http request returns as failure but actually succeeds

I'm developing a web API and a website to interact with that api. So far I have each part done. I am using angular js for my website and an asp.net webapi for the other end. When I try to connect the two together to make it all work the signal sends and the api end gets executed like normal however in the console on the website end gives me an error: XMLHttpRequest cannot load http://localhost:1795/api/products/[ip address]/en-us/[product]/[version]/[email address]. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:50028' is therefore not allowed access.

It just seems to be going in loops because if I now remove the custom header I provided for the Access-Control-Allow-Origin it still triggers the process I have in the api which gets executed as normal but I still end up getting an error on the other end. XMLHttpRequest cannot load http://localhost:1795/api/products/[ip address]/en-us/[product]/[version]/[email address]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50028' is therefore not allowed access.

If I remove the credentials from the http request I get a 401 unauthorized error and the api process won't trigger. I've created both of these projects in Visual Studio 2013 and are both running in Chrome.

Do I ignore the errors on the website side and keep things as they are? Or is there another way to make the call without getting these console errors?



via Chebli Mohamed

Windows App Design

how to start windows app design in Visual Studio 2012 and latest version. I have good knowledge of design and develop web app in Visual Studio 2010 and 2012. Now I wish to move on Windows Mobile App Design and Develop. But I am unable to Start. Kindly help me and suggest me how I can start to design Windows mobile app.



via Chebli Mohamed

Textbox for Decimal value null when submitting form in ASP.Net?

Textbox value when submitting the form is null in the controller. Simplified structure of what I have is below:

MODEL

public class MyObject
{
    public decimal DecimalProperty { get; set; }
}

VIEW

@for(var i = 0; i < Model.Count; i++) 
{
   using (Html.BeginForm("UpdateObject", "MyController", FormMethod.Post))
   {
      @Html.Textbox(String.Format("Model[{0}].DecimalProperty", i), Model[i].DecimalProperty)
      <input type="submit" value="Update"/>
   }
}

CONTROLLER

public ActionResult UpdateObject(MyObject myObject)
{
   // Do Stuff...
}

If I put a breakpoint in the controller method, then check the property values of myObject, the DecimalProperty is null. There are other properties on the actual object I'm using and those come across alright, but for some reason this property isn't. I haven't found anything that suggests that decimals must be handled differently than a DateTime or string. I have also tried writing out the html for the input by hand:

 <input type="text" name="@(String.Format("Model[{0}].DecimalProperty", i))" value="@Model[i].DecimalProperty" />

I have set the name and the id attributes of the textbox just to be on the safe side. Any ideas as to why my textbox value is null when I submit the form?



via Chebli Mohamed

append server side code from client side jquery

I have a server side code block such as <%Response.Write(...)%> How would i append it dynamically from client side script using jquery?

$("div.items").append('<form action="#" method="POST">');
$(".items form').append('<%Response.Write(...)%>')  //???



via Chebli Mohamed

How to do performance testing for website hosted in integration environment

I wanted to do performance testing(profiling, instrumentation) for asp.net website which is hosted in our integration environment. I am able to do it in local machine using visual studio performance and diagnostics. How to do this in integration environment without installing visual studio in integration.



via Chebli Mohamed

ASP.NET c# Customer Resources "branching" system

Last couple of hours I am trying to figure out how I can use CustomerResources like the localization and globalization version of the Resources. I have a multilanguage website which uses Resources.localization-globalization.resx to get the texts for that language, example : Resources.en-EN.resx. Now I have multiple customers who want to have some texts changed to their own way of saying it. But also use Multilanguage on that version so what I wanted to do is create a folder based on the customer GUID, and use that name to select the right Resources file like this :

Google/CustomerResources.resx

the /\ folder is dynamic and could be either Google or Yahoo or Bing.

Is there a way to achieve this or could I change this to CustomerResources.Google.resx?



via Chebli Mohamed

Ajax Post in MVC... Why is the string null?

So basically I'm creating a Request system in a MVC application. I have this "Create Request" section where I can select the type of request I want to do in a DropDownList from Telerik. What I want to do is, every time I choose something from the list, a partial view appears with the form related to that type of request.

This is my ajax Post from the Create.cshtml View:

<script>
    function change() {
        var value = $("#RequestType").val();
        alert(value);
        $.ajax({
            url: "/Request/CreateRequestForm",
            type: "get",
            data: { requestValue : JSON.stringify(value)}
        }).done(function (data) {
            $("#partialplaceholder").html(data);
        }).fail(function () {
            alert('error');
        })
    };
</script>

This is my controller:

public ActionResult Index()
        {
           //Things
            return View();
        }

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpGet]
    public PartialViewResult CreateRequestForm(string dropDownValue)
    {   string partialView="";
        int RequestType = Convert.ToInt32(dropDownValue);
        switch (RequestType)
        {
            case 1 :
                partialView+="_CreateAbsence";
                break;
            case 2 :
                partialView += "_CreateAdditionalHours";
                break;
            case 3 :
                partialView += "_CreateCompensationDay";
                break;
            case 4 :
                partialView += "_CreateErrorCorrection";
                break;
            case 5 :
                partialView += "_CreateVacation";
                break;
        }
        return this.PartialView(partialView);
    }

Everytime time the even triggers my dropDownValue string is null... Why? Thanks in advance! :)

EDIT View Code

<h1>Create New Request</h1>

        @(Html.Kendo().DropDownList()
          .Name("RequestType")
          .DataTextField("Text")
          .DataValueField("Value")
          .Events(e => e.Change("change"))
          .BindTo(new List<SelectListItem>() {
              new SelectListItem() {
                  Text = "Absence",
                  Value = "1"
              },
              new SelectListItem() {
                  Text = "Additional Hours",
                  Value = "2"
              },
              new SelectListItem() {
                  Text = "Compensation Day",
                  Value = "3"
              },
              new SelectListItem() {
                  Text = "Error Correction",
                  Value = "4"
              },
              new SelectListItem() {
                  Text = "Vacation",
                  Value = "5"
              }
          })
          .Value("1")
        )


<script>
    function change() {
        var value = $("#RequestType").val();
        alert(value);
        $.ajax({
            url: "/Request/CreateRequestForm",
            type: "get",
            data: { requestValue : JSON.stringify(value)}
        }).done(function (data) {
            $("#partialplaceholder").html(data);
        }).fail(function () {
            alert('error');
        })
    };
</script>

<div id="partialplaceholder">

</div>



via Chebli Mohamed

The table-border doesn't work in IE11 but works in Chrome

I'm trying to get the border working in IE11 like it's working in Google Chrome. I use ASP.NET,inline styling, nth-child, last-child. This is a example of how I use it.

.GridView tbody tr:nth-child(13) td,.GridView tbody tr:nth-child(15) td,.GridView tbody tr:last-child td{
        border-bottom:thin solid white;
    }

Can anyone tell me which attribute or selector I'm not allowed to use?



via Chebli Mohamed

Web method not called from ajax post

I am trying to call a method as web method from ajax like:

$.ajax({
                    url: 'http://ift.tt/1SI1MDN',
                    method: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    //data: angular.toJson(categories),
                    data: angular.copy(categories)

Here categories is serialized as

 [
    {
        "name": "Fruits",
        "metrics": "cups",
        "entry": 0,
        "recommended": true,
        "color": "#989898"
    },
    {
        "name": "Vegetables",
        "metrics": "cups",
        "entry": 1,
        "recommended": true,
        "color": "#37A0BC"
    }
]

Webmethod is like:

        [WebMethod(true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string AddSelfEntry(List<Entry> items)
        {

Here entry is

public class Entry
        {
            public string name;
            public string metrics;
            public int entry;
            public bool recommended;
            public string color;
            //{"name":"Sugary Drinks","metrics":"times","entry":1,"recommended":false,"$$hashKey":"00F"}
        }

I am getting error at console:

enter image description here

No breakpoint hit at webmethod in debugmode.

Please help where I am wrong?



via Chebli Mohamed

How to add service reference in visual studio with nettcpbinding hosted in IIS?

enter image description here

I have configured wcf service in IIS. my web.config is

<services>
<service name="DNExpWCFService.Service1"        
behaviorConfiguration="DNExpWCFServiceBehaviour">
<endpoint name="WSGetEmployee" address="/WSGetEmployee"                       
binding="wsHttpBinding" contract="DNExpWCFService.IService1">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"></endpoint>
</service>
</services>

Now when I add service reference using http://localhost:8333/Service1.svc it works fine. But for nettcpbinding I can't add service reference. I tried using net.tcp://localhost:8444/Service1.svc. But it also fails. How to add service reference using nettcpbinding?



via Chebli Mohamed

dimanche 28 juin 2015

How do I search/replace all 'n(' -> 'n*(' and ')n' -> ')*n' within same equation?

Scenario:
The user can enter any number of parentheses pairs into an equation in String format. However I need to check to be sure that all parentheses '(' or ')' have an adjacent multiplier symbol ''. Hence '3(' should be '3(' as ')3' should be ')3'.

I need to replace all occurrences of possible 'n(' with 'n(' and ')n' with ')*n'.

Example: 1+5(3+4)7/2 ---> 1+5*(3+4)7/2

What is the correct regex what to do this?

I was thinking of something like '[0-9](' & )[0-9]'. But I don't know the full syntax of search for all assurances of patterns to be replaced with '' insert.

Making a [code][/code] for BBcode with php regex

I would like to make a [code][/code] tag for bbcode so that what would be inside wouldn't be taken into account by the php regex that I made.

Example :

Hello [b]newbie[/b], to write in bold, use the following : [code][b](YOURTEXT)[/b][/code]

Should return in HTML :

Hello <strong>newbie</strong>, to write in bold, use the following : [b](YOURTEXT)[/b]

Here is a view of a part of my bbcode function :

<?
function bbcode($var) {
   $var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
   $var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
   $var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
   return $var;
}
?>

Thank you in advance for your kind help !


EDIT : Here is how I finally made it work :

<? 
function bbcode($var) {
$var2 = preg_split('`(\[code].*?\[/code])`isU', $var, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);

$var = preg_replace('`(\[code].*?\[/code])`isU', $var2[1], $var);
$var = preg_replace('`\[code\](.+)\[/code\]`isU', '<div>$1</div>', $var);
return $var;
}

$text = 'Hello [b]newbie[/b], to write in bold, use the following [u]lol[/u] : [code][b](YOURTEXT) [u]lol[/u][/b][/code] [b][u]LOL[/u][/b]';

echo bbcode($text); 
?>

HOWEVER, there is a new problem left : if the character chain starts directly with '[code]' for example

[code][b]hello[/b][/code] test

than the result will be :

test test

This is because $var2[1] now leads to what comes after the [/code].

Could someone please help me to make a better delimitation that would also work for that second character chain ? Thank you in advance !

Regex - parsing string into groups

I have specific log messages and I would like to parse it into groups. I would like to make an alternative version in case if my string is more specific.

My logs:

18:48:24:284 => [DEBUG] [xxx.yyy.zzz] [8] Message1
18:48:24:671 => [INFO] [uuu.www.aaa] [8] Method: 'ReturnType MethodName(MethodParameter)'. Line: ~30. Message2

I have written a regex:

(?<timestamp>\d+:\d+:\d+:\d+.*)\s+=>\s+\[(?<level>\w+)\]\s+\[(?<emmiter>.*)\]\s+\[(?<thread>\d+)\]\s+(?<message>.*)

which parses these messages into specific groups:

timestamp: 18:48:24:284
level: DEBUG
emmiter: xxx.yyy.zzz
thread: 8
message: Message1

timestamp: 18:48:24:671
level: INFO
emmiter: uuu.www.aaa
thread: 8
message: Method: 'ReturnType MethodName(MethodParameter)'. Line: ~30. Message2

But right now I would like to add 2 more groups, in case if they exist : method and Line

So, I would like to get results like this:

timestamp: 18:48:24:284
level: DEBUG
emmiter: xxx.yyy.zzz
thread: 8
method:
line: 
message: Message1

timestamp: 18:48:24:671
level: INFO
emmiter: uuu.www.aaa
thread: 8
method: ReturnType MethodName(MethodParameter)
line: ~30
message: Message2

Can you please help me with that? Everything I do results in parsing only Line1 or only Line2 properly, but I would like to parse them both with one regex.

finding repeated characters in a row (3 times or more) in a string

Here is the code for finding repeated character like A in AAbbbc

String stringToMatch = "abccdef";
    Pattern p = Pattern.compile("((\\w)\\2+)+");
    Matcher m = p.matcher(tweet);
    while (m.find())
    {
       System.out.println("Duplicate character " + m.group(0));
    }

Now the problem is that I want to find the characters that are repeated but 3 times or more in a row, when I change 2 to 3 in the above code it does not work, Can anyone help?

Trouble Understanding Regular Expression [duplicate]

This question already has an answer here:

I am trying to learn the regular expression and I have learnt some easier notations but unable to understand what does the below expression means. Please shed some light on it.

Sample Data :

create table targets ( target varchar2(15) );

REM INSERTING into TARGETS
SET DEFINE OFF;
Insert into TARGETS (TARGET) values ('aaa');
Insert into TARGETS (TARGET) values ('a b c');
Insert into TARGETS (TARGET) values ('b  b  b  b');
Insert into TARGETS (TARGET) values ('  bbb xx  ');
Insert into TARGETS (TARGET) values ('wdef def w');
Insert into TARGETS (TARGET) values ('defxdefdef');
Insert into TARGETS (TARGET) values (null);


select target,
       regexp_replace(target,'(d)ef|.','\1') intermediate_string

from targets;

If possible please direct me to some good site for learning Regular expressions. Thanks!

python regex use capture group to define another groups length { }

I am parsing streaming hex data with python regex. I have the following packet structure that I am trying to extract from the stream of packets:

'\xaa\x01\xFF\x44'

  • \xaa - start of packet
  • \x01 - data length [value can vary from 00-FF]
  • \xFF - data
  • \x44 - end of packet

i want to use python regex to indicate how much of the data portion of the packet to match as such:

r = re.compile('\xaa(?P<length>[\x00-\xFF]{1})(.*){?P<length>}\x44')

this compiles without errors, but it doesnt work. I suspect it doesnt work because it the regex engine cannot convert the <length> named group hex value to an appropriate integer for use inside the regex {} expression. Is there a method by which this can be accomplished in python without resorting to disseminating the match groups?

Background: I have been using erlang for packet unpacking and I was looking for something similar in python

Php: How to ignore newline in Regex

I've already found a lot of stackoverflow questions about this topic. But I cannot find out the solution out of these questions for my problem.

I have the following html:

<p><a name="first-title"></a></p>
<h3>First Title</h3>
<h2><a href='#second'>Second Title</a></h2>
<h3>Third Title</h3>

I want to find out the <h3> prepended by </a></p>. In this case, the output should be:

<h3>First Title</h3>

So I implement the following regular expression;

preg_match_all('/(?<=<\/a><\/p>)<h3>(.+?)<\/h3>/s',$html,$data);

The above regular expression cannot output anything from the above html. But if I remove the newlines from the html, the above regular expression can correctly output my desire result.

I would not like to remove newlines from the html if possible. How should I develop regular expression to ignore the newlines from the source string?

Please, help me.

Python // Regex // Tags

I am trying to extract some text from between

</br></td>, <td class="first">TEXT_1a<br>TEXT_1b
                                </br></td>, <td class="first">TEXT_2a<br>TEXT_2b
                                </br></td>, <td class="first">TEXT_3a<br>TEXT_3b
                                </br></td>, <td class="first">TEXT_4a<br>TEXT_4b
                                </br></td>, <td class="first">TEXT_5a<br>TEXT_5b
                                </br></td>, <td class="first">TEXT_6a<br>TEXT_6b

I used BeautifulSoup (BS4) text = first_td.renderContents() trimmed_text = text.strip() print trimmed_text to extract the text. However, I only get the first text after <td tag. Nevertheless I would like to extract all the text in the tags, preferably sorted in columns (array). After I went with BS and it did not work I thought Regex is the way to go. One minor thing, I am an absolute regex amateur...

Any ideas how to get the text out there?

Thank you in advance

Shell remove string including newlines

I am currently working on a custom source patcher and I'm having troubles with replacing string by another, including newlines.

For instance, I want to remove this pattern :

\n/* @patch[...]*/

In order to get this... :

this.is = code ;
/* @patch beta
    blah blah
*/
if (!this.is) return 0 ;
/* @patch end */

... to this :

this.is = code ;
if (!this.is) return 0 ;

And not this :

this.is = code ;
<- newline
if (!this.is) return 0 ;
<- newline


Using a shell script, I'm using sed command in order to do what I want :

sed -e "s|\/\* @patch.*\*\/||g" $file > $file"_2"

This works pretty well, but the newlines are still there.


This way doesn't work as sed can't parse newlines :

sed -e "s|\n\/\* @patch.*\*\/||g" $file > $file"_2"

Neither this method work : How can I replace a newline (\n) using sed? , nor tr (second answer on the same thread).


Would you have any solution to this ? Even heavy ones, performance is not important here.

P.S. : I am working on a web application, and in this case JavaScript files. Under Mac OS X Yosemite, but no matter what system I'm using, it seems to be a common issue for all bash users.


I found out another solution using Node.js for those who have troubles with their Awk version :

node -e "console.log(process.argv[1].replace(/[\n\r]\/\* @patch([\s\S]*?)\*\//mg, ''))" "`cat $filepath`"

How do I make Wget name files as part of URL?

Short story:

I want Wget to name downloaded files as they match regex token ([^/]*)

wget -r --accept-regex="^.*/([^/]*)/$" $MYURL

Full story:

I use GNU Wget to recursively download one specific folder under particular WordPress website. I use regex to accept only posts and nothing else. Here is how I use it:

wget -r --accept-regex="^.*/([^/]*)/$" $MYURL

It works and Wget follows all the desired URLs. However, it saves files as .../last_directory/index.html, but I want these files to be saved as last_directory.html (.html part is optional).

Is there a way to do that with Wget alone? Or would you suggest how to do the same thing with sed or similar tools?

Replace text on every selected line in a textarea

I have a textarea in my HTML where users can type something. There is a button near the textarea that adds a ' - ' to the beginning of a selected line to make it like a list.

For example if I have the following text:

This is a line of text

And I selected it all and pressed the button it would appear like this:

- This is a line of text

However, this only works when selecting one line. If I was to select two lines, it will only format the one line. Here is my code:

Javascript with some jQuery:

var selection = $("#answer" + questionNumber).getSelection();
if (selection.text != '') {
    $("#answer" + questionNumber).replaceSelectedText('  - ' + selection.text);
    return;
}

The .getSelection() and .replaceSelectedText() methods come from this jQuery plugin.

I though maybe by identifying if there are '\n' in the selection then adding the list styling to it, perhaps using regex, though I'm not sure how to go about coding that.

Here is a JSFiddle of my issue.

Check whether the string a number

I am trying to check whether the string a number is. I have tried the following which works seperatly but not together.

if (i.matches("\\d{2} | [0-9]"))

I appreciate any help.

How to escape xml for use in perl multiline search and replace?

I want to use perl to replace a key-value pair in an xml file, but I am having problems escaping the xml from the regex parser. All this is supposed to run from a bash script. So I have two variables:

macDefault="<key>DefaultVolume</key>\
                <string>91630106-4A1F-4C58-81E9-D51877DE2EAB</string>"

winDefault="<key>DefaultVolume</key>\
                <string>EBD0A8B3-EE3D-427F-9A83-099C37A90556</string>"

And I want perl to replace the occurrence of the value $macDefault with the value of $winDefault in the file config.plist

Unfortunately

perl -0pe  's/'"$macDefault"'/'"$winDefault"'/' config.plist

does not work, as perl reports:

Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "s/<key>DefaultVolume</key>                <string>91630106-4A1F-4C58-81E9-D51877DE2EAB</string"
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "<string>EBD0A8B3"
        (Missing operator before EBD0A8B3?)
Bareword found where operator expected at -e line 1, near "427F"
        (Missing operator before F?)
Bareword found where operator expected at -e line 1, near "9A83"
        (Missing operator before A83?)
Bareword found where operator expected at -e line 1, near "099C37A90556"
        (Missing operator before C37A90556?)
syntax error at -e line 1, near "s/<key>DefaultVolume</key>                <string>91630106-4A1F-4C58-81E9-D51877DE2EAB</string"
Illegal octal digit '9' at -e line 1, at end of line
Illegal octal digit '9' at -e line 1, at end of line
Execution of -e aborted due to compilation errors.

Thanks for any help!

php remove all attributes from a tag

Here is my code:

$content2= preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1);

This code removes all attributes from all tags in my website, but what I want is to only remove attributes from the form tag. This is what I have tried:

$content2 = preg_replace("/<form([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 

and

$content2 = preg_replace("/<(form[a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 

Pyhton/RegEx: Exclude StopWords

I have such list:

stopwords = ['a', 'and', 'is']

and such sentence:

sentence = 'A Mule is Eating and drinking'

Expected output:

reduced = ['mule', 'eating', 'drinking']

I have so far:

reduced = filter(None, re.match(r'\W+', sentence.lower()))

Now how would you filter out the stopwords?

Edit: Note the upper to lowercase conversion

replacing curly brackets and text in it with node

I have a string

var str="Hello my name is {john/www.john.com} and welcome to my {site/www.site.com}."

i have extracted curly brackets and made an anchor tag out of them like

<a href="www.john.com">john</a>

What i am trying to do is replace curly brackets and content in them with these nodes. Is it possible using regExp? I have studied regExp on MDN but still cant figure out the way.

How to grep just strings "ip" into a file?

Do you guys know some other way?
I am trying to find every way to find a string in some text. I want to find more ways using grep or sed. (bear in mind It's case sensitive)
  • Every word (strings) containing string "ip" and redirect the output result in /root/found;
 grep ip /usr/share/dict/words/ > /root/found
  • Just words (strings) initiating with "ip" and redirect the output result in /root/found;
 grep ^ip  /ust/share/dict/words > /root/found 
  • Just the word "ip" and redirect the output result in /root/found;
grep ^ip$ /ust/share/dict/words > /root/found

Nginx space on regex condition

I'm trying to block some user-agents on Nginx, and it's working great:

location /page {
  if ($http_user_agent ~* (badUserAgent1|badUserAgent2) ) {
   add_header 'Content-Type' 'text/plain';
   return 200 'Hello World';
  }
 }

But if I add a string with space, I get an error:

invalid condition "$http_user_agent"

Example:

location /page {
  if ($http_user_agent ~* (badUserAgent1|bad user agent 2) ) {
   add_header 'Content-Type' 'text/plain';
   return 200 'Hello World';
  }
 }

I tried to use apostrophes like this: ("badUserAgent1"|"bad user agent 2") without success.

Validate a datetime using: Y-m-d H:m:s in javascript

Pretty simple question, how do i validate a datetime, so the input is both the correct format, but also a valid date unlike 2015-02-30 ....

2015-06-28 16:06:35 //Valid

Regex matching multiple delimiters

I am trying to split on the following delimiters: full stop, semi-colon, *, +, ? and -

I tried the following but I am not making any progress, any help will be appreciated:

sentences = re.split("[.-;]*[\+]*[\?]*[\*]*", txt)

here is the sample text I've been trying this on:

- Text Editor: Now you can edit plain text files with airport tools
* Updated Dropbox support 
* Improved
stability
- New icon

Expected output after the split is a list of items:

TextEditor: Now you can edit plain text files with airport tools, Updated Dropbox support, Improved stability, New icon

Scrapy LinkExtractor - which RegEx to follow?

I'm trying to scrape a category from amazon but the links that I get in Scrapy are different from the ones in the browser. Now I am trying to follow the next page trail and in Scrapy (printed response.body into a txt file) I see those links:

<span class="pagnMore">...</span>
<span class="pagnLink"><a href="/s?ie=UTF8&page=4&rh=n%3A2619533011%2Ck%3Apet%20supplies%2Cp_72%3A2661618011%2Cp_n_date_first_available_absolute%3A2661609011" >4</a></span>
<span class="pagnCur">5</span>
<span class="pagnLink"><a href="/s?ie=UTF8&page=6&rh=n%3A2619533011%2Ck%3Apet%20supplies%2Cp_72%3A2661618011%2Cp_n_date_first_available_absolute%3A2661609011" >6</a></span>
<span class="pagnMore">...</span>
<span class="pagnDisabled">20</span>
<span class="pagnRA"> <a title="Next Page"
                   id="pagnNextLink"
                   class="pagnNext"
                   href="/s?ie=UTF8&page=6&rh=n%3A2619533011%2Ck%3Apet%20supplies%2Cp_72%3A2661618011%2Cp_n_date_first_available_absolute%3A2661609011">
<span id="pagnNextString">Next Page</span>

I'd like to follow the pagnNextString link, but my spider doesn't even start crawling:

Rule(SgmlLinkExtractor(allow=("n\%3A2619533011\%", ),restrict_xpaths=('//*[@id="pagnNextLink"]',)) , callback="parse_items", follow= True),

If I get rid of the rule or do sth. like '^http.*' it's working but it follows everything. What am I doing wrong here?

How to transform the current tab into an image and after that into text?

The problem I have is this: I have 2 kind of questions (see them below). So, here it is: there is a web where questions pop-up and the top 3 fastest persons who answer, get a score for that. I want to make a database with questions, but the OCR method I should use is a bit abstract to me. (NOTE: you can't click the text or select it. It's like an image into the browser). Should I save the whole page as an image and than parse the immage to get the text?

http://ift.tt/1LOsAup "Firt type of questions" http://ift.tt/1LvSsgT "Second type of questions"

The method should be very fast and finish the whole task in less than 2 seconds. Maybe 1 second or 2 at most. My problem is that in the begining, I want to save the question and further, to save the answer, but for now, I have no ideea how to treat the question in order so save it.

I would like to know a method to use a C# library for OCR. The data storage will not be a problem.

Sublime Text Syntax Highlighting – override one pattern with another

I have recently created my own syntax highlighting whose purpose is to aid me process post-OCR file. What it does is basically coloring various scripts – for instance all Latin-derived scripts in green, Cyrillic in orange and numbers in blue. Another function is to highlight all sorts of possible thrash. For instance, some dictionaries use ♦ to mark certain phraseologisms. However, OCR usually treats them as <|>, <ф>, «~► etc. I have a regex for that:

(; [•\<«'~◄\-■][СC0фóJГOО\(\)56\^\*£\$\&§][•\>»'~►\-■] )|(; [•\<«'~◄\-■][СC0фóJГO\(\)56\^\*£\$\&§] )|(; [СC0фóJГO\(\)56\^\*£\$\&§][•\>»'~►\-■] )|(; <> )

The regex works in the search function, but for whatever reason, it either works partially (highlights everything in red except for the letters, which retain their script-based colors) or not at all (I actually moved the whole block writing this, but when I moved it back it didn't work at all).

Here's the YAML-tmLanuage file on pastebin.

So, how do I make such regexes work? What can I do to make them globally override other syntax definitions?

Replace all occurrence of pattern in a string

I have a string that needs that look like this:

{"myObject":"{ \"timestamp\" : \"123\" , \"data\" : {\"description\": \"sample\" , \"number\": \"123\"}

What I need to do is to replace all \" with " only. What is the regex for this?

I have tried inputString.replace(/\\"/g, '"'); but its not working

Regex to remove punctuation from tokenized text

I'm trying to remove punctuation from tokenized text using regular expressions. Can anyone explain the following behaviour:

$ STRING='hey , you ! what " are you doing ? say ... ," what '
$ echo $STRING | sed -r 's/ [^[:alnum:][:space:]-]+ / /g;'
hey you what are you doing say ," what
$ echo $STRING | sed -r 's/ [[:punct:]]+ / /g;'
hey you what are you doing say ," what
$ echo $STRING | perl -pe 's/ [^[:alnum:][:space:]-]+ / /g;'
hey you what are you doing say ," what
$ echo $STRING | perl -pe 's/ [[:punct:]]+ / /g;'
hey you what are you doing say ," what

The ," token is preserved in the output, which I don't want. It's possible to match this token with:

$ echo $STRING | perl -pe 's/ [",]+ / /g;'
hey you ! what are you doing ? say ... what

URL rewrite not found

My URL it's like this

http://ift.tt/1TWVaiZ

and i want to rewrite url's like this

http://ift.tt/1GTUlAH

I thought this was the way

RewriteEngine On
RewriteBase /validar/
RewriteRule ^/([^/]*)/([^/]*)/$/api.php?desde=$1&que=$2 [L]

But i'm getting 404 and cant make it work

Any ideas? Thanks

PHP: filter specific pattern out of string

My raw output of socket_recvfrom is:

ID IP PING IDENTIFIERNUMBER USERNAME


0 127.0.0.1:1234 0 ID123456789 Moritz

1 127.0.0.1:1234 46 ID123456789 August Jones

2 127.0.0.1:1234 46 ID123456789 Miller


It is a single string that contains all of this informations in once and just contains whitespaces between the informations. All keys can be longer or shorter.

My problem:

When I preg_split("/\s+/") it, then I get a good array with useable data, but when the username contains spaces it creates a second index for this. Not good, all data that comes after this just get destroyed.

I sort the array like this: ID, USERNAME, PING, IDENTIFIERNUMBER, IP

Example by the sorting output with username with one space in it:


ID: 0, USERNAME: Moritz, PING: 0, IDENTIFIERNUMBER: ID123456789, IP: 127.0.0.1:1234

ID: 1, USERNAME: August, PING: Jones, IDENTIFIERNUMBER: 46, IP: ID123456789

ID: 127.0.0.1:1234, USERNAME: 2, PING: Miller, IDENTIFIERNUMBER: 46, IP: ID123456789


How do I get the information correctly out of the string?

Just forgot to say:

The string begins with: --------------------------------- in a not countable order. So it can be like 10 characters or 12. The string ends with:

 (8 users in total)

The regex methode looks good. I only need to filter out the other characters.

--------------------------------- 0 127.0.0.1:1234 0 ID123456789(OK) Moritz 1 127.0.0.1:1234 46 ID123456789(OK) August Jones 2 127.0.0.1:1234 46 ID123456789(OK) Miller (7 users in total)

Last problem: http://ift.tt/1eRW0xy

Regex PHP: Get specific content from a block of code from another website

I have a site from which I want to get specific content from 7 posts. Those all 7 seven posts have same HTML layout (See Below)

<div class="eventInfo">
<h3>Z's(矢沢永吉)</h3>
  <h4>Z's TOUR 2015</h4>

<dl>
    <dt><img src="/event/img/btn_day.png" alt="公演日時" width="92" height="20"> </dt>
    <dd>
      <table width="99%" border="0" cellpadding="0" cellspacing="0">
        <tbody><tr>
      <td width="9%" nowrap="nowrap">2015年6月</td>
      <td width="74%">4日 (木) 19:00開演</td>
    </tr>

  </tbody></table>
</dd>
<dt><img src="/event/img/btn_price.png" alt="料金" width="92" height="20"> </dt>
<dd>S¥10,500 A¥7,500 (全席指定・消費税込)<br><span class="attention">※</span>注意事項の詳細を<a href="http://ift.tt/1HpdVrL" target="_blank">矢沢永吉公式サイト</a>より必ずご確認ください</dd>

<dt><img src="/event/img/btn_ticket.png" alt="一般発売" width="92" height="20"> </dt>
<dd>
 <table width="99%" border="0" cellpadding="0" cellspacing="0">
  <tbody><tr>
    <td width="9%" nowrap="nowrap">2015年5月</td>
    <td width="74%">16日(土)</td>
  </tr>
</tbody></table>
  </dd>

  <dt><img src="/event/img/btn_contact.png" alt="お問合わせ" width="92" height="20"> </dt>
  <dd><a href="http://www.siteurl.com/" target="_blank">ソーゴー大阪</a> 06-6344-3326</dd>

  <dt><img src="/event/img/btn_info.png" alt="公演詳細" width="92" height="20"> </dt>
  <dd><a href="http://ift.tt/1GF5ySz" target="_blank">http://ift.tt/1HpdVrN; </dd>
</dl>
</div>

I just want to fetch the H3 from this layout and the first table in the code. What regex method should I use to get the desired results?

Also these are 7 posts just like the code above and I have to get H3 and the first table from each of it.

I have tested it but not sure that is it a correct way or not: http://ift.tt/1GF5z8P

But as you can see that I have to add unwanted data too like H4 DT IMG :(

This regex doesn't work in c++

It is supposed to match "abababab" since "ab" is repeated more than two times consecutively but the code isn't printing any output. Is there some other trick in using regex in C++.

I tried with other languages and it works just fine.

#include<bits/stdc++.h>

int main(){

  std::string s ("xaxababababaxax");
  std::smatch m;
  std::regex e ("(.+)\1\1+");   

   while (std::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

Redirect Loops and .htaccess

I just moved from a CentOS dedi to an Ubuntu VPS. The site is custom coded PHP.

Frontend works fine (including rewrite rules). The admin backend I can't get rewrite rules to work...

First error:

H00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

Then after using debug level:

AH00122: redirected from r->uri = /admin/index.php

The relevant bits of my htaccess are:

# mod_rewrite set:

Options +Includes

RewriteEngine on

# Administration
RewriteCond %{REQUEST_URI} ^(/+)admin/(.*)$
RewriteRule (.*) %{DOCUMENT_ROOT}/admin/index.php [L,QSA]

# Rewrite orther
RewriteCond %{REQUEST_URI} !^(/+)index.php(.*)$
RewriteCond %{REQUEST_URI} !^(/+)syscmd.php$
RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/index.php?page=$1 [L,QSA]

# If Rewriting Failure, Show error message (Internal backup)
RewriteCond %{REQUEST_URI} !^(/+)index.php$
RewriteCond %{REQUEST_URI} !^(/+)syscmd.php$
RewriteRule (.*) \1 [F]

This was working fine on CentOS too.

Any ideas? I already tried adding the following as the first condition:

RewriteCond %{REQUEST_URI} !/admin/ [NC]

That stopped it rewriting /admin completely.

Thanks

Grouping Output Pattern in Regex- Python

I would like to get only the sentences which match the regex pattern as output and avoid these NONE, how do i group the output which matches the pattern?

import re regex = re.compile('(.*)(?:India)') with open("D:/txt_res/abc.txt") as f: for line in f: result = regex.search(line) print(result)

The output which im getting is

None

None

None

<_sre.SRE_Match object; span=(0, 101), match='Email: abc.bitz@gmail.com >

None

None

None

<_sre.SRE_Match object; span=(0, 47), match='XYZ Engineer at ABC Organization, India'>

None

None

<_sre.SRE_Match object; span=(0, 32), match='Intern at S360, India'>

None

None

Using replace() replaces too much content

I'm using replace() to transform t in gwhen tis not followed by a letter p, I'm using this line of code:

"tpto".replace(/(t)[^p]/g, "g");

However, the result of this function is tpgand I was expecting tpgo. As I don't know which letter will follow the t I need something dynamic but I don't know what to do, any ideas?

Java String Replace Using Reular Expression

Original String: Flexible Premium Deferred Annuity (Policy #0410011)

Expected String : Flexible Premium Deferred Annuity

Would appreciate if someone can provide java code to accomplish this.

Thanks.

Download site with selected CGI input

So I have this script:
http://ift.tt/1JrcpWF
How do I download for example, file which has input 1880: http://ift.tt/1SUjWig from this site
They are all cgi files and when I enter http://ift.tt/Y9onHf, it gaves me output for 2013. But I checked the code of the sites and there is input for year and number of entries. So how do I select the entry I need using Python?

Extracting using a string pattern in Regex- Python

Cant we give a string in the Regex? For example, re.compile('((.*)?=<Bangalore>)'), in the below code i have mentioned <Bangalore> but its not displaying.

I want to extract the text before Bangalore.

import re

regex = re.compile('((.*)?=<>)')

line = ("Kathick Kumar, Bangalore who was a great person and lived from 29th 

March 1980 - 21 Dec 2014")

result = regex.search(line)

print(result)

Desired output: Kathick Kumar, Bangalore

How to censor website links?

I've been working on a regex censor for quite the time and can't seem to find a decent way of censoring address links (and attempts to circumvent that).

Here's what I got so far, ignoring escape sequences:

([a-zA-Z0-9_-]+[\\W[_]]*)+(\\.|[\\W]?|dot|\\(\\.\\)|[\\(]?dot[\\)]?)+([\\w]{2,6})((\\.|[\\W]?|dot|\\(\\.\\)|[\\(]?dot[\\)]?)([\\w]{1,4}))*

I'm not so sure what might be causing the problem but however it censors the word "com" and "come" and pretty much anything that is about 3+ letters.

Problem: I want to know how to censor website links and invalid links that are attempts to circumvent the censor. Examples:

Google.com

goo gle .com

g o o g l e . c o m

go o gl e % com

go og le (.) c om

Also a slight addition, is there a possible way to add links to a white list for this? Thank you.

regex encapsulation

I've got a question concerning regex.

I was wondering how one could replace an encapsulated text, something like {key:23} to something like <span class="highlightable">23</span, so that the entity will still remain encapsulated, but with something else.

I will do this in JS, but the regex is what is important, I have been searching for a while, probably searching for the wrong terms, I should probably learn more about regex, generally.

In any case, is there someone who knows how to perform this operation with simplicity?

Thanks!

samedi 27 juin 2015

Converting perl snippet to java

I want to rewrite a perl code in java:

sub validate_and_fix_regex {
    my $regex = $_[0];
    eval { qr/$regex/ };
    if ($@) {
        $regex = rquote($regex);
    }
    return $regex;
}

sub rquote {
    my $string = $_[0] || return;
    $string =~ s/([^A-Za-z_0-9 "'\\])/\\$1/g;
    return $string;
}

the code gets a regex and fix it if it has any escaped character. i cant find any alternative for eval { qr/$regex/ }; and $string =~ s/([^A-Za-z_0-9 "'\\])/\\$1/g; in java.

Regex Look Ahead

Today for a project I was trying to make use of regular expression and learnt about groups and how to use them. I am using this site to test it.The problem is that whenever I write the following regex:

(?=\S*\d)

, the site gives me an error : the expression can match 0 characters and therefore can match infinitely.

while this doesn't throw any error :

(?=\S*\d)(\S{6,16})

can anyone explain to me what is the meaning of the error.

PHP regex strip coma and space from beginning and end of string

I have some strings like this

", One "
", One , Two"
"One, Two "
" One,Two, "
" ,Two ,Three "

and need to remove space and or coma at beginning and end of string only tried few regex with preg_replace(), but they replace all occurrences.

EDIT: Actually would be great to remove all clutter like !@#$%^&*( etc whatever is at the end and beginning of string, but not in between.




Optionally need to make strings look proper by placing word then coma then space then another word (if there's coma one in between words).

Example "One,Two ,Three , Four" into "One, Two, Three, Four".

P.S. Please provide answer as two separate regex as its easier to understand.

In C#, how can I get the start/end indexes of all the replacements by the Regex.Replace() function

I have made a program to highlight the phrases in the input matched by a given Regex expression on the fly.

However, I want to highlight the replacements in the output panel too. To do this, I need to obtain the indexes and lengths found by Regex.Replace(). Unfortunately, it would seem C# doesn't give access to this data. Have I missed something?

I've thought about manually trying to figure out the indexes by accumulating sums given off from the MatchCollection produced by Regex.Matches(). But this is prone to error, and may not take into account the special $ symbol in the replace expression which could throw the figures off.

There must be a more elegant way.

Regex Expression replacing spaces in both end of the word

enter image description here

http://ift.tt/1ICDGzE

/(^|\s):bin:(\s|$)/gm

It is unable to scan and replace the one in the middle. How can I fix that without repeating replace() twice.

variable expansion as a pattern in sed not working

I've a simple script to set several parameters in /etc/ssh/sshd_config :

#! /bin/bash

declare -a param=('Banner' 'ClientAliveInterval' 'ClientAliveCountMax' 'Ciphers' \
'PermitUserEnvironment' 'PermitEmptyPasswords' 'PermitRootLogin' \
'HostbasedAuthentication' 'IgnoreRhosts' 'MaxAuthTries' \
'X11Forwarding' 'LogLevel'\
)

declare -a val=('/etc/issue.net' '300' '0' 'aes128-ctr,aes192-ctr,aes256-ctr' \
'no' 'no' 'no' 'no' 'yes' '4' 'no' 'INFO' \
)

for (( i=0;i<12;i++ ))
do
 #echo "${param[$i]} ${val[$i]}"
  egrep "^[ #]*${param[$i]}.*" /etc/ssh/sshd_config &> /dev/null
   if [ $? -eq 0 ];
    then
       sed -i "s|^[ #]*\$param[$i].*|${param[$i]} ${val[$i]}|1" /etc/ssh/sshd_config
  else
       echo "${param[$i]} ${val[$i]}" >> /etc/ssh/sshd_config
  fi
done;

However the variable expansion in sed pattern match is not working as desired:

sed -i "s|^[ #]*\$param[$i].*|${param[$i]} ${val[$i]}|1" /etc/ssh/sshd_config

Can someone help me. My array expansion and everything in the script is fine though. I've checked the same with an echo printout.